嘲笑回叫奇怪的行为

2024-10-02 04:28:35 发布

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

我有一个模块,负责选择回调方法。我想模拟方法choice,但即使它看起来像是模拟的,它仍然返回随机结果(有时测试通过,有时失败)。这种不确定行为的原因是什么?你知道吗

decision.py

from numpy.random.mtrand import choice

class RandomDecision:

    def __init__(self, f_bet, f_call, f_fold):
        bet, call, fold = 0.15, 0.50, 0.35
        self.propabilities = [bet, call, fold]
        self.choices = [f_bet, f_call, f_fold]

    def decide(self, player=None, information=None):
        decision = choice(self.choices, 1, p=self.propabilities)[0]
        args = ()
        if decision == self.f_bet:
            args = self._get_random_bet(information, player),
        decision(*args)

    # some more methods...

现在让我们试着测试一下

test_decisions.py

from unittest.mock import Mock, patch
from decision import RandomDecision

class TestRandomDecisions(unittest.TestCase):

def setUp(self):
    self.fold = Mock()
    self.call = Mock()
    self.bet = Mock()
    self.rand_decision = RandomDecision(f_fold=self.fold,
                                        f_call=self.call,
                                        f_bet=self.bet)

def test_call(self):
    bet = 40
    with patch('numpy.random.mtrand.choice', side_effect=[self.call]),\
        patch('decision.RandomDecision._get_random_bet',
              return_value=bet):
        self.rand_decision.decide(Mock(), None)
        self.assertTrue(self.call.called)

Tags: fromimportselfnonedefargsrandomfold
1条回答
网友
1楼 · 发布于 2024-10-02 04:28:35

当我开始玩patch时,我也遇到了同样的问题。问题是这句话有点鬼鬼祟祟。你知道吗

from numpy.random.mtrand import choice

它正在将choice属性从numpy.random.mtrand模块复制到decision模块。从decision模块调用choice()时,使用的是本地副本而不是原始副本。你知道吗

您的测试正在模拟原始版本,而您的代码正在使用其本地副本,因此它不使用模拟版本。你知道吗

如果您将patch('numpy.random.mtrand.choice', side_effect=[self.call])更改为patch('decision.choice', side_effect=[self.call]),它应该可以工作。你知道吗

相关问题 更多 >

    热门问题