Search code examples
pythondjangodjango-testingpytest-django

How to test Django Querysets are equal using pytest-django


What's the best / most readable way to assert two querysets are equal? I've come up with a few solutions:

# option 1
assert sorted(qs1.values_list("pk", flat=True)) == sorted(qs2.values_list("pk", flat=True))

# option 2 (need to assert length first because set might remove duplicates)
assert len(qs1) == len(qs2)
assert set(qs1) == set(qs2)

I know Django has a method django.test.TransactionTestCase.assertQuerysetEqual. Does pytest-django have something similar? I don't see it in the documentation.


Solution

  • It's there in the starting lines of the link that you suggested:

    Assertions
    All of Django’s TestCase Assertions are available in pytest_django.asserts, e.g. from pytest_django.asserts import assertTemplateUsed

    Similarly you can use, from pytest_django.asserts import assertQuerysetEqual