current position:Home>Test driven development using Django

Test driven development using Django

2022-02-01 06:07:49 somenzz

The so-called test driven development (TDD), Is to write test cases first , Then write code to meet the test cases , It includes the following steps :

  1. Write test cases .
  2. Write code to meet the requirements in the test case .
  3. Run test cases .
  4. If you pass , Explain that the code meets the requirements defined by the test case .
  5. If not , You need to refactor the code , Until it passes .
  6. Repeat the above steps , Until you pass all the test cases .

Usually , We all write code first , Then write test cases , So test driven development is counterintuitive , Then why do you do this ? For the following reasons :

  1. TDD It can be considered to illustrate requirements according to test cases . Then write the source code , The focus is 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 creep .
  2. TDD The development efficiency can be improved through a shorter development cycle . Solving individual requirements in test cases at one time can minimize interference factors . Major changes will be easier to track and resolve , Reduce debugging work , Improved efficiency , And spend more time on Development .
  3. Write tests with requirements in mind . Because of that , They are more likely to be written explicitly , Understandable . Such a test can be used as a high-quality document of the code base .
  4. Writing test cases first ensures that your source code is always testable , It also ensures that as the code base grows , Test coverage is always maintained at a reasonable percentage .

However , Test driven development is not a silver bullet , The following situations are not suitable for Test Driven Development :

  1. When the requirements are not clear , Sometimes the renewal will become clear as the development goes on , In this case, any tests originally written may be outdated .
  2. When the purpose of development is to prove a concept —— For example, during the hacker Marathon , Testing is usually not a priority .

After learning about Test Driven Development , We use it Django Let's demonstrate the process of Test Driven Development .(Python 3.7 above ,Django 2.0 above )

First, describe the requirements , We want to realize such a unit conversion function Web application , It can be in centimeters 、 rice 、 Miles directly convert to each other ,Web The interface is as shown in the figure :

Create project

First , We created a project called convert Project :

pip install django
django-admin startproject converter
 Copy code 

here Django Has generated for us converter Directory and basic project files :

converter/
    converter/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    manage.py
 Copy code 

then , Get into converter Catalog , Create a name called length Of app:

cd converter
python manage.py startapp length
 Copy code 

Then you will see such a directory structure :

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
 Copy code 

To configure app

modify converter/settings.py, stay INSTALLED_APPS Add in lengh :

INSTALLED_APPS = [
    .
    .
    .
    'length',
]
 Copy code 

And then in length New under the directory urls.py, Write the following :

from django.urls import path

from length import views

app_name = 'length'
urlpatterns = [
    path('convert/', views.convert, name='convert'),
]

 Copy code 

Last in converter/urls.py Point to length/urls.py:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('length/', include('length.urls')),
]
 Copy code 

Such a project without any business logic is successfully created , Next, write test cases :

Write test cases

stay lengh New under the directory tests.py, Write the following :

from django.test import TestCase, Client
from django.urls import reverse


class 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)
 Copy code 

The above code has two test cases , Each represents two requirements .test_centimetre_to_metre_conversion Represents the demand for centimeter to meter , and test_centimetre_to_mile_conversion Represents the demand for centimeters to miles .

Write code

This sum Django Development is no different , Let's write one forms.py, The contents are as follows :

from django import forms

class LengthConverterForm(forms.Form):
    MEASUREMENTS = (
        ('centimetre', ' centimeter '),
        ('metre', ' rice '),
        ('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)

 Copy code 

Then write html, stay length New under the directory templates/length.html, The contents are as follows :

<html lang="en">
  <head>
    <title>Length Conversion</title>
  </head>
  <body>
    <form action={% url "length:convert" %} method="get">
      <div>
        {{ form.input_unit }}
        {{ form.input_value }}
      </div>
      <input type="submit" value=" Convert to :"/>
      <div>
        {{ form.output_unit }}
        {{ form.output_value }}
      </div>
   </form>
  </body>
</html>
 Copy code 

Then write the most important view function views.py, The contents are as follows :

from django.shortcuts import render

from length.forms import LengthConverterForm

convert_to_metre = {
    "centimetre": 0.01,
    "metre": 1.0,
    "mile": 1609.34
}
convert_from_metre = {
    "centimetre": 100,
    "metre": 1.0,
    "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_metre[input_unit] * float(input_value)
        print(f"{metres = }, {input_value = }")
        output_value = metres * convert_from_metre[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})
 Copy code 

Perform the test

Implementing strategy 4 does not need to start django Of runserver:

appear OK Indicates that the test passed , start-up django:

python manage.py runserver
 Copy code 

Open the browser , visit http://localhost:8000/length/convert/ You can see the interface :

Last words

This article shares what test driven development is , And Test Driven Development Create a simple Django Applications , For length conversion . The difference from general development is to write test cases first , Coding is to make the test case pass , This way can make the requirements clearer , Shorter development cycle , Increment controllable , Improve development efficiency , Ensure test coverage .

If it works , Please like it 、 Looking at 、 Focus on supporting , thank !

copyright notice
author[somenzz],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202010607464483.html

Random recommended