It's hard to say exactly what is going wrong, without seeing the call stack, but the following general pattern works.

foo.py

def foo():
    pass


def bar():
    result = foo()
    return result["status"]

The with test_foo.py as

import mock

from foo import bar


@mock.patch("foo.foo", return_value={"status": "PASSED"})
def test_add(mock_foo):
    assert bar() == "PASSED"

This general pattern works with pytest test_foo.py in the same directory.

Answer from Josmoor98 on Stack Overflow
🌐
CodiLime
codilime.com › blog › software development › backend › testing apis with pytest: how to effectively use mocks in python
Testing APIs with PyTest: How to Effectively Use Mocks in Python
October 22, 2024 - from http import HTTPStatus import requests import pytest from unittest.mock import patch class APIClient: def get_data(self, url): response = requests.get(url) return response @pytest.fixture def mock_response(): with patch('requests.get') as mock_get: yield mock_get @pytest.mark.parametrize( "status_code", [ HTTPStatus.OK, HTTPStatus.NOT_FOUND, HTTPStatus.UNPROCESSABLE_ENTITY ] ) def test_api_example(mock_response, status_code): mock_response.return_value.status_code = status_code client = APIClient() url = 'http://example.com/api' result = client.get_data(url) assert result.status_code == s
🌐
Readthedocs
requests-mock.readthedocs.io › en › latest › pytest.html
pytest — requests-mock 1.10.1.dev10 documentation
The fixture then provides the same interface as the requests_mock.Mocker letting you use requests-mock as you would expect. >>> import pytest >>> import requests >>> def test_url(requests_mock): ... requests_mock.get('http://test.com', text='data') ...
Discussions

python - Pytest mock / patch of an api call - Stack Overflow
I am trying to understand patching, but I seem to be failing to do so. Currently I am trying to patch an api call inside of the tested function: # function being tested def tested_function(): re... More on stackoverflow.com
🌐 stackoverflow.com
python - How to mock requests using pytest? - Stack Overflow
You can use requests-mock (PyPI), there is a fixture for a pytest usage. More on stackoverflow.com
🌐 stackoverflow.com
python - how to mock the response from a library api in pytest - Stack Overflow
Writing an pytest for a function that is making api call using an installed package. How do you mock the response from the api response? This is how the function looks like import hubspot from pprint More on stackoverflow.com
🌐 stackoverflow.com
How to mock a class which is making an API call outside my function under test?
I’m not a Python expert but I think you should put your function inside of a class, and pass class_A to that class’s constructor, saving it as an instance field e.g. self.receiver. In the function, call self.receiver.receive_file(). In the test you can inject a fake receiver instance. More on reddit.com
🌐 r/pythontips
10
3
October 22, 2024
🌐
Miguendes
miguendes.me › 3-ways-to-test-api-client-applications-in-python
3 Ways to Unit Test REST APIs in Python - miguendes's blog
September 19, 2020 - Master REST API testing in Python. Learn how to test HTTP calls to an external API using VCR.py, pytest-mock and the responses / requests libraries.
🌐
Auth0
auth0.com › blog › mocking-api-calls-in-python
Mocking API calls in Python | Auth0
December 6, 2017 - The nose2 library extends the built-in Python unittest module to make testing easier. You can use unittest or other third-party libraries such as pytest to achieve the same results. The requests library simplifies HTTP calls in Python. For this tutorial, we will be communicating with a fake API on ...
🌐
Pytest With Eric
pytest-with-eric.com › pytest-best-practices › python-rest-api-unit-testing
Python REST API Unit Testing for External APIs | Pytest With Eric
November 18, 2022 - As you can see, calling the External API ALL the time is a bad idea. ... A hybrid one. We can gracefully “mock” the response of the External API thanks to libraries like pytest-mock and requests-mock .
Find elsewhere
🌐
Medium
medium.com › nishkoder › mocking-apis-in-python-tests-with-pytest-and-solid-principles-f92dfdbc7ea5
Mocking APIs in Python Tests with pytest and SOLID Principles | by Nishant Gupta | DataScience with Python — NishKoder | Medium
March 29, 2023 - import pytest from user import User from user_service import UserService from user_repository import UserRepository @pytest.mark.parametrize("user_id, fake_response_data", [ (1, { "id": 1, "name": "John Doe", "email": "john.doe@example.com" }), (2, { "id": 2, "name": "Jane Doe", "email": "jane.doe@example.com" }), ]) def test_get_user_by_id(user_id, fake_response_data, mock_api, user_repository): # Register the mock API call with the correct URL and response data mock_api.get(f"https://api.example.com/users/{user_id}", json=fake_response_data) # Initialize the UserService with the UserReposito
Top answer
1 of 2
1

Have a look at requests-mock. It provides a fixture requests_mock that you can put in your test function. In the function, you mock the API call with requests_mock.get("https://api-url"), and optionally add a response, status code, etc..

2 of 2
1

In your case you need to mock the hubspot.Client object and then mock the appropriate methods that are being called. Your function doesn't make sense just printing when there is an error, you should just let the error propagate up to the caller wherever that is coming from. I slightly modified your function to error out in order to show that and how to test both scenarios.

# src/get_events.py

from hubspot import Client
from hubspot.events.exceptions import ApiException

def get_clicked_events():
    client = Client.create(api_key="YOUR_HUBSPOT_API_KEY")

    try:
        api_response = client.events.get_page(limit=100, event_type="clicked")
    except ApiException:
        raise

    return api_response

from unittest.mock import patch

import pytest

from hubspot import Client
from hubspot.events.exceptions import ApiException

from src.get_events import get_clicked_events


def test_get_clicked_events_success():
    with patch("src.get_events.Client", spec=Client) as mock_client:
        mock_client.configure_mock(
            **{
                "create.return_value": mock_client,
                "events.get_page.return_value": "fizz"
            }
        )

        events = get_clicked_events()
        assert events == "fizz"


def test_get_clicked_events_fail():
    err_msg = "Failed to get events!"

    with patch("src.get_events.Client", spec=Client) as mock_client:
        mock_client.configure_mock(
            **{
                "create.return_value": mock_client,
                "events.get_page.side_effect": ApiException(err_msg)
            }
        )

        with pytest.raises(ApiException) as err:
            get_clicked_events()
            assert err_msg == err.value

Then when running from the root of the repository you can see both tests pass.

platform darwin -- Python 3.8.9, pytest-7.0.1, pluggy-1.0.0
cachedir: .pytest_cache
rootdir: ***
plugins: mock-3.7.0
collected 2 items                                                                                                                                   

tests/test_script.py::test_get_clicked_events_success PASSED                                                                                  [ 50%]
tests/test_script.py::test_get_clicked_events_fail PASSED                                                                                     [100%]

=========================================================== 2 passed============================================================
🌐
DataCamp
datacamp.com › tutorial › pytest-mock
pytest-mock Tutorial: A Beginner’s Guide to Mocking in Python | DataCamp
December 18, 2024 - Learn how to efficiently use pytest-mock for mocking in Python tests. This guide covers setup, basics, and advanced techniques for effective testing.
🌐
Pytest with Eric
pytest-with-eric.com › api-testing › pytest-external-api-testing
How To Write Tests For External (3rd Party) API Calls with Pytest | Pytest with Eric
January 25, 2025 - In this code, we’re testing the upload_file function without making an actual API request by using a mock for requests.post. First, we define stub_upload_response—an expected response that mimics what the real API would return when upload_file is called.
🌐
Medium
medium.com › anitab-org-open-source › my-week-3-gsoc20-journey-with-anitab-org-dce2c4a7e855
Mocking API calls using Python unittests.mock | by Maya Treacy | AnitaB.org Open Source | Medium
July 15, 2020 - Another difference is for the ‘Assert’ section, beside confirming the error response message and status code received, I also wanted to make sure that the line response.raise_for_status() on the post_request() method never gets called in the event of error. Now, it’s done for real 🤣. To know more about unittest.mock, you can read the python documentation here · Anyway, skip forward, I’ve managed to overcome that first challenge of the week and completed the test cases for Register backend with 100% test-coverage (on Register related functionality) according to pytest-cov. 💃🎉 ... PS: You can find the code I’ve written on mocking the APIs on BridgeInTech backend repository under `tests` folder.
🌐
Python
docs.python.org › 3 › library › unittest.mock.html
unittest.mock — mock object library
Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway).
🌐
PyPI
pypi.org › project › pytest-mock-server
pytest-mock-server · PyPI
Download URL: pytest_mock_server-0.3.0-py3-none-any.whl
      » pip install pytest-mock-server
    
Published   Jan 09, 2022
Version   0.3.0
🌐
Real Python
realpython.com › testing-third-party-apis-with-mocks
Understanding the Python Mock Object Library – Real Python
January 18, 2025 - To do so, install mock from the Python Package Index (PyPI) using pip: ... You may want to create and activate a virtual environment before installing the package. unittest.mock provides a class called Mock, which you’ll use to imitate real objects in your codebase.
🌐
Chang Hsin Lee
changhsinlee.com › pytest-mock
pytest: How to mock in Python - Chang Hsin Lee
May 2, 2020 - Write a single test on compute() that contains both the api call expensive_api_call() and the computation result + x. Takes 1,000 seconds to run. Write two tests: mock the API call in the test for compute(), and write another test to test that ...
🌐
Medium
pradappandiyan.medium.com › create-and-test-a-mock-api-server-in-python-using-flask-and-pytest-with-github-actions-ci-ca884f6a2396
Create and Test a Mock API Server in Python Using Flask and Pytest (with GitHub Actions CI) | by Pradap Pandiyan | Medium
July 5, 2025 - python-api-mock-test/ ├── app.py # Flask mock server ├── requirements.txt # Project dependencies ├── test_mock_apis.sh # Optional: curl test script ├── tests/ │ └── test_api.py # Pytest test suite
🌐
Newtum
apitest.newtum.com › examples › python-test-api-with-pytest
How to Test an API in Python with `pytest` and `mocker` | API Navigator
import requests # Assuming pytest and pytest-mock are installed # A simple function that interacts with an API def get_todo_title(todo_id): response = requests.get(f"https://jsonplaceholder.typicode.com/todos/{todo_id}") if response.status_code == 200: return response.json()['title'] return None def test_get_todo_title_success(mocker): # Mock the requests.get call mock_response = mocker.Mock() mock_response.status_code = 200 mock_response.json.return_value = {'title': 'delectus aut autem'} mocker.patch('requests.get', return_value=mock_response) # Call the function and assert the result title
🌐
Pytest with Eric
pytest-with-eric.com › mocking › pytest-mocking
How To Mock In Pytest? (A Comprehensive Guide) | Pytest with Eric
March 27, 2023 - Some popular mocking frameworks include Mockito for Java, unittest.mock and pytest-mockfor Python, and Moq for .NET. ... Imagine, you’re testing a Rest API to get Cat Facts. Every time you run your test, it calls an external API and depending on the server’s capacity to handle requests, ...