Skip to main content
 首页 » 编程设计

python之Pytest 不收集静态方法

2024年10月01日8bhlsheji

我有一个测试类,其中包含一些静态方法和普通方法。问题是 pytest 没有收集静态方法。我在文档中找不到与此相关的任何内容。我怎样才能让它也收集静态方法?

class TestFoo(object): 
    @staticmethod 
    def test_bar(): 
        assert 1 == 1 
 
    def test_bar2(self): 
        assert 1 == 1 

在上面的类中,只有test_bar2被收集,test_bar()没有被收集。

我正在运行 Python 2.7.13、pytest-3.1.2、py-1.4.34、pluggy-0.4.0

插件是xdist-1.17.1、leaks-0.2.2、cov-2.5.1

请您参考如下方法:

收集测试函数时,pytest ensure each functions are callable .

但是 staticmethod 是不可调用的,来自 https://docs.python.org/3/reference/datamodel.html :

Static method objects are not themselves callable, although the objects they wrap usually are.

见:

>>> class TestFoo(object): 
...     @staticmethod 
...     def test_bar(): 
...         assert 1 == 1 
...  
>>> hasattr(TestFoo.__dict__['test_bar'], '__call__') 
False 

为此,应该修改 pytest 本身以接受静态方法,我不知道这是否是他们想要的,如果你认为你真的需要它,你可以在 github 上的问题跟踪器上打开一个问题。

为什么您认为静态方法是一种解决方案?具体针对哪个问题?