3

I am writing a simple test code in Python using the Hypothesis package. It there a way to use multiple strategies for the same function parameter? As an example, use integers() and floats() to test my values parameter without writing two separate test functions?

from hypothesis import given
from hypothesis.strategies import lists, integers, floats, sampled_from
@given(
    integers() ,floats()
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

The above code doesn't work, but it represents what i would like to achieve.

NB: I have already tried the trivial solution of creating two different tests with two different strategies:

def _test_lt(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

test_lt_operator_interval_bin_int = given(integers())(_test_lt)

test_lt_operator_interval_bin_float = given(floats())(_test_lt)

However I was wondering if there was a nicer way to do this: when the nummber of strategies becomes larger, it is quite redundant as code.

Mattia Surricchio
  • 1,362
  • 2
  • 21
  • 49

1 Answers1

3

In general if you need your values to be one of several things (like ints or floats in your example) then we can combine strategies for separate things into one with | operator (which operates similar to one for sets -- a union operator and works by invoking __or__ magic method):

from hypothesis import given
from hypothesis.strategies import integers, floats
@given(
    integers() | floats()
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

or you can use strategies.one_of as @Zac Hatfield-Dodds mentioned which does pretty much the same thing:

from hypothesis import given
from hypothesis.strategies import integers, floats, one_of
@given(
    one_of(integers(), floats())
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50