Skip to content

Commit

Permalink
Revise mockup submodule, pylover#182
Browse files Browse the repository at this point in the history
  • Loading branch information
pylover committed Jun 5, 2019
1 parent d815f3c commit 44dbb28
Showing 1 changed file with 13 additions and 87 deletions.
100 changes: 13 additions & 87 deletions restfulpy/mockup.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,92 +13,23 @@
from .application import Application


SERVER_LOCK = threading.Event()


@contextlib.contextmanager
def mockup_http_server(app=None, handler_class=WSGIRequestHandler,
server_class=WSGIServer, bind=('', 0)):
server = server_class(bind, handler_class)
if app:
assert isinstance(server, WSGIServer)
server.set_app(app)
thread = threading.Thread(
target=server.serve_forever,
name='sa-media test server.',
daemon=True
)
thread.start()
url = 'http://localhost:%s' % server.server_address[1]
yield server, url
server.shutdown()
thread.join()


def mockup_http_static_server(content: bytes = b'Simple file content.',
content_type: str = None, **kwargs):

class StaticMockupHandler(BaseHTTPRequestHandler):
def serve_text(self):
self.send_header('Content-Type', "text/plain")
self.send_header('Content-Length', str(len(content)))
self.send_header('Last-Modified', self.date_time_string())
self.end_headers()
self.wfile.write(content)

def serve_static_file(self, filename):
self.send_header('Content-Type', guess_type(filename))
with open(filename, 'rb') as f:
self.serve_stream(f)

def serve_stream(self, stream):
buffer = io.BytesIO()
self.send_header(
'Content-Length',
str(copy_stream(stream, buffer))
)
self.end_headers()
buffer.seek(0)
try:
copy_stream(buffer, self.wfile)
except ConnectionResetError:
pass

def do_GET(self):
self.send_response(HTTPStatus.OK)
if isinstance(content, bytes):
self.serve_text()
elif isinstance(content, str):
self.serve_static_file(content)
else:
self.send_header('Content-Type', content_type)
self.serve_stream(content)

return simple_http_server(
None,
handler_class=StaticMockupHandler,
server_class=HTTPServer,
**kwargs
)


class MockupSMTPServer(smtpd.SMTPServer):

def __init__(self, bind):
super().__init__(bind, None, decode_data=False)
self.server_address = self.socket.getsockname()[:2]
SERVER_LOCK.set()

def process_message(*args, **kwargs):
pass
def mockup_smtp_server(bind=('localhost', 0)):
SMTP_SERVER_LOCK = threading.Event()
class MockupSMTPServer(smtpd.SMTPServer):
def __init__(self, bind):
super().__init__(bind, None, decode_data=False)
self.server_address = self.socket.getsockname()[:2]
SMTP_SERVER_LOCK.set()

def process_message(*args, **kwargs):
pass


@contextlib.contextmanager
def mockup_smtp_server(bind=('localhost', 0)):
server = MockupSMTPServer(bind)
thread = threading.Thread(target=asyncore.loop, daemon=True)
thread.start()
SERVER_LOCK.wait()
SMTP_SERVER_LOCK.wait()
yield server, server.server_address
asyncore.close_all()

Expand All @@ -124,9 +55,6 @@ def send(
from_=None,
attachments=None
):
if attachments:
for attachment in attachments:
assert hasattr(attachment, 'name')
self.last_message = {
'to': to,
'body': body,
Expand All @@ -137,10 +65,8 @@ def send(
@contextlib.contextmanager
def mockup_localtimezone(timezone):
backup = datetimehelpers.localtimezone
if callable(timezone):
datetimehelpers.localtimezone = timezone
else:
datetimehelpers.localtimezone = lambda: timezone
datetimehelpers.localtimezone = timezone if callable(timezone) \
else datetimehelpers.localtimezone = lambda: timezone

yield

Expand Down

0 comments on commit 44dbb28

Please sign in to comment.