Python将随机数注入测试

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
Run Code Online (Sandbox Code Playgroud)

我需要创建一些测试:

import unittest
class Tests(unittest.TestCase):
    def test_choice(self):
        assertEquals(choice(states),something_equl)
Run Code Online (Sandbox Code Playgroud)

我该如何将自己的随机数注入测试?获得确定性结果?

ale*_*cxe 5

嘲笑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)]))
Run Code Online (Sandbox Code Playgroud)