Skip to content

Commit

Permalink
Address action unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
abmccann-r7 committed Nov 6, 2023
1 parent d3b530c commit 0891df3
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 77 deletions.
4 changes: 4 additions & 0 deletions plugins/whois/unit_test/inputs/address_error.json.inp
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"address": "1",
"registrar": "Autodetect"
}
8 changes: 4 additions & 4 deletions plugins/whois/unit_test/responses/address.json.resp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"stdout":"{'netrange': '198.51.100.0 - 198.51.100.255', 'cidr': '198.51.100.0/24', 'netname': 'TEST-NET-1', 'nettype': 'IANA Special Use', 'regdate': 'Updated', 'update': '2013-08-30', 'orgname': 'Internet Assigned Numbers Authority', 'address': 'Suite 300', 'city': 'Los Angeles', 'state': 'CA', 'postal': '90292', 'country': 'US', 'org_tech_phone': '+1-310-301-5820', 'org_tech_email': 'abuse@iana.org', 'org_abuse_phone': '+1-310-301-5820', 'org_abuse_email': 'abuse@iana.org'}",
"stderr":"",
"rcode":""
}
"stdout": "\n#\n# ARIN WHOIS data and services are subject to the Terms of Use\n# available at: https://www.arin.net/resources/registry/whois/tou/\n#\n# If you see inaccuracies in the results, please report at\n# https://www.arin.net/resources/registry/whois/inaccuracy_reporting/\n#\n# Copyright 1997-2023, American Registry for Internet Numbers, Ltd.\n#\n\n\nNetRange: 198.51.100.0 - 198.51.100.255\nCIDR: 198.51.100.0/24\nNetName: TEST-NET-1\nNetHandle: NET-198-51-100-0-1\nParent: NET198 (NET-198-0-0-0-0)\nNetType: IANA Special Use\nOriginAS: \nOrganization: Internet Assigned Numbers Authority (IANA)\nRegDate: 2009-08-26\nUpdated: 2013-08-30\nComment: Addresses starting with \"192.0.2.\", \"198.51.100.\", or \"203.0.113.\" are reserved for use in documentation and sample configurations. They should never be used in a live network configuration. No one has permission to use these addresses on the Internet.\nComment: \nComment: Network operators should add these address blocks to the list of non-routable address space, and if packet filters are deployed, then these address blocks should be added to packet filters. These blocks are not for local use, and the filters may be used in both local and public contexts.\nComment: \nComment: These addresses are assigned by the IETF, the organization that develops Internet protocols, in the Informational document RFC 5737, which can be found at:\nComment: http://datatracker.ietf.org/doc/rfc5737\nRef: https://rdap.arin.net/registry/ip/198.51.100.0\n\n\n\nOrgName: Internet Assigned Numbers Authority\nOrgId: IANA\nAddress: 12025 Waterfront Drive\nAddress: Suite 300\nCity: Los Angeles\nStateProv: CA\nPostalCode: 90292\nCountry: US\nRegDate: \nUpdated: 2012-08-31\nRef: https://rdap.arin.net/registry/entity/IANA\n\n\nOrgAbuseHandle: IANA-IP-ARIN\nOrgAbuseName: ICANN\nOrgAbusePhone: +1-310-301-5820 \nOrgAbuseEmail: abuse@iana.org\nOrgAbuseRef: https://rdap.arin.net/registry/entity/IANA-IP-ARIN\n\nOrgTechHandle: IANA-IP-ARIN\nOrgTechName: ICANN\nOrgTechPhone: +1-310-301-5820 \nOrgTechEmail: abuse@iana.org\nOrgTechRef: https://rdap.arin.net/registry/entity/IANA-IP-ARIN\n\n\n#\n# ARIN WHOIS data and services are subject to the Terms of Use\n# available at: https://www.arin.net/resources/registry/whois/tou/\n#\n# If you see inaccuracies in the results, please report at\n# https://www.arin.net/resources/registry/whois/inaccuracy_reporting/\n#\n# Copyright 1997-2023, American Registry for Internet Numbers, Ltd.\n#\n\n",
"stderr": "",
"rcode": ""
}
5 changes: 5 additions & 0 deletions plugins/whois/unit_test/responses/address_error.json.resp
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"stdout": "No whois server is known for this kind of object.\n",
"stderr": "",
"rcode": ""
}
19 changes: 16 additions & 3 deletions plugins/whois/unit_test/test_address.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

