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