How do unit testing Web project

You might use unit testing framework, python's unittest, pytest, Java's Junit, testNG and so on.

So what would you do unit testing! Of course, what is difficult?

test_demo.py

def inc(x):
    return x + 1


def test_answer():
    assert inc(3) == 4

inc is () is defined by a test function, test_anserver () for the above test piece of code.

Pytest by running the above code:

> pytest test_demo.py
====================== test session starts ======================= platform win32 -- Python 3.7.1, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: D:\vipcn\demo
plugins: cov-2.7.1, forked-1.0.2, html-1.20.0, metadata-1.8.0, ordering-0.6, parallel-0.0.9, rerunfailures-7.0, xdist-1.28.0, seleniumbase-1.23.10
collected 1 item

test_demo.py .                                              [100%]

==================== 1 passed in 0.08 seconds ====================

Unit testing is so not a single thing!


Then the Web project unit testing how to do?

We Django Web framework, for example, it is a MTVdevelopment model. The next will be around this model explains how to do the test.

Model test

  • Models M means, for defining the ORM, i.e., object-relational mapping, by using metadata mapping between objects and description databases, object-oriented object language program automatically persisted to a relational database.

models.py code is such that:

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(auto_now=True)

This defines two classes, i.e., no two parameters into classes, there is no return value is returned. How to test it?

Test code is as follows:

from django.test import TestCase
from myapp.models import Question

class QuestionTestCase(TestCase):

    def setUp(self):
        Question.objects.create(id=1, question_text="你会做单元测试么?")

    def test_question(self):
        """查询id=1的问题"""
        question = Question.objects.get(id=1)
        self.assertEqual(question.question_text, '你会做单元测试么?')

I do not know if you read the code, django model we can be seen as a database table, then the operating table is for CRUD , where the first piece of data is created, then check out this data, and then determine which fields are correct .

Reference: https: //docs.djangoproject.com/en/2.2/topics/testing/overview/

View test

  • V refers to the views, the front end for receiving a request sent, may need to call the database, then the corresponding data processing, and returns HTML pages to the front end together.

views.py code is as follows:

from django.shortcuts import render
from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

index () view does have the function parameters, request contains the client information, such as the request method, request host, the request header Header, these data the client how to construct? return returns HTML pages, and data query the database, how to write data to these assertions do?

Test code is as follows:

from django.test import TestCase
from myapp.models import Question

class IndexTestCase(TestCase):

    def setUp(self):
        Question.objects.create(id=1, question_text="你会做单元测试么?")

    def test_index(self):
        """测试index视图"""
        response = self.client.get("/index")
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "polls/index.html")

It is assumed that when the browser visits http://127.0.0.1:8000/index call when the index view, the problem back to the list page.

self.client.get () can impersonate the client browser sends a request GET request. Get the service side of the response, determining whether the status code 200. self.assertTemplateUsed () predicate returns a page are correct.

Reference: https: //docs.djangoproject.com/en/2.2/topics/testing/tools/

Mask Testing

  • T refers Teamplate, mainly HTML page. Users type in the URL in your browser will eventually get an HTML page.

index.html code is as follows:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a name="q" href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

There's even a method of code are not, not to mention the parameters and return values, and to ask how the HTML code to test?

We really have no way directly to the HTML code to be tested. However, the UI can make use of Selenium to do automated testing, so as to ensure the correctness of the page.

from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver

class MySeleniumTests(StaticLiveServerTestCase):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.selenium = webdriver.Chrome()
        cls.selenium.implicitly_wait(10)

    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        super().tearDownClass()

    def test_index_page(self):
        self.selenium.get('%s%s' % (self.live_server_url, '/index'))
        question_list = self.selenium.find_elements_by_name("q")
        for q in question_list:
            print(q.text)

Django encapsulates StaticLiveServerTestCase , so that when you run the UI test starts Django service automatically. So, you can directly use self.live_server_url access service address django started.

Reference: https: //docs.djangoproject.com/en/2.2/topics/testing/tools/

Was this article to refresh your understanding of the project unit test? So the question is, which part I belong to the above code written unit tests ?

Guess you like

Origin www.cnblogs.com/fnng/p/11318441.html