How to mock requests using pytest? [duplicate]

You can use requests-mock (PyPI), there is a fixture for a pytest usage.

For your example:

from correct.package import __BASE_URL
from requests import HTTPError


def test_get_employee(requests_mock):
    test_id = 'random-id'
    requests_mock.get(f'{__BASE_URL}/employee/{test_id}', json= {'name': 'awesome-mock'})
    resp = get_employee('random-id')
    assert resp == {'name': 'awesome-mock'}

def test_absent_employee(requests_mock):
    test_id = 'does_not_exist'
    requests_mock.get(f'{__BASE_URL}/employee/{test_id}', status_code=404)
    with pytest.raises(HTTPError):
        resp = get_employee(test_id)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)