Django单元测试:应该如何测试抽象模型?
在我的Django项目中,我有一个名为“core”的应用程序,其中包含我所有的可重用模型混合/抽象模型(behaviors.py)、模型(models.py)、视图(views.py)和助手函数(utils.py): 现在我想为这些文件编写测试。对于模型、UTIL和视图,我只是像以前一样编写了单元测试 我现在不确定应该如何测试behaviors.py中包含的抽象模型。例如,我有一个mixin模型:Django单元测试:应该如何测试抽象模型?,django,unit-testing,django-models,django-testing,django-tests,Django,Unit Testing,Django Models,Django Testing,Django Tests,在我的Django项目中,我有一个名为“core”的应用程序,其中包含我所有的可重用模型混合/抽象模型(behaviors.py)、模型(models.py)、视图(views.py)和助手函数(utils.py): 现在我想为这些文件编写测试。对于模型、UTIL和视图,我只是像以前一样编写了单元测试 我现在不确定应该如何测试behaviors.py中包含的抽象模型。例如,我有一个mixin模型: 将uuid导入为uuid_库 从django.db导入模型 类UniversalYuniquide
将uuid导入为uuid_库
从django.db导入模型
类UniversalYuniquidentifiable(models.Model):
uuid=models.UUIDField(
db_index=True,
默认值=uuid_lib.uuid4,
可编辑=假
)
类元:
抽象=真
如何测试抽象模型?
在我以前学习的fat模型中,作者只是测试他使用抽象模型的模型。但这对我来说并不是很枯燥,因为这意味着我必须在使用UUID的每个模型中测试UUID的添加。
有更好的方法吗?试试下面的代码
from django.db import connection
from django.db.models.base import ModelBase
from django.test import TestCase
from .models import UniversallyUniqueIdentifiable
import uuid
class TestUniversallyUniqueIdentifiable(TestCase):
model = UniversallyUniqueIdentifiable
def setUp(self):
# Create a dummy model
self.model = ModelBase(
'__TestModel__' + self.model.__name__, (self.model,),
{'__module__': self.model.__module__}
)
# Create the schema for our test model
with connection.schema_editor() as schema_editor:
schema_editor.create_model(self.model)
def test_mytest_case(self):
self.model.objects.create(uuid=uuid.uuid4())
self.assertEqual(self.model.objects.count(), 1)
def tearDown(self):
# Delete the schema for the test model
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(self.model)
如果Django团队改变连接内部行为的方式,Django的答案是惊人的,但可读性不强,并且可能不太容易维护
我要做的是:
通过使用此抽象类的任何模型测试抽象类的泛型属性
测试该是否为抽象类的子类化
测试此模型的特定属性
对任何其他型号重复2和3
示例:一个抽象类平行四边形
和一个使用它的模型正方形
from unittest import TestCase
from tetrahedrons.models import Parallelogram, Square
class ParallelogramAbstractModelTest(TestCase):
def test_has_four_sides(self):
...
def test_parallel_opposite_sides(self):
...
class SquareModelTest(TestCase):
def test_subclasses_mobel_base(self):
self.assertTrue(issubclass(Square, Parallelogram))
def test_equal_sides(self):
...
我不确定你想在这里测试什么。这是一个具有单个UUID字段的简单模型;没有要测试的功能。哦,好的。我认为您必须测试UUID是否成功地添加到从该模型继承的类中。
from unittest import TestCase
from tetrahedrons.models import Parallelogram, Square
class ParallelogramAbstractModelTest(TestCase):
def test_has_four_sides(self):
...
def test_parallel_opposite_sides(self):
...
class SquareModelTest(TestCase):
def test_subclasses_mobel_base(self):
self.assertTrue(issubclass(Square, Parallelogram))
def test_equal_sides(self):
...