【问题标题】:How to mock uuid4() in python?如何在 python 中模拟 uuid4()?
【发布时间】:2022-01-08 01:33:43
【问题描述】:

A_script.py

from uuid import uuid4

def get_unique_identifier(env, customer_id):
    return env + '-' + customer_id + '-' + str(uuid4())[0:8]

test_A_script.py

import unittest
from unittest.mock import patch
import src.A_script as a_script

class MyTestCase(unittest.TestCase):
   @patch('uuid.uuid4')
   def test_get_unique_identifier(self, mock_uuid4):
      mock_uuid4.return_value = 'abcd1234'
      expected = 'test_env-test_cust-abcd1234'
      unique_identifier = a_script.get_unique_identifier('test_env', 'test_cust')
      self.assertEqual(expected, unique_identifier)

如何让 uuid4 返回 'abcd1234'?

【问题讨论】:

    标签: python unit-testing mocking python-unittest patch


    【解决方案1】:

    你必须修补在你的 srcipt 中导入的 uuid,所以改变

    @patch('uuid.uuid4')
    

    @patch('src.A_script.uuid4')
    # or @patch('src.A_script.uuid4', return_value="abcd1234")
    # or @patch('src.A_script.uuid4', new=lambda:"abcd1234")
    

    在最后一种情况下,您根本不将模拟作为函数参数传递

    【讨论】:

      【解决方案2】:

      您需要在使用它的模块中模拟该方法。在您的情况下,您在模块A_script 中使用它,因此您必须使用'A_script.uuid4 调用patch

      【讨论】:

        猜你喜欢
        • 2018-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-23
        • 1970-01-01
        • 2022-10-17
        • 2017-11-01
        • 2016-11-12
        相关资源
        最近更新 更多