mongoengine模型的假设策略
hypothesis-mongoengine的Python项目详细描述
此包包含用于从MongoEngine模型生成示例文档的Hypothesis策略。
下面是一个简单的例子:
fromhypothesisimportgiven,notefromhypothesis_mongoengine.strategiesimportdocumentsfrommongoengineimportDocument,StringFieldclassFoo(Document):foo=StringField()@given(documents(Foo))deftest_something(foo):# Handy since the default __repr__ is unhelpful:note(foo.to_json())asserthasattr(foo,'id')
通过将每个字段的备用策略作为关键字参数传递,可以自定义示例的生成:
@given(documents(Foo,foo=strategies.strings(max_size=7)))deftest_anotherthing(foo):pass
默认情况下,将生成针对内置mongoengine限制进行验证的所有示例。 如果不需要该字段,则还将生成None。 如果指定了choices,则只生成这些值。
如果指定了validation,则验证函数将筛选默认策略。 如果自定义验证函数接受的值太少,则假设可能无法通过运行状况检查。 在这种情况下,提供一个自定义验证器,它可以更有效地生成可接受的示例。
不支持的内容
ReferenceField一般不受支持,可能永远也不受支持。 您可以而且应该为这些字段提供特定于应用程序的策略。 这允许您确保满足应用程序所需的引用完整性约束。 不要忘记MongoEngine希望在您尝试引用文档之前将文档保存到数据库中。 可以使用hypothesis_mongoengine.helpers.mark_saved函数使文档显示为已保存。
DictField一般不受支持,可能永远也不受支持。 MapField一般受支持,当值同质时,应首选DictField。 为DictField编写自定义策略时, 您可以使用hypothesis_mongoengine.strategies.mongodb_keys策略在缺少有关密钥的更具体应用程序知识的情况下生成密钥。
DynamicDocument(和DynamicEmbeddedDocument)当前只生成显式指定的字段。
DynamicField通常由DynamicDocument在内部使用, 但是,如果您有一个显式引用它的模型,则不会对其进行泛型处理。
处理自定义字段
如果在应用程序中使用自定义字段, 您可以使用field_stratdecorator注册一个策略来为它生成示例。
例如,来自extras-mongoengine的EnumField的策略可能如下所示:
fromextras_mongoengine.fieldsimportEnumFieldfromhypothesisimportstrategiesfromhypothesis_mongoengine.strategiesimportfield_strat@field_strat(EnumField)defmy_custom_strat(field):returnstrategies.sampled_from(field.enum)
通过类的相等性在注册表中查找字段, 因此,如果有自定义字段的层次结构,则必须注册叶类型。 但是,如果需要,可以多次堆叠装饰器:
fromextras_mongoengine.fieldsimportEnumField,IntEnumField,StringEnumFieldfromhypothesisimportstrategiesfromhypothesis_mongoengine.strategiesimportfield_strat@field_strat(EnumField)@field_strat(IntEnumField)@field_strat(StringEnumField)defmy_custom_strat(field):returnstrategies.sampled_from(field.enum)