Awesome Open Source
Awesome Open Source

============= pytest-socket

.. image:: :target:

.. image:: :target:

.. image:: :target: :alt: Python Tests

.. image:: :target: :alt: Maintainability

.. image:: :target: :alt: FOSSA Status

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.


  • Pytest_ 3.6.3 or greater


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:

    .. code:: ini

    [pytest] addopts = --disable-socket

    or update your to include:

    .. code:: python

    from pytest_socket import disable_socket

    def pytest_runtest_setup(): disable_socket()

  • To enable specific tests use of socket, pass in the fixture to the test or use a marker:

    .. code:: python

    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:

    .. code:: python

    @pytest.mark.allow_hosts(['']) def test_explicitly_enable_socket_with_mark(): assert socket.socket.connect(('', 80))

or for whole test run

.. code:: ini

addopts = --allow-hosts=,


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

.. image:: :target: :alt: FOSSA Status


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.

.. _Cookiecutter: .. _@hackebrot: .. _MIT: .. _cookiecutter-pytest-plugin: .. _file an issue: .. _pytest: .. _tox: .. _pip: .. _PyPI: .. _@hangtwenty: .. _StackOverflow question: .. _@miketheman:

Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
python (48,431
testing (881
testing-tools (188
socket (160
pytest-plugin (27

Find Open Source By Browsing 7,000 Topics Across 59 Categories