python - 如何获取测试函数的 pytest 标记名称?

标签 python pytest

import pytest
class TestSomething(object):

    @pytest.mark.somethinga
    def test_something(self):

在函数 test_something 中,我想检查我给函数的标记,如果它是 somethinga 函数的行为不同于,例如 somethingb。

我想我应该使用 inspect.py(内省(introspection)),但我还没有找到如何去做。非常感谢你们!

最佳答案

这里不需要使用inspect;装饰器向函数对象添加一个属性,它不包装对象。来自source code :

holder = getattr(func, self.name, None)
if holder is None:
    holder = MarkInfo(
        self.name, self.args, self.kwargs
    )
    setattr(func, self.name, holder)
else:
    holder.add(self.args, self.kwargs)

您可以通过遍历函数属性来检测设置了哪些名称:

from _pytest.mark import MarkInfo

def function_marks(func):
    return [name for name, ob in vars(func).items() if isinstance(ob, MarkInfo)]

或者您可以只测试属性名称并假设它是一个标记实例:

if hasattr(TestSomething.test_something, 'somethinga'):
    # the somethinga mark is set

演示:

>>> import pytest
>>> from _pytest.mark import MarkInfo
>>> @pytest.mark.foo
... @pytest.mark.bar
... def demo(): pass
... 
>>> [name for name, ob in vars(demo).items() if isinstance(ob, MarkInfo)]
['foo', 'bar']
>>> demo.foo
<MarkInfo 'foo' args=() kwargs={}>
>>> demo.bar
<MarkInfo 'bar' args=() kwargs={}>

关于python - 如何获取测试函数的 pytest 标记名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31242087/

相关文章:

python - 使用 pytest 进行 Flask 基本身份验证测试

python - 在网络中有效识别给定距离内的祖先/后代

python - 如何在Python中将特定文本搜索到二维数组中

python - 如何在 Python 中嵌套元组

python - 为什么 pip(使用 --find-links)仍然从 Internet 收集一些依赖项,尽管在多阶段 docker 构建中存在一个轮子?

python - 使用单独的测试文件运行 pytest

python - 使用 request.user 的 Django 测试功能

java - 使用ant自动构建系统

python - Pytest - 使用 asyncio 进行 python 测试

python - 使用 PyTest fixture 而不通过它们