如何在测试中动态创建模型?
how to dynamicaly create models in tests?
我想测试我的自定义子类 Django 模型字段。我可以使用我项目中的现有模型,但它们非常复杂且难以设置。
我找到了两个 SO 问题,但它们都很旧(2009 年和 2012 年)。
#1 #2
所以我想问问有没有人知道更好的方法来实现这个。 Django wiki 有一个专门的页面 custom fields,但我在那里没有找到任何关于测试的信息。
感谢任何提示或建议。
最简单的答案是您可以在代码中声明 class。如果您只想测试初始化或验证之类的事情,那就足够了。为了在数据库中创建对象,您需要将模型添加到 django 注册表,并且为了不污染注册表以供其他测试 运行 依次使用,您需要清除它。
可以找到有关如何处理注册表内容的文档 here。这是一些基本的概述代码,是我用来测试自定义字段的代码的精简版:
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
我想测试我的自定义子类 Django 模型字段。我可以使用我项目中的现有模型,但它们非常复杂且难以设置。
我找到了两个 SO 问题,但它们都很旧(2009 年和 2012 年)。 #1 #2
所以我想问问有没有人知道更好的方法来实现这个。 Django wiki 有一个专门的页面 custom fields,但我在那里没有找到任何关于测试的信息。
感谢任何提示或建议。
最简单的答案是您可以在代码中声明 class。如果您只想测试初始化或验证之类的事情,那就足够了。为了在数据库中创建对象,您需要将模型添加到 django 注册表,并且为了不污染注册表以供其他测试 运行 依次使用,您需要清除它。
可以找到有关如何处理注册表内容的文档 here。这是一些基本的概述代码,是我用来测试自定义字段的代码的精简版:
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