如何用kwargs模拟烧瓶宁静的课程

时间:2019-09-25 18:28:12

标签: python-3.x flask mocking tdd flask-restful

来自Intermediate-Usage Flask-RESTful 0.3.7 documentation 在底部的将构造函数参数传递到资源部分中,您将如何编写测试以模拟kwarg?旁注:我对其进行了调整,以便直接传递Smart Engine类,而不是将其实例化为变量然后传递。

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

正在测试的课程:

import unittest

class TestTodoNext(unittest.TestCase):
    todo_next_instance = TodoNext() # How would you mock smart_engine in this case?

1 个答案:

答案 0 :(得分:1)

您可以使用Mock中的unittest.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")