By setting up a local server when executing a unit test, it is possible to perform tests that do not depend on the outside.
Convenient for API and crawler development.
The flow is like this
--Describe http server start / end processing as fixture in conftest.py
--Call a fixture in a test function
conftest.py
import pytest
from http.server import (
HTTPServer as SuperHTTPServer,
SimpleHTTPRequestHandler
)
import threading
class HTTPServer(SuperHTTPServer):
"""
Class for wrapper to run SimpleHTTPServer on Thread.
Ctrl +Only Thread remains dead when terminated with C.
Keyboard Interrupt passes.
"""
def run(self):
try:
self.serve_forever()
except KeyboardInterrupt:
pass
finally:
self.server_close()
@pytest.fixture()
def http_server():
host, port = '127.0.0.1', 8888
url = f'http://{host}:{port}/index.html'
# serve_Run forever under thread
server = HTTPServer((host, port), SimpleHTTPRequestHandler)
thread = threading.Thread(None, server.run)
thread.start()
yield url #Transition to test here
#End thread
server.shutdown()
thread.join()
Transfer control to the test function with the yield
statement.
The setUp
and tearDown
in the unit test are before and after the yield
statement, respectively.
Place the content in the execution directory.
index.html
<html>Hello pytest!</html>
Use fixture (http_server
) in test function
test_httpserver.py
import requests
def test_index(http_server):
url = http_server
response = requests.get(url)
assert response.text == '<html>Hello pytest!</html>'
$ pytest --setup-show test_httpserver.py
========================================= test session starts =========================================platform linux -- Python 3.8.1, pytest-5.3.3, py-1.8.1, pluggy-0.13.1
rootdir: /home/skokado/workspace/sandbox
collected 1 item
test_httpserver.py
SETUP F http_server
test_httpserver.py::test_index (fixtures used: http_server).
TEARDOWN F http_server
========================================== 1 passed in 0.60s ==========================================
You can trace the generation of fixtures with the --setup-show
option.
You can see that the test_index
function uses the fixture http_server
.
Bankushi (@vaaaaanquish), I used it as a reference.
Reference-Write a unit test for web scraping using Python's http.server
Recommended Posts