【问题标题】:Python: Conditional variables based on whether nosetest is runningPython:基于nosetest是否正在运行的条件变量
【发布时间】:2011-09-07 21:57:44
【问题描述】:

我正在运行具有设置功能的鼻子测试,该功能需要加载与生产数据库不同的数据库。我使用的 ORM 是 peewee,它要求在定义中设置模型的数据库。

所以我需要设置一个条件变量,但我不知道使用什么条件来检查nosetest 是否正在运行文件。

我在 Stack Overflow 上读到,您可以在 sys.modules 中检查 nose,但我想知道是否有更准确的方法来检查鼻子是否在运行。

【问题讨论】:

    标签: python nose peewee


    【解决方案1】:

    也许检查sys.argv[0] 以查看正在运行的命令?

    【讨论】:

    • import sys; testing = sys.argv[0].endswith('nosetests')
    【解决方案2】:

    检查 sys.argv 可能有效,但您可以使用 nosetestspython -m nose 执行鼻子,这显然会给您不同的结果。

    我认为更稳健的方法是检查堆栈并查看代码是否通过名为 nose 的包调用。

    示例代码:

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

    示例用法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2018-11-14
      • 2017-11-14
      相关资源
      最近更新 更多