In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use Django for test-driven development". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The so-called test-driven development (TDD) is to write a test case first, and then write code to satisfy the test case, which includes the following steps:
Write test cases.
Write code to meet the requirements in the test case.
Run the test case.
If passed, the code meets the requirements defined by the test case.
If not, the code needs to be refactored until it is passed.
Repeat the above steps until all the test cases are passed.
Usually, we write code first and then write test cases, so test-driven development is counterintuitive, so why do we do it? For the following reasons:
TDD can be thought of as illustrating requirements based on test cases. The source code is then written with a focus on meeting these requirements. When the test finally passes, you can be sure that the requirements have been met. This focus can help developers avoid scope contagion.
TDD can improve development efficiency through a shorter development cycle. Solving individual requirements in test cases at once can minimize interference factors. Major changes will be easier to track and resolve, reduce debugging, improve efficiency, and spend more time on development.
Requirements are taken into account when writing tests. Because of this, they are more likely to be written as clear and understandable. Such tests can be used as quality documentation for the code base.
Writing test cases first ensures that your source code is always testable and that test coverage is always maintained at a reasonable percentage as the code base grows.
However, test-driven development is not a silver bullet, and the following situations are not suitable for test-driven development:
When the requirements are not clear, sometimes the renewal becomes clear as the development progresses, in which case any tests originally written may become obsolete.
The purpose of development is to prove a concept-for example, during a hackathon, testing is not usually a priority.
After learning about test-driven development, we use Django to demonstrate the process of test-driven development. (Python 3.7 +, Django 2.0 +)
First of all, describe the requirements. We want to implement a Web application with unit conversion function, which can be converted directly to each other in centimeters, meters, and miles. The Web interface is shown in the figure:
Create a project
First, we create a project called convert:
Pip install djangodjango-admin startproject converter
At this point, Django has generated the converter directory and basic project files for us:
Converter/ converter/ _ _ init__.py settings.py urls.py wsgi.py manage.py
Then, go to the converter directory and create an app named length:
Cd converterpython manage.py startapp length
Then you will see the directory structure like this:
Converter/ converter/ _ _ init__.py settings.py urls.py wsgi.py length/ _ _ init__.py admin.py apps.py migrations/ _ _ init__.py models.py tests.py views.py manage.py configure app
Modify converter/settings.py and add lengh to INSTALLED_APPS:
INSTALLED_APPS = [. . . 'length',]
Then create a new urls.py under the length directory and write the following:
From django.urls import pathfrom length import viewsapp_name = 'length'urlpatterns = [path (' convert/', views.convert, name='convert'),]
Finally, point to length/urls.py in converter/urls.py:
From django.contrib import adminfrom django.urls import path, includeurlpatterns = [path ('admin/', admin.site.urls), path (' length/', include ('length.urls')),]
Such a project without any business logic is created successfully, and then write the test case:
Write test cases
Create a new tests.py under the lengh directory and write the following:
From django.test import TestCase, Clientfrom django.urls import reverseclass TestLengthConversion (TestCase): "This class contains tests that convert measurements from one unit of measurement to another." Def setUp (self): "This method runs before the execution of each test case." Self.client = Client () self.url = reverse ("length:convert") def test_centimetre_to_metre_conversion (self): "" Tests conversion of centimetre measurements to metre. Data = {"input_unit": "centimetre", "output_unit": "metre", "input_value": 8096.894} response = self.client.get (self.url, data) self.assertContains (response, 80.96894) def test_centimetre_to_mile_conversion (self): data = {"input_unit": "centimetre" Output_unit: mile, input_value: round (985805791.3527409, 3)} response = self.client.get (self.url, data) self.assertContains (response, 6125.5113)
The above code has two test cases that represent two requirements. Test_centimetre_to_metre_conversion represents the need for centimeters to meters, while test_centimetre_to_mile_conversion represents the need for centimeters to miles.
Write code
This is no different from Django development. Write a forms.py first, as follows:
From django import formsclass LengthConverterForm (forms.Form): MEASUREMENTS = (('centimetre',' cm'), ('metre',' meters'), ('mile',' miles') input_unit = forms.ChoiceField (choices=MEASUREMENTS) input_value = forms.DecimalField (decimal_places=3) output_unit = forms.ChoiceField (choices=MEASUREMENTS) output_value = forms.DecimalField (decimal_places=3, required=False)
Then write html and create a new templates/length.html under the length directory, as follows:
Length Conversion {{form.input_unit}} {{form.input_value}} {{form.output_unit}} {{form.output_value}}
Then write the most important view function, views.py, which is as follows:
From django.shortcuts import renderfrom length.forms import LengthConverterFormconvert_to_metre = {"centimetre": 0.01,1.0 "metre", "mile": 1609.34} convert_from_metre = {"centimetre": 100,1.0 "metre" "mile": 0.000621371} # Create your views here.def convert (request): form = LengthConverterForm () if request.GET: input_unit = request.GET ['input_unit'] input_value = request.GET [' input_value'] output_unit = request.GET ['output_unit'] metres = convert_to_ tret [input _ unit] * float (input_value) print (f "{metres =} {input_value =} ") output_value = metres * convert_from_ tret [output _ unit] data = {" input_unit ": input_unit," input_value ": input_value," output_unit ": output_unit," output_value ": round (output_value 5)} form = LengthConverterForm (initial=data) return render (request, "length.html", context= {"form": form}) return render (request, "length.html", context= {"form": form}) execute the test
To implement strategy 4, you do not need to start django's runserver:
When OK appears, the test passes, and start django:
Python manage.py runserver
Open the browser and visit http://localhost:8000/length/convert/ to see the interface:
This is the end of "how to use Django for Test-driven Development". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.