Skip to content

Commit

Permalink
More strict type checking.
Browse files Browse the repository at this point in the history
  • Loading branch information
xkww3n committed Dec 10, 2023
1 parent 931f9fb commit 925f6af
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
12 changes: 12 additions & 0 deletions Tests/test_0_single_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ def test_type_checking_init(self):
rule.Rule("IPCIDR", "114514")
with raises(ValueError):
rule.Rule("IPCIDR6", "1919810")
with raises(ValueError):
rule.Rule("IPCIDR", "fc00:114::514")
with raises(ValueError):
rule.Rule("IPCIDR6", "1.14.5.14")

def test_type_checking_runtime(self):
test_rule = rule.Rule()
Expand All @@ -37,6 +41,14 @@ def test_type_checking_runtime(self):
with raises(ValueError):
test_rule.set_payload("1919810")

test_rule.set_type("IPCIDR")
with raises(ValueError):
test_rule.set_payload("fc00:114::514")

test_rule.set_type("IPCIDR6")
with raises(ValueError):
test_rule.set_payload("1.14.5.14")

def test_to_str(self):
test_rule = rule.Rule("DomainSuffix", "example.com", "TEST")
assert str(test_rule) == 'Type: "DomainSuffix", Payload: "example.com", Tag: TEST'
Expand Down
8 changes: 6 additions & 2 deletions Utils/rule.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ipaddress import ip_network
from ipaddress import ip_network, IPv4Network, IPv6Network


class Rule:
Expand Down Expand Up @@ -37,9 +37,13 @@ def set_payload(self, payload: str):
raise ValueError(f"Invalid domain: {payload}")
elif "IP" in self.Type:
try:
ip_network(payload)
ip_type = ip_network(payload)
except ValueError:
raise ValueError(f"Invalid IP address: {payload}")
if self.Type == "IPCIDR6" and type(ip_type) is IPv4Network:
raise ValueError(f"IPv4 address stored in IPv6 type: {payload}")
elif self.Type == "IPCIDR" and type(ip_type) is IPv6Network:
raise ValueError(f"IPv6 address stored in IPv4 type: {payload}")
self.Payload = payload

def set_tag(self, tag: str = ""):
Expand Down

0 comments on commit 925f6af

Please sign in to comment.