【发布时间】:2018-10-22 08:00:14
【问题描述】:
我想使用假设来测试我们为从 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 化的模型编写测试,它们将完全相同,除了 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 模型编写相同的基本参数测试?
【问题讨论】: