SlideShare a Scribd company logo
Simplified: How to Test Django App with Pytest in 5 Mins?
As we see companies embracing artificial intelligence (AI), machine learning (ML)
and Data Science, we’ve witnessed a steep rise in the usage of Python language as it
is extensively used in these domains. Django framework, in particular, has become a
silver bullet in the armory of Python Developers. It’s a powerful and flexible toolkit for
developing web APIs, including REST APIs -
As a result of all the features it provides, Django has become a favourite weapon in
developers’ arsenal. Developers look to develop the best applications, they often
underestimate performing unit testing on the developed products.
Having said that, the Python and Django experts understand that unit testing
applications is a crucial step as they help in detection of bugs and improve app’s
performance. That’s why the best Django development companies give utmost
importance. So make sure you consider unit testing as a criteria when hiring a
Django development company.
In this blog post, we’re going to show how you can write a basic unit test using
Pytest for Django applications. Let’s get started!
Why Use Pytest?
Pytest is a framework that Django experts rely on heavily. It makes writing small test
codes simple and easier while also scaling and supporting complex functional
testing for applications or libraries. One of the major uses of Pytest is to write test
codes for APIs. Pytest, as the name suggests, writes test codes in the Python
programming language.
Pytest is used by many different developers and companies because it enables
automation - it has its own way to detect tests, run tests, skip an entire subset of
tests and even run multiple tests. Pytest is the best option when the objective is to
reduce the execution time. Some of the major benefits of Pytest are:
- It has a very easy and simple syntax which makes your start effortless and
quick.
- The execution time of the test suite is reduced because of multiple tests being
run parallelly.
- It detects test files and test functions without any explicit mention with
complete automation.
- You can skip an entire subset of tests during the time of execution and also
run an entire subset of tests.
- Pytest has scalable, modular fixtures.
- Pytest is completely open source and free for everyone.
These benefits are some of the major reasons why more and more businesses which
want to scale up and digitize are looking to hire python Django developers.
Especially in 2021, Python’s use in many different directions is ascendant and evident
with more and more companies growing proficient at deploying it.
Some of the most Attractive Features of Pytest
Django provides various easy-to-implement features for developers and Pytest is
one of them. Pytest owes a lot of its popularity amongst the developer community
to the wide variety of features it provides. Pytest enables you to create marks and
custom labels for any code testing of your preference. Pytest fixtures are used for
configuring data, connecting and disconnecting the databases, etc.
Setting up Pytest for your Django App
The fixtures that are provided in Django are not ideal for some cases and that is
precisely where Pytest fixtures come in.
Installation of Pytest and Django plug-in
This plug-in is maintained by the Pytest development team and it provides useful
tools for writing test codes for any projects on Django.
Get access to the database from the tests
In order to access the database, you need to start by running a test. Write a test that
will help you check if the function create-user() is setting the username correctly.
Once the test is executed from your command, if it fails, it means you have to inject a
special fixture called DB. This fixture is a part of the Django plug-in and is very
important for accessing databases.
Create and maintain fixtures for the Django Models
Once the access is granted and the username is all set, you need to set a password.
The test will help you in validating your password. You must also mark functions as
fixtures to inject more test cases. This way you don’t have to go to every test case
and add it to a group. Using fixtures, just one time examination allows you to add
cases to the group.
Fixtures help you avoid repetition while also making the tests more maintainable -
which is why most python development companies are pivoting to using Django
and Pytest framework.
What is the Process of Django testing with Pytest?
Before we get to the testing part, we need to perform some critical functions. Let’s
go through them first.
Create a Virtual Environment:
We are using Python 3, which has inbuilt support for creating virtual environments.
You need to run the following command to create and activate a virtual
environment:
$ mkdir pytest_project
$ cd pytest_project
$ python3 -m venv pytest-env
Running the above command will create a virtual environment called pytest-env in
the working directory.
Activate Virtual Environment:
We need to activate virtualenv so that we can use it. Here’s the command:
$ source pytest-env/bin/activate
The activation makes sure that all packages will be installed in the virtual
environment, rather than in the global Python installation.
Install Pytest: In order to install Pytest, you will need to install the pip package
manager. Once done, you can install Pytest using following command:
$ pip install pytest
Let’s Run a Sample Test
Step 1: Create a new Django project from the terminal
django-admin startproject django_testing .
Step 2: Create a sample Django application
python manage.py startapp main_app
Step 3: Register the app
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main_app.apps.MainAppConfig' # add this
]
Step 4: Change the templates directory
# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # add this
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Step 5: Run the Application
python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 17 unapplied migration(s). Your project may not work properly until you
apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
December 01, 2021 - 21:15:31
Django version 3.0.5, using settings 'django_testing.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Step 6: Create a pytest file
touch pytest.ini
# pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = django_testing.settings
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py
Step 7: Run the test suite
$ pytest
============================= test session starts
==============================
platform linux -- Python 3.7.5, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /home/username/projects/username/source-
code/django_testing_using_pytest, inifile: pytest.ini
plugins: django-3.9.0
collected 0 items
Step 8: Write the test
Here’s a test sample that we’ve used. You can write a test that works for you.
# models.py
from django.db import models
class Contact(models.Model):
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
phone = models.CharField(max_length=150)
email = models.CharField(max_length=150, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.phone
# tests.py
import pytest
from .models import Contact
@pytest.mark.django_db
def test_contact_create():
contact = Contact.objects.create(
first_name="John",
last_name="Doe",
email="john@gmail.com",
phone="00221 70 992 33 43"
)
assert contact.email == "john@gmail.com"
assert contact.phone == "00221 70 992 33 43"
Step 9: Run the Test
pytest
============================= test session starts
=============================
platform linux -- Python 3.7.5, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
django: settings: django_testing.settings (from ini)
rootdir: /home/username/projects/username/source-
code/django_testing_using_pytest, inifile: pytest.ini
plugins: django-3.9.0
collected 1 item
main_app/tests.py . [100%]
============================== 1 passed in 0.27s
==============================
As you can see, our test has successfully passed. Easy, wasn’t it? We hope this helped
you. You might need to be a Django expert to develop an app, but not to run a test.
Final Words
The Django framework has been playing a key role when it comes to Python
development. Often Django experts underline the significance of unit testing the
app for complexity but Pytest provides an easy way to do so. No matter where it
ranks on the spectrum of complexity, you no longer need to worry about it.
We, at Inexture, are an award-winning Django development company providing
across the board services. Feel free to get in touch with our experts today!
Original Published by Here’s Your Step by Step Guide to Test Django App with Pytest

More Related Content

PDF
Cursus phpunit
PDF
Modern Python Testing
PPT
Unit Testing RPG with JUnit
ODP
Python unit testing
PPT
RPG Program for Unit Testing RPG
PDF
TDD in Python With Pytest
PDF
Python Testing Fundamentals
ODP
Automated testing in Python and beyond
 
Cursus phpunit
Modern Python Testing
Unit Testing RPG with JUnit
Python unit testing
RPG Program for Unit Testing RPG
TDD in Python With Pytest
Python Testing Fundamentals
Automated testing in Python and beyond
 

What's hot (20)

PPTX
Interpreter RPG to Java
DOC
Tortuga-A simulation software
ODP
Testing In Java
PPT
Google test training
PPTX
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
PDF
Funcargs & other fun with pytest
PDF
What is new in JUnit5
PPT
Automated Unit Testing
PPTX
Unit Testing with Python
PDF
PuppetConf 2016: Turning Pain Into Gain: A Unit Testing Story – Nadeem Ahmad ...
PPT
Simple Unit Testing With Netbeans 6.1
PDF
JUnit 5 - The Next Generation
PPT
Google mock for dummies
PPS
Why Unit Testingl
PPT
20111018 boost and gtest
PDF
Unit testing, principles
PPTX
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
PDF
JUnit5 Custom TestEngines intro - version 2020-06
PDF
New Features PHPUnit 3.3 - Sebastian Bergmann
 
PPS
JUnit Presentation
Interpreter RPG to Java
Tortuga-A simulation software
Testing In Java
Google test training
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
Funcargs & other fun with pytest
What is new in JUnit5
Automated Unit Testing
Unit Testing with Python
PuppetConf 2016: Turning Pain Into Gain: A Unit Testing Story – Nadeem Ahmad ...
Simple Unit Testing With Netbeans 6.1
JUnit 5 - The Next Generation
Google mock for dummies
Why Unit Testingl
20111018 boost and gtest
Unit testing, principles
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
JUnit5 Custom TestEngines intro - version 2020-06
New Features PHPUnit 3.3 - Sebastian Bergmann
 
JUnit Presentation
Ad

Similar to DIY in 5 Minutes: Testing Django App with Pytest (20)

PPTX
Testing Django APIs
PDF
Token Testing Slides
PPTX
Django strategy-test
PDF
Write unit test from scratch
PDF
PyBCN - Pytest: recomendaciones, paquetes básicos para testing en Python y Dj...
PDF
Testdriven Development With Python 1st Edition Harry J W Percival
PPTX
A Beginer's Guide to testing in Django
PDF
Effective testing with pytest
PDF
Django
PDF
Py.test
PDF
Pytest - testing tips and useful plugins
PDF
Testing Django Applications
ODP
Automated Testing in Django
PDF
Making the most of your Test Suite
PDF
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
PPT
Testing In Django
PDF
Testing Django Applications
PDF
Two Scope of Django 1.6 Chapter 20 and 21
PPTX
Tango with django
KEY
Overview of Testing Talks at Pycon
Testing Django APIs
Token Testing Slides
Django strategy-test
Write unit test from scratch
PyBCN - Pytest: recomendaciones, paquetes básicos para testing en Python y Dj...
Testdriven Development With Python 1st Edition Harry J W Percival
A Beginer's Guide to testing in Django
Effective testing with pytest
Django
Py.test
Pytest - testing tips and useful plugins
Testing Django Applications
Automated Testing in Django
Making the most of your Test Suite
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
Testing In Django
Testing Django Applications
Two Scope of Django 1.6 Chapter 20 and 21
Tango with django
Overview of Testing Talks at Pycon
Ad

More from Inexture Solutions (20)

PDF
AI-Powered Tutoring System_ A Step-by-Step Guide to Building It.pdf
PDF
AI Chatbot Development in 2025: Costs, Trends & Business Impact
PDF
Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
PDF
Mobile App Development Cost 2024 Budgeting Your Dream App
PDF
Data Serialization in Python JSON vs. Pickle
PDF
Best EV Charging App 2024 A Tutorial on Building Your Own
PDF
What is a WebSocket? Real-Time Communication in Applications
PDF
SaaS Application Development Explained in 10 mins
PDF
Best 7 SharePoint Migration Tools of 2024
PDF
Spring Boot with Microsoft Azure Integration.pdf
PDF
Best Features of Adobe Experience Manager (AEM).pdf
PDF
React Router Dom Integration Tutorial for Developers
PDF
Python Kafka Integration: Developers Guide
PDF
What is SaMD Model, Benefits, and Development Process.pdf
PDF
Unlocking the Potential of AI in Spring.pdf
PDF
Mobile Banking App Development Cost in 2024.pdf
PDF
Education App Development : Cost, Features and Example
PDF
Firebase Push Notification in JavaScript Apps
PDF
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
PDF
Steps to Install NPM and Node.js on Windows and MAC
AI-Powered Tutoring System_ A Step-by-Step Guide to Building It.pdf
AI Chatbot Development in 2025: Costs, Trends & Business Impact
Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Mobile App Development Cost 2024 Budgeting Your Dream App
Data Serialization in Python JSON vs. Pickle
Best EV Charging App 2024 A Tutorial on Building Your Own
What is a WebSocket? Real-Time Communication in Applications
SaaS Application Development Explained in 10 mins
Best 7 SharePoint Migration Tools of 2024
Spring Boot with Microsoft Azure Integration.pdf
Best Features of Adobe Experience Manager (AEM).pdf
React Router Dom Integration Tutorial for Developers
Python Kafka Integration: Developers Guide
What is SaMD Model, Benefits, and Development Process.pdf
Unlocking the Potential of AI in Spring.pdf
Mobile Banking App Development Cost in 2024.pdf
Education App Development : Cost, Features and Example
Firebase Push Notification in JavaScript Apps
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
Steps to Install NPM and Node.js on Windows and MAC

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Machine learning based COVID-19 study performance prediction
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
Teaching material agriculture food technology
PPTX
Machine Learning_overview_presentation.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Programs and apps: productivity, graphics, security and other tools
Machine learning based COVID-19 study performance prediction
Dropbox Q2 2025 Financial Results & Investor Presentation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
Spectral efficient network and resource selection model in 5G networks
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
sap open course for s4hana steps from ECC to s4
20250228 LYD VKU AI Blended-Learning.pptx
cuic standard and advanced reporting.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
The AUB Centre for AI in Media Proposal.docx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Reach Out and Touch Someone: Haptics and Empathic Computing
Teaching material agriculture food technology
Machine Learning_overview_presentation.pptx

DIY in 5 Minutes: Testing Django App with Pytest

  • 1. Simplified: How to Test Django App with Pytest in 5 Mins? As we see companies embracing artificial intelligence (AI), machine learning (ML) and Data Science, we’ve witnessed a steep rise in the usage of Python language as it is extensively used in these domains. Django framework, in particular, has become a silver bullet in the armory of Python Developers. It’s a powerful and flexible toolkit for developing web APIs, including REST APIs - As a result of all the features it provides, Django has become a favourite weapon in developers’ arsenal. Developers look to develop the best applications, they often underestimate performing unit testing on the developed products. Having said that, the Python and Django experts understand that unit testing applications is a crucial step as they help in detection of bugs and improve app’s performance. That’s why the best Django development companies give utmost importance. So make sure you consider unit testing as a criteria when hiring a Django development company. In this blog post, we’re going to show how you can write a basic unit test using Pytest for Django applications. Let’s get started!
  • 2. Why Use Pytest? Pytest is a framework that Django experts rely on heavily. It makes writing small test codes simple and easier while also scaling and supporting complex functional testing for applications or libraries. One of the major uses of Pytest is to write test codes for APIs. Pytest, as the name suggests, writes test codes in the Python programming language. Pytest is used by many different developers and companies because it enables automation - it has its own way to detect tests, run tests, skip an entire subset of tests and even run multiple tests. Pytest is the best option when the objective is to reduce the execution time. Some of the major benefits of Pytest are: - It has a very easy and simple syntax which makes your start effortless and quick. - The execution time of the test suite is reduced because of multiple tests being run parallelly. - It detects test files and test functions without any explicit mention with complete automation. - You can skip an entire subset of tests during the time of execution and also run an entire subset of tests. - Pytest has scalable, modular fixtures. - Pytest is completely open source and free for everyone. These benefits are some of the major reasons why more and more businesses which want to scale up and digitize are looking to hire python Django developers. Especially in 2021, Python’s use in many different directions is ascendant and evident with more and more companies growing proficient at deploying it. Some of the most Attractive Features of Pytest Django provides various easy-to-implement features for developers and Pytest is one of them. Pytest owes a lot of its popularity amongst the developer community to the wide variety of features it provides. Pytest enables you to create marks and custom labels for any code testing of your preference. Pytest fixtures are used for configuring data, connecting and disconnecting the databases, etc.
  • 3. Setting up Pytest for your Django App The fixtures that are provided in Django are not ideal for some cases and that is precisely where Pytest fixtures come in. Installation of Pytest and Django plug-in This plug-in is maintained by the Pytest development team and it provides useful tools for writing test codes for any projects on Django. Get access to the database from the tests In order to access the database, you need to start by running a test. Write a test that will help you check if the function create-user() is setting the username correctly. Once the test is executed from your command, if it fails, it means you have to inject a special fixture called DB. This fixture is a part of the Django plug-in and is very important for accessing databases. Create and maintain fixtures for the Django Models Once the access is granted and the username is all set, you need to set a password. The test will help you in validating your password. You must also mark functions as
  • 4. fixtures to inject more test cases. This way you don’t have to go to every test case and add it to a group. Using fixtures, just one time examination allows you to add cases to the group. Fixtures help you avoid repetition while also making the tests more maintainable - which is why most python development companies are pivoting to using Django and Pytest framework. What is the Process of Django testing with Pytest? Before we get to the testing part, we need to perform some critical functions. Let’s go through them first. Create a Virtual Environment: We are using Python 3, which has inbuilt support for creating virtual environments. You need to run the following command to create and activate a virtual environment: $ mkdir pytest_project $ cd pytest_project $ python3 -m venv pytest-env Running the above command will create a virtual environment called pytest-env in the working directory. Activate Virtual Environment: We need to activate virtualenv so that we can use it. Here’s the command: $ source pytest-env/bin/activate The activation makes sure that all packages will be installed in the virtual environment, rather than in the global Python installation. Install Pytest: In order to install Pytest, you will need to install the pip package manager. Once done, you can install Pytest using following command: $ pip install pytest
  • 5. Let’s Run a Sample Test Step 1: Create a new Django project from the terminal django-admin startproject django_testing . Step 2: Create a sample Django application python manage.py startapp main_app Step 3: Register the app # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_app.apps.MainAppConfig' # add this ] Step 4: Change the templates directory # settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # add this 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
  • 6. Step 5: Run the Application python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. December 01, 2021 - 21:15:31 Django version 3.0.5, using settings 'django_testing.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Step 6: Create a pytest file touch pytest.ini # pytest.ini [pytest] DJANGO_SETTINGS_MODULE = django_testing.settings # -- recommended but optional: python_files = tests.py test_*.py *_tests.py Step 7: Run the test suite $ pytest ============================= test session starts ============================== platform linux -- Python 3.7.5, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 rootdir: /home/username/projects/username/source- code/django_testing_using_pytest, inifile: pytest.ini plugins: django-3.9.0 collected 0 items Step 8: Write the test
  • 7. Here’s a test sample that we’ve used. You can write a test that works for you. # models.py from django.db import models class Contact(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) phone = models.CharField(max_length=150) email = models.CharField(max_length=150, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.phone # tests.py import pytest from .models import Contact @pytest.mark.django_db def test_contact_create(): contact = Contact.objects.create( first_name="John", last_name="Doe", email="[email protected]", phone="00221 70 992 33 43" ) assert contact.email == "[email protected]" assert contact.phone == "00221 70 992 33 43" Step 9: Run the Test pytest ============================= test session starts ============================= platform linux -- Python 3.7.5, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 django: settings: django_testing.settings (from ini) rootdir: /home/username/projects/username/source- code/django_testing_using_pytest, inifile: pytest.ini
  • 8. plugins: django-3.9.0 collected 1 item main_app/tests.py . [100%] ============================== 1 passed in 0.27s ============================== As you can see, our test has successfully passed. Easy, wasn’t it? We hope this helped you. You might need to be a Django expert to develop an app, but not to run a test. Final Words The Django framework has been playing a key role when it comes to Python development. Often Django experts underline the significance of unit testing the app for complexity but Pytest provides an easy way to do so. No matter where it ranks on the spectrum of complexity, you no longer need to worry about it. We, at Inexture, are an award-winning Django development company providing across the board services. Feel free to get in touch with our experts today! Original Published by Here’s Your Step by Step Guide to Test Django App with Pytest