Test Case
import datetime from django.test import TestCase from django.utils import timezone from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False)
Execute python manage.py test polls, will proceed as follows
1 polls find application in the test code
2 subclass looking django.test.TestCase, such as QuestionModelTests
3 to create a special database for testing, such as creating future_question, not in the user database is created, but created in a test database
4 looking in the class test methods - methods that begin with the test
5 using assertls () method, to confirm whether the function returns expectations
Client
Django provides a Client for testing to simulate user interaction and the view-level code
python shell UI
from django.test Import Client from django.urls Import Reverse Client = Client () Response = client.get ( ' / ' ) response.status_code Response = client.get (Reverse ( ' polls: index ' )) # request the application polls view index response.status_code # output: 200 is response.content # output: index view corresponding html content of response.context [ ' latest_question_list ' ] #输出:<QuerySet [<Question: What's up?>]>
About test cases
before writing the code to write test cases can be decided according to the actual situation of
each add a functionality to be added to the corresponding test cases and test cases better
test cases too, might lose control, : in the overall planning, refer to the following principles
for each model and create separate views are TestClass
each test method to test only one function
to each test method from a name of its function can be described
later when the test finished by , it can be forever retained
because the role of the test case, in fact, in monitoring the corresponding code
when, for example, in the future to modify other code, you may inadvertently cause this code does not return the expected value
when the test is performed after modification, will It found that the bug
Selenium
Selenium is a browser test automation tool
it pretends to be a browser and the site is interactive, life-like access to the site in
Django provides LiveServerTestCase with tools such as Selenium to interact
Code coverage
to find the code that are not part of the test method is to check the code coverage
it helps to find out the weak and useless parts of the code section
delete If you can not test a piece of code, usually indicates the code needs to be reconstructed or
Continuous integration
of automated source code to compile, test, code inspection, and packing procedures, deploy (publish) to the application server