2024-06-26 18:10:03 发布
网友
import pytest class TestSomething(object): @pytest.mark.somethinga def test_something(self):
在函数test_something中,我想检查一下我给这个函数打了什么标记,如果是某个东西,那么这个函数的行为就不同于,比如somethingb。在
我想我应该用检验.py(自省)但我还没找到怎么做。多谢各位!在
这里不需要使用inspect;decorator向函数对象添加一个属性,它不包装对象。从source code:
inspect
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)
通过迭代函数属性,可以检测设置了哪些名称:
也可以只测试属性名并假设它是一个标记实例:
演示:
>>> 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={}>
测试功能标记:
import pytest @pytest.mark.major_test def test_foo(): print("Marker:") print(test_foo.pytestmark[0].name) assert(True)
Pytest输入标记:
所以基本上,当你调用pytest.mark.<attribute>时,它将<attribute>设置为你修饰/标记的函数上的_pytest.mark.Markinfo()的实例。在
pytest.mark.<attribute>
<attribute>
_pytest.mark.Markinfo()
示例:
代码:
import pytest from _pytest.mark import MarkInfo @pytest.mark.foo def test_foo(): assert hasattr(test_foo, "foo") assert isinstance(test_foo.foo, MarkInfo) def test_bar(): assert not hasattr(test_bar, "foo")
“mark”的“name”也作为属性MarkInfo()存储在MarkInfo()中:
MarkInfo()
这里不需要使用
inspect
;decorator向函数对象添加一个属性,它不包装对象。从source code:通过迭代函数属性,可以检测设置了哪些名称:
^{pr2}$也可以只测试属性名并假设它是一个标记实例:
^{3}$演示:
测试功能标记:
Pytest输入标记:
^{pr2}$所以基本上,当你调用
pytest.mark.<attribute>
时,它将<attribute>
设置为你修饰/标记的函数上的_pytest.mark.Markinfo()
的实例。在示例:
代码:
^{pr2}$
“mark”的“name”也作为属性
^{3}$MarkInfo()
存储在MarkInfo()
中:相关问题 更多 >
编程相关推荐