pytest-django icon indicating copy to clipboard operation
pytest-django copied to clipboard

Adds ability to capture all the db queries at once

Open kingbuzzman opened this issue 9 months ago • 4 comments
trafficstars

Related PR

When managing multiple databases—over six in our case—we don’t focus on tracking queries for each one individually (e.g., db1 vs. db2 vs. db3). Instead, our priority is the overall number of queries executed. If that total seems off, we then dive deeper to identify the specific issue.

Old approach:

@pytest.mark.django_db(databases=["default", "log", "backoffice", "cart"])
def test_models(django_assert_num_queries):
    with django_assert_num_queries(3), django_assert_num_queries(2, using="log"), django_assert_num_queries(3, using="backoffice"), django_assert_num_queries(1, using="cart"):
        Model.objects.create(...)
        ...

Since we use a django database router these model's data store can change location due to size at any moment. When this happens, all our tests will break.

New approach:

@pytest.mark.django_db(databases=["default", "log", "backoffice", "cart"])
def test_models(django_assert_num_queries_all_connections):
    with django_assert_num_queries_all_connections(9):
        Model.objects.create(...)
        ...

kingbuzzman avatar Feb 10 '25 17:02 kingbuzzman