[英]Mocking a class in a Flask API
I have three files我有三个文件
helper.py助手文件
class helper:
def __init__(self, out_file):
self.out_file = out_file
def foo(first, second):
# Write data to file
flask_API.py烧瓶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 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)
I am having trouble mocking the helper class.我在嘲笑助手类时遇到了麻烦。 This gives me an error saying
这给了我一个错误说
AttributeError: <Flask 'flask_API'> does not have the attribute 'helper'
I read that a class/method needs to be mocked where it is being called instead of where it's defined.我读到一个类/方法需要在调用它的地方而不是定义它的地方进行模拟。 Is there something wrong with the way I am patching the class?
我修补课程的方式有问题吗?
In the end the solution turned out to be fairly simple.最终,解决方案变得相当简单。 First there was no need to add
app
in the @patch
decorator.首先不需要在
@patch
装饰器中添加app
。 The test just needed @patch('flask_API.helper')
.测试只需要
@patch('flask_API.helper')
。 Second, I first needed to return the mock of the class and then mock the function call as well.其次,我首先需要返回类的模拟,然后也模拟函数调用。 So the final answer turned out to be
所以最后的答案竟然是
@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.