【问题标题】:How to Mock a flask-restful class with kwargs如何用 kwargs 模拟烧瓶休息类
【发布时间】:2023-04-06 12:40:02
【问题描述】:

来自Intermediate-Usage Flask-RESTful 0.3.7 documentation 在底部的 Passing Constructor Parameters Into Resources 部分中,您将如何编写测试来模拟 kwargs?旁注:我对其进行了调整,以便直接传递 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?

【问题讨论】:

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


    【解决方案1】:

    您可以使用来自unittest.mockMock 对象来模拟 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")
    

    【讨论】:

      猜你喜欢
      • 2017-11-09
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 2021-11-29
      • 2022-01-01
      • 1970-01-01
      相关资源
      最近更新 更多