gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:11:41 25 4
gpt4 key购买 nike

我有一个生成sms_token的函数。它不能与数据库中现有的重复。然而,token的空间可能不够大,那么新的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()

因此,我想让 randintside_effect 按此顺序返回确定性值 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 中?

最佳答案

感谢 Klaus D. 的评论。我必须坚持使用模块

  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()
  • 使用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()

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

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com