1

我的代码是这样的:

self.testbed.init_blobstore_stub()
upload_url = blobstore.create_upload_url('/image')
upload_url = re.sub('^http://testbed\.example\.com', '', upload_url)

response = self.testapp.post(upload_url, params={
    'shopid': id,
    'description': 'JLo',
    }, upload_files=[('file', imgPath)])
self.assertEqual(response.status_int, 200)

怎么会显示404错误?由于某些原因,上传路径似乎根本不存在。

4

2 回答 2

3

你不能这样做。我认为问题在于 webtest(我认为这是 self.testapp 的来源)不能很好地与 testbed blobstore 功能一起使用。你可以在这个问题上找到一些信息。

我的解决方案是覆盖unittest.TestCase并添加以下方法:

def create_blob(self, contents, mime_type):
    "Since uploading blobs doesn't work in testing, create them this way."
    fn = files.blobstore.create(mime_type = mime_type,
                                _blobinfo_uploaded_filename = "foo.blt")
    with files.open(fn, 'a') as f:
        f.write(contents)
    files.finalize(fn)
    return files.blobstore.get_blob_key(fn)

def get_blob(self, key):
    return self.blobstore_stub.storage.OpenBlob(key).read()

您还需要这里的解决方案。

对于我通常会执行 get 或 post 到 blobstore 处理程序的测试,我改为调用上述两种方法之一。这有点hacky,但它有效。

我正在考虑的另一个解决方案是使用 Selenium 的 HtmlUnit 驱动程序。这将需要开发服务器正在运行,但应该允许对 blobstore 和 javascript 进行全面测试(作为附带好处)。

于 2012-11-09T14:07:23.677 回答
2

我认为 Kekito 是对的,您不能直接 POST 到 upload_url。

但是,如果您想测试 BlobstoreUploadHandler,您可以通过以下方式伪造它通常会从 Blobstore 收到的 POST 请求。假设您的处理程序位于 /handler :

    import email
    ...

    def test_upload(self):
        blob_key = 'abcd'
        # The blobstore upload handler receives a multipart form request
        # containing uploaded files. But instead of containing the actual
        # content, the files contain an 'email' message that has some meta
        # information about the file. They also contain a blob-key that is
        # the key to get the blob from the blobstore

        # see blobstore._get_upload_content
        m = email.message.Message()
        m.add_header('Content-Type', 'image/png')
        m.add_header('Content-Length', '100')
        m.add_header('X-AppEngine-Upload-Creation', '2014-03-02 23:04:05.123456')
        # This needs to be valie base64 encoded
        m.add_header('content-md5', 'd74682ee47c3fffd5dcd749f840fcdd4')
        payload = m.as_string()
        # The blob-key in the Content-type is important
        params = [('file', webtest.forms.Upload('test.png', payload,
                                                'image/png; blob-key='+blob_key))]

        self.testapp.post('/handler', params, content_type='blob-key')

我通过深入研究 blobstore 代码发现了这一点。重要的是,blobstore 发送到 UploadHandler 的 POST 请求不包含文件内容。相反,它包含一个“电子邮件消息”(嗯,像电子邮件一样编码的信息),其中包含有关文件的元数据(内容类型、内容长度、上传时间和 md5)。它还包含一个 blob-key,可用于从 blobstore 中检索文件。

于 2014-07-16T08:35:41.757 回答