test_ipgenerator.py 1.3 KB

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