我想使用假设来测试我们为从 Django 模型创建 avro 模式而编写的工具。使用 django extra 为单个模型编写测试非常简单:
from avro.io import AvroTypeException
from hypothesis import given
from hypothesis.extra.django.models import models as hypothetical
from my_code import models
@given(hypothetical(models.Foo))
def test_amodel_schema(self, amodel):
"""Test a model through avro_utils.AvroSchema"""
# Get the already-created schema for the current model:
schema = (s for m, s in SCHEMA if m == amodel.model_name)
for schemata in schema:
error = None
try:
schemata.add_django_object(amodel)
except AvroTypeException as error:
pass
assert error is None
...但是如果我要为每个可以被 avro-schema-ified 的模型编写测试,它们将完全相同,除了given
装饰器的参数。我可以获得我有兴趣测试的所有模型,并ContentTypeCache.list_models()
返回一个字典schema_name: model
(是的,我知道,它不是一个列表)。但是我怎样才能生成像
for schema_name, model in ContentTypeCache.list_models().items():
@given(hypothetical(model))
def test_this_schema(self, amodel):
# Same logic as above
我考虑过基本上动态生成每个测试方法并将其直接附加到全局变量,但这听起来很难理解。如何以尽可能少的混乱动态编程为不同的 django 模型编写相同的基本参数测试?