Created
November 29, 2010 12:15
-
-
Save amcgregor/719889 to your computer and use it in GitHub Desktop.
A simple mock HTTP server useful for HTTP client testing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Gist is in reply to: https://gist.github.com/719843