[QUESTION] How to test BackgroundTasks?
See original GitHub issueI’m wondering if there is a recommended way to stub out BackgroundTasks in unit tests? If I’m running a test for an endpoint I definitely don’t want to run any BackgroundTasks that endpoint is creating (e.g. sending emails).
The way I’m doing this right now which seems to work is by creating a wrapper dependency so I can then override it like any other custom dependency. Like this:
def tasks(background_tasks: BackgroundTasks) -> BackgroundTasks:
""" Just a wrapper dependency for BackgroundTasks """
return background_tasks
@router.post("/")
def my_endpoint(background_tasks: BackgroundTasks = Depends(tasks)):
tasks.add_task(...)
Then in my conftest.py I do something like:
@pytest.fixture
def mock_backround_tasks(mocker):
""" The mocked background_tasks dependency """
return mocker.MagicMock(autospec=BackgroundTasks)
app.dependency_overrides[tasks] = lambda: mock_backround_tasks
This feels a bit clunky, I’m wondering if there is a better way to do something like this and if you might add a Testing BackgroundTasks section to the docs with your recommendation?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:6 (4 by maintainers)
Top Results From Across the Web
Mocking `background_tasks.add_task` - Stack Overflow
Here's a working example. Create two files : main.py. from fastapi import FastAPI, BackgroundTasks app = FastAPI() def ...
Read more >Background Tasks - FastAPI
To see an example, check the Project Generators, they all include Celery already configured. But if you need to access variables and objects...
Read more >New BackgroundTask in SwiftUI and How to Test It - Holy Swift
Learn the new BackgroundTask in SwiftUI and how to test It. Check how to automatically reschedule it and debug the background tasks in...
Read more >Background Tasks | Apple Developer Documentation
Use the BackgroundTasks framework to keep your app content up to date and run tasks requiring minutes to complete while your app is...
Read more >Efficiency awaits: Background tasks in SwiftUI - Videos
Background Tasks help apps respond to system events and keep time-sensitive data ... Ask with tag wwdc2022-10142 · Search the forums for tag...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
In case people want an example:
In addition to the comments above, it is also possible to modify the behaviour of a particular background task using the built-in pytest fixture
monkeypatch
.