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