单元测试BlobStore create_upload_url上传

时间:2015-03-04 10:10:41

标签: python unit-testing google-app-engine blobstore

我使用GAE BlobStore API创建上传网址,如下所示:

self.response.write(blobstore.create_upload_url(....))

生产中一切正常,但是当使用testbed对此API进行单元测试时,我会收到以下网址:

http://testbed.example.com/_ah/upload/agx0ZXN0YmVkLXRlc3RyGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxgDDA

从测试上传到此URL不起作用,我得到404.我应该正确地初始化所有存根,其中包括:

self.testbed.init_datastore_v3_stub()
self.testbed.init_blobstore_stub()
self.testbed.init_files_stub()

我做错了什么?如何使用blobstore create_upload_url API对文件上载进行单元测试?

3 个答案:

答案 0 :(得分:0)

从评论和查看代码中,我假设您无法开箱即用。

我对此问题的解决方案是自行实现上传,使用google.appengine.api.datastore.Getcreate_upload_url网址指向的会话中提取信息。

下面是一些测试代码。它使用来自WebTest的post和使用GCS的存根,尽管后者可能是不必要的。

from google.appengine.api import datastore
import uuid
import base64
import md5

def testSomething(self):
  upload_url = self.testapp.post('/path/to/create_upload_url/handler').body
  response = self.upload_blobstore_file(upload_url, "file", "myfile.txt", "MYDATA1").json
  # Test something on the response from the success handler and/or backing storage

def upload_blobstore_file(self, upload_url, field, filename, contents, type = "application/octet-stream"):
  session = datastore.Get(upload_url.split('/')[-1])
  new_object = "/" + session["gs_bucket_name"] + "/" + str(uuid.uuid4())
  self.storage_stub.store(new_object, type, contents)

  message = "Content-Type: application/octet-stream\r\nContent-Length: " + str(len(contents)) + "\r\nContent-MD5: " + base64.b64encode(md5.new(contents).hexdigest()) + "\r\nX-AppEngine-Cloud-Storage-Object: /gs" + new_object.encode("ascii") + "\r\ncontent-disposition: form-data; name=\"" + field + "\"; filename=\"" + filename + "\"\r\nX-AppEngine-Upload-Creation: 2015-07-17 16:19:55.531719\r\n\r\n"
  return self.testapp.post(session["success_path"], upload_files = [
  (field, filename, message, "message/external-body; blob-key=\"encoded_gs_file:blablabla\"; access-type=\"X-AppEngine-BlobKey\"")
])

答案 1 :(得分:0)

在testbed中设置http_host:

self.testbed.setup_env(
        http_host='%s:%s' % (SERVER_NAME, PORT),
        overwrite=True,)

答案 2 :(得分:-1)

据我所知,您不能直接创建blob数据,而是通过提交的Web表单或HTTP post请求间接创建blob。有关详细信息,请参阅文档[1]。

[1] https://cloud.google.com/appengine/docs/java/blobstore/#Java_Introducing_the_Blobstore