How can I run local unit tests on models that use

2019-07-14 04:41发布

I'm trying to write unit tests for a model that calls on files stored on google cloud storage, but I haven't found any examples on how to simulate the GCS service for unit testing.

It seems that there should be a stub service I can use, and I see some references to gcs within the testbed docs described there, but haven't nailed down an example using it I can work off of.

Here's a condensed/example version of the model I have:

import peewee
from google.appengine.api import app_identity
import cloudstorage

class Example(Model):
    uuid = peewee.CharField(default=uuid4)
    some_property = peewee.CharField()

    @property
    def raw_file_one(self):
        bucket = app_identity.get_default_gcs_bucket_name()
        filename = '/{0}/repo_one/{1}'.format(bucket, self.uuid)
        with cloudstorage.open(filename, 'r') as f:
            return f.read()

    def store_raw_file(self, raw_file_one):
        bucket = app_identity.get_default_gcs_bucket_name()

        filename = '/{0}/stat_doms/{1}'.format(bucket, self.uuid)
        with cloudstorage.open(filename, 'w') as f:
            f.write(raw_file_one)

I'll build test cases with:

import unittest

from google.appengine.ext import testbed    

class TestCase(unittest.TestCase):
    def run(self, *args, **kwargs):
        self.stub_google_services()
        result = super(TestCase, self).run(*args, **kwargs)
        self.unstub_google_services()
        return result

    def stub_google_services(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_all_stubs()

    def unstub_google_services(self):
        self.testbed.deactivate()

Into module tests like:

from application.tests.testcase import TestCase
from application.models import Example

class ExampleTest(TestCase):
    def test_store_raw_file(self):
    ...
    [assert something]

I presume I'd do something like blobstore = self.testbed.get_stub('blobstore') to create a service I can perform tests on (e.g. blobstore.CreateBlob(blob_key, image)) -- but I don't see a service for GCS in the testbed ref docs.

Thoughts on how to implement unit tests with GCS?

1条回答
We Are One
2楼-- · 2019-07-14 04:53

I think you're looking for:

from google.appengine.ext.cloudstorage import cloudstorage_stub
from google.appengine.api.blobstore import blobstore_stub

and:

blob_stub = blobstore_stub.BlobstoreServiceStub(blob_storage)
storage_stub = cloudstorage_stub.CloudStorageStub(blob_storage)

testbed._register_stub('blobstore', self.blob_stub)
testbed._register_stub("cloudstorage", self.storage_stub)
查看更多
登录 后发表回答