Skip to content

Instantly share code, notes, and snippets.

@ozydingo
Last active February 21, 2022 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozydingo/381d8c2825bcec366ac44ad5773f2dc3 to your computer and use it in GitHub Desktop.
Save ozydingo/381d8c2825bcec366ac44ad5773f2dc3 to your computer and use it in GitHub Desktop.
Configure and use requests-mock for all tests without fussing with decorators or function params in your tests
import pytest
import requests_mock
# By autousing this yielding fixture, all tests with have requests_mock enabled with
# the registered stubbed responses as defined here
@pytest.fixture(autouse=True)
def stub_or_disable_requests():
with requests_mock.Mocker() as mocker:
mocker.get('//example.com/mock1', text='example.com mock 1')
mocker.get('/mock2', text='any domain mock 2')
yield
import pytest
import requests
import requests_mock
def test_unmocked_get():
with pytest.raises(requests_mock.exceptions.NoMockAddress):
requests.get("http://www.google.com")
def test_session():
session = requests.Session()
with pytest.raises(requests_mock.exceptions.NoMockAddress):
session.get("http://www.google.com")
def test_mocked_get():
response1 = requests.get("https://example.com/mock1")
response2 = requests.get("https://example.com/mock2")
with pytest.raises(requests_mock.exceptions.NoMockAddress):
requests.get("https://anything.com/mock1")
response4 = requests.get("https://anything.com/mock2")
assert response1.text == "example.com mock 1"
assert response2.text == "any domain mock 2"
assert response4.text == "any domain mock 2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment