【问题标题】:Same hypothesis test for different django models不同 Django 模型的相同假设检验
【发布时间】: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 模型编写相同的基本参数测试?

【问题讨论】:

    标签: django python-hypothesis


    【解决方案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 个测试相同数量的示例。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-11-25
        • 2020-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-15
        • 1970-01-01
        • 2020-09-02
        相关资源
        最近更新 更多