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.