简体   繁体   English

当Django解释器返回True时,为什么测试用例在Django中失败?

[英]Why is test case failing in Django when it returns True in Python intrepreter?

When I run this code in the Python interpreter, it returns True: 当我在Python解释器中运行此代码时,它返回True:

>>> from movies.models import Movie
>>> movie_list = Movie.objects.all()
>>> bool(movie_list)
True

When I run my test case, python3 manage.py test movies , it fails: 当我运行测试用例python3 manage.py test movies ,它将失败:

from django.test import TestCase
from .models import Movie

class QuestionMethodTests(TestCase):

    def test_movie_list_empty(self):
        movie_list = Movie.objects.all()
        self.assertEqual(bool(movie_list), True)

What am I missing? 我想念什么? Shouldn't the test pass? 考试不应该通过吗?

I see. 我懂了。 Does that mean the test cases only test the code but can't use any of the actual database content in its tests? 这是否意味着测试用例仅测试代码,但不能在测试中使用任何实际的数据库内容?

By default no, and you don't want to mess with the actual DB anyway, there is a usual way to provide the initial objects for the tests (the actual source can differ, eg loading from a file) 默认情况下,不,并且您也不想弄乱实际的数据库,有一种通常的方法为测试提供初始对象(实际来源可能有所不同,例如从文件加载)

from django.test import TestCase
from .models import Movie

class QuestionMethodTests(TestCase):

    def setUp(self):
        # You can create your movie objects here
        Movie.objects.create(title='Forest Gump', ...)

    def test_movie_list_empty(self):
        movie_list = Movie.objects.all()
        self.assertEqual(bool(movie_list), True)

The TestCase class also contains a setUpTestData method if you fancy that, https://docs.djangoproject.com/en/1.8/topics/testing/tools/#django.test.TestCase.setUpTestData 如果您setUpTestDataTestCase类还包含一个setUpTestData方法, https : setUpTestData

PS: test_movie_list_empty name sounds weird, cause it seems to test that the movie list is NOT empty PS: test_movie_list_empty名称听起来很奇怪,导致似乎测试电影列表不为空

Because in tests you are using a temporary database which doesn't have the objects: 因为在测试中您使用的是一个没有对象的临时数据库

Tests that require a database (namely, model tests) will not use your “real” (production) database. 需要数据库的测试(即模型测试)将不会使用“实际”(生产)数据库。 Separate, blank databases are created for the tests. 将为测试创建单独的空白数据库。

Regardless of whether the tests pass or fail, the test databases are destroyed when all the tests have been executed. 无论测试是通过还是失败,都将在执行所有测试后破坏测试数据库。

It's dangerous to use the real database for tests. 使用真实的数据库进行测试是危险的。 Especially that tests should be reproducible, on other machines too. 尤其是该测试也应该在其他机器上可以重现。 You should use fixtures for tests. 您应该使用夹具进行测试。 Look at factory_boy . factory_boy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM