test_ipaddress.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  1. '''
  2. Python 2.[67] port of Python 3.4's test_ipaddress.
  3. Almost verbatim copy of core lib w/compatibility fixes
  4. '''
  5. # pylint: skip-file
  6. # List of compatibility changes:
  7. # This backport uses bytearray instead of bytes, as bytes is the same
  8. # as str in Python 2.7.
  9. #bytes = bytearray
  10. # s/\(b'[^']\+'\)/bytearray(\1)/g
  11. # plus manual fixes for implicit string concatenation.
  12. # Python 3.4 has assertRaisesRegex where Python 2.7 only has assertRaisesRegexp.
  13. # s/\.assertRaisesRegexp(/.assertRaisesRegexp(/
  14. # Python 2.6 carries assertRaisesRegexp and others in unittest2
  15. # Python 2.6 wants unicode into bytes.fromhex
  16. # s/bytes.fromhex\("/bytes.fromhex(u"/g
  17. # Further compatibility changes are marked "Compatibility", below.
  18. # ----------------------------------------------------------------------------
  19. # Copyright 2007 Google Inc.
  20. # Licensed to PSF under a Contributor Agreement.
  21. """Unittest for ipaddress module."""
  22. # Import python libs
  23. import re
  24. import sys
  25. import contextlib
  26. import operator
  27. import sys
  28. # Import salt libs
  29. from salt._compat import ipaddress
  30. # Import salt test libs
  31. from tests.support.unit import TestCase, skipIf, WAR_ROOM_SKIP
  32. if sys.version_info < (3,):
  33. bytes = bytearray
  34. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  35. class BaseTestCase(TestCase):
  36. # One big change in ipaddress over the original ipaddr module is
  37. # error reporting that tries to assume users *don't know the rules*
  38. # for what constitutes an RFC compliant IP address
  39. # Ensuring these errors are emitted correctly in all relevant cases
  40. # meant moving to a more systematic test structure that allows the
  41. # test structure to map more directly to the module structure
  42. # Note that if the constructors are refactored so that addresses with
  43. # multiple problems get classified differently, that's OK - just
  44. # move the affected examples to the newly appropriate test case.
  45. # There is some duplication between the original relatively ad hoc
  46. # test suite and the new systematic tests. While some redundancy in
  47. # testing is considered preferable to accidentally deleting a valid
  48. # test, the original test suite will likely be reduced over time as
  49. # redundant tests are identified.
  50. @property
  51. def factory(self):
  52. raise NotImplementedError
  53. @contextlib.contextmanager
  54. def assertCleanError(self, exc_type, details, *args):
  55. """
  56. Ensure exception does not display a context by default
  57. Wraps TestCase.assertRaisesRegex
  58. """
  59. if args:
  60. details = details % args
  61. cm = self.assertRaisesRegex(exc_type, details)
  62. with cm as exc:
  63. yield exc
  64. # Compatibility: Python 2.7 does not support exception chaining
  65. ## Ensure we produce clean tracebacks on failure
  66. #if exc.exception.__context__ is not None:
  67. # self.assertTrue(exc.exception.__suppress_context__)
  68. def assertAddressError(self, details, *args):
  69. """Ensure a clean AddressValueError"""
  70. return self.assertCleanError(ipaddress.AddressValueError,
  71. details, *args)
  72. def assertNetmaskError(self, details, *args):
  73. """Ensure a clean NetmaskValueError"""
  74. return self.assertCleanError(ipaddress.NetmaskValueError,
  75. details, *args)
  76. def assertInstancesEqual(self, lhs, rhs):
  77. """Check constructor arguments produce equivalent instances"""
  78. self.assertEqual(self.factory(lhs), self.factory(rhs))
  79. class CommonTestMixin:
  80. def test_empty_address(self):
  81. with self.assertAddressError("Address cannot be empty"):
  82. self.factory("")
  83. def test_floats_rejected(self):
  84. with self.assertAddressError(re.escape(repr("1.0"))):
  85. self.factory(1.0)
  86. def test_not_an_index_issue15559(self):
  87. # Implementing __index__ makes for a very nasty interaction with the
  88. # bytes constructor. Thus, we disallow implicit use as an integer
  89. self.assertRaises(TypeError, operator.index, self.factory(1))
  90. self.assertRaises(TypeError, hex, self.factory(1))
  91. self.assertRaises(TypeError, bytes, self.factory(1))
  92. class CommonTestMixin_v4(CommonTestMixin):
  93. def test_leading_zeros(self):
  94. self.assertInstancesEqual("000.000.000.000", "0.0.0.0")
  95. self.assertInstancesEqual("192.168.000.001", "192.168.0.1")
  96. def test_int(self):
  97. self.assertInstancesEqual(0, "0.0.0.0")
  98. self.assertInstancesEqual(3232235521, "192.168.0.1")
  99. def test_packed(self):
  100. self.assertInstancesEqual(bytes.fromhex(u"00000000"), "0.0.0.0")
  101. self.assertInstancesEqual(bytes.fromhex(u"c0a80001"), "192.168.0.1")
  102. def test_negative_ints_rejected(self):
  103. msg = "-1 (< 0) is not permitted as an IPv4 address"
  104. with self.assertAddressError(re.escape(msg)):
  105. self.factory(-1)
  106. def test_large_ints_rejected(self):
  107. msg = "%d (>= 2**32) is not permitted as an IPv4 address"
  108. with self.assertAddressError(re.escape(msg % 2**32)):
  109. self.factory(2**32)
  110. def test_bad_packed_length(self):
  111. def assertBadLength(length):
  112. addr = bytes(length)
  113. msg = "%r (len %d != 4) is not permitted as an IPv4 address"
  114. with self.assertAddressError(re.escape(msg % (addr, length))):
  115. self.factory(addr)
  116. assertBadLength(3)
  117. assertBadLength(5)
  118. class CommonTestMixin_v6(CommonTestMixin):
  119. def test_leading_zeros(self):
  120. self.assertInstancesEqual("0000::0000", "::")
  121. self.assertInstancesEqual("000::c0a8:0001", "::c0a8:1")
  122. def test_int(self):
  123. self.assertInstancesEqual(0, "::")
  124. self.assertInstancesEqual(3232235521, "::c0a8:1")
  125. def test_packed(self):
  126. addr = bytes(12) + bytes.fromhex(u"00000000")
  127. self.assertInstancesEqual(addr, "::")
  128. addr = bytes(12) + bytes.fromhex(u"c0a80001")
  129. self.assertInstancesEqual(addr, "::c0a8:1")
  130. addr = bytes.fromhex(u"c0a80001") + bytes(12)
  131. self.assertInstancesEqual(addr, "c0a8:1::")
  132. def test_negative_ints_rejected(self):
  133. msg = "-1 (< 0) is not permitted as an IPv6 address"
  134. with self.assertAddressError(re.escape(msg)):
  135. self.factory(-1)
  136. def test_large_ints_rejected(self):
  137. msg = "%d (>= 2**128) is not permitted as an IPv6 address"
  138. with self.assertAddressError(re.escape(msg % 2**128)):
  139. self.factory(2**128)
  140. def test_bad_packed_length(self):
  141. def assertBadLength(length):
  142. addr = bytes(length)
  143. msg = "%r (len %d != 16) is not permitted as an IPv6 address"
  144. with self.assertAddressError(re.escape(msg % (addr, length))):
  145. self.factory(addr)
  146. self.factory(addr)
  147. assertBadLength(15)
  148. assertBadLength(17)
  149. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  150. class AddressTestCase_v4(BaseTestCase, CommonTestMixin_v4):
  151. factory = ipaddress.IPv4Address
  152. def test_network_passed_as_address(self):
  153. addr = "127.0.0.1/24"
  154. with self.assertAddressError("Unexpected '/' in %r", addr):
  155. ipaddress.IPv4Address(addr)
  156. def test_bad_address_split(self):
  157. def assertBadSplit(addr):
  158. with self.assertAddressError("Expected 4 octets in %r", addr):
  159. ipaddress.IPv4Address(addr)
  160. assertBadSplit("127.0.1")
  161. assertBadSplit("42.42.42.42.42")
  162. assertBadSplit("42.42.42")
  163. assertBadSplit("42.42")
  164. assertBadSplit("42")
  165. assertBadSplit("42..42.42.42")
  166. assertBadSplit("42.42.42.42.")
  167. assertBadSplit("42.42.42.42...")
  168. assertBadSplit(".42.42.42.42")
  169. assertBadSplit("...42.42.42.42")
  170. assertBadSplit("016.016.016")
  171. assertBadSplit("016.016")
  172. assertBadSplit("016")
  173. assertBadSplit("000")
  174. assertBadSplit("0x0a.0x0a.0x0a")
  175. assertBadSplit("0x0a.0x0a")
  176. assertBadSplit("0x0a")
  177. assertBadSplit(".")
  178. assertBadSplit("bogus")
  179. assertBadSplit("bogus.com")
  180. assertBadSplit("1000")
  181. assertBadSplit("1000000000000000")
  182. assertBadSplit("192.168.0.1.com")
  183. def test_empty_octet(self):
  184. def assertBadOctet(addr):
  185. with self.assertAddressError("Empty octet not permitted in %r",
  186. addr):
  187. ipaddress.IPv4Address(addr)
  188. assertBadOctet("42..42.42")
  189. assertBadOctet("...")
  190. def test_invalid_characters(self):
  191. def assertBadOctet(addr, octet):
  192. msg = "Only decimal digits permitted in %r in %r" % (octet, addr)
  193. with self.assertAddressError(re.escape(msg)):
  194. ipaddress.IPv4Address(addr)
  195. assertBadOctet("0x0a.0x0a.0x0a.0x0a", "0x0a")
  196. assertBadOctet("0xa.0x0a.0x0a.0x0a", "0xa")
  197. assertBadOctet("42.42.42.-0", "-0")
  198. assertBadOctet("42.42.42.+0", "+0")
  199. assertBadOctet("42.42.42.-42", "-42")
  200. assertBadOctet("+1.+2.+3.4", "+1")
  201. assertBadOctet("1.2.3.4e0", "4e0")
  202. assertBadOctet("1.2.3.4::", "4::")
  203. assertBadOctet("1.a.2.3", "a")
  204. def test_octal_decimal_ambiguity(self):
  205. def assertBadOctet(addr, octet):
  206. msg = "Ambiguous (octal/decimal) value in %r not permitted in %r"
  207. with self.assertAddressError(re.escape(msg % (octet, addr))):
  208. ipaddress.IPv4Address(addr)
  209. assertBadOctet("016.016.016.016", "016")
  210. assertBadOctet("001.000.008.016", "008")
  211. def test_octet_length(self):
  212. def assertBadOctet(addr, octet):
  213. msg = "At most 3 characters permitted in %r in %r"
  214. with self.assertAddressError(re.escape(msg % (octet, addr))):
  215. ipaddress.IPv4Address(addr)
  216. assertBadOctet("0000.000.000.000", "0000")
  217. assertBadOctet("12345.67899.-54321.-98765", "12345")
  218. def test_octet_limit(self):
  219. def assertBadOctet(addr, octet):
  220. msg = "Octet %d (> 255) not permitted in %r" % (octet, addr)
  221. with self.assertAddressError(re.escape(msg)):
  222. ipaddress.IPv4Address(addr)
  223. assertBadOctet("257.0.0.0", 257)
  224. assertBadOctet("192.168.0.999", 999)
  225. @skipIf(WAR_ROOM_SKIP, 'WAR ROOM TEMPORARY SKIP')
  226. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  227. class AddressTestCase_v6(BaseTestCase, CommonTestMixin_v6):
  228. factory = ipaddress.IPv6Address
  229. def test_network_passed_as_address(self):
  230. addr = "::1/24"
  231. with self.assertAddressError("Unexpected '/' in %r", addr):
  232. ipaddress.IPv6Address(addr)
  233. def test_bad_address_split_v6_not_enough_parts(self):
  234. def assertBadSplit(addr):
  235. msg = "At least 3 parts expected in %r"
  236. with self.assertAddressError(msg, addr):
  237. ipaddress.IPv6Address(addr)
  238. assertBadSplit(":")
  239. assertBadSplit(":1")
  240. assertBadSplit("FEDC:9878")
  241. def test_bad_address_split_v6_too_many_colons(self):
  242. def assertBadSplit(addr):
  243. msg = "At most 8 colons permitted in %r"
  244. with self.assertAddressError(msg, addr):
  245. ipaddress.IPv6Address(addr)
  246. assertBadSplit("9:8:7:6:5:4:3::2:1")
  247. assertBadSplit("10:9:8:7:6:5:4:3:2:1")
  248. assertBadSplit("::8:7:6:5:4:3:2:1")
  249. assertBadSplit("8:7:6:5:4:3:2:1::")
  250. # A trailing IPv4 address is two parts
  251. assertBadSplit("10:9:8:7:6:5:4:3:42.42.42.42")
  252. def test_bad_address_split_v6_too_many_parts(self):
  253. def assertBadSplit(addr):
  254. msg = "Exactly 8 parts expected without '::' in %r"
  255. with self.assertAddressError(msg, addr):
  256. ipaddress.IPv6Address(addr)
  257. assertBadSplit("3ffe:0:0:0:0:0:0:0:1")
  258. assertBadSplit("9:8:7:6:5:4:3:2:1")
  259. assertBadSplit("7:6:5:4:3:2:1")
  260. # A trailing IPv4 address is two parts
  261. assertBadSplit("9:8:7:6:5:4:3:42.42.42.42")
  262. assertBadSplit("7:6:5:4:3:42.42.42.42")
  263. def test_bad_address_split_v6_too_many_parts_with_double_colon(self):
  264. def assertBadSplit(addr):
  265. msg = "Expected at most 7 other parts with '::' in %r"
  266. with self.assertAddressError(msg, addr):
  267. ipaddress.IPv6Address(addr)
  268. assertBadSplit("1:2:3:4::5:6:7:8")
  269. def test_bad_address_split_v6_repeated_double_colon(self):
  270. def assertBadSplit(addr):
  271. msg = "At most one '::' permitted in %r"
  272. with self.assertAddressError(msg, addr):
  273. ipaddress.IPv6Address(addr)
  274. assertBadSplit("3ffe::1::1")
  275. assertBadSplit("1::2::3::4:5")
  276. assertBadSplit("2001::db:::1")
  277. assertBadSplit("3ffe::1::")
  278. assertBadSplit("::3ffe::1")
  279. assertBadSplit(":3ffe::1::1")
  280. assertBadSplit("3ffe::1::1:")
  281. assertBadSplit(":3ffe::1::1:")
  282. assertBadSplit(":::")
  283. assertBadSplit('2001:db8:::1')
  284. def test_bad_address_split_v6_leading_colon(self):
  285. def assertBadSplit(addr):
  286. msg = "Leading ':' only permitted as part of '::' in %r"
  287. with self.assertAddressError(msg, addr):
  288. ipaddress.IPv6Address(addr)
  289. assertBadSplit(":2001:db8::1")
  290. assertBadSplit(":1:2:3:4:5:6:7")
  291. assertBadSplit(":1:2:3:4:5:6:")
  292. assertBadSplit(":6:5:4:3:2:1::")
  293. def test_bad_address_split_v6_trailing_colon(self):
  294. def assertBadSplit(addr):
  295. msg = "Trailing ':' only permitted as part of '::' in %r"
  296. with self.assertAddressError(msg, addr):
  297. ipaddress.IPv6Address(addr)
  298. assertBadSplit("2001:db8::1:")
  299. assertBadSplit("1:2:3:4:5:6:7:")
  300. assertBadSplit("::1.2.3.4:")
  301. assertBadSplit("::7:6:5:4:3:2:")
  302. def test_bad_v4_part_in(self):
  303. def assertBadAddressPart(addr, v4_error):
  304. with self.assertAddressError("%s in %r", v4_error, addr):
  305. ipaddress.IPv6Address(addr)
  306. assertBadAddressPart("3ffe::1.net", "Expected 4 octets in '1.net'")
  307. assertBadAddressPart("3ffe::127.0.1",
  308. "Expected 4 octets in '127.0.1'")
  309. assertBadAddressPart("::1.2.3",
  310. "Expected 4 octets in '1.2.3'")
  311. assertBadAddressPart("::1.2.3.4.5",
  312. "Expected 4 octets in '1.2.3.4.5'")
  313. assertBadAddressPart("3ffe::1.1.1.net",
  314. "Only decimal digits permitted in 'net' "
  315. "in '1.1.1.net'")
  316. def test_invalid_characters(self):
  317. def assertBadPart(addr, part):
  318. msg = "Only hex digits permitted in %r in %r" % (part, addr)
  319. with self.assertAddressError(re.escape(msg)):
  320. ipaddress.IPv6Address(addr)
  321. assertBadPart("3ffe::goog", "goog")
  322. assertBadPart("3ffe::-0", "-0")
  323. assertBadPart("3ffe::+0", "+0")
  324. assertBadPart("3ffe::-1", "-1")
  325. assertBadPart("1.2.3.4::", "1.2.3.4")
  326. assertBadPart('1234:axy::b', "axy")
  327. def test_part_length(self):
  328. def assertBadPart(addr, part):
  329. msg = "At most 4 characters permitted in %r in %r"
  330. with self.assertAddressError(msg, part, addr):
  331. ipaddress.IPv6Address(addr)
  332. assertBadPart("::00000", "00000")
  333. assertBadPart("3ffe::10000", "10000")
  334. assertBadPart("02001:db8::", "02001")
  335. assertBadPart('2001:888888::1', "888888")
  336. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  337. class NetmaskTestMixin_v4(CommonTestMixin_v4):
  338. """Input validation on interfaces and networks is very similar"""
  339. def test_split_netmask(self):
  340. addr = "1.2.3.4/32/24"
  341. with self.assertAddressError("Only one '/' permitted in %r" % addr):
  342. self.factory(addr)
  343. def test_address_errors(self):
  344. def assertBadAddress(addr, details):
  345. with self.assertAddressError(details):
  346. self.factory(addr)
  347. assertBadAddress("/", "Address cannot be empty")
  348. assertBadAddress("/8", "Address cannot be empty")
  349. assertBadAddress("bogus", "Expected 4 octets")
  350. assertBadAddress("google.com", "Expected 4 octets")
  351. assertBadAddress("10/8", "Expected 4 octets")
  352. assertBadAddress("::1.2.3.4", "Only decimal digits")
  353. assertBadAddress("1.2.3.256", re.escape("256 (> 255)"))
  354. def test_valid_netmask(self):
  355. self.assertEqual(str(self.factory('192.0.2.0/255.255.255.0')),
  356. '192.0.2.0/24')
  357. for i in range(0, 33):
  358. # Generate and re-parse the CIDR format (trivial).
  359. net_str = '0.0.0.0/%d' % i
  360. net = self.factory(net_str)
  361. self.assertEqual(str(net), net_str)
  362. # Generate and re-parse the expanded netmask.
  363. self.assertEqual(
  364. str(self.factory('0.0.0.0/%s' % net.netmask)), net_str)
  365. # Zero prefix is treated as decimal.
  366. self.assertEqual(str(self.factory('0.0.0.0/0%d' % i)), net_str)
  367. # Generate and re-parse the expanded hostmask. The ambiguous
  368. # cases (/0 and /32) are treated as netmasks.
  369. if i in (32, 0):
  370. net_str = '0.0.0.0/%d' % (32 - i)
  371. self.assertEqual(
  372. str(self.factory('0.0.0.0/%s' % net.hostmask)), net_str)
  373. def test_netmask_errors(self):
  374. def assertBadNetmask(addr, netmask):
  375. msg = "%r is not a valid netmask" % netmask
  376. with self.assertNetmaskError(re.escape(msg)):
  377. self.factory("%s/%s" % (addr, netmask))
  378. assertBadNetmask("1.2.3.4", "")
  379. assertBadNetmask("1.2.3.4", "-1")
  380. assertBadNetmask("1.2.3.4", "+1")
  381. assertBadNetmask("1.2.3.4", " 1 ")
  382. assertBadNetmask("1.2.3.4", "0x1")
  383. assertBadNetmask("1.2.3.4", "33")
  384. assertBadNetmask("1.2.3.4", "254.254.255.256")
  385. assertBadNetmask("1.2.3.4", "1.a.2.3")
  386. assertBadNetmask("1.1.1.1", "254.xyz.2.3")
  387. assertBadNetmask("1.1.1.1", "240.255.0.0")
  388. assertBadNetmask("1.1.1.1", "255.254.128.0")
  389. assertBadNetmask("1.1.1.1", "0.1.127.255")
  390. assertBadNetmask("1.1.1.1", "pudding")
  391. assertBadNetmask("1.1.1.1", "::")
  392. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  393. class InterfaceTestCase_v4(BaseTestCase, NetmaskTestMixin_v4):
  394. factory = ipaddress.IPv4Interface
  395. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  396. class NetworkTestCase_v4(BaseTestCase, NetmaskTestMixin_v4):
  397. factory = ipaddress.IPv4Network
  398. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  399. class NetmaskTestMixin_v6(CommonTestMixin_v6):
  400. """Input validation on interfaces and networks is very similar"""
  401. def test_split_netmask(self):
  402. addr = "cafe:cafe::/128/190"
  403. with self.assertAddressError("Only one '/' permitted in %r" % addr):
  404. self.factory(addr)
  405. def test_address_errors(self):
  406. def assertBadAddress(addr, details):
  407. with self.assertAddressError(details):
  408. self.factory(addr)
  409. assertBadAddress("/", "Address cannot be empty")
  410. assertBadAddress("/8", "Address cannot be empty")
  411. assertBadAddress("google.com", "At least 3 parts")
  412. assertBadAddress("1.2.3.4", "At least 3 parts")
  413. assertBadAddress("10/8", "At least 3 parts")
  414. assertBadAddress("1234:axy::b", "Only hex digits")
  415. def test_valid_netmask(self):
  416. # We only support CIDR for IPv6, because expanded netmasks are not
  417. # standard notation.
  418. self.assertEqual(str(self.factory('2001:db8::/32')), '2001:db8::/32')
  419. for i in range(0, 129):
  420. # Generate and re-parse the CIDR format (trivial).
  421. net_str = '::/%d' % i
  422. self.assertEqual(str(self.factory(net_str)), net_str)
  423. # Zero prefix is treated as decimal.
  424. self.assertEqual(str(self.factory('::/0%d' % i)), net_str)
  425. def test_netmask_errors(self):
  426. def assertBadNetmask(addr, netmask):
  427. msg = "%r is not a valid netmask" % netmask
  428. with self.assertNetmaskError(re.escape(msg)):
  429. self.factory("%s/%s" % (addr, netmask))
  430. assertBadNetmask("::1", "")
  431. assertBadNetmask("::1", "::1")
  432. assertBadNetmask("::1", "1::")
  433. assertBadNetmask("::1", "-1")
  434. assertBadNetmask("::1", "+1")
  435. assertBadNetmask("::1", " 1 ")
  436. assertBadNetmask("::1", "0x1")
  437. assertBadNetmask("::1", "129")
  438. assertBadNetmask("::1", "1.2.3.4")
  439. assertBadNetmask("::1", "pudding")
  440. assertBadNetmask("::", "::")
  441. @skipIf(WAR_ROOM_SKIP, 'WAR ROOM TEMPORARY SKIP')
  442. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  443. class InterfaceTestCase_v6(BaseTestCase, NetmaskTestMixin_v6):
  444. factory = ipaddress.IPv6Interface
  445. @skipIf(WAR_ROOM_SKIP, 'WAR ROOM TEMPORARY SKIP')
  446. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  447. class NetworkTestCase_v6(BaseTestCase, NetmaskTestMixin_v6):
  448. factory = ipaddress.IPv6Network
  449. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  450. class FactoryFunctionErrors(BaseTestCase):
  451. def assertFactoryError(self, factory, kind):
  452. """Ensure a clean ValueError with the expected message"""
  453. addr = "camelot"
  454. msg = '%r does not appear to be an IPv4 or IPv6 %s'
  455. with self.assertCleanError(ValueError, msg, addr, kind):
  456. factory(addr)
  457. def test_ip_address(self):
  458. self.assertFactoryError(ipaddress.ip_address, "address")
  459. def test_ip_interface(self):
  460. self.assertFactoryError(ipaddress.ip_interface, "interface")
  461. def test_ip_network(self):
  462. self.assertFactoryError(ipaddress.ip_network, "network")
  463. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  464. class ComparisonTests(TestCase):
  465. v4addr = ipaddress.IPv4Address(1)
  466. v4net = ipaddress.IPv4Network(1)
  467. v4intf = ipaddress.IPv4Interface(1)
  468. v6addr = ipaddress.IPv6Address(1)
  469. v6net = ipaddress.IPv6Network(1)
  470. v6intf = ipaddress.IPv6Interface(1)
  471. v4_addresses = [v4addr, v4intf]
  472. v4_objects = v4_addresses + [v4net]
  473. v6_addresses = [v6addr, v6intf]
  474. v6_objects = v6_addresses + [v6net]
  475. objects = v4_objects + v6_objects
  476. def test_foreign_type_equality(self):
  477. # __eq__ should never raise TypeError directly
  478. other = object()
  479. for obj in self.objects:
  480. self.assertNotEqual(obj, other)
  481. self.assertFalse(obj == other)
  482. self.assertEqual(obj.__eq__(other), NotImplemented)
  483. self.assertEqual(obj.__ne__(other), NotImplemented)
  484. def test_mixed_type_equality(self):
  485. # Ensure none of the internal objects accidentally
  486. # expose the right set of attributes to become "equal"
  487. for lhs in self.objects:
  488. for rhs in self.objects:
  489. if lhs is rhs:
  490. continue
  491. self.assertNotEqual(lhs, rhs)
  492. def test_containment(self):
  493. for obj in self.v4_addresses:
  494. self.assertIn(obj, self.v4net)
  495. for obj in self.v6_addresses:
  496. self.assertIn(obj, self.v6net)
  497. for obj in self.v4_objects + [self.v6net]:
  498. self.assertNotIn(obj, self.v6net)
  499. for obj in self.v6_objects + [self.v4net]:
  500. self.assertNotIn(obj, self.v4net)
  501. def test_mixed_type_ordering(self):
  502. for lhs in self.objects:
  503. for rhs in self.objects:
  504. if isinstance(lhs, type(rhs)) or isinstance(rhs, type(lhs)):
  505. continue
  506. self.assertRaises(TypeError, lambda: lhs < rhs)
  507. self.assertRaises(TypeError, lambda: lhs > rhs)
  508. self.assertRaises(TypeError, lambda: lhs <= rhs)
  509. self.assertRaises(TypeError, lambda: lhs >= rhs)
  510. def test_mixed_type_key(self):
  511. # with get_mixed_type_key, you can sort addresses and network.
  512. v4_ordered = [self.v4addr, self.v4net, self.v4intf]
  513. v6_ordered = [self.v6addr, self.v6net, self.v6intf]
  514. self.assertEqual(v4_ordered,
  515. sorted(self.v4_objects,
  516. key=ipaddress.get_mixed_type_key))
  517. self.assertEqual(v6_ordered,
  518. sorted(self.v6_objects,
  519. key=ipaddress.get_mixed_type_key))
  520. self.assertEqual(v4_ordered + v6_ordered,
  521. sorted(self.objects,
  522. key=ipaddress.get_mixed_type_key))
  523. self.assertEqual(NotImplemented, ipaddress.get_mixed_type_key(object))
  524. def test_incompatible_versions(self):
  525. # These should always raise TypeError
  526. v4addr = ipaddress.ip_address('1.1.1.1')
  527. v4net = ipaddress.ip_network('1.1.1.1')
  528. v6addr = ipaddress.ip_address('::1')
  529. v6net = ipaddress.ip_address('::1')
  530. self.assertRaises(TypeError, v4addr.__lt__, v6addr)
  531. self.assertRaises(TypeError, v4addr.__gt__, v6addr)
  532. self.assertRaises(TypeError, v4net.__lt__, v6net)
  533. self.assertRaises(TypeError, v4net.__gt__, v6net)
  534. self.assertRaises(TypeError, v6addr.__lt__, v4addr)
  535. self.assertRaises(TypeError, v6addr.__gt__, v4addr)
  536. self.assertRaises(TypeError, v6net.__lt__, v4net)
  537. self.assertRaises(TypeError, v6net.__gt__, v4net)
  538. @skipIf(WAR_ROOM_SKIP, 'WAR ROOM TEMPORARY SKIP')
  539. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  540. class IpaddrUnitTest(TestCase):
  541. def setUp(self):
  542. self.ipv4_address = ipaddress.IPv4Address('1.2.3.4')
  543. self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24')
  544. self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24')
  545. #self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255')
  546. self.ipv6_address = ipaddress.IPv6Interface(
  547. '2001:658:22a:cafe:200:0:0:1')
  548. self.ipv6_interface = ipaddress.IPv6Interface(
  549. '2001:658:22a:cafe:200:0:0:1/64')
  550. self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64')
  551. def tearDown(self):
  552. for attrname in ('ipv4_network', 'ipv4_interface', 'ipv4_address',
  553. 'ipv6_network', 'ipv6_interface', 'ipv6_address'):
  554. try:
  555. delattr(self, attrname)
  556. except AttributeError:
  557. continue
  558. def testRepr(self):
  559. self.assertEqual("IPv4Interface('1.2.3.4/32')",
  560. repr(ipaddress.IPv4Interface('1.2.3.4')))
  561. self.assertEqual("IPv6Interface('::1/128')",
  562. repr(ipaddress.IPv6Interface('::1')))
  563. # issue57
  564. def testAddressIntMath(self):
  565. self.assertEqual(ipaddress.IPv4Address('1.1.1.1') + 255,
  566. ipaddress.IPv4Address('1.1.2.0'))
  567. self.assertEqual(ipaddress.IPv4Address('1.1.1.1') - 256,
  568. ipaddress.IPv4Address('1.1.0.1'))
  569. self.assertEqual(ipaddress.IPv6Address('::1') + (2**16 - 2),
  570. ipaddress.IPv6Address('::ffff'))
  571. self.assertEqual(ipaddress.IPv6Address('::ffff') - (2**16 - 2),
  572. ipaddress.IPv6Address('::1'))
  573. def testInvalidIntToBytes(self):
  574. self.assertRaises(ValueError, ipaddress.v4_int_to_packed, -1)
  575. self.assertRaises(ValueError, ipaddress.v4_int_to_packed,
  576. 2 ** ipaddress.IPV4LENGTH)
  577. self.assertRaises(ValueError, ipaddress.v6_int_to_packed, -1)
  578. self.assertRaises(ValueError, ipaddress.v6_int_to_packed,
  579. 2 ** ipaddress.IPV6LENGTH)
  580. def testInternals(self):
  581. first, last = ipaddress._find_address_range([
  582. ipaddress.IPv4Address('10.10.10.10'),
  583. ipaddress.IPv4Address('10.10.10.12')])
  584. self.assertEqual(first, last)
  585. self.assertEqual(128, ipaddress._count_righthand_zero_bits(0, 128))
  586. self.assertEqual("IPv4Network('1.2.3.0/24')", repr(self.ipv4_network))
  587. def testMissingAddressVersion(self):
  588. class Broken(ipaddress._BaseAddress):
  589. pass
  590. broken = Broken('127.0.0.1')
  591. with self.assertRaisesRegex(NotImplementedError, "Broken.*version"):
  592. broken.version
  593. def testMissingNetworkVersion(self):
  594. class Broken(ipaddress._BaseNetwork):
  595. pass
  596. broken = Broken('127.0.0.1')
  597. with self.assertRaisesRegex(NotImplementedError, "Broken.*version"):
  598. broken.version
  599. def testMissingAddressClass(self):
  600. class Broken(ipaddress._BaseNetwork):
  601. pass
  602. broken = Broken('127.0.0.1')
  603. with self.assertRaisesRegex(NotImplementedError, "Broken.*address"):
  604. broken._address_class
  605. def testGetNetwork(self):
  606. self.assertEqual(int(self.ipv4_network.network_address), 16909056)
  607. self.assertEqual(str(self.ipv4_network.network_address), '1.2.3.0')
  608. self.assertEqual(int(self.ipv6_network.network_address),
  609. 42540616829182469433403647294022090752)
  610. self.assertEqual(str(self.ipv6_network.network_address),
  611. '2001:658:22a:cafe::')
  612. self.assertEqual(str(self.ipv6_network.hostmask),
  613. '::ffff:ffff:ffff:ffff')
  614. def testIpFromInt(self):
  615. self.assertEqual(self.ipv4_interface._ip,
  616. ipaddress.IPv4Interface(16909060)._ip)
  617. ipv4 = ipaddress.ip_network('1.2.3.4')
  618. ipv6 = ipaddress.ip_network('2001:658:22a:cafe:200:0:0:1')
  619. self.assertEqual(ipv4, ipaddress.ip_network(int(ipv4.network_address)))
  620. self.assertEqual(ipv6, ipaddress.ip_network(int(ipv6.network_address)))
  621. v6_int = 42540616829182469433547762482097946625
  622. self.assertEqual(self.ipv6_interface._ip,
  623. ipaddress.IPv6Interface(v6_int)._ip)
  624. self.assertEqual(ipaddress.ip_network(self.ipv4_address._ip).version,
  625. 4)
  626. self.assertEqual(ipaddress.ip_network(self.ipv6_address._ip).version,
  627. 6)
  628. def testIpFromPacked(self):
  629. address = ipaddress.ip_address
  630. self.assertEqual(self.ipv4_interface._ip,
  631. ipaddress.ip_interface(bytearray(b'\x01\x02\x03\x04'))._ip)
  632. self.assertEqual(address('255.254.253.252'),
  633. address(bytearray(b'\xff\xfe\xfd\xfc')))
  634. self.assertEqual(self.ipv6_interface.ip,
  635. ipaddress.ip_interface(
  636. bytearray(b'\x20\x01\x06\x58\x02\x2a\xca\xfe'
  637. b'\x02\x00\x00\x00\x00\x00\x00\x01')).ip)
  638. self.assertEqual(address('ffff:2:3:4:ffff::'),
  639. address(bytearray(b'\xff\xff\x00\x02\x00\x03\x00\x04') +
  640. bytearray(b'\xff\xff') + bytearray(b'\x00') * 6))
  641. self.assertEqual(address('::'),
  642. address(bytearray(b'\x00') * 16))
  643. def testGetIp(self):
  644. self.assertEqual(int(self.ipv4_interface.ip), 16909060)
  645. self.assertEqual(str(self.ipv4_interface.ip), '1.2.3.4')
  646. self.assertEqual(int(self.ipv6_interface.ip),
  647. 42540616829182469433547762482097946625)
  648. self.assertEqual(str(self.ipv6_interface.ip),
  649. '2001:658:22a:cafe:200::1')
  650. def testGetNetmask(self):
  651. self.assertEqual(int(self.ipv4_network.netmask), 4294967040)
  652. self.assertEqual(str(self.ipv4_network.netmask), '255.255.255.0')
  653. self.assertEqual(int(self.ipv6_network.netmask),
  654. 340282366920938463444927863358058659840)
  655. self.assertEqual(self.ipv6_network.prefixlen, 64)
  656. def testZeroNetmask(self):
  657. ipv4_zero_netmask = ipaddress.IPv4Interface('1.2.3.4/0')
  658. self.assertEqual(int(ipv4_zero_netmask.network.netmask), 0)
  659. self.assertEqual(ipv4_zero_netmask._prefix_from_prefix_string('0'), 0)
  660. self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0'))
  661. self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0.0.0.0'))
  662. self.assertFalse(ipv4_zero_netmask._is_valid_netmask('invalid'))
  663. ipv6_zero_netmask = ipaddress.IPv6Interface('::1/0')
  664. self.assertEqual(int(ipv6_zero_netmask.network.netmask), 0)
  665. self.assertEqual(ipv6_zero_netmask._prefix_from_prefix_string('0'), 0)
  666. def testIPv4NetAndHostmasks(self):
  667. net = self.ipv4_network
  668. self.assertFalse(net._is_valid_netmask('invalid'))
  669. self.assertTrue(net._is_valid_netmask('128.128.128.128'))
  670. self.assertFalse(net._is_valid_netmask('128.128.128.127'))
  671. self.assertFalse(net._is_valid_netmask('128.128.128.255'))
  672. self.assertTrue(net._is_valid_netmask('255.128.128.128'))
  673. self.assertFalse(net._is_hostmask('invalid'))
  674. self.assertTrue(net._is_hostmask('128.255.255.255'))
  675. self.assertFalse(net._is_hostmask('255.255.255.255'))
  676. self.assertFalse(net._is_hostmask('1.2.3.4'))
  677. net = ipaddress.IPv4Network('127.0.0.0/0.0.0.255')
  678. self.assertEqual(net.prefixlen, 24)
  679. def testGetBroadcast(self):
  680. self.assertEqual(int(self.ipv4_network.broadcast_address), 16909311)
  681. self.assertEqual(str(self.ipv4_network.broadcast_address), '1.2.3.255')
  682. self.assertEqual(int(self.ipv6_network.broadcast_address),
  683. 42540616829182469451850391367731642367)
  684. self.assertEqual(str(self.ipv6_network.broadcast_address),
  685. '2001:658:22a:cafe:ffff:ffff:ffff:ffff')
  686. def testGetPrefixlen(self):
  687. self.assertEqual(self.ipv4_interface.network.prefixlen, 24)
  688. self.assertEqual(self.ipv6_interface.network.prefixlen, 64)
  689. def testGetSupernet(self):
  690. self.assertEqual(self.ipv4_network.supernet().prefixlen, 23)
  691. self.assertEqual(str(self.ipv4_network.supernet().network_address),
  692. '1.2.2.0')
  693. self.assertEqual(
  694. ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(),
  695. ipaddress.IPv4Network('0.0.0.0/0'))
  696. self.assertEqual(self.ipv6_network.supernet().prefixlen, 63)
  697. self.assertEqual(str(self.ipv6_network.supernet().network_address),
  698. '2001:658:22a:cafe::')
  699. self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(),
  700. ipaddress.IPv6Network('::0/0'))
  701. def testGetSupernet3(self):
  702. self.assertEqual(self.ipv4_network.supernet(3).prefixlen, 21)
  703. self.assertEqual(str(self.ipv4_network.supernet(3).network_address),
  704. '1.2.0.0')
  705. self.assertEqual(self.ipv6_network.supernet(3).prefixlen, 61)
  706. self.assertEqual(str(self.ipv6_network.supernet(3).network_address),
  707. '2001:658:22a:caf8::')
  708. def testGetSupernet4(self):
  709. self.assertRaises(ValueError, self.ipv4_network.supernet,
  710. prefixlen_diff=2, new_prefix=1)
  711. self.assertRaises(ValueError, self.ipv4_network.supernet,
  712. new_prefix=25)
  713. self.assertEqual(self.ipv4_network.supernet(prefixlen_diff=2),
  714. self.ipv4_network.supernet(new_prefix=22))
  715. self.assertRaises(ValueError, self.ipv6_network.supernet,
  716. prefixlen_diff=2, new_prefix=1)
  717. self.assertRaises(ValueError, self.ipv6_network.supernet,
  718. new_prefix=65)
  719. self.assertEqual(self.ipv6_network.supernet(prefixlen_diff=2),
  720. self.ipv6_network.supernet(new_prefix=62))
  721. def testHosts(self):
  722. hosts = list(self.ipv4_network.hosts())
  723. self.assertEqual(254, len(hosts))
  724. self.assertEqual(ipaddress.IPv4Address('1.2.3.1'), hosts[0])
  725. self.assertEqual(ipaddress.IPv4Address('1.2.3.254'), hosts[-1])
  726. # special case where only 1 bit is left for address
  727. self.assertEqual([ipaddress.IPv4Address('2.0.0.0'),
  728. ipaddress.IPv4Address('2.0.0.1')],
  729. list(ipaddress.ip_network('2.0.0.0/31').hosts()))
  730. def testFancySubnetting(self):
  731. self.assertEqual(sorted(self.ipv4_network.subnets(prefixlen_diff=3)),
  732. sorted(self.ipv4_network.subnets(new_prefix=27)))
  733. self.assertRaises(ValueError, list,
  734. self.ipv4_network.subnets(new_prefix=23))
  735. self.assertRaises(ValueError, list,
  736. self.ipv4_network.subnets(prefixlen_diff=3,
  737. new_prefix=27))
  738. self.assertEqual(sorted(self.ipv6_network.subnets(prefixlen_diff=4)),
  739. sorted(self.ipv6_network.subnets(new_prefix=68)))
  740. self.assertRaises(ValueError, list,
  741. self.ipv6_network.subnets(new_prefix=63))
  742. self.assertRaises(ValueError, list,
  743. self.ipv6_network.subnets(prefixlen_diff=4,
  744. new_prefix=68))
  745. def testGetSubnets(self):
  746. self.assertEqual(list(self.ipv4_network.subnets())[0].prefixlen, 25)
  747. self.assertEqual(str(list(
  748. self.ipv4_network.subnets())[0].network_address),
  749. '1.2.3.0')
  750. self.assertEqual(str(list(
  751. self.ipv4_network.subnets())[1].network_address),
  752. '1.2.3.128')
  753. self.assertEqual(list(self.ipv6_network.subnets())[0].prefixlen, 65)
  754. def testGetSubnetForSingle32(self):
  755. ip = ipaddress.IPv4Network('1.2.3.4/32')
  756. subnets1 = [str(x) for x in ip.subnets()]
  757. subnets2 = [str(x) for x in ip.subnets(2)]
  758. self.assertEqual(subnets1, ['1.2.3.4/32'])
  759. self.assertEqual(subnets1, subnets2)
  760. def testGetSubnetForSingle128(self):
  761. ip = ipaddress.IPv6Network('::1/128')
  762. subnets1 = [str(x) for x in ip.subnets()]
  763. subnets2 = [str(x) for x in ip.subnets(2)]
  764. self.assertEqual(subnets1, ['::1/128'])
  765. self.assertEqual(subnets1, subnets2)
  766. def testSubnet2(self):
  767. ips = [str(x) for x in self.ipv4_network.subnets(2)]
  768. self.assertEqual(
  769. ips,
  770. ['1.2.3.0/26', '1.2.3.64/26', '1.2.3.128/26', '1.2.3.192/26'])
  771. ipsv6 = [str(x) for x in self.ipv6_network.subnets(2)]
  772. self.assertEqual(
  773. ipsv6,
  774. ['2001:658:22a:cafe::/66',
  775. '2001:658:22a:cafe:4000::/66',
  776. '2001:658:22a:cafe:8000::/66',
  777. '2001:658:22a:cafe:c000::/66'])
  778. def testSubnetFailsForLargeCidrDiff(self):
  779. self.assertRaises(ValueError, list,
  780. self.ipv4_interface.network.subnets(9))
  781. self.assertRaises(ValueError, list,
  782. self.ipv4_network.subnets(9))
  783. self.assertRaises(ValueError, list,
  784. self.ipv6_interface.network.subnets(65))
  785. self.assertRaises(ValueError, list,
  786. self.ipv6_network.subnets(65))
  787. def testSupernetFailsForLargeCidrDiff(self):
  788. self.assertRaises(ValueError,
  789. self.ipv4_interface.network.supernet, 25)
  790. self.assertRaises(ValueError,
  791. self.ipv6_interface.network.supernet, 65)
  792. def testSubnetFailsForNegativeCidrDiff(self):
  793. self.assertRaises(ValueError, list,
  794. self.ipv4_interface.network.subnets(-1))
  795. self.assertRaises(ValueError, list,
  796. self.ipv4_network.subnets(-1))
  797. self.assertRaises(ValueError, list,
  798. self.ipv6_interface.network.subnets(-1))
  799. self.assertRaises(ValueError, list,
  800. self.ipv6_network.subnets(-1))
  801. def testGetNum_Addresses(self):
  802. self.assertEqual(self.ipv4_network.num_addresses, 256)
  803. self.assertEqual(list(self.ipv4_network.subnets())[0].num_addresses,
  804. 128)
  805. self.assertEqual(self.ipv4_network.supernet().num_addresses, 512)
  806. self.assertEqual(self.ipv6_network.num_addresses, 18446744073709551616)
  807. self.assertEqual(list(self.ipv6_network.subnets())[0].num_addresses,
  808. 9223372036854775808)
  809. self.assertEqual(self.ipv6_network.supernet().num_addresses,
  810. 36893488147419103232)
  811. def testContains(self):
  812. self.assertIn(ipaddress.IPv4Interface('1.2.3.128/25'),
  813. self.ipv4_network)
  814. self.assertNotIn(ipaddress.IPv4Interface('1.2.4.1/24'),
  815. self.ipv4_network)
  816. # We can test addresses and string as well.
  817. addr1 = ipaddress.IPv4Address('1.2.3.37')
  818. self.assertIn(addr1, self.ipv4_network)
  819. # issue 61, bad network comparison on like-ip'd network objects
  820. # with identical broadcast addresses.
  821. self.assertFalse(ipaddress.IPv4Network('1.1.0.0/16').__contains__(
  822. ipaddress.IPv4Network('1.0.0.0/15')))
  823. def testNth(self):
  824. self.assertEqual(str(self.ipv4_network[5]), '1.2.3.5')
  825. self.assertRaises(IndexError, self.ipv4_network.__getitem__, 256)
  826. self.assertEqual(str(self.ipv6_network[5]),
  827. '2001:658:22a:cafe::5')
  828. def testGetitem(self):
  829. # http://code.google.com/p/ipaddr-py/issues/detail?id=15
  830. addr = ipaddress.IPv4Network('172.31.255.128/255.255.255.240')
  831. self.assertEqual(28, addr.prefixlen)
  832. addr_list = list(addr)
  833. self.assertEqual('172.31.255.128', str(addr_list[0]))
  834. self.assertEqual('172.31.255.128', str(addr[0]))
  835. self.assertEqual('172.31.255.143', str(addr_list[-1]))
  836. self.assertEqual('172.31.255.143', str(addr[-1]))
  837. self.assertEqual(addr_list[-1], addr[-1])
  838. def testEqual(self):
  839. self.assertTrue(self.ipv4_interface ==
  840. ipaddress.IPv4Interface('1.2.3.4/24'))
  841. self.assertFalse(self.ipv4_interface ==
  842. ipaddress.IPv4Interface('1.2.3.4/23'))
  843. self.assertFalse(self.ipv4_interface ==
  844. ipaddress.IPv6Interface('::1.2.3.4/24'))
  845. self.assertFalse(self.ipv4_interface == '')
  846. self.assertFalse(self.ipv4_interface == [])
  847. self.assertFalse(self.ipv4_interface == 2)
  848. self.assertTrue(self.ipv6_interface ==
  849. ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
  850. self.assertFalse(self.ipv6_interface ==
  851. ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
  852. self.assertFalse(self.ipv6_interface ==
  853. ipaddress.IPv4Interface('1.2.3.4/23'))
  854. self.assertFalse(self.ipv6_interface == '')
  855. self.assertFalse(self.ipv6_interface == [])
  856. self.assertFalse(self.ipv6_interface == 2)
  857. def testNotEqual(self):
  858. self.assertFalse(self.ipv4_interface !=
  859. ipaddress.IPv4Interface('1.2.3.4/24'))
  860. self.assertTrue(self.ipv4_interface !=
  861. ipaddress.IPv4Interface('1.2.3.4/23'))
  862. self.assertTrue(self.ipv4_interface !=
  863. ipaddress.IPv6Interface('::1.2.3.4/24'))
  864. self.assertTrue(self.ipv4_interface != '')
  865. self.assertTrue(self.ipv4_interface != [])
  866. self.assertTrue(self.ipv4_interface != 2)
  867. self.assertTrue(self.ipv4_address !=
  868. ipaddress.IPv4Address('1.2.3.5'))
  869. self.assertTrue(self.ipv4_address != '')
  870. self.assertTrue(self.ipv4_address != [])
  871. self.assertTrue(self.ipv4_address != 2)
  872. self.assertFalse(self.ipv6_interface !=
  873. ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
  874. self.assertTrue(self.ipv6_interface !=
  875. ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
  876. self.assertTrue(self.ipv6_interface !=
  877. ipaddress.IPv4Interface('1.2.3.4/23'))
  878. self.assertTrue(self.ipv6_interface != '')
  879. self.assertTrue(self.ipv6_interface != [])
  880. self.assertTrue(self.ipv6_interface != 2)
  881. self.assertTrue(self.ipv6_address !=
  882. ipaddress.IPv4Address('1.2.3.4'))
  883. self.assertTrue(self.ipv6_address != '')
  884. self.assertTrue(self.ipv6_address != [])
  885. self.assertTrue(self.ipv6_address != 2)
  886. def testSlash32Constructor(self):
  887. self.assertEqual(str(ipaddress.IPv4Interface(
  888. '1.2.3.4/255.255.255.255')), '1.2.3.4/32')
  889. def testSlash128Constructor(self):
  890. self.assertEqual(str(ipaddress.IPv6Interface('::1/128')),
  891. '::1/128')
  892. def testSlash0Constructor(self):
  893. self.assertEqual(str(ipaddress.IPv4Interface('1.2.3.4/0.0.0.0')),
  894. '1.2.3.4/0')
  895. def testCollapsing(self):
  896. # test only IP addresses including some duplicates
  897. ip1 = ipaddress.IPv4Address('1.1.1.0')
  898. ip2 = ipaddress.IPv4Address('1.1.1.1')
  899. ip3 = ipaddress.IPv4Address('1.1.1.2')
  900. ip4 = ipaddress.IPv4Address('1.1.1.3')
  901. ip5 = ipaddress.IPv4Address('1.1.1.4')
  902. ip6 = ipaddress.IPv4Address('1.1.1.0')
  903. # check that addreses are subsumed properly.
  904. collapsed = ipaddress.collapse_addresses(
  905. [ip1, ip2, ip3, ip4, ip5, ip6])
  906. self.assertEqual(list(collapsed),
  907. [ipaddress.IPv4Network('1.1.1.0/30'),
  908. ipaddress.IPv4Network('1.1.1.4/32')])
  909. # test a mix of IP addresses and networks including some duplicates
  910. ip1 = ipaddress.IPv4Address('1.1.1.0')
  911. ip2 = ipaddress.IPv4Address('1.1.1.1')
  912. ip3 = ipaddress.IPv4Address('1.1.1.2')
  913. ip4 = ipaddress.IPv4Address('1.1.1.3')
  914. #ip5 = ipaddress.IPv4Interface('1.1.1.4/30')
  915. #ip6 = ipaddress.IPv4Interface('1.1.1.4/30')
  916. # check that addreses are subsumed properly.
  917. collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3, ip4])
  918. self.assertEqual(list(collapsed),
  919. [ipaddress.IPv4Network('1.1.1.0/30')])
  920. # test only IP networks
  921. ip1 = ipaddress.IPv4Network('1.1.0.0/24')
  922. ip2 = ipaddress.IPv4Network('1.1.1.0/24')
  923. ip3 = ipaddress.IPv4Network('1.1.2.0/24')
  924. ip4 = ipaddress.IPv4Network('1.1.3.0/24')
  925. ip5 = ipaddress.IPv4Network('1.1.4.0/24')
  926. # stored in no particular order b/c we want CollapseAddr to call
  927. # [].sort
  928. ip6 = ipaddress.IPv4Network('1.1.0.0/22')
  929. # check that addreses are subsumed properly.
  930. collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3, ip4, ip5,
  931. ip6])
  932. self.assertEqual(list(collapsed),
  933. [ipaddress.IPv4Network('1.1.0.0/22'),
  934. ipaddress.IPv4Network('1.1.4.0/24')])
  935. # test that two addresses are supernet'ed properly
  936. collapsed = ipaddress.collapse_addresses([ip1, ip2])
  937. self.assertEqual(list(collapsed),
  938. [ipaddress.IPv4Network('1.1.0.0/23')])
  939. # test same IP networks
  940. ip_same1 = ip_same2 = ipaddress.IPv4Network('1.1.1.1/32')
  941. self.assertEqual(list(ipaddress.collapse_addresses(
  942. [ip_same1, ip_same2])),
  943. [ip_same1])
  944. # test same IP addresses
  945. ip_same1 = ip_same2 = ipaddress.IPv4Address('1.1.1.1')
  946. self.assertEqual(list(ipaddress.collapse_addresses(
  947. [ip_same1, ip_same2])),
  948. [ipaddress.ip_network('1.1.1.1/32')])
  949. ip1 = ipaddress.IPv6Network('2001::/100')
  950. ip2 = ipaddress.IPv6Network('2001::/120')
  951. ip3 = ipaddress.IPv6Network('2001::/96')
  952. # test that ipv6 addresses are subsumed properly.
  953. collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3])
  954. self.assertEqual(list(collapsed), [ip3])
  955. # the toejam test
  956. addr_tuples = [
  957. (ipaddress.ip_address('1.1.1.1'),
  958. ipaddress.ip_address('::1')),
  959. (ipaddress.IPv4Network('1.1.0.0/24'),
  960. ipaddress.IPv6Network('2001::/120')),
  961. (ipaddress.IPv4Network('1.1.0.0/32'),
  962. ipaddress.IPv6Network('2001::/128')),
  963. ]
  964. for ip1, ip2 in addr_tuples:
  965. self.assertRaises(TypeError, ipaddress.collapse_addresses,
  966. [ip1, ip2])
  967. def testSummarizing(self):
  968. #ip = ipaddress.ip_address
  969. #ipnet = ipaddress.ip_network
  970. summarize = ipaddress.summarize_address_range
  971. ip1 = ipaddress.ip_address('1.1.1.0')
  972. ip2 = ipaddress.ip_address('1.1.1.255')
  973. # summarize works only for IPv4 & IPv6
  974. class IPv7Address(ipaddress.IPv6Address):
  975. @property
  976. def version(self):
  977. return 7
  978. ip_invalid1 = IPv7Address('::1')
  979. ip_invalid2 = IPv7Address('::1')
  980. self.assertRaises(ValueError, list,
  981. summarize(ip_invalid1, ip_invalid2))
  982. # test that a summary over ip4 & ip6 fails
  983. self.assertRaises(TypeError, list,
  984. summarize(ip1, ipaddress.IPv6Address('::1')))
  985. # test a /24 is summarized properly
  986. self.assertEqual(list(summarize(ip1, ip2))[0],
  987. ipaddress.ip_network('1.1.1.0/24'))
  988. # test an IPv4 range that isn't on a network byte boundary
  989. ip2 = ipaddress.ip_address('1.1.1.8')
  990. self.assertEqual(list(summarize(ip1, ip2)),
  991. [ipaddress.ip_network('1.1.1.0/29'),
  992. ipaddress.ip_network('1.1.1.8')])
  993. # all!
  994. ip1 = ipaddress.IPv4Address(0)
  995. ip2 = ipaddress.IPv4Address(ipaddress.IPv4Address._ALL_ONES)
  996. self.assertEqual([ipaddress.IPv4Network('0.0.0.0/0')],
  997. list(summarize(ip1, ip2)))
  998. ip1 = ipaddress.ip_address('1::')
  999. ip2 = ipaddress.ip_address('1:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
  1000. # test a IPv6 is sumamrized properly
  1001. self.assertEqual(list(summarize(ip1, ip2))[0],
  1002. ipaddress.ip_network('1::/16'))
  1003. # test an IPv6 range that isn't on a network byte boundary
  1004. ip2 = ipaddress.ip_address('2::')
  1005. self.assertEqual(list(summarize(ip1, ip2)),
  1006. [ipaddress.ip_network('1::/16'),
  1007. ipaddress.ip_network('2::/128')])
  1008. # test exception raised when first is greater than last
  1009. self.assertRaises(ValueError, list,
  1010. summarize(ipaddress.ip_address('1.1.1.0'),
  1011. ipaddress.ip_address('1.1.0.0')))
  1012. # test exception raised when first and last aren't IP addresses
  1013. self.assertRaises(TypeError, list,
  1014. summarize(ipaddress.ip_network('1.1.1.0'),
  1015. ipaddress.ip_network('1.1.0.0')))
  1016. self.assertRaises(TypeError, list,
  1017. summarize(ipaddress.ip_network('1.1.1.0'),
  1018. ipaddress.ip_network('1.1.0.0')))
  1019. # test exception raised when first and last are not same version
  1020. self.assertRaises(TypeError, list,
  1021. summarize(ipaddress.ip_address('::'),
  1022. ipaddress.ip_network('1.1.0.0')))
  1023. def testAddressComparison(self):
  1024. self.assertTrue(ipaddress.ip_address('1.1.1.1') <=
  1025. ipaddress.ip_address('1.1.1.1'))
  1026. self.assertTrue(ipaddress.ip_address('1.1.1.1') <=
  1027. ipaddress.ip_address('1.1.1.2'))
  1028. self.assertTrue(ipaddress.ip_address('::1') <=
  1029. ipaddress.ip_address('::1'))
  1030. self.assertTrue(ipaddress.ip_address('::1') <=
  1031. ipaddress.ip_address('::2'))
  1032. def testInterfaceComparison(self):
  1033. self.assertTrue(ipaddress.ip_interface('1.1.1.1') <=
  1034. ipaddress.ip_interface('1.1.1.1'))
  1035. self.assertTrue(ipaddress.ip_interface('1.1.1.1') <=
  1036. ipaddress.ip_interface('1.1.1.2'))
  1037. self.assertTrue(ipaddress.ip_interface('::1') <=
  1038. ipaddress.ip_interface('::1'))
  1039. self.assertTrue(ipaddress.ip_interface('::1') <=
  1040. ipaddress.ip_interface('::2'))
  1041. def testNetworkComparison(self):
  1042. # ip1 and ip2 have the same network address
  1043. ip1 = ipaddress.IPv4Network('1.1.1.0/24')
  1044. ip2 = ipaddress.IPv4Network('1.1.1.0/32')
  1045. ip3 = ipaddress.IPv4Network('1.1.2.0/24')
  1046. self.assertTrue(ip1 < ip3)
  1047. self.assertTrue(ip3 > ip2)
  1048. self.assertEqual(ip1.compare_networks(ip1), 0)
  1049. # if addresses are the same, sort by netmask
  1050. self.assertEqual(ip1.compare_networks(ip2), -1)
  1051. self.assertEqual(ip2.compare_networks(ip1), 1)
  1052. self.assertEqual(ip1.compare_networks(ip3), -1)
  1053. self.assertEqual(ip3.compare_networks(ip1), 1)
  1054. self.assertTrue(ip1._get_networks_key() < ip3._get_networks_key())
  1055. ip1 = ipaddress.IPv6Network('2001:2000::/96')
  1056. ip2 = ipaddress.IPv6Network('2001:2001::/96')
  1057. ip3 = ipaddress.IPv6Network('2001:ffff:2000::/96')
  1058. self.assertTrue(ip1 < ip3)
  1059. self.assertTrue(ip3 > ip2)
  1060. self.assertEqual(ip1.compare_networks(ip3), -1)
  1061. self.assertTrue(ip1._get_networks_key() < ip3._get_networks_key())
  1062. # Test comparing different protocols.
  1063. # Should always raise a TypeError.
  1064. self.assertRaises(TypeError,
  1065. self.ipv4_network.compare_networks,
  1066. self.ipv6_network)
  1067. ipv6 = ipaddress.IPv6Interface('::/0')
  1068. ipv4 = ipaddress.IPv4Interface('0.0.0.0/0')
  1069. self.assertRaises(TypeError, ipv4.__lt__, ipv6)
  1070. self.assertRaises(TypeError, ipv4.__gt__, ipv6)
  1071. self.assertRaises(TypeError, ipv6.__lt__, ipv4)
  1072. self.assertRaises(TypeError, ipv6.__gt__, ipv4)
  1073. # Regression test for issue 19.
  1074. ip1 = ipaddress.ip_network('10.1.2.128/25')
  1075. self.assertFalse(ip1 < ip1)
  1076. self.assertFalse(ip1 > ip1)
  1077. ip2 = ipaddress.ip_network('10.1.3.0/24')
  1078. self.assertTrue(ip1 < ip2)
  1079. self.assertFalse(ip2 < ip1)
  1080. self.assertFalse(ip1 > ip2)
  1081. self.assertTrue(ip2 > ip1)
  1082. ip3 = ipaddress.ip_network('10.1.3.0/25')
  1083. self.assertTrue(ip2 < ip3)
  1084. self.assertFalse(ip3 < ip2)
  1085. self.assertFalse(ip2 > ip3)
  1086. self.assertTrue(ip3 > ip2)
  1087. # Regression test for issue 28.
  1088. ip1 = ipaddress.ip_network('10.10.10.0/31')
  1089. ip2 = ipaddress.ip_network('10.10.10.0')
  1090. ip3 = ipaddress.ip_network('10.10.10.2/31')
  1091. ip4 = ipaddress.ip_network('10.10.10.2')
  1092. sorted = [ip1, ip2, ip3, ip4]
  1093. unsorted = [ip2, ip4, ip1, ip3]
  1094. unsorted.sort()
  1095. self.assertEqual(sorted, unsorted)
  1096. unsorted = [ip4, ip1, ip3, ip2]
  1097. unsorted.sort()
  1098. self.assertEqual(sorted, unsorted)
  1099. self.assertRaises(TypeError, ip1.__lt__,
  1100. ipaddress.ip_address('10.10.10.0'))
  1101. self.assertRaises(TypeError, ip2.__lt__,
  1102. ipaddress.ip_address('10.10.10.0'))
  1103. # <=, >=
  1104. self.assertTrue(ipaddress.ip_network('1.1.1.1') <=
  1105. ipaddress.ip_network('1.1.1.1'))
  1106. self.assertTrue(ipaddress.ip_network('1.1.1.1') <=
  1107. ipaddress.ip_network('1.1.1.2'))
  1108. self.assertFalse(ipaddress.ip_network('1.1.1.2') <=
  1109. ipaddress.ip_network('1.1.1.1'))
  1110. self.assertTrue(ipaddress.ip_network('::1') <=
  1111. ipaddress.ip_network('::1'))
  1112. self.assertTrue(ipaddress.ip_network('::1') <=
  1113. ipaddress.ip_network('::2'))
  1114. self.assertFalse(ipaddress.ip_network('::2') <=
  1115. ipaddress.ip_network('::1'))
  1116. def testStrictNetworks(self):
  1117. self.assertRaises(ValueError, ipaddress.ip_network, '192.168.1.1/24')
  1118. self.assertRaises(ValueError, ipaddress.ip_network, '::1/120')
  1119. def testOverlaps(self):
  1120. other = ipaddress.IPv4Network('1.2.3.0/30')
  1121. other2 = ipaddress.IPv4Network('1.2.2.0/24')
  1122. other3 = ipaddress.IPv4Network('1.2.2.64/26')
  1123. self.assertTrue(self.ipv4_network.overlaps(other))
  1124. self.assertFalse(self.ipv4_network.overlaps(other2))
  1125. self.assertTrue(other2.overlaps(other3))
  1126. def testEmbeddedIpv4(self):
  1127. ipv4_string = '192.168.0.1'
  1128. ipv4 = ipaddress.IPv4Interface(ipv4_string)
  1129. v4compat_ipv6 = ipaddress.IPv6Interface('::%s' % ipv4_string)
  1130. self.assertEqual(int(v4compat_ipv6.ip), int(ipv4.ip))
  1131. v4mapped_ipv6 = ipaddress.IPv6Interface('::ffff:%s' % ipv4_string)
  1132. self.assertNotEqual(v4mapped_ipv6.ip, ipv4.ip)
  1133. self.assertRaises(ipaddress.AddressValueError, ipaddress.IPv6Interface,
  1134. '2001:1.1.1.1:1.1.1.1')
  1135. # Issue 67: IPv6 with embedded IPv4 address not recognized.
  1136. def testIPv6AddressTooLarge(self):
  1137. # RFC4291 2.5.5.2
  1138. self.assertEqual(ipaddress.ip_address('::FFFF:192.0.2.1'),
  1139. ipaddress.ip_address('::FFFF:c000:201'))
  1140. # RFC4291 2.2 (part 3) x::d.d.d.d
  1141. self.assertEqual(ipaddress.ip_address('FFFF::192.0.2.1'),
  1142. ipaddress.ip_address('FFFF::c000:201'))
  1143. def testIPVersion(self):
  1144. self.assertEqual(self.ipv4_address.version, 4)
  1145. self.assertEqual(self.ipv6_address.version, 6)
  1146. def testMaxPrefixLength(self):
  1147. self.assertEqual(self.ipv4_interface.max_prefixlen, 32)
  1148. self.assertEqual(self.ipv6_interface.max_prefixlen, 128)
  1149. def testPacked(self):
  1150. self.assertEqual(self.ipv4_address.packed,
  1151. bytearray(b'\x01\x02\x03\x04'))
  1152. self.assertEqual(ipaddress.IPv4Interface('255.254.253.252').packed,
  1153. bytearray(b'\xff\xfe\xfd\xfc'))
  1154. self.assertEqual(self.ipv6_address.packed,
  1155. bytearray(b'\x20\x01\x06\x58\x02\x2a\xca\xfe'
  1156. b'\x02\x00\x00\x00\x00\x00\x00\x01'))
  1157. self.assertEqual(ipaddress.IPv6Interface('ffff:2:3:4:ffff::').packed,
  1158. bytearray(b'\xff\xff\x00\x02\x00\x03\x00\x04\xff\xff')
  1159. + bytearray(b'\x00') * 6)
  1160. self.assertEqual(ipaddress.IPv6Interface('::1:0:0:0:0').packed,
  1161. bytearray(b'\x00') * 6 + bytearray(b'\x00\x01') + bytearray(b'\x00') * 8)
  1162. def testIpType(self):
  1163. ipv4net = ipaddress.ip_network('1.2.3.4')
  1164. ipv4addr = ipaddress.ip_address('1.2.3.4')
  1165. ipv6net = ipaddress.ip_network('::1.2.3.4')
  1166. ipv6addr = ipaddress.ip_address('::1.2.3.4')
  1167. self.assertEqual(ipaddress.IPv4Network, type(ipv4net))
  1168. self.assertEqual(ipaddress.IPv4Address, type(ipv4addr))
  1169. self.assertEqual(ipaddress.IPv6Network, type(ipv6net))
  1170. self.assertEqual(ipaddress.IPv6Address, type(ipv6addr))
  1171. def testReservedIpv4(self):
  1172. # test networks
  1173. self.assertEqual(True, ipaddress.ip_interface(
  1174. '224.1.1.1/31').is_multicast)
  1175. self.assertEqual(False, ipaddress.ip_network('240.0.0.0').is_multicast)
  1176. self.assertEqual(True, ipaddress.ip_network('240.0.0.0').is_reserved)
  1177. self.assertEqual(True, ipaddress.ip_interface(
  1178. '192.168.1.1/17').is_private)
  1179. self.assertEqual(False, ipaddress.ip_network('192.169.0.0').is_private)
  1180. self.assertEqual(True, ipaddress.ip_network(
  1181. '10.255.255.255').is_private)
  1182. self.assertEqual(False, ipaddress.ip_network('11.0.0.0').is_private)
  1183. self.assertEqual(False, ipaddress.ip_network('11.0.0.0').is_reserved)
  1184. self.assertEqual(True, ipaddress.ip_network(
  1185. '172.31.255.255').is_private)
  1186. self.assertEqual(False, ipaddress.ip_network('172.32.0.0').is_private)
  1187. self.assertEqual(True,
  1188. ipaddress.ip_network('169.254.1.0/24').is_link_local)
  1189. self.assertEqual(True,
  1190. ipaddress.ip_interface(
  1191. '169.254.100.200/24').is_link_local)
  1192. self.assertEqual(False,
  1193. ipaddress.ip_interface(
  1194. '169.255.100.200/24').is_link_local)
  1195. self.assertEqual(True,
  1196. ipaddress.ip_network(
  1197. '127.100.200.254/32').is_loopback)
  1198. self.assertEqual(True, ipaddress.ip_network(
  1199. '127.42.0.0/16').is_loopback)
  1200. self.assertEqual(False, ipaddress.ip_network('128.0.0.0').is_loopback)
  1201. self.assertEqual(False,
  1202. ipaddress.ip_network('100.64.0.0/10').is_private)
  1203. self.assertEqual(False, ipaddress.ip_network('100.64.0.0/10').is_global)
  1204. self.assertEqual(True,
  1205. ipaddress.ip_network('192.0.2.128/25').is_private)
  1206. self.assertEqual(True,
  1207. ipaddress.ip_network('192.0.3.0/24').is_global)
  1208. # test addresses
  1209. self.assertEqual(True, ipaddress.ip_address('0.0.0.0').is_unspecified)
  1210. self.assertEqual(True, ipaddress.ip_address('224.1.1.1').is_multicast)
  1211. self.assertEqual(False, ipaddress.ip_address('240.0.0.0').is_multicast)
  1212. self.assertEqual(True, ipaddress.ip_address('240.0.0.1').is_reserved)
  1213. self.assertEqual(False,
  1214. ipaddress.ip_address('239.255.255.255').is_reserved)
  1215. self.assertEqual(True, ipaddress.ip_address('192.168.1.1').is_private)
  1216. self.assertEqual(False, ipaddress.ip_address('192.169.0.0').is_private)
  1217. self.assertEqual(True, ipaddress.ip_address(
  1218. '10.255.255.255').is_private)
  1219. self.assertEqual(False, ipaddress.ip_address('11.0.0.0').is_private)
  1220. self.assertEqual(True, ipaddress.ip_address(
  1221. '172.31.255.255').is_private)
  1222. self.assertEqual(False, ipaddress.ip_address('172.32.0.0').is_private)
  1223. self.assertEqual(True,
  1224. ipaddress.ip_address('169.254.100.200').is_link_local)
  1225. self.assertEqual(False,
  1226. ipaddress.ip_address('169.255.100.200').is_link_local)
  1227. self.assertEqual(True,
  1228. ipaddress.ip_address('127.100.200.254').is_loopback)
  1229. self.assertEqual(True, ipaddress.ip_address('127.42.0.0').is_loopback)
  1230. self.assertEqual(False, ipaddress.ip_address('128.0.0.0').is_loopback)
  1231. self.assertEqual(True, ipaddress.ip_network('0.0.0.0').is_unspecified)
  1232. def testReservedIpv6(self):
  1233. self.assertEqual(True, ipaddress.ip_network('ffff::').is_multicast)
  1234. self.assertEqual(True, ipaddress.ip_network(2**128 - 1).is_multicast)
  1235. self.assertEqual(True, ipaddress.ip_network('ff00::').is_multicast)
  1236. self.assertEqual(False, ipaddress.ip_network('fdff::').is_multicast)
  1237. self.assertEqual(True, ipaddress.ip_network('fecf::').is_site_local)
  1238. self.assertEqual(True, ipaddress.ip_network(
  1239. 'feff:ffff:ffff:ffff::').is_site_local)
  1240. self.assertEqual(False, ipaddress.ip_network(
  1241. 'fbf:ffff::').is_site_local)
  1242. self.assertEqual(False, ipaddress.ip_network('ff00::').is_site_local)
  1243. self.assertEqual(True, ipaddress.ip_network('fc00::').is_private)
  1244. self.assertEqual(True, ipaddress.ip_network(
  1245. 'fc00:ffff:ffff:ffff::').is_private)
  1246. self.assertEqual(False, ipaddress.ip_network('fbff:ffff::').is_private)
  1247. self.assertEqual(False, ipaddress.ip_network('fe00::').is_private)
  1248. self.assertEqual(True, ipaddress.ip_network('fea0::').is_link_local)
  1249. self.assertEqual(True, ipaddress.ip_network(
  1250. 'febf:ffff::').is_link_local)
  1251. self.assertEqual(False, ipaddress.ip_network(
  1252. 'fe7f:ffff::').is_link_local)
  1253. self.assertEqual(False, ipaddress.ip_network('fec0::').is_link_local)
  1254. self.assertEqual(True, ipaddress.ip_interface('0:0::0:01').is_loopback)
  1255. self.assertEqual(False, ipaddress.ip_interface('::1/127').is_loopback)
  1256. self.assertEqual(False, ipaddress.ip_network('::').is_loopback)
  1257. self.assertEqual(False, ipaddress.ip_network('::2').is_loopback)
  1258. self.assertEqual(True, ipaddress.ip_network('0::0').is_unspecified)
  1259. self.assertEqual(False, ipaddress.ip_network('::1').is_unspecified)
  1260. self.assertEqual(False, ipaddress.ip_network('::/127').is_unspecified)
  1261. self.assertEqual(True,
  1262. ipaddress.ip_network('2001::1/128').is_private)
  1263. self.assertEqual(True,
  1264. ipaddress.ip_network('200::1/128').is_global)
  1265. # test addresses
  1266. self.assertEqual(True, ipaddress.ip_address('ffff::').is_multicast)
  1267. self.assertEqual(True, ipaddress.ip_address(2**128 - 1).is_multicast)
  1268. self.assertEqual(True, ipaddress.ip_address('ff00::').is_multicast)
  1269. self.assertEqual(False, ipaddress.ip_address('fdff::').is_multicast)
  1270. self.assertEqual(True, ipaddress.ip_address('fecf::').is_site_local)
  1271. self.assertEqual(True, ipaddress.ip_address(
  1272. 'feff:ffff:ffff:ffff::').is_site_local)
  1273. self.assertEqual(False, ipaddress.ip_address(
  1274. 'fbf:ffff::').is_site_local)
  1275. self.assertEqual(False, ipaddress.ip_address('ff00::').is_site_local)
  1276. self.assertEqual(True, ipaddress.ip_address('fc00::').is_private)
  1277. self.assertEqual(True, ipaddress.ip_address(
  1278. 'fc00:ffff:ffff:ffff::').is_private)
  1279. self.assertEqual(False, ipaddress.ip_address('fbff:ffff::').is_private)
  1280. self.assertEqual(False, ipaddress.ip_address('fe00::').is_private)
  1281. self.assertEqual(True, ipaddress.ip_address('fea0::').is_link_local)
  1282. self.assertEqual(True, ipaddress.ip_address(
  1283. 'febf:ffff::').is_link_local)
  1284. self.assertEqual(False, ipaddress.ip_address(
  1285. 'fe7f:ffff::').is_link_local)
  1286. self.assertEqual(False, ipaddress.ip_address('fec0::').is_link_local)
  1287. self.assertEqual(True, ipaddress.ip_address('0:0::0:01').is_loopback)
  1288. self.assertEqual(True, ipaddress.ip_address('::1').is_loopback)
  1289. self.assertEqual(False, ipaddress.ip_address('::2').is_loopback)
  1290. self.assertEqual(True, ipaddress.ip_address('0::0').is_unspecified)
  1291. self.assertEqual(False, ipaddress.ip_address('::1').is_unspecified)
  1292. # some generic IETF reserved addresses
  1293. self.assertEqual(True, ipaddress.ip_address('100::').is_reserved)
  1294. self.assertEqual(True, ipaddress.ip_network('4000::1/128').is_reserved)
  1295. def testIpv4Mapped(self):
  1296. self.assertEqual(
  1297. ipaddress.ip_address('::ffff:192.168.1.1').ipv4_mapped,
  1298. ipaddress.ip_address('192.168.1.1'))
  1299. self.assertEqual(ipaddress.ip_address('::c0a8:101').ipv4_mapped, None)
  1300. self.assertEqual(ipaddress.ip_address('::ffff:c0a8:101').ipv4_mapped,
  1301. ipaddress.ip_address('192.168.1.1'))
  1302. def testAddrExclude(self):
  1303. addr1 = ipaddress.ip_network('10.1.1.0/24')
  1304. addr2 = ipaddress.ip_network('10.1.1.0/26')
  1305. addr3 = ipaddress.ip_network('10.2.1.0/24')
  1306. addr4 = ipaddress.ip_address('10.1.1.0')
  1307. addr5 = ipaddress.ip_network('2001:db8::0/32')
  1308. self.assertEqual(sorted(list(addr1.address_exclude(addr2))),
  1309. [ipaddress.ip_network('10.1.1.64/26'),
  1310. ipaddress.ip_network('10.1.1.128/25')])
  1311. self.assertRaises(ValueError, list, addr1.address_exclude(addr3))
  1312. self.assertRaises(TypeError, list, addr1.address_exclude(addr4))
  1313. self.assertRaises(TypeError, list, addr1.address_exclude(addr5))
  1314. self.assertEqual(list(addr1.address_exclude(addr1)), [])
  1315. def testHash(self):
  1316. self.assertEqual(hash(ipaddress.ip_interface('10.1.1.0/24')),
  1317. hash(ipaddress.ip_interface('10.1.1.0/24')))
  1318. self.assertEqual(hash(ipaddress.ip_network('10.1.1.0/24')),
  1319. hash(ipaddress.ip_network('10.1.1.0/24')))
  1320. self.assertEqual(hash(ipaddress.ip_address('10.1.1.0')),
  1321. hash(ipaddress.ip_address('10.1.1.0')))
  1322. # i70
  1323. self.assertEqual(hash(ipaddress.ip_address('1.2.3.4')),
  1324. hash(ipaddress.ip_address(
  1325. int(ipaddress.ip_address('1.2.3.4')._ip))))
  1326. ip1 = ipaddress.ip_address('10.1.1.0')
  1327. ip2 = ipaddress.ip_address('1::')
  1328. dummy = {}
  1329. dummy[self.ipv4_address] = None
  1330. dummy[self.ipv6_address] = None
  1331. dummy[ip1] = None
  1332. dummy[ip2] = None
  1333. self.assertIn(self.ipv4_address, dummy)
  1334. self.assertIn(ip2, dummy)
  1335. def testIPBases(self):
  1336. net = self.ipv4_network
  1337. self.assertEqual('1.2.3.0/24', net.compressed)
  1338. net = self.ipv6_network
  1339. self.assertRaises(ValueError, net._string_from_ip_int, 2**128 + 1)
  1340. def testIPv6NetworkHelpers(self):
  1341. net = self.ipv6_network
  1342. self.assertEqual('2001:658:22a:cafe::/64', net.with_prefixlen)
  1343. self.assertEqual('2001:658:22a:cafe::/ffff:ffff:ffff:ffff::',
  1344. net.with_netmask)
  1345. self.assertEqual('2001:658:22a:cafe::/::ffff:ffff:ffff:ffff',
  1346. net.with_hostmask)
  1347. self.assertEqual('2001:658:22a:cafe::/64', str(net))
  1348. def testIPv4NetworkHelpers(self):
  1349. net = self.ipv4_network
  1350. self.assertEqual('1.2.3.0/24', net.with_prefixlen)
  1351. self.assertEqual('1.2.3.0/255.255.255.0', net.with_netmask)
  1352. self.assertEqual('1.2.3.0/0.0.0.255', net.with_hostmask)
  1353. self.assertEqual('1.2.3.0/24', str(net))
  1354. def testCopyConstructor(self):
  1355. addr1 = ipaddress.ip_network('10.1.1.0/24')
  1356. addr2 = ipaddress.ip_network(addr1)
  1357. addr3 = ipaddress.ip_interface('2001:658:22a:cafe:200::1/64')
  1358. addr4 = ipaddress.ip_interface(addr3)
  1359. addr5 = ipaddress.IPv4Address('1.1.1.1')
  1360. addr6 = ipaddress.IPv6Address('2001:658:22a:cafe:200::1')
  1361. self.assertEqual(addr1, addr2)
  1362. self.assertEqual(addr3, addr4)
  1363. self.assertEqual(addr5, ipaddress.IPv4Address(addr5))
  1364. self.assertEqual(addr6, ipaddress.IPv6Address(addr6))
  1365. def testCompressIPv6Address(self):
  1366. test_addresses = {
  1367. '1:2:3:4:5:6:7:8': '1:2:3:4:5:6:7:8/128',
  1368. '2001:0:0:4:0:0:0:8': '2001:0:0:4::8/128',
  1369. '2001:0:0:4:5:6:7:8': '2001::4:5:6:7:8/128',
  1370. '2001:0:3:4:5:6:7:8': '2001:0:3:4:5:6:7:8/128',
  1371. '2001:0:3:4:5:6:7:8': '2001:0:3:4:5:6:7:8/128',
  1372. '0:0:3:0:0:0:0:ffff': '0:0:3::ffff/128',
  1373. '0:0:0:4:0:0:0:ffff': '::4:0:0:0:ffff/128',
  1374. '0:0:0:0:5:0:0:ffff': '::5:0:0:ffff/128',
  1375. '1:0:0:4:0:0:7:8': '1::4:0:0:7:8/128',
  1376. '0:0:0:0:0:0:0:0': '::/128',
  1377. '0:0:0:0:0:0:0:0/0': '::/0',
  1378. '0:0:0:0:0:0:0:1': '::1/128',
  1379. '2001:0658:022a:cafe:0000:0000:0000:0000/66':
  1380. '2001:658:22a:cafe::/66',
  1381. '::1.2.3.4': '::102:304/128',
  1382. '1:2:3:4:5:ffff:1.2.3.4': '1:2:3:4:5:ffff:102:304/128',
  1383. '::7:6:5:4:3:2:1': '0:7:6:5:4:3:2:1/128',
  1384. '::7:6:5:4:3:2:0': '0:7:6:5:4:3:2:0/128',
  1385. '7:6:5:4:3:2:1::': '7:6:5:4:3:2:1:0/128',
  1386. '0:6:5:4:3:2:1::': '0:6:5:4:3:2:1:0/128',
  1387. }
  1388. for uncompressed, compressed in list(test_addresses.items()):
  1389. self.assertEqual(compressed, str(ipaddress.IPv6Interface(
  1390. uncompressed)))
  1391. def testExplodeShortHandIpStr(self):
  1392. addr1 = ipaddress.IPv6Interface('2001::1')
  1393. addr2 = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
  1394. addr3 = ipaddress.IPv6Network('2001::/96')
  1395. addr4 = ipaddress.IPv4Address('192.168.178.1')
  1396. self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0001/128',
  1397. addr1.exploded)
  1398. self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0001/128',
  1399. ipaddress.IPv6Interface('::1/128').exploded)
  1400. # issue 77
  1401. self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1',
  1402. addr2.exploded)
  1403. self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0000/96',
  1404. addr3.exploded)
  1405. self.assertEqual('192.168.178.1', addr4.exploded)
  1406. def testIntRepresentation(self):
  1407. self.assertEqual(16909060, int(self.ipv4_address))
  1408. self.assertEqual(42540616829182469433547762482097946625,
  1409. int(self.ipv6_address))
  1410. def testForceVersion(self):
  1411. self.assertEqual(ipaddress.ip_network(1).version, 4)
  1412. self.assertEqual(ipaddress.IPv6Network(1).version, 6)
  1413. def testWithStar(self):
  1414. self.assertEqual(self.ipv4_interface.with_prefixlen, "1.2.3.4/24")
  1415. self.assertEqual(self.ipv4_interface.with_netmask,
  1416. "1.2.3.4/255.255.255.0")
  1417. self.assertEqual(self.ipv4_interface.with_hostmask,
  1418. "1.2.3.4/0.0.0.255")
  1419. self.assertEqual(self.ipv6_interface.with_prefixlen,
  1420. '2001:658:22a:cafe:200::1/64')
  1421. self.assertEqual(self.ipv6_interface.with_netmask,
  1422. '2001:658:22a:cafe:200::1/ffff:ffff:ffff:ffff::')
  1423. # this probably don't make much sense, but it's included for
  1424. # compatibility with ipv4
  1425. self.assertEqual(self.ipv6_interface.with_hostmask,
  1426. '2001:658:22a:cafe:200::1/::ffff:ffff:ffff:ffff')
  1427. def testNetworkElementCaching(self):
  1428. # V4 - make sure we're empty
  1429. self.assertNotIn('network_address', self.ipv4_network._cache)
  1430. self.assertNotIn('broadcast_address', self.ipv4_network._cache)
  1431. self.assertNotIn('hostmask', self.ipv4_network._cache)
  1432. # V4 - populate and test
  1433. self.assertEqual(self.ipv4_network.network_address,
  1434. ipaddress.IPv4Address('1.2.3.0'))
  1435. self.assertEqual(self.ipv4_network.broadcast_address,
  1436. ipaddress.IPv4Address('1.2.3.255'))
  1437. self.assertEqual(self.ipv4_network.hostmask,
  1438. ipaddress.IPv4Address('0.0.0.255'))
  1439. # V4 - check we're cached
  1440. self.assertIn('broadcast_address', self.ipv4_network._cache)
  1441. self.assertIn('hostmask', self.ipv4_network._cache)
  1442. # V6 - make sure we're empty
  1443. self.assertNotIn('broadcast_address', self.ipv6_network._cache)
  1444. self.assertNotIn('hostmask', self.ipv6_network._cache)
  1445. # V6 - populate and test
  1446. self.assertEqual(self.ipv6_network.network_address,
  1447. ipaddress.IPv6Address('2001:658:22a:cafe::'))
  1448. self.assertEqual(self.ipv6_interface.network.network_address,
  1449. ipaddress.IPv6Address('2001:658:22a:cafe::'))
  1450. self.assertEqual(
  1451. self.ipv6_network.broadcast_address,
  1452. ipaddress.IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff'))
  1453. self.assertEqual(self.ipv6_network.hostmask,
  1454. ipaddress.IPv6Address('::ffff:ffff:ffff:ffff'))
  1455. self.assertEqual(
  1456. self.ipv6_interface.network.broadcast_address,
  1457. ipaddress.IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff'))
  1458. self.assertEqual(self.ipv6_interface.network.hostmask,
  1459. ipaddress.IPv6Address('::ffff:ffff:ffff:ffff'))
  1460. # V6 - check we're cached
  1461. self.assertIn('broadcast_address', self.ipv6_network._cache)
  1462. self.assertIn('hostmask', self.ipv6_network._cache)
  1463. self.assertIn('broadcast_address', self.ipv6_interface.network._cache)
  1464. self.assertIn('hostmask', self.ipv6_interface.network._cache)
  1465. def testTeredo(self):
  1466. # stolen from wikipedia
  1467. server = ipaddress.IPv4Address('65.54.227.120')
  1468. client = ipaddress.IPv4Address('192.0.2.45')
  1469. teredo_addr = '2001:0000:4136:e378:8000:63bf:3fff:fdd2'
  1470. self.assertEqual((server, client),
  1471. ipaddress.ip_address(teredo_addr).teredo)
  1472. bad_addr = '2000::4136:e378:8000:63bf:3fff:fdd2'
  1473. self.assertFalse(ipaddress.ip_address(bad_addr).teredo)
  1474. bad_addr = '2001:0001:4136:e378:8000:63bf:3fff:fdd2'
  1475. self.assertFalse(ipaddress.ip_address(bad_addr).teredo)
  1476. # i77
  1477. teredo_addr = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
  1478. self.assertEqual((ipaddress.IPv4Address('94.245.121.253'),
  1479. ipaddress.IPv4Address('95.26.244.94')),
  1480. teredo_addr.teredo)
  1481. def testsixtofour(self):
  1482. sixtofouraddr = ipaddress.ip_address('2002:ac1d:2d64::1')
  1483. bad_addr = ipaddress.ip_address('2000:ac1d:2d64::1')
  1484. self.assertEqual(ipaddress.IPv4Address('172.29.45.100'),
  1485. sixtofouraddr.sixtofour)
  1486. self.assertFalse(bad_addr.sixtofour)