Skip to content

Instantly share code, notes, and snippets.

@arc279
Last active January 23, 2019 09:31
Show Gist options
  • Save arc279/53b16c7a7274dab3a197f8123249cb86 to your computer and use it in GitHub Desktop.
Save arc279/53b16c7a7274dab3a197f8123249cb86 to your computer and use it in GitHub Desktop.
BaseHTTPRequestHandler をテストする(python2)
# -*- coding: utf-8 -*-
import BaseHTTPServer
from StringIO import StringIO
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""これをテストしたい"""
def do_GET(self):
print("executing do_GET")
self.send_response(200)
self.send_header("X-Hoge", "hoge")
self.send_header("Content-type", "text/html")
self.end_headers()
html = "<html><p>hello world</p></html>"
self.wfile.write(html.encode())
###
# レスポンスを読めるように
# cf. https://github.com/python/cpython/blob/3.6/Lib/socketserver.py#L788
def no_finish(*args, **kwargs):
print("no_finish", args, kwargs)
BaseHTTPServer.BaseHTTPRequestHandler.finish = no_finish
###
# リクエストとサーバのモック化
# cf. https://stackoverflow.com/questions/25369068/python-how-to-unit-test-a-custom-http-request-handler
class MockRequest(object):
def makefile(self, *args, **kwargs):
return StringIO(b"GET / HTTP/1.1")
class MockServer(object):
def __init__(self, ip_port, Handler):
self.handler = Handler(MockRequest(), ip_port, self)
###
# レスポンスのパース
# cf. https://stackoverflow.com/questions/24728088/python-parse-http-response-string
from httplib import HTTPResponse
from StringIO import StringIO
class FakeSocket():
def __init__(self, response_str):
self._file = StringIO(response_str)
def makefile(self, *args, **kwargs):
return self._file
###
# ここからテスト
import pytest
def test_handler():
server = MockServer(('0.0.0.0', 8888), MyHandler)
resp_str = server.handler.wfile.getvalue()
source = FakeSocket(resp_str)
response = HTTPResponse(source)
response.begin()
headers = { x[0]: x[1] for x in response.getheaders() }
body = response.read()
assert response.status == 200
assert headers["content-type"] == 'text/html'
assert "x-hoge" in headers
assert "hello world" in body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment