在Django项目中的每一个app下都有一个tests.py文件,该app中所有的行为测试都可以放在该文件中,通过对视图或者行为建立测试函数,运行python3 manage.py test app 即可得到测试结果
import datetimefrom django.test import TestCasefrom django.utils import timezonefrom.models import QuestionclassQuestionModelTests(TestCase):deftest_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)deftest_was_published_recently_with_old_question(self):""" was_published_recently() returns False for questions whose pub_date is older than 1 day. """ time = timezone.now()- datetime.timedelta(days=1, seconds=1) old_question =Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False)deftest_was_published_recently_with_recent_question(self):""" was_published_recently() returns True for questions whose pub_date is within the last day. """ time = timezone.now()- datetime.timedelta(hours=23, minutes=59, seconds=59) recent_question =Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True)
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> # create an instance of the client for our use
>>> client = Client()
>>> # get a response from '/'
>>> response = client.get('/')
Not Found: /
>>> # we should expect a 404 from that address; if you instead see an
>>> # "Invalid HTTP_HOST header" error and a 400 response, you probably
>>> # omitted the setup_test_environment() call described earlier.
>>> response.status_code
404
>>> # on the other hand we should expect to find something at '/polls/'
>>> # we'll use 'reverse()' rather than a hardcoded URL
>>> from django.urls import reverse
>>> response = client.get(reverse('polls:index'))
>>> response.status_code
200
>>> response.content
b'\n <ul>\n \n <li><a href="/polls/1/">What's up?</a></li>\n \n </ul>\n\n'
>>> response.context['latest_question_list']
<QuerySet [<Question: What's up?>]>
defget_queryset(self):""" Return the last five published questions (not including those set to be published in the future). """return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5]