Open In App

How do I run the pytest tests in Django?

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Are you someone who wants to ensure the stability and reliability of their application then testing Django is a very important step you need to perform. Not just this but pytest is a very popular testing framework for Python which provides a simple yet powerful way to write and run tests. For people who combine it with pytest-django then it becomes even easier to test Django applications by utilizing Django’s testing capabilities using pytest's powerful features.

How do I run the pytest in Django?

To run the pytest tests in Django we need to follow these simple steps one by one:

Step1: Start by Installing Pytest and Pytest-Django

If you already have pytest and pytest-django installed on your computer then you can proceed to the next step but if you haven’t then you can install them using:

pip install pytest pytest-django

Step2: After installation, arrange pytest for Django

Arrange a pytest.ini file in the root of your project (where your main file is located mainfile.py) and add the following configuration:

[pytest]
DJANGO_SETTINGS_MODULE = your_project_name.settings
python_files = tests.py test_*.py *_tests.py

Step3: Write your tests

To write tests, a person must create test files in Django directories. By naming conventions, test files always start with “test_” and end with ‘_test.py’.

Step 4: Run the tests:

To run the tests use the “pytest” command in your terminal like

pytest

A person can also run the tests for a specific file or module using :

pytest your_app/tests/

Let us now look at a example to understand Django model test using "pytest" :

Example 1:

In this example we are testing a django model.

models.py:

models.py
from django.db import models

# Create your models here.
class Member(models.Model):
    firstName = models.CharField(max_length=255)
    lastName = models.CharField(max_length=255)
    phone = models.IntegerField()
    joinedDate = models.DateField()
    

tests/test_models.py:

tests/test_models.py
import pytest
from django.utils import timezone
from members.models import Member


@pytest.mark.django_db
def test_member_creation():
    member = Member.objects.create(
        firstName = "John",
        lastName="Doe",
        phone=6307730629,
        joinedDate=timezone.now().date()
    )
    
    assert member.firstName == "John"
    assert member.lastName == "Doe"
    assert member.phone == 6307730629
    assert member.joinedDate == timezone.now().date()


Output:

result

Example 1:

Here’s a simple example of a Django views test using pytest:

forms.py:

forms.py
from django import forms

class SimpleForm(forms.Form):
    name = forms.CharField(max_length=100)
    age = forms.IntegerField(min_value=0, max_value=120)

views.py:

views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import SimpleForm

def simple_form_view(request):
    if request.method == 'POST':
        form = SimpleForm(request.POST)
        if form.is_valid():
            # Process the data in form.cleaned_data
            name = form.cleaned_data['name']
            age = form.cleaned_data['age']
            return HttpResponse(f"Hello {name}, you are {age} years old.")
    else:
        form = SimpleForm()

    return render(request, 'simple_form.html', {'form': form})

tests/test_models.py:

tests/tests_views.py
import pytest
from django.urls import reverse
from django.test import Client

@pytest.mark.django_db
def test_simple_form_view_get():
    client = Client()
    response = client.get(reverse('simple_form_view'))
    assert response.status_code == 200
    assert 'form' in response.context
    assert '<form method="post">' in response.content.decode()

@pytest.mark.django_db
def test_simple_form_view_post_valid_data():
    client = Client()
    response = client.post(reverse('simple_form_view'), {'name': 'Alice', 'age': 30})
    assert response.status_code == 200
    assert "Hello Alice, you are 30 years old." in response.content.decode()

Output:

result


Conclusion

From the above blog we saw that the process of designing and executing tests is made simpler by integrating pytest with Django. This improves the features of Django's built-in testing tools with a secure and flexible testing framework. People can make sure that their Django applications are strong and well-tested by following the instructions in this guide, which include installing pytest and pytest-django, setting up projects, creating test cases, and running tests.


Next Article
Article Tags :

Similar Reads