我如何在谷歌应用引擎中进行单元测试?

时间:2012-11-05 06:00:54

标签: python google-app-engine

在搜索甚至阅读有关应用引擎单元测试的文档后,仍然无法使其在我的项目上运行。

任务很简单,我在main.py中有我的模型和请求处理程序。 我已经安装了gaetestbed并将其包含在我的测试类中。

我的测试类看起来像这样;

from main import CloudDocument   # My model
class TestCloudDocument(DataStoreTestCase, unittest.TestCase):
    def test_find_document(self):
        self.assertEqual(CloudDocument.all().count(), 0)

当我运行上面的测试时,它返回True但我的数据存储区有记录,我原本预计这个测试会失败。

似乎测试类没有看到我的应用程序的数据存储区。我怎么能做到 查看并访问我的本地数据存储区?

加特

3 个答案:

答案 0 :(得分:3)

单元测试在具有自己的本地数据存储的隔离环境中运行。只有您在测试中或setUp函数中添加的记录才会出现。

答案 1 :(得分:1)

无耻插件:如果您想从setUp方法中加载大量对象,可以使用appengine-fixture-loader

答案 2 :(得分:0)

我建议使用ext.testbed(Local Unit Testing for Python)而不是gaetestbed。正如JJ(gaetestbed的维护者)所指出的那样,它被ext.testbed取代了

如果您这样做并且您想要测试现有的和已填充的数据存储区,则可以使用

执行此操作
 def init_datastore_v3_stub(self, enable=True, datastore_file=None,
                             use_sqlite=False, **stub_kw_args):
    """Enable the datastore stub.

    The 'datastore_file' argument can be the path to an existing
    datastore file, or None (default) to use an in-memory datastore
    that is initially empty.  If you use the sqlite stub and have
    'datastore_file' defined, changes you apply in a test will be
    written to the file.  If you use the default datastore stub,
    changes are _not_ saved to disk unless you set save_changes=True.

    Note that you can only access those entities of the datastore file
    which have the same application ID associated with them as the
    test run. You can change the application ID for a test with
    setup_env().

    Args:
      enable: True if the fake service should be enabled, False if real
        service should be disabled.
      datastore_file: Filename of a dev_appserver datastore file.
      use_sqlite: True to use the Sqlite stub, False (default) for file stub.
      stub_kw_args: Keyword arguments passed on to the service stub.
    """

http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/testbed/__init__.py#431