Logo

dev-resources.site

for different kinds of informations.

How to debug your Python mocks or imports

Published at
7/28/2024
Categories
python
unittest
mock
testing
Author
funtimes
Categories
4 categories in total
python
open
unittest
open
mock
open
testing
open
Author
8 person written this
funtimes
open
How to debug your Python mocks or imports

Hands up if you've spent 20 minutes making a feature then 2 hours testing it πŸ™‹. I recently struggled with mocking an object declared globally in a file I was testing. It was making all my tests fail because its __init__ method made a call to AWS which wouldn't have the right credentials everywhere the test was run.

Because of my relatively complicated directory structure, I was struggling to find exactly the right module to mock. You might have read this relatively simple where to mock section in the unittest docs but here is how to figure where to mock out for any scenario, no matter how complicated.

I first commented out the call to the AWS client in MyClient.py. As it was called globally the NoCredentialsError was causing all my tests to fail before any methods or tests were executing πŸ˜΅β€πŸ’«. Then I inspected the sys.modules dict containing all the modules that your test file can see and the path to them.

# test_app.py
import sys
import json

def test_lambda_handler():
    print(sys.modules)

    assert True == False
Enter fullscreen mode Exit fullscreen mode

It'll show your own modules at the bottom.

...
    "boto3.resources.factory": <module "boto3.resources.factory" from "/usr/local/lib/python3.11/site-packages/boto3/resources/factory.py">,
    "boto3.session": <module "boto3.session" from "/usr/local/lib/python3.11/site-packages/boto3/session.py">,
    "boto3": <module "boto3" from "/usr/local/lib/python3.11/site-packages/boto3/__init__.py">,
    "hello_world.util": <module "hello_world.util" from "/Users/sophiewarner/repos/project/hello_world/util.py">,
    "hello_world.service.my_client": <module "hello_world.service.my_client" from "/Users/sophiewarner/repos/project/hello_world/service/slack_client.py">,
    "hello_world.app": <module "hello_world.app" from "/Users/sophiewarner/repos/project/hello_world/app.py">
}
Enter fullscreen mode Exit fullscreen mode

From here you can just replace what sys thinks is at that path with a mock.

# test_app.py
import sys
import json
from unittest.mock import MagicMock

sys.modules["hello_world.service.my_client"] = MagicMock()
from hello_world import app
event = {...}

def test_lambda_handler(event):
    ret = app.lambda_handler(event, "")
    assert ret["statusCode"] == 200
Enter fullscreen mode Exit fullscreen mode

This will update sys.modules for your entire python session. An improvement on this would be patching it just for one test.

# test_app.py
import sys
import json
from unittest.mock import MagicMock, patch

event = {...}

with patch.dict("sys.modules", {"hello_world.service.my_client": MagicMock()}):
def test_lambda_handler(event):
    from hello_world import app
    ret = app.lambda_handler(event, "")
    assert ret["statusCode"] == 200
Enter fullscreen mode Exit fullscreen mode

βœ… No more mocking and patching headaches.

mock Article's
30 articles in total
Favicon
FAQ β€” Bloomer Mock Data Generator
Favicon
Best Practices: How to Make Your API Smarter and More Flexible
Favicon
Testing ReactJS Context - A Guide with test-doubles
Favicon
The beauty of MSW
Favicon
Realistic data Generation Using Bloomer Mock
Favicon
Testing Spring Boot Applications: Unit, Integration, and Mocking β€” A Comprehensive Guide
Favicon
How to debug your Python mocks or imports
Favicon
Is there any option for Mock EncryptAsync() in Azure.Security.KeyVault.Keys.Cryptography
Favicon
Learn to Simulate Online APIs Without Server Infrastructure
Favicon
Diferenças entre o jest.spyOn e jest.mock
Favicon
Mock Class Constructor in Jest Test with Mocking Partials
Favicon
You stub/mock incorrectly
Favicon
Step-by-Step Tutorial on Setting Up a Mock Server Using Postman
Favicon
Mocking ES6 Class Instances with Jest
Favicon
Create free mock apis with unlimited storage
Favicon
Free API server with unlimited access
Favicon
Handle Variables and Dynamic Values with `jest.fn()`
Favicon
A way to mock PHP internal functions with xepozz/internal-mocker
Favicon
Mock vs Stub vs Fake: Understand the difference
Favicon
Mock modules properly with Jest and Typescript
Favicon
Simplified Strategies for Mocking API Calls
Favicon
Fastify Meets WireMock: External Service Mocking
Favicon
OpenAI API Mock for Devs on a Budget
Favicon
Mock S3 for AWS SDK for JavaScript (v3)
Favicon
Simplifying Kafka Testing in Python: A Mockafka-py Tutorial
Favicon
When to use Mock API?
Favicon
Datafaker: Simplifying Test Data Generation for Java and Kotlin
Favicon
NestJS: Mocking Databases for Efficient Tests
Favicon
Understanding Mocks, Stubs, and Fakes in Software Testing
Favicon
How to Typescript to JSON with Butlermock

Featured ones: