Django测试

创建一个测试

## app/tests.py

import
datetime from django.utils import timezone from django.test import TestCase from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertEqual(future_question.was_published_recently(), False)

我们在这里做的是创建一个django.test.TestCase子类,它具有一个方法可以创建一个pub_date在未来的Question实例。然后我们检查was_published_recently()的输出 —— 它应该是 False.

运行测试

在终端中,我们可以运行我们的测试:

$ python manage.py test polls

你将看到类似下面的输出:

Creating test database for alias 'default'...
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionMethodTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/to/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_question
    self.assertEqual(future_question.was_published_recently(), False)
AssertionError: True != False

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)
Destroying test database for alias 'default'...

发生了如下这些事:

  • python manage.py test app 命令会查找app 应用下的测试用例
  • 它找到 django.test.TestCase 类的一个子类
  • 它为测试创建了一个特定的数据库
  • 它查找用于测试的方法 —— 名字以test开始
  • 它运行test_was_published_recently_with_future_question创建一个pub_date为未来30天的 Question实例
  • ... 然后利用assertEqual()方法,它发现was_published_recently() 返回True,尽管我们希望它返回False。(assertEqual()方法返回True值说明检测到了错误,返回False值说明没有检测到错误)

这个测试通知我们哪个测试失败,甚至是错误出现在哪一行。

修复这个错误

再次运行测试

原文地址:https://www.cnblogs.com/haoshine/p/5631674.html