pytest-localserver
pytest-localserver is a pytest plugin that provides easy-to-use fixtures for testing server connections locally. It allows you to run HTTP(S) and SMTP servers directly within your test suite, simplifying integration tests against external services. The current version is 0.10.0, with releases focusing on Python version support, dependency updates, and minor feature enhancements.
Warnings
- breaking Python 3.6 support has been dropped. Users on Python 3.6 must remain on version 0.9.x or earlier.
- breaking The minimum required pytest version was raised to `pytest>=4.6`. Users working with older pytest versions (e.g., `pytest>=4,<4.6`) must stay on `pytest-localserver<0.9.0.post0`.
- breaking SMTP server support is no longer installed by default. To use the SMTP server, you must install `pytest-localserver` with the `[smtp]` extra.
- gotcha The SMTP server internally uses `aiosmtpd`, which had breaking changes (e.g., removal of `_stop` method in 1.4.3+). While `pytest-localserver` attempts to handle this, ensure compatibility if explicitly interacting with `aiosmtpd` versions.
Install
-
pip install pytest-localserver -
pip install 'pytest-localserver[smtp]'
Imports
- http
from pytest_localserver import http
- smtp
from pytest_localserver import smtp
- Server
from pytest_localserver.http import Server
Quickstart
import pytest
from pytest_localserver.http import WSGIHandler, Server
# Define a simple WSGI application
def my_app(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'text/plain; charset=utf-8')]
start_response(status, headers)
return [b"Hello, World!"]
# Create a fixture for the local HTTP server
@pytest.fixture
def http_server():
# Instantiate the WSGI handler with your app
handler = WSGIHandler(my_app)
# Start the server
server = Server(handler)
server.start()
yield server
# Stop the server after the test
server.stop()
# Example test using the http_server fixture
def test_my_app_endpoint(http_server):
import requests
# Access the server URL provided by the fixture
response = requests.get(http_server.url)
assert response.status_code == 200
assert response.text == "Hello, World!"