做网站后付款,网站建设色系搭配,免费建立属于自己的网站,北京顺义网站建设Django 应用的测试应该写在应用的 tests.py 文件里。测试系统会自动的在所有以 tests 开头的文件里寻找并执行测试代码。 我们的 polls 应用现在有一个小 bug 需要被修复#xff1a;我们的要求是如果 Question 是在一天之内发布的#xff0c; Question.was_published_recentl…Django 应用的测试应该写在应用的 tests.py 文件里。测试系统会自动的在所有以 tests 开头的文件里寻找并执行测试代码。 我们的 polls 应用现在有一个小 bug 需要被修复我们的要求是如果 Question 是在一天之内发布的 Question.was_published_recently() 方法将会返回 True 然而现在这个方法在 Question 的 pub_date 字段比当前时间还晚时也会返回 True这是个 Bug。 https://docs.djangoproject.com/zh-hans/4.2/intro/tutorial05/
polls/test.py
import datetimefrom django.test import TestCase
from django.utils import timezonefrom .models import Questionclass QuestionModelTests(TestCase):def test_was_published_recently_with_future_question(self):was_published_recently() returns False for questions whose pub_dateis in the future.time timezone.now() datetime.timedelta(days30)future_question Question(pub_datetime)self.assertIs(future_question.was_published_recently(), False)运行
$ python manage.py test polls自动化测试的运行过程
python manage.py test polls 将会寻找 polls 应用里的测试代码 它找到了 django.test.TestCase 的一个子类 它创建一个特殊的数据库供测试使用 它在类中寻找测试方法——以 test 开头的方法。 在 test_was_published_recently_with_future_question 方法中它创建了一个 pub_date 值为 30 天后的 Question 实例。 接着使用 assertls() 方法发现 was_published_recently() 返回了 True而我们期望它返回 False。 测试系统通知我们哪些测试样例失败了和造成测试失败的代码所在的行号。
修复缺陷 polls/models.py
def was_published_recently(self):now timezone.now()return now - datetime.timedelta(days1) self.pub_date now再次运行测试通过。