-1

When defining strategies, is it possible to reference another strategy?

@given(maximum=strategies.floats(min_value=0),
       actual=strategies.floats(max_value=maximum))
def foo(maximum, actual):
    pass

This throws NameError: 'maximum' not defined'

Edit:

A workaround (or perhaps the workaround), is to use hypothesis's assume function. In my case, it looks like:

@given(maximum=strategies.floats(min_value=0),
       actual=strategies.floats(min_value=0))
def foo(maximum, actual):
    assume(actual <= maximum)
    pass
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
  • What does given do? – Jab May 26 '19 at 23:17
  • It's from the hypothesis library for unit testing. It generates a myriad of values. You use it so that you don't have to just choose a couple of arbitrary values for your unit test and hope that it won't break for other values. – Michael Bianconi May 27 '19 at 00:55

1 Answers1

1

Your options can be summarised as "do it by rejecting some examples" (with .filter() or assume(), or "do it by construction".

The latter is generally more efficient, though it may require more code. If you do want to try satisfying your constraints by construction, you'll need to either write a @st.composite strategy that supplies several arguments as a tuple; or go all the way to the st.data() strategy and draw interactively inside your test.

Or... in simple cases like this one, you could just put if actual > maximum: actual, maximum = maximum, actual at the top of the test function.

Zac Hatfield-Dodds
  • 2,455
  • 6
  • 19