2012-11-09 27 views
1

我的代码是这样的:GAE - 如何在测试平台中使用blobstore存根?

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错误?由于某些原因,上传路径似乎根本不存在。

+0

http://stackoverflow.com/questions/10928339/how-to-simulate-image-upload-to-google-app-engine-blobstore/10929293#10929293 – alex

回答

3

你不能这样做。我认为问题在于webtest(我假设self.testapp来自哪里)不适用于测试平台blobstore功能。你可以在question找到一些信息。

我的解决办法是重写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() 

您还需要解决here

对于我通常会做一个get或post到blobstore处理程序的测试,我改为调用上面两种方法之一。这有点哈克,但它的作品。

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

+0

对不起,不够清楚。我想要做的是在'/ image'测试帖子处理程序,如果我不能使用'upload_url',这是不可能的。我只需要接受这部分不能被单元测试。 – Khoi

+0

@Khoi,看到我的第一句话。 :)你不能测试blobstore处理程序的操作。其余的目的是为您提供其他选项来解决这个问题。 –

2

我认为Kekito是正确的,你不能直接POST到upload_url。

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

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检索文件。