Pytest Plugin to disable socket calls during tests
A plugin to use with Pytest to disable or restrict
socket calls during
tests to ensure network calls are prevented.
- Disables all network calls flowing through Python's
- Pytest 3.6.3 or greater
$ pip install pytest-socket
or add to your
pyproject.toml for poetry:
[tool.poetry.dev-dependencies] pytest-socket = "*"
pytest --disable-socket, tests should fail on any access to
libraries using socket with a
To add this flag as the default behavior, add this section to your
[pytest] addopts = --disable-socket
or add this to your
[tool:pytest] addopts = --disable-socket
or update your
conftest.py to include:
from pytest_socket import disable_socket def pytest_runtest_setup(): disable_socket()
To enable Unix sockets during the test run (e.g. for async), add this option:
[pytest] addopts = --disable-socket --allow-unix-socket
To enable specific tests use of
socket, pass in the fixture to the test or
use a marker:
def test_explicitly_enable_socket(socket_enabled): assert socket.socket(socket.AF_INET, socket.SOCK_STREAM) @pytest.mark.enable_socket def test_explicitly_enable_socket_with_mark(): assert socket.socket(socket.AF_INET, socket.SOCK_STREAM)
To allow only specific hosts per-test:
@pytest.mark.allow_hosts(['127.0.0.1']) def test_explicitly_enable_socket_with_mark(): assert socket.socket.connect(('127.0.0.1', 80))
or for whole test run
[pytest] addopts = --allow-hosts=127.0.0.1,127.0.1.1
Frequently Asked Questions
Q: Why is network access disabled in some of my tests but not others?
A: pytest's default fixture scope is "function", which
If you create another fixture that creates a socket usage that has a "higher"
instantiation order, such as at the module/class/session, then the higher order
fixture will be resolved first, and won't be disabled during the tests.
Read more in this excellent example
and more about pytest fixture order here.
This behavior may change in the future, as we learn more about pytest fixture order, and what users expect to happen.
Contributions are very welcome. Tests can be run with pytest, please ensure the coverage at least stays the same before you submit a pull request.
Distributed under the terms of the MIT license, "pytest-socket" is free and open source software
If you encounter any problems, please file an issue along with a detailed description.
Release history Release notifications | RSS feed
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Hashes for pytest_socket-0.5.1-py3-none-any.whl