首页 > 解决方案 > Django:固定装置对象不可检索

问题描述

我没有看到 LiveServerTestCase 没有加载固定装置的任何地方,但是当我执行以下操作时:

class FrontTest(LiveServerTestCase):

    fixtures = ['event.json']


    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        print(Event.objects.all())

输出是:

Using existing test database for alias 'default'...
[]

而当我使用TestCase

class FrontTest(TestCase):

    fixtures = ['event.json']


    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        print(Event.objects.all())

输出是:

[<Event: event search>]

你知道为什么我的夹具只加载在 TestCase 中吗?我真的很想让它使用 Selenium。谢谢 !

PS:event.json :

{
       "model": "mezzanine_agenda.event",
       "pk": 1,
       "fields": {
          "comments_count": 0,
          "keywords_string": "",
          "rating_count": 0,
          "rating_sum": 0,
          "rating_average": 0.0,
          "site": 1,
          "title": "event search",
          "slug": "event-search",
          "_meta_title": "",
          "description": "event search",
          "gen_description": true,
          "created": "2018-05-25T15:49:55.223Z",
          "updated": "2018-05-25T15:49:55.257Z",
          "status": 2,
          "publish_date": "2018-05-25T15:49:32Z",
          "expiry_date": null,
       }
    }, 

标签: pythondjangotestingfixtures

解决方案


这是因为TransactionTestCase在 instance'setUp方法中加载了夹具,所以它的子类包括LiveServerTestCase做同样的事情 - except TestCase,每个类使用单个原子事务并加载夹具setUpClass以加速测试执行。此行为是在#20392中添加的。

这对您来说意味着您应该将所有与数据库相关的代码从子类中setupClass移到:setUpLiveServerTestCase

class FrontendLiveTest(LiveServerTestCase):

    def setUp(self):
        # the transaction is opened, fixtures are loaded
        assert Event.objects.exists()

笔记

如果您尝试将TestCases 原子事务与LiveServerTestCases 后台线程混合:如LiveServerTestCase文档中所述,

它继承自TransactionTestCase而不是TestCase因为线程不共享相同的事务(除非使用 in-memory sqlite)并且每个线程都需要提交所有事务,以便其他线程可以看到更改。


推荐阅读