gpt4 book ai didi

python - 禁用 Nose 运行设置()

转载 作者:太空宇宙 更新时间:2023-11-04 06:03:00 26 4
gpt4 key购买 nike

nose包通常用于运行 doctests以及专用测试文件中的测试。似乎即使在 doctest 文件中,它也会尝试运行 setupteardown fixture。

当用于文档测试的模块碰巧需要一个名为 setup 的函数用于其他目的——它可能是一个 Sphinx extension ,例如——nosetests 将调用 setup 并失败。

为了清楚起见,这里有一个例子:

def my_tricky_function(arg):
"""Do something testable

>>> my_tricky_function(1)
2
"""
return arg + arg


def my_extension(app):
...


def setup(app):
"""Establish sphinx hooks"""
app.connect('build-finished', my_extension)

运行 nosetests 结果:

File ".../site-packages/nose/suite.py", line 291, in setUp
self.setupContext(ancestor)
File ".../site-packages/nose/suite.py", line 314, in setupContext
try_run(context, names)
File ".../site-packages/nose/util.py", line 468, in try_run
return func(obj)
File "sphinx_ext.py", line 14, in setup
app.connect('build-finished', my_extension)
AttributeError: 'module' object has no attribute 'connect'

(注意:当 setup 接受参数时,nosetest 传递 setup 是名称的范围,在本例中是模块。)

请注意以下内容不(似乎)适用:

  • 添加属性 __test__ = False (或使用 this decorator )setup 不会阻止它被调用。
  • 没有等同于--ignore-files 的命令行选项
  • 设置 my_tricky_function.setup = None 不会停止模块级设置 (h/t @alecxe)

最佳答案

虽然 joeln 自己的回答很漂亮,但它确实有点污染了模块的顶级命名空间。

我会检查 setup() 的参数以区分 nosetests 调用和普通调用。在您的情况下,如果 app 是一个模块(或没有 connect 属性),只需返回而不执行任何操作。

def setup(app):
"""Establish sphinx hooks"""
if hasattr(app, 'connect'):
app.connect('build-finished', my_extension)

我遇到了一个自定义 setuptools.setup(**kwargs) 绊倒 Nose 的问题。虽然 nosetests 在没有任何参数的情况下调用它,但 setup() 的正常使用总是会传入一些关键字参数,这使我能够区分这两种情况。

关于python - 禁用 Nose 运行设置(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23749154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com