How to Build a Food...
December 18, 2024
Written by Dharmesh Patel
46,846
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!
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:
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.
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.
The fixtures that are provided in Django are not ideal for some cases and that is precisely where Pytest fixtures come 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.
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.
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.
Before we get to the testing part, we need to perform some critical functions. Let’s go through them first.
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.
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!
Writen by Dharmesh Patel