0
0
Djangoframework~5 mins

Mocking external services in Django - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is mocking in the context of testing external services?
Mocking means creating a fake version of an external service to test your code without calling the real service. It helps test how your code behaves when the service responds in certain ways.
Click to reveal answer
beginner
Which Python library is commonly used in Django to mock external HTTP requests?
The unittest.mock library is commonly used to replace parts of your code with mock objects. For HTTP requests, libraries like requests-mock or patching requests.get with unittest.mock are popular.
Click to reveal answer
beginner
Why should you mock external services in Django tests?
Mocking avoids slow or unreliable tests caused by real external services. It also prevents using real data or costs, and lets you test how your code handles different responses or errors.
Click to reveal answer
intermediate
How do you use patch from unittest.mock to mock an external API call in Django?
You use @patch('path.to.external.call') above your test function to replace the real call with a mock. Inside the test, you set what the mock should return or raise to simulate the external service.
Click to reveal answer
intermediate
What is a common pattern to test error handling when mocking external services?
You configure the mock to raise an exception or return an error response. Then you check if your code handles it gracefully, like retrying, logging, or returning a fallback result.
Click to reveal answer
What does mocking an external service help you avoid in tests?
ARunning tests locally
BCalling the real external service
CUsing Django models
DWriting any test code
Which Python module provides the patch decorator for mocking?
Arequests
Bdjango.test
Cunittest.mock
Dpytest
When mocking an external API call, what can you set on the mock object?
AUser sessions
BDatabase connections
CCSS styles
DReturn values and exceptions
Why is it important to test error handling with mocks?
ATo ensure your code handles failures gracefully
BTo speed up the real API
CTo avoid writing tests
DTo change the database schema
Which of these is NOT a benefit of mocking external services?
ATesting UI layout
BFaster tests
CAvoiding real service costs
DControlling test scenarios
Explain how you would mock an external HTTP request in a Django test using unittest.mock.
Think about replacing the real call with a fake one that returns controlled data.
You got /4 concepts.
    Describe why mocking external services is important for reliable and fast Django tests.
    Consider what happens if your tests depended on real internet calls.
    You got /4 concepts.