add some default bogus values in __init__
[quix0rs-apt-p2p.git] / node.py
1 import hash
2 import time
3 from types import *
4 from xmlrpclib import Binary
5
6 class Node:
7     """encapsulate contact info"""
8     
9     def __init__(self):
10         self.fails = 0
11         self.lastSeen = 0
12         self.id = self.host = self.port = ''
13         
14     def init(self, id, host, port):
15         self.id = id
16         self.int = hash.intify(id)
17         self.host = host
18         self.port = port
19         self._senderDict = {'id': Binary(self.id), 'port' : self.port, 'host' : self.host}
20         return self
21         
22     def initWithDict(self, dict):
23         self._senderDict = dict
24         self.id = dict['id'].data
25         self.int = hash.intify(self.id)
26         self.port = dict['port']
27         self.host = dict['host']
28         return self
29         
30     def updateLastSeen(self):
31         self.lastSeen = time.time()
32         self.fails = 0
33         
34     def msgFailed(self):
35         self.fails = self.fails + 1
36         return self.fails
37         
38     def senderDict(self):
39         return self._senderDict
40         
41     def __repr__(self):
42         return `(self.id, self.host, self.port)`
43         
44     ## these comparators let us bisect/index a list full of nodes with either a node or an int/long
45     def __lt__(self, a):
46         if type(a) == InstanceType:
47             a = a.int
48         return self.int < a
49     def __le__(self, a):
50         if type(a) == InstanceType:
51             a = a.int
52         return self.int <= a
53     def __gt__(self, a):
54         if type(a) == InstanceType:
55             a = a.int
56         return self.int > a
57     def __ge__(self, a):
58         if type(a) == InstanceType:
59             a = a.int
60         return self.int >= a
61     def __eq__(self, a):
62         if type(a) == InstanceType:
63             a = a.int
64         return self.int == a
65     def __ne__(self, a):
66         if type(a) == InstanceType:
67             a = a.int
68         return self.int != a
69
70
71 import unittest
72
73 class TestNode(unittest.TestCase):
74     def setUp(self):
75         self.node = Node().init(hash.newID(), 'localhost', 2002)
76     def testUpdateLastSeen(self):
77         t = self.node.lastSeen
78         self.node.updateLastSeen()
79         assert t < self.node.lastSeen
80