【问题标题】:Python mock patch syntax trouble with different arguments number具有不同参数编号的 Python 模拟补丁语法问题
【发布时间】:2017-09-04 10:27:39
【问题描述】:
## 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 怎么办:请,无论我的 create_stripe_charge 方法有多少参数,我只是想模拟它引发异常。

执行此操作的正确语法是什么?谢谢。

【问题讨论】:

    标签: python django unit-testing mocking


    【解决方案1】:

    要在调用模拟时引发异常,请将 side_effect 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),但使用新函数并不是一个好主意。

    使用适当的模拟来替换函数还可以让您断言模拟被正确调用,并且您可以断言传入的参数。当您使用自己的函数时,您不能这样做。

    【讨论】:

    • 很好的解释......被困在文档中......谢谢。
    猜你喜欢
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2015-12-17
    • 2015-08-09
    • 1970-01-01
    相关资源
    最近更新 更多