Django 单元测试:应该如何测试抽象模型?



在我的Django项目中,我有一个名为'core'的应用程序,其中包含我所有可重用的模型mixins/抽象模型(behaviors.py(,模型(models.py(,视图(views.py(和辅助函数(utils.py(:

core/
__init__.py
behaviors.py  
models.py
utils.py
views.py

我现在想为这些文件编写测试。对于模型、实用程序和视图,我只是像以前一样编写单元测试。

我现在不确定我应该如何测试 behaviors.py 中包含的抽象模型。例如,我有这个模型混合:

import uuid as uuid_lib
from django.db import models

class UniversallyUniqueIdentifiable(models.Model):
uuid = models.UUIDField(
db_index=True,
default=uuid_lib.uuid4,
editable=False
)
class Meta:
abstract = True

如何测试抽象模型? 在我用来学习脂肪模型的一篇文章中,作者只是测试了他使用抽象模型的模型。但这对我来说感觉不是很干燥,因为这意味着我必须在我使用它的每个模型中测试UUID的添加。 有没有更好的方法?

Anjaneyulu Batta的答案是惊人的,但不是那么可读,如果Django团队改变内部行为方式connection可能会不太容易维护。

我会做什么:

  1. 使用此 抽象类通过任何模型测试抽象类的泛型属性。
  2. 测试这是否是抽象类的子类化。
  3. 测试此模型的特定属性
  4. 对任何其他型号重复 2 和 3。

示例:一个抽象类Parallelogram,一个使用它的模型称为Square

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):
...

尝试下面的代码

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)

最新更新