A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://pytest-django.readthedocs.io/en/latest/helpers.html below:

Website Navigation


Django helpers — pytest-django documentation

Fixtures

pytest-django provides some pytest fixtures to provide dependencies for tests. More information on fixtures is available in the pytest documentation.

rf - RequestFactory

An instance of a django.test.RequestFactory.

Example
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
async_rf - AsyncRequestFactory

An instance of a django.test.AsyncRequestFactory.

Example

This example uses pytest-asyncio.

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
client - django.test.Client

An instance of a django.test.Client.

Example
def test_with_client(client):
    response = client.get('/')
    assert response.content == 'Foobar'

To use client as an authenticated standard user, call its force_login() or login() method before accessing a URL:

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'
async_client - django.test.AsyncClient

An instance of a django.test.AsyncClient.

Example

This example uses pytest-asyncio.

@pytest.mark.asyncio
async def test_with_async_client(async_client):
    response = await async_client.get('/')
    assert response.content == 'Foobar'
admin_client - django.test.Client logged in as admin

An instance of a django.test.Client, logged in as an admin user.

Example
def test_an_admin_view(admin_client):
    response = admin_client.get('/admin/')
    assert response.status_code == 200

Using the admin_client fixture will cause the test to automatically be marked for database use (no need to specify the django_db() mark).

admin_user - an admin user (superuser)

An instance of a superuser, with username “admin” and password “password” (in case there is no “admin” user yet).

Using the admin_user fixture will cause the test to automatically be marked for database use (no need to specify the django_db() mark).

django_user_model

A shortcut to the User model configured for use by the current Django project (aka the model referenced by settings.AUTH_USER_MODEL). Use this fixture to make pluggable apps testable regardless what User model is configured in the containing Django project.

Example
def test_new_user(django_user_model):
    django_user_model.objects.create_user(username="someone", password="something")
django_username_field

This fixture extracts the field name used for the username on the user model, i.e. resolves to the user model’s USERNAME_FIELD. Use this fixture to make pluggable apps testable regardless what the username field is configured to be in the containing Django project.

db

This fixture will ensure the Django database is set up. Only required for fixtures that want to use the database themselves. A test function should normally use the pytest.mark.django_db() mark to signal it needs the database. This fixture does not return a database connection object. When you need a Django database connection or cursor, import it from Django using from django.db import connection.

transactional_db

This fixture can be used to request access to the database including transaction support. This is only required for fixtures which need database access themselves. A test function should normally use the pytest.mark.django_db() mark with transaction=True to signal it needs the database.

django_db_reset_sequences

This fixture provides the same transactional database access as transactional_db, with additional support for reset of auto increment sequences (if your database supports it). This is only required for fixtures which need database access themselves. A test function should normally use the pytest.mark.django_db() mark with transaction=True and reset_sequences=True.

django_db_serialized_rollback

This fixture triggers rollback emulation. This is only required for fixtures which need to enforce this behavior. A test function should normally use pytest.mark.django_db() with serialized_rollback=True (and most likely also transaction=True) to request this behavior.

live_server

This fixture runs a live Django server in a background thread. The server’s URL can be retrieved using the live_server.url attribute or by requesting it’s string value: str(live_server). You can also directly concatenate a string to form a URL: live_server + '/foo'.

Since the live server and the tests run in different threads, they cannot share a database transaction. For this reason, live_server depends on the transactional_db fixture. If tests depend on data created in data migrations, you should add the django_db_serialized_rollback fixture.

Note

Combining database access fixtures.

When using multiple database fixtures together, only one of them is used. Their order of precedence is as follows (the last one wins):

In addition, using live_server or django_db_reset_sequences will also trigger transactional database access, and django_db_serialized_rollback regular database access, if not specified.

settings

This fixture will provide a handle on the Django settings module, and automatically revert any changes made to the settings (modifications, additions and deletions).

Example
def test_with_specific_settings(settings):
    settings.USE_TZ = True
    assert settings.USE_TZ
django_assert_num_queries
django_assert_num_queries(num, connection=None, info=None, *, using=None)
Parameters:
  • num – expected number of queries

  • connection – optional database connection

  • info (str) – optional info message to display on failure

  • using (str) – optional database alias

This fixture allows to check for an expected number of DB queries.

If the assertion failed, the executed queries can be shown by using the verbose command line option.

It wraps django.test.utils.CaptureQueriesContext and yields the wrapped CaptureQueriesContext instance.

Example usage:

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']

If you use type annotations, you can annotate the fixture like this:

from pytest_django import DjangoAssertNumQueries

def test_num_queries(
    django_assert_num_queries: DjangoAssertNumQueries,
):
    ...
django_assert_max_num_queries
django_assert_max_num_queries(num, connection=None, info=None, *, using=None)
Parameters:
  • num – expected maximum number of queries

  • connection – optional database connection

  • info (str) – optional info message to display on failure

  • using (str) – optional database alias

This fixture allows to check for an expected maximum number of DB queries.

It is a specialized version of django_assert_num_queries.

Example usage:

def test_max_queries(django_assert_max_num_queries):
    with django_assert_max_num_queries(2):
        Item.objects.create('foo')
        Item.objects.create('bar')

If you use type annotations, you can annotate the fixture like this:

from pytest_django import DjangoAssertNumQueries

def test_max_num_queries(
    django_assert_max_num_queries: DjangoAssertNumQueries,
):
    ...
django_capture_on_commit_callbacks
django_capture_on_commit_callbacks(*, using=DEFAULT_DB_ALIAS, execute=False)
Parameters:
  • using – The alias of the database connection to capture callbacks for.

  • execute – If True, all the callbacks will be called as the context manager exits, if no exception occurred. This emulates a commit after the wrapped block of code.

Added in version 4.4.

Returns a context manager that captures transaction.on_commit() callbacks for the given database connection. It returns a list that contains, on exit of the context, the captured callback functions. From this list you can make assertions on the callbacks or call them to invoke their side effects, emulating a commit.

Avoid this fixture in tests using transaction=True; you are not likely to get useful results.

This fixture is based on Django’s django.test.TestCase.captureOnCommitCallbacks() helper.

Example usage:

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'

If you use type annotations, you can annotate the fixture like this:

from pytest_django import DjangoCaptureOnCommitCallbacks

def test_on_commit(
    django_capture_on_commit_callbacks: DjangoCaptureOnCommitCallbacks,
):
    ...
mailoutbox

A clean email outbox to which Django-generated emails are sent.

Example
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']

This uses the django_mail_patch_dns fixture, which patches DNS_NAME used by django.core.mail with the value from the django_mail_dnsname fixture, which defaults to “fake-tests.example.com”.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4