@patch("insightconnect_plugin_runtime.helper.exec_command", side_effect=Util.mock_whois)
class TestAddress(TestCase):

@classmethod
def setUpClass(cls) -> None:
cls.action = Util.default_connector(Address())
Expand All @@ -30,10 +29,24 @@ def setUpClass(cls) -> None:
]
]
)
def test_address(self, _test_mock: MagicMock, _test_name: str, input_params: str, expected: str):
def test_address(self, _test_mock: MagicMock, _test_name: str, input_params: str, expected: dict):
actual = self.action.run(input_params)
print(f"{actual =}")
print(f"{expected =}")
self.assertEqual(actual, expected)


@parameterized.expand(
[
[
"address_error",
Util.read_file_to_dict("inputs/address_error.json.inp"),
"Error: Request did not return any data.",
"Please check provided address and try again.",
]
]
)
def test_address(self, _test_mock: MagicMock, _test_name: str, input_params: str, cause: str, assistance: str):
with self.assertRaises(PluginException) as error:
self.action.run(input_params)
self.assertEqual(error.exception.cause, cause)
self.assertEqual(error.exception.assistance, assistance)
5 changes: 1 addition & 4 deletions plugins/whois/unit_test/test_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

@patch("whois.query", side_effect=Util.mock_whois)
class TestDomain(TestCase):

@classmethod
def setUpClass(cls) -> None:
cls.action = Util.default_connector(Domain())
Expand All @@ -26,7 +25,7 @@ def setUpClass(cls) -> None:
[
"domain",
Util.read_file_to_dict("inputs/domain.json.inp"),
Util.read_file_to_dict("expected/domain.json.exp")
Util.read_file_to_dict("expected/domain.json.exp"),
]
]
)
Expand All @@ -49,5 +48,3 @@ def test_invalid(self, _mock_request: MagicMock, _test_name: str, input_params:
self.action.run(input_params)
self.assertEqual(error.exception.cause, cause)
self.assertEqual(error.exception.assistance, assistance)


136 changes: 70 additions & 66 deletions plugins/whois/unit_test/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def default_connector(action: insightconnect_plugin_runtime.Action, params: dict
@staticmethod
def read_file_to_dict(filename: str, encodingenabled: bool = False) -> dict:
with open(
os.path.join(os.path.dirname(os.path.realpath(__file__)), filename), "r", encoding="utf-8"
os.path.join(os.path.dirname(os.path.realpath(__file__)), filename), "r", encoding="utf-8"
) as file_reader:
data = json.load(file_reader)
if encodingenabled:
Expand All @@ -38,43 +38,43 @@ def read_file_to_dict(filename: str, encodingenabled: bool = False) -> dict:

@staticmethod
def mock_whois(*args, **kwargs):

class MockWhois:
def __init__(self, data):
try:
self.name = data['domain_name'][0].strip().lower()
self.registrar = data['registrar'][0].strip()
self.registrant_cc = data['registrant_cc'][0].strip().lower()
self.creation_date = str_to_date(data['creation_date'][0])
self.expiration_date = str_to_date(data['expiration_date'][0])
self.last_updated = str_to_date(data['updated_date'][0])
self.name = data["domain_name"][0].strip().lower()
self.registrar = data["registrar"][0].strip()
self.registrant_cc = data["registrant_cc"][0].strip().lower()
self.creation_date = str_to_date(data["creation_date"][0])
self.expiration_date = str_to_date(data["expiration_date"][0])
self.last_updated = str_to_date(data["updated_date"][0])

tmp = []
for x in data['name_servers']:
for x in data["name_servers"]:
if isinstance(x, str):
tmp.append(x)
else:
for y in x: tmp.append(y)
for y in x:
tmp.append(y)

self.name_servers = []
for x in tmp:
x = x.strip(' .')
x = x.strip(" .")
if x:
if ' ' in x:
x, _ = x.split(' ', 1)
x = x.strip(' .')
if " " in x:
x, _ = x.split(" ", 1)
x = x.strip(" .")

self.name_servers.append(x.lower())

# Komand additions
self.registry_domain_id = data['registry_domain_id'][0].strip().lower()
self.registrar_whois_server = data['registrar_whois_server'][0].strip().lower()
self.registrar_url = data['registrar_url'][0].strip().lower()
self.registrar_iana_id = data['registrar_iana_id'][0].strip().lower()
self.registrar_abuse_contact_email = data['registrar_abuse_contact_email'][0].strip().lower()
self.registrar_abuse_contact_phone = data['registrar_abuse_contact_phone'][0].strip().lower()
self.domain_status = list(map(lambda ds: ds.strip().lower(), data['domain_status']))
self.dnssec = data['dnssec'][0].strip().lower()
self.registry_domain_id = data["registry_domain_id"][0].strip().lower()
self.registrar_whois_server = data["registrar_whois_server"][0].strip().lower()
self.registrar_url = data["registrar_url"][0].strip().lower()
self.registrar_iana_id = data["registrar_iana_id"][0].strip().lower()
self.registrar_abuse_contact_email = data["registrar_abuse_contact_email"][0].strip().lower()
self.registrar_abuse_contact_phone = data["registrar_abuse_contact_phone"][0].strip().lower()
self.domain_status = list(map(lambda ds: ds.strip().lower(), data["domain_status"]))
self.dnssec = data["dnssec"][0].strip().lower()

except KeyError:
pass
Expand All @@ -92,56 +92,56 @@ def get_json_serializable(self):

# http://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_FORMATS = [
'%d-%b-%Y', # 02-jan-2000
'%d.%m.%Y', # 02.02.2000
'%d/%m/%Y', # 01/06/2011
'%Y-%m-%d', # 2000-01-02
'%Y.%m.%d', # 2000.01.02
'%Y/%m/%d', # 2005/05/30
'before %b-%Y', # before aug-1996
'%Y.%m.%d %H:%M:%S', # 2002.09.19 13:00:00
'%Y%m%d %H:%M:%S', # 20110908 14:44:51
'%Y-%m-%d %H:%M:%S', # 2011-09-08 14:44:51
'%Y-%m-%d %H:%M:%S CLST', # 2011-09-08 14:44:51 CLST CL
'%Y-%m-%d %H:%M:%S.%f', # 2011-09-08 14:44:51 CLST CL
'%d.%m.%Y %H:%M:%S', # 19.09.2002 13:00:00
'%d-%b-%Y %H:%M:%S %Z', # 24-Jul-2009 13:20:03 UTC
'%Y/%m/%d %H:%M:%S (%z)', # 2011/06/01 01:05:01 (+0900)
'%Y/%m/%d %H:%M:%S', # 2011/06/01 01:05:01
'%a %b %d %H:%M:%S %Z %Y', # Tue Jun 21 23:59:59 GMT 2011
'%a %b %d %Y', # Tue Dec 12 2000
'%Y-%m-%dT%H:%M:%S', # 2007-01-26T19:10:31
'%Y-%m-%dT%H:%M:%SZ', # 2007-01-26T19:10:31Z
'%Y-%m-%dt%H:%M:%S.%fz', # 2007-01-26t19:10:31.00z
'%Y-%m-%dT%H:%M:%S%z', # 2011-03-30T19:36:27+0200
'%Y-%m-%dT%H:%M:%S.%f%z', # 2011-09-08T14:44:51.622265+03:00
'%Y-%m-%dt%H:%M:%S.%f', # 2011-09-08t14:44:51.622265
'%Y-%m-%dt%H:%M:%S', # 2007-01-26T19:10:31
'%Y-%m-%dt%H:%M:%SZ', # 2007-01-26T19:10:31Z
'%Y-%m-%dt%H:%M:%S.%fz', # 2007-01-26t19:10:31.00z
'%Y-%m-%dt%H:%M:%S%z', # 2011-03-30T19:36:27+0200
'%Y-%m-%dt%H:%M:%S %z', # 2011-03-30T19:36:27+0200
'%Y-%m-%dt%H:%M:%S.%f%z', # 2011-09-08T14:44:51.622265+03:00
'%Y%m%d', # 20110908
'%Y. %m. %d.', # 2020. 01. 12.
'before %b-%Y', # before aug-1996
'%a %d %b %Y', # Tue 21 Jun 2011
'%A %d %b %Y', # Tuesday 21 Jun 2011
'%a %d %B %Y', # Tue 21 June 2011
'%A %d %B %Y', # Tuesday 21 June 2011
'%Y-%m-%d %H:%M:%S (%Z+0:00)', # 2007-12-24 10:24:32 (gmt+0:00)
'%B %d %Y', # January 01 2000
"%d-%b-%Y", # 02-jan-2000
"%d.%m.%Y", # 02.02.2000
"%d/%m/%Y", # 01/06/2011
"%Y-%m-%d", # 2000-01-02
"%Y.%m.%d", # 2000.01.02
"%Y/%m/%d", # 2005/05/30
"before %b-%Y", # before aug-1996
"%Y.%m.%d %H:%M:%S", # 2002.09.19 13:00:00
"%Y%m%d %H:%M:%S", # 20110908 14:44:51
"%Y-%m-%d %H:%M:%S", # 2011-09-08 14:44:51
"%Y-%m-%d %H:%M:%S CLST", # 2011-09-08 14:44:51 CLST CL
"%Y-%m-%d %H:%M:%S.%f", # 2011-09-08 14:44:51 CLST CL
"%d.%m.%Y %H:%M:%S", # 19.09.2002 13:00:00
"%d-%b-%Y %H:%M:%S %Z", # 24-Jul-2009 13:20:03 UTC
"%Y/%m/%d %H:%M:%S (%z)", # 2011/06/01 01:05:01 (+0900)
"%Y/%m/%d %H:%M:%S", # 2011/06/01 01:05:01
"%a %b %d %H:%M:%S %Z %Y", # Tue Jun 21 23:59:59 GMT 2011
"%a %b %d %Y", # Tue Dec 12 2000
"%Y-%m-%dT%H:%M:%S", # 2007-01-26T19:10:31
"%Y-%m-%dT%H:%M:%SZ", # 2007-01-26T19:10:31Z
"%Y-%m-%dt%H:%M:%S.%fz", # 2007-01-26t19:10:31.00z
"%Y-%m-%dT%H:%M:%S%z", # 2011-03-30T19:36:27+0200
"%Y-%m-%dT%H:%M:%S.%f%z", # 2011-09-08T14:44:51.622265+03:00
"%Y-%m-%dt%H:%M:%S.%f", # 2011-09-08t14:44:51.622265
"%Y-%m-%dt%H:%M:%S", # 2007-01-26T19:10:31
"%Y-%m-%dt%H:%M:%SZ", # 2007-01-26T19:10:31Z
"%Y-%m-%dt%H:%M:%S.%fz", # 2007-01-26t19:10:31.00z
"%Y-%m-%dt%H:%M:%S%z", # 2011-03-30T19:36:27+0200
"%Y-%m-%dt%H:%M:%S %z", # 2011-03-30T19:36:27+0200
"%Y-%m-%dt%H:%M:%S.%f%z", # 2011-09-08T14:44:51.622265+03:00
"%Y%m%d", # 20110908
"%Y. %m. %d.", # 2020. 01. 12.
"before %b-%Y", # before aug-1996
"%a %d %b %Y", # Tue 21 Jun 2011
"%A %d %b %Y", # Tuesday 21 Jun 2011
"%a %d %B %Y", # Tue 21 June 2011
"%A %d %B %Y", # Tuesday 21 June 2011
"%Y-%m-%d %H:%M:%S (%Z+0:00)", # 2007-12-24 10:24:32 (gmt+0:00)
"%B %d %Y", # January 01 2000
]

def str_to_date(text):
text = text.strip().lower()

if not text or text == 'not defined':
if not text or text == "not defined":
return

text = text.replace('(jst)', '(+0900)')
text = re.sub('(\+[0-9]{2}):([0-9]{2})', '\\1\\2', text)
text = re.sub('(\ #.*)', '', text)
text = text.replace("(jst)", "(+0900)")
text = re.sub("(\+[0-9]{2}):([0-9]{2})", "\\1\\2", text)
text = re.sub("(\ #.*)", "", text)
# hack for 1st 2nd 3rd 4th etc
# better here https://stackoverflow.com/questions/1258199/python-datetime-strptime-wildcard
text = re.sub(r"(\d+)(st|nd|rd|th) ", r"\1 ", text)
Expand All @@ -165,6 +165,10 @@ def str_to_date(text):
return MockWhois(data=test_data)
elif query == f"/usr/bin/whois 198.51.100.100":
filename = "address.json.resp"
test_data = Util.read_file_to_dict(f"responses/{filename}", encodingenabled=False)
test_data = Util.read_file_to_dict(f"responses/{filename}", encodingenabled=True)
print(f"{test_data =}")
return test_data
elif query == f"/usr/bin/whois 1":
filename = "address_error.json.resp"
test_data = Util.read_file_to_dict(f"responses/{filename}", encodingenabled=True)
return test_data

0 comments on commit 0891df3

Please sign in to comment.