3

Id like to write some unit tests that among other thing will need to read a blobstore file

How to write a unit test setUp that puts some file in testbed blobstore so it will availabe for read this way:

blob_info = BlobInfo(blob_key)
reader = BlobReader(blob_info)
reader.readline()

EDIT:

I do not look for a way to test files API, I want to put some arbitrary data in the testbed blobstore storage dusring the test case setUp phase, so I can run tests against this data.

1 Answer 1

5

You can add the following to your setUp method, and perhaps store the blob_key as self.blob_key for later use. The init_files_stub is important as it initializes the file service with the memory blobstore.

self.testbed.init_blobstore_stub()
self.testbed.init_files_stub()
from google.appengine.api import files
file_name = files.blobstore.create(mime_type='application/octet-stream')
with files.open(file_name, 'a') as f:
    f.write('blobdata')
files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)

Note that testbed refers to from google.appengine.ext import testbed and self.testbed is the testbed instance.

With init_files_stub, this is exactly as described in docs:

Sign up to request clarification or add additional context in comments.

5 Comments

My first example works for me if I put it in setUp, it writes the 'blobdata' (can be image bytes or whatever) to a blob with id 'blob' and reader.read() in your example will return 'blobdata'. Save self.blob_key in setUp if you need the exact key in your test. The second example seems like the appropriate way to do it according to APIs, but doesn't work. How did the first example fail when you tried to use it?
Sorry I did not test it yet, should work part of your answer confused ;) I did found a solution in the meantime, putting BlobInfo into datastore myself, like this: datastore.Put(datastore.Entity('__BlobInfo__', name=file_path, namespace=''). Your solution much prettier, thx mate!
First example works like a charm but, second examples fails for me on create with AssertionError: No api proxy found for service "file". I did init the init_blobstore_stub. Is there another init method for files api stub?
You're right, my explanation was confusing, I've tried modifying it a bit, hope it helps. On testbed, I activate(), and init datastore_v3, memcache, taskqueue, blobstore and I don't see the AssertionError you mention. I don't know where it tries to use a 'file' service or how to init it.
With init_files_stub present, the API method works and should be preferred. I updated my answer accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.