gpt4 book ai didi

python,在同一个函数中 stub 随机性两次

转载 作者:行者123 更新时间:2023-11-28 17:26:11 27 4
gpt4 key购买 nike

我如何 stub pickCard() 函数的输出,它在 deal() 函数中被调用了两次?我想测试失败和获胜的案例。
例如,对于获胜案例,我希望在第一次调用 pickCard() 时将值 8 赋给 card1,并且第二个给定值 10card2

我试过使用@Mock.patch,但这只适用于一次调用。

我已经使用了 self.blackjack.pickCard = MagicMock(return_value=8) 但是如果我再次使用它两次它会覆盖返回值

代码如下:

import random

class Game:
def __init__(self):
self.cards = [1,2,3,4,5,6,7,8,9,10]

def deal(self):
card1 = self.pickCard()
self.removeCards(card1)
card2 = self.pickCard()
return card1 + card2 > 16

def pickCard(self):
return random.choice(self.cards)

def removeCards(self,card1):
return self.cards.remove(card1)

测试文件是:

import unittest
from mock import MagicMock
import mock
from lib.game import Game

class TestGame(unittest.TestCase):
def setUp(self):
self.game = Game()

def test_0(self):#passing
"""Only cards from 1 to 10 exist"""
self.assertListEqual(self.game.cards, [1,2,3,4,5,6,7,8,9,10])

#Here is where I am finding difficulty writing the test
def test_1(self):
"""Player dealt winning card"""
with mock.patch('lib.game.Game.pickCard') as mock_pick:
mock_pick.side_effect = (8, 10)
g = Game()
g.pickCard()
g.pickCard()
self.assertTrue(self.game.deal())

编辑

我用上面的代码运行了这个测试,我得到了这个堆栈跟踪而不是通过

Traceback (most recent call last):
tests/game_test.py line 26 in test_1
self.assertTrue(self.game.deal())
lib/game.py line 8 in deal
card1 = self.pickCard()
/usr/local/lib/python2.7/site-packages/mock/mock.py line 1062 in __call__
return _mock_self._mock_call(*args, **kwargs)
/usr/local/lib/python2.7/site-packages/mock/mock.py line 1121 in _mock_call
result = next(effect)
/usr/local/lib/python2.7/site-packages/mock/mock.py line 109 in next
return _next(obj)

我是否需要将两个 g.pickCard() 放在测试的其他地方?或者我是否需要以某种方式在 self.game.deal() 方法中访问它?

最佳答案

mock.patch 是要走的路,但是您应该指定 side_effect=(8, 10) 而不是 return_value >

with mock.patch('lib.game.Game.pickCard') as mock_pick:
mock_pick.side_effect = (8, 10)
g = Game()
print(g.pickCard())
print(g.pickCard())

# 8
# 10

编辑#1

Pick card 只是为了演示不同的卡片被挑选出来。在您的代码中,您选择了两张牌,然后调用 game.deal,它选择了另外两张未被模拟的牌,这引发了 StopIteration。此外,由于您的游戏对象已经存在(在 setUp 中创建),您应该直接修补该对象,而不是创建新的游戏对象,因此您的 test_1 应该是:

def test_1(self):
"""Player dealt winning card"""
with mock.patch.object(self.game, 'pickCard') as mock_pick:
mock_pick.side_effect = (8, 10)
self.assertTrue(self.game.deal())

您使用 MagicMock 路径对象的属性 pickCard 并将其副作用分别设置为 8 和 10。

关于python,在同一个函数中 stub 随机性两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38853524/

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