对不同的django模型进行相同的假设检验

时间:2018-05-11 20:58:09

标签: django python-hypothesis

我想使用假设来测试我们编写的工具,以便从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模型编写相同的基本参数测试,并尽可能地混淆动态编程?

1 个答案:

答案 0 :(得分:1)

您可以使用one_of将其编写为单个测试:

import hypothesis.strategies as st

@given(one_of([hypothetical(model) for model in ContentTypeCache.list_models().values()]))
def test_this_schema(self, amodel):
   # Same logic as above

您可能希望使用类似@settings(max_examples=settings.default.max_examples * len(ContentTypeCache.list_models()))的内容来增加在这种情况下运行的测试数量,以便它运行与N个测试相同数量的示例。