【问题标题】:Disable nose running setup()禁用鼻子运行设置()
【发布时间】:2014-05-20 00:21:32
【问题描述】:

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

当用于 doctesting 的模块碰巧需要一个名为 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)

运行 nosestests 会导致:

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)

【问题讨论】:

  • 只是在黑暗中拍摄 - 设置 my_tricky_function.setup = None 有帮助吗?

标签: python python-sphinx nose doctest


【解决方案1】:

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

我会检查setup() 的参数,以区分nosetests 调用和正常调用。在您的情况下,如果 app 是一个模块(或没有 connect 属性),只需返回并且什么都不做。

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

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

【讨论】:

    【解决方案2】:

    我找到了以下有点 hacky 的解决方案:添加另一个函数 setup_module,它将隐藏 setup 的鼻子。

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

    【讨论】:

      猜你喜欢
      • 2019-09-10
      • 2015-08-21
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 2014-10-03
      相关资源
      最近更新 更多