SlideShare a Scribd company logo
1 of 8
Download to read offline
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

What's hot

Interpreter RPG to Java
Interpreter RPG to JavaInterpreter RPG to Java
Interpreter RPG to Javafarerobe
 
Tortuga-A simulation software
Tortuga-A simulation softwareTortuga-A simulation software
Tortuga-A simulation softwareSyeda Nyma
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
 
Funcargs & other fun with pytest
Funcargs & other fun with pytestFuncargs & other fun with pytest
Funcargs & other fun with pytestBrianna Laugher
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with PythonMicroPyramid .
 
PuppetConf 2016: Turning Pain Into Gain: A Unit Testing Story – Nadeem Ahmad ...
PuppetConf 2016: Turning Pain Into Gain: A Unit Testing Story – Nadeem Ahmad ...PuppetConf 2016: Turning Pain Into Gain: A Unit Testing Story – Nadeem Ahmad ...
PuppetConf 2016: Turning Pain Into Gain: A Unit Testing Story – Nadeem Ahmad ...Puppet
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Kiki Ahmadi
 
JUnit 5 - The Next Generation
JUnit 5 - The Next GenerationJUnit 5 - The Next Generation
JUnit 5 - The Next GenerationKostadin Golev
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)Jen Wong
 
JUnit5 Custom TestEngines intro - version 2020-06
JUnit5 Custom TestEngines intro - version 2020-06JUnit5 Custom TestEngines intro - version 2020-06
JUnit5 Custom TestEngines intro - version 2020-06Sven Ruppert
 
New Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian BergmannNew Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian Bergmanndpc
 

What's hot (20)

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

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

Django Article V0
Django Article V0Django Article V0
Django Article V0Udi Bauman
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suiteericholscher
 
Django strategy-test
Django strategy-testDjango strategy-test
Django strategy-testRoyce Haynes
 
Quality of life through Unit Testing
Quality of life through Unit TestingQuality of life through Unit Testing
Quality of life through Unit TestingSian Lerk Lau
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django frameworkKnoldus Inc.
 
Django framework
Django framework Django framework
Django framework TIB Academy
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010guest5639fa9
 
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose presoTest Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose presoElad Elrom
 
Marek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with BuildoutMarek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with Buildoutmarekkuziel
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
Python Requirements File How to Create Python requirements.txt
Python Requirements File How to Create Python requirements.txtPython Requirements File How to Create Python requirements.txt
Python Requirements File How to Create Python requirements.txtInexture Solutions
 
STAMP: Software Testing Amplification in DevOps, Etienne Sauvage, OW2con'17
STAMP: Software Testing Amplification in DevOps, Etienne Sauvage, OW2con'17STAMP: Software Testing Amplification in DevOps, Etienne Sauvage, OW2con'17
STAMP: Software Testing Amplification in DevOps, Etienne Sauvage, OW2con'17OW2
 

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

Django Article V0
Django Article V0Django Article V0
Django Article V0
 
Django
DjangoDjango
Django
 
Django
Django Django
Django
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
 
Django strategy-test
Django strategy-testDjango strategy-test
Django strategy-test
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Quality of life through Unit Testing
Quality of life through Unit TestingQuality of life through Unit Testing
Quality of life through Unit Testing
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
Django framework
Django framework Django framework
Django framework
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010
 
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose presoTest Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
 
Marek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with BuildoutMarek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with Buildout
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
Django - basics
Django - basicsDjango - basics
Django - basics
 
Python and test
Python and testPython and test
Python and test
 
Python Requirements File How to Create Python requirements.txt
Python Requirements File How to Create Python requirements.txtPython Requirements File How to Create Python requirements.txt
Python Requirements File How to Create Python requirements.txt
 
STAMP: Software Testing Amplification in DevOps, Etienne Sauvage, OW2con'17
STAMP: Software Testing Amplification in DevOps, Etienne Sauvage, OW2con'17STAMP: Software Testing Amplification in DevOps, Etienne Sauvage, OW2con'17
STAMP: Software Testing Amplification in DevOps, Etienne Sauvage, OW2con'17
 
Django Best Practices
Django Best PracticesDjango Best Practices
Django Best Practices
 

More from Inexture Solutions

Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive GuideSpring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive GuideInexture Solutions
 
Mobile App Development Cost 2024 Budgeting Your Dream App
Mobile App Development Cost 2024 Budgeting Your Dream AppMobile App Development Cost 2024 Budgeting Your Dream App
Mobile App Development Cost 2024 Budgeting Your Dream AppInexture Solutions
 
Data Serialization in Python JSON vs. Pickle
Data Serialization in Python JSON vs. PickleData Serialization in Python JSON vs. Pickle
Data Serialization in Python JSON vs. PickleInexture Solutions
 
Best EV Charging App 2024 A Tutorial on Building Your Own
Best EV Charging App 2024 A Tutorial on Building Your OwnBest EV Charging App 2024 A Tutorial on Building Your Own
Best EV Charging App 2024 A Tutorial on Building Your OwnInexture Solutions
 
What is a WebSocket? Real-Time Communication in Applications
What is a WebSocket? Real-Time Communication in ApplicationsWhat is a WebSocket? Real-Time Communication in Applications
What is a WebSocket? Real-Time Communication in ApplicationsInexture Solutions
 
SaaS Application Development Explained in 10 mins
SaaS Application Development Explained in 10 minsSaaS Application Development Explained in 10 mins
SaaS Application Development Explained in 10 minsInexture Solutions
 
Best 7 SharePoint Migration Tools of 2024
Best 7 SharePoint Migration Tools of 2024Best 7 SharePoint Migration Tools of 2024
Best 7 SharePoint Migration Tools of 2024Inexture Solutions
 
Spring Boot with Microsoft Azure Integration.pdf
Spring Boot with Microsoft Azure Integration.pdfSpring Boot with Microsoft Azure Integration.pdf
Spring Boot with Microsoft Azure Integration.pdfInexture Solutions
 
Best Features of Adobe Experience Manager (AEM).pdf
Best Features of Adobe Experience Manager (AEM).pdfBest Features of Adobe Experience Manager (AEM).pdf
Best Features of Adobe Experience Manager (AEM).pdfInexture Solutions
 
React Router Dom Integration Tutorial for Developers
React Router Dom Integration Tutorial for DevelopersReact Router Dom Integration Tutorial for Developers
React Router Dom Integration Tutorial for DevelopersInexture Solutions
 
Python Kafka Integration: Developers Guide
Python Kafka Integration: Developers GuidePython Kafka Integration: Developers Guide
Python Kafka Integration: Developers GuideInexture Solutions
 
What is SaMD Model, Benefits, and Development Process.pdf
What is SaMD Model, Benefits, and Development Process.pdfWhat is SaMD Model, Benefits, and Development Process.pdf
What is SaMD Model, Benefits, and Development Process.pdfInexture Solutions
 
Unlocking the Potential of AI in Spring.pdf
Unlocking the Potential of AI in Spring.pdfUnlocking the Potential of AI in Spring.pdf
Unlocking the Potential of AI in Spring.pdfInexture Solutions
 
Mobile Banking App Development Cost in 2024.pdf
Mobile Banking App Development Cost in 2024.pdfMobile Banking App Development Cost in 2024.pdf
Mobile Banking App Development Cost in 2024.pdfInexture Solutions
 
Education App Development : Cost, Features and Example
Education App Development : Cost, Features and ExampleEducation App Development : Cost, Features and Example
Education App Development : Cost, Features and ExampleInexture Solutions
 
Firebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsFirebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsInexture Solutions
 
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
Micronaut Framework Guide Framework Basics and Fundamentals.pdfMicronaut Framework Guide Framework Basics and Fundamentals.pdf
Micronaut Framework Guide Framework Basics and Fundamentals.pdfInexture Solutions
 
Steps to Install NPM and Node.js on Windows and MAC
Steps to Install NPM and Node.js on Windows and MACSteps to Install NPM and Node.js on Windows and MAC
Steps to Install NPM and Node.js on Windows and MACInexture Solutions
 
Gain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring BatchGain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring BatchInexture Solutions
 
Explore the System Development Life Cycle and Phases
Explore the System Development Life Cycle and PhasesExplore the System Development Life Cycle and Phases
Explore the System Development Life Cycle and PhasesInexture Solutions
 

More from Inexture Solutions (20)

Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive GuideSpring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
 
Mobile App Development Cost 2024 Budgeting Your Dream App
Mobile App Development Cost 2024 Budgeting Your Dream AppMobile App Development Cost 2024 Budgeting Your Dream App
Mobile App Development Cost 2024 Budgeting Your Dream App
 
Data Serialization in Python JSON vs. Pickle
Data Serialization in Python JSON vs. PickleData Serialization in Python JSON vs. Pickle
Data Serialization in Python JSON vs. Pickle
 
Best EV Charging App 2024 A Tutorial on Building Your Own
Best EV Charging App 2024 A Tutorial on Building Your OwnBest EV Charging App 2024 A Tutorial on Building Your Own
Best EV Charging App 2024 A Tutorial on Building Your Own
 
What is a WebSocket? Real-Time Communication in Applications
What is a WebSocket? Real-Time Communication in ApplicationsWhat is a WebSocket? Real-Time Communication in Applications
What is a WebSocket? Real-Time Communication in Applications
 
SaaS Application Development Explained in 10 mins
SaaS Application Development Explained in 10 minsSaaS Application Development Explained in 10 mins
SaaS Application Development Explained in 10 mins
 
Best 7 SharePoint Migration Tools of 2024
Best 7 SharePoint Migration Tools of 2024Best 7 SharePoint Migration Tools of 2024
Best 7 SharePoint Migration Tools of 2024
 
Spring Boot with Microsoft Azure Integration.pdf
Spring Boot with Microsoft Azure Integration.pdfSpring Boot with Microsoft Azure Integration.pdf
Spring Boot with Microsoft Azure Integration.pdf
 
Best Features of Adobe Experience Manager (AEM).pdf
Best Features of Adobe Experience Manager (AEM).pdfBest Features of Adobe Experience Manager (AEM).pdf
Best Features of Adobe Experience Manager (AEM).pdf
 
React Router Dom Integration Tutorial for Developers
React Router Dom Integration Tutorial for DevelopersReact Router Dom Integration Tutorial for Developers
React Router Dom Integration Tutorial for Developers
 
Python Kafka Integration: Developers Guide
Python Kafka Integration: Developers GuidePython Kafka Integration: Developers Guide
Python Kafka Integration: Developers Guide
 
What is SaMD Model, Benefits, and Development Process.pdf
What is SaMD Model, Benefits, and Development Process.pdfWhat is SaMD Model, Benefits, and Development Process.pdf
What is SaMD Model, Benefits, and Development Process.pdf
 
Unlocking the Potential of AI in Spring.pdf
Unlocking the Potential of AI in Spring.pdfUnlocking the Potential of AI in Spring.pdf
Unlocking the Potential of AI in Spring.pdf
 
Mobile Banking App Development Cost in 2024.pdf
Mobile Banking App Development Cost in 2024.pdfMobile Banking App Development Cost in 2024.pdf
Mobile Banking App Development Cost in 2024.pdf
 
Education App Development : Cost, Features and Example
Education App Development : Cost, Features and ExampleEducation App Development : Cost, Features and Example
Education App Development : Cost, Features and Example
 
Firebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsFirebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript Apps
 
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
Micronaut Framework Guide Framework Basics and Fundamentals.pdfMicronaut Framework Guide Framework Basics and Fundamentals.pdf
Micronaut Framework Guide Framework Basics and Fundamentals.pdf
 
Steps to Install NPM and Node.js on Windows and MAC
Steps to Install NPM and Node.js on Windows and MACSteps to Install NPM and Node.js on Windows and MAC
Steps to Install NPM and Node.js on Windows and MAC
 
Gain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring BatchGain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring Batch
 
Explore the System Development Life Cycle and Phases
Explore the System Development Life Cycle and PhasesExplore the System Development Life Cycle and Phases
Explore the System Development Life Cycle and Phases
 

Recently uploaded

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

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="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
  • 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