如何用 kwargs 模拟烧瓶-restful class
How to Mock a flask-restful class with kwargs
来自Intermediate-Usage Flask-RESTful 0.3.7 documentation
在底部的 Passing Constructor Parameters Into Resources 部分中,您将如何编写测试以模拟 kwargs?旁注:我对其进行了调整,以便直接传递智能引擎 class 而不是实例化为变量然后传递。
from flask_restful import Resource
class TodoNext(Resource):
def __init__(self, **kwargs):
# smart_engine is a black box dependency
self.smart_engine = kwargs['smart_engine']
def get(self):
return self.smart_engine.next_todo()
您可以像这样将所需的依赖项注入 TodoNext:
api.add_resource(TodoNext, '/next',
resource_class_kwargs={ 'smart_engine': SmartEngine() })
有问题的测试class:
import unittest
class TestTodoNext(unittest.TestCase):
todo_next_instance = TodoNext() # How would you mock smart_engine in this case?
您可以使用 unittest.mock
中的 Mock
对象来模拟 smart_engine。
import unittest
from unittest.mock import Mock
class TestTodoNext(unittest.TestCase):
smart_engine = Mock()
smart_engine.next_todo.return_value = "YOUR DESIRED RETURN VALUE"
todo_next_instance = TodoNext(smart_engine=smart_engine)
self.assertEqual(todo_next_instace.get(), "YOUR DESIRED RETURN VALUE")
来自Intermediate-Usage Flask-RESTful 0.3.7 documentation 在底部的 Passing Constructor Parameters Into Resources 部分中,您将如何编写测试以模拟 kwargs?旁注:我对其进行了调整,以便直接传递智能引擎 class 而不是实例化为变量然后传递。
from flask_restful import Resource
class TodoNext(Resource):
def __init__(self, **kwargs):
# smart_engine is a black box dependency
self.smart_engine = kwargs['smart_engine']
def get(self):
return self.smart_engine.next_todo()
您可以像这样将所需的依赖项注入 TodoNext:
api.add_resource(TodoNext, '/next',
resource_class_kwargs={ 'smart_engine': SmartEngine() })
有问题的测试class:
import unittest
class TestTodoNext(unittest.TestCase):
todo_next_instance = TodoNext() # How would you mock smart_engine in this case?
您可以使用 unittest.mock
中的 Mock
对象来模拟 smart_engine。
import unittest
from unittest.mock import Mock
class TestTodoNext(unittest.TestCase):
smart_engine = Mock()
smart_engine.next_todo.return_value = "YOUR DESIRED RETURN VALUE"
todo_next_instance = TodoNext(smart_engine=smart_engine)
self.assertEqual(todo_next_instace.get(), "YOUR DESIRED RETURN VALUE")