pytest-localserver

0.10.0 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates how to set up a local HTTP server with a simple WSGI application using pytest-localserver. It defines a pytest fixture that starts the server before tests and stops it afterwards. The example then shows a test function that uses `requests` to make a call to the local server's URL and asserts the response.

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!"

view raw JSON →