Search code examples
pythonpython-3.xpython-hypothesis

python Hypothesis test with optional parameter


On my project, I am using Hypothesis to test a function. The function under testing accept one mandatory argument called stop and two optional parameters called respectively start and step. If the parameter step is zero, the code under test should trigger an exception.

Here is my test function

@given(start=st.integers(min_value=-1000, max_value=1000),
       stop=st.integers(min_value=-1000, max_value=1000),
       step=st.integers(min_value=-1000, max_value=1000))
@settings(settings(verbosity=Verbosity.verbose))
def test_XXX_for_integer(start, stop, step):
    if step == 0:
        with raises(ValueError) as excinfo:
            _ = myrange3(start, stop, step)
        assert 'arg 3 must not be zero' in str(excinfo.value)
    else:
        output = <some code>
        expected = <some output> 
        assert output == expected

MY QUESTION: I would like to also simulate the fact that start and step is optional and therefore one or both of these parameters are set to None. How can I do that without recreating a dedicated test function for each variation of the code?


Solution

  • You can join strategies the same way you join sets. Example:

    strategy_bools_or_ints = st.booleans() | st.integers()
    

    In the test, you could join st.integers with st.none:

    st_input = st.integers(min_value=-1000, max_value=1000)
    st_input_optional = st_input | st.none()
    
    @given(start=st_input_optional, stop=st_input, step=st_input_optional)
    def test_XXX_for_integer(start, stop, step):
        assert myrange3(stop, start=start, step=step)