gpt4 book ai didi

python - 为pytest测试方法编写装饰器

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:32 24 4
gpt4 key购买 nike

假设结构如下:

class SetupTestParam(object):
def setup_method(self, method):
self.foo = bar()

@pytest.fixture
def some_fixture():
self.baz = 'foobar'

我使用 SetupTestParam 作为测试类的父类。

class TestSomething(SetupTestParam):
def test_a_lot(self, some_fixture):
with self.baz as magic:
with magic.fooz as more_magic:
blah = more_magic.much_more_magic() # repetative bleh
... # not repetative code here
assert spam == 'something cool'

现在,编写测试变得重复(使用语句),我想编写一个装饰器来减少代码行数。但是 pytest 和函数签名有问题。

我发现了 library这应该会有帮助,但我无法让它工作。

我在我的 SetupTestParam 类中创建了一个 classmethod

@classmethod
@decorator.decorator
def this_is_decorator(cls, f):
def wrapper(self, *args, **kw):
with self.baz as magic:
with magic.fooz as more_magic:
blah = more_magic.much_more_magic() # repetative bleh
return f(self, *args)
return wrapper

装饰test_a_lot 方法后,我收到错误TypeError: transaction_decorator() takes exactly 1 argument (2 given)

有人可以解释一下我做错了什么吗? (我假设测试方法中的 self 有问题?)

最佳答案

经过一些调整并意识到我需要将参数传递给装饰器后,我选择将其编写为一个类:

class ThisIsDecorator(object):
def __init__(self, param):
self.param = param # Parameter may vary with the function being decorated
def __call__(self, fn):
wraps(fn) # [1]
def wrapper(fn, fn_self, *args): # [2] fn_self refers to original self param from function fn (test_a_lot) [2]
with fn_self.baz as fn_self.magic: # I pass magic to fn_self to make magic accesible in function fn (test_a_lot)
with fn_self.magic.fooz as more_magic:
blah = self.param.much_more_magic() # repetative bleh
return fn(fn_self, *args)
return decorator.decorator(wrapper, fn)

[1] 我用 wraps拥有原创fn __name__ , __module____doc__ .

[2] 传递给 wrapper 的参数是self = <function test_a_lot at 0x24820c8> args = (<TestSomething object at 0x29c77d0>, None, None, None, None), kw = {}所以我拿出了args[0]作为fn_self .

原始版本(不传递参数):

 @classmethod
def this_is_decorator(cls, fn):
@wraps(fn)
def wrapper(fn, fn_self, *args):
with fn_self.baz as fn_self.magic:
with fn_self.magic.fooz as more_magic:
blah = more_magic.much_more_magic() # repetative bleh
return fn(fn_self, *args)
return decorator.decorator(wrapper,fn)

感谢 Mike Muller 指出了正确的方向。

关于python - 为pytest测试方法编写装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16794363/

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