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

时间:2014-06-14 11:55:06

标签: 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'})

那么我做错了什么?

1 个答案:

答案 0 :(得分: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

<强> 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)

第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

<强> 4。一切都完成了!

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