1

我使用 django 和 neo4j 作为数据库和 noemodel 作为 OGM。我该如何测试它?

当我运行python3 manage.py test所有更改时,我的测试就留下了。

还有我如何制作两个数据库,一个用于测试,另一个用于生产,并指定如何使用哪个数据库?

4

2 回答 2

3

我认为保留所有更改的原因是由于使用与您在开发中使用的相同的 neo4j 数据库进行测试。由于 neomodel 没有与 Django 紧密集成,因此它在测试时的行为方式与 Django 的 ORM 不同。当您使用它的 ORM 运行测试时,Django 会做一些有用的事情,例如创建一个测试数据库,该数据库将在完成时被销毁。

对于 neo4j 和 neomodel,我建议您执行以下操作:

创建自定义测试运行器

Django 使您能够通过设置设置变量来定义自定义测试运行器。TEST_RUNNER一个非常简单的版本可以帮助您:

from time import sleep
from subprocess import call

from django.test.runner import DiscoverRunner


class MyTestRunner(DiscoverRunner):
    def setup_databases(self, *args, **kwargs):
        # Stop your development instance
        call("sudo service neo4j-service stop", shell=True)
        # Sleep to ensure the service has completely stopped
        sleep(1)
        # Start your test instance (see section below for more details)
        success = call("/path/to/test/db/neo4j-community-2.2.2/bin/neo4j"
                       " start-no-wait", shell=True)
        # Need to sleep to wait for the test instance to completely come up
        sleep(10)
        if success != 0:
            return False
        try:
            # For neo4j 2.2.x you'll need to set a password or deactivate auth
            # Nigel Small's py2neo gives us an easy way to accomplish this
            call("source /path/to/virtualenv/bin/activate && "
                 "/path/to/virtualenv/bin/neoauth "
                 "neo4j neo4j my-p4ssword")
        except OSError:
            pass
        # Don't import neomodel until we get here because we need to wait 
        # for the new db to be spawned
        from neomodel import db
        # Delete all previous entries in the db prior to running tests
        query = "match (n)-[r]-() delete n,r"
        db.cypher_query(query)
        super(MyTestRunner, self).__init__(*args, **kwargs)

    def teardown_databases(self, old_config, **kwargs):
        from neomodel import db
        # Delete all previous entries in the db after running tests
        query = "match (n)-[r]-() delete n,r"
        db.cypher_query(query)
        sleep(1)
        # Shut down test neo4j instance
        success = call("/path/to/test/db/neo4j-community-2.2.2/bin/neo4j"
                       " stop", shell=True)
        if success != 0:
            return False
        sleep(1)
        # start back up development instance
        call("sudo service neo4j-service start", shell=True)

添加辅助 neo4j 数据库

这可以通过多种方式完成,但要跟随上面的测试运行器,您可以从neo4j 的网站下载社区发行版。call有了这个辅助实例,您现在可以利用测试运行器中 s 中使用的命令行语句在您想使用的数据库之间进行交换。

包起来

此解决方案假设您使用的是 linux 机器,但应该可以移植到不同的操作系统,只需稍作修改。另外,我建议查看Django 的 Test Runner Docs以扩展测试运行器可以做什么。

于 2015-08-10T14:49:17.633 回答
2

目前没有在 neomodel 中使用测试数据库的机制,因为 neo4j 每个实例只有 1 个模式。

但是,您可以在像这样运行测试时覆盖环境变量 NEO4J_REST_URL

导出 NEO4J_REST_URL= http://localhost:7473/db/data python3 manage.py test

于 2015-08-10T15:00:00.843 回答