Frist Django app-V, Test

Source: Internet
Author: User
Tags timedelta

test--is very important but not be attached to a link, at least I myself, in fact, I was in the Java Web before the time to try to do the rest interface test, has not found a suitable way, and because the time is not further to delve into, But the consequences of each change are not sufficient to test, causing new problems, so this time for Python just look at the Django unit test.

Use a separate database, the database is clean (there is no database, test all operations are zero-based), will not affect the formal database

Test Model

By now our main business logic code is in model and view, so our test is mainly for model and view. In Django, our test code is written in tests.py, where we first add a was_published_recently method to the question class of models.py:

    def was_published_recently (self):         = Timezone.now ()        return self.publ_date >= Now-datetime.timedelta (Days=1)

Next, write unit tests for this method

classquestionmethodtest (TestCase):deftest_was_pblished_recently_with_future_question (self): time= Timezone.now () + Datetime.timedelta (days=30) Future_question= Question (publ_date=Time ) self.assertequal (future_question.was_published_recently (), False)deftest_was_pblished_recently_with_old_question (self): time= Timezone.now ()-Datetime.timedelta (days=30) Future_question= Question (publ_date=Time ) self.assertequal (future_question.was_published_recently (), False)deftest_was_pblished_recently_with_recently_question (self): time= Timezone.now ()-Datetime.timedelta (Hours=1) Future_question= Question (publ_date=Time ) self.assertequal (future_question.was_published_recently (), True)

Here we write three test cases and test them separately

    • Whether the time is greater than the current time will be checked
    • Question whether the time is less than the current time for some days will be queried to
    • Time is less than the current time of day (our previous "recent" rule sets the day) whether it will be queried to

Let's look at how Django provides the environment for our unit tests.

    • All the tests inherited from Django.test.testcase,testcase provide many test methods, such as: Assertequal,assertcontains, etc.
    • Django finds all methods that begin with test (another convention is greater than the configuration)
    • Run our tests using the Python manage.py test polls to run tests on only one app
    • Each time the test is made, Django creates a new database, which deletes the database after the test is complete, so that no pollution data is available for each test

We run the test in the MySite directory

Python manage.py Test Polls

You can see the output

Creating Test Database forAlias'default'... F..======================================================================fail:test_was_pblished_recently_with_future_question (polls.tests.QuestionMethodTest)----------------------------------------------------------------------Traceback (most recent): File"/root/django/mysite/polls/tests.py", line 17,inchtest_was_pblished_recently_with_future_question self.assertequal (future_question.was_published_recently (), False) Assertionerror:true!=False----------------------------------------------------------------------Ran3 Testsinch0.001sFAILED (Failures=1) destroying test database forAlias'default'...

You can see a total of three Tests, failed 1, review the failure information found to return true, and our expected mismatch, stating that our was_published_recently function logic is not correct, all the time is greater than the current time should not be queried out, we fix the following

    def was_published_recently (self):         = Timezone.now ()        return now >= self.publ_date >= Now-datetime.timedelta (Days=1)

Run again and you'll find that three are all successful and the result is OK

 for ' default ' ...... ----------------------------------------------------------------------in for  'default'...
Test View

The view layer invokes the code of the model layer to implement the business logic, and we guarantee the correctness of the model layer by testing the model, and then we can borrow the Django-provided environment to test whether our business logic is correct, edit tests.py

 fromDjango.testImportTestCaseImportdatetime fromDjango.utilsImportTimeZone fromPolls.modelsImportQuestion fromDjango.core.urlresolversImportReverse#Create your tests here.defcreate_question (Question_text, days): time= Timezone.now () + Datetime.timedelta (days=Days )returnQuestion.objects.create (Question_text=question_text, publ_date=Time )classquestionmethodtest (TestCase):deftest_was_pblished_recently_with_future_question (self): time= Timezone.now () + Datetime.timedelta (days=30) Future_question= Question (publ_date=Time ) self.assertequal (future_question.was_published_recently (), False)deftest_was_pblished_recently_with_old_question (self): time= Timezone.now ()-Datetime.timedelta (days=30) Future_question= Question (publ_date=Time ) self.assertequal (future_question.was_published_recently (), False)deftest_was_pblished_recently_with_recently_question (self): time= Timezone.now ()-Datetime.timedelta (Hours=1) Future_question= Question (publ_date=Time ) self.assertequal (future_question.was_published_recently (), True)classquestionviewtest (TestCase):deftest_index_view_with_no_questions (self): response= Self.client.get (Reverse ('Polls:index')) self.assertequal (Response.status_code,200) Self.assertcontains (response,'No polls is available') self.assertquerysetequal (response.context['latest_question_list'], [])    deftest_index_view_with_a_past_question (self): create_question ('past question.',-30) Response= Self.client.get (Reverse ('Polls:index')) self.assertquerysetequal (response.context['latest_question_list'], ['<question:past question.>'])    deftest_index_view_with_a_future_question (self): create_question ('Future question.', 30) Response= Self.client.get (Reverse ('Polls:index')) Self.assertcontains (response,'No polls is available') self.assertquerysetequal (response.context['latest_question_list'], [])    deftest_index_view_with_future_question_and_past_question (self): create_question ('past question.',-30) create_question ('Future question.', 30) Response= Self.client.get (Reverse ('Polls:index')) self.assertquerysetequal (response.context['latest_question_list'], ['<question:past question.>'])    deftest_index_view_with_two_past_question (self): create_question ('past question 1.',-30) create_question ('past question 2.',-5) Response= Self.client.get (Reverse ('Polls:index')) self.assertquerysetequal (response.context['latest_question_list'], ['<question:past Question 2.>','<question:past Question 1.>'])
View Code

Django provides more help for our view layer testing

    • TestCase includes a client that represents a
    • The Get,post method can be called by the client to get the return value of the server response
    • Gets the httpcode of the response, returning the context parameter
About testing
    • More is better,test would look after themselves. The more test cases, the more comprehensive testing, if the code changes, test case execution will fail, you can remind us to modify the corresponding test
    • A separate model or view should use a separate test class
    • Each test case writes a separate test method
    • The test method describes its function as much as possible (see article)

Full code

Http://pan.baidu.com/s/1geJ7DYj

Frist Django app-V, Test

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.