Yet*_*tti 1 python testing random unit-testing mocking
我写了这样的代码:
def choice(states):
    states = list(states)
    rnd = random.random()
    for state, p in states:
        rnd -= p
        if rnd <= 0:
            return state
我需要创建一些测试:
import unittest
class Tests(unittest.TestCase):
    def test_choice(self):
        assertEquals(choice(states),something_equl)
我该如何将自己的随机数注入测试?获得确定性结果?
嘲笑的random.random()功能,例如:
import random
import unittest
import mock
def choice(states):
    states = list(states)
    rnd = random.random()
    for state, p in states:
        rnd -= p
        if rnd <= 0:
            return state
class Tests(unittest.TestCase):
    @mock.patch('random.random')
    def test_first_state_fires(self, random_call):
        random_call.return_value = 1
        self.assertEquals(choice([(1, 1)]), 1)
    @mock.patch('random.random')
    def test_returns_none(self, random_call):
        random_call.return_value = 2
        self.assertIsNone(choice([(1, 1)]))
| 归档时间: | 
 | 
| 查看次数: | 2131 次 | 
| 最近记录: |