I don't know much about the unittest
module, but if you're running the file directly for the unit test, you can enclose the test code with the following if:
if __name__ == "__main__":
Any code that lies within that if statement will only be executed if your particular module is being directly invoked, and not imported into something else. According to the docs, that's how you should be calling unittest.main()
in the first place.
https://docs.python.org/2/library/unittest.html
This assumes you're not running from the command line.
EDIT: you could look at the function stack to try and find the unittest.main()
function.
import inspect
def in_unit_test():
current_stack = inspect.stack()
for stack_frame in current_stack:
for program_line in stack_frame[4]: # This element of the stack frame contains
if "unittest" in program_line: # some contextual program lines
return True
return False
https://docs.python.org/2/library/inspect.html
It's kind of a hacky solution, but the inspect
module has a lot of useful functions for introspection.