Considering sys.argv may work, but you can run the nose with either nosetests or python -m nose , which will obviously give you a different result.
I think a more reliable way is to check the stack and see if the code is called through a package called nose .
Code example:
import inspect import unittest def is_called_by_nose(): stack = inspect.stack() return any(x[0].f_globals['__name__'].startswith('nose.') for x in stack) class TestFoo(unittest.TestCase): def test_foo(self): self.assertTrue(is_called_by_nose())
Usage example:
$ python -m nose test_caller . ---------------------------------------------------------------------- Ran 1 test in 0.009s OK $ nosetests test_caller . ---------------------------------------------------------------------- Ran 1 test in 0.009s OK $ python -m unittest test_caller F ====================================================================== FAIL: test_foo (test_caller.TestFoo) ---------------------------------------------------------------------- Traceback (most recent call last): File "test_caller.py", line 14, in test_foo self.assertTrue(is_called_by_nose()) AssertionError: False is not true ---------------------------------------------------------------------- Ran 1 test in 0.004s FAILED (failures=1)
Stefan
source share