Skip to main content

Tools for testing applications that make network requests.

Project description

Networktest

A library to test and enforce testing rules for Python applications that make network requests.

Installation

pip install networktest

Blocking network requests

networktest provides a context manager NetworkBlocker that can be used to prevent tests or an application from making network requests.

import urllib.request
from networktest import NetworkBlocker

with NetworkBlocker():
    # A NetworkBlockException will be raised
    urllib.request.urlopen('http://127.0.0.1').read()

In some types of tests you may want to allow certain types of requests but not others. When testing an API you may want to allow tests to access that API’s database but not make requests to another API.

import urllib.request
from networktest import NetworkBlocker
from my_database import Database

with NetworkBlocker(allowed_packages=NetworkBlocker.AllowablePackages.DATASTORE):
    # This is fine
    Database.query('SELECT 1')

    # A NetworkBlockException will be raised
    urllib.request.urlopen('http://127.0.0.1').read()

If you’re in the process of migrating your tests to mock requests you may want to use NetworkBlocker’s warning mode. This mode will allow requests but display a warning.

import urllib.request
from networktest import NetworkBlocker

with NetworkBlocker(mode=NetworkBlocker.Modes.WARNING):
    # This will be allowed but a warning will be displayed
    urllib.request.urlopen('http://127.0.0.1').read()

TestCase Support

Some TestCases are provided that will apply NetworkBlocker to all tests in that case with some default settings.

import urllib.request
from my_database import Database
from networktest import NetworkBlockedTest, NetworkLimitedTest

class MyTest(NetworkBlockedTest):

    def test_blocker(self):
        # A NetworkBlockException will be raised
        urllib.request.urlopen('http://127.0.0.1').read()

class MyOtherTest(NetworkLimitedTest):

    def test_blocker(self):
        # This is fine
        Database.query('SELECT 1')

        # A NetworkBlockException will be raised
        urllib.request.urlopen('http://127.0.0.1').read()

pytest Support

pytest markers networkblocked and networklimited are available to apply NetworkBlocker to tests. These may be applied to modules, classes, methods or any other way pytest markers are supported.

from pytest import mark

@mark.networkblocked
def test_blocked(self):
    # A NetworkBlockException will be raised
    urllib.request.urlopen('http://127.0.0.1').read()

@mark.networklimited
def test_limited(self):
    # This is fine
    Database.query('SELECT 1')

    # A NetworkBlockException will be raised
    urllib.request.urlopen('http://127.0.0.1').read()

NetworkBlocker may be applied to an entire directory by adding an autouse fixture to a conftest.py file in that directory.

@pytest.fixture(scope='module', autouse=True)
def networkblocker():
    with NetworkBlocker():
        yield

Mocking API requests

HttpApiMock is provided to help with mocking API requests in unit and functional tests.

import urllib.request
from networktest.mock import HttpApiMock

class MyApiMock(HttpApiMock):

    hostnames = [
       'my-api'
    ]

    endpoints = [
        HttpApiMockEndpoint(
            operation_id='example',
            match_pattern=b'^GET /example/(?P<example_id>.*?)/',
            response=lambda groups: (418, {
                'id': groups['example_id'],
            })
        )
    ]

def test_my_api():
    with MyApiMock() as mock_api:
        response = urllib.request.urlopen('http://my-api/')
        response.read()
        # Requests which do not have a matched endpoint return a 200 response code by default
        assert response.getcode() == 200

        try:
            # This request matches the 'example' endpoint defined in MyApiMock
            urllib.request.urlopen('http://my-api/example/1234/').read()
        except urllib.error.HTTPError as e:
            # The response is the one defined for the 'example' endpoint
            assert e.code == 418
            assert e.read() == b'{"id": "1234"}'

        # It's possible to change the default responses inside of a test
        # In most tests it would make sense to apply MyApiMock to all tests of a certain type
        #   and only explictly use MyApiMock when doing something like this.
        mock_api.example.response = lambda groups: (204, None)
        response = urllib.request.urlopen('http://my-api/')
        response.read()
        assert response.getcode() == 204

Integration tests

HttpApiMock may also be used to create assertions for integration tests without preventing API requests from being made.

import urllib.request
from networktest.mock import HttpApiMock

class MyApiMock(HttpApiMock):

    hostnames = [
        'my-api'
    ]

    endpoints = [
        HttpApiMockEndpoint(
            operation_id='example',
            match_pattern=b'^GET /example/(?P<example_id>.*?)/',
            response=lambda groups: (204, None)
        )
    ]

def test_my_api():
    with MyApiMock(Mode=MyApiMock.Modes.WATCH) as mock_api:
        urllib.request.urlopen('http://my-api/example/1234/').read()
        mock_api.example.request_mock.assert_called_once()

Versioning

This package strictly follows semantic versioning.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

networktest-0.1.0.tar.gz (16.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

networktest-0.1.0-py3-none-any.whl (14.7 kB view details)

Uploaded Python 3

File details

Details for the file networktest-0.1.0.tar.gz.

File metadata

  • Download URL: networktest-0.1.0.tar.gz
  • Upload date:
  • Size: 16.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.20.1 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.3

File hashes

Hashes for networktest-0.1.0.tar.gz
Algorithm Hash digest
SHA256 afc0eb95d6ba786d0cda3b761d846bd304aef8434cc059bb5997de978e708f43
MD5 c356990ed08f5d62503516d206e9e275
BLAKE2b-256 7c017d81fb10d23612664ef5a38dbc81dad86a7269d713b71c76b8b707bfc5de

See more details on using hashes here.

File details

Details for the file networktest-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: networktest-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 14.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.20.1 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.3

File hashes

Hashes for networktest-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5f3182c828df76899a34d363e515fbaf22af1feee6d7d4e1ea9ee70cb769014c
MD5 ddc36468651f565832dca56951c3bc71
BLAKE2b-256 29413121f105ac32971654d07e67207572f64c9bb33dd1cc2e2f8c8b0b941c0f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page