Pytest Plugin to disable socket calls during tests
Project description
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.
Features
Disables all network calls flowing through Python’s socket interface.
Requirements
Pytest 3.6.3 or greater
Installation
You can install “pytest-socket” via pip from PyPI:
$ pip install pytest-socket
Usage
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:
[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 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
Contributing
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.
License
Distributed under the terms of the MIT license, “pytest-socket” is free and open source software
Issues
If you encounter any problems, please file an issue along with a detailed description.
References
This plugin came about due to the efforts by @hangtwenty solving a StackOverflow question, then converted into a pytest plugin by @miketheman.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file pytest-socket-0.3.1.tar.gz
.
File metadata
- Download URL: pytest-socket-0.3.1.tar.gz
- Upload date:
- Size: 4.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | bb0857c4a459b7ed4586c51b48ad99920ca82f3314c95ed6de84847c2a8b6eef |
|
MD5 | 8d3652951ffb57dd6c64dc4685fb6890 |
|
BLAKE2b-256 | c33fa879ee90224e7b46482be0d9fd8abcc4030d800712707740cac5ac2d1326 |