[Pkg-privacy-commits] [txtorcon] 50/96: pep8, The Great Whitespacing
Jérémy Bobbio
lunar at moszumanska.debian.org
Sun Sep 6 18:33:39 UTC 2015
This is an automated email from the git hooks/post-receive script.
lunar pushed a commit to branch master
in repository txtorcon.
commit 819f2a2614a15edc87c40d85326b6f8fb5fd9a25
Author: meejah <meejah at meejah.ca>
Date: Thu Feb 5 17:12:05 2015 -0700
pep8, The Great Whitespacing
---
Makefile | 2 +-
examples/disallow_streams_by_port.py | 4 +-
examples/dump_config.py | 4 +-
examples/launch_tor.py | 4 +-
examples/launch_tor_endpoint.py | 19 +-
examples/launch_tor_endpoint2.py | 13 +-
examples/launch_tor_with_hiddenservice.py | 64 ++++---
examples/monitor.py | 6 +-
examples/schedule_bandwidth.py | 6 +-
examples/stream_circuit_logger.py | 27 +--
examples/tor_info.py | 34 ++--
examples/webui_server.py | 30 ++--
test/test_addrmap.py | 42 ++---
test/test_circuit.py | 55 ++++--
test/test_endpoints.py | 99 ++++++++---
test/test_router.py | 36 +++-
test/test_stream.py | 94 ++++++----
test/test_torconfig.py | 282 +++++++++++++++++++++++-------
test/test_torcontrolprotocol.py | 146 +++++++++++-----
test/test_torinfo.py | 40 +++--
test/test_torstate.py | 158 +++++++++++------
test/test_util.py | 26 ++-
test/test_util_imports.py | 1 -
test/util.py | 4 +-
txtorcon/__init__.py | 26 ++-
txtorcon/addrmap.py | 6 +-
txtorcon/circuit.py | 22 +--
txtorcon/endpoints.py | 5 +-
txtorcon/interface.py | 8 +-
txtorcon/spaghetti.py | 9 +-
txtorcon/stream.py | 29 +--
txtorcon/torconfig.py | 77 ++++----
txtorcon/torcontrolprotocol.py | 150 ++++++++++------
txtorcon/torinfo.py | 78 +++++----
txtorcon/torstate.py | 154 +++++++++-------
txtorcon/util.py | 19 +-
36 files changed, 1146 insertions(+), 633 deletions(-)
diff --git a/Makefile b/Makefile
index 40c7001..4f3ae80 100644
--- a/Makefile
+++ b/Makefile
@@ -46,7 +46,7 @@ coverage-debian:
python-coverage report
pep8: txtorcon/*.py test/*.py examples/*.py
- pep8 --ignore=E501,E265 $^
+ pep8 --ignore=E501 $^
pep8count:
pep8 --ignore=E501,E265 $^ | wc -l
diff --git a/examples/disallow_streams_by_port.py b/examples/disallow_streams_by_port.py
index e6e2d0e..7766c5c 100755
--- a/examples/disallow_streams_by_port.py
+++ b/examples/disallow_streams_by_port.py
@@ -36,7 +36,9 @@ class PortFilterAttacher:
"""
if stream.target_port in self.disallow_ports:
print "Disallowing", stream, "to port", stream.target_port
- self.state.close_stream(stream).addCallback(stream_closed).addErrback(log.err)
+ d = self.state.close_stream(stream)
+ d.addCallback(stream_closed)
+ d.addErrback(log.err)
return txtorcon.TorState.DO_NOT_ATTACH
# Ask Tor to assign stream to a circuit by itself
diff --git a/examples/dump_config.py b/examples/dump_config.py
index 034b224..4810011 100755
--- a/examples/dump_config.py
+++ b/examples/dump_config.py
@@ -1,8 +1,6 @@
#!/usr/bin/env python
-##
-## Simple usage example of TorConfig
-##
+# Simple usage example of TorConfig
import sys
import types
diff --git a/examples/launch_tor.py b/examples/launch_tor.py
index 6bd8288..489bc6b 100755
--- a/examples/launch_tor.py
+++ b/examples/launch_tor.py
@@ -1,8 +1,6 @@
#!/usr/bin/env python
-##
-## Launch a slave Tor by first making a TorConfig object.
-##
+# Launch a slave Tor by first making a TorConfig object.
import functools
from twisted.internet import reactor
diff --git a/examples/launch_tor_endpoint.py b/examples/launch_tor_endpoint.py
index e0f1151..abdc881 100755
--- a/examples/launch_tor_endpoint.py
+++ b/examples/launch_tor_endpoint.py
@@ -1,11 +1,9 @@
#!/usr/bin/env python
-##
-## Here we set up a Twisted Web server and then launch a slave tor
-## with a configured hidden service directed at the Web server we set
-## up. This uses serverFromString to translate the "onion" endpoint descriptor
-## into a TCPHiddenServiceEndpoint object...
-##
+# Here we set up a Twisted Web server and then launch a slave tor
+# with a configured hidden service directed at the Web server we set
+# up. This uses serverFromString to translate the "onion" endpoint descriptor
+# into a TCPHiddenServiceEndpoint object...
from twisted.internet import reactor
from twisted.web import server, resource
@@ -51,14 +49,17 @@ def progress(percent, tag, message):
# several ways to proceed here and what they mean:
#
# ep0:
-# launch a new Tor instance, configure a hidden service on some port and pubish descriptor for port 80
+# launch a new Tor instance, configure a hidden service on some
+# port and pubish descriptor for port 80
# ep1:
# connect to existing Tor via control-port 9051, configure a hidden
# service listening locally on 8080, publish a descriptor for port
# 80 and use an explicit hiddenServiceDir (where "hostname" and
-# "private_key" files are put by Tor). We set SOCKS port explicitly, too.
+# "private_key" files are put by Tor). We set SOCKS port
+# explicitly, too.
# ep2:
-# all the same as ep1, except we launch a new Tor (because no "controlPort=9051")
+# all the same as ep1, except we launch a new Tor (because no
+# "controlPort=9051")
#
ep0 = "onion:80"
diff --git a/examples/launch_tor_endpoint2.py b/examples/launch_tor_endpoint2.py
index 8951d16..1adc178 100755
--- a/examples/launch_tor_endpoint2.py
+++ b/examples/launch_tor_endpoint2.py
@@ -1,11 +1,9 @@
#!/usr/bin/env python
-##
-## Here we set up a Twisted Web server and then launch a slave tor
-## with a configured hidden service directed at the Web server we set
-## up. This uses serverFromString to translate the "onion" endpoint descriptor
-## into a TCPHiddenServiceEndpoint object...
-##
+# Here we set up a Twisted Web server and then launch a slave tor
+# with a configured hidden service directed at the Web server we set
+# up. This uses serverFromString to translate the "onion" endpoint descriptor
+# into a TCPHiddenServiceEndpoint object...
import shutil
@@ -30,8 +28,9 @@ def setup_failed(arg):
def setup_complete(port):
+ local = txtorcon.IHiddenService(port).local_address.getHost()
print "Hidden serivce:", port.getHost()
- print " locally at:", txtorcon.IHiddenService(port).local_address.getHost()
+ print " locally at:", local
def progress(percent, tag, message):
diff --git a/examples/launch_tor_with_hiddenservice.py b/examples/launch_tor_with_hiddenservice.py
index 56a3315..c50e073 100755
--- a/examples/launch_tor_with_hiddenservice.py
+++ b/examples/launch_tor_with_hiddenservice.py
@@ -1,10 +1,8 @@
#!/usr/bin/env python
-##
-## Here we set up a Twisted Web server and then launch a slave tor
-## with a configured hidden service directed at the Web server we set
-## up.
-##
+# Here we set up a Twisted Web server and then launch a slave tor
+# with a configured hidden service directed at the Web server we set
+# up.
import tempfile
import functools
@@ -48,38 +46,48 @@ hs_port = 9876
hs_public_port = 80
hs_temp = tempfile.mkdtemp(prefix='torhiddenservice')
-## register something to clean up our tempdir
-reactor.addSystemEventTrigger('before', 'shutdown',
- functools.partial(txtorcon.util.delete_file_or_tree,
- hs_temp))
-
-## configure the hidden service we want.
-## obviously, we'd want a more-persistent place to keep the hidden
-## service directory for a "real" setup. If the directory is empty at
-## startup as here, Tor creates new keys etcetera (which IS the .onion
-## address). That is, every time you run this script you get a new
-## hidden service URI, which is probably not what you want.
-## The launch_tor method adds other needed config directives to give
-## us a minimal config.
+# register something to clean up our tempdir
+reactor.addSystemEventTrigger(
+ 'before', 'shutdown',
+ functools.partial(
+ txtorcon.util.delete_file_or_tree,
+ hs_temp
+ )
+)
+
+# configure the hidden service we want.
+# obviously, we'd want a more-persistent place to keep the hidden
+# service directory for a "real" setup. If the directory is empty at
+# startup as here, Tor creates new keys etcetera (which IS the .onion
+# address). That is, every time you run this script you get a new
+# hidden service URI, which is probably not what you want.
+# The launch_tor method adds other needed config directives to give
+# us a minimal config.
config = txtorcon.TorConfig()
config.SOCKSPort = 0
config.ORPort = 9089
-config.HiddenServices = [txtorcon.HiddenService(config, hs_temp, [str(hs_public_port) + " 127.0.0.1:" + str(hs_port)])]
+config.HiddenServices = [
+ txtorcon.HiddenService(
+ config,
+ hs_temp,
+ ["%d 127.0.0.1:%d" % (hs_public_port, hs_port)]
+ )
+]
config.save()
-## next we set up our service to listen on hs_port which is forwarded
-## (via the HiddenService options) from the hidden service address on
-## port hs_public_port
+# next we set up our service to listen on hs_port which is forwarded
+# (via the HiddenService options) from the hidden service address on
+# port hs_public_port
site = server.Site(Simple())
hs_endpoint = TCP4ServerEndpoint(reactor, hs_port, interface='127.0.0.1')
hs_endpoint.listen(site)
-## we've got our Twisted service listening locally and our options
-## ready to go, so we now launch Tor. Once it's done (see above
-## callbacks) we print out the .onion URI and then do "nothing"
-## (i.e. let the Web server do its thing). Note that the way we've set
-## up the slave Tor process, when we close the connection to it tor
-## will exit.
+# we've got our Twisted service listening locally and our options
+# ready to go, so we now launch Tor. Once it's done (see above
+# callbacks) we print out the .onion URI and then do "nothing"
+# (i.e. let the Web server do its thing). Note that the way we've set
+# up the slave Tor process, when we close the connection to it tor
+# will exit.
d = txtorcon.launch_tor(config, reactor, progress_updates=updates)
d.addCallback(functools.partial(setup_complete, config))
diff --git a/examples/monitor.py b/examples/monitor.py
index e4af689..1ce8034 100755
--- a/examples/monitor.py
+++ b/examples/monitor.py
@@ -1,9 +1,7 @@
#!/usr/bin/env python
-##
-## Just listens for a few EVENTs from Tor (INFO NOTICE WARN ERR) and
-## prints out the contents, so functions like a log monitor.
-##
+# Just listens for a few EVENTs from Tor (INFO NOTICE WARN ERR) and
+# prints out the contents, so functions like a log monitor.
from twisted.internet import reactor
import txtorcon
diff --git a/examples/schedule_bandwidth.py b/examples/schedule_bandwidth.py
index 98edc45..acd6e23 100755
--- a/examples/schedule_bandwidth.py
+++ b/examples/schedule_bandwidth.py
@@ -1,9 +1,7 @@
#!/usr/bin/env python
-##
-## Here, we do something possible-useful and schedule changes to the
-## "BandWidthRate" and optionally "BandWidthBurst" settings in Tor.
-##
+# Here, we do something possible-useful and schedule changes to the
+# "BandWidthRate" and optionally "BandWidthBurst" settings in Tor.
import datetime
from twisted.internet import reactor
diff --git a/examples/stream_circuit_logger.py b/examples/stream_circuit_logger.py
index d9fc008..381edff 100755
--- a/examples/stream_circuit_logger.py
+++ b/examples/stream_circuit_logger.py
@@ -1,9 +1,7 @@
#!/usr/bin/env python
-##
-## This uses an IStreamListener and an ICircuitListener to log all
-## built circuits and all streams that succeed.
-##
+# This uses an IStreamListener and an ICircuitListener to log all
+# built circuits and all streams that succeed.
import sys
from twisted.python import log
@@ -13,14 +11,20 @@ import txtorcon
def logCircuit(circuit):
path = '->'.join(map(lambda x: str(x.location.countrycode), circuit.path))
- log.msg('Circuit %d (%s) is %s for purpose "%s"' % (circuit.id, path, circuit.state, circuit.purpose))
+ log.msg('Circuit %d (%s) is %s for purpose "%s"' %
+ (circuit.id, path, circuit.state, circuit.purpose))
def logStream(stream, state):
circ = ''
if stream.circuit:
- circ = ' via circuit %d (%s)' % (stream.circuit.id, '->'.join(map(lambda x: x.location.countrycode, stream.circuit.path)))
- proc = txtorcon.util.process_from_address(stream.source_addr, stream.source_port, state)
+ path = '->'.join(map(lambda x: x.location.countrycode, stream.circuit.path))
+ circ = ' via circuit %d (%s)' % (stream.circuit.id, path)
+ proc = txtorcon.util.process_from_address(
+ stream.source_addr,
+ stream.source_port,
+ state
+ )
if proc:
proc = ' from process "%s"' % (proc, )
@@ -28,11 +32,14 @@ def logStream(stream, state):
proc = ' for Tor internal use'
else:
- proc = ' from remote "%s:%s"' % (str(stream.source_addr), str(stream.source_port))
- log.msg('Stream %d to %s:%d attached%s%s' % (stream.id, stream.target_host, stream.target_port, circ, proc))
+ proc = ' from remote "%s:%s"' % (str(stream.source_addr),
+ str(stream.source_port))
+ log.msg('Stream %d to %s:%d attached%s%s' %
+ (stream.id, stream.target_host, stream.target_port, circ, proc))
-class StreamCircuitLogger(txtorcon.StreamListenerMixin, txtorcon.CircuitListenerMixin):
+class StreamCircuitLogger(txtorcon.StreamListenerMixin,
+ txtorcon.CircuitListenerMixin):
def __init__(self, state):
self.state = state
diff --git a/examples/tor_info.py b/examples/tor_info.py
index c521926..9cd9e08 100755
--- a/examples/tor_info.py
+++ b/examples/tor_info.py
@@ -1,21 +1,19 @@
#!/usr/bin/env python
-##
-## Simple usage example of TorInfo. This class does some magic so that
-## once it's set up, all the attributes it has (or appears to) are
-## GETINFO ones, in a heirarchy. So where GETINFO specifies
-## "net/listeners/dns" TorInfo will have a "net" attribute that
-## contains at least "listeners", etcetera. The leaves are all methods
-## which return a Deferred. If the corresponding GETINFO takes an
-## argument, so does the leaf.
-##
-## Go straight to "setup_complete" for the goods -- this is called
-## after TorInfo and the underlying TorControlProtocol are set up.
-##
-## If you want to issue multiple GETINFO calls in one network
-## transaction, you'll have to use TorControlProtocol's get_info
-## instead.
-##
+# Simple usage example of TorInfo. This class does some magic so that
+# once it's set up, all the attributes it has (or appears to) are
+# GETINFO ones, in a heirarchy. So where GETINFO specifies
+# "net/listeners/dns" TorInfo will have a "net" attribute that
+# contains at least "listeners", etcetera. The leaves are all methods
+# which return a Deferred. If the corresponding GETINFO takes an
+# argument, so does the leaf.
+#
+# Go straight to "setup_complete" for the goods -- this is called
+# after TorInfo and the underlying TorControlProtocol are set up.
+#
+# If you want to issue multiple GETINFO calls in one network
+# transaction, you'll have to use TorControlProtocol's get_info
+# instead.
import sys
from twisted.internet import reactor, defer
@@ -54,7 +52,7 @@ def setup_complete(info):
print "Top-Level Things:", dir(info)
if True:
- ## some examples of getting specific GETINFO callbacks
+ # some examples of getting specific GETINFO callbacks
v = yield info.version()
ip = yield info.ip_to_country('1.2.3.4')
boot_phase = yield info.status.bootstrap_phase()
@@ -67,7 +65,7 @@ def setup_complete(info):
print 'moria1:', ns
print 'entry guards:', guards
- ## now we dump everything, one at a time
+ # now we dump everything, one at a time
d = recursive_dump('', info)
d.addCallback(lambda x: reactor.stop())
d.addErrback(error)
diff --git a/examples/webui_server.py b/examples/webui_server.py
index 1f85639..b0255bd 100755
--- a/examples/webui_server.py
+++ b/examples/webui_server.py
@@ -20,19 +20,19 @@ class TorPage(livepage.LivePage):
ctx = None
torstate = None
- ## Could be done with XHTML 1.0, or a "real" templating language
+ # Could be done with XHTML 1.0, or a "real" templating language
docFactory = loaders.stan(
tags.html[
tags.head[
tags.directive('liveglue')],
tags.body[
tags.h1["Tor Launching..."],
- ## obviously you might want a javascript library or
- ## something here instead of this hackery...
+ # obviously you might want a javascript library or
+ # something here instead of this hackery...
tags.div(id='progress', style='position:abso lute; left:20em; top:10px; width:300px; height:50px; border:2px solid black;background-color:#ffaaaa;')[
tags.div(id='progress_done', style='position:absolute; top:0px; left:0px; width:0%; height: 100%; background-color:#aaffaa;')],
- ## this is where the messages will go
+ # this is where the messages will go
tags.div(id='status', style='padding:5px; background-color:#ffaaaa; text-indent:2em; width: 50em; font-weight:bold; border: 2px solid black;')[""]]])
def goingLive(self, ctx, client):
@@ -56,11 +56,11 @@ class TorPage(livepage.LivePage):
self.client.send(livepage.js('''document.getElementById('progress_done').style.width = "%dpx";''' % point))
if percent == 100:
- ## done, turn message box green too
+ # done, turn message box green too
self.client.send(livepage.js('''document.getElementById("status").style.backgroundColor="#aaffaa";'''))
if self.continuous_update:
- ## add a text node for each update, creating a continuous list
+ # add a text node for each update, creating a continuous list
self.client.send(livepage.js('''var newNode = document.createElement('div');
newNode.appendChild(document.createTextNode("%d%% -- %s"));
document.getElementById('status').appendChild(newNode);''' % (percent, summary)))
@@ -69,27 +69,27 @@ document.getElementById('status').appendChild(newNode);''' % (percent, summary))
self.client.send(livepage.set('status', "%d%% — %s" % (percent, summary)))
-## This only properly works with one client (the last one to load the
-## page). To work with multiples, we'd have to track all clients so
-## sending async updates to them worked properly.
+# This only properly works with one client (the last one to load the
+# page). To work with multiples, we'd have to track all clients so
+# sending async updates to them worked properly.
top_level = TorPage()
-## minimal Tor configuration
+# minimal Tor configuration
config = txtorcon.TorConfig()
config.OrPort = 1234
config.SocksPort = 9999
-## launch a Tor based on the above config; the callback will trigger
-## when the TorControlProtocol and TorState instances are up and
-## running (i.e. Tor process is launched, and we connected to it via
-## control protocol and bootstrapped our notion of its state).
+# launch a Tor based on the above config; the callback will trigger
+# when the TorControlProtocol and TorState instances are up and
+# running (i.e. Tor process is launched, and we connected to it via
+# control protocol and bootstrapped our notion of its state).
d = txtorcon.launch_tor(config, reactor, progress_updates=top_level.tor_update)
d.addCallback(top_level.set_tor_state)
d.addErrback(setup_failed)
print "Launching Tor and providing a Web interface on: \nhttp://localhost:8080\n"
-## Start up the Web server
+# Start up the Web server
site = NevowSite(top_level)
reactor.listenTCP(8080, site)
reactor.run()
diff --git a/test/test_addrmap.py b/test/test_addrmap.py
index c656605..af3ab50 100644
--- a/test/test_addrmap.py
+++ b/test/test_addrmap.py
@@ -20,25 +20,25 @@ class AddrMapTests(unittest.TestCase):
now = datetime.datetime.now() + datetime.timedelta(seconds=10)
nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
- ## we need to not-barf on extra args as per control-spec.txt
+ # we need to not-barf on extra args as per control-spec.txt
line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s" FOO=bar BAR=baz' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))
am = AddrMap()
am.update(line)
addr = am.find('www.example.com')
self.assertTrue(addr.ip == '72.30.2.43' or addr.ip.exploded == '72.30.2.43')
- ## maybe not the most robust, should convert to
- ## seconds-since-epoch instead? the net result of the parsing
- ## is we've rounded to seconds...
+ # maybe not the most robust, should convert to
+ # seconds-since-epoch instead? the net result of the parsing
+ # is we've rounded to seconds...
self.assertEqual(addr.expires.ctime(), nowutc.ctime())
line = 'www.example.com 72.30.2.43 "%s" "%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))
am.update(line)
self.assertEqual(addr.expires.ctime(), nowutc.ctime())
- ## this will have resulted in an expiry call, which we need to
- ## cancel to keep the reactor clean. for consistency, we use
- ## the IReactorTime interface from AddrMap
+ # this will have resulted in an expiry call, which we need to
+ # cancel to keep the reactor clean. for consistency, we use
+ # the IReactorTime interface from AddrMap
am.scheduler.getDelayedCalls()[0].cancel()
def test_expires(self):
@@ -57,7 +57,7 @@ class AddrMapTests(unittest.TestCase):
am.update(line)
self.assertTrue('www.example.com' in am.addr)
- ## advance time past when the expiry should have occurred
+ # advance time past when the expiry should have occurred
clock.advance(10)
self.assertTrue('www.example.com' not in am.addr)
@@ -92,10 +92,10 @@ class AddrMapTests(unittest.TestCase):
am.update(line)
self.assertTrue('www.example.com' in am.addr)
- ## arguably we shouldn't even have put this in the map maybe,
- ## but the reactor needs to iterate before our expiry callback
- ## gets called (right away) which is simulated by the
- ## clock.advance call
+ # arguably we shouldn't even have put this in the map maybe,
+ # but the reactor needs to iterate before our expiry callback
+ # gets called (right away) which is simulated by the
+ # clock.advance call
clock.advance(0)
self.assertTrue('www.example.com' not in am.addr)
@@ -108,27 +108,27 @@ class AddrMapTests(unittest.TestCase):
am = AddrMap()
am.scheduler = IReactorTime(clock)
- ## now do an actual update to an existing Addr entry.
+ # now do an actual update to an existing Addr entry.
now = datetime.datetime.now() + datetime.timedelta(seconds=10)
nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))
am.update(line)
self.assertTrue(am.find('www.example.com'))
- ## the update
+ # the update
now = datetime.datetime.now() + datetime.timedelta(seconds=20)
nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=20)
line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))
am.update(line)
self.assertTrue('www.example.com' in am.addr)
- ## advance time by the old expiry value and we should still
- ## find the entry
+ # advance time by the old expiry value and we should still
+ # find the entry
clock.advance(10)
self.assertTrue('www.example.com' in am.addr)
- ## ...but advance past the new expiry (another 10 seconds) and
- ## it should vanish
+ # ...but advance past the new expiry (another 10 seconds) and
+ # it should vanish
clock.advance(10)
self.assertTrue('www.example.com' not in am.addr)
@@ -186,12 +186,12 @@ class AddrMapTests(unittest.TestCase):
am.update(line)
- ## see if our listener got an update
+ # see if our listener got an update
a = am.find('www.example.com')
self.assertEqual(self.addrmap, [a])
- ## advance time past when the expiry should have occurred
+ # advance time past when the expiry should have occurred
clock.advance(10)
- ## check that our listener got an expires event
+ # check that our listener got an expires event
self.assertEqual(self.expires, ['www.example.com'])
diff --git a/test/test_circuit.py b/test/test_circuit.py
index ba2815d..fc8844b 100644
--- a/test/test_circuit.py
+++ b/test/test_circuit.py
@@ -5,7 +5,10 @@ from twisted.internet import defer
from zope.interface import implements
from txtorcon import Circuit, Stream, TorControlProtocol, TorState
-from txtorcon.interface import IRouterContainer, ICircuitListener, ICircuitContainer, CircuitListenerMixin
+from txtorcon.interface import IRouterContainer
+from txtorcon.interface import ICircuitListener
+from txtorcon.interface import ICircuitContainer
+from txtorcon.interface import CircuitListenerMixin
class FakeTorController(object):
@@ -105,9 +108,9 @@ class CircuitTests(unittest.TestCase):
from zope.interface.verify import verifyObject
self.assertTrue(verifyObject(ICircuitListener, listener))
- ## call all the methods with None for each arg. This is mostly
- ## just to gratuitously increase test coverage, but also
- ## serves to ensure these methods don't just blow up
+ # call all the methods with None for each arg. This is mostly
+ # just to gratuitously increase test coverage, but also
+ # serves to ensure these methods don't just blow up
for (methodname, desc) in ICircuitListener.namesAndDescriptions():
method = getattr(listener, methodname)
args = [None] * len(desc.positional)
@@ -115,7 +118,9 @@ class CircuitTests(unittest.TestCase):
def test_unlisten(self):
tor = FakeTorController()
- tor.routers['$E11D2B2269CC25E67CA6C9FB5843497539A74FD0'] = FakeRouter('$E11D2B2269CC25E67CA6C9FB5843497539A74FD0', 'a')
+ tor.routers['$E11D2B2269CC25E67CA6C9FB5843497539A74FD0'] = FakeRouter(
+ '$E11D2B2269CC25E67CA6C9FB5843497539A74FD0', 'a'
+ )
circuit = Circuit(tor)
circuit.listen(tor)
@@ -133,7 +138,10 @@ class CircuitTests(unittest.TestCase):
circuit = Circuit(state)
circuit.update('1 EXTENDED $E11D2B2269CC25E67CA6C9FB5843497539A74FD0=eris PURPOSE=GENERAL'.split())
self.assertEqual(1, len(circuit.path))
- self.assertEqual('$E11D2B2269CC25E67CA6C9FB5843497539A74FD0', circuit.path[0].id_hex)
+ self.assertEqual(
+ '$E11D2B2269CC25E67CA6C9FB5843497539A74FD0',
+ circuit.path[0].id_hex
+ )
self.assertEqual('eris', circuit.path[0].name)
def test_wrong_update(self):
@@ -141,7 +149,11 @@ class CircuitTests(unittest.TestCase):
circuit = Circuit(tor)
circuit.listen(tor)
circuit.update('1 LAUNCHED PURPOSE=GENERAL'.split())
- self.assertRaises(Exception, circuit.update, '2 LAUNCHED PURPOSE=GENERAL'.split())
+ self.assertRaises(
+ Exception,
+ circuit.update,
+ '2 LAUNCHED PURPOSE=GENERAL'.split()
+ )
def test_closed_remaining_streams(self):
tor = FakeTorController()
@@ -162,16 +174,25 @@ class CircuitTests(unittest.TestCase):
tor = FakeTorController()
circuit = Circuit(tor)
circuit.listen(tor)
- tor.routers['$E11D2B2269CC25E67CA6C9FB5843497539A74FD0'] = FakeRouter('$E11D2B2269CC25E67CA6C9FB5843497539A74FD0', 'a')
- tor.routers['$50DD343021E509EB3A5A7FD0D8A4F8364AFBDCB5'] = FakeRouter('$50DD343021E509EB3A5A7FD0D8A4F8364AFBDCB5', 'b')
- tor.routers['$253DFF1838A2B7782BE7735F74E50090D46CA1BC'] = FakeRouter('$253DFF1838A2B7782BE7735F74E50090D46CA1BC', 'c')
+ tor.routers['$E11D2B2269CC25E67CA6C9FB5843497539A74FD0'] = FakeRouter(
+ '$E11D2B2269CC25E67CA6C9FB5843497539A74FD0', 'a'
+ )
+ tor.routers['$50DD343021E509EB3A5A7FD0D8A4F8364AFBDCB5'] = FakeRouter(
+ '$50DD343021E509EB3A5A7FD0D8A4F8364AFBDCB5', 'b'
+ )
+ tor.routers['$253DFF1838A2B7782BE7735F74E50090D46CA1BC'] = FakeRouter(
+ '$253DFF1838A2B7782BE7735F74E50090D46CA1BC', 'c'
+ )
for ex in examples[:-1]:
circuit.update(ex.split()[1:])
self.assertEqual(circuit.state, ex.split()[2])
self.assertEqual(circuit.purpose, 'GENERAL')
if '$' in ex:
- self.assertEqual(len(circuit.path), len(ex.split()[3].split(',')))
+ self.assertEqual(
+ len(circuit.path),
+ len(ex.split()[3].split(','))
+ )
for (r, p) in zip(ex.split()[3].split(','), circuit.path):
d = r.split('=')[0]
self.assertEqual(d, p.hash)
@@ -207,7 +228,8 @@ class CircuitTests(unittest.TestCase):
def test_extends_no_path(self):
'''
- without connectivity, it seems you get EXTENDS messages with no path update.
+ without connectivity, it seems you get EXTENDS messages with no
+ path update.
'''
tor = FakeTorController()
circuit = Circuit(tor)
@@ -259,7 +281,8 @@ class CircuitTests(unittest.TestCase):
# CLOSECIRCUIT call (see close_circuit() in FakeTorController
# above) however the circuit isn't "really" closed yet...
self.assertTrue(not d.called)
- ## not unit-test-y? shouldn't probably delve into internals I suppose...
+ # not unit-test-y? shouldn't probably delve into internals I
+ # suppose...
self.assertTrue(circuit._closing_deferred is not None)
# simulate that Tor has really closed the circuit for us
@@ -267,5 +290,9 @@ class CircuitTests(unittest.TestCase):
circuit.update('123 CLOSED $E11D2B2269CC25E67CA6C9FB5843497539A74FD0=eris,$50DD343021E509EB3A5A7FD0D8A4F8364AFBDCB5=venus,$253DFF1838A2B7782BE7735F74E50090D46CA1BC=chomsky PURPOSE=GENERAL REASON=FINISHED'.split())
# confirm that our circuit callback has been triggered already
- self.assertRaises(defer.AlreadyCalledError, d.callback, "should have been called already")
+ self.assertRaises(
+ defer.AlreadyCalledError,
+ d.callback,
+ "should have been called already"
+ )
return d
diff --git a/test/test_endpoints.py b/test/test_endpoints.py
index fd419a5..dbc032a 100644
--- a/test/test_endpoints.py
+++ b/test/test_endpoints.py
@@ -51,9 +51,14 @@ class EndpointTests(unittest.TestCase):
'descriptor (status 200 ("Service descriptor (v2) stored"))'
)
self.config = TorConfig(self.protocol)
- self.protocol.answers.append('config/names=\nHiddenServiceOptions Virtual')
+ self.protocol.answers.append(
+ 'config/names=\nHiddenServiceOptions Virtual'
+ )
self.protocol.answers.append('HiddenServiceOptions')
- self.patcher = patch('txtorcon.torconfig.find_tor_binary', return_value='/not/tor')
+ self.patcher = patch(
+ 'txtorcon.torconfig.find_tor_binary',
+ return_value='/not/tor'
+ )
self.patcher.start()
def tearDown(self):
@@ -65,12 +70,18 @@ class EndpointTests(unittest.TestCase):
@defer.inlineCallbacks
def test_global_tor(self):
- config = yield get_global_tor(Mock(), _tor_launcher=lambda x, y, z: True)
+ config = yield get_global_tor(
+ Mock(),
+ _tor_launcher=lambda x, y, z: True
+ )
self.assertEqual(0, config.SOCKSPort)
@defer.inlineCallbacks
def test_global_tor_error(self):
- config0 = yield get_global_tor(Mock(), _tor_launcher=lambda x, y, z: True)
+ config0 = yield get_global_tor(
+ Mock(),
+ _tor_launcher=lambda x, y, z: True
+ )
# now if we specify a control_port it should be an error since
# the above should have launched one.
try:
@@ -120,7 +131,10 @@ class EndpointTests(unittest.TestCase):
return bam
with patch('txtorcon.endpoints.launch_tor') as m:
with patch('txtorcon.endpoints.build_tor_connection', new_callable=boom) as btc:
- client = clientFromString(self.reactor, "tcp:host=localhost:port=9050")
+ client = clientFromString(
+ self.reactor,
+ "tcp:host=localhost:port=9050"
+ )
ep = yield TCPHiddenServiceEndpoint.system_tor(self.reactor,
client, 80)
port = yield ep.listen(NoOpProtocolFactory())
@@ -184,9 +198,14 @@ class EndpointTests(unittest.TestCase):
return ep
def test_hiddenservice_key_unfound(self):
- ep = TCPHiddenServiceEndpoint.private_tor(self.reactor, 1234, hidden_service_dir='/dev/null')
+ ep = TCPHiddenServiceEndpoint.private_tor(
+ self.reactor,
+ 1234,
+ hidden_service_dir='/dev/null'
+ )
- # FIXME Mock() should work somehow for this, but I couldn't make it "go"
+ # FIXME Mock() should work somehow for this, but I couldn't
+ # make it "go"
class Blam(object):
@property
def private_key(self):
@@ -252,14 +271,20 @@ class EndpointTests(unittest.TestCase):
return None
def test_parse_via_plugin(self):
- # make sure we have a valid thing from get_global_tor without actually launching tor
+ # make sure we have a valid thing from get_global_tor without
+ # actually launching tor
config = TorConfig()
config.post_bootstrap = defer.succeed(config)
from txtorcon import torconfig
torconfig._global_tor_config = None
- get_global_tor(self.reactor,
- _tor_launcher=lambda react, config, prog: defer.succeed(config))
- ep = serverFromString(self.reactor, 'onion:88:localPort=1234:hiddenServiceDir=/foo/bar')
+ get_global_tor(
+ self.reactor,
+ _tor_launcher=lambda react, config, prog: defer.succeed(config)
+ )
+ ep = serverFromString(
+ self.reactor,
+ 'onion:88:localPort=1234:hiddenServiceDir=/foo/bar'
+ )
self.assertEqual(ep.public_port, 88)
self.assertEqual(ep.local_port, 1234)
self.assertEqual(ep.hidden_service_dir, '/foo/bar')
@@ -268,30 +293,42 @@ class EndpointTests(unittest.TestCase):
# this makes sure we expand users and symlinks in
# hiddenServiceDir args. see Issue #77
- # make sure we have a valid thing from get_global_tor without actually launching tor
+ # make sure we have a valid thing from get_global_tor without
+ # actually launching tor
config = TorConfig()
config.post_bootstrap = defer.succeed(config)
from txtorcon import torconfig
torconfig._global_tor_config = None
- get_global_tor(self.reactor,
- _tor_launcher=lambda react, config, prog: defer.succeed(config))
- ep = serverFromString(self.reactor, 'onion:88:localPort=1234:hiddenServiceDir=~/blam/blarg')
+ get_global_tor(
+ self.reactor,
+ _tor_launcher=lambda react, config, prog: defer.succeed(config)
+ )
+ ep = serverFromString(
+ self.reactor,
+ 'onion:88:localPort=1234:hiddenServiceDir=~/blam/blarg'
+ )
# would be nice to have a fixed path here, but then would have
# to run as a known user :/
# maybe using the docker stuff to run integration tests better here?
- self.assertEqual(os.path.expanduser('~/blam/blarg'), ep.hidden_service_dir)
+ self.assertEqual(
+ os.path.expanduser('~/blam/blarg'),
+ ep.hidden_service_dir
+ )
def test_parse_relative_path(self):
# this makes sure we convert a relative path to absolute
# hiddenServiceDir args. see Issue #77
- # make sure we have a valid thing from get_global_tor without actually launching tor
+ # make sure we have a valid thing from get_global_tor without
+ # actually launching tor
config = TorConfig()
config.post_bootstrap = defer.succeed(config)
from txtorcon import torconfig
torconfig._global_tor_config = None
- get_global_tor(self.reactor,
- _tor_launcher=lambda react, config, prog: defer.succeed(config))
+ get_global_tor(
+ self.reactor,
+ _tor_launcher=lambda react, config, prog: defer.succeed(config)
+ )
orig = os.path.realpath('.')
try:
@@ -302,8 +339,14 @@ class EndpointTests(unittest.TestCase):
hsdir = os.path.join(t, 'foo', 'blam')
os.mkdir(hsdir)
- ep = serverFromString(self.reactor, 'onion:88:localPort=1234:hiddenServiceDir=foo/blam')
- self.assertEqual(os.path.realpath(hsdir), ep.hidden_service_dir)
+ ep = serverFromString(
+ self.reactor,
+ 'onion:88:localPort=1234:hiddenServiceDir=foo/blam'
+ )
+ self.assertEqual(
+ os.path.realpath(hsdir),
+ ep.hidden_service_dir
+ )
finally:
os.chdir(orig)
@@ -356,7 +399,10 @@ class EndpointLaunchTests(unittest.TestCase):
"""
reactor = proto_helpers.MemoryReactor()
- ep = serverFromString(reactor, 'onion:8888:controlPort=9055:localPort=1234')
+ ep = serverFromString(
+ reactor,
+ 'onion:8888:controlPort=9055:localPort=1234'
+ )
r = yield ep.listen(NoOpProtocolFactory())
self.assertEqual(global_tor.call_count, 0)
self.assertEqual(private_tor.call_count, 0)
@@ -466,11 +512,10 @@ class FakeReactorTcp(FakeReactor):
def connectTCP(self, host, port, factory, timeout, bindAddress):
'''should return IConnector'''
-# print "CONN", host, port, factory
-# print dir(factory)
-# print "XX", factory
- r = tcp.Connector(host, port, factory, timeout, bindAddress, reactor=self)
-# print dir(r)
+ r = tcp.Connector(
+ host, port, factory, timeout,
+ bindAddress, reactor=self
+ )
def blam(*args):
print "BLAAAAAM", args
diff --git a/test/test_router.py b/test/test_router.py
index 83ba306..c23ba36 100644
--- a/test/test_router.py
+++ b/test/test_router.py
@@ -12,10 +12,19 @@ class FakeController(object):
class UtilityTests(unittest.TestCase):
def test_hex_converters(self):
- self.assertEqual(hexIdFromHash('AHhuQ8zFQJdT8l42Axxc6m6kNwI'), '$00786E43CCC5409753F25E36031C5CEA6EA43702')
- self.assertEqual(hashFromHexId('$00786E43CCC5409753F25E36031C5CEA6EA43702'), 'AHhuQ8zFQJdT8l42Axxc6m6kNwI')
- ## should work with or without leading $
- self.assertEqual(hexIdFromHash(hashFromHexId('00786E43CCC5409753F25E36031C5CEA6EA43702')), '$00786E43CCC5409753F25E36031C5CEA6EA43702')
+ self.assertEqual(
+ hexIdFromHash('AHhuQ8zFQJdT8l42Axxc6m6kNwI'),
+ '$00786E43CCC5409753F25E36031C5CEA6EA43702'
+ )
+ self.assertEqual(
+ hashFromHexId('$00786E43CCC5409753F25E36031C5CEA6EA43702'),
+ 'AHhuQ8zFQJdT8l42Axxc6m6kNwI'
+ )
+ # should work with or without leading $
+ self.assertEqual(
+ hexIdFromHash(hashFromHexId('00786E43CCC5409753F25E36031C5CEA6EA43702')),
+ '$00786E43CCC5409753F25E36031C5CEA6EA43702'
+ )
class RouterTests(unittest.TestCase):
@@ -29,7 +38,10 @@ class RouterTests(unittest.TestCase):
"2011-12-16 15:11:34",
"77.183.225.114",
"24051", "24052")
- self.assertEqual(router.id_hex, "$00786E43CCC5409753F25E36031C5CEA6EA43702")
+ self.assertEqual(
+ router.id_hex,
+ "$00786E43CCC5409753F25E36031C5CEA6EA43702"
+ )
self.assertEqual(router.policy, '')
def test_unique_name(self):
@@ -41,8 +53,14 @@ class RouterTests(unittest.TestCase):
"2011-12-16 15:11:34",
"77.183.225.114",
"24051", "24052")
- self.assertEqual(router.id_hex, "$00786E43CCC5409753F25E36031C5CEA6EA43702")
- self.assertEqual(router.unique_name, "$00786E43CCC5409753F25E36031C5CEA6EA43702")
+ self.assertEqual(
+ router.id_hex,
+ "$00786E43CCC5409753F25E36031C5CEA6EA43702"
+ )
+ self.assertEqual(
+ router.unique_name,
+ "$00786E43CCC5409753F25E36031C5CEA6EA43702"
+ )
router.flags = ['Named']
self.assertEqual(router.unique_name, "foo")
@@ -106,7 +124,9 @@ class RouterTests(unittest.TestCase):
def test_countrycode(self):
class CountryCodeController(object):
def get_info_raw(self, i):
- return defer.succeed('250-ip-to-country/127.1.2.3=ZZ\r\n250 OK')
+ return defer.succeed(
+ '250-ip-to-country/127.1.2.3=ZZ\r\n250 OK'
+ )
controller = CountryCodeController()
router = Router(controller)
router.update("foo",
diff --git a/test/test_stream.py b/test/test_stream.py
index a275253..ee8ddc5 100644
--- a/test/test_stream.py
+++ b/test/test_stream.py
@@ -3,7 +3,10 @@ from twisted.trial import unittest
from twisted.internet import defer
from zope.interface import implements
-from txtorcon import Stream, IStreamListener, ICircuitContainer, StreamListenerMixin
+from txtorcon import Stream
+from txtorcon import IStreamListener
+from txtorcon import ICircuitContainer
+from txtorcon import StreamListenerMixin
class FakeCircuit:
@@ -21,20 +24,32 @@ class Listener(object):
def checker(self, state, stream, *args, **kw):
if self.expected[0][0] != state:
- raise RuntimeError('Expected event "%s" not "%s".' % (self.expected[0][0], state))
+ raise RuntimeError(
+ 'Expected event "%s" not "%s".' % (self.expected[0][0], state)
+ )
for (k, v) in self.expected[0][1].items():
if k == 'args':
if v != args:
- raise RuntimeError('Expected argument to have value "%s", not "%s"' % (v, args))
+ raise RuntimeError(
+ 'Expected argument to have value "%s", not "%s"' % (v, args)
+ )
elif k == 'kwargs':
for (key, value) in v.items():
if key not in kw:
print key, value, k, v, kw
- raise RuntimeError('Expected keyword argument for key "%s" but found nothing.' % key)
+ raise RuntimeError(
+ 'Expected keyword argument for key "%s" but found nothing.' % key
+ )
elif kw[key] != value:
- raise RuntimeError('KW Argument expected "%s" but got "%s"' % (value, kw[key]))
+ raise RuntimeError(
+ 'KW Argument expected "%s" but got "%s"' %
+ (value, kw[key])
+ )
elif getattr(stream, k) != v:
- raise RuntimeError('Expected attribute "%s" to have value "%s", not "%s"' % (k, v, getattr(stream, k)))
+ raise RuntimeError(
+ 'Expected attribute "%s" to have value "%s", not "%s"' %
+ (k, v, getattr(stream, k))
+ )
self.expected = self.expected[1:]
def stream_new(self, stream):
@@ -79,7 +94,7 @@ class StreamTests(unittest.TestCase):
self.circuits = {}
def test_lowercase_flags(self):
- ## testing an internal method, maybe a no-no?
+ # testing an internal method, maybe a no-no?
stream = Stream(self)
kw = dict(FOO='bar', BAR='baz')
flags = stream._create_flags(kw)
@@ -96,9 +111,9 @@ class StreamTests(unittest.TestCase):
from zope.interface.verify import verifyObject
self.assertTrue(verifyObject(IStreamListener, listener))
- ## call all the methods with None for each arg. This is mostly
- ## just to gratuitously increase test coverage, but also
- ## serves to ensure these methods don't just blow up
+ # call all the methods with None for each arg. This is mostly
+ # just to gratuitously increase test coverage, but also
+ # serves to ensure these methods don't just blow up
for (methodname, desc) in IStreamListener.namesAndDescriptions():
method = getattr(listener, methodname)
args = [None] * len(desc.positional)
@@ -140,9 +155,12 @@ class StreamTests(unittest.TestCase):
def test_listener_attach(self):
self.circuits[186] = FakeCircuit(186)
- listener = Listener([('new', {'target_host': 'www.yahoo.com',
- 'target_port': 80}),
- ('attach', {'target_addr': maybe_ip_addr('1.2.3.4')})])
+ listener = Listener(
+ [
+ ('new', {'target_host': 'www.yahoo.com', 'target_port': 80}),
+ ('attach', {'target_addr': maybe_ip_addr('1.2.3.4')})
+ ]
+ )
stream = Stream(self)
stream.listen(listener)
@@ -224,11 +242,14 @@ class StreamTests(unittest.TestCase):
self.circuits[123] = FakeCircuit(123)
self.circuits[456] = FakeCircuit(456)
- listener = Listener([('new', {'target_host': 'www.yahoo.com',
- 'target_port': 80}),
- ('attach', {}),
- ('detach', {'kwargs': dict(reason='END', remote_reason='MISC')}),
- ('attach', {})])
+ listener = Listener(
+ [
+ ('new', {'target_host': 'www.yahoo.com', 'target_port': 80}),
+ ('attach', {}),
+ ('detach', {'kwargs': dict(reason='END', remote_reason='MISC')}),
+ ('attach', {})
+ ]
+ )
stream = Stream(self)
stream.listen(listener)
@@ -247,10 +268,13 @@ class StreamTests(unittest.TestCase):
def test_listener_close(self):
self.circuits[186] = FakeCircuit(186)
- listener = Listener([('new', {'target_host': 'www.yahoo.com',
- 'target_port': 80}),
- ('attach', {'target_addr': maybe_ip_addr('1.2.3.4')}),
- ('closed', {'kwargs': dict(REASON='END', REMOTE_REASON='DONE')})])
+ listener = Listener(
+ [
+ ('new', {'target_host': 'www.yahoo.com', 'target_port': 80}),
+ ('attach', {'target_addr': maybe_ip_addr('1.2.3.4')}),
+ ('closed', {'kwargs': dict(REASON='END', REMOTE_REASON='DONE')})
+ ]
+ )
stream = Stream(self)
stream.listen(listener)
stream.update("316 NEW 0 www.yahoo.com:80 SOURCE_ADDR=127.0.0.1:55877 PURPOSE=USER".split())
@@ -260,10 +284,13 @@ class StreamTests(unittest.TestCase):
self.assertEqual(len(self.circuits[186].streams), 0)
def test_listener_fail(self):
- listener = Listener([('new', {'target_host': 'www.yahoo.com',
- 'target_port': 80}),
- ('attach', {'target_addr': maybe_ip_addr('1.2.3.4')}),
- ('failed', {'kwargs': dict(REASON='TIMEOUT', REMOTE_REASON='DESTROYED')})])
+ listener = Listener(
+ [
+ ('new', {'target_host': 'www.yahoo.com', 'target_port': 80}),
+ ('attach', {'target_addr': maybe_ip_addr('1.2.3.4')}),
+ ('failed', {'kwargs': dict(REASON='TIMEOUT', REMOTE_REASON='DESTROYED')})
+ ]
+ )
stream = Stream(self)
stream.listen(listener)
stream.update("316 NEW 0 www.yahoo.com:80 SOURCE_ADDR=127.0.0.1:55877 PURPOSE=USER".split())
@@ -291,8 +318,12 @@ class StreamTests(unittest.TestCase):
self.assertEqual(stream.target_addr, maybe_ip_addr('::1'))
def test_ipv6_source(self):
- listener = Listener([('new', {'source_addr': maybe_ip_addr('::1'),
- 'source_port': 12345})])
+ listener = Listener(
+ [
+ ('new', {'source_addr': maybe_ip_addr('::1'),
+ 'source_port': 12345})
+ ]
+ )
stream = Stream(self)
stream.listen(listener)
@@ -302,9 +333,10 @@ class StreamTests(unittest.TestCase):
self.circuits[1] = FakeCircuit(1)
stream = Stream(self)
- for address in ['1.2.3.4:80',
- '1.2.3.4.315D5684D5343580D409F16119F78D776A58AEFB.exit:80',
- 'timaq4ygg2iegci7.onion:80']:
+ for address in [
+ '1.2.3.4:80',
+ '1.2.3.4.315D5684D5343580D409F16119F78D776A58AEFB.exit:80',
+ 'timaq4ygg2iegci7.onion:80']:
line = "316 %s 1 %s REASON=FOO"
for state in ['NEW', 'SUCCEEDED', 'REMAP',
diff --git a/test/test_torconfig.py b/test/test_torconfig.py
index 6101a33..6f65b1e 100644
--- a/test/test_torconfig.py
+++ b/test/test_torconfig.py
@@ -14,9 +14,23 @@ from twisted.test import proto_helpers
from twisted.internet import defer, error, task, tcp
from twisted.internet.endpoints import TCP4ServerEndpoint, serverFromString
from twisted.python.failure import Failure
-from twisted.internet.interfaces import IReactorCore, IProtocolFactory, IProtocol, IReactorTCP, IListeningPort, IAddress
-
-from txtorcon import TorControlProtocol, ITorControlProtocol, TorConfig, DEFAULT_VALUE, HiddenService, launch_tor, TCPHiddenServiceEndpoint, TorNotFound, TCPHiddenServiceEndpointParser, IProgressProvider
+from twisted.internet.interfaces import IReactorCore
+from twisted.internet.interfaces import IProtocolFactory
+from twisted.internet.interfaces import IProtocol
+from twisted.internet.interfaces import IReactorTCP
+from twisted.internet.interfaces import IListeningPort
+from twisted.internet.interfaces import IAddress
+
+from txtorcon import TorControlProtocol
+from txtorcon import ITorControlProtocol
+from txtorcon import TorConfig
+from txtorcon import DEFAULT_VALUE
+from txtorcon import HiddenService
+from txtorcon import launch_tor
+from txtorcon import TCPHiddenServiceEndpoint
+from txtorcon import TorNotFound
+from txtorcon import TCPHiddenServiceEndpointParser
+from txtorcon import IProgressProvider
from txtorcon import torconfig
from txtorcon.torconfig import TorProcessProtocol
@@ -51,8 +65,9 @@ class FakeControlProtocol:
def event_happened(self, event_type, *args):
'''
- Use this in your tests to send 650 events when an event-listener is added.
- XXX Also if we've *already* added one? Do that if there's a use-case for it
+ Use this in your tests to send 650 events when an event-listener
+ is added. XXX Also if we've *already* added one? Do that if
+ there's a use-case for it
'''
if event_type in self.pending_events:
self.pending_events[event_type].append(args)
@@ -84,7 +99,7 @@ class FakeControlProtocol:
self.answers = self.answers[1:]
return d
- get_conf_raw = get_conf # up to test author ensure the answer is a raw string
+ get_conf_raw = get_conf # up to test author ensure the answer is a raw string
def set_conf(self, *args):
for i in range(0, len(args), 2):
@@ -135,15 +150,17 @@ class ConfigTests(unittest.TestCase):
self.protocol.answers.append('config/names=\nfoo Boolean\nbar Boolean')
self.protocol.answers.append({'foo': '0'})
self.protocol.answers.append({'bar': '1'})
- ## FIXME does a Tor controller only ever send "0" and "1" for
- ## true/false? Or do we need to accept others?
+ # FIXME does a Tor controller only ever send "0" and "1" for
+ # true/false? Or do we need to accept others?
conf = TorConfig(self.protocol)
self.assertTrue(conf.foo is False)
self.assertTrue(conf.bar is True)
def test_boolean_auto_parser(self):
- self.protocol.answers.append('config/names=\nfoo Boolean+Auto\nbar Boolean+Auto\nbaz Boolean+Auto')
+ self.protocol.answers.append(
+ 'config/names=\nfoo Boolean+Auto\nbar Boolean+Auto\nbaz Boolean+Auto'
+ )
self.protocol.answers.append({'foo': '0'})
self.protocol.answers.append({'bar': '1'})
self.protocol.answers.append({'baz': 'auto'})
@@ -255,7 +272,9 @@ class ConfigTests(unittest.TestCase):
self.assertTrue('foo' in str(e))
def test_invalid_parser(self):
- self.protocol.answers.append('config/names=\nSomethingExciting NonExistantParserType')
+ self.protocol.answers.append(
+ 'config/names=\nSomethingExciting NonExistantParserType'
+ )
cfg = TorConfig(self.protocol)
return self.assertFailure(cfg.post_bootstrap, RuntimeError)
@@ -268,7 +287,9 @@ class ConfigTests(unittest.TestCase):
conf.save()
def test_get_type(self):
- self.protocol.answers.append('config/names=\nSomethingExciting CommaList\nHiddenServices Dependant')
+ self.protocol.answers.append(
+ 'config/names=\nSomethingExciting CommaList\nHiddenServices Dependant'
+ )
self.protocol.answers.append({'SomethingExciting': 'a,b'})
conf = TorConfig(self.protocol)
@@ -290,9 +311,9 @@ class ConfigTests(unittest.TestCase):
def test_slutty_postbootstrap(self):
# test that doPostbootstrap still works in "slutty" mode
self.protocol.answers.append('config/names=\nORPort Port')
- ## we can't answer right away, or we do all the _do_setup
- ## callbacks before _setup_ is set -- but we need to do an
- ## answer callback after that to trigger this bug
+ # we can't answer right away, or we do all the _do_setup
+ # callbacks before _setup_ is set -- but we need to do an
+ # answer callback after that to trigger this bug
conf = TorConfig(self.protocol)
self.assertTrue('_setup_' in conf.__dict__)
@@ -332,8 +353,12 @@ class ConfigTests(unittest.TestCase):
self.assertEqual(self.protocol.sets[0], ('AwesomeKey', 'pac man'))
def test_log_double_save(self):
- self.protocol.answers.append('config/names=\nLog LineList\nFoo String''')
- self.protocol.answers.append({'Log': 'notice file /var/log/tor/notices.log'})
+ self.protocol.answers.append(
+ 'config/names=\nLog LineList\nFoo String'''
+ )
+ self.protocol.answers.append(
+ {'Log': 'notice file /var/log/tor/notices.log'}
+ )
self.protocol.answers.append({'Foo': 'foo'})
conf = TorConfig(self.protocol)
@@ -350,7 +375,9 @@ class ConfigTests(unittest.TestCase):
def test_set_save_modify(self):
self.protocol.answers.append('config/names=\nLog LineList')
- self.protocol.answers.append({'Log': 'notice file /var/log/tor/notices.log'})
+ self.protocol.answers.append(
+ {'Log': 'notice file /var/log/tor/notices.log'}
+ )
conf = TorConfig(self.protocol)
conf.log = []
@@ -411,7 +438,9 @@ class LogTests(unittest.TestCase):
def setUp(self):
self.protocol = FakeControlProtocol([])
self.protocol.answers.append('config/names=\nLog LineList''')
- self.protocol.answers.append({'Log': 'notice file /var/log/tor/notices.log'})
+ self.protocol.answers.append(
+ {'Log': 'notice file /var/log/tor/notices.log'}
+ )
def test_log_set(self):
conf = TorConfig(self.protocol)
@@ -420,8 +449,14 @@ class LogTests(unittest.TestCase):
self.assertTrue(conf.needs_save())
conf.save()
- self.assertEqual(self.protocol.sets[0], ('Log', 'notice file /var/log/tor/notices.log'))
- self.assertEqual(self.protocol.sets[1], ('Log', 'info file /tmp/foo.log'))
+ self.assertEqual(
+ self.protocol.sets[0],
+ ('Log', 'notice file /var/log/tor/notices.log')
+ )
+ self.assertEqual(
+ self.protocol.sets[1],
+ ('Log', 'info file /tmp/foo.log')
+ )
def test_log_set_capital(self):
conf = TorConfig(self.protocol)
@@ -430,8 +465,14 @@ class LogTests(unittest.TestCase):
self.assertTrue(conf.needs_save())
conf.save()
- self.assertEqual(self.protocol.sets[0], ('Log', 'notice file /var/log/tor/notices.log'))
- self.assertEqual(self.protocol.sets[1], ('Log', 'info file /tmp/foo.log'))
+ self.assertEqual(
+ self.protocol.sets[0],
+ ('Log', 'notice file /var/log/tor/notices.log')
+ )
+ self.assertEqual(
+ self.protocol.sets[1],
+ ('Log', 'info file /tmp/foo.log')
+ )
def test_log_set_index(self):
conf = TorConfig(self.protocol)
@@ -440,7 +481,10 @@ class LogTests(unittest.TestCase):
self.assertTrue(conf.needs_save())
conf.save()
- self.assertEqual(self.protocol.sets[0], ('Log', 'info file /tmp/foo.log'))
+ self.assertEqual(
+ self.protocol.sets[0],
+ ('Log', 'info file /tmp/foo.log')
+ )
def test_log_set_slice(self):
conf = TorConfig(self.protocol)
@@ -450,7 +494,10 @@ class LogTests(unittest.TestCase):
conf.save()
self.assertEqual(1, len(self.protocol.sets))
- self.assertEqual(self.protocol.sets[0], ('Log', 'info file /tmp/foo.log'))
+ self.assertEqual(
+ self.protocol.sets[0],
+ ('Log', 'info file /tmp/foo.log')
+ )
def test_log_set_pop(self):
conf = TorConfig(self.protocol)
@@ -473,8 +520,14 @@ class LogTests(unittest.TestCase):
self.assertEqual(len(conf.log), 2)
self.assertEqual(len(self.protocol.sets), 2)
- self.assertEqual(self.protocol.sets[0], ('Log', 'notice file /var/log/tor/notices.log'))
- self.assertEqual(self.protocol.sets[1], ('Log', 'info file /tmp/foo'))
+ self.assertEqual(
+ self.protocol.sets[0],
+ ('Log', 'notice file /var/log/tor/notices.log')
+ )
+ self.assertEqual(
+ self.protocol.sets[1],
+ ('Log', 'info file /tmp/foo')
+ )
def test_log_set_insert(self):
conf = TorConfig(self.protocol)
@@ -486,8 +539,14 @@ class LogTests(unittest.TestCase):
self.assertEqual(len(conf.log), 2)
self.assertEqual(len(self.protocol.sets), 2)
- self.assertEqual(self.protocol.sets[1], ('Log', 'notice file /var/log/tor/notices.log'))
- self.assertEqual(self.protocol.sets[0], ('Log', 'info file /tmp/foo'))
+ self.assertEqual(
+ self.protocol.sets[1],
+ ('Log', 'notice file /var/log/tor/notices.log')
+ )
+ self.assertEqual(
+ self.protocol.sets[0],
+ ('Log', 'info file /tmp/foo')
+ )
def test_log_set_remove(self):
conf = TorConfig(self.protocol)
@@ -541,8 +600,10 @@ class CreateTorrcTests(unittest.TestCase):
def test_create_torrc(self):
config = TorConfig()
config.SocksPort = 1234
- config.hiddenservices = [HiddenService(config, '/some/dir', '80 127.0.0.1:1234',
- 'auth', 2, True)]
+ config.hiddenservices = [
+ HiddenService(config, '/some/dir', '80 127.0.0.1:1234',
+ 'auth', 2, True)
+ ]
config.Log = ['80 127.0.0.1:80', '90 127.0.0.1:90']
config.save()
torrc = config.create_torrc()
@@ -570,7 +631,10 @@ HiddenServiceAuthorizeClient Dependant''')
@defer.inlineCallbacks
def test_options_hidden(self):
- self.protocol.answers.append('HiddenServiceDir=/fake/path\nHiddenServicePort=80 127.0.0.1:1234\nHiddenServiceDirGroupReadable=1\n')
+ self.protocol.answers.append(
+ 'HiddenServiceDir=/fake/path\nHiddenServicePort=80 '
+ '127.0.0.1:1234\nHiddenServiceDirGroupReadable=1\n'
+ )
conf = TorConfig(self.protocol)
yield conf.post_bootstrap
@@ -580,7 +644,9 @@ HiddenServiceAuthorizeClient Dependant''')
self.assertEqual(len(conf.HiddenServices), 1)
self.assertTrue(not conf.needs_save())
- conf.hiddenservices.append(HiddenService(conf, '/some/dir', '80 127.0.0.1:2345', 'auth', 2, True))
+ conf.hiddenservices.append(
+ HiddenService(conf, '/some/dir', '80 127.0.0.1:2345', 'auth', 2, True)
+ )
conf.hiddenservices[0].ports.append('443 127.0.0.1:443')
self.assertTrue(conf.needs_save())
conf.save()
@@ -738,7 +804,8 @@ class FakeReactor(task.Clock):
self.transport = trans
self.on_protocol = on_protocol
- def spawnProcess(self, processprotocol, bin, args, env, path, uid=None, gid=None, usePTY=None, childFDs=None):
+ def spawnProcess(self, processprotocol, bin, args, env, path,
+ uid=None, gid=None, usePTY=None, childFDs=None):
self.protocol = processprotocol
self.protocol.makeConnection(self.transport)
self.transport.process_protocol = processprotocol
@@ -748,9 +815,9 @@ class FakeReactor(task.Clock):
def addSystemEventTrigger(self, *args):
self.test.assertEqual(args[0], 'before')
self.test.assertEqual(args[1], 'shutdown')
- ## we know this is just for the temporary file cleanup, so we
- ## nuke it right away to avoid polluting /tmp by calling the
- ## callback now.
+ # we know this is just for the temporary file cleanup, so we
+ # nuke it right away to avoid polluting /tmp by calling the
+ # callback now.
args[2]()
def removeSystemEventTrigger(self, id):
@@ -762,14 +829,22 @@ class FakeProcessTransport(proto_helpers.StringTransportWithDisconnection):
pid = -1
def signalProcess(self, signame):
- self.process_protocol.processEnded(Failure(error.ProcessTerminated(signal=signame)))
+ self.process_protocol.processEnded(
+ Failure(error.ProcessTerminated(signal=signame))
+ )
def closeStdin(self):
self.protocol.dataReceived('250 OK\r\n')
self.protocol.dataReceived('250 OK\r\n')
self.protocol.dataReceived('250 OK\r\n')
- self.protocol.dataReceived('650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=90 TAG=circuit_create SUMMARY="Establishing a Tor circuit"\r\n')
- self.protocol.dataReceived('650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=100 TAG=done SUMMARY="Done"\r\n')
+ self.protocol.dataReceived(
+ '650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=90 '
+ 'TAG=circuit_create SUMMARY="Establishing a Tor circuit"\r\n'
+ )
+ self.protocol.dataReceived(
+ '650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=100 '
+ 'TAG=done SUMMARY="Done"\r\n'
+ )
class FakeProcessTransportNeverBootstraps(FakeProcessTransport):
@@ -780,7 +855,9 @@ class FakeProcessTransportNeverBootstraps(FakeProcessTransport):
self.protocol.dataReceived('250 OK\r\n')
self.protocol.dataReceived('250 OK\r\n')
self.protocol.dataReceived('250 OK\r\n')
- self.protocol.dataReceived('650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=90 TAG=circuit_create SUMMARY="Establishing a Tor circuit"\r\n')
+ self.protocol.dataReceived(
+ '650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=90 TAG=circuit_create '
+ 'SUMMARY="Establishing a Tor circuit"\r\n')
class FakeProcessTransportNoProtocol(FakeProcessTransport):
@@ -812,8 +889,8 @@ class LaunchTorTests(unittest.TestCase):
self.assertTrue(not os.path.exists(f))
self.assertEqual(proto._timeout_delayed_call, None)
- ## make sure we set up the config to track the created tor
- ## protocol connection
+ # make sure we set up the config to track the created tor
+ # protocol connection
self.assertEquals(config.protocol, proto.tor_protocol)
def setup_complete_fails(self, proto, stdout, stderr):
@@ -821,8 +898,10 @@ class LaunchTorTests(unittest.TestCase):
self.assertEqual("", stderr.getvalue())
todel = proto.to_delete
self.assertTrue(len(todel) > 0)
- ## the "12" is just arbitrary, we check it later in the error-message
- proto.processEnded(Failure(error.ProcessTerminated(12, None, 'statusFIXME')))
+ # the "12" is just arbitrary, we check it later in the error-message
+ proto.processEnded(
+ Failure(error.ProcessTerminated(12, None, 'statusFIXME'))
+ )
self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError)))
self.assertEqual(len(proto.to_delete), 0)
for f in todel:
@@ -850,28 +929,42 @@ class LaunchTorTests(unittest.TestCase):
self.expected = expected
def __call__(self, percent, tag, summary):
- self.test.assertEqual(self.expected[0], (percent, tag, summary))
+ self.test.assertEqual(
+ self.expected[0],
+ (percent, tag, summary)
+ )
self.expected = self.expected[1:]
self.test.assertTrue('"' not in summary)
self.test.assertTrue(percent >= 0 and percent <= 100)
def on_protocol(proto):
proto.outReceived('Bootstrapped 100%\n')
- proto.progress = OnProgress(self, [(90, 'circuit_create', 'Establishing a Tor circuit'),
- (100, 'done', 'Done')])
+ proto.progress = OnProgress(
+ self, [
+ (90, 'circuit_create', 'Establishing a Tor circuit'),
+ (100, 'done', 'Done'),
+ ]
+ )
trans = FakeProcessTransport()
trans.protocol = self.protocol
fakeout = StringIO()
fakeerr = StringIO()
creator = functools.partial(connector, self.protocol, self.transport)
- d = launch_tor(config, FakeReactor(self, trans, on_protocol), connection_creator=creator, tor_binary='/bin/echo', stdout=fakeout, stderr=fakeerr)
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, on_protocol),
+ connection_creator=creator,
+ tor_binary='/bin/echo',
+ stdout=fakeout,
+ stderr=fakeerr
+ )
d.addCallback(self.setup_complete_no_errors, config, fakeout, fakeerr)
return d
def check_setup_failure(self, fail):
self.assertTrue("with error-code 12" in fail.getErrorMessage())
- ## cancel the errback chain, we wanted this
+ # cancel the errback chain, we wanted this
return None
def test_launch_tor_fails(self):
@@ -893,7 +986,14 @@ class LaunchTorTests(unittest.TestCase):
fakeout = StringIO()
fakeerr = StringIO()
creator = functools.partial(connector, self.protocol, self.transport)
- d = launch_tor(config, FakeReactor(self, trans, on_protocol), connection_creator=creator, tor_binary='/bin/echo', stdout=fakeout, stderr=fakeerr)
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, on_protocol),
+ connection_creator=creator,
+ tor_binary='/bin/echo',
+ stdout=fakeout,
+ stderr=fakeerr
+ )
d.addCallback(self.setup_complete_fails, fakeout, fakeerr)
self.flushLoggedErrors(RuntimeError)
return d
@@ -909,7 +1009,7 @@ class LaunchTorTests(unittest.TestCase):
@patch('txtorcon.torconfig.pwd')
@patch('txtorcon.torconfig.os.geteuid')
@patch('txtorcon.torconfig.os.chown')
- def test_launch_root_changes_tmpdir_ownership(self, chown, euid, _pwd, _sys):
+ def test_launch_root_changes_tmp_ownership(self, chown, euid, _pwd, _sys):
_pwd.return_value = 1000
_sys.platform = 'linux2'
euid.return_value = 0
@@ -931,7 +1031,11 @@ ControlPort Port''')
config.DataDirectory = '/dev/null'
trans = Mock()
- d = launch_tor(config, FakeReactor(self, trans, Mock()), tor_binary='/bin/echo')
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, Mock()),
+ tor_binary='/bin/echo'
+ )
tpp = yield d
tpp.transport = trans
trans.signalProcess = Mock(side_effect=error.ProcessExitedAlready)
@@ -956,7 +1060,11 @@ ControlPort Port''')
config.DataDirectory = '/dev/null'
trans = Mock()
- d = launch_tor(config, FakeReactor(self, trans, Mock()), tor_binary='/bin/echo')
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, Mock()),
+ tor_binary='/bin/echo'
+ )
tpp = yield d
tpp.timeout_expired()
tpp.transport = trans
@@ -996,7 +1104,10 @@ ControlPort Port''')
self.expected = expected
def __call__(self, percent, tag, summary):
- self.test.assertEqual(self.expected[0], (percent, tag, summary))
+ self.test.assertEqual(
+ self.expected[0],
+ (percent, tag, summary)
+ )
self.expected = self.expected[1:]
self.test.assertTrue('"' not in summary)
self.test.assertTrue(percent >= 0 and percent <= 100)
@@ -1014,7 +1125,9 @@ ControlPort Port''')
react.advance(timeout + 1)
self.assertTrue(d.called)
- self.assertTrue(d.result.getErrorMessage().strip().endswith('Tor was killed (TERM).'))
+ self.assertTrue(
+ d.result.getErrorMessage().strip().endswith('Tor was killed (TERM).')
+ )
self.flushLoggedErrors(RuntimeError)
return self.assertFailure(d, RuntimeError)
@@ -1036,7 +1149,10 @@ ControlPort Port''')
self.expected = expected
def __call__(self, percent, tag, summary):
- self.test.assertEqual(self.expected[0], (percent, tag, summary))
+ self.test.assertEqual(
+ self.expected[0],
+ (percent, tag, summary)
+ )
self.expected = self.expected[1:]
self.test.assertTrue('"' not in summary)
self.test.assertTrue(percent >= 0 and percent <= 100)
@@ -1059,8 +1175,10 @@ ControlPort Port''')
def setup_fails_stderr(self, fail, stdout, stderr):
self.assertEqual('', stdout.getvalue())
self.assertEqual('Something went horribly wrong!\n', stderr.getvalue())
- self.assertTrue('Something went horribly wrong!' in fail.getErrorMessage())
- ## cancel the errback chain, we wanted this
+ self.assertTrue(
+ 'Something went horribly wrong!' in fail.getErrorMessage()
+ )
+ # cancel the errback chain, we wanted this
return None
def test_tor_produces_stderr_output(self):
@@ -1107,7 +1225,9 @@ ControlPort Port''')
def __call__(self, proto, trans):
self.count += 1
if self.count < 2:
- return defer.fail(error.CannotListenError(None, None, None))
+ return defer.fail(
+ error.CannotListenError(None, None, None)
+ )
proto._set_valid_events('STATUS_CLIENT')
proto.makeConnection(trans)
@@ -1120,7 +1240,12 @@ ControlPort Port''')
trans = FakeProcessTransport()
trans.protocol = self.protocol
creator = functools.partial(Connector(), self.protocol, self.transport)
- d = launch_tor(config, FakeReactor(self, trans, on_protocol), connection_creator=creator, tor_binary='/bin/echo')
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, on_protocol),
+ connection_creator=creator,
+ tor_binary='/bin/echo'
+ )
d.addCallback(self.setup_complete_fails)
return self.assertFailure(d, Exception)
@@ -1147,7 +1272,12 @@ ControlPort Port''')
trans = FakeProcessTransport()
trans.protocol = self.protocol
creator = functools.partial(Connector(), self.protocol, self.transport)
- d = launch_tor(config, FakeReactor(self, trans, on_protocol), connection_creator=creator, tor_binary='/bin/echo')
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, on_protocol),
+ connection_creator=creator,
+ tor_binary='/bin/echo'
+ )
def still_have_data_dir(proto, tester):
proto.cleanup() # FIXME? not really unit-testy as this is sort of internal function
@@ -1181,11 +1311,16 @@ ControlPort Port''')
trans = FakeProcessTransport()
trans.protocol = self.protocol
creator = functools.partial(Connector(), self.protocol, self.transport)
- d = launch_tor(config, FakeReactor(self, trans, on_protocol), connection_creator=creator, tor_binary='/bin/echo')
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, on_protocol),
+ connection_creator=creator,
+ tor_binary='/bin/echo'
+ )
def check_control_port(proto, tester):
- ## we just want to ensure launch_tor() didn't mess with
- ## the controlport we set
+ # we just want to ensure launch_tor() didn't mess with
+ # the controlport we set
tester.assertEquals(config.ControlPort, 4321)
d.addCallback(check_control_port, self)
@@ -1213,10 +1348,15 @@ ControlPort Port''')
trans = FakeProcessTransport()
trans.protocol = self.protocol
creator = functools.partial(Connector(), self.protocol, self.transport)
- d = launch_tor(config, FakeReactor(self, trans, on_protocol), connection_creator=creator, tor_binary='/bin/echo')
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, on_protocol),
+ connection_creator=creator,
+ tor_binary='/bin/echo'
+ )
def check_control_port(proto, tester):
- ## ensure ControlPort was set to a default value
+ # ensure ControlPort was set to a default value
tester.assertEquals(config.ControlPort, 9052)
d.addCallback(check_control_port, self)
@@ -1245,7 +1385,9 @@ ControlPort Port''')
i.e. success and then shutdown. This repeats it.
"""
process = TorProcessProtocol(None)
- process.status_client('STATUS_CLIENT BOOTSTRAP PROGRESS=100 TAG=foo SUMMARY=cabbage')
+ process.status_client(
+ 'STATUS_CLIENT BOOTSTRAP PROGRESS=100 TAG=foo SUMMARY=cabbage'
+ )
self.assertEqual(None, process.connected_cb)
class Value(object):
@@ -1304,7 +1446,11 @@ class ErrorTests(unittest.TestCase):
trans.protocol = self.protocol
creator = functools.partial(Connector(), self.protocol, self.transport)
try:
- d = launch_tor(config, FakeReactor(self, trans, lambda x: None), connection_creator=creator)
+ d = launch_tor(
+ config,
+ FakeReactor(self, trans, lambda x: None),
+ connection_creator=creator
+ )
self.fail()
except TorNotFound:
diff --git a/test/test_torcontrolprotocol.py b/test/test_torcontrolprotocol.py
index 38b4957..d249bc0 100644
--- a/test/test_torcontrolprotocol.py
+++ b/test/test_torcontrolprotocol.py
@@ -27,8 +27,9 @@ class CallbackChecker:
v = args[0]
if v != self.expected_value:
print "WRONG"
- raise RuntimeError('Expected "%s" but got "%s"' % (self.expected_value, v))
- ##print "got correct value",v
+ raise RuntimeError(
+ 'Expected "%s" but got "%s"' % (self.expected_value, v)
+ )
self.called_back = True
return v
@@ -55,7 +56,7 @@ class LogicTests(unittest.TestCase):
self.assertTrue(d.called)
self.assertTrue(d.result)
self.assertTrue('even number' in d.result.getErrorMessage())
- ## ignore the error so trial doesn't get unhappy
+ # ignore the error so trial doesn't get unhappy
d.addErrback(lambda foo: True)
return d
@@ -86,7 +87,10 @@ class AuthenticationTests(unittest.TestCase):
self.send('250-VERSION Tor="0.2.2.34"')
self.send('250 OK')
- self.assertEqual(self.transport.value(), 'AUTHENTICATE %s\r\n' % cookie_data.encode("hex"))
+ self.assertEqual(
+ self.transport.value(),
+ 'AUTHENTICATE %s\r\n' % cookie_data.encode("hex")
+ )
def test_authenticate_password(self):
self.protocol.password_function = lambda: 'foo'
@@ -111,13 +115,16 @@ class AuthenticationTests(unittest.TestCase):
self.send('250-VERSION Tor="0.2.2.34"')
self.send('250 OK')
- ## make sure we haven't tried to authenticate before getting
- ## the password callback
+ # make sure we haven't tried to authenticate before getting
+ # the password callback
self.assertEqual(self.transport.value(), '')
d.callback('foo')
- ## now make sure we DID try to authenticate
- self.assertEqual(self.transport.value(), 'AUTHENTICATE %s\r\n' % "foo".encode("hex"))
+ # now make sure we DID try to authenticate
+ self.assertEqual(
+ self.transport.value(),
+ 'AUTHENTICATE %s\r\n' % "foo".encode("hex")
+ )
def test_authenticate_password_deferred_but_no_password(self):
d = defer.Deferred()
@@ -156,7 +163,7 @@ class DisconnectionTests(unittest.TestCase):
self.protocol.connectionMade = lambda: None
self.transport = proto_helpers.StringTransportWithDisconnection()
self.protocol.makeConnection(self.transport)
- ## why doesn't makeConnection do this?
+ # why doesn't makeConnection do this?
self.transport.protocol = self.protocol
def tearDown(self):
@@ -171,7 +178,8 @@ class DisconnectionTests(unittest.TestCase):
it_was_called.yes = True
return None
it_was_called.yes = False
- self.protocol.on_disconnect.addCallback(it_was_called).addErrback(it_was_called)
+ self.protocol.on_disconnect.addCallback(it_was_called)
+ self.protocol.on_disconnect.addErrback(it_was_called)
f = failure.Failure(error.ConnectionDone("It's all over"))
self.protocol.connectionLost(f)
self.assertTrue(it_was_called.yes)
@@ -185,7 +193,8 @@ class DisconnectionTests(unittest.TestCase):
it_was_called.yes = True
return None
it_was_called.yes = False
- self.protocol.on_disconnect.addCallback(it_was_called).addErrback(it_was_called)
+ self.protocol.on_disconnect.addCallback(it_was_called)
+ self.protocol.on_disconnect.addErrback(it_was_called)
f = failure.Failure(RuntimeError("The thing didn't do the stuff."))
self.protocol.connectionLost(f)
self.assertTrue(it_was_called.yes)
@@ -309,15 +318,21 @@ OK''' % cookietmp.name)
AUTH METHODS=SAFECOOKIE COOKIEFILE="%s"
VERSION Tor="0.2.2.35"
OK''' % cookietmp.name)
- self.assertTrue('AUTHCHALLENGE SAFECOOKIE ' in self.transport.value())
+ self.assertTrue(
+ 'AUTHCHALLENGE SAFECOOKIE ' in self.transport.value()
+ )
client_nonce = base64.b16decode(self.transport.value().split()[-1])
self.transport.clear()
server_nonce = str(bytearray([0] * 32))
- server_hash = hmac_sha256("Tor safe cookie authentication server-to-controller hash",
- cookiedata + client_nonce + server_nonce)
-
- self.send('250 AUTHCHALLENGE SERVERHASH=%s SERVERNONCE=%s' %
- (base64.b16encode(server_hash), base64.b16encode(server_nonce)))
+ server_hash = hmac_sha256(
+ "Tor safe cookie authentication server-to-controller hash",
+ cookiedata + client_nonce + server_nonce
+ )
+
+ self.send(
+ '250 AUTHCHALLENGE SERVERHASH=%s SERVERNONCE=%s' %
+ (base64.b16encode(server_hash), base64.b16encode(server_nonce))
+ )
self.assertTrue('AUTHENTICATE ' in self.transport.value())
def test_authenticate_safecookie_wrong_hash(self):
@@ -325,13 +340,15 @@ OK''' % cookietmp.name)
server_nonce = str(bytearray([0] * 32))
server_hash = str(bytearray([0] * 32))
- ## pretend we already did PROTOCOLINFO and read the cookie
- ## file
+ # pretend we already did PROTOCOLINFO and read the cookie
+ # file
self.protocol.cookie_data = cookiedata
self.protocol.client_nonce = server_nonce # all 0's anyway
try:
- self.protocol._safecookie_authchallenge('250 AUTHCHALLENGE SERVERHASH=%s SERVERNONCE=%s' %
- (base64.b16encode(server_hash), base64.b16encode(server_nonce)))
+ self.protocol._safecookie_authchallenge(
+ '250 AUTHCHALLENGE SERVERHASH=%s SERVERNONCE=%s' %
+ (base64.b16encode(server_hash), base64.b16encode(server_nonce))
+ )
self.assertTrue(False)
except RuntimeError, e:
self.assertTrue('hash not expected' in str(e))
@@ -350,7 +367,7 @@ OK''' % cookietmp.name)
events = 'GUARD STREAM CIRC NS NEWCONSENSUS ORCONN NEWDESC ADDRMAP STATUS_GENERAL'
self.protocol._bootstrap()
- ## answer all the requests generated by boostrapping etc.
+ # answer all the requests generated by boostrapping etc.
self.send("250-version=foo")
self.send("250 OK")
@@ -377,14 +394,19 @@ OK''' % cookietmp.name)
return d
def test_async_multiline(self):
- ## same as above, but i think the 650's can be multline,
- ## too. Like:
- ## 650-CIRC 1000 EXTENDED moria1,moria2 0xBEEF
- ## 650-EXTRAMAGIC=99
- ## 650 ANONYMITY=high
+ # same as above, but i think the 650's can be multline,
+ # too. Like:
+ # 650-CIRC 1000 EXTENDED moria1,moria2 0xBEEF
+ # 650-EXTRAMAGIC=99
+ # 650 ANONYMITY=high
self.protocol._set_valid_events('CIRC')
- self.protocol.add_event_listener('CIRC', CallbackChecker("1000 EXTENDED moria1,moria2\nEXTRAMAGIC=99\nANONYMITY=high"))
+ self.protocol.add_event_listener(
+ 'CIRC',
+ CallbackChecker(
+ "1000 EXTENDED moria1,moria2\nEXTRAMAGIC=99\nANONYMITY=high"
+ )
+ )
self.send("250 OK")
d = self.protocol.get_conf("SOCKSPORT ORPORT")
@@ -416,7 +438,10 @@ OK''' % cookietmp.name)
self.assertEqual(expected, actual)
def test_getinfo_incremental(self):
- d = self.protocol.get_info_incremental("FOO", functools.partial(self.incremental_check, "bar"))
+ d = self.protocol.get_info_incremental(
+ "FOO",
+ functools.partial(self.incremental_check, "bar")
+ )
self.send("250+FOO=")
self.send("bar")
self.send("bar")
@@ -425,7 +450,10 @@ OK''' % cookietmp.name)
return d
def test_getinfo_incremental_continuation(self):
- d = self.protocol.get_info_incremental("FOO", functools.partial(self.incremental_check, "bar"))
+ d = self.protocol.get_info_incremental(
+ "FOO",
+ functools.partial(self.incremental_check, "bar")
+ )
self.send("250-FOO=")
self.send("250-bar")
self.send("250-bar")
@@ -433,7 +461,10 @@ OK''' % cookietmp.name)
return d
def test_getinfo_one_line(self):
- d = self.protocol.get_info("foo", functools.partial(self.incremental_check, "bar"))
+ d = self.protocol.get_info(
+ "foo",
+ functools.partial(self.incremental_check, "bar")
+ )
self.send('250 foo=bar')
return d
@@ -455,16 +486,22 @@ OK''' % cookietmp.name)
self.assertEqual(v, '')
def test_setconf(self):
- d = self.protocol.set_conf("foo", "bar").addCallback(functools.partial(self.response_ok))
+ d = self.protocol.set_conf("foo", "bar").addCallback(
+ functools.partial(self.response_ok)
+ )
self.send("250 OK")
self._wait(d)
self.assertEqual(self.transport.value(), "SETCONF foo=bar\r\n")
def test_setconf_with_space(self):
- d = self.protocol.set_conf("foo", "a value with a space").addCallback(functools.partial(self.response_ok))
+ d = self.protocol.set_conf("foo", "a value with a space")
+ d.addCallback(functools.partial(self.response_ok))
self.send("250 OK")
self._wait(d)
- self.assertEqual(self.transport.value(), 'SETCONF foo="a value with a space"\r\n')
+ self.assertEqual(
+ self.transport.value(),
+ 'SETCONF foo="a value with a space"\r\n'
+ )
def test_setconf_multi(self):
d = self.protocol.set_conf("foo", "bar", "baz", 1)
@@ -520,7 +557,10 @@ OK''' % cookietmp.name)
def test_650_after_authenticate(self):
self.protocol._set_valid_events('CONF_CHANGED')
- self.protocol.add_event_listener('CONF_CHANGED', CallbackChecker("Foo=bar"))
+ self.protocol.add_event_listener(
+ 'CONF_CHANGED',
+ CallbackChecker("Foo=bar")
+ )
self.send("250 OK")
self.send("650-CONF_CHANGED")
@@ -528,7 +568,10 @@ OK''' % cookietmp.name)
def test_notify_after_getinfo(self):
self.protocol._set_valid_events('CIRC')
- self.protocol.add_event_listener('CIRC', CallbackChecker("1000 EXTENDED moria1,moria2"))
+ self.protocol.add_event_listener(
+ 'CIRC',
+ CallbackChecker("1000 EXTENDED moria1,moria2")
+ )
self.send("250 OK")
d = self.protocol.get_info("FOO")
@@ -557,12 +600,15 @@ OK''' % cookietmp.name)
self.protocol._set_valid_events('FOO BAR')
self.protocol.add_event_listener('FOO', lambda _: None)
- ## is it dangerous/ill-advised to depend on internal state of
- ## class under test?
+ # is it dangerous/ill-advised to depend on internal state of
+ # class under test?
d = self.protocol.defer
self.send("250 OK")
self._wait(d)
- self.assertEqual(self.transport.value().split('\r\n')[-2], "SETEVENTS FOO")
+ self.assertEqual(
+ self.transport.value().split('\r\n')[-2],
+ "SETEVENTS FOO"
+ )
self.transport.clear()
self.protocol.add_event_listener('BAR', lambda _: None)
@@ -573,7 +619,9 @@ OK''' % cookietmp.name)
self._wait(d)
try:
- self.protocol.add_event_listener('SOMETHING_INVALID', lambda _: None)
+ self.protocol.add_event_listener(
+ 'SOMETHING_INVALID', lambda _: None
+ )
self.assertTrue(False)
except:
pass
@@ -629,19 +677,19 @@ OK''' % cookietmp.name)
self.assertEqual(self.transport.value(), 'SETEVENTS STREAM\r\n')
self.protocol.lineReceived("250 OK")
self.transport.clear()
- ## add another one, shouldn't issue a tor command
+ # add another one, shouldn't issue a tor command
self.protocol.add_event_listener('STREAM', listener1)
self.assertEqual(self.transport.value(), '')
- ## remove one, should still not issue a tor command
+ # remove one, should still not issue a tor command
self.protocol.remove_event_listener('STREAM', listener0)
self.assertEqual(self.transport.value(), '')
- ## remove the other one, NOW should issue a command
+ # remove the other one, NOW should issue a command
self.protocol.remove_event_listener('STREAM', listener1)
self.assertEqual(self.transport.value(), 'SETEVENTS \r\n')
- ## try removing invalid event
+ # try removing invalid event
try:
self.protocol.remove_event_listener('FOO', listener0)
self.fail()
@@ -666,8 +714,9 @@ OK''' % cookietmp.name)
def test_newdesc(self):
"""
- FIXME: this test is now maybe a little silly, it's just testing multiline GETINFO...
- (Real test is in TorStateTests.test_newdesc_parse)
+ FIXME: this test is now maybe a little silly, it's just testing
+ multiline GETINFO... (Real test is in
+ TorStateTests.test_newdesc_parse)
"""
self.protocol.get_info_raw('ns/id/624926802351575FF7E4E3D60EFA3BFB56E67E8A')
@@ -694,7 +743,8 @@ p accept 43,53,79-81,110,143,194,220,443,953,989-990,993,995,1194,1293,1723,1863
def test_minus_line_no_command(self):
"""
- haven't seen 600's use - "in the wild" but don't see why it's not possible
+ haven't seen 600's use - "in the wild" but don't see why it's not
+ possible
"""
self.protocol._set_valid_events('NS')
self.protocol.add_event_listener('NS', lambda _: None)
@@ -798,7 +848,7 @@ r Unnamed AHe2V2pmj4Yfn0H9+Np3lci7htU T/g7ZLzG/ooqCn+gdLd9Jjh+AEI 2011-12-02 15:
s Exit Fast Running V2Dir Valid
w Bandwidth=33
p reject 25,119,135-139,445,563,1214,4661-4666,6346-6429,6699,6881-6999""")
- ## the routers list is always keyed with both name and hash
+ # the routers list is always keyed with both name and hash
self.assertEqual(len(self.controller.routers_by_name), 2)
self.assertEqual(len(self.controller.routers_by_hash), 2)
self.assertTrue('right2privassy3' in self.controller.routers)
diff --git a/test/test_torinfo.py b/test/test_torinfo.py
index 19539e1..573a2d1 100644
--- a/test/test_torinfo.py
+++ b/test/test_torinfo.py
@@ -68,17 +68,18 @@ class ProtocolIntegrationTests(unittest.TestCase):
info = TorInfo(self.protocol)
pb = info.post_bootstrap
- ## now we hook up the protocol like it connected to a real Tor
+ # now we hook up the protocol like it connected to a real Tor
self.protocol.makeConnection(self.transport)
- ## answer all the requests generated by TorControlProtocol boostrapping etc.
+ # answer all the requests generated by TorControlProtocol
+ # boostrapping etc.
self.send('250-AUTH METHODS=PASSWORD')
self.send('250 OK')
- ## response to AUTHENTICATE
+ # response to AUTHENTICATE
self.send('250 OK')
- ## now we're in _bootstrap() in TorControlProtocol()
+ # now we're in _bootstrap() in TorControlProtocol()
self.send("250-version=foo")
self.send("250 OK")
@@ -87,24 +88,26 @@ class ProtocolIntegrationTests(unittest.TestCase):
self.send("250 OK") # for USEFEATURE
- ## do the TorInfo magic
+ # do the TorInfo magic
self.send('250-info/names=')
self.send('250-multi/path/arg/* a documentation string')
self.send('250 OK')
- ## we had to save this up above due to the "interesting" way
- ## TorInfo switches to become a possible-nice magic thingy
- ## that does attribute-access for you.
+ # we had to save this up above due to the "interesting" way
+ # TorInfo switches to become a possible-nice magic thingy
+ # that does attribute-access for you.
yield pb
self.assertTrue(hasattr(info, 'multi'))
self.assertTrue(hasattr(getattr(info, 'multi'), 'path'))
- self.assertTrue(hasattr(getattr(getattr(info, 'multi'), 'path'), 'arg'))
+ self.assertTrue(
+ hasattr(getattr(getattr(info, 'multi'), 'path'), 'arg')
+ )
- ## Finally! The test! We see if we can get this multi-path
- ## value with an argument...
- ## a "real" tor example is "net/listeners/socks" which shows
- ## up in info/names as "net/listeners/*"
+ # Finally! The test! We see if we can get this multi-path
+ # value with an argument...
+ # a "real" tor example is "net/listeners/socks" which shows
+ # up in info/names as "net/listeners/*"
d = info.multi.path.arg('quux')
d.addCallback(CheckAnswer(self, 'foo'))
@@ -243,10 +246,13 @@ multi/path/arg/* a documentation string
info = TorInfo(self.protocol)
self.assertTrue(hasattr(info, 'multi'))
self.assertTrue(hasattr(getattr(info, 'multi'), 'path'))
- self.assertTrue(hasattr(getattr(getattr(info, 'multi'), 'path'), 'arg'))
+ self.assertTrue(
+ hasattr(getattr(getattr(info, 'multi'), 'path'), 'arg')
+ )
- ## FIXME should have a test that "really" goes out through TorControlProtocol instance for this stuff...
- ## TorControlProtocol now strips the OK line...
+ # FIXME should have a test that "really" goes out through
+ # TorControlProtocol instance for this stuff...
+ # TorControlProtocol now strips the OK line...
self.protocol.answers.append('multi/path/arg/quux=\nbar\nbaz\nquux')
try:
@@ -304,6 +310,6 @@ foo/* bar
''')
info = TorInfo(self.protocol)
- ## not the end of the world if this fails
+ # not the end of the world if this fails
self.assertTrue(str(info.version) == "version()")
self.assertTrue(str(info.foo) == "foo(arg)")
diff --git a/test/test_torstate.py b/test/test_torstate.py
index 4389b32..35b9097 100644
--- a/test/test_torstate.py
+++ b/test/test_torstate.py
@@ -8,8 +8,19 @@ from twisted.internet.interfaces import IStreamClientEndpoint, IReactorCore
import os
import tempfile
-from txtorcon import TorControlProtocol, TorProtocolError, TorState, Stream, Circuit, build_tor_connection, build_local_tor_connection
-from txtorcon.interface import ITorControlProtocol, IStreamAttacher, ICircuitListener, IStreamListener, StreamListenerMixin, CircuitListenerMixin
+from txtorcon import TorControlProtocol
+from txtorcon import TorProtocolError
+from txtorcon import TorState
+from txtorcon import Stream
+from txtorcon import Circuit
+from txtorcon import build_tor_connection
+from txtorcon import build_local_tor_connection
+from txtorcon.interface import ITorControlProtocol
+from txtorcon.interface import IStreamAttacher
+from txtorcon.interface import ICircuitListener
+from txtorcon.interface import IStreamListener
+from txtorcon.interface import StreamListenerMixin
+from txtorcon.interface import CircuitListenerMixin
class CircuitListener(object):
@@ -21,13 +32,21 @@ class CircuitListener(object):
def checker(self, state, circuit, arg=None):
if self.expected[0][0] != state:
- raise RuntimeError('Expected event "%s" not "%s".' % (self.expected[0][0], state))
+ raise RuntimeError(
+ 'Expected event "%s" not "%s".' %
+ (self.expected[0][0], state)
+ )
for (k, v) in self.expected[0][1].items():
if k == 'arg':
if v != arg:
- raise RuntimeError('Expected argument to have value "%s", not "%s"' % (arg, v))
+ raise RuntimeError(
+ 'Expected argument to have value "%s", not "%s"' % (arg, v)
+ )
elif getattr(circuit, k) != v:
- raise RuntimeError('Expected attribute "%s" to have value "%s", not "%s"' % (k, v, getattr(circuit, k)))
+ raise RuntimeError(
+ 'Expected attribute "%s" to have value "%s", not "%s"' %
+ (k, v, getattr(circuit, k))
+ )
self.expected = self.expected[1:]
def circuit_new(self, circuit):
@@ -58,13 +77,21 @@ class StreamListener(object):
def checker(self, state, stream, arg=None):
if self.expected[0][0] != state:
- raise RuntimeError('Expected event "%s" not "%s".' % (self.expected[0][0], state))
+ raise RuntimeError(
+ 'Expected event "%s" not "%s".' % (self.expected[0][0], state)
+ )
for (k, v) in self.expected[0][1].items():
if k == 'arg':
if v != arg:
- raise RuntimeError('Expected argument to have value "%s", not "%s"' % (arg, v))
+ raise RuntimeError(
+ 'Expected argument to have value "%s", not "%s"' %
+ (arg, v)
+ )
elif getattr(stream, k) != v:
- raise RuntimeError('Expected attribute "%s" to have value "%s", not "%s"' % (k, v, getattr(stream, k)))
+ raise RuntimeError(
+ 'Expected attribute "%s" to have value "%s", not "%s"' %
+ (k, v, getattr(stream, k))
+ )
self.expected = self.expected[1:]
def stream_new(self, stream):
@@ -119,7 +146,8 @@ class FakeEndpoint:
implements(IStreamClientEndpoint)
def get_info_raw(self, keys):
- return defer.succeed('\r\n'.join(map(lambda k: '%s=' % k, keys.split())))
+ ans = '\r\n'.join(map(lambda k: '%s=' % k, keys.split()))
+ return defer.succeed(ans)
def get_info_incremental(self, key, linecb):
linecb('%s=' % key)
@@ -130,7 +158,9 @@ class FakeEndpoint:
self.proto.transport = proto_helpers.StringTransport()
self.proto.get_info_raw = self.get_info_raw
self.proto.get_info_incremental = self.get_info_incremental
- self.proto._set_valid_events('GUARD STREAM CIRC NS NEWCONSENSUS ORCONN NEWDESC ADDRMAP STATUS_GENERAL')
+ self.proto._set_valid_events(
+ 'GUARD STREAM CIRC NS NEWCONSENSUS ORCONN NEWDESC ADDRMAP STATUS_GENERAL'
+ )
return defer.succeed(self.proto)
@@ -160,7 +190,9 @@ class FakeEndpointAnswers:
self.proto.transport = proto_helpers.StringTransport()
self.proto.get_info_raw = self.get_info_raw
self.proto.get_info_incremental = self.get_info_incremental
- self.proto._set_valid_events('GUARD STREAM CIRC NS NEWCONSENSUS ORCONN NEWDESC ADDRMAP STATUS_GENERAL')
+ self.proto._set_valid_events(
+ 'GUARD STREAM CIRC NS NEWCONSENSUS ORCONN NEWDESC ADDRMAP STATUS_GENERAL'
+ )
return defer.succeed(self.proto)
@@ -213,13 +245,21 @@ class BootstrapTests(unittest.TestCase):
return d
def test_build_unix_wrong_permissions(self):
- self.assertRaises(ValueError, build_tor_connection, (FakeReactor(self), 'a non-existant filename'))
+ self.assertRaises(
+ ValueError,
+ build_tor_connection,
+ (FakeReactor(self), 'a non-existant filename')
+ )
def test_build_wrong_size_tuple(self):
self.assertRaises(TypeError, build_tor_connection, (1, 2, 3, 4))
def test_build_wrong_args_entirely(self):
- self.assertRaises(TypeError, build_tor_connection, 'incorrect argument')
+ self.assertRaises(
+ TypeError,
+ build_tor_connection,
+ 'incorrect argument'
+ )
def confirm_pid(self, state):
self.assertEqual(state.tor_pid, 1234)
@@ -308,19 +348,28 @@ class StateTests(unittest.TestCase):
self.state._stream_update("76 CLOSED 0 www.example.com:0 REASON=DONE")
def test_stream_update(self):
- ## we use a circuit ID of 0 so it doesn't try to look anything up but it's
- ## not really correct to have a SUCCEEDED w/o a valid circuit, I don't think
+ # we use a circuit ID of 0 so it doesn't try to look anything
+ # up but it's not really correct to have a SUCCEEDED w/o a
+ # valid circuit, I don't think
self.state._stream_update('1610 SUCCEEDED 0 74.125.224.243:80')
self.assertTrue(1610 in self.state.streams)
def test_single_streams(self):
self.state.circuits[496] = FakeCircuit(496)
- self.state._stream_status('stream-status=123 SUCCEEDED 496 www.example.com:6667')
+ self.state._stream_status(
+ 'stream-status=123 SUCCEEDED 496 www.example.com:6667'
+ )
self.assertEqual(len(self.state.streams), 1)
def test_multiple_streams(self):
self.state.circuits[496] = FakeCircuit(496)
- self.state._stream_status('stream-status=\r\n123 SUCCEEDED 496 www.example.com:6667\r\n124 SUCCEEDED 496 www.example.com:6667')
+ self.state._stream_status(
+ '\r\n'.join([
+ 'stream-status=',
+ '123 SUCCEEDED 496 www.example.com:6667',
+ '124 SUCCEEDED 496 www.example.com:6667',
+ ])
+ )
self.assertEqual(len(self.state.streams), 2)
def send(self, line):
@@ -365,9 +414,9 @@ class StateTests(unittest.TestCase):
self.send(".")
self.send("250 OK")
- ## implicitly created Router object for the $1111...11 lookup
- ## but 0.0.0.0 will have to country, so Router will ask Tor
- ## for one via GETINFO ip-to-country
+ # implicitly created Router object for the $1111...11 lookup
+ # but 0.0.0.0 will have to country, so Router will ask Tor
+ # for one via GETINFO ip-to-country
self.send("250-ip-to-country/0.0.0.0=??")
self.send("250 OK")
@@ -480,7 +529,11 @@ class StateTests(unittest.TestCase):
self.send("250 OK")
self.state.set_attacher(None, fr)
self.send("250 OK")
- self.assertEqual(self.transport.value(), 'SETCONF __LeaveStreamsUnattached=1\r\nSETCONF __LeaveStreamsUnattached=0\r\n')
+ self.assertEqual(
+ self.transport.value(),
+ 'SETCONF __LeaveStreamsUnattached=1\r\nSETCONF'
+ ' __LeaveStreamsUnattached=0\r\n'
+ )
def test_attacher(self):
class MyAttacher(object):
@@ -548,8 +601,8 @@ class StateTests(unittest.TestCase):
attacher = MyAttacher(self.state.circuits[1])
self.state.set_attacher(attacher, FakeReactor(self))
- ## boilerplate to finish enough set-up in the protocol so it
- ## works
+ # boilerplate to finish enough set-up in the protocol so it
+ # works
events = 'GUARD STREAM CIRC NS NEWCONSENSUS ORCONN NEWDESC ADDRMAP STATUS_GENERAL'
self.protocol._set_valid_events(events)
self.state._add_events()
@@ -642,7 +695,12 @@ class StateTests(unittest.TestCase):
stream = Stream(self.state)
stream.id = 1
self.state.streams[1] = stream
- self.assertRaises(ValueError, self.state.close_stream, stream, 'FOO_INVALID_REASON')
+ self.assertRaises(
+ ValueError,
+ self.state.close_stream,
+ stream,
+ 'FOO_INVALID_REASON'
+ )
def test_close_circuit_with_id(self):
circuit = Circuit(self.state)
@@ -694,7 +752,7 @@ class StateTests(unittest.TestCase):
for ignored in self.state.event_map.items():
self.send("250 OK")
- ## we use this router later on in an EXTEND
+ # we use this router later on in an EXTEND
self.state._update_network_status("""ns/all=
r PPrivCom012 2CGDscCeHXeV/y1xFrq1EGqj5g4 QX7NVLwx7pwCuk6s8sxB4rdaCKI 2011-12-20 08:34:19 84.19.178.6 9001 0
s Fast Guard Running Stable Unnamed Valid
@@ -706,22 +764,22 @@ p reject 1-65535""")
('extend', {'id': 123})
]
listen = CircuitListener(expected)
- ## first add a Circuit before we listen
+ # first add a Circuit before we listen
self.protocol.dataReceived("650 CIRC 123 LAUNCHED PURPOSE=GENERAL\r\n")
self.assertEqual(len(self.state.circuits), 1)
- ## make sure we get added to existing circuits
+ # make sure we get added to existing circuits
self.state.add_circuit_listener(listen)
self.assertTrue(listen in self.state.circuits.values()[0].listeners)
- ## now add a Circuit after we started listening
+ # now add a Circuit after we started listening
self.protocol.dataReceived("650 CIRC 456 LAUNCHED PURPOSE=GENERAL\r\n")
self.assertEqual(len(self.state.circuits), 2)
self.assertTrue(listen in self.state.circuits.values()[0].listeners)
self.assertTrue(listen in self.state.circuits.values()[1].listeners)
- ## now update the first Circuit to ensure we're really, really
- ## listening
+ # now update the first Circuit to ensure we're really, really
+ # listening
self.protocol.dataReceived("650 CIRC 123 EXTENDED $D82183B1C09E1D7795FF2D7116BAB5106AA3E60E~PPrivCom012 PURPOSE=GENERAL\r\n")
self.assertEqual(len(listen.expected), 0)
@@ -829,7 +887,7 @@ p accept 43,53
self.assertEqual(r.bandwidth, 518000)
self.assertEqual(len(self.state.routers_by_name['fake']), 2)
- ## now we do an update
+ # now we do an update
self.state._update_network_status('''ns/all=
r fake YkkmgCNRV1/35OPWDvo7+1bmfoo tanLV/4ZfzpYQW0xtGFqAa46foo 2011-12-12 16:29:16 12.45.56.78 443 80
s Exit Fast Guard HSDir Named Running Stable V2Dir Valid FutureProof Authority
@@ -850,8 +908,8 @@ p accept 43,53,79-81,110,143,194,220,443,953,989-990,993,995,1194,1293,1723,1863
errors.
"""
- ## bootstrap the TorState so we can send it a "real" 650
- ## update
+ # bootstrap the TorState so we can send it a "real" 650
+ # update
self.protocol._set_valid_events(' '.join(self.state.event_map.keys()))
self.state._bootstrap()
@@ -878,7 +936,7 @@ p accept 43,53,79-81,110,143,194,220,443,953,989-990,993,995,1194,1293,1723,1863
self.send("250 OK")
- ## state is now bootstrapped, we can send our NEWCONSENSUS update
+ # state is now bootstrapped, we can send our NEWCONSENSUS update
self.protocol.dataReceived('\r\n'.join('''650+NEWCONSENSUS
r Unnamed ABJlguUFz1lvQS0jq8nhTdRiXEk /zIVUg1tKMUeyUBoyimzorbQN9E 2012-05-23 01:10:22 219.94.255.254 9001 0
@@ -907,8 +965,8 @@ p reject 1-65535
errors.
"""
- ## bootstrap the TorState so we can send it a "real" 650
- ## update
+ # bootstrap the TorState so we can send it a "real" 650
+ # update
self.protocol._set_valid_events(' '.join(self.state.event_map.keys()))
self.state._bootstrap()
@@ -935,7 +993,7 @@ p reject 1-65535
self.send("250 OK")
- ## state is now bootstrapped, we can send our NEWCONSENSUS update
+ # state is now bootstrapped, we can send our NEWCONSENSUS update
self.protocol.dataReceived('\r\n'.join('''650+NEWCONSENSUS
r Unnamed ABJlguUFz1lvQS0jq8nhTdRiXEk /zIVUg1tKMUeyUBoyimzorbQN9E 2012-05-23 01:10:22 219.94.255.254 9001 0
@@ -954,8 +1012,8 @@ w Bandwidth=166
errors.
"""
- ## bootstrap the TorState so we can send it a "real" 650
- ## update
+ # bootstrap the TorState so we can send it a "real" 650
+ # update
self.protocol._set_valid_events(' '.join(self.state.event_map.keys()))
self.state._bootstrap()
@@ -982,7 +1040,7 @@ w Bandwidth=166
self.send("250 OK")
- ## state is now bootstrapped, we can send our NEWCONSENSUS update
+ # state is now bootstrapped, we can send our NEWCONSENSUS update
self.protocol.dataReceived('\r\n'.join('''650+NEWCONSENSUS
r Unnamed ABJlguUFz1lvQS0jq8nhTdRiXEk /zIVUg1tKMUeyUBoyimzorbQN9E 2012-05-23 01:10:22 219.94.255.254 9001 0
@@ -1046,14 +1104,14 @@ s Fast Guard Running Stable Valid
path = []
for x in range(3):
path.append(FakeRouter("$%040d" % x))
- ## can't just check flags for guard status, need to know if
- ## it's in the running Tor's notion of Entry Guards
+ # can't just check flags for guard status, need to know if
+ # it's in the running Tor's notion of Entry Guards
path[0].flags = ['guard']
self.state.build_circuit(path, using_guards=True)
self.assertEqual(self.transport.value(), 'EXTENDCIRCUIT 0 0000000000000000000000000000000000000000,0000000000000000000000000000000000000001,0000000000000000000000000000000000000002\r\n')
- ## should have gotten a warning about this not being an entry
- ## guard
+ # should have gotten a warning about this not being an entry
+ # guard
self.assertEqual(len(self.flushWarnings()), 1)
def test_build_circuit_no_routers(self):
@@ -1077,19 +1135,19 @@ s Fast Guard Running Stable Valid
path = []
for x in range(3):
path.append(FakeRouter("$%040d" % x))
- ## can't just check flags for guard status, need to know if
- ## it's in the running Tor's notion of Entry Guards
+ # can't just check flags for guard status, need to know if
+ # it's in the running Tor's notion of Entry Guards
path[0].flags = ['guard']
- ## FIXME TODO we should verify we get a circuit_new event for
- ## this circuit
+ # FIXME TODO we should verify we get a circuit_new event for
+ # this circuit
d = self.state.build_circuit(path, using_guards=True)
d.addCallback(self.circuit_callback)
self.assertEqual(self.transport.value(), 'EXTENDCIRCUIT 0 0000000000000000000000000000000000000000,0000000000000000000000000000000000000001,0000000000000000000000000000000000000002\r\n')
self.send('250 EXTENDED 1234')
- ## should have gotten a warning about this not being an entry
- ## guard
+ # should have gotten a warning about this not being an entry
+ # guard
self.assertEqual(len(self.flushWarnings()), 1)
return d
diff --git a/test/test_util.py b/test/test_util.py
index e53a814..82c3d3a 100644
--- a/test/test_util.py
+++ b/test/test_util.py
@@ -5,7 +5,12 @@ from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet.interfaces import IProtocolFactory
from zope.interface import implements
-from txtorcon.util import process_from_address, delete_file_or_tree, find_keywords, ip_from_int, find_tor_binary, maybe_ip_addr
+from txtorcon.util import process_from_address
+from txtorcon.util import delete_file_or_tree
+from txtorcon.util import find_keywords
+from txtorcon.util import ip_from_int
+from txtorcon.util import find_tor_binary
+from txtorcon.util import maybe_ip_addr
import os
import tempfile
@@ -47,8 +52,10 @@ class TestFindKeywords(unittest.TestCase):
def test_filter(self):
"make sure we filter out keys that look like router IDs"
- self.assertEqual(find_keywords("foo=bar $1234567890=routername baz=quux".split()),
- {'foo': 'bar', 'baz': 'quux'})
+ self.assertEqual(
+ find_keywords("foo=bar $1234567890=routername baz=quux".split()),
+ {'foo': 'bar', 'baz': 'quux'}
+ )
class FakeGeoIP(object):
@@ -176,13 +183,14 @@ class TestProcessFromUtil(unittest.TestCase):
@defer.inlineCallbacks
def test_real_addr(self):
- ## FIXME should choose a port which definitely isn't used.
+ # FIXME should choose a port which definitely isn't used.
- ## it's apparently frowned upon to use the "real" reactor in
- ## tests, but I was using "nc" before, and I think this is
- ## preferable.
+ # it's apparently frowned upon to use the "real" reactor in
+ # tests, but I was using "nc" before, and I think this is
+ # preferable.
from twisted.internet import reactor
- listener = yield TCP4ServerEndpoint(reactor, 9887).listen(FakeProtocolFactory())
+ ep = TCP4ServerEndpoint(reactor, 9887)
+ listener = yield ep.listen(FakeProtocolFactory())
try:
pid = process_from_address('0.0.0.0', 9887, self.fakestate)
@@ -221,7 +229,7 @@ class TestDelete(unittest.TestCase):
class TestFindTor(unittest.TestCase):
def test_simple_find_tor(self):
- ## just test that this doesn't raise an exception
+ # just test that this doesn't raise an exception
find_tor_binary()
def test_find_tor_globs(self):
diff --git a/test/test_util_imports.py b/test/test_util_imports.py
index ed1f59f..77a2df1 100644
--- a/test/test_util_imports.py
+++ b/test/test_util_imports.py
@@ -7,7 +7,6 @@ from unittest import skipIf
def fake_import(orig, name, *args, **kw):
- ##print "IMPORTING", name
if name in ['GeoIP', 'ipaddr']:
raise ImportError('testing!')
return orig(*((name,) + args), **kw)
diff --git a/test/util.py b/test/util.py
index 8bf3653..c8e0858 100644
--- a/test/util.py
+++ b/test/util.py
@@ -5,9 +5,11 @@ import shutil
class TempDir(object):
'''
- This is a simple context manager that handles creating and cleaning up a tempdir.
+ This is a simple context manager that handles creating and
+ cleaning up a tempdir.
See also: https://gist.github.com/meejah/6430613
+
'''
def __enter__(self, *args):
diff --git a/txtorcon/__init__.py b/txtorcon/__init__.py
index 221cfee..0b5a7a1 100644
--- a/txtorcon/__init__.py
+++ b/txtorcon/__init__.py
@@ -1,5 +1,5 @@
-## for now, this needs to be changed in setup.py also until I find a
-## better solution
+# for now, this needs to be changed in setup.py also until I find a
+# better solution
__version__ = '0.12.0'
__author__ = 'meejah'
__contact__ = 'meejah at meejah.ca'
@@ -11,9 +11,18 @@ __copyright__ = 'Copyright 2012-2014'
from txtorcon.router import Router
from txtorcon.circuit import Circuit
from txtorcon.stream import Stream
-from txtorcon.torcontrolprotocol import TorControlProtocol, TorProtocolError, TorProtocolFactory, DEFAULT_VALUE
-from txtorcon.torstate import TorState, build_tor_connection, build_local_tor_connection
-from txtorcon.torconfig import TorConfig, HiddenService, TorProcessProtocol, launch_tor, TorNotFound
+from txtorcon.torcontrolprotocol import TorControlProtocol
+from txtorcon.torcontrolprotocol import TorProtocolError
+from txtorcon.torcontrolprotocol import TorProtocolFactory
+from txtorcon.torcontrolprotocol import DEFAULT_VALUE
+from txtorcon.torstate import TorState
+from txtorcon.torstate import build_tor_connection
+from txtorcon.torstate import build_local_tor_connection
+from txtorcon.torconfig import TorConfig
+from txtorcon.torconfig import HiddenService
+from txtorcon.torconfig import TorProcessProtocol
+from txtorcon.torconfig import launch_tor
+from txtorcon.torconfig import TorNotFound
from txtorcon.torinfo import TorInfo
from txtorcon.addrmap import AddrMap
from txtorcon.endpoints import TorOnionAddress
@@ -33,8 +42,8 @@ __all__ = ["Router",
"TorControlProtocol", "TorProtocolError", "TorProtocolFactory",
"TorState", "DEFAULT_VALUE",
"TorInfo",
- "build_tor_connection", "build_local_tor_connection", "launch_tor", "TorNotFound",
- "TorConfig", "HiddenService", "TorProcessProtocol",
+ "build_tor_connection", "build_local_tor_connection", "launch_tor",
+ "TorNotFound", "TorConfig", "HiddenService", "TorProcessProtocol",
"TorInfo",
"TCPHiddenServiceEndpoint", "TCPHiddenServiceEndpointParser",
"IHiddenService", "IProgressProvider",
@@ -46,5 +55,6 @@ __all__ = ["Router",
"ITorControlProtocol",
"IStreamListener", "IStreamAttacher", "StreamListenerMixin",
"ICircuitContainer", "ICircuitListener", "CircuitListenerMixin",
- "IRouterContainer", "IAddrListener", "IProgressProvider", "IHiddenService",
+ "IRouterContainer", "IAddrListener", "IProgressProvider",
+ "IHiddenService",
]
diff --git a/txtorcon/addrmap.py b/txtorcon/addrmap.py
index ef869f9..ec7c61a 100644
--- a/txtorcon/addrmap.py
+++ b/txtorcon/addrmap.py
@@ -57,13 +57,13 @@ class Addr(object):
fmt = "%Y-%m-%d %H:%M:%S"
- ## if we already have expiry times, etc then we want to
- ## properly delay our timeout
+ # if we already have expiry times, etc then we want to
+ # properly delay our timeout
oldexpires = self.expires
if gmtexpires.upper() == 'NEVER':
- ## FIXME can I just select a date 100 years in the future instead?
+ # FIXME can I just select a date 100 years in the future instead?
self.expires = None
else:
self.expires = datetime.datetime.strptime(gmtexpires, fmt)
diff --git a/txtorcon/circuit.py b/txtorcon/circuit.py
index 2228381..8f954f8 100644
--- a/txtorcon/circuit.py
+++ b/txtorcon/circuit.py
@@ -7,7 +7,7 @@ from interface import IRouterContainer
from txtorcon.util import find_keywords
-#look like "2014-01-25T02:12:14.593772"
+# look like "2014-01-25T02:12:14.593772"
TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
@@ -77,11 +77,11 @@ class Circuit(object):
self.build_flags = []
self.flags = {}
- ## this is used to hold a Deferred that will callback() when
- ## this circuit is being CLOSED or FAILED.
+ # this is used to hold a Deferred that will callback() when
+ # this circuit is being CLOSED or FAILED.
self._closing_deferred = None
- ## caches parsed value for time_created()
+ # caches parsed value for time_created()
self._time_created = None
@property
@@ -89,7 +89,7 @@ class Circuit(object):
if self._time_created is not None:
return self._time_created
if 'TIME_CREATED' in self.flags:
- ## strip off milliseconds
+ # strip off milliseconds
t = self.flags['TIME_CREATED'].split('.')[0]
tstruct = time.strptime(t, TIME_FORMAT)
self._time_created = datetime.datetime(*tstruct[:7])
@@ -150,7 +150,7 @@ class Circuit(object):
return flags
def update(self, args):
- ##print "Circuit.update:",args
+ # print "Circuit.update:",args
if self.id is None:
self.id = int(args[0])
[x.circuit_new(self) for x in self.listeners]
@@ -180,9 +180,9 @@ class Circuit(object):
elif self.state == 'CLOSED':
if len(self.streams) > 0:
- ## FIXME it seems this can/does happen if a remote
- ## router crashes or otherwise shuts down a circuit
- ## with streams on it still
+ # FIXME it seems this can/does happen if a remote
+ # router crashes or otherwise shuts down a circuit
+ # with streams on it still
log.err(RuntimeError("Circuit is %s but still has %d streams" %
(self.state, len(self.streams))))
flags = self._create_flags(kw)
@@ -228,8 +228,8 @@ class Circuit(object):
if p[0] != '$':
break
- ## this will create a Router if we give it a router
- ## LongName that doesn't yet exist
+ # this will create a Router if we give it a router
+ # LongName that doesn't yet exist
router = self.router_container.router_from_id(p)
self.path.append(router)
diff --git a/txtorcon/endpoints.py b/txtorcon/endpoints.py
index e2e5619..7703bf1 100644
--- a/txtorcon/endpoints.py
+++ b/txtorcon/endpoints.py
@@ -385,7 +385,10 @@ class TCPHiddenServiceEndpoint(object):
# specifically NOT creating the hidden-service dir; letting
# Tor do it will more-likely result in a usable situation...
if not os.path.exists(self.hidden_service_dir):
- log.msg('Noting that "%s" does not exist; letting Tor create it.' % self.hidden_service_dir)
+ log.msg(
+ 'Noting that "%s" does not exist; letting Tor create it.' %
+ self.hidden_service_dir
+ )
# listen for the descriptor upload event
info_callback = defer.Deferred()
diff --git a/txtorcon/interface.py b/txtorcon/interface.py
index 91ebb91..8ccfded 100644
--- a/txtorcon/interface.py
+++ b/txtorcon/interface.py
@@ -141,8 +141,8 @@ class ICircuitContainer(Interface):
is started (not necessarily finished inside Tor).
"""
- ## FIXME do we need an IStreamContainer that Stream instances get?
- ## (Currently, they get an ICircuitContainer...)
+ # FIXME do we need an IStreamContainer that Stream instances get?
+ # (Currently, they get an ICircuitContainer...)
def close_stream(stream, **kwargs):
"""
Close a stream.
@@ -175,7 +175,8 @@ class ICircuitListener(Interface):
def circuit_closed(circuit, **kw):
"""
- A circuit has been closed cleanly (won't be in controller's list any more).
+ A circuit has been closed cleanly (won't be in controller's list
+ any more).
:param kw:
A dict of additional args. REASON is alsways included, and
@@ -192,6 +193,7 @@ class ICircuitListener(Interface):
remote_reason=None, **kw)) lower-case versions of all the
keys are also provided (pointing to the same -- usually
UPPERCASE -- strings as the upper-case keys).
+
"""
def circuit_failed(circuit, **kw):
diff --git a/txtorcon/spaghetti.py b/txtorcon/spaghetti.py
index 173cac6..0bbaddb 100644
--- a/txtorcon/spaghetti.py
+++ b/txtorcon/spaghetti.py
@@ -22,18 +22,16 @@ class FSM(object):
self.states = states
def process(self, data):
- #print self,"process",data
if self.state is None:
raise RuntimeError("There is no initial state.")
next_state = self.state.process(data)
if next_state:
- #print "changing to",next_state.name,next_state
self.state = next_state
else:
warnings.warn("No next state", RuntimeWarning)
def add_state(self, state):
- ## first added state is initial state
+ # first added state is initial state
if len(self.states) == 0:
self.state = state
self.states.append(state)
@@ -52,7 +50,6 @@ class State(object):
self.transitions = []
def process(self, data):
- #print self.name,"process",data
for t in self.transitions:
r = t.process(data)
if r is not None:
@@ -94,7 +91,6 @@ class Transition(object):
self.next_state = next_state
if self.next_state is None:
raise RuntimeError("next_state must be valid")
- #print self,self.matcher,self.handler
def match(self, data):
"""
@@ -102,7 +98,6 @@ class Transition(object):
data by default. may override instead of providing a matcher
methdo to ctor.
"""
- #print self,"match",data,self.matcher
if self.matcher is not None:
return self.matcher(data)
return True
@@ -114,7 +109,6 @@ class Transition(object):
"""
if self.handler:
state = self.handler(data)
- #print "got",state
if state is None:
return self.next_state
return state
@@ -122,7 +116,6 @@ class Transition(object):
def process(self, data):
"""return next state, or None if not handled."""
- #print self,"process",data
if self.match(data):
return self.handle(data)
return None
diff --git a/txtorcon/stream.py b/txtorcon/stream.py
index 4f3b933..dc31590 100644
--- a/txtorcon/stream.py
+++ b/txtorcon/stream.py
@@ -58,10 +58,10 @@ class Stream(object):
self.circuit_container = ICircuitContainer(circuitcontainer)
- ## FIXME: Sphinx doesn't seem to understand these variable
- ## docstrings, so consolidate with above if Sphinx is the
- ## answer -- actually it does, so long as the :ivar: things
- ## are never mentioned it seems.
+ # FIXME: Sphinx doesn't seem to understand these variable
+ # docstrings, so consolidate with above if Sphinx is the
+ # answer -- actually it does, so long as the :ivar: things
+ # are never mentioned it seems.
self.id = None
"""An int, Tor's ID for this :class:`txtorcon.Circuit`"""
@@ -146,7 +146,10 @@ class Stream(object):
return self._closing_deferred
def _create_flags(self, kw):
- "this clones the kw dict, adding a lower-case version of every key (duplicated in circuit.py; consider putting in util?)"
+ """
+ this clones the kw dict, adding a lower-case version of every key
+ (duplicated in circuit.py; consider putting in util?)
+ """
flags = {}
for k in kw.keys():
@@ -155,7 +158,7 @@ class Stream(object):
return flags
def update(self, args):
- ## print "update",self.id,args
+ # print "update",self.id,args
if self.id is None:
self.id = int(args[0])
@@ -217,8 +220,8 @@ class Stream(object):
self.circuit.streams.remove(self)
self.circuit = None
- ## FIXME does this count as closed?
- ##self.maybe_call_closing_deferred()
+ # FIXME does this count as closed?
+ # self.maybe_call_closing_deferred()
flags = self._create_flags(kw)
[x.stream_detach(self, **flags) for x in self.listeners]
@@ -243,11 +246,17 @@ class Stream(object):
self.circuit = self.circuit_container.find_circuit(cid)
if self not in self.circuit.streams:
self.circuit.streams.append(self)
- [x.stream_attach(self, self.circuit) for x in self.listeners]
+ for x in self.listeners:
+ x.stream_attach(self, self.circuit)
else:
if self.circuit.id != cid:
- log.err(RuntimeError('Circuit ID changed from %d to %d.' % (self.circuit.id, cid)))
+ log.err(
+ RuntimeError(
+ 'Circuit ID changed from %d to %d.' %
+ (self.circuit.id, cid)
+ )
+ )
def maybe_call_closing_deferred(self):
"""
diff --git a/txtorcon/torconfig.py b/txtorcon/torconfig.py
index e46166b..389837f 100644
--- a/txtorcon/torconfig.py
+++ b/txtorcon/torconfig.py
@@ -212,7 +212,7 @@ class TorProcessProtocol(protocol.ProcessProtocol):
if self.progress_updates:
self.progress_updates(percent, tag, summary)
- ## the below are all callbacks
+ # the below are all callbacks
def tor_connection_failed(self, failure):
# FIXME more robust error-handling please, like a timeout so
@@ -257,8 +257,8 @@ class TorProcessProtocol(protocol.ProcessProtocol):
self.tor_protocol.add_event_listener(
'STATUS_CLIENT', self.status_client)
- ## FIXME: should really listen for these to complete as well
- ## as bootstrap etc. For now, we'll be optimistic.
+ # FIXME: should really listen for these to complete as well
+ # as bootstrap etc. For now, we'll be optimistic.
self.tor_protocol.queue_command('TAKEOWNERSHIP')
self.tor_protocol.queue_command('RESETCONF __OwningControllerProcess')
@@ -356,19 +356,19 @@ def launch_tor(config, reactor,
the time, so FIXME look at Tor source.
"""
- ## We have a slight problem with the approach: we need to pass a
- ## few minimum values to a torrc file so that Tor will start up
- ## enough that we may connect to it. Ideally, we'd be able to
- ## start a Tor up which doesn't really do anything except provide
- ## "AUTHENTICATE" and "GETINFO config/names" so we can do our
- ## config validation.
+ # We have a slight problem with the approach: we need to pass a
+ # few minimum values to a torrc file so that Tor will start up
+ # enough that we may connect to it. Ideally, we'd be able to
+ # start a Tor up which doesn't really do anything except provide
+ # "AUTHENTICATE" and "GETINFO config/names" so we can do our
+ # config validation.
- ## the other option here is to simply write a torrc version of our
- ## config and get Tor to load that...which might be the best
- ## option anyway.
+ # the other option here is to simply write a torrc version of our
+ # config and get Tor to load that...which might be the best
+ # option anyway.
- ## actually, can't we pass them all as command-line arguments?
- ## could be pushing some limits for giant configs...
+ # actually, can't we pass them all as command-line arguments?
+ # could be pushing some limits for giant configs...
if tor_binary is None:
tor_binary = find_tor_binary()
@@ -527,7 +527,7 @@ class TimeInterval(Integer):
pass
-## not actually used?
+# not actually used?
class TimeMsecInterval(TorConfigType):
pass
@@ -541,7 +541,7 @@ class Float(TorConfigType):
return float(s)
-## unused also?
+# unused also?
class Time(TorConfigType):
pass
@@ -558,7 +558,7 @@ class TimeIntervalCommaList(CommaList):
pass
-## FIXME: is this really a comma-list?
+# FIXME: is this really a comma-list?
class RouterList(CommaList):
pass
@@ -650,7 +650,8 @@ class HiddenService(object):
127.0.0.1:1234']))
"""
- def __init__(self, config, thedir, ports, auth=None, ver=2, group_readable=0):
+ def __init__(self, config, thedir, ports,
+ auth=None, ver=2, group_readable=0):
"""
config is the TorConfig to which this will belong (FIXME,
can't we make this automatic somehow?), thedir corresponds to
@@ -707,14 +708,17 @@ class HiddenService(object):
"""
rtn = [('HiddenServiceDir', str(self.dir))]
- if self.conf._supports['HiddenServiceDirGroupReadable'] and self.group_readable:
+ if self.conf._supports['HiddenServiceDirGroupReadable'] \
+ and self.group_readable:
rtn.append(('HiddenServiceDirGroupReadable', str(1)))
for x in self.ports:
rtn.append(('HiddenServicePort', str(x)))
if self.version:
rtn.append(('HiddenServiceVersion', str(self.version)))
if self.authorize_client:
- rtn.append(('HiddenServiceAuthorizeClient', str(self.authorize_client)))
+ rtn.append(
+ ('HiddenServiceAuthorizeClient', str(self.authorize_client))
+ )
return rtn
@@ -876,7 +880,7 @@ class TorConfig(object):
def __getattr__(self, name):
"""
- on purpose, we don't return self.saved if the key is in there
+ on purpose, we don't return self.unsaved if the key is in there
because I want the config to represent the running Tor not
``things which might get into the running Tor if save() were
to be called''
@@ -934,8 +938,8 @@ class TorConfig(object):
conf = parse_keywords(arg, multiline_values=False)
for (k, v) in conf.items():
- ## v will be txtorcon.DEFAULT_VALUE already from
- ## parse_keywords if it was unspecified
+ # v will be txtorcon.DEFAULT_VALUE already from
+ # parse_keywords if it was unspecified
self.config[self._find_real_name(k)] = v
def bootstrap(self, arg=None):
@@ -947,8 +951,8 @@ class TorConfig(object):
self.protocol.add_event_listener(
'CONF_CHANGED', self._conf_changed)
except RuntimeError:
- ## for Tor versions which don't understand CONF_CHANGED
- ## there's nothing we can really do.
+ # for Tor versions which don't understand CONF_CHANGED
+ # there's nothing we can really do.
log.msg(
"Can't listen for CONF_CHANGED event; won't stay up-to-date "
"with other clients.")
@@ -1007,9 +1011,9 @@ class TorConfig(object):
# update then, right?
self.config[self._find_real_name(key)] = value
- ## FIXME might want to re-think this, but currently there's no
- ## way to put things into a config and get them out again
- ## nicely...unless you just don't assign a protocol
+ # FIXME might want to re-think this, but currently there's no
+ # way to put things into a config and get them out again
+ # nicely...unless you just don't assign a protocol
if self.protocol:
d = self.protocol.set_conf(*args)
d.addCallback(self._save_completed)
@@ -1025,7 +1029,8 @@ class TorConfig(object):
return self
def _find_real_name(self, name):
- for x in self.__dict__['parsers'].keys() + self.__dict__['config'].keys():
+ keys = self.__dict__['parsers'].keys() + self.__dict__['config'].keys()
+ for x in keys:
if x.lower() == name.lower():
return x
return name
@@ -1041,7 +1046,7 @@ class TorConfig(object):
self._supports[name] = True
if name == 'HiddenServiceOptions':
- ## set up the "special-case" hidden service stuff
+ # set up the "special-case" hidden service stuff
servicelines = yield self.protocol.get_conf_raw(
'HiddenServiceOptions')
self._setup_hidden_services(servicelines)
@@ -1050,9 +1055,9 @@ class TorConfig(object):
if value == 'Dependant':
continue
- ## there's a thing called "Boolean+Auto" which is -1 for
- ## auto, 0 for false and 1 for true. could be nicer if it
- ## was called AutoBoolean or something, but...
+ # there's a thing called "Boolean+Auto" which is -1 for
+ # auto, 0 for false and 1 for true. could be nicer if it
+ # was called AutoBoolean or something, but...
value = value.replace('+', '_')
inst = None
@@ -1094,7 +1099,11 @@ class TorConfig(object):
k, v = line.split('=')
if k == 'HiddenServiceDir':
if directory is not None:
- hs.append(HiddenService(self, directory, ports, auth, ver, group_read))
+ hs.append(
+ HiddenService(
+ self, directory, ports, auth, ver, group_read
+ )
+ )
directory = v
ports = []
ver = None
diff --git a/txtorcon/torcontrolprotocol.py b/txtorcon/torcontrolprotocol.py
index 3c33423..cdd3930 100644
--- a/txtorcon/torcontrolprotocol.py
+++ b/txtorcon/torcontrolprotocol.py
@@ -102,7 +102,7 @@ class Event(object):
self.callbacks.remove(cb)
def got_update(self, data):
- #print self.name,"got_update:",data
+ # print self.name,"got_update:",data
for cb in self.callbacks:
cb(data)
@@ -134,7 +134,7 @@ def parse_keywords(lines, multiline_values=True):
rtn = {}
key = None
value = ''
- ## FIXME could use some refactoring to reduce code duplication!
+ # FIXME could use some refactoring to reduce code duplication!
for line in lines.split('\n'):
if line.strip() == 'OK':
continue
@@ -248,17 +248,17 @@ class TorControlProtocol(LineOnlyReceiver):
See the helper method :func:`txtorcon.build_tor_connection`.
"""
- ## variables related to the state machine
- self.defer = None # Deferred we returned for the current command
+ # variables related to the state machine
+ self.defer = None # Deferred we returned for the current command
self.response = ''
self.code = None
- self.command = None # currently processing this command
- self.commands = [] # queued commands
+ self.command = None # currently processing this command
+ self.commands = [] # queued commands
- ## Here we build up the state machine. Mostly it's pretty
- ## simply, confounded by the fact that 600's (notify) can come
- ## at any time AND can be multi-line itself. Luckily, these
- ## can't be nested, nor can the responses be interleaved.
+ # Here we build up the state machine. Mostly it's pretty
+ # simply, confounded by the fact that 600's (notify) can come
+ # at any time AND can be multi-line itself. Luckily, these
+ # can't be nested, nor can the responses be interleaved.
idle = State("IDLE")
recv = State("RECV")
@@ -294,8 +294,8 @@ class TorControlProtocol(LineOnlyReceiver):
self.fsm = FSM([recvnotify, idle, recvmulti, recv])
self.state_idle = idle
- ## hand-set initial state default start state is first in the
- ## list; the above looks nice in dotty though
+ # hand-set initial state default start state is first in the
+ # list; the above looks nice in dotty though
self.fsm.state = idle
self.stop_debug()
@@ -314,13 +314,14 @@ class TorControlProtocol(LineOnlyReceiver):
def graphviz_data(self):
return self.fsm.dotty()
- ## see end of file for all the state machine matcher and
- ## transition methods.
+ # see end of file for all the state machine matcher and
+ # transition methods.
def get_info_raw(self, *args):
"""
- Mostly for internal use; gives you the raw string back from
- the GETINFO command. See :meth:`getinfo <txtorcon.TorControlProtocol.get_info>`
+ Mostly for internal use; gives you the raw string back from the
+ GETINFO command. See :meth:`getinfo
+ <txtorcon.TorControlProtocol.get_info>`
"""
info = ' '.join(map(lambda x: str(x), list(args)))
return self.queue_command('GETINFO %s' % info)
@@ -338,8 +339,8 @@ class TorControlProtocol(LineOnlyReceiver):
line_cb(line)
return self.queue_command('GETINFO %s' % key, strip_ok_and_call)
- ## The following methods are the main TorController API and
- ## probably the most interesting for users.
+ # The following methods are the main TorController API and
+ # probably the most interesting for users.
def get_info(self, *args):
"""
@@ -384,7 +385,9 @@ class TorControlProtocol(LineOnlyReceiver):
otherwise.
"""
- return self.queue_command('GETCONF %s' % ' '.join(args)).addCallback(parse_keywords).addErrback(log.err)
+ d = self.queue_command('GETCONF %s' % ' '.join(args))
+ d.addCallback(parse_keywords).addErrback(log.err)
+ return d
def get_conf_raw(self, *args):
"""
@@ -522,9 +525,9 @@ class TorControlProtocol(LineOnlyReceiver):
self._maybe_issue_command()
return d
- ## the remaining methods are internal API implementations,
- ## callbacks and state-tracking methods -- you shouldn't have any
- ## need to call them.
+ # the remaining methods are internal API implementations,
+ # callbacks and state-tracking methods -- you shouldn't have any
+ # need to call them.
def lineReceived(self, line):
"""
@@ -538,7 +541,9 @@ class TorControlProtocol(LineOnlyReceiver):
def connectionMade(self):
"Protocol API"
txtorlog.msg('got connection, authenticating')
- self.protocolinfo().addCallback(self._do_authenticate).addErrback(self._auth_failed)
+ d = self.protocolinfo()
+ d.addCallback(self._do_authenticate)
+ d.addErrback(self._auth_failed)
def connectionLost(self, reason):
"Protocol API"
@@ -601,16 +606,23 @@ class TorControlProtocol(LineOnlyReceiver):
server_hash = base64.b16decode(kw['SERVERHASH'])
server_nonce = base64.b16decode(kw['SERVERNONCE'])
- ## FIXME put string in global. or something.
- expected_server_hash = hmac_sha256("Tor safe cookie authentication server-to-controller hash",
- self.cookie_data + self.client_nonce + server_nonce)
+ # FIXME put string in global. or something.
+ expected_server_hash = hmac_sha256(
+ "Tor safe cookie authentication server-to-controller hash",
+ self.cookie_data + self.client_nonce + server_nonce
+ )
if not compare_via_hash(expected_server_hash, server_hash):
- raise RuntimeError('Server hash not expected; wanted "%s" and got "%s".' % (base64.b16encode(expected_server_hash),
- base64.b16encode(server_hash)))
-
- client_hash = hmac_sha256("Tor safe cookie authentication controller-to-server hash",
- self.cookie_data + self.client_nonce + server_nonce)
+ raise RuntimeError(
+ 'Server hash not expected; wanted "%s" and got "%s".' %
+ (base64.b16encode(expected_server_hash),
+ base64.b16encode(server_hash))
+ )
+
+ client_hash = hmac_sha256(
+ "Tor safe cookie authentication controller-to-server hash",
+ self.cookie_data + self.client_nonce + server_nonce
+ )
client_hash_hex = base64.b16encode(client_hash)
return self.queue_command('AUTHENTICATE %s' % client_hash_hex)
@@ -626,19 +638,28 @@ class TorControlProtocol(LineOnlyReceiver):
kw = parse_keywords(line[5:].replace(' ', '\n'))
methods = kw['METHODS'].split(',')
if not methods:
- raise RuntimeError("Didn't find AUTH line in PROTOCOLINFO response.")
+ raise RuntimeError(
+ "Didn't find AUTH line in PROTOCOLINFO response."
+ )
if 'SAFECOOKIE' in methods:
cookie = re.search('COOKIEFILE="(.*)"', protoinfo).group(1)
self.cookie_data = open(cookie, 'r').read()
if len(self.cookie_data) != 32:
- raise RuntimeError("Expected authentication cookie to be 32 bytes, got %d" % len(self.cookie_data))
+ raise RuntimeError(
+ "Expected authentication cookie to be 32 bytes, got %d" %
+ len(self.cookie_data)
+ )
txtorlog.msg("Using SAFECOOKIE authentication", cookie,
len(self.cookie_data), "bytes")
self.client_nonce = os.urandom(32)
- d = self.queue_command('AUTHCHALLENGE SAFECOOKIE %s' % base64.b16encode(self.client_nonce))
- d.addCallback(self._safecookie_authchallenge).addCallback(self._bootstrap).addErrback(self._auth_failed)
+ cmd = 'AUTHCHALLENGE SAFECOOKIE ' + \
+ base64.b16encode(self.client_nonce)
+ d = self.queue_command(cmd)
+ d.addCallback(self._safecookie_authchallenge)
+ d.addCallback(self._bootstrap)
+ d.addErrback(self._auth_failed)
return
elif 'COOKIE' in methods:
@@ -646,22 +667,34 @@ class TorControlProtocol(LineOnlyReceiver):
with open(cookie, 'r') as cookiefile:
data = cookiefile.read()
if len(data) != 32:
- raise RuntimeError("Expected authentication cookie to be 32 bytes, got %d" % len(data))
- txtorlog.msg("Using COOKIE authentication", cookie, len(data), "bytes")
- self.authenticate(data).addCallback(self._bootstrap).addErrback(self._auth_failed)
+ raise RuntimeError(
+ "Expected authentication cookie to be 32 "
+ "bytes, got %d instead." % len(data)
+ )
+ txtorlog.msg("Using COOKIE authentication",
+ cookie, len(data), "bytes")
+ d = self.authenticate(data)
+ d.addCallback(self._bootstrap)
+ d.addErrback(self._auth_failed)
return
if self.password_function:
- passwd = defer.maybeDeferred(self.password_function)
- passwd.addCallback(self._do_password_authentication).addErrback(self._auth_failed)
+ d = defer.maybeDeferred(self.password_function)
+ d.addCallback(self._do_password_authentication)
+ d.addErrback(self._auth_failed)
return
- raise RuntimeError("The Tor I connected to doesn't support SAFECOOKIE nor COOKIE authentication and I have no password_function specified.")
+ raise RuntimeError(
+ "The Tor I connected to doesn't support SAFECOOKIE nor COOKIE"
+ " authentication and I have no password_function specified."
+ )
def _do_password_authentication(self, passwd):
if not passwd:
raise RuntimeError("No password available.")
- self.authenticate(passwd).addCallback(self._bootstrap).addErrback(self._auth_failed)
+ d = self.authenticate(passwd)
+ d.addCallback(self._bootstrap)
+ d.addErrback(self._auth_failed)
def _set_valid_events(self, events):
"used as a callback; see _bootstrap"
@@ -679,11 +712,13 @@ class TorControlProtocol(LineOnlyReceiver):
callback.
"""
- ## unfortunately I don't see a way to get this from the runing
- ## tor like the events...so this was taken from some version
- ## of the control-spec and must be kept up-to-date (or accpet
- ## any signal name and just wait for the reply?
- self.valid_signals = ["RELOAD", "DUMP", "DEBUG", "NEWNYM", "CLEARDNSCACHE"]
+ # unfortunately I don't see a way to get this from the runing
+ # tor like the events...so this was taken from some version
+ # of the control-spec and must be kept up-to-date (or accpet
+ # any signal name and just wait for the reply?
+ # FIXME XXX there is now "GETINFO signal/names"
+ self.valid_signals = ["RELOAD", "DUMP", "DEBUG", "NEWNYM",
+ "CLEARDNSCACHE"]
self.version = yield self.get_info('version')
self.version = self.version['version']
@@ -697,10 +732,8 @@ class TorControlProtocol(LineOnlyReceiver):
self.post_bootstrap.callback(self)
defer.returnValue(self)
- ##
- ## State Machine transitions and matchers. See the __init__ method
- ## for a way to output a GraphViz dot diagram of the machine.
- ##
+ # State Machine transitions and matchers. See the __init__ method
+ # for a way to output a GraphViz dot diagram of the machine.
def _is_end_line(self, line):
"for FSM"
@@ -718,7 +751,7 @@ class TorControlProtocol(LineOnlyReceiver):
return False
sl = len(line) > 3 and line[3] == ' '
- #print "single line?",line,sl
+ # print "single line?",line,sl
if sl:
self.code = code
return True
@@ -786,7 +819,8 @@ class TorControlProtocol(LineOnlyReceiver):
"for FSM"
# print "BCAST",line
if len(line) > 3:
- if self.code >= 200 and self.code < 300 and self.command and self.command[2] is not None:
+ if self.code >= 200 and self.code < 300 and \
+ self.command and self.command[2] is not None:
self.command[2](line[4:])
resp = ''
@@ -797,7 +831,9 @@ class TorControlProtocol(LineOnlyReceiver):
self.response = ''
if self.code >= 200 and self.code < 300:
if self.defer is None:
- raise RuntimeError('Got a response, but didn\'t issue a command: "%s"' % resp)
+ raise RuntimeError(
+ 'Got a response, but didn\'t issue a command: "%s"' % resp
+ )
if resp.endswith('\nOK'):
resp = resp[:-3]
self.defer.callback(resp)
@@ -811,9 +847,11 @@ class TorControlProtocol(LineOnlyReceiver):
elif self.code is None:
raise RuntimeError("No code set yet in broadcast response.")
else:
- raise RuntimeError("Unknown code in broadcast response %d." % self.code)
+ raise RuntimeError(
+ "Unknown code in broadcast response %d." % self.code
+ )
- ## note: we don't do this for 600-level responses
+ # note: we don't do this for 600-level responses
self.command = None
self.code = None
self.defer = None
diff --git a/txtorcon/torinfo.py b/txtorcon/torinfo.py
index a2395ed..3c930f4 100644
--- a/txtorcon/torinfo.py
+++ b/txtorcon/torinfo.py
@@ -76,13 +76,14 @@ class ConfigMethod(object):
n = self.info_key.replace('/', '.')
n = n.replace('-', '_')
s = '%s(%s)' % (n, 'arg' if self.takes_arg else '')
- #print s
return s
def __call__(self, *args):
if self.takes_arg:
if len(args) != 1:
- raise TypeError('"%s" takes exactly one argument' % self.info_key)
+ raise TypeError(
+ '"%s" takes exactly one argument' % self.info_key
+ )
req = '%s/%s' % (self.info_key, str(args[0]))
else:
@@ -92,11 +93,13 @@ class ConfigMethod(object):
req = self.info_key
def stripper(key, arg):
- ## strip "keyname="
- ## sometimes keyname= is followed by a newline, so the final .strip()
+ # strip "keyname="
+ # sometimes keyname= is followed by a newline, so final .strip()
return arg.strip()[len(key) + 1:].strip()
- return self.proto.get_info_raw(req).addCallback(functools.partial(stripper, req))
+ d = self.proto.get_info_raw(req)
+ d.addCallback(functools.partial(stripper, req))
+ return d
def __str__(self):
arg = ''
@@ -106,8 +109,7 @@ class ConfigMethod(object):
class TorInfo(object):
- """
- Implements some attribute magic over top of TorControlProtocol so
+ """Implements some attribute magic over top of TorControlProtocol so
that all the available GETINFO values are gettable in a little
easier fashion. Dashes are replaced by underscores (since dashes
aren't valid in method/attribute names for Python). Some of the
@@ -127,19 +129,21 @@ class TorInfo(object):
info.traffic.written().addCallback(cb)
info.ip_to_country('8.8.8.8').addCallback(cb)
- For interactive use -- or even checking things progammatically -- TorInfo
- pretends it only has attributes that coorespond to valid GETINFO calls.
- So for example, dir(info) will only return all the currently valid top-level
- things. In the above example this might be ['traffic', 'ip_to_country'] (of
- course in practice this is a much longer list). And "dir(info.traffic)" might
- return ['read', 'written']
+ For interactive use -- or even checking things progammatically --
+ TorInfo pretends it only has attributes that coorespond to valid
+ GETINFO calls. So for example, dir(info) will only return all the
+ currently valid top-level things. In the above example this might
+ be ['traffic', 'ip_to_country'] (of course in practice this is a
+ much longer list). And "dir(info.traffic)" might return ['read',
+ 'written']
+
+ For something similar to this for configuration (GETCONF, SETCONF)
+ see TorConfig which is quite a lot more complicated (internally)
+ since you can set config items.
- For something similar to this for configuration (GETCONF, SETCONF) see
- TorConfig which is quite a lot more complicated (internally) since you can set
- config items.
+ NOTE that 'GETINFO config/*' is not supported as it's the only
+ case that's not a leaf, but theoretically a method.
- NOTE that 'GETINFO config/*' is not supported as it's the only case that's not a
- leaf, but theoretically a method.
"""
def __init__(self, control, errback=None):
@@ -160,7 +164,7 @@ class TorInfo(object):
def _add_attribute(self, n, v):
self.attrs[n] = v
- ## iterator protocol
+ # iterator protocol
def __getitem__(self, idx):
sup = super(TorInfo, self)
@@ -174,7 +178,7 @@ class TorInfo(object):
return len(object.__getattribute__(self, 'attrs'))
raise TypeError("No length until we're setup.")
- ## change our attribute behavior based on the value of _setup
+ # change our attribute behavior based on the value of _setup
def __dir__(self):
sup = super(TorInfo, self)
@@ -202,7 +206,8 @@ class TorInfo(object):
raise AttributeError(name)
def bootstrap(self, *args):
- d = self.protocol.get_info_raw("info/names").addCallback(self._do_setup)
+ d = self.protocol.get_info_raw("info/names")
+ d.addCallback(self._do_setup)
if self.errback:
d.addErrback(self.errback)
d.addCallback(self._setup_complete)
@@ -213,26 +218,26 @@ class TorInfo(object):
x.dump('')
def _do_setup(self, data):
- # FIXME figure out why network-status doesn't work (get nothing back from
- # Tor it seems, although stem does get an answer). this is a space-separated
- # list of ~2500 OR id's; could it be that LineReceiver can't handle it?
+ # FIXME figure out why network-status doesn't work (get
+ # nothing back from Tor it seems, although stem does get an
+ # answer). this is a space-separated list of ~2500 OR id's;
+ # could it be that LineReceiver can't handle it?
added_magic = []
for line in data.split('\n'):
if line == "info/names=" or line.strip() == '':
continue
- #print "LINE:",line
(name, documentation) = line.split(' ', 1)
- ## FIXME think about this -- this is the only case where
- ## there's something that's a directory
- ## (i.e. MagicContainer) AND needs to be a ConfigMethod as
- ## well...but doesn't really seem very useful. Somewhat
- ## simpler to not support this case for now...
+ # FIXME think about this -- this is the only case where
+ # there's something that's a directory
+ # (i.e. MagicContainer) AND needs to be a ConfigMethod as
+ # well...but doesn't really seem very useful. Somewhat
+ # simpler to not support this case for now...
if name == 'config/*':
continue
if name.endswith('/*'):
- ## this takes an arg, so make a method
+ # this takes an arg, so make a method
bits = name[:-2].split('/')
takes_arg = True
@@ -246,7 +251,9 @@ class TorInfo(object):
if bit in mine.attrs:
mine = mine.attrs[bit]
if not isinstance(mine, MagicContainer):
- raise RuntimeError("Already had something: %s for %s" % (bit, name))
+ raise RuntimeError(
+ "Already had something: %s for %s" % (bit, name)
+ )
else:
c = MagicContainer(bit)
@@ -255,8 +262,11 @@ class TorInfo(object):
mine = c
n = bits[-1].replace('-', '_')
if n in mine.attrs:
- raise RuntimeError("Already had something: %s for %s" % (n, name))
- mine._add_attribute(n, ConfigMethod('/'.join(bits), self.protocol, takes_arg))
+ raise RuntimeError(
+ "Already had something: %s for %s" % (n, name)
+ )
+ mine._add_attribute(n, ConfigMethod('/'.join(bits),
+ self.protocol, takes_arg))
for c in added_magic:
c._setup_complete()
diff --git a/txtorcon/torstate.py b/txtorcon/torstate.py
index 1f7efa2..164ef1a 100644
--- a/txtorcon/torstate.py
+++ b/txtorcon/torstate.py
@@ -6,9 +6,11 @@ import warnings
from twisted.python import log
from twisted.internet import defer
-from twisted.internet.endpoints import TCP4ClientEndpoint, UNIXClientEndpoint
-from twisted.internet.interfaces import IReactorCore, IStreamClientEndpoint
-from zope.interface import implements
+from twisted.internet.endpoints import TCP4ClientEndpoint
+from twisted.internet.endpoints import UNIXClientEndpoint
+from twisted.internet.interfaces import IReactorCore
+from twisted.internet.interfaces import IStreamClientEndpoint
+from zope.interface import implementer
from txtorcon import TorProtocolFactory
from txtorcon.stream import Stream
@@ -19,8 +21,12 @@ from txtorcon.torcontrolprotocol import parse_keywords
from txtorcon.log import txtorlog
from txtorcon.torcontrolprotocol import TorProtocolError
-from txtorcon.interface import ITorControlProtocol, IRouterContainer, ICircuitListener
-from txtorcon.interface import ICircuitContainer, IStreamListener, IStreamAttacher
+from txtorcon.interface import ITorControlProtocol
+from txtorcon.interface import IRouterContainer
+from txtorcon.interface import ICircuitListener
+from txtorcon.interface import ICircuitContainer
+from txtorcon.interface import IStreamListener
+from txtorcon.interface import IStreamAttacher
from spaghetti import FSM, State, Transition
@@ -93,7 +99,11 @@ def build_tor_connection(connection, build_state=True, wait_for_proto=True,
'Endpoint for argument "connection", got %s' %
(connection, ))
- d = endpoint.connect(TorProtocolFactory(password_function=password_function))
+ d = endpoint.connect(
+ TorProtocolFactory(
+ password_function=password_function
+ )
+ )
if build_state:
d.addCallback(build_state if callable(build_state) else _build_state)
elif wait_for_proto:
@@ -176,10 +186,10 @@ class TorState(object):
def __init__(self, protocol, bootstrap=True, write_state_diagram=False):
self.protocol = ITorControlProtocol(protocol)
- ## fixme could use protocol.on_disconnect to re-connect; see issue #3
+ # fixme could use protocol.on_disconnect to re-connect; see issue #3
- ## could override these to get your own Circuit/Stream subclasses
- ## to track these things
+ # could override these to get your own Circuit/Stream subclasses
+ # to track these things
self.circuit_factory = Circuit
self.stream_factory = Stream
@@ -209,7 +219,7 @@ class TorState(object):
self.cleanup = None # see set_attacher
class die(object):
- __name__ = 'die' # FIXME? just to ease spagetti.py:82's pain
+ __name__ = 'die' # FIXME? just to ease spagetti.py:82's pain
def __init__(self, msg):
self.msg = msg
@@ -230,7 +240,7 @@ class TorState(object):
waiting_r.add_transition(Transition(waiting_r, ignorable_line, nothing))
waiting_r.add_transition(Transition(waiting_s, lambda x: x[:2] == 'r ', self._router_begin))
- ## FIXME use better method/func than die!!
+ # FIXME use better method/func than die!!
waiting_r.add_transition(Transition(waiting_r, lambda x: x[:2] != 'r ', die('Expected "r " while parsing routers not "%s"')))
waiting_s.add_transition(Transition(waiting_w, lambda x: x[:2] == 's ', self._router_flags))
@@ -252,28 +262,28 @@ class TorState(object):
waiting_p.add_transition(Transition(waiting_r, lambda x: x.strip() == '.', nothing))
self._network_status_parser = FSM([waiting_r, waiting_s, waiting_w, waiting_p])
- if write_state_diagram:
- with open('routerfsm.dot', 'w') as fsmfile:
- fsmfile.write(self._network_status_parser.dotty())
self.post_bootstrap = defer.Deferred()
if bootstrap:
- self.protocol.post_bootstrap.addCallback(self._bootstrap).addErrback(self.post_bootstrap.errback)
+ self.protocol.post_bootstrap.addCallback(self._bootstrap)
+ self.protocol.post_bootstrap.addErrback(self.post_bootstrap.errback)
def _router_begin(self, data):
args = data.split()
self._router = Router(self.protocol)
self._router.from_consensus = True
- self._router.update(args[1], # nickname
- args[2], # idhash
- args[3], # orhash
- datetime.datetime.strptime(args[4] + args[5], '%Y-%m-%f%H:%M:%S'),
- args[6], # ip address
- args[7], # ORPort
- args[8]) # DirPort
+ self._router.update(
+ args[1], # nickname
+ args[2], # idhash
+ args[3], # orhash
+ datetime.datetime.strptime(args[4] + args[5], '%Y-%m-%f%H:%M:%S'),
+ args[6], # ip address
+ args[7], # ORPort
+ args[8], # DirPort
+ )
if self._router.id_hex in self.routers:
- ## FIXME should I do an update() on this one??
+ # FIXME should I do an update() on this one??
self._router = self.routers[self._router.id_hex]
return
@@ -324,8 +334,10 @@ class TorState(object):
# be the empty string, but we call _update_network_status for
# the de-duplication of named routers
- ns = yield self.protocol.get_info_incremental('ns/all',
- self._network_status_parser.process)
+ ns = yield self.protocol.get_info_incremental(
+ 'ns/all',
+ self._network_status_parser.process
+ )
self._update_network_status(ns)
# update list of existing circuits
@@ -459,7 +471,9 @@ class TorState(object):
try:
reason = TorState.stream_close_reasons[reason]
except KeyError:
- raise ValueError('Unknown stream close reason "%s"' % str(reason))
+ raise ValueError(
+ 'Unknown stream close reason "%s"' % str(reason)
+ )
flags = flags_from_dict(kwargs)
@@ -485,10 +499,12 @@ class TorState(object):
"""
if type(circid) != int:
- ## assume it's a Circuit instance
+ # assume it's a Circuit instance
circid = circid.id
flags = flags_from_dict(kwargs)
- return self.protocol.queue_command('CLOSECIRCUIT %s%s' % (circid, flags))
+ return self.protocol.queue_command(
+ 'CLOSECIRCUIT %s%s' % (circid, flags)
+ )
def add_circuit_listener(self, icircuitlistener):
listen = ICircuitListener(icircuitlistener)
@@ -535,7 +551,10 @@ class TorState(object):
else:
if using_guards and routers[0] not in self.entry_guards.values():
- warnings.warn("Building a circuit not starting with a guard: %s" % (str(routers),), RuntimeWarning)
+ warnings.warn(
+ "Circuit doesn't start with a guard: %s" % routers,
+ RuntimeWarning
+ )
cmd = "EXTENDCIRCUIT 0 "
first = True
for router in routers:
@@ -543,7 +562,8 @@ class TorState(object):
first = False
else:
cmd += ','
- if isinstance(router, types.StringType) and len(router) == 40 and hashFromHexId(router):
+ if isinstance(router, types.StringType) and len(router) == 40 \
+ and hashFromHexId(router):
cmd += router
else:
cmd += router.id_hex[1:]
@@ -569,15 +589,16 @@ class TorState(object):
"""
if self.attacher:
- if stream.target_host is not None and '.exit' in stream.target_host:
- ## we want to totally ignore .exit URIs as these are
- ## used to specify a particular exit node, and trying
- ## to do STREAMATTACH on them will fail with an error
- ## from Tor anyway.
+ if stream.target_host is not None \
+ and '.exit' in stream.target_host:
+ # we want to totally ignore .exit URIs as these are
+ # used to specify a particular exit node, and trying
+ # to do STREAMATTACH on them will fail with an error
+ # from Tor anyway.
txtorlog.msg("ignore attacher:", stream)
return
- circ = IStreamAttacher(self.attacher).attach_stream(stream, self.circuits)
+ circ = self.attacher.attach_stream(stream, self.circuits)
if circ is self.DO_NOT_ATTACH:
return
@@ -593,23 +614,33 @@ class TorState(object):
def __call__(self, arg):
circid = arg.id
- self.state.protocol.queue_command("ATTACHSTREAM %d %d" % (self.stream_id, circid))
+ self.state.protocol.queue_command(
+ "ATTACHSTREAM %d %d" % (self.stream_id, circid)
+ )
- circ.addCallback(IssueStreamAttach(self, stream.id)).addErrback(log.err)
+ circ.addCallback(IssueStreamAttach(self, stream.id))
+ circ.addErrback(log.err)
else:
if circ.id not in self.circuits:
- raise RuntimeError("Attacher returned a circuit unknown to me.")
+ raise RuntimeError(
+ "Attacher returned a circuit unknown to me."
+ )
if circ.state != 'BUILT':
- raise RuntimeError("Can only attach to BUILT circuits; %d is in %s." % (circ.id, circ.state))
- self.protocol.queue_command("ATTACHSTREAM %d %d" % (stream.id, circ.id))
+ raise RuntimeError(
+ "Can only attach to BUILT circuits; %d is in %s." %
+ (circ.id, circ.state)
+ )
+ self.protocol.queue_command(
+ "ATTACHSTREAM %d %d" % (stream.id, circ.id)
+ )
def _circuit_status(self, data):
"""Used internally as a callback for updating Circuit information"""
data = data[len('circuit-status='):].split('\n')
- ## sometimes there's a newline after circuit-status= and
- ## sometimes not, so we get rid of it
+ # sometimes there's a newline after circuit-status= and
+ # sometimes not, so we get rid of it
if len(data) and len(data[0].strip()) == 0:
data = data[1:]
@@ -669,7 +700,7 @@ class TorState(object):
from CIRC events.
"""
- #print "circuit_update",line
+ # print "circuit_update",line
args = line.split()
circ_id = int(args[0])
@@ -682,9 +713,9 @@ class TorState(object):
from STREAM events.
"""
- #print "stream_update",line
+ # print "stream_update",line
if line.strip() == 'stream-status=':
- ## this happens if there are no active streams
+ # this happens if there are no active streams
return
args = line.split()
@@ -700,9 +731,9 @@ class TorState(object):
wasnew = True
self.streams[stream_id].update(args)
- ## if the update closed the stream, it won't be in our list
- ## anymore. FIXME: how can we ever hit such a case as the
- ## first update being a CLOSE?
+ # if the update closed the stream, it won't be in our list
+ # anymore. FIXME: how can we ever hit such a case as the
+ # first update being a CLOSE?
if wasnew and stream_id in self.streams:
self._maybe_attach(self.streams[stream_id])
@@ -724,17 +755,20 @@ class TorState(object):
"""
for (event, func) in self.event_map.items():
- ## the map contains unbound methods, so we bind them
- ## to self so they call the right thing
- yield self.protocol.add_event_listener(event, types.MethodType(func, self, TorState))
+ # the map contains unbound methods, so we bind them
+ # to self so they call the right thing
+ yield self.protocol.add_event_listener(
+ event,
+ types.MethodType(func, self, TorState)
+ )
- ## ICircuitContainer
+ # ICircuitContainer
def find_circuit(self, circid):
"ICircuitContainer API"
return self.circuits[circid]
- ## IRouterContainer
+ # IRouterContainer
def router_from_id(self, routerid):
"""IRouterContainer API"""
@@ -759,7 +793,7 @@ class TorState(object):
self.routers[router.id_hex] = router
return router
- ## implement IStreamListener
+ # implement IStreamListener
def stream_new(self, stream):
"IStreamListener: a new stream has been created"
@@ -802,7 +836,7 @@ class TorState(object):
txtorlog.msg("stream_failed", stream.id)
del self.streams[stream.id]
- ## implement ICircuitListener
+ # implement ICircuitListener
def circuit_launched(self, circuit):
"ICircuitListener API"
@@ -815,9 +849,11 @@ class TorState(object):
def circuit_built(self, circuit):
"ICircuitListener API"
- txtorlog.msg("circuit_built:", circuit.id,
- "->".join("%s.%s" % (x.name, x.location.countrycode) for x in circuit.path),
- circuit.streams)
+ txtorlog.msg(
+ "circuit_built:", circuit.id,
+ "->".join("%s.%s" % (x.name, x.location.countrycode) for x in circuit.path),
+ circuit.streams
+ )
def circuit_new(self, circuit):
"ICircuitListener API"
diff --git a/txtorcon/util.py b/txtorcon/util.py
index d5a5edd..62366d7 100644
--- a/txtorcon/util.py
+++ b/txtorcon/util.py
@@ -25,16 +25,16 @@ asn = None
def create_geoip(fname):
- ## It's more "pythonic" to just wait for the exception,
- ## but GeoIP prints out "Can't open..." messages for you,
- ## which isn't desired here
+ # It's more "pythonic" to just wait for the exception,
+ # but GeoIP prints out "Can't open..." messages for you,
+ # which isn't desired here
if not os.path.isfile(fname):
raise IOError("Can't find %s" % fname)
if GeoIP is None:
return None
- ## just letting any errors make it out
+ # just letting any errors make it out
return GeoIP.open(fname, GeoIP.GEOIP_STANDARD)
@@ -81,9 +81,11 @@ def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/',
# Try to find the tor executable using the shell
if system_tor:
try:
- proc = subprocess.Popen(('which tor'),
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- shell=True)
+ proc = subprocess.Popen(
+ ('which tor'),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ shell=True
+ )
except OSError:
pass
else:
@@ -130,7 +132,8 @@ def find_keywords(args, key_filter=lambda x: not x.startswith("$")):
a dict of key->value (both strings) of all name=value type
keywords found in args.
"""
- return dict(x.split('=', 1) for x in args if '=' in x and key_filter(x.split('=')[0]))
+ filtered = filter(lambda x: '=' in x and key_filter(x.split('=')[0]), args)
+ return dict(x.split('=', 1) for x in filtered)
def delete_file_or_tree(*args):
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-privacy/packages/txtorcon.git
More information about the Pkg-privacy-commits
mailing list