Django测试neo4j数据库

时间:2015-08-08 16:05:01

标签: django neo4j neomodel

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

当我运行python3 manage.py test所有更改时,我的测试结果仍然存在。

另外,我如何创建两个数据库,一个用于测试,另一个用于生产,并指定使用哪个数据库?

2 个答案:

答案 0 :(得分:3)

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

使用neo4j和neomodel我建议执行以下操作:

创建自定义测试运行器

Django允许您通过设置TEST_RUNNER设置变量来定义custom 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's website下载社区分发。使用此辅助实例,您现在可以使用测试运行器中call s中使用的命令行语句在您要使用的数据库之间进行切换。

总结

此解决方案假设您已经在Linux机器上,但应该可以移植到不同的操作系统,只需稍加修改即可。另外,我建议您查看Django's Test Runner Docs以扩展测试运行器的功能。

答案 1 :(得分:2)

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

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

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