1
# Copyright (C) 2004 Anthony Baxter
2
"""Tests for shtoom.upnp
5
# This is more a functional test than a unit test. oh well.
7
from twisted.trial import unittest
8
from twisted.trial import util
9
from twisted.internet import reactor, defer
10
from twisted.internet.protocol import Protocol, Factory, DatagramProtocol
15
from shtoom.upnp import getUPnP
19
util.wait(d, timeout=8)
21
raise unittest.SkipTest('no UPnP available')
25
def discovered(self, prot):
26
#print "upnp discovery done,", prot
28
return self.prot.getExternalIPAddress()
30
def gotexternal(self, res):
31
#print "upnp external address,",res
32
return self.prot.getPortMappings()
34
def gotmappings(self, res):
35
#print "upnp mappings:", res
36
return self.prot.addPortMapping(12367,12367,'test mapping')
39
#print "upnp port mapping added"
40
return self.prot.getPortMappings()
42
def gotmappings2(self, res):
43
#print "upnp mappings:", res
44
return self.prot.deletePortMapping(12367)
46
def deleted(self, res):
47
#print "upnp port mapping removed"
48
return self.prot.getPortMappings()
50
def gotmappings3(self, res):
51
#print "upnp mappings:", res
52
return self.prot.getExternalIPAddress()
54
def gotexternal2(self, res):
55
#print "upnp external address,",res
59
from shtoom.upnp import getUPnP
61
d.addCallback(self.discovered)
62
d.addCallback(self.gotexternal)
63
d.addCallback(self.gotmappings)
64
d.addCallback(self.added)
65
d.addCallback(self.gotmappings2)
66
d.addCallback(self.deleted)
67
d.addCallback(self.gotmappings3)
68
d.addCallback(self.gotexternal2)
78
def __init__(self, mapper, port):
84
d = self.mapper.map(self.port)
85
d.addCallback(lambda x: self.cb_mapped(x, cd))
87
def cb_mapped(self, ext, cd):
90
self.info_res = self.mapper.info(self.port)
91
d = self.mapper.unmap(self.port)
92
d.addCallback(lambda x: self.cb_unmapped(x, cd))
93
def cb_unmapped(self, res, cd):
98
class UPnPTest(unittest.TestCase):
105
util.wait(d, timeout=32)
107
def test_upnp_mapper(self):
108
from shtoom.upnp import UPnPMapper
109
ae = self.assertEquals
110
ar = self.assertRaises
112
mapper = UPnPMapper()
113
uprot = DatagramProtocol()
114
uport = reactor.listenUDP(random.randint(10000,20000), uprot)
115
class tfactory(Factory):
117
tport = reactor.listenTCP(0, tfactory())
118
for port in uport, tport:
119
ar(ValueError, mapper.unmap, port)
120
ar(ValueError, mapper.info, port)
121
t = TestMapper(mapper, port)
123
util.wait(d, timeout=16)
124
ae(len(t.map_res), 2)
125
ae(t.map_res, t.info_res)
126
ae(t.unmap_res, None)
127
# Can't unmap a port that's not mapped
128
ar(ValueError, mapper.unmap, port)
129
d = port.stopListening()
131
# Can't map a closed port
132
ar(ValueError, mapper.map, port)
133
# Can't get info on a closed port
134
ar(ValueError, mapper.info, port)