assert_mixin.py 文件源码

python
阅读 21 收藏 0 点赞 0 评论 0

项目:data-store 作者: HumanCellAtlas 项目源码 文件源码
def assertResponse(
            self,
            method: str,
            path: str,
            expected_code: typing.Union[int, typing.Container[int]],
            json_request_body: typing.Optional[dict]=None,
            expected_error: typing.Optional[ExpectedErrorFields]=None,
            **kwargs) -> DSSAssertResponse:
        """
        Make a request given a HTTP method and a path.  The HTTP status code is checked against `expected_code`.

        If json_request_body is provided, it is serialized and set as the request body, and the content-type of the
        request is set to application/json.

        The first element of the return value is the response object.  The second element of the return value is the
        response text.  Attempt to parse the response body as JSON and return that as the third element of the return
        value.  Otherwise, the third element of the return value is None.

        If expected_error is provided, the content-type is expected to be "application/problem+json" and the response is
        tested in accordance to the documentation of `ExpectedErrorFields`.
        """
        if json_request_body is not None:
            if 'data' in kwargs:
                self.fail("both json_input and data are defined")
            kwargs['data'] = json.dumps(json_request_body)
            if 'headers' not in kwargs:
                kwargs['headers'] = {}
            kwargs['headers']['Content-Type'] = "application/json"

        response = getattr(self.app, method)(path, **kwargs)
        try:
            actual_json = response.json()
        except json.decoder.JSONDecodeError:
            actual_json = None

        try:
            if isinstance(expected_code, collections.abc.Container):
                self.assertIn(response.status_code, expected_code)
            else:
                self.assertEqual(response.status_code, expected_code)

            if expected_error is not None:
                self.assertEqual(response.headers['content-type'], "application/problem+json")
                self.assertEqual(actual_json['code'], expected_error.code)
                self.assertIn('title', actual_json)
                if expected_error.status is not None:
                    self.assertEqual(actual_json['status'], expected_error.status)
                if expected_error.expect_stacktrace is not None:
                    self.assertEqual('stacktrace' in actual_json, expected_error.expect_stacktrace)
        except AssertionError:
            if actual_json is not None:
                print("Response:")
                pprint.pprint(actual_json)
            raise

        return DSSAssertResponse(response, response.content, actual_json)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号