首页 > 解决方案 > 在 python 中模拟另一个模块中间函数的问题

问题描述

我的项目文件夹结构:

myproject

   utilities--encrypt_decrypt_util -- encrypt()
   src --sample.py
   tests --sample_test2.py

src/sample.py:

from utilities.encrypt_decrypt_util import encrypt

def m1():
    print('from m1 method')
    encr_pwd=encrypt('SGu2s2RFT')
    print(encr_pwd)

测试/sample_test2.py:

from src.sample import m1
from mock import patch

def encrypt(password):
    print('its mock...')
    return 'encryptedpassword'

@patch('utilities.encrypt_decrypt_util.encrypt')
def test_mytst2(mock_m2):
    print('From test_mytst2 method')
    mock_m2.return_value= encrypt('password')
    print(m1())

实用程序/encrypt_decrypt_util.py

def encrypt(plain_text_pwd: str) -> bytes:
    #some code here
    return encrypted_password

当我执行pytest test_mytst2时,该encrypt方法应被模拟,但utils会调用原始方法 from 。您能否帮助了解问题所在。

标签: pythonmockingpytest

解决方案


推荐阅读