pytest assert message customization with variable introspection

you could use Python built-in capability to show custom exception message: assert response.status_code == 200, f”My custom msg: actual status code {response.status_code}” Or you can built a helper assert functions: def assert_status(response, status=200): # you can assert other status codes too assert response.status_code == status, \ f”Expected {status}. Actual status {response.status_code}. Response text {response.text}” # … Read more

pytest and Failed: Database access not allowed, use the “django_db” mark, or the “db” or “transactional_db” fixtures to enable it

Solution: import pytest @pytest.mark.django_db class TestExample: def test_one(): … Assume that you’ve created a TestExample class inside your test file and it should be decorated with @pytest.mark.django_db. It should solve your problem.

pytest ScopeMismatch error: how to use fixtures properly

The db fixture has the function scope for a reason, so the transaction rollbacks on the end of each test ensure the database is left in the same state it has when test starts. Nevertheless, you can have the session/module scoped access to database in fixture by using the django_db_blocker fixture: @pytest.fixture(scope=”module”) def get_all_models(django_db_blocker): with … Read more

Disable autouse fixtures on specific pytest marks

You can also use the request object in your fixture to check the markers used on the test, and don’t do anything if a specific marker is set: import pytest @pytest.fixture(autouse=True) def autofixt(request): if ‘noautofixt’ in request.keywords: return print(“patching stuff”) def test1(): pass @pytest.mark.noautofixt def test2(): pass Output with -vs: x.py::test1 patching stuff PASSED x.py::test2 … Read more