Skip to main content

pytest fixture finding an unused local port

Project description

pytest-unused-port

PyPI Tests Changelog License

pytest fixture finding an unused local port, built using Claude Code

Installation

Install this library using pip:

pip install pytest-unused-port

Usage

This pytest plugin provides a unused_port fixture that returns an available TCP port on localhost that your tests can use.

Basic Example

def test_my_server(unused_port):
    # unused_port is an integer containing an available port number
    server = start_my_server(port=unused_port)
    assert server.is_running()

Starting an HTTP Server

import http.server

def test_http_server(unused_port):
    handler = http.server.SimpleHTTPRequestHandler
    server = http.server.HTTPServer(('127.0.0.1', unused_port), handler)
    # Now you can test your server on the unused port
    assert server.server_port == unused_port

Using with Socket Programming

import socket

def test_socket_server(unused_port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('127.0.0.1', unused_port))
    sock.listen(1)
    # Your test code here
    sock.close()

The fixture automatically finds an available port by binding to port 0 (which tells the OS to assign any available port), getting the assigned port number, and then releasing it for your test to use.

The unused_port_server fixture

For convenience, this plugin also provides an unused_port_server fixture that manages an HTTP server for you. This is especially useful for testing applications that need to fetch content from a local server.

Basic Example

def test_fetch_from_server(unused_port_server, tmp_path):
    # Create a test file
    test_file = tmp_path / "index.html"
    test_file.write_text("<h1>Hello</h1>")

    # Start the server serving the directory
    unused_port_server.start(tmp_path)

    # Make requests to http://127.0.0.1:{unused_port_server.port}/
    # Server automatically stops at the end of the test

Features

  • Automatic cleanup: The server automatically stops when the test ends
  • Explicit control: Call .stop() to stop the server manually if needed
  • Port access: Access the port number via unused_port_server.port
  • Method chaining: .start() returns self for convenience

Example with explicit stop

def test_server_lifecycle(unused_port_server, tmp_path):
    unused_port_server.start(tmp_path)

    # Do some testing...

    # Explicitly stop the server
    unused_port_server.stop()

    # Server is now stopped

Example fetching a file

from urllib.request import urlopen

def test_fetch_file(unused_port_server, tmp_path):
    # Create a test file
    (tmp_path / "data.txt").write_text("test data")

    # Start server
    unused_port_server.start(tmp_path)

    # Fetch the file
    url = f"http://127.0.0.1:{unused_port_server.port}/data.txt"
    response = urlopen(url)
    assert response.read().decode() == "test data"

Using as a context manager

You can also use StaticServer directly as a context manager if you need more control:

from pytest_unused_port import StaticServer

def test_with_context_manager(unused_port, tmp_path):
    with StaticServer(unused_port) as server:
        server.start(tmp_path)
        # Server runs here
        # ... your test code ...
    # Server automatically stops when exiting the context

The server runs python -m http.server in a subprocess, serving static files from the specified directory.

Development

To contribute to this library, first checkout the code. Then install the dependencies using uv:

cd pytest-unused-port
uv pip install -e '.[test]'

To run the tests:

uv run pytest

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytest_unused_port-0.1.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pytest_unused_port-0.1-py3-none-any.whl (8.6 kB view details)

Uploaded Python 3

File details

Details for the file pytest_unused_port-0.1.tar.gz.

File metadata

  • Download URL: pytest_unused_port-0.1.tar.gz
  • Upload date:
  • Size: 9.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pytest_unused_port-0.1.tar.gz
Algorithm Hash digest
SHA256 ae334058c7f62ee5247d45ec0f101ca9210a9c4b8cabafa6cd75776ae2165cdd
MD5 23d5d0b9338f42a11c5ba8133e4f6da1
BLAKE2b-256 2424ab917a6da818afc0beada91776ee49492a53ed852cc67ffdb3acefec291e

See more details on using hashes here.

Provenance

The following attestation bundles were made for pytest_unused_port-0.1.tar.gz:

Publisher: publish.yml on simonw/pytest-unused-port

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pytest_unused_port-0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for pytest_unused_port-0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d296229ae03ce11f738699c0a838dfb5f1ec069b2769ce5770279427e1ea1398
MD5 8286af2eea4262032d24c9c022e5310e
BLAKE2b-256 ec2b637537b57f23234a2152afca798c3ea2bf7486c7c3fe4a6b62ba9799a117

See more details on using hashes here.

Provenance

The following attestation bundles were made for pytest_unused_port-0.1-py3-none-any.whl:

Publisher: publish.yml on simonw/pytest-unused-port

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page