2012-11-09 26 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檢索文件。