Skip to content

Commit

Permalink
Merge pull request #24 from markcottrell/master
Browse files Browse the repository at this point in the history
IpAddressAdapter python 2.x fix
  • Loading branch information
tomerfiliba committed May 25, 2013
2 parents 2644672 + 966723e commit 54f9c6b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
10 changes: 9 additions & 1 deletion construct/protocols/layer3/ipv4.py
Expand Up @@ -5,10 +5,18 @@
import six
from binascii import unhexlify

try:
bytes
except NameError:
bytes = str


class IpAddressAdapter(Adapter):
def _encode(self, obj, context):
return bytes(int(b) for b in obj.split("."))
if bytes is str:
return "".join(chr(int(b)) for b in obj.split("."))
else:
return bytes(int(b) for b in obj.split("."))
def _decode(self, obj, context):
if bytes is str:
return ".".join(str(ord(b)) for b in obj)
Expand Down
21 changes: 21 additions & 0 deletions tests/test_adaptors.py
Expand Up @@ -3,6 +3,7 @@
from construct import Field, UBInt8
from construct import OneOf, NoneOf, HexDumpAdapter
from construct import ValidationError
from construct.protocols.layer3.ipv4 import IpAddress
import six

class TestHexDumpAdapter(unittest.TestCase):
Expand Down Expand Up @@ -61,3 +62,23 @@ def test_build(self):

def test_build_invalid(self):
self.assertRaises(ValidationError, self.o.build, 9)


class TestIpAddress(unittest.TestCase):

def setUp(self):
self.ipa = IpAddress("foo")

def test_trivial(self):
pass

def test_parse(self):
self.assertEqual(self.ipa.parse(six.b("\x7f\x80\x81\x82")),
"127.128.129.130")

def test_build(self):
self.assertEqual(self.ipa.build("127.1.2.3"),
six.b("\x7f\x01\x02\x03"))

def test_build_invalid(self):
self.assertRaises(ValueError, self.ipa.build, "300.1.2.3")

0 comments on commit 54f9c6b

Please sign in to comment.