【问题标题】:Using example for strategies that return class instances将示例用于返回类实例的策略
【发布时间】:2018-04-15 11:03:00
【问题描述】:

我有

class A(st.SearchStrategy):
  def do_draw(self, data):
     return object_a(b=st.integers(), c=st.boolean()...)

class B(st.SearchStrategy):
  def do_draw(self, data):
     return object_a(d=st.boolean(), e=st.boolean()...)

@given(a=A(), b=B())
def test_A_and_B(a, b):
  ...

我如何确定一个测试用例

a = A(b=5, c=True)
# b can be anything

和一个测试用例

a = A(b=10, c=True)
b = B(c=True, d=<can be either T or F>)

生成?

我知道@example。这是正确的吗?

@given(a=A(), b=B())
@example(a=A(b=10, c=True), b=B(c=True, d=False)
# not sure how to set d to be either true or false
def test_A_and_B(a, b):
  ...

【问题讨论】:

    标签: python-hypothesis


    【解决方案1】:

    不要从搜索策略继承。
    它是私有的内部代码,我们可能随时更改。反正你用错了!

    相反,您应该根据documented functions 中的hypothesis.strategies 制定策略。例如,您可以使用builds() 定义一个创建object_a 实例的策略,如下所示:

    builds(object_a, b=st.integers(), c=st.booleans(), ...)
    

    @example 是单个精确输入,因此您需要使用它两次来检查真假:

    @example(a=object_a(b=10, c=True), b=object_b(c=True, d=True)
    @example(a=object_a(b=10, c=True), b=object_b(c=True, d=False)
    

    如果您根本不关心 b 的值,只需使用该参数的默认值定义一个示例。

    所有这些,看起来像:

    @given(
        a=builds(object_a, b=st.integers(), c=st.booleans()), 
        b=builds(object_b, d=st.booleans(), e=st.booleans()
    )
    @example(a=object_a(b=5, c=True), b=None)  # assuming b=None is valid
    @example(a=object_a(b=10, c=True), b=object_b(d=True, e=True))
    @example(a=object_a(b=10, c=True), b=object_b(d=True, e=False))
    def test_A_and_B(a, b):
        ...
    

    希望有所帮助:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2021-06-12
      相关资源
      最近更新 更多