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