python - Django : fixtures object not retrievable

标签 python django testing fixtures

我在任何地方都没有看到 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>]

你知道为什么我的 fixture 只在 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,
       }
    }, 

最佳答案

那是因为 TransactionTestCase 在实例的 setUp 方法中加载了固定装置,所以它的子类包括 LiveServerTestCase 做同样的事情 - 除了 TestCase,每个类使用单个原子事务并加载 setUpClass 中的固定装置以加速测试执行。此行为已添加到 #20392 中.

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

class FrontendLiveTest(LiveServerTestCase):

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

注意事项

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

It inherits from TransactionTestCase instead of TestCase because the threads don't share the same transactions (unless if using in-memory sqlite) and each thread needs to commit all their transactions so that the other thread can see the changes.

关于python - Django : fixtures object not retrievable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50609171/

相关文章:

php - 使用 phpspec 在命令处理程序中测试工厂方法

javascript - Testcafe - 页面对象结构和默认类

python - 预期的二维数组错误未得到解决

python - 使用 PyDev 自定义调试打印格式

python - 从 .dat 文件制作颤动图

python - 在 Django 模板中循环

python - 无法在 Django 中设置自定义权限

python - Django 每天汇总记录数

java - 使用 JUnit 测试 Tapestry 页面和组件

java - 字符串类内部 - 如果使用 UTF-8,缓存字符偏移到字节关系