我有一个生成sms_token的函数。它不能与数据库中的现有副本重复。但是,令牌的空间可能不够大,因此可能发生较新的令牌的冲突。

Python 3.7.0

from random import randint

from multy_herr.user_profiles.models import UserProfile


def rand_six():
    """
    Must find the `sms_token` which no `UserProfile`
    :return:
    """
    tmp = ""
    for i in range(6):
        tmp += str(randint(0, 9))
    if 0 == UserProfile.objects.filter(sms_token=tmp).count():
        return tmp
    else:
        return rand_six()


因此,我想将side_effect设为randint,以便按此顺序123456, 123456, 111222向我返回确定性值

具有给定的值。我将能够在我的else中测试rand_six逻辑

我已经尝试过此answer,但是不起作用。 rand_six()仍返回我原始功能,而不是我创建的假功能。

from unittest.mock import patch
from multy_herr.users.utils import rand_six

    @patch('random.randint')
    def test_rand_six(self, some_func):
        """
        Suppose it generates the duplicated `sms_token`
        :return:
        """
        some_func.return_value = '123456'
        assert '123456' == rand_six()


问题:

它不会修补random.randint的行为

题:
如何将伪造的生成列表放入randint

最佳答案

感谢Klaus D.的评论。我必须坚持module


使用import randomrandom.randint(0, 9)


import random

from multy_herr.user_profiles.models import UserProfile


def rand_six():
    """
    Must find the `sms_token` which no `UserProfile`
    :return:
    """
    tmp = ""
    for i in range(6):
        tmp += str(random.randint(0, 9))
    if 0 == UserProfile.objects.filter(sms_token=tmp).count():
        return tmp
    else:
        return rand_six()



使用global以获得给定条件下的我定义的值。我的问题有点作弊。由于我想要2个答案相同,但不是最后一个。


    def _rand111(self, a, b):
        global idx
        if idx in range(12):
            idx += 1
            return 1
        else:
            return 2

    def test_mock_randint(self):
        """
        Test mock the behaviour of `random.randint`
        :return:
        """

        with mock.patch('random.randint', self._rand111):
            assert '111111' == rand_six()
            assert '111111' == rand_six()
            assert '222222' == rand_six()

关于python - 将我的函数修补为随机randint函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55209306/

10-10 10:56