import pytest def my_function(): return "Hello, world!" def test_my_function(mocker): mocker.patch('my_module.my_function', return_value='Hi there!') assert my_function() == 'Hi there!'
import pytest import requests def get_data(): response = requests.get('https://jsonplaceholder.typicode.com/todos/1') return response.json() def test_get_data(mocker): mock_response = {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False} mocker.patch('requests.get', return_value=mock_response) assert get_data() == mock_responseIn this example, we use the mocker fixture to create a mock object of requests.get(). We then patch the function to return a mocked response object, which we have defined as a dictionary. Finally, we assert that the mocked response object is returned by the get_data() function. Package/Library: pytest_mock