簡體   English   中英

在 Flask API 中模擬一個類

[英]Mocking a class in a Flask API

我有三個文件

助手文件

class helper:
    def __init__(self, out_file):
    self.out_file = out_file
    def foo(first, second):
        # Write data to file

燒瓶API.py

from helper import helper

@app.route('/', methods=['POST'])
def parse_request():
    content = request.get_json()

    out_file = #based on timestamp

    helper(out_file).foo(content['first'], content['second'])

test_flask.py

import unittest
from unittest.mock import patch
import flask_API

class testFlaskAPI(unittest.TestCase):
    def setUp(self):
        self.app = flask_API.app.test_client()
        self.app.test = True

    @patch('flask_API.app.helper', return_value=None)
    def test_service(self, mock_helper):
        response = self.app.post(base_url, data=json.dumps({"some":"value"}, content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

我在嘲笑助手類時遇到了麻煩。 這給了我一個錯誤說

AttributeError: <Flask 'flask_API'> does not have the attribute 'helper'

我讀到一個類/方法需要在調用它的地方而不是定義它的地方進行模擬。 我修補課程的方式有問題嗎?

最終,解決方案變得相當簡單。 首先不需要在@patch裝飾器中添加app 測試只需要@patch('flask_API.helper') 其次,我首先需要返回類的模擬,然后也模擬函數調用。 所以最后的答案竟然是

@patch('flask_API.helper')
def test_service(self, mock_helper):

    mocking_helper = mock_helper.return_value  # mocking the class
    mocking_helper.foo.return_value = None

    response = self.app.post(base_url, data=json.dumps({"some":"value"}, content_type='application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM