Pytest Socket

0.7.0 · active · verified Thu Apr 09

pytest-socket is a pytest plugin that allows you to disable real socket connections during test runs. This helps ensure your tests are truly isolated, do not make unintended network calls, and are faster by avoiding I/O. It is currently at version 0.7.0 and has a moderate release cadence, with updates addressing compatibility and new features.

Warnings

Install

Quickstart

This quickstart demonstrates the default behavior of `pytest-socket` blocking network connections and how to selectively re-enable them using `pytest.mark.enable_socket` or the `socket_enabled` fixture. It also shows how CLI flags like `--disable-socket` and `--allow-socket` influence test execution.

import pytest
import socket
import os

# By default, if pytest-socket is installed, socket calls are blocked.
# This test will fail if run without explicitly allowing sockets.
def test_blocked_socket_connection():
    with pytest.raises(socket.error): # pytest-socket raises socket.error for blocked connections
        socket.create_connection(("example.com", 80), timeout=0.1)

# Use the @pytest.mark.enable_socket marker to allow sockets for a specific test.
@pytest.mark.enable_socket
def test_allowed_socket_with_marker():
    try:
        sock = socket.create_connection(("google.com", 80), timeout=0.1)
        sock.close()
        assert True
    except Exception as e:
        pytest.fail(f"Socket connection failed unexpectedly: {e}")

# Use the socket_enabled fixture to allow sockets for a specific test.
def test_allowed_socket_with_fixture(socket_enabled):
    try:
        sock = socket.create_connection(("github.com", 80), timeout=0.1)
        sock.close()
        assert True
    except Exception as e:
        pytest.fail(f"Socket connection failed unexpectedly: {e}")

# To run these tests and observe behavior:
# 1. Install: pip install pytest pytest-socket
# 2. Run normally: pytest -v your_test_file.py
#    (test_blocked_socket_connection should fail, others should pass)
# 3. Run with --disable-socket explicitly: pytest -v your_test_file.py --disable-socket
#    (test_blocked_socket_connection should fail with pytest-socket's error, others should pass)
# 4. Run with --allow-socket: pytest -v your_test_file.py --allow-socket
#    (All tests should attempt to connect, and pass if network is available)

view raw JSON →