Python flask请求处理程序中使用的模拟函数

Python flask请求处理程序中使用的模拟函数,python,unit-testing,flask,mocking,python-unittest,Python,Unit Testing,Flask,Mocking,Python Unittest,我试图模拟在测试文件的flask请求处理程序中调用的upload\u image函数 但是,在我当前的实现中,原始函数仍然在请求处理程序中调用,并且不会返回模拟的返回值。如何从test.py文件中模拟此函数 守则: tests/test.py import os from unittest.mock import patch def test_image_upload(test_client): with patch("app.utils.upload_image", 'test_pa

我试图模拟在测试文件的flask请求处理程序中调用的
upload\u image
函数

但是,在我当前的实现中,原始函数仍然在请求处理程序中调用,并且不会返回模拟的返回值。如何从
test.py
文件中模拟此函数

守则:

tests/test.py

import os
from unittest.mock import patch

def test_image_upload(test_client):
    with patch("app.utils.upload_image", 'test_path'):
        test_file_path = os.path.dirname(os.path.abspath(__file__)) + '/test_file.png'
        f = open(test_file_path, 'rb')

        data = {
            'num-files': 1,
            'test_file.png': f
        }

        response = test_client.post('/file/upload', data=data)
        assert response.status_code == 200
from utils import upload_image
@app.route('/file/upload', methods=['POST'])
def upload_file():
    # should be returning 'test_path', but is actually uploading the file and returning a URL
    file_url = upload_image(image)
    return jsonify({'file_url': file_url})
app/files/handler.py

import os
from unittest.mock import patch

def test_image_upload(test_client):
    with patch("app.utils.upload_image", 'test_path'):
        test_file_path = os.path.dirname(os.path.abspath(__file__)) + '/test_file.png'
        f = open(test_file_path, 'rb')

        data = {
            'num-files': 1,
            'test_file.png': f
        }

        response = test_client.post('/file/upload', data=data)
        assert response.status_code == 200
from utils import upload_image
@app.route('/file/upload', methods=['POST'])
def upload_file():
    # should be returning 'test_path', but is actually uploading the file and returning a URL
    file_url = upload_image(image)
    return jsonify({'file_url': file_url})

我认为您应该修补
app.files.handler.upload\u image
,因为您正在将函数导入当前名称空间。如果你导入了utils,你会给app.utils.upload\u image添加补丁;utils.upload_image()是的,就是这样。谢谢