mitmproxy/pathod/test.py

106 lines
2.6 KiB
Python
Raw Normal View History

2016-03-20 18:40:03 +00:00
from six.moves import cStringIO as StringIO
import time
2016-03-20 21:50:03 +00:00
from six.moves import queue
from . import pathod
from netlib import basethread
class Daemon:
IFACE = "127.0.0.1"
2015-05-30 00:03:13 +00:00
def __init__(self, ssl=None, **daemonargs):
2016-03-20 21:50:03 +00:00
self.q = queue.Queue()
2016-03-20 18:40:03 +00:00
self.logfp = StringIO()
daemonargs["logfp"] = self.logfp
self.thread = _PaThread(self.IFACE, self.q, ssl, daemonargs)
self.thread.start()
self.port = self.q.get(True, 5)
2015-05-30 00:03:13 +00:00
self.urlbase = "%s://%s:%s" % (
2014-10-24 01:01:34 +00:00
"https" if ssl else "http",
self.IFACE,
self.port
)
2012-07-30 08:58:59 +00:00
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.logfp.truncate(0)
2012-07-30 08:58:59 +00:00
self.shutdown()
return False
def p(self, spec):
"""
Return a URL that will render the response in spec.
"""
2015-05-30 00:03:13 +00:00
return "%s/p/%s" % (self.urlbase, spec)
def text_log(self):
return self.logfp.getvalue()
def wait_for_silence(self, timeout=5):
self.thread.server.wait_for_silence(timeout=timeout)
2016-06-02 05:55:11 +00:00
def expect_log(self, n, timeout=5):
l = []
start = time.time()
while True:
l = self.log()
if time.time() - start >= timeout:
return None
if len(l) >= n:
break
return l
def last_log(self):
"""
Returns the last logged request, or None.
"""
l = self.expect_log(1)
if not l:
return None
2016-06-02 07:45:18 +00:00
return l[-1]
def log(self):
"""
Return the log buffer as a list of dictionaries.
"""
return self.thread.server.get_log()
def clear_log(self):
"""
Clear the log.
"""
return self.thread.server.clear_log()
def shutdown(self):
"""
Shut the daemon down, return after the thread has exited.
"""
2012-06-19 01:23:07 +00:00
self.thread.server.shutdown()
self.thread.join()
class _PaThread(basethread.BaseThread):
2015-06-18 16:12:11 +00:00
def __init__(self, iface, q, ssl, daemonargs):
basethread.BaseThread.__init__(self, "PathodThread")
self.iface, self.q, self.ssl = iface, q, ssl
self.daemonargs = daemonargs
self.server = None
def run(self):
2012-06-24 03:12:31 +00:00
self.server = pathod.Pathod(
(self.iface, 0),
2015-06-18 16:12:11 +00:00
ssl=self.ssl,
**self.daemonargs
2012-06-24 03:12:31 +00:00
)
2014-10-24 01:01:34 +00:00
self.name = "PathodThread (%s:%s)" % (
self.server.address.host,
self.server.address.port
)
self.q.put(self.server.address.port)
2012-06-19 01:23:07 +00:00
self.server.serve_forever()