谷歌云端点测试中的内容长度错误

pea*_*eak 6 python unit-testing google-cloud-endpoints

每当我想在我的代码中测试404 HTTP错误路径时,我都会收到以下错误:

AssertionError:Content-Length与实际的app_iter长度不同(512!= 60)

我创建了一个触发此行为的最小示例:

import unittest
import endpoints
from protorpc import remote
from protorpc.message_types import VoidMessage
import webtest

@endpoints.api(name='test', version='v1')
class HelloWorld(remote.Service):
    @endpoints.method(VoidMessage, VoidMessage,
                      path='test_path', http_method='POST',
                      name='test_name')
    def test(self, request):
        raise endpoints.NotFoundException("Not found")

class AppTest(unittest.TestCase):
    def setUp(self):
        app = endpoints.api_server([HelloWorld])
        self.testapp = webtest.TestApp(app)

    # Test the handler.
    def testHelloWorldHandler(self):
        response = self.testapp.post('/_ah/spi/HelloWorld.test', extra_environ={
            'SERVER_SOFTWARE': 'Development/X', 'CONTENT_TYPE': 'application/json'})
Run Code Online (Sandbox Code Playgroud)

那么我做错了什么?

Rob*_*odd 9

这是App Engine的已知错误.

引发异常时,端点不会设置正确的Content-Length标头:

https://code.google.com/p/googleappengine/issues/detail?id=10544

要解决此问题,diff上面的链接中包含一个文件,或按照我的说明自行暂时修补它.

1.打开 apiserving.py

在Mac上,您可以在以下位置找到该文件:

/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/endpoints-1.0/endpoints
Run Code Online (Sandbox Code Playgroud)

2.找到以下部分(第467行):

它应该如下所示:

headers_dict = dict([(k.lower(), v) for k, v in headers])
if self.__is_json_error(status, headers_dict):
  status, body = self.protorpc_to_endpoints_error(status, body)
Run Code Online (Sandbox Code Playgroud)

3.将其更改为:

headers_dict = dict([(k.lower(), v) for k, v in headers])
if self.__is_json_error(status, headers_dict):
  pre_body_length = len(body)
  status, body = self.protorpc_to_endpoints_error(status, body)
  post_body_length = len(body)
  if pre_body_length != post_body_length:
    for index, header in enumerate(headers):
      header_key, _header_value = header
      if header_key == 'content-length':
        headers[index] = (header_key, str(post_body_length))
        break
Run Code Online (Sandbox Code Playgroud)

一切都完成了!

端点将返回正确的Content-Length,WebOb将很高兴,您的API测试将正常工作:)