Skip to content

Commit

Permalink
Fix ValueError Exception.
Browse files Browse the repository at this point in the history
  • Loading branch information
nmasdoufi-ol committed Nov 12, 2024
1 parent 5c7391b commit 56395e8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
6 changes: 6 additions & 0 deletions agent/whois_ip_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ def _process_ip(self, message: m.Message, host: str) -> None:
network = ipaddress.ip_network(host)
else:
version = message.data.get("version")
if version is None:
try:
ip = ipaddress.ip_address(host)
version = ip.version
except ValueError:
raise ValueError(f"Invalid IP address: {host}")

Check warning on line 130 in agent/whois_ip_agent.py

View check run for this annotation

Codecov / codecov/patch

agent/whois_ip_agent.py#L129-L130

Added lines #L129 - L130 were not covered by tests
if version not in (4, 6):
raise ValueError(f"Incorrect ip version {version}.")
elif version == 4 and int(mask) < IPV4_CIDR_LIMIT:
Expand Down
30 changes: 30 additions & 0 deletions tests/whois_ip_agent_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Unittests for WhoisIP agent."""

from typing import List, Dict
from unittest import mock

import ipwhois
import pytest
Expand Down Expand Up @@ -304,3 +305,32 @@ def testWhoisIP_whenIPHasNoASN_doesNotCrash(
test_agent.process(scan_message_global_ipv4_with_mask32)

assert len(agent_mock) == 0


def testWhoisIP_withIPv4AndMaskButNoVersion_shouldHandleVersionCorrectly(
test_agent: whois_ip_agent.WhoisIPAgent,
agent_persist_mock: dict[str | bytes, str | bytes],
) -> None:
"""Test that process() handles the case when the version is None."""
message_data = {"host": "80.121.155.176", "mask": "29"}
test_message = message.Message.from_data(
selector="v3.asset.ip.v4",
data=message_data,
)

with mock.patch.object(
test_agent, "_redis_client"
) as mock_redis_client, mock.patch.object(
test_agent, "add_ip_network"
) as mock_add_ip_network, mock.patch.object(
test_agent, "start", mock.MagicMock()
), mock.patch.object(test_agent, "run", mock.MagicMock()), mock.patch(
"agent.whois_ip_agent.WhoisIPAgent.main", mock.MagicMock()
):
mock_redis_client.sismember.return_value = False

mock_add_ip_network.return_value = None

test_agent.process(test_message)

mock_add_ip_network.assert_called_once()

0 comments on commit 56395e8

Please sign in to comment.