Debian Codegraph @

tests/test_wire.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 import unittest
4
5 import dns.exception
6 import dns.wire
7 import dns.name
8
9
10 class BinaryTestCase(unittest.TestCase):
11 def test_basic(self):
12 wire = bytes.fromhex("0102010203040102")
13 p = dns.wire.Parser(wire)
14 self.assertEqual(p.get_uint16(), 0x0102)
15 with p.restrict_to(5):
16 self.assertEqual(p.get_uint32(), 0x01020304)
17 self.assertEqual(p.get_uint8(), 0x01)
18 self.assertEqual(p.remaining(), 0)
19 with self.assertRaises(dns.exception.FormError):
20 p.get_uint16()
21 self.assertEqual(p.remaining(), 1)
22 self.assertEqual(p.get_uint8(), 0x02)
23 with self.assertRaises(dns.exception.FormError):
24 p.get_uint8()
25
26 def test_name(self):
27 # www.dnspython.org NS IN question
28 wire = b"\x03www\x09dnspython\x03org\x00\x00\x02\x00\x01"
29 expected = dns.name.from_text("www.dnspython.org")
30 p = dns.wire.Parser(wire)
31 self.assertEqual(p.get_name(), expected)
32 self.assertEqual(p.get_uint16(), 2)
33 self.assertEqual(p.get_uint16(), 1)
34 self.assertEqual(p.remaining(), 0)
35
36 def test_relativized_name(self):
37 # www.dnspython.org NS IN question
38 wire = b"\x03www\x09dnspython\x03org\x00\x00\x02\x00\x01"
39 origin = dns.name.from_text("dnspython.org")
40 expected = dns.name.from_text("www", None)
41 p = dns.wire.Parser(wire)
42 self.assertEqual(p.get_name(origin), expected)
43 self.assertEqual(p.remaining(), 4)
44
45 def test_compressed_name(self):
46 # www.dnspython.org NS IN question
47 wire = b"\x09dnspython\x03org\x00\x03www\xc0\x00"
48 expected1 = dns.name.from_text("dnspython.org")
49 expected2 = dns.name.from_text("www.dnspython.org")
50 p = dns.wire.Parser(wire)
51 self.assertEqual(p.get_name(), expected1)
52 self.assertEqual(p.get_name(), expected2)
53 self.assertEqual(p.remaining(), 0)
54 # verify the restore_furthest()
55 self.assertEqual(p.current, len(wire))
56
57 def test_seek(self):
58 wire = b"\x09dnspython\x03org\x00"
59 p = dns.wire.Parser(wire)
60 p.seek(10)
61 self.assertEqual(p.get_uint8(), 3)
62 # seeking to the end index is OK
63 p.seek(len(wire))
64 self.assertEqual(p.current, p.end)
65 with self.assertRaises(dns.exception.FormError):
66 # but reading there will not succeed
67 p.get_uint8()
68 with self.assertRaises(dns.exception.FormError):
69 p.seek(-1)
70 with self.assertRaises(dns.exception.FormError):
71 p.seek(len(wire) + 1)
72
73 def test_not_reading_everything_in_restriction(self):
74 wire = bytes.fromhex("0102010203040102")
75 p = dns.wire.Parser(wire)
76 with self.assertRaises(dns.exception.FormError):
77 with p.restrict_to(5):
78 v = p.get_uint8()
79 self.assertEqual(v, 1)
80 # don't read the other 4 bytes
81
82 def test_restriction_does_not_mask_exception(self):
83 wire = bytes.fromhex("0102010203040102")
84 p = dns.wire.Parser(wire)
85 with self.assertRaises(NotImplementedError):
86 with p.restrict_to(5):
87 raise NotImplementedError