question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] How to test BackgroundTasks?

See original GitHub issue

I’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:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

20reactions
Kludexcommented, Aug 26, 2020

In case people want an example:

    with patch("fastapi.BackgroundTasks.add_task") as mock:

        def side_effect(*args, **kwargs):
            <do something>

        mock.side_effect = side_effect
0reactions
mateoradmancommented, Nov 16, 2022

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.

def do_nothing(*_: list[Any]) -> None:
    return None

@pytest.mark.anyio
async def test_create_something(
    monkeypatch,
    async_client: AsyncClient,
    db: Session,
) -> None:
    monkeypatch.setattr("app.background_tasks.handle_uploaded_file", do_nothing)  # make the background_task do_nothing
    r = await async_client.post(
        ....
    )
    assert r.status_code == 201
Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found