import pytest from unittest.mock import MagicMock @pytest.fixture def mock_http_request(mocker): m = mocker.patch('http.request', autospec=True, spec_set=True, return_value='sample response') yield m def test_get_data(mock_http_request): # this mock will replace the actual http.request function in our get_data function # and always return "sample response" response = get_data('http://example.com') assert response == 'sample response'
import pytest from unittest.mock import MagicMock @pytest.fixture def mock_path_exists(mocker): m = mocker.patch('os.path.exists', autospec=True, spec_set=True, return_value=True) yield m def test_file_processing(mock_path_exists,): # this mock will replace the actual os.path.exists function in our file_processing function # and always return True, allowing us to test when the file exists result = file_processing('example.txt') assert result == 'file exists'In both examples, we use the `pytest_mock` library to create a mock function and use it to replace the actual function in our test functions. The package libraries being mocked are `http` and `os`, respectively.