Python模拟补丁语法问题不同参数numb

2024-10-01 00:15:50 发布

您现在位置:Python中文网/ 问答频道 /正文

## tests file
@mock.patch('profiles.models.create_stripe_charge', StripeMocks._mock_raises_stripe_error)
def my_test(self):
    #  ... stuff


## logic file
def create_stripe_charge(customer, amount_in_cents, capture=True):
    # ... stuff

## mocks file
class StripeMocks:
    def _mock_raises_stripe_error(self):
        raise stripe.error.StripeError

运行测试时,我遇到了_mock_raises_stripe_error() takes 1 positional argument but 3 were given'错误。在

我知道我试图用1-arg方法模拟一个3-args方法,但是如果我只想告诉Python:please,不管我的create_stripe_charge方法有多少个参数,我只想模拟它会引发一个异常。在

正确的语法是什么?谢谢。在


Tags: 方法selfdefcreatetestserrorprofilesmock
1条回答
网友
1楼 · 发布于 2024-10-01 00:15:50

要在调用模拟时引发异常,请将^{} attribute设置为异常:

@mock.patch('profiles.models.create_stripe_charge',
            side_effect=stripe.error.StripeError)
def my_test(self, mock_create_stripe_charge):
    # ...

您将create_stripe_charge()完全替换为只接受一个参数(self)的函数。您可以使用*args来捕获其他参数(由于您使用了一个未绑定的方法,因此根本不需要使用self),但是使用新函数并不是一个好主意。在

使用适当的mock替换函数还可以断言mock被正确调用,并且可以断言传入了什么参数。当您使用自己的函数时,您不能这样做。在

相关问题 更多 >