Test-driven development (TDD) is a software development technique in which tests are developed first, followed by source code. The following bullet points are used to summarize his workflow:
- Tests are written first – they can not pass because the source code they are supposed to test does not yet exist.
- The source code was written to meet the requirements specified in the tests.
- The tests are complete.
- If they pass, it means that the source code meets the test requirements.
- The source code is restored to suit failed test requirements.
- For each test, repeat the instructions above.
TDD in Django
TDD seems to go against intuition. So why would you want to use it? Turns out there are some compelling reasons to do so. Consider the following points:
- TDD is defined as expressing requirements in terms of test cases. The source code was then written to meet these requirements. When all the tests pass, you can rest assured that the criterion has been completed. Developers may avoid crawling scope with this kind of attention.
- TDD can increase developer productivity by reducing development time. Working on individual requirements at a time reduces the number of variables involved. To encode, you use manageable intervals. As a result, you can effectively resolve breaking changes and track them. The amount of time spent debugging is reduced. As a result, efficiency improves, and more time is devoted to development.
- The tests are written taking into account the needs of the users. As a result, they are more likely to be produced with a specific purpose in mind. These tests can provide adequate documentation for a code base.
- Writing tests first ensures that your source code includes tests at all times. Furthermore, as the code base increases, the test coverage is constantly maintained at an acceptable percentage.
TDD, however, is not a panacea! There are times when it’s not ideal, like when you’re working on a project.
When creating proof for a concept – for example, in a hackathon, tests are secondary. Often tests are not a priority because of the accepted time constraints involved in such events.
When the required specifications are not concise, the requirements of the application may become clearer as the development progresses. Any test written in this situation may become obsolete. As a result, more time is spent cleaning up the test package than working on development.
Django High Level Review
Django describes itself as an “Internet framework for deadline-driven perfectionists.” This is a Python framework, and it’s great and fun to work with, just like most other Python libraries.
Django comes with views and templates, mostly HTML pages, models that map to your database tables, and a host of other out-of-the-box features listed in their topic guide.
The documentation for Django is one of the best and most expensive of any library or framework.
We need to install Python first before we can use Django. For this tutorial, we will be using Python 3.9.
Installing Python 3.9
Install Python according to the instructions on the official Python page for your platform. Then, open the terminal to make sure the installation was successful and type the following.
The result should be somehow similar to the screenshot below if the installation was successful.
The rule of thumb is to create a virtual environment for each project before installing Django or most other Python libraries, for that matter.
As described, a virtual environment is a subdirectory on your computer where you can install project-specific requirements. This allows us to separate environments belonging to different projects in one machine. We can escape hell from dependence by using virtual environments.
For this post, virtualenv will suffice. Run the following command.
There are simply three commands we must control;
1) The virtualenv command is used to create a virtual environment
2) The source command is used to activate a virtual environment.
3) Ordinance for the cancellation of a virtual environment
Django can now be installed within the env virtual environment.
Django 4.0 has been used since it was last updated.
We need to set up a repository (temperature_converter) and where the code of our app will reside after installing Django. You can also do this before installing Django – it’s all up to you.
Next, open a terminal and move to the Temperature Converter folder.
Under the guidance of your console, always put the name of the virtual environment in parentheses when operating it. This is how our directive appears.
(temp_env) ➜ temperature_converter
We can now give a quick summary of the project we want to develop now that Django is installed.
The app – a tool for temperature conversion
We hope we have demonstrated how to use TDD to create a Django application by the end of this article. Temperature converter is the application in question. This was chosen because temperature conversion is a simple concept to grasp, but it leaves us with a lot of opportunities for TDD and further testing.
We will concentrate on temperature conversion between Celsius and Fahrenheit units.
Creating a “Temperature Converter” project.
We must first create a Django project before launching the Django app. Django projects consist of Django applications. With the temperature_converter library, we create a project.
django-admin startproject temperature_converter .
The converter project is created in the current directory as indicated by the period character ending the command above. Your converter directory should include this content up to this point.
Create an app called ‘Temperature’
Django projects contain Django apps. We will start by creating a temperature application within the temperature_converter project.
django-admin startapp temperature
The temperature app is now included in the library structure of the converter.
Setting up the app
We can change some settings to prepare the app for development. To get started, we’ll add the Temperature app to the INSTALLED_APPS list. temperature_converter / settings.py contains this setting.
INSTALLED_APPS = [ . . . 'temperature,' ]
Next, we’ll create a blank URL file for our temperature app. Any URL used to process temperature conversion requests will be saved here.
Then, in temperatur_converter / urls.py, add a reference to temperatur / urls.py. Because of the reference to temperatur.urls, the temperature_converter project is aware of any URL related to temperature conversion.
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('temperature.urls')), ]
We are now ready to start working on our temperature converter app with TDD!
Writing unit tests
The specifications of the converter app are quite excellent. All that is required of the software is to translate between different units of measurement.
TDD is used with well-defined specifications.
In temperatur / tests.py, we will define our unit tests. First, we will create the TestTemperatureConversion class. It will include unit tests that include conversions to measure temperature.
from django.test import TestCase, Client from django.urls import reverse class TestTemperatureConversion(TestCase): """ This class contains tests that convert temperature from Celcius to Fahrenheit. """ def setUp(self): """ It runs before any execution in each test case. """ self.client = Client() self.url = reverse("temperature:temperature-conversion")
We will import the customer department at the top of temperature / tests.py. This is a test browser that allows Django tests to make http requests. When the URL name is given as input, the reverse function is imported to generate a URL. We can now write tests according to our needs.
Requirement 1: Convert Celsius to Fahrenheit
In TestTemperatureConversion, let’s write a unit test for this requirement.
class TestTemperatureConversion(TestCase): def test_celcius_to_fahrenheit_conversion(self): """ Tests conversion of celcius to fahrenheit. """ celsius_1 = 25.8 data = "temperature_in_celcius": celsius_1, response = self.client.get(self.url, data) self.assertContains(response, 78.44)
Our app is expected to convert 25.8 Celsius to 78.44 Fahrenheit in the test (2 decimal places). Because the source code does not yet exist, testing will fail.
python manage.py test temperature
Only by converting Celsius to Fahrenheit will we correct this test.
Writing a source code for converting degrees Celsius to Fahrenheit
The following is a simple approach to dealing with single conversions:
- Get the input value in degrees Celsius
- Convert the value provided to the Fahrenheit temperature corresponding to the temperatures in degrees Celsius.
- Return the temperature created in Fahrenheit.
The emphasis is now transferred to the temperature / view.py file. The temperature conversion code from Celsius to Fahrenheit is added here. We also note how available measurement units are translated from Celsius. This will help us with conversions. Add the following content to a file named temperature / views.py.
from django.shortcuts import render from django.http import JsonResponse def convert(request): temp_in_celcius =float(request.GET.get('temperature_in_celcius')) temp_in_fahrenheit= float((temp_in_celcius * 9/5) + 32) data = 'temp_in_fahrenheit': temp_in_fahrenheit, return JsonResponse(data)
Finally, the conversion view should be mapped to a URL. Add the following to a file named temperature / urls.py:
from django.urls import path from .views import convert app_name="temperature" urlpatterns = [ path('temperature/', convert, name="temperature-conversion"), ]
Now it’s time to run the test with the logic to convert Celsius to Fahrenheit.
python manage.py test temperature
We have successfully implemented the Celsius Conversion Unit test to Fahrenheit and the source code to pass the unit test.
We have created a small Django app that converts temperature measurement using TDD. We went through the TDD cycle of test setup, test failure and assimilation / recovery for the test to pass. When we did, we found that passing the test actually ensures compliance with the defined criteria.
We were able to achieve and maintain a good level of test coverage, and we created tests that would serve as documentation for anyone unfamiliar with our work.
As previously stated, the temperature conversion tool allows for a great many personal experiments. For example, how about starting a Fahrenheit conversion to Celsius using TDD and letting us know how it works for you.