Skip to content

Commit

Permalink
Create and test a Contact class for the DHT.
Browse files Browse the repository at this point in the history
  • Loading branch information
Renelvon committed May 17, 2015
1 parent 6095b95 commit b6adf2c
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 0 deletions.
Empty file added dht/__init__.py
Empty file.
35 changes: 35 additions & 0 deletions dht/contact.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import collections


class Contact(collections.Hashable):
"""
A node in the DHT.
Contains all information specified by the Kademlia protocol
(aka: IP, PORT, GUID).
"""
def __init__(self, ip, port, guid):
"""
Make a new Contact.
Args:
ip: The IP of the Contact as a string or unicode. It may
be an IPv4 or an IPv6.
port: The port of the Contact as an integer
guid: The unique ID of the Contact as a hex string of
proper length (see constants module)
"""
self.ip = ip
self.port = port
self.guid = guid

def __eq__(self, other):
if isinstance(other, self.__class__):
return self.guid == other.guid
return NotImplemented

def __hash__(self):
return hash(self.guid)

def __repr__(self):
return 'Contact({0}, {1}, {2})'.format(self.ip, self.port, self.guid)
Empty file added tests/dht/__init__.py
Empty file.
56 changes: 56 additions & 0 deletions tests/dht/test_contact.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import unittest

from dht import contact


class TestContact(unittest.TestCase):
"""
Test the API of dht.contact.
"""
@classmethod
def setUpClass(cls):
cls.guid1 = '1' * 40
cls.guid2 = 'f' * 40
cls.ipv4 = '123.45.67.89'
cls.ipv6 = '2001:db8:85a3::8a2e:370:7334'
cls.port1 = 12345
cls.port2 = 12346

def _test_init_scenario(self, ip, port, guid):
contact1 = contact.Contact(ip, port, guid)
self.assertEqual(contact1.ip, ip)
self.assertEqual(contact1.port, port)
self.assertEqual(contact1.guid, guid)

def test_init_classic(self):
self._test_init_scenario(self.ipv4, self.port1, self.guid1)

def test_init_unicode(self):
self._test_init_scenario(self.ipv4, self.port1, unicode(self.guid1))

def test_init_ipv6(self):
self._test_init_scenario(self.ipv6, self.port1, self.guid1)

def test_eq_hash(self):
c1 = contact.Contact(self.ipv4, self.port1, self.guid1)
c2 = contact.Contact(self.ipv6, self.port2, self.guid1)
self.assertIsNot(c1, c2)
self.assertEqual(c1, c2)
self.assertEqual(hash(c1), hash(c2))

def test_uneq(self):
c1 = contact.Contact(self.ipv4, self.port1, self.guid1)
c2 = contact.Contact(self.ipv4, self.port1, self.guid2)
self.assertNotEqual(c1, c2)

def test_repr(self):
c1 = contact.Contact(self.ipv4, self.port1, self.guid1)
cr = repr(c1)
self.assertEqual(
cr,
'Contact({0}, {1}, {2})'.format(self.ipv4, self.port1, self.guid1)
)


if __name__ == "__main__":
unittest.main()

0 comments on commit b6adf2c

Please sign in to comment.