我具有生成 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()
因此,我想使randint
的side_effect
通过此顺序返回确定性值123456, 123456, 111222
给定值。我将能够在我的rand_six
else
逻辑我尝试了这个答案,但行不通。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 random
和random.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()