python - 在 Django 单元测试中测试手动事务

标签 python django django-unittest

如何测试禁用 autocommit 的代码并在 Django 单元测试中使用保存点?

默认的 Django unittest 类将所有测试包装在 @atomic 装饰器中,这通常正是您想要的,以确保在测试之间重置 sqlite 数据库。但是,任何从测试中触及 transaction.set_autocommit() 的代码都会抛出错误:

TransactionManagementError: This is forbidden when an 'atomic' block is active.

即使它在单元测试之外工作正常。

如何在单元测试中暂时禁用事务自动提交,以便测试手动提交?

最佳答案

使用TransactionTestCase :

TransactionTestCase and TestCase are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback: A TransactionTestCase resets the database after the test runs by truncating all tables. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

关于python - 在 Django 单元测试中测试手动事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51164697/

相关文章:

mysql - 测试中的 Django 外部 mysql 数据库连接提示 "unknown database"

python - Django 单元测试输出

Python:从字符串中检测单词并找到它的位置

python - 在 Pytorch 中强制执行 nn.Parameter(矩阵)参数中的结构

python - NGINX 在 Dockered Django 项目中找不到静态文件

django - 如何在 Django 中配置 X-Frame-Options 以允许 iframe 嵌入一个 View ?

python - Django 单元测试,未知列错误

python - 使用 OpenCV 和 Tkinter 在整个屏幕上显示视频

python - 绘制二维 numpy 数组的图例

python - 如何向 django admin 添加非 CRUD 操作