Google Cloud Endpoints 测试中的内容长度错误

6 投票
1 回答
637 浏览
提问于 2025-04-18 09:46

每当我想在代码中测试一个404 HTTP错误路径时,就会出现以下错误:

AssertionError: 内容长度与实际的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 个回答

9

这是一个在App Engine上常见的错误。

当你抛出一个异常时,Endpoints没有正确设置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. 完成了!

这样,Endpoints就会返回正确的Content-Length,WebOb会很满意,你的API测试也能正常工作了 :)

撰写回答