如何对 api 调用函数进行猴子修补

问题描述 投票:0回答:1

我正在使用 pytest 为此函数编写测试用例

def function_to_testcase(conn, event, customer):
   if customer["userStatus"] is None:
       raise IncompleteSignup("Customer marked as Incomplete Signup")
   logger.info("Forgot password flow started")
   send_update_customer_details_message(
       db_id=customer["cid"],
       zu_id=customer["AccountId"],
       email=customer["UserName"],
       encrypted_password=customer["Password"],
       skip_targets=True,
   )

我需要给外部API调用函数打猴子补丁

send_update_customer_details_message
,我写的测试用例附在这里。

import pytest
import unittest
from customers_migration.flows.legacy import (
    run_legacy_forgot_password_flow,
)
class TestLegacy(unittest.TestCase):
    monkeypatch = pytest.MonkeyPatch()
    MSG = "Forgot password flow for Legacy started"
    event_trigger_other = {
        "request": {"password": "test_pwd"},
        "triggerSource": "Other",
    }
    customer_status = {
        "userStatus": 2,
        "Password": "Test1ngpa$",
        "cid": 1,
        "AccountId": "12312",
        "UserName": "[email protected]",
    }

    def test_run_forgot_password_flow_logger(self):
        with self.assertLogs() as captured:
            self.monkeypatch.setattr(
                run_legacy_forgot_password_flow,
                "send_update_customer_details_message",
                None,
            )
            run_ipv_legacy_forgot_password_flow(
                "", self.event_trigger_other, self.customer_status
            )
        self.assertEqual(len(captured.records), 1)
        self.assertEqual(
            self.MSG,
            captured.records[0].getMessage(),
        )

但我收到这样的错误

 AttributeError: <function run_legacy_forgot_password_flow at 0x7fc75f780280> has no attribute 'send_update_customer_details_message'
我在这里做错了什么?

python python-3.x unit-testing testing pytest
1个回答
0
投票

您需要在here中以相同的方式对导入进行猴子修补。

def test_run_forgot_password_flow_logger(self):
    with self.assertLogs() as captured:
        self.monkeypatch.setattr(
            'customers_migration.flows.legacy.send_update_customer_details_message',
            None,
        )
        run_ipv_legacy_forgot_password_flow(
            "", self.event_trigger_other, self.customer_status
        )
    self.assertEqual(len(captured.records), 1)
    self.assertEqual(
        self.MSG,
        captured.records[0].getMessage(),
    )
© www.soinside.com 2019 - 2024. All rights reserved.