烧瓶请求处理程序中使用的模拟功能

时间:2020-01-17 22:43:49

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

我正在尝试从测试文件中模拟在烧瓶请求处理程序中调用的upload_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

app/files/handler.py

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})

0 个答案:

没有答案