Skip to content

Instantly share code, notes, and snippets.

@amcgregor
Created November 29, 2010 12:15
Show Gist options
  • Save amcgregor/719889 to your computer and use it in GitHub Desktop.
Save amcgregor/719889 to your computer and use it in GitHub Desktop.
A simple mock HTTP server useful for HTTP client testing.
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import logging
from functools import partial
from marrow.script import execute
from marrow.util.compat import unicode
from marrow.server.base import Server
from marrow.server.protocol import Protocol
CRLF = b"\r\n"
log = logging.getLogger(__name__)
__all__ = ['MockProtocol', 'serve', 'main']
class MockProtocol(Protocol):
def __init__(self, server, code, mime, content):
super(MockProtocol, self).__init__(server)
self.code = code
self.mime = mime
self.content = content.encode('utf8')
def accept(self, client):
log.debug("Connection from: %s", client.address)
client.read_until(CRLF + CRLF, partial(self.headers, client))
def headers(self, client, headers):
log.debug("Headers from: %s\n\n%s", client.address, headers.strip(CRLF).replace(CRLF, '\n').decode('ISO-8859-1'))
headers = b"HTTP/1.0 " + self.code.encode('ascii') + CRLF + \
b"Content-Type: " + unicode(self.mime).encode('ascii') + b"; charset=UTF-8" + CRLF + \
b"Content-Length: " + unicode(len(self.content) + 2).encode('ascii') + CRLF + CRLF
client.write(headers + self.content + CRLF, client.close)
def main():
def serve(port=8080, code="200 OK", mime="text/plain", content="Hello world!", verbose=False, quiet=False, forking=False):
logging.basicConfig(level=logging.DEBUG if verbose else (logging.WARN if quiet else logging.INFO))
if verbose and quiet:
log.error("Can not set verbose and quiet at the same time!")
return 1
Server('127.0.0.1', port, MockProtocol, fork=0 if forking else 1, code=code, mime=mime, content=content).start()
execute(serve)
if __name__ == '__main__':
main()
@amcgregor
Copy link
Author

Added forking option (pass -f|--forking to run one process per logical core) and now safely decodes headers for Py3K.

@amcgregor
Copy link
Author

Added content encoding.

@amcgregor
Copy link
Author

This Gist is in reply to: https://gist.github.com/719843

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment