3

How can python program know if it is being tested? For example:

def foo():
    if foo_being_tested:
        pseudorandom()
    else:
        random()

When in test, program should use pseudorandom sequence to be able to compare with C code version of the program and in regular execution random from numpy should be used.

2
  • 1
    Could you precise why you need such a behavior? I believe it is very dangerous: how can you test 'do_regular_stuff'?
    – Simpom
    Aug 21, 2014 at 11:32
  • 1
    @Simpom I have added an explanation to the question.
    – Bula
    Aug 21, 2014 at 11:38

1 Answer 1

6

You can't, not without inspecting the call stack.

Generally speaking, you should not do this at all; by altering your code when tested you are not correctly testing your code.

Instead, you'd use mocking to replace any parts your code uses (anything used by the code under test but not part of it). For your specific example, you'd mock out random(); on Python 3.3 and up you can use unittest.mock, available as mock on PyPI for other Python versions, or you can just manually swap out module_under_test.random for the duration of the test.

You could also set an environment variable in your unittests to make it explicit you are running a test, but ideally that should be avoided.

2
  • 1
    I have considered using mockup but wanted to explore this option also as it had a potential to be more elegant. Inspecting stack is definitely taking elegance out of this option :)
    – Bula
    Aug 21, 2014 at 11:43
  • 1
    Accepted, and in this special case the solution was to use the same random number generator from c and initalize it with the same seed in python and in c.
    – Bula
    Aug 24, 2014 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.