opensafely-core / job-server

A server for mediating jobs that can be run in an OpenSAFELY secure environment. q.v. job-runner
https://jobs.opensafely.org
Other
5 stars 10 forks source link

Replace Zen Queries with `django_assert_num_queries` on rendered template #4391

Open lucyb opened 5 days ago

lucyb commented 5 days ago

We've been bitten by Zen Queries a few times (including with a production outage). I think we can replace this dependency with unit tests that use the Django test client and the django_assert_num_queries fixture. This will tell us about errors when we run our tests rather than at runtime. It should also provide developers with a more obvious error message that they can debug and fix (example one, example two).

We are already doing this in some places, such as the unauthenticated index page: https://github.com/opensafely-core/job-server/blob/327fbd971c28d8b19bcc6f96fa39502c1afa8589/tests/unit/jobserver/views/test_index.py#L70-L78

As another example, a test for the JobDetail page might look like this (slack :thread: ):

def test_jobrequestdetail_count_queries_in_rendered_template(
    client, rf, django_assert_num_queries
):
    job_request = JobRequestFactory()
    JobFactory(job_request=job_request, updated_at=minutes_ago(timezone.now(), 31))
    request = rf.get("/")
    request.user = UserFactory()

    with django_assert_num_queries(8):
        response = JobRequestDetail.as_view()(
            request,
            project_slug=job_request.workspace.project.slug,
            workspace_slug=job_request.workspace.name,
            pk=job_request.pk,
        )

    with django_assert_num_queries(10):
        response = client.get(job_request.get_absolute_url())
        assert response.status_code == 200
        assert job_request.identifier in response.rendered_content