Pytest Plugin to disable socket calls during tests
Switch branches/tags
Nothing to show
Clone or download
miketheman pytest-socket, v0.3.1
Signed-off-by: Mike Fiedler <>
Latest commit 4c2bd57 Jul 16, 2018



See Build Status on Travis CI See Build Status on AppVeyor Maintainability

A plugin to use with Pytest to disable or restrict socket calls during tests to ensure network calls are prevented.

This Pytest plugin was generated with Cookiecutter along with @hackebrot's Cookiecutter-pytest-plugin template.


  • Disables all network calls flowing through Python's socket interface.



You can install "pytest-socket" via pip from PyPI:

$ pip install pytest-socket


  • Run pytest --disable-socket, tests should fail on any access to socket or libraries using socket with a SocketBlockedError.

    To add this flag as the default behavior, add this section to your pytest.ini or setup.cfg:

    addopts = --disable-socket

    or update your to include:

    from pytest_socket import disable_socket
    def pytest_runtest_setup():
  • 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)
    def test_explicitly_enable_socket_with_mark():
        assert socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  • To allow only specific hosts per-test:

    def test_explicitly_enable_socket_with_mark():
        assert socket.socket.connect(('', 80))

or for whole test run

addopts = --allow-hosts=,


Contributions are very welcome. Tests can be run with tox, 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.


This plugin came about due to the efforts by @hangtwenty solving a StackOverflow question, then converted into a pytest plugin by @miketheman.