Python: Conditional variables based on whether nosetest is running

心已入冬 提交于 2020-01-23 05:23:13

问题


I'm running nosetests which have a setup function that needs to load a different database than the production database. The ORM I'm using is peewee which requires that the database for a model is set in the definition.

So I need to set a conditional variable but I don't know what condition to use in order to check if nosetest is running the file.

I read on Stack Overflow that you can check for nose in sys.modules but I was wondering if there is a more exact way to check if nose is running.


回答1:


Perhaps examining sys.argv[0] to see what command is running?




回答2:


Examining sys.argv might work, but you can execute nose either with nosetests or python -m nose, which obviously will give you a different result.

I think the more robust way is to inspect the stack and see if the code is being called through a package called nose.

Example code:

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())

Example usage:

$ 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)


来源:https://stackoverflow.com/questions/7341005/python-conditional-variables-based-on-whether-nosetest-is-running

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!