Change all unittests to use twisted's trial.
authorCameron Dale <camrdale@gmail.com>
Fri, 21 Dec 2007 03:43:25 +0000 (19:43 -0800)
committerCameron Dale <camrdale@gmail.com>
Fri, 21 Dec 2007 03:43:25 +0000 (19:43 -0800)
Merge separate "test_*.py" files into their modules.

apt_dht_Khashmir/actions.py
apt_dht_Khashmir/khash.py
apt_dht_Khashmir/khashmir.py
apt_dht_Khashmir/krpc.py
apt_dht_Khashmir/ktable.py
apt_dht_Khashmir/node.py
apt_dht_Khashmir/test.py [deleted file]
apt_dht_Khashmir/test_khashmir.py [deleted file]
apt_dht_Khashmir/test_krpc.py [deleted file]

index dc743de..a3a6fc8 100644 (file)
@@ -260,7 +260,7 @@ class KeyExpirer:
     def __init__(self, store, config):
         self.store = store
         self.config = config
-        reactor.callLater(self.config['KEINITIAL_DELAY'], self.doExpire)
+        self.next_expire = reactor.callLater(self.config['KEINITIAL_DELAY'], self.doExpire)
     
     def doExpire(self):
         self.cut = "%0.6f" % (time() - self.config['KE_AGE'])
@@ -270,4 +270,4 @@ class KeyExpirer:
         c = self.store.cursor()
         s = "delete from kv where time < '%s';" % self.cut
         c.execute(s)
-        reactor.callLater(self.config['KE_DELAY'], self.doExpire)
+        self.next_expire = reactor.callLater(self.config['KE_DELAY'], self.doExpire)
index 1832edf..8db84d8 100644 (file)
@@ -4,6 +4,8 @@
 from sha import sha
 from os import urandom
 
+from twisted.trial import unittest
+
 def intify(hstr):
     """20 bit hash, big-endian -> long python integer"""
     assert len(hstr) == 20
@@ -39,17 +41,14 @@ def randRange(min, max):
 def newTID():
     return randRange(-2**30, 2**30)
 
-### Test Cases ###
-import unittest
-
-class NewID(unittest.TestCase):
+class TestNewID(unittest.TestCase):
     def testLength(self):
         self.assertEqual(len(newID()), 20)
     def testHundreds(self):
         for x in xrange(100):
             self.testLength
 
-class Intify(unittest.TestCase):
+class TestIntify(unittest.TestCase):
     known = [('\0' * 20, 0),
             ('\xff' * 20, 2L**160 - 1),
             ]
@@ -66,7 +65,7 @@ class Intify(unittest.TestCase):
         for x in xrange(100):
             self.testEndianessOnce()
 
-class Disantance(unittest.TestCase):
+class TestDisantance(unittest.TestCase):
     known = [
             (("\0" * 20, "\xff" * 20), 2**160L -1),
             ((sha("foo").digest(), sha("foo").digest()), 0),
@@ -80,7 +79,7 @@ class Disantance(unittest.TestCase):
             x, y, z = newID(), newID(), newID()
             self.assertEqual(distance(x,y) ^ distance(y, z), distance(x, z))
         
-class RandRange(unittest.TestCase):
+class TestRandRange(unittest.TestCase):
     def testOnce(self):
         a = intify(newID())
         b = intify(newID())
@@ -94,10 +93,3 @@ class RandRange(unittest.TestCase):
     def testOneHundredTimes(self):
         for i in xrange(100):
             self.testOnce()
-
-
-
-if __name__ == '__main__':
-    unittest.main()   
-
-    
index eaee998..b253c38 100644 (file)
@@ -3,12 +3,13 @@
 
 from time import time
 from random import randrange
+from sha import sha
 import os
 import sqlite  ## find this at http://pysqlite.sourceforge.net/
 
 from twisted.internet.defer import Deferred
-from twisted.internet import protocol
-from twisted.internet import reactor
+from twisted.internet import protocol, reactor
+from twisted.trial import unittest
 
 from ktable import KTable
 from knode import KNodeBase, KNodeRead, KNodeWrite, NULL_ID
@@ -28,19 +29,19 @@ class KhashmirBase(protocol.Factory):
         
     def setup(self, config, cache_dir):
         self.config = config
-        self._findDB(os.path.join(cache_dir, 'khashmir.db'))
         self.port = config['PORT']
+        self._findDB(os.path.join(cache_dir, 'khashmir.' + str(self.port) + '.db'))
         self.node = self._loadSelfNode('', self.port)
         self.table = KTable(self.node, config)
         #self.app = service.Application("krpc")
         self.udp = krpc.hostbroker(self)
         self.udp.protocol = krpc.KRPC
-        self.listenport = reactor.listenUDP(port, self.udp)
+        self.listenport = reactor.listenUDP(self.port, self.udp)
         self.last = time()
         self._loadRoutingTable()
-        KeyExpirer(self.store, config)
+        self.expirer = KeyExpirer(self.store, config)
         self.refreshTable(force=1)
-        reactor.callLater(60, self.checkpoint, (1,))
+        self.next_checkpoint = reactor.callLater(60, self.checkpoint, (1,))
 
     def Node(self):
         n = self._Node()
@@ -70,11 +71,12 @@ class KhashmirBase(protocol.Factory):
         self._dumpRoutingTable()
         self.refreshTable()
         if auto:
-            reactor.callLater(randrange(int(self.config['CHECKPOINT_INTERVAL'] * .9), 
+            self.next_checkpoint = reactor.callLater(randrange(int(self.config['CHECKPOINT_INTERVAL'] * .9), 
                                         int(self.config['CHECKPOINT_INTERVAL'] * 1.1)), 
                               self.checkpoint, (1,))
         
     def _findDB(self, db):
+        self.db = db
         try:
             os.stat(db)
         except OSError:
@@ -350,3 +352,175 @@ class KhashmirWrite(KhashmirRead):
 # the whole shebang, for testing
 class Khashmir(KhashmirWrite):
     _Node = KNodeWrite
+
+class SimpleTests(unittest.TestCase):
+    DHT_DEFAULTS = {'PORT': 9977, 'K': 8, 'HASH_LENGTH': 160,
+                    'CHECKPOINT_INTERVAL': 900, 'CONCURRENT_REQS': 4,
+                    'STORE_REDUNDANCY': 3, 'MAX_FAILURES': 3,
+                    'MIN_PING_INTERVAL': 900,'BUCKET_STALENESS': 3600,
+                    'KEINITIAL_DELAY': 15, 'KE_DELAY': 1200,
+                    'KE_AGE': 3600, }
+
+    def setUp(self):
+        d = self.DHT_DEFAULTS.copy()
+        d['PORT'] = 4044
+        self.a = Khashmir(d)
+        d = self.DHT_DEFAULTS.copy()
+        d['PORT'] = 4045
+        self.b = Khashmir(d)
+        
+    def tearDown(self):
+        self.a.listenport.stopListening()
+        self.b.listenport.stopListening()
+        try:
+            self.a.next_checkpoint.cancel()
+        except:
+            pass
+        try:
+            self.b.next_checkpoint.cancel()
+        except:
+            pass
+        try:
+            self.a.expirer.next_expire.cancel()
+        except:
+            pass
+        try:
+            self.b.expirer.next_expire.cancel()
+        except:
+            pass
+        self.a.store.close()
+        self.b.store.close()
+        os.unlink(self.a.db)
+        os.unlink(self.b.db)
+
+    def testAddContact(self):
+        self.assertEqual(len(self.a.table.buckets), 1)
+        self.assertEqual(len(self.a.table.buckets[0].l), 0)
+
+        self.assertEqual(len(self.b.table.buckets), 1)
+        self.assertEqual(len(self.b.table.buckets[0].l), 0)
+
+        self.a.addContact('127.0.0.1', 4045)
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+
+        self.assertEqual(len(self.a.table.buckets), 1)
+        self.assertEqual(len(self.a.table.buckets[0].l), 1)
+        self.assertEqual(len(self.b.table.buckets), 1)
+        self.assertEqual(len(self.b.table.buckets[0].l), 1)
+
+    def testStoreRetrieve(self):
+        self.a.addContact('127.0.0.1', 4045)
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        self.got = 0
+        self.a.storeValueForKey(sha('foo').digest(), 'foobar')
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        self.a.valueForKey(sha('foo').digest(), self._cb)
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+        reactor.iterate()
+
+    def _cb(self, val):
+        if not val:
+            self.assertEqual(self.got, 1)
+        elif 'foobar' in val:
+            self.got = 1
+
+
+class MultiTest(unittest.TestCase):
+    num = 20
+    DHT_DEFAULTS = {'PORT': 9977, 'K': 8, 'HASH_LENGTH': 160,
+                    'CHECKPOINT_INTERVAL': 900, 'CONCURRENT_REQS': 4,
+                    'STORE_REDUNDANCY': 3, 'MAX_FAILURES': 3,
+                    'MIN_PING_INTERVAL': 900,'BUCKET_STALENESS': 3600,
+                    'KEINITIAL_DELAY': 15, 'KE_DELAY': 1200,
+                    'KE_AGE': 3600, }
+
+    def _done(self, val):
+        self.done = 1
+        
+    def setUp(self):
+        self.l = []
+        self.startport = 4088
+        for i in range(self.num):
+            d = self.DHT_DEFAULTS.copy()
+            d['PORT'] = self.startport + i
+            self.l.append(Khashmir(d))
+        reactor.iterate()
+        reactor.iterate()
+        
+        for i in self.l:
+            i.addContact('127.0.0.1', self.l[randrange(0,self.num)].port)
+            i.addContact('127.0.0.1', self.l[randrange(0,self.num)].port)
+            i.addContact('127.0.0.1', self.l[randrange(0,self.num)].port)
+            reactor.iterate()
+            reactor.iterate()
+            reactor.iterate() 
+            
+        for i in self.l:
+            self.done = 0
+            i.findCloseNodes(self._done)
+            while not self.done:
+                reactor.iterate()
+        for i in self.l:
+            self.done = 0
+            i.findCloseNodes(self._done)
+            while not self.done:
+                reactor.iterate()
+
+    def tearDown(self):
+        for i in self.l:
+            i.listenport.stopListening()
+            try:
+                i.next_checkpoint.cancel()
+            except:
+                pass
+            try:
+                i.expirer.next_expire.cancel()
+            except:
+                pass
+            i.store.close()
+            os.unlink(i.db)
+            
+        reactor.iterate()
+        
+    def testStoreRetrieve(self):
+        for i in range(10):
+            K = newID()
+            V = newID()
+            
+            for a in range(3):
+                self.done = 0
+                def _scb(val):
+                    self.done = 1
+                self.l[randrange(0, self.num)].storeValueForKey(K, V, _scb)
+                while not self.done:
+                    reactor.iterate()
+
+
+                def _rcb(val):
+                    if not val:
+                        self.done = 1
+                        self.assertEqual(self.got, 1)
+                    elif V in val:
+                        self.got = 1
+                for x in range(3):
+                    self.got = 0
+                    self.done = 0
+                    self.l[randrange(0, self.num)].valueForKey(K, _rcb)
+                    while not self.done:
+                        reactor.iterate()
index 8a60092..1458fc2 100644 (file)
@@ -7,8 +7,8 @@ import sys
 from traceback import format_exception
 
 from twisted.internet.defer import Deferred
-from twisted.internet import protocol
-from twisted.internet import reactor
+from twisted.internet import protocol, reactor
+from twisted.trial import unittest
 
 KRPC_TIMEOUT = 20
 
@@ -153,7 +153,105 @@ class KRPC:
                 del(tids[id])
                 print ">>>>>> KRPC_ERROR_TIMEOUT"
                 df.errback(KRPC_ERROR_TIMEOUT)
-        reactor.callLater(KRPC_TIMEOUT, timeOut)
+        later = reactor.callLater(KRPC_TIMEOUT, timeOut)
+        def dropTimeOut(dict, later_call = later):
+            if later_call.active():
+                later_call.cancel()
+            return dict
+        d.addBoth(dropTimeOut)
         self.transport.write(str, self.addr)
         return d
  
+def connectionForAddr(host, port):
+    return host
+    
+class Receiver(protocol.Factory):
+    protocol = KRPC
+    def __init__(self):
+        self.buf = []
+    def krpc_store(self, msg, _krpc_sender):
+        self.buf += [msg]
+    def krpc_echo(self, msg, _krpc_sender):
+        return msg
+
+def make(port):
+    af = Receiver()
+    a = hostbroker(af)
+    a.protocol = KRPC
+    p = reactor.listenUDP(port, a)
+    return af, a, p
+    
+class KRPCTests(unittest.TestCase):
+    def setUp(self):
+        KRPC.noisy = 0
+        self.af, self.a, self.ap = make(1180)
+        self.bf, self.b, self.bp = make(1181)
+
+    def tearDown(self):
+        self.ap.stopListening()
+        self.bp.stopListening()
+
+    def bufEquals(self, result, value):
+        self.assertEqual(self.bf.buf, value)
+
+    def testSimpleMessage(self):
+        d = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
+        d.addCallback(self.bufEquals, ["This is a test."])
+        return d
+
+    def testMessageBlast(self):
+        for i in range(100):
+            d = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
+        d.addCallback(self.bufEquals, ["This is a test."] * 100)
+        return d
+
+    def testEcho(self):
+        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
+        df.addCallback(self.gotMsg, "This is a test.")
+        return df
+
+    def gotMsg(self, dict, should_be):
+        _krpc_sender = dict['_krpc_sender']
+        msg = dict['rsp']
+        self.assertEqual(msg, should_be)
+
+    def testManyEcho(self):
+        for i in xrange(100):
+            df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
+            df.addCallback(self.gotMsg, "This is a test.")
+        return df
+
+    def testMultiEcho(self):
+        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
+        df.addCallback(self.gotMsg, "This is a test.")
+
+        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
+        df.addCallback(self.gotMsg, "This is another test.")
+
+        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
+        df.addCallback(self.gotMsg, "This is yet another test.")
+        
+        return df
+
+    def testEchoReset(self):
+        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
+        df.addCallback(self.gotMsg, "This is a test.")
+
+        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
+        df.addCallback(self.gotMsg, "This is another test.")
+        df.addCallback(self.echoReset)
+        return df
+    
+    def echoReset(self, dict):
+        del(self.a.connections[('127.0.0.1', 1181)])
+        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
+        df.addCallback(self.gotMsg, "This is yet another test.")
+        return df
+
+    def testUnknownMeth(self):
+        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('blahblah', {'msg' : "This is a test."})
+        df.addErrback(self.gotErr, KRPC_ERROR_METHOD_UNKNOWN)
+        return df
+
+    def gotErr(self, err, should_be):
+        self.assertEqual(err.value, should_be)
index 6340513..c27d6c3 100644 (file)
@@ -4,6 +4,8 @@
 from time import time
 from bisect import bisect_left
 
+from twisted.trial import unittest
+
 import khash
 from node import Node, NULL_ID
 
@@ -47,11 +49,11 @@ class KTable:
             
         # don't have the node, get the K closest nodes
         nodes = nodes + self.buckets[i].l
-        if len(nodes) < K:
+        if len(nodes) < self.config['K']:
             # need more nodes
             min = i - 1
             max = i + 1
-            while len(nodes) < K and (min >= 0 or max < len(self.buckets)):
+            while len(nodes) < self.config['K'] and (min >= 0 or max < len(self.buckets)):
                 #ASw: note that this requires K be even
                 if min >= 0:
                     nodes = nodes + self.buckets[min].l
@@ -61,7 +63,7 @@ class KTable:
                 max = max + 1
     
         nodes.sort(lambda a, b, num=num: cmp(num ^ a.num, num ^ b.num))
-        return nodes[:K]
+        return nodes[:self.config['K']]
         
     def _splitBucket(self, a):
         diff = (a.max - a.min) / 2
@@ -206,14 +208,10 @@ class KBucket:
         if isinstance(a, Node): a = a.num
         return self.min >= a or self.max < a
 
-
-### UNIT TESTS ###
-import unittest
-
 class TestKTable(unittest.TestCase):
     def setUp(self):
         self.a = Node().init(khash.newID(), 'localhost', 2002)
-        self.t = KTable(self.a)
+        self.t = KTable(self.a, {'HASH_LENGTH': 160, 'K': 8, 'MAX_FAILURES': 3})
 
     def testAddNode(self):
         self.b = Node().init(khash.newID(), 'localhost', 2003)
@@ -228,14 +226,10 @@ class TestKTable(unittest.TestCase):
 
     def testFail(self):
         self.testAddNode()
-        for i in range(const.MAX_FAILURES - 1):
+        for i in range(self.t.config['MAX_FAILURES'] - 1):
             self.t.nodeFailed(self.b)
             self.assertEqual(len(self.t.buckets[0].l), 1)
             self.assertEqual(self.t.buckets[0].l[0], self.b)
             
         self.t.nodeFailed(self.b)
         self.assertEqual(len(self.t.buckets[0].l), 0)
-
-
-if __name__ == "__main__":
-    unittest.main()
index fda6fbe..dabe08c 100644 (file)
@@ -4,10 +4,12 @@
 from time import time
 from types import InstanceType
 
+from twisted.trial import unittest
+
 import khash
 
 # magic id to use before we know a peer's id
-NULL_ID = 20 * '\0',
+NULL_ID = 20 * '\0'
 
 class Node:
     """encapsulate contact info"""
@@ -73,8 +75,6 @@ class Node:
         return self.num != a
 
 
-import unittest
-
 class TestNode(unittest.TestCase):
     def setUp(self):
         self.node = Node().init(khash.newID(), 'localhost', 2002)
diff --git a/apt_dht_Khashmir/test.py b/apt_dht_Khashmir/test.py
deleted file mode 100644 (file)
index bd949fd..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
-# see LICENSE.txt for license information
-
-import unittest
-
-tests = unittest.defaultTestLoader.loadTestsFromNames(['khash', 'node', 'knode', 'actions',  'ktable', 'test_krpc'])
-result = unittest.TextTestRunner().run(tests)
diff --git a/apt_dht_Khashmir/test_khashmir.py b/apt_dht_Khashmir/test_khashmir.py
deleted file mode 100644 (file)
index 24a8760..0000000
+++ /dev/null
@@ -1,145 +0,0 @@
-from unittest import defaultTestLoader, TextTestRunner, TestCase
-from sha import sha
-from random import randrange
-import os, sys
-
-from twisted.internet import reactor
-
-from khashmir import Khashmir
-from khash import newID
-
-if __name__ =="__main__":
-    tests = defaultTestLoader.loadTestsFromNames([sys.argv[0][:-3]])
-    result = TextTestRunner().run(tests)
-
-class SimpleTests(TestCase):
-    def setUp(self):
-        self.a = Khashmir('127.0.0.1', 4044, '/tmp/a.test')
-        self.b = Khashmir('127.0.0.1', 4045, '/tmp/b.test')
-        
-    def tearDown(self):
-        self.a.listenport.stopListening()
-        self.b.listenport.stopListening()
-        os.unlink('/tmp/a.test')
-        os.unlink('/tmp/b.test')                
-        reactor.iterate()
-        reactor.iterate()
-
-    def addContacts(self):
-        self.a.addContact('127.0.0.1', 4045)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-
-    def testAddContact(self):
-        self.assertEqual(len(self.a.table.buckets), 1) 
-        self.assertEqual(len(self.a.table.buckets[0].l), 0)
-
-        self.assertEqual(len(self.b.table.buckets), 1) 
-        self.assertEqual(len(self.b.table.buckets[0].l), 0)
-
-        self.addContacts()
-
-        self.assertEqual(len(self.a.table.buckets), 1) 
-        self.assertEqual(len(self.a.table.buckets[0].l), 1)
-        self.assertEqual(len(self.b.table.buckets), 1) 
-        self.assertEqual(len(self.b.table.buckets[0].l), 1)
-
-    def testStoreRetrieve(self):
-        self.addContacts()
-        self.got = 0
-        self.a.storeValueForKey(sha('foo').digest(), 'foobar')
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.a.valueForKey(sha('foo').digest(), self._cb)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-
-    def _cb(self, val):
-        if not val:
-            self.assertEqual(self.got, 1)
-        elif 'foobar' in val:
-            self.got = 1
-
-
-class MultiTest(TestCase):
-    num = 20
-    def _done(self, val):
-        self.done = 1
-        
-    def setUp(self):
-        self.l = []
-        self.startport = 4088
-        for i in range(self.num):
-            self.l.append(Khashmir('127.0.0.1', self.startport + i, '/tmp/%s.test' % (self.startport + i)))
-        reactor.iterate()
-        reactor.iterate()
-        
-        for i in self.l:
-            i.addContact('127.0.0.1', self.l[randrange(0,self.num)].port)
-            i.addContact('127.0.0.1', self.l[randrange(0,self.num)].port)
-            i.addContact('127.0.0.1', self.l[randrange(0,self.num)].port)
-            reactor.iterate()
-            reactor.iterate()
-            reactor.iterate() 
-            
-        for i in self.l:
-            self.done = 0
-            i.findCloseNodes(self._done)
-            while not self.done:
-                reactor.iterate()
-        for i in self.l:
-            self.done = 0
-            i.findCloseNodes(self._done)
-            while not self.done:
-                reactor.iterate()
-
-    def tearDown(self):
-        for i in self.l:
-            i.listenport.stopListening()
-        for i in range(self.startport, self.startport+self.num):
-            os.unlink('/tmp/%s.test' % i)
-            
-        reactor.iterate()
-        
-    def testStoreRetrieve(self):
-        for i in range(10):
-            K = newID()
-            V = newID()
-            
-            for a in range(3):
-                self.done = 0
-                def _scb(val):
-                    self.done = 1
-                self.l[randrange(0, self.num)].storeValueForKey(K, V, _scb)
-                while not self.done:
-                    reactor.iterate()
-
-
-                def _rcb(val):
-                    if not val:
-                        self.done = 1
-                        self.assertEqual(self.got, 1)
-                    elif V in val:
-                        self.got = 1
-                for x in range(3):
-                    self.got = 0
-                    self.done = 0
-                    self.l[randrange(0, self.num)].valueForKey(K, _rcb)
-                    while not self.done:
-                        reactor.iterate()
-
-
-            
-            
-            
diff --git a/apt_dht_Khashmir/test_krpc.py b/apt_dht_Khashmir/test_krpc.py
deleted file mode 100644 (file)
index 3c41d07..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
-# see LICENSE.txt for license information
-
-from unittest import defaultTestLoader, TestCase, TextTestRunner
-import sys
-
-from twisted.internet import protocol
-from twisted.internet import reactor
-
-from krpc import KRPC, hostbroker, KRPC_ERROR_METHOD_UNKNOWN
-
-KRPC.noisy = 0
-
-if __name__ =="__main__":
-    tests = defaultTestLoader.loadTestsFromNames([sys.argv[0][:-3]])
-    result = TextTestRunner().run(tests)
-
-
-def connectionForAddr(host, port):
-    return host
-    
-
-class Receiver(protocol.Factory):
-    protocol = KRPC
-    def __init__(self):
-        self.buf = []
-    def krpc_store(self, msg, _krpc_sender):
-        self.buf += [msg]
-    def krpc_echo(self, msg, _krpc_sender):
-        return msg
-
-def make(port):
-    af = Receiver()
-    a = hostbroker(af)
-    a.protocol = KRPC
-    p = reactor.listenUDP(port, a)
-    return af, a, p
-    
-class KRPCTests(TestCase):
-    def setUp(self):
-        self.noisy = 0
-        self.af, self.a, self.ap = make(1180)
-        self.bf, self.b, self.bp = make(1181)
-
-    def tearDown(self):
-        self.ap.stopListening()
-        self.bp.stopListening()
-        reactor.iterate()
-        reactor.iterate()
-
-    def testSimpleMessage(self):
-        self.noisy = 0
-        self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.bf.buf, ["This is a test."])
-
-    def testMessageBlast(self):
-        self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.bf.buf, ["This is a test."])
-        self.bf.buf = []
-        
-        for i in range(100):
-            self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
-            reactor.iterate()
-            #self.bf.buf = []
-        self.assertEqual(self.bf.buf, ["This is a test."] * 100)
-
-    def testEcho(self):
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
-        df.addCallback(self.gotMsg)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.msg, "This is a test.")
-
-    def gotMsg(self, dict):
-        _krpc_sender = dict['_krpc_sender']
-        msg = dict['rsp']
-        self.msg = msg
-
-    def testManyEcho(self):
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
-        df.addCallback(self.gotMsg)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.msg, "This is a test.")
-        for i in xrange(100):
-            self.msg = None
-            df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
-            df.addCallback(self.gotMsg)
-            reactor.iterate()
-            reactor.iterate()
-            reactor.iterate()
-            reactor.iterate()
-            self.assertEqual(self.msg, "This is a test.")
-
-    def testMultiEcho(self):
-        self.noisy = 1
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
-        df.addCallback(self.gotMsg)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.msg, "This is a test.")
-
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
-        df.addCallback(self.gotMsg)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.msg, "This is another test.")
-
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
-        df.addCallback(self.gotMsg)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.msg, "This is yet another test.")
-
-    def testEchoReset(self):
-        self.noisy = 1
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
-        df.addCallback(self.gotMsg)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.msg, "This is a test.")
-
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
-        df.addCallback(self.gotMsg)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.msg, "This is another test.")
-
-        del(self.a.connections[('127.0.0.1', 1181)])
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
-        df.addCallback(self.gotMsg)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.msg, "This is yet another test.")
-
-    def testLotsofEchoReset(self):
-        for i in range(100):
-            self.testEchoReset()
-            
-    def testUnknownMeth(self):
-        self.noisy = 1
-        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('blahblah', {'msg' : "This is a test."})
-        df.addErrback(self.gotErr)
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        reactor.iterate()
-        self.assertEqual(self.err, KRPC_ERROR_METHOD_UNKNOWN)
-
-    def gotErr(self, err):
-        self.err = err.value
-        
\ No newline at end of file