gpt4 book ai didi

unit-testing - Python 中的模拟条纹方法进行测试

转载 作者:行者123 更新时间:2023-12-04 13:16:04 27 4
gpt4 key购买 nike

所以我试图模拟所有 stripe web hooks在方法中,这样我就可以写 Unit test为了它。我正在使用 mock library用于模拟 strip 方法。这是我试图模拟的方法:

class AddCardView(APIView):
"""
* Add card for the customer
"""

permission_classes = (
CustomerPermission,
)

def post(self, request, format=None):
name = request.DATA.get('name', None)
cvc = request.DATA.get('cvc', None)
number = request.DATA.get('number', None)
expiry = request.DATA.get('expiry', None)

expiry_month, expiry_year = expiry.split("/")

customer_obj = request.user.contact.business.customer

customer = stripe.Customer.retrieve(customer_obj.stripe_id)

try:
card = customer.sources.create(
source={
"object": "card",
"number": number,
"exp_month": expiry_month,
"exp_year": expiry_year,
"cvc": cvc,
"name": name
}
)
# making it the default card
customer.default_source = card.id
customer.save()
except CardError as ce:
logger.error("Got CardError for customer_id={0}, CardError={1}".format(customer_obj.pk, ce.json_body))
return Response({"success": False, "error": "Failed to add card"})
else:
customer_obj.card_last_4 = card.get('last4')
customer_obj.card_kind = card.get('type', '')
customer_obj.card_fingerprint = card.get('fingerprint')
customer_obj.save()

return Response({"success": True})

这是 unit testing的方法:
@mock.patch('stripe.Customer.retrieve')
@mock.patch('stripe.Customer.create')
def test_add_card(self,create_mock,retrieve_mock):
response = {
'default_card': None,
'cards': {
"count": 0,
"data": []
}
}

# save_mock.return_value = response
create_mock.return_value = response
retrieve_mock.return_value = response

self.api_client.client.login(username = self.username, password = self.password)
res = self.api_client.post('/biz/api/auth/card/add')

print res

现在 stripe.Customer.retrieve正在被正确 mock 。但我无法模拟 customer.sources.create .我真的坚持这一点。

最佳答案

这是正确的做法:

@mock.patch('stripe.Customer.retrieve')
def test_add_card_failure(self, retrieve_mock):
data = {
'name': "shubham",
'cvc': 123,
'number': "4242424242424242",
'expiry': "12/23",
}
e = CardError("Card Error", "", "")
retrieve_mock.return_value.sources.create.return_value = e

self.api_client.client.login(username=self.username, password=self.password)

res = self.api_client.post('/biz/api/auth/card/add', data=data)

self.assertEqual(self.deserialize(res)['success'], False)

关于unit-testing - Python 中的模拟条纹方法进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31284622/

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