2017-02-16 16 views
1

コールバックメソッドの選択を担当するモジュールがあります。私はメソッド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... 

今、私はpatchで遊んで始めたとき、私はまったく同じ問題を抱えていたのは、

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) 
+0

ええ、 'patch'と' from'インポートはうまくいっていません。それを 'patch 'したいのであれば、それをインポートするのが最善ではないでしょう。 – user2357112

答えて

0

それをテストしてみましょう。問題は、この声明がやや卑劣な何かをしているということです。

from numpy.random.mtrand import choice 

それはdecisionモジュールへnumpy.random.mtrandモジュールからchoice属性をコピーしています。 decisionモジュールからchoice()を呼び出すと、元のコピーではなくローカルのコピーが使用されます。

あなたのテストはオリジナルを嘲笑しており、あなたのコードはそのローカルコピーを使用しているので、モックバージョンは使用しません。

patch('numpy.random.mtrand.choice', side_effect=[self.call])patch('decision.choice', side_effect=[self.call])に変更すると正常に動作します。

+0

それはそれです、それは魅力のように動作します!私が間違えてしまって、 'side_effect'を' return_value'に変更しなければならないことも認めておく価値がありますので、patch( 'decision.choice'、return_value = [self.call]) 'となります。手伝ってくれてありがとう。 – user2817340