0

我想使用假设来测试我们为从 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 模型编写相同的基本参数测试?

4

2 回答 2

2

您可以使用以下命令将其编写为单个测试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 个测试相同数量的示例。

于 2018-05-12T11:45:23.917 回答
0

我通常会通过参数化测试并在内部借鉴策略来解决此类问题:

@pytest.mark.parametrize('model_type', list(ContentTypeCache.list_models().values()))
@given(data=st.data())
def test_amodel_schema(self, model_type, data):
    amodel = data.draw(hypothetical(model_type))
    ...
于 2018-05-23T04:27:19.960 回答