请给Flask测试用包装纸

2024-05-14 16:38:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为我的包做一个可用的测试,但是使用Flask.test_clientrequestsAPI有很大的不同,我发现很难使用。在

我试图让requests.adapters.HTTPAdapter包装响应,但是看起来werkzeug没有使用httplib(或者urllib)来构建它自己的Response对象。在

你知道怎么做吗?参考现有的代码将是最好的(google werkzeug+请求没有给出任何有用的结果)

非常感谢!!在


Tags: 对象代码testclientflaskresponsegoogleurllib
2条回答

您可以使用下面代码部分中定义的requests方法。 要使用它,还需要定义下面代码中显示的get_auth_headers方法。在

特点:

  • 包装瓶测试客户端。在
  • 自动设置请求头。在

    • Content-Type: Application/json传递时{}
    • Basic Authentication在传递{}时构造。在
  • json数据作为字符串转储到Flask测试客户端。在
  • (缺少)将响应包装到requests.Response对象中

代码:

class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing')
        self.client = self.app.test_client()
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

    def get_auth_headers(self, username, password):
        return {
            'Authorization':
                'Basic ' + base64.b64encode(
                    (username + ':' + password).encode('utf-8')).decode('utf-8'),
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }

    def requests(self, method, url, json={}, auth=(), **kwargs):
        """Wrapper around Flask test client to automatically set headers if JSON
        data is passed + dump JSON data as string."""
        if not hasattr(self.client, method):
            print("Method %s not supported" % method)
            return
        fun = getattr(self.client, method)

        # Set headers
        headers = {}
        if auth:
            username, password = auth
            headers = self.get_auth_headers(username, password)

        # Prepare JSON if needed
        if json:
            import json as _json
            headers.update({'Content-Type': 'application/json'})
            response = fun(url,
                           data=_json.dumps(json),
                           headers=headers,
                           **kwargs)
        else:
            response = fun(url, **kwargs)
        self.assertTrue(response.headers['Content-Type'] == 'application/json')
        return response

用法(在测试用例中):

^{pr2}$

requests的唯一区别是,与键入requests.get(...)不同的是,您必须键入self.request('get', ...)。在

如果你真的想要requests行为,你需要定义你自己的getputpostdelete的包装

注意:

最好的方法是将FlaskClient子类化,如Flask API documentation所述

据我所知,您需要的是一个嘲弄(参见What is Mocking?Mock Object)。好吧,下面列出几个选项:

相关问题 更多 >

    热门问题