python / expert
Snippet
Isolated Async Generator Mocking in Django Unit Tests
Demonstrates isolated unit testing of async generator consumers in Django using inline async generator stubs and mock patching.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from unittest.mock import patchfrom django.test import SimpleTestCaseclass AsyncStreamServiceTest(SimpleTestCase):async def test_async_generator_stream(self):async def mock_stream():yield {"status": "processing"}yield {"status": "complete"}with patch("services.external.fetch_stream", side_effect=mock_stream):from services.external import fetch_streamresults = [data async for data in fetch_stream()]self.assertEqual(len(results), 2)self.assertEqual(results[1]["status"], "complete")
django
Breakdown
1
class AsyncStreamServiceTest(SimpleTestCase):
Uses SimpleTestCase to perform fast unit testing without database setup.
2
async def test_async_generator_stream(self):
Declares an asynchronous test method supported natively by Django's test runner.
3
async def mock_stream():
Defines an inline async generator function yielding stubbed stream packets.
4
with patch("services.external.fetch_stream", side_effect=mock_stream):
Replaces target service function with the async generator stub for test duration.