python - 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,
}
},
解决方案
这是因为TransactionTestCase
在 instance'setUp
方法中加载了夹具,所以它的子类包括LiveServerTestCase
做同样的事情 - except TestCase
,每个类使用单个原子事务并加载夹具setUpClass
以加速测试执行。此行为是在#20392中添加的。
这对您来说意味着您应该将所有与数据库相关的代码从子类中setupClass
移到:setUp
LiveServerTestCase
class FrontendLiveTest(LiveServerTestCase):
def setUp(self):
# the transaction is opened, fixtures are loaded
assert Event.objects.exists()
笔记
如果您尝试将TestCase
s 原子事务与LiveServerTestCase
s 后台线程混合:如LiveServerTestCase
文档中所述,
它继承自
TransactionTestCase
而不是TestCase
因为线程不共享相同的事务(除非使用 in-memorysqlite
)并且每个线程都需要提交所有事务,以便其他线程可以看到更改。
推荐阅读
- laravel - REST - 嵌套资源和控制器 & Laravel
- wordpress - 在 rest api 上获取自定义分类
- delphi - 是否可以将 jpg/png 图像加载到 TbitBtn 或 TSpeedButton 中?
- python - 如何在没有身份验证的情况下使用 python 上传到谷歌驱动器?
- javascript - 调用外部函数时如何重新渲染 React 组件?
- php - MySQL 查询更新失败
- javascript - 默认情况下如何使Angular-Google-Map全屏
- image - Vue.js 不显示动态加载路径字符串的图像
- ios - DateFormatter 返回有效字符串
- apache-spark - MLeap 和 Spark ML SQLTransformer