首页 > 解决方案 > 如何在测试中动态创建模型?

问题描述

我想测试我的自定义子类 Django 模型字段。我可以使用我项目中的现有模型,但它们非常复杂且难以设置。

我发现了两个 SO 问题,但都相当老了(2009 年和 2012 年)。 #1 #2

所以我想问是否有人知道实现这一目标的更好方法。Django wiki 有一个自定义字段的专用页面,但我在那里没有找到任何关于测试的信息。

感谢您的任何提示或建议。

标签: pythondjangopython-3.xunit-testingdjango-2.x

解决方案


最简单的答案是您可以在代码中声明该类。如果您只想测试初始化​​或验证之类的东西,那就足够了。为了在数据库中创建对象,您需要将模型添加到 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

推荐阅读