Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

target() cannot be called outside a hypothesis test #2581

Closed
aarchiba opened this issue Sep 1, 2020 · 3 comments · Fixed by #2742
Closed

target() cannot be called outside a hypothesis test #2581

aarchiba opened this issue Sep 1, 2020 · 3 comments · Fixed by #2742
Labels
enhancement it's not broken, but we want it to be better

Comments

@aarchiba
Copy link
Contributor

aarchiba commented Sep 1, 2020

I have a test assert_allclose_phase which checks whether two arrays are almost equal modulo one. When running under hypothesis, this seems like a sensible place to put target, albeit with a(n optional?) name argument in case I want to call it twice in the same test. Unfortunately if I do so then I can't use the same function in non-hypothesis tests:

E           hypothesis.errors.InvalidArgument: Calling target() outside of a test is invalid.

My current workaround is to call target only if name is provided, but this clutters simple tests that wouldn't need a name.

@Zac-HD Zac-HD added the enhancement it's not broken, but we want it to be better label Sep 4, 2020
@Zac-HD
Copy link
Member

Zac-HD commented Sep 4, 2020

context = _current_build_context.value
if context is None:
raise InvalidArgument("Calling target() outside of a test is invalid.")

I'd be happy to add an optional keyword-only argument like allow_outside_given_test=False, and if True add an early return inside this check. The idea would be to continue catching accidental use outside @given-tests, which would be a noop, but also support this kind of helper function which may be used outside them too.

@PurpleDevAu
Copy link
Contributor

I'll give this a shot, if no one has yet

@Zac-HD
Copy link
Member

Zac-HD commented Dec 9, 2020

Thanks to @PiDelport in #2675 (review), I've come around to the idea that instead of a special-case argument, we should provide a general predicate. For example:

if hypothesis.currently_in_test_context():
    # We're in an @given or stateful test, and can safely use e.g.
    target(x)
    event("hello")
    assume(foo)
    if bar: reject()

This should still be documented as "only use this in test helper functions", but I think it would be of sufficient if niche interest to justify its existence - and more orthogonal/composable than supporting similar capabilities on a function-by-function basis.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement it's not broken, but we want it to be better
Projects
None yet
3 participants