3
0

test_ipgenerator.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from ID2TLib.Generator import IPGenerator
  2. import unittest
  3. # FIXME: These tests rely on randomness. They are NOT repeatable, and therefore unsuitable as unittests!
  4. class IPGeneratorTestCase(unittest.TestCase):
  5. IP_GENERATOR = None
  6. IP_SAMPLES = None
  7. IP_SAMPLES_NUM = 1000
  8. @classmethod
  9. def setUpClass(cls):
  10. cls.IP_GENERATOR = IPGenerator()
  11. cls.IP_SAMPLES = [cls.IP_GENERATOR.random_ip() for _ in range(cls.IP_SAMPLES_NUM)]
  12. def test_valid_ips(self):
  13. ip = None
  14. try:
  15. for ip in self.IP_SAMPLES:
  16. parts = ip.split(".")
  17. self.assertTrue(len(parts) == 4)
  18. numbers = [int(i) for i in parts]
  19. self.assertTrue(all(n in range(256) for n in numbers))
  20. except:
  21. self.fail("%s is not a valid IPv4" % ip)
  22. def test_generates_localhost_ip(self):
  23. self.assertFalse(any(ip.startswith("127.") for ip in self.IP_SAMPLES))
  24. def test_generates_private_ip(self):
  25. def private_ip(ip):
  26. private_starts = ["10.", "192.168."] + ["172.%i." % i for i in range(16, 32)]
  27. return any(ip.startswith(start) for start in private_starts)
  28. self.assertFalse(any(map(private_ip, self.IP_SAMPLES)))
  29. def test_unique_ips(self):
  30. self.assertTrue(len(self.IP_SAMPLES) == len(set(self.IP_SAMPLES)))
  31. def test_blacklist(self):
  32. generator = IPGenerator(blacklist=["42.0.0.0/8"])
  33. self.assertFalse(any(generator.random_ip().startswith("42.") for _ in range(self.IP_SAMPLES_NUM)))