Python: nosetest-based condition variables

I run nosetests that have a tuning function that should load a different database than the production database. The ORM I use is peewee, which requires the database for the model to be defined in the definition.

So I need to set a conditional variable, but I don’t know what condition to use to check if the nosetest file is working.

I read Stack Overflow, which you can check for nose in sys.modules , but I was wondering if there is a more accurate way to check if the nose works.

+7
source share
2 answers

Perhaps consider sys.argv[0] to see which command is running?

+9
source

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) 
0
source

All Articles