python - 如何在测试中动态创建模型?
问题描述
我想测试我的自定义子类 Django 模型字段。我可以使用我项目中的现有模型,但它们非常复杂且难以设置。
我发现了两个 SO 问题,但都相当老了(2009 年和 2012 年)。 #1 #2
所以我想问是否有人知道实现这一目标的更好方法。Django wiki 有一个自定义字段的专用页面,但我在那里没有找到任何关于测试的信息。
感谢您的任何提示或建议。
解决方案
最简单的答案是您可以在代码中声明该类。如果您只想测试初始化或验证之类的东西,那就足够了。为了在数据库中创建对象,您需要将模型添加到 django 注册表,并且为了不污染注册表以供其他按顺序运行的测试,您需要清除它。
可以在此处找到有关如何处理注册表内容的文档。这是一些基本的概述代码,它是我用来测试自定义字段的精简版本:
from django.db import connection
from django.test import TestCase
from django.test.utils import isolate_apps
class MyFieldTestCase(TestCase):
@isolate_apps('my_app_label')
def test_my_field(self):
"""Example field test
"""
class TestModel(models.Model):
test_field = MySuperCoolFieldClass()
class Meta:
app_label = 'my_app_label'
def cleanup_test_model():
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(TestModel)
with connection.schema_editor() as schema_editor:
schema_editor.create_model(TestModel)
self.addCleanup(cleanup_test_model)
# run stuff with your TestModel class
推荐阅读
- python - Odoo V10 - 组和子组
- c# - 正确使用属性和自动实现的属性?
- sublimetext3 - 在 Sublime 文本中排除 goto (CTRL + P) 中的文件夹
- c# - 人物跳跃有时更强
- c++ - 为什么 __builtin_popcount 比我自己的位计数功能慢?
- php - 在 Codeigniter 中从数据库中路由 slug 或 url
- xamarin - 单页应用程序上的 Xamarin WebView 错误 CanGoBack
- python - python - 在具有相同“外部”大小的数组之间广播
- python - Tensorflow:多尺度训练
- java - 窗口中的 Eclipse e4 部件工具栏左对齐