将我的函数修补为随机randint函数

2024-10-06 10:32:48 发布

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

我有一个函数来生成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_effectrandint按这个顺序返回确定性值123456, 123456, 111222

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

我试过这个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?你知道吗


Tags: 函数fromimporttokenreturndefrandomsms
1条回答
网友
1楼 · 发布于 2024-10-06 10:32:48

感谢Klaus D.的评论。我必须坚持module。你知道吗

  1. 使用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()
  1. 使用global以获得给定条件下定义的值。还有我自己的问题。因为我想要两个相同的答案,但不是最后一个。你知道吗
    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()

相关问题 更多 >