Package: networktest
NetworktestA library to test and enforce testing rules for Python applications that make network requests.InstallationpipinstallnetworktestBlocking network requestsnetworktest provides a context manager NetworkBlocker that can be used to prevent tests or an application from making network requests.importurllib.requestfromnetworktestimportNetworkBlockerwithNetworkBlocker():# A NetworkBlockException will be raisedurllib.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.importurllib.requestfromnetworktestimportNetworkBlockerfrommy_databaseimportDatabasewithNetworkBlocker(allowed_packages=NetworkBlocker.AllowablePackages.DATASTORE):# This is fineDatabase.query('SELECT 1')# A NetworkBlockException will be raisedurllib.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.importurllib.requestfromnetworktestimportNetworkBlockerwithNetworkBlocker(mode=NetworkBlocker.Modes.WARNING):# This will be allowed but a warning will be displayedurllib.request.urlopen('http://127.0.0.1').read()TestCase SupportSome TestCases are provided that will apply NetworkBlocker to all tests in that case with some default settings.importurllib.requestfrommy_databaseimportDatabasefromnetworktestimportNetworkBlockedTest,NetworkLimitedTestclassMyTest(NetworkBlockedTest):deftest_blocker(self):# A NetworkBlockException will be raisedurllib.request.urlopen('http://127.0.0.1').read()classMyOtherTest(NetworkLimitedTest):deftest_blocker(self):# This is fineDatabase.query('SELECT 1')# A NetworkBlockException will be raisedurllib.request.urlopen('http://127.0.0.1').read()pytest Supportpytest 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.frompytestimportmark@mark.networkblockeddeftest_blocked(self):# A NetworkBlockException will be raisedurllib.request.urlopen('http://127.0.0.1').read()@mark.networklimiteddeftest_limited(self):# This is fineDatabase.query('SELECT 1')# A NetworkBlockException will be raisedurllib.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)defnetworkblocker():withNetworkBlocker():yieldMocking API requestsHttpApiMock is provided to help with mocking API requests in unit and functional tests.importurllib.requestfromnetworktest.mockimportHttpApiMockclassMyApiMock(HttpApiMock):hostnames=['my-api']endpoints=[HttpApiMockEndpoint(operation_id='example',match_pattern=b'^GET /example/(?P<example_id>.*?)/',response=lambdagroups:(418,{'id':groups['example_id'],}))]deftest_my_api():withMyApiMock()asmock_api:response=urllib.request.urlopen('http://my-api/')response.read()# Requests which do not have a matched endpoint return a 200 response code by defaultassertresponse.getcode()==200try:# This request matches the 'example' endpoint defined in MyApiMockurllib.request.urlopen('http://my-api/example/1234/').read()excepturllib.error.HTTPErrorase:# The response is the one defined for the 'example' endpointasserte.code==418asserte.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=lambdagroups:(204,None)response=urllib.request.urlopen('http://my-api/')response.read()assertresponse.getcode()==204Integration testsHttpApiMock may also be used to create assertions for integration tests without preventing API requests from being made.importurllib.requestfromnetworktest.mockimportHttpApiMockclassMyApiMock(HttpApiMock):hostnames=['my-api']endpoints=[HttpApiMockEndpoint(operation_id='example',match_pattern=b'^GET /example/(?P<example_id>.*?)/',response=lambdagroups:(204,None))]deftest_my_api():withMyApiMock(Mode=MyApiMock.Modes.WATCH)asmock_api:urllib.request.urlopen('http://my-api/example/1234/').read()mock_api.example.request_mock.assert_called_once()VersioningThis package strictly followssemantic versioning.