[英]Python: Mock Patch module that's used in an array
這是我的方法:
def _eda_workflow(self, workflow_id, account_id):
uuids = [str(uuid.uuid4()) for x in range(2)]
return {
'id': workflow_id,
'root': uuids[0],
'accountId': account_id,
'steps': [
{
'this': uuids[0],
'next': [uuids[1]],
'type': 'on-contact-signed-up',
'displayName': 'Sign Up',
'constraints': {},
},
{
'this': uuids[1],
'prev': uuids[0],
'next': [],
'type': 'on-time-elapsed',
'displayName': 'Send the email after delay or not!',
'delay': 'PT0M',
'sideEffect': {
'task': 'sendEmail',
'constraints': {},
'mailing_data': {},
'email': {}
}
}
]
}
我遇到的問題是寫這篇文章時
def generate_uuids():
return ["10e6e848-dc77-4057-890e-5acd4ed9aeb3", "d8d501a7-f7e7-4423-921c-e0f39b7e1301"]
@mock.patch('path.to.uuid')
def test_translte_workflow(self, uuid_mock):
uuid_mock.uuid4.side_effect = generate_uuids
return方法返回值list
,而不是我期望的值。 不確定如何正確編寫此測試
副作用只是用於指定每次調用模擬時都會發生的其他事情。 我認為這更是您想要的:
def fake_uuid4():
yield "10e6e848-dc77-4057-890e-5acd4ed9aeb3"
yield "d8d501a7-f7e7-4423-921c-e0f39b7e1301"
@mock.patch('path.to.uuid.uuid4', fake_uuid4().next)
def test_translte_workflow(self):
...
您的generate_uuids
函數將返回UUID 列表 ,這就是您得到的。
如果要創建一次從正好兩個 UUID的池中一次返回一個UUID的函數,請從兩個 UUID的列表中創建一個迭代器 ,然后從該函數返回iterator.next()
。 如果您還想對這些UUID進行斷言,請將其與迭代器分開存儲:
import mock
import unittest
import uuid
TEST_UUIDS = ["10e6e848-dc77-4057-890e-5acd4ed9aeb3",
"d8d501a7-f7e7-4423-921c-e0f39b7e1301"]
uuid_pool = iter(TEST_UUIDS)
def generate_uuid():
return uuid_pool.next()
def func():
uuid_1 = uuid.uuid4()
uuid_2 = uuid.uuid4()
return [uuid_1, uuid_2]
class TestUUIDs(unittest.TestCase):
@mock.patch('uuid.uuid4', generate_uuid)
def test_uuid_mock(self):
actual = func()
expected = TEST_UUIDS
self.assertEquals(expected, actual)
unittest.main()
一旦耗盡了該迭代器(在獲取兩個元素之后),它將引發StopIteration
。
如果要創建一個函數,該函數總是從無窮無盡的UUID流中僅返回一個UUID,則可以使用itertools.cycle
:
from itertools import cycle
uuid_pool = cycle(["10e6e848-dc77-4057-890e-5acd4ed9aeb3",
"d8d501a7-f7e7-4423-921c-e0f39b7e1301"])
我需要解決類似的問題,並且在進行了一些實驗之后,更喜歡使用帶有@patch
和side_effect
的迭代side_effect
。 就我而言,不是填充數組,而是填充了比測試中的函數更深的稱為函數層的函數的返回值。
TEST_UUIDS = ["10e6e848-dc77-4057-890e-5acd4ed9aeb3",
"d8d501a7-f7e7-4423-921c-e0f39b7e1301"]
TEST_UUID_POOL = iter(TEST_UUIDS)
@patch('path.to.function1', side_effect=TEST_UUID_POOL)
def test_translate_workflow(self, uuid_mock):
# function 1 is called twice in function2
function2()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.