### Add Editable Install to requirements.txt Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/managing_python_path.md Include this line in your `requirements.txt` file to ensure your project is installed in editable mode along with other dependencies. ```text # requirements.txt -e . django pytest-django ``` -------------------------------- ### Basic pyproject.toml for Editable Install Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/managing_python_path.md Create a `pyproject.toml` file with this content to get started with installing your project in editable mode using pip. This is a minimal configuration for local development. ```toml # pyproject.toml [build-system] requires = [ "setuptools>=61.0.0", ] build-backend = "setuptools.build_meta" ``` -------------------------------- ### Install Pytest-xdist Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/usage.md Install the pytest-xdist plugin to enable parallel test execution. This plugin is typically installed using pip. ```bash pip install pytest-xdist ``` -------------------------------- ### Install Project in Editable Mode Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/managing_python_path.md Use this pip command to install your project in editable mode, making its code available on the Python path. This is recommended for local development. ```bash pip install --editable . ``` -------------------------------- ### Install pytest-django Source: https://github.com/pytest-dev/pytest-django/blob/main/README.rst Install the pytest-django package using pip. This command is used to add the testing tool to your project environment. ```bash pip install pytest-django ``` -------------------------------- ### Example Usage of urls Mark Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Demonstrates how to use the @pytest.mark.urls decorator to test a specific URL configuration and assert the response content. ```python @pytest.mark.urls('myapp.test_urls') def test_something(client): assert b'Success!' in client.get('/some_url_defined_in_test_urls/').content ``` -------------------------------- ### Modify App Before Django Setup with Pytest Plugin Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Implement a pytest plugin using pytest_load_initial_conftests with tryfirst=True to modify Django apps before django.setup() is called. ```python @pytest.hookimpl(tryfirst=True) def pytest_load_initial_conftests(early_config, parser, args): import project.app.signals def noop(*args, **kwargs): pass project.app.signals.something = noop ``` -------------------------------- ### Randomize PostgreSQL Sequence Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Customizes the django_db_setup fixture to give a PostgreSQL sequence a random starting value. Useful for preventing hard-coded primary key IDs in tests. ```python import random import pytest from django.db import connection @pytest.fixture(scope='session') def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): cur = connection.cursor() cur.execute('ALTER SEQUENCE app_model_id_seq RESTART WITH %s;', [random.randint(10000, 20000)]) ``` -------------------------------- ### Share Database Across xdist Processes Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Configures pytest-django to use the same database across all xdist worker processes. This overrides the default behavior where each process gets its own database, which is typically needed for transactional tests. ```python import pytest @pytest.fixture(scope='session') def django_db_modify_db_settings(): pass ``` -------------------------------- ### Test Transactions with Django_db Mark Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Use the 'transaction=True' argument within the '@pytest.mark.django_db' decorator to enable transaction-based testing. This style flushes the database between tests for isolation but can be slower due to setup. ```python @pytest.mark.django_db(transaction=True) def test_spam(): pass # test relying on transactions ``` -------------------------------- ### Run all tests Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/contributing.md Use the Makefile to set up a virtual environment and run all tests. ```bash $ make test ``` -------------------------------- ### Create Test Database from Custom SQL Script (SQLite) Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Replaces the default django_db_setup fixture to create a test database using a custom SQL script, demonstrated with SQLite's executescript method. For other databases, cursor().execute() might be used. ```python import pytest from django.db import connection @pytest.fixture(scope='session') def django_db_setup(django_db_blocker): with django_db_blocker.unblock(): with connection.cursor() as c: c.executescript(''' DROP TABLE IF EXISTS theapp_item; CREATE TABLE theapp_item (id, name); INSERT INTO theapp_item (name) VALUES ('created from a sql script'); ''') ``` -------------------------------- ### Run tox for multiple configurations Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/contributing.md Use tox to run the test suite against different Python, Django, and database configurations. ```bash $ tox ``` -------------------------------- ### Use a Read-Only Database Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Replaces django_db_setup to avoid database creation/migrations, allowing direct use of the database without rollbacks or truncating. Tests must not change the database state. ```python import pytest @pytest.fixture(scope='session') def django_db_setup(): """Avoid creating/setting up the test database""" pass @pytest.fixture def db_access_without_rollback_and_truncate(request, django_db_setup, django_db_blocker): django_db_blocker.unblock() yield django_db_blocker.restore() ``` -------------------------------- ### Activate virtual environment Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/contributing.md Activate the created virtual environment to run tests. ```bash $ source bin/activate ``` -------------------------------- ### Specify Test Files or Directories Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/usage.md Select specific test files or directories to run by listing them on the command line. This allows for targeted test execution. ```bash pytest test_something.py a_directory ``` -------------------------------- ### Create virtual environment Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/contributing.md Manually create a virtual environment with pytest and the latest stable Django version. ```bash $ make testenv ``` -------------------------------- ### Configure Django Settings Programmatically in conftest.py Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Use django.conf.settings.configure() in your conftest.py to set up settings when DJANGO_SETTINGS_MODULE is not defined. ```python from django.conf import settings def pytest_configure(): settings.configure(DATABASES=...) ``` -------------------------------- ### Configure Django Settings with pyproject.toml Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/tutorial.md Alternatively, configure the Django settings module using pyproject.toml for projects using this configuration format. ```toml [tool.pytest.ini_options] DJANGO_SETTINGS_MODULE = "yourproject.settings" ``` -------------------------------- ### Run tox with specific environments Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/contributing.md Execute tox for a subset of configurations using the -e flag. ```bash $ tox -e py39-dj42-postgres,py310-dj52-mysql ``` -------------------------------- ### Set Django Settings via Command Line Option Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Use the --ds command-line option to specify Django settings for the current test run. ```bash $ pytest --ds=test.settings ``` -------------------------------- ### Combine coverage files and generate report Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/contributing.md After running tests for coverage, combine all generated .coverage files and create an HTML report. ```bash $ coverage combine $ coverage html ``` -------------------------------- ### Populate Test Database with Fixture Data (Session Scope) Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Populates the test database once per session using Django's loaddata command. This is suitable for tests that do not use transactional or live_server fixtures, ensuring data is available without resetting between tests. ```python import pytest from django.core.management import call_command @pytest.fixture(scope='session') def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command('loaddata', 'my_fixture.json') ``` -------------------------------- ### Use Django Test Client Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Provides an instance of django.test.Client for making requests. For authenticated requests, use client.force_login() or client.login(). ```python def test_with_client(client): response = client.get('/') assert response.content == 'Foobar' ``` ```python def test_with_authenticated_client(client, django_user_model): username = "user1" password = "bar" user = django_user_model.objects.create_user(username=username, password=password) # Use this: client.force_login(user) # Or this: client.login(username=username, password=password) response = client.get('/private') assert response.content == 'Protected Area' ``` -------------------------------- ### Populate Test Database with Model Data (Function Scope) Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Populates the test database for each test function using model creation. This is necessary for transactional tests or when using the live_server fixture, as the database is reset between tests. ```python import pytest from myapp.models import Widget @pytest.fixture(scope='function') def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): Widget.objects.create(...) ``` -------------------------------- ### Configure DJANGO_CONFIGURATION in pyproject.toml Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Set the DJANGO_CONFIGURATION in your pyproject.toml file for persistent configuration with django-configurations. ```toml [tool.pytest.ini_options] DJANGO_CONFIGURATION = "MySettings" ``` -------------------------------- ### Configure Django Settings with pytest.ini Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/tutorial.md Create a pytest.ini file in your project root to specify the Django settings module for pytest. ```ini [pytest] DJANGO_SETTINGS_MODULE = yourproject.settings ``` -------------------------------- ### Create User with Django User Model Fixture Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Use the `django_user_model` fixture to create a user with the project's configured user model. ```python def test_new_user(django_user_model): django_user_model.objects.create_user(username="someone", password="something") ``` -------------------------------- ### Set Django Configuration via Command Line Option Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Use the --dc command-line option to specify the Django configuration class for django-configurations. ```bash $ pytest --dc=MySettings ``` -------------------------------- ### Run pytest with specific settings Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/contributing.md Invoke pytest to run the test suite, specifying a Django settings file. ```bash $ pytest --ds=pytest_django_test.settings_sqlite ``` -------------------------------- ### Configure Test File Discovery Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/tutorial.md Optionally, add this line to pytest.ini to instruct pytest to collect tests in Django's default app layouts. ```ini python_files = tests.py test_*.py *_tests.py ``` -------------------------------- ### Run Test Suite with pytest Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/tutorial.md Invoke your test suite directly using the pytest command. ```bash pytest ``` -------------------------------- ### Configure Python Path and Settings Module Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/managing_python_path.md For a project with a 'src' layout and tests in a separate 'tests' package, specify the `DJANGO_SETTINGS_MODULE` and add both the project root and 'src' directory to the `pythonpath` in `pytest.ini`. ```ini [pytest] DJANGO_SETTINGS_MODULE = tests.settings pythonpath = . src ``` -------------------------------- ### Configure Django Settings in pyproject.toml (pytest 9.0+) Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/index.md Configure DJANGO_SETTINGS_MODULE and python_files using the native TOML format in pyproject.toml for pytest 9.0 and later. ```toml # -- Example FILE: pyproject.toml [tool.pytest] DJANGO_SETTINGS_MODULE = "test.settings" # -- recommended but optional: python_files = ["test_*.py", "*_test.py", "testing/python/*.py"] ``` -------------------------------- ### Use Async Django Test Client Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Provides an instance of django.test.AsyncClient for making asynchronous requests, requiring pytest-asyncio. Requests must be awaited. ```python import pytest @pytest.mark.asyncio async def test_with_async_client(async_client): response = await async_client.get('/') assert response.content == 'Foobar' ``` -------------------------------- ### Configure Pytest.ini for Database Reuse Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Add '--reuse-db' to the 'addopts' setting in your project's 'pytest.ini' file to automatically reuse the test database across test runs. This significantly speeds up test startup times by avoiding database recreation. ```ini [pytest] addopts = --reuse-db ``` -------------------------------- ### Set DJANGO_CONFIGURATION via Environment Variable Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Use the DJANGO_CONFIGURATION environment variable when using django-configurations to specify the settings class. ```bash $ export DJANGO_CONFIGURATION=MySettings $ pytest ``` -------------------------------- ### Request Database Access with django_db Mark Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Mark a test function to ensure the database is set up correctly. Each test runs in its own transaction, rolled back at the end. This is the default behavior for Django's TestCase. ```python @pytest.mark.django_db() ``` -------------------------------- ### Use Admin Django Test Client Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Provides an instance of django.test.Client logged in as an admin user. This fixture automatically marks the test for database use. ```python def test_an_admin_view(admin_client): response = admin_client.get('/admin/') assert response.status_code == 200 ``` -------------------------------- ### Capture and Execute on Commit Callbacks Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Captures transaction.on_commit callbacks and optionally executes them upon exiting the context manager. Useful for testing asynchronous operations triggered by commits. ```python def test_on_commit(client, mailoutbox, django_capture_on_commit_callbacks): with django_capture_on_commit_callbacks(execute=True) as callbacks: response = client.post( '/contact/', {'message': 'I like your site'}, ) assert response.status_code == 200 assert len(callbacks) == 1 assert len(mailoutbox) == 1 assert mailoutbox[0].subject == 'Contact Form' assert mailoutbox[0].body == 'I like your site' ``` ```python from pytest_django import DjangoCaptureOnCommitCallbacks def test_on_commit( django_capture_on_commit_callbacks: DjangoCaptureOnCommitCallbacks, ): ... ``` -------------------------------- ### Use Async Django RequestFactory Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Provides an instance of django.test.AsyncRequestFactory, requiring pytest-asyncio. Requests are awaited. ```python import pytest from myapp.views import my_view @pytest.mark.asyncio async def test_details(async_rf): request = await async_rf.get('/customer/details') response = my_view(request) assert response.status_code == 200 ``` -------------------------------- ### Enable Database Access for All Tests Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/faq.md Create an autouse fixture in conftest.py to grant database access to all tests without requiring the @pytest.mark.django_db decorator. ```python @pytest.fixture(autouse=True) def enable_db_access_for_all_tests(db): pass ``` -------------------------------- ### Email Outbox for Testing Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Provides a clean email outbox for testing purposes, allowing assertions on sent emails. It relies on django_mail_patch_dns for DNS patching. ```python from django.core import mail def test_mail(mailoutbox): mail.send_mail('subject', 'body', 'from@example.com', ['to@example.com']) assert len(mailoutbox) == 1 m = mailoutbox[0] assert m.subject == 'subject' assert m.body == 'body' assert m.from_email == 'from@example.com' assert list(m.to) == ['to@example.com'] ``` -------------------------------- ### Override URL Configuration with urls Mark Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Specify a different ROOT_URLCONF module for marked tests, similar to Django's TestCase.urls attribute. This is useful for testing specific URL configurations. ```python @pytest.mark.urls('myapp.test_urls') ``` -------------------------------- ### Configure DJANGO_CONFIGURATION in pytest.ini Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Set the DJANGO_CONFIGURATION in your pytest.ini file for persistent configuration with django-configurations. ```ini [pytest] DJANGO_CONFIGURATION=MySettings ``` -------------------------------- ### Use Django RequestFactory for Tests Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Provides an instance of django.test.RequestFactory. Note that requests made with RequestFactory do not pass through middleware, so fields like request.user must be set explicitly. ```python from myapp.views import my_view def test_details(rf, admin_user): request = rf.get('/customer/details') # Remember that when using RequestFactory, the request does not pass # through middleware. If your view expects fields such as request.user # to be set, you need to set them explicitly. # The following line sets request.user to an admin user. request.user = admin_user response = my_view(request) assert response.status_code == 200 ``` -------------------------------- ### Set DJANGO_SETTINGS_MODULE via Environment Variable Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Use the DJANGO_SETTINGS_MODULE environment variable to specify Django settings. This is the default way Django finds settings. ```bash $ export DJANGO_SETTINGS_MODULE=test.settings $ pytest ``` ```bash $ DJANGO_SETTINGS_MODULE=test.settings pytest ``` -------------------------------- ### Measure test coverage with subprocesses Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/contributing.md Measure code coverage when tests run in subprocesses. Requires setting up .pth files and potentially uninstalling pytest_django in editable mode. Ensure MySQL and PostgreSQL databases are available. ```bash $ COVERAGE_PROCESS_START=`pwd`/pyproject.toml COVERAGE_FILE=`pwd`/.coverage pytest --ds=pytest_django_test.settings_postgres ``` -------------------------------- ### Assert Exact Number of DB Queries Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Use this fixture to assert that a specific number of database queries are executed within a context. It wraps Django's CaptureQueriesContext. ```python def test_queries(django_assert_num_queries): with django_assert_num_queries(3) as captured: Item.objects.create('foo') Item.objects.create('bar') Item.objects.create('baz') assert 'foo' in captured.captured_queries[0]['sql'] ``` ```python from pytest_django import DjangoAssertNumQueries def test_num_queries( django_assert_num_queries: DjangoAssertNumQueries, ): ... ``` -------------------------------- ### Request Multiple Databases for a Test Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Specify the 'databases' argument in the '@pytest.mark.django_db' decorator to request access to multiple databases. Use a list of database aliases or the shortcut '__all__' to include all configured databases. ```python @pytest.mark.django_db(databases=['default', 'other']) def test_spam(): assert MyModel.objects.using('other').count() == 0 ``` -------------------------------- ### Fixture to Use a Template PostgreSQL Database Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Configures pytest-django to use a pre-created PostgreSQL database as a template for test databases. This fixture drops and recreates the test database from the template for each test session. ```python import pytest from django.db import connections import psycopg def run_sql(sql): with psycopg.connect(database='postgres') as conn: conn.execute(sql) @pytest.fixture(scope='session') def django_db_setup(): from django.conf import settings settings.DATABASES['default']['NAME'] = 'the_copied_db' run_sql('DROP DATABASE IF EXISTS the_copied_db') run_sql('CREATE DATABASE the_copied_db TEMPLATE the_source_db') yield for connection in connections.all(): connection.close() run_sql('DROP DATABASE the_copied_db') ``` -------------------------------- ### Run Tests in Parallel with Pytest-xdist Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/usage.md Execute tests in parallel using pytest-xdist by specifying the number of processes with the -n option. This speeds up test suites on multi-core machines. ```bash pytest -n ``` -------------------------------- ### Disable Automatic Django Project Finder Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/managing_python_path.md Add this setting to `pytest.ini`, `setup.cfg`, or `tox.ini` to disable pytest-django's automatic detection of the Django project's `manage.py` file. ```ini [pytest] django_find_project = false ``` -------------------------------- ### Import Django Assertions Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Import Django's built-in assertions for use in pytest tests. ```python from pytest_django.asserts import assertTemplateUsed ``` -------------------------------- ### Unblock Database Access with DjangoDbBlocker Context Manager Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Use django_db_blocker as a context manager to temporarily enable database access within a specific block of code. This is useful for modifying the database state when the automatic transaction management of other fixtures is not desired. ```python import pytest @pytest.fixture def myfixture(django_db_blocker): with django_db_blocker.unblock(): ... # modify something in the database ``` -------------------------------- ### Enable Database Access for a Class or Module Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Mark an entire test class or module with '@pytest.mark.django_db' or by setting 'pytestmark = pytest.mark.django_db' to enable database access for all tests within that scope. This demonstrates multiple ways to apply the mark, though only one is needed per test. ```python import pytest pytestmark = pytest.mark.django_db @pytest.mark.django_db class TestUsers: pytestmark = pytest.mark.django_db def test_my_user(self): me = User.objects.get(username='me') assert me.is_superuser ``` -------------------------------- ### Set Default Language for Tests Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/faq.md Use this fixture in conftest.py to ensure all tests run with a specific locale. It activates the desired language before each test. ```python from django.utils.translation import activate @pytest.fixture(autouse=True) def set_default_language(): activate('en') ``` -------------------------------- ### Modify Django Settings in a Test Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md The `settings` fixture allows temporary modification of Django settings within a test. Changes are automatically reverted after the test completes. ```python def test_with_specific_settings(settings): settings.USE_TZ = True assert settings.USE_TZ ``` -------------------------------- ### Assert Maximum Number of DB Queries Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md This fixture checks if the number of executed database queries does not exceed a specified maximum. It's a specialized version of django_assert_num_queries. ```python def test_max_queries(django_assert_max_num_queries): with django_assert_max_num_queries(2): Item.objects.create('foo') Item.objects.create('bar') ``` ```python from pytest_django import DjangoAssertNumQueries def test_max_num_queries( django_assert_max_num_queries: DjangoAssertNumQueries, ): ... ``` -------------------------------- ### Override Individual Django Settings with Fixture Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/configuring_django.md Use the 'settings' fixture to override specific Django settings within your tests. The fixture can be autouse=True for all tests or requested individually. ```python @pytest.fixture(autouse=True) def use_dummy_cache_backend(settings): settings.CACHES = { "default": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", } } ``` -------------------------------- ### Isolate Django Apps for Tests Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md Use this marker to isolate models defined within marked tests into their own apps registry. Useful for managing dependencies in complex projects. ```python import pytest @pytest.mark.django_isolate_apps("myapp") def test_something(django_isolated_apps): assert django_isolated_apps.is_installed("myapp") assert not django_isolated_apps.is_installed("otherapp") ``` -------------------------------- ### Enable Fail on Template Variables Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/usage.md Configure pytest.ini to fail tests that render templates with invalid template variables. This helps catch template errors early. ```ini [pytest] FAIL_INVALID_TEMPLATE_VARS = True ``` -------------------------------- ### Fixture to Use an Existing External MySQL Database Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Configures pytest-django to connect to and use an existing external MySQL database for tests. This disables pytest-django's test database creation and points to the specified external database. ```python import pytest @pytest.fixture(scope='session') def django_db_setup(): from django.conf import settings settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'db.example.com', 'NAME': 'external_db', } ``` -------------------------------- ### Configure Test File Naming Conventions Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/faq.md Modify pytest's test collection behavior by specifying file naming patterns in pytest.ini. This is useful if your test files do not follow the default naming conventions. ```ini [pytest] python_files = tests.py test_*.py *_tests.py ``` -------------------------------- ### Keep Django Debug Mode Setting Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/usage.md Configure pytest.ini to keep the existing Django DEBUG setting, disabling pytest-django's default override. Use 'keep' to respect the current setting. ```ini [pytest] django_debug_mode = keep ``` -------------------------------- ### Integrate manage.py test with pytest-django Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/faq.md To use manage.py test with pytest-django, set TEST_RUNNER in your Django settings. Note that some pytest-django command-line options are not compatible with this approach. ```python TEST_RUNNER = 'pytest_django.runner.TestRunner' ``` -------------------------------- ### Enable Database Access for a Single Test Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/database.md Use the '@pytest.mark.django_db' decorator to allow a specific test function to access the database. This ensures that only tests explicitly needing database access are run with it. ```python import pytest @pytest.mark.django_db def test_my_user(): me = User.objects.get(username='me') assert me.is_superuser ``` -------------------------------- ### Set Django Debug Mode Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/usage.md Configure pytest.ini to set Django's DEBUG mode to true during tests. By default, DEBUG is False to mimic production. ```ini [pytest] django_debug_mode = true ``` -------------------------------- ### Ignore Template Errors in Tests Source: https://github.com/pytest-dev/pytest-django/blob/main/docs/helpers.md This marker ignores errors when using the --fail-on-template-vars option, preventing tests from failing due to invalid template variables. It sets the string_if_invalid template option. ```python import pytest @pytest.mark.ignore_template_errors def test_something(client): client('some-url-with-invalid-template-vars') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.