Skip to main content
 首页 » 编程设计

python之在脚本中使用 Python 中的 nose 时覆盖现有配置

2025年05月04日18yxwkf

我正在尝试设置 Python 来执行 nose,但仅在现有应用程序上我正在本地开发。我不希望 nose 在当前安装的所有库中跑来跑去。但是,我确实希望 nose 发现当前工作目录和子目录中的所有测试。

首先,我要做的就是确保使用我传递的参数(由下面的@need-batchelder 解决)。但是,目前我传递的参数似乎被忽略了,并且正在对测试进行全局发现(即也从 python 文件夹中获取测试。

来自 the docs :

     -V, --version 
     Output nose version and exit 

从命令行运行 nosetests -V 会产生预期的版本输出:

     nosetests -V 
     nosetests-script.py version 1.2.1 

然而,下面的测试脚本开始运行它能找到的每个测试,包括那些安装在 python 路径中的库,而不是当前工作目录的一部分,即使它位于在应用程序的根目录中:

import nose, os 
 
def main(): 
    print os.getcwd() 
    x=raw_input() #This is just so I can see the output of the cwd before it launches into testing everything it can find. 
    result = nose.run(argv=['-V'])  
 
if __name__ == '__main__': 
    main() 

这是我尝试过的:

  • 使用 nose.main()、x=nose.core.run()、x=nose.run()。
  • 将参数直接传递给 nose.run() 并使用列表。
  • 使用 nose.cfg 文件。

谢谢

编辑:尝试@ned-batchelder 的建议允许我使用给定的参数运行 nose,但不允许在应用程序文件夹中发现测试。因此,如果我这样做,我可以传递参数,但无法测试我的应用程序。

请您参考如下方法:

我相信 nose 期望 argv 是完整的 argv,这意味着第一个元素应该是程序的名称:

nose.run(argv=['me.py', '-V'])