データベースとしてneo4j、OGMとしてnoemodelでdjangoを使用しています。どうやってテストするのですか?
すべての変更を実行python3 manage.py test
すると、テストの作成が残ります。
また、テスト用と本番用の 2 つのデータベースを作成し、どちらをどのように使用するかを指定するにはどうすればよいでしょうか。
すべての変更が保持されている理由は、開発で使用しているものと同じ neo4j データベースをテストに使用しているためだと思います。neomodel は Django と緊密に統合されていないため、テスト時に Django の ORM と同じように動作しません。Django は、ORM を使用してテストを実行するときに、完了時に破棄されるテスト データベースの作成など、いくつかの役立つことを行います。
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 の Web サイトからコミュニティ ディストリビューションをダウンロードできます。call
このセカンダリ インスタンスを使用すると、テスト ランナー内の で使用されるコマンド ライン ステートメントを利用して、使用するデータベースを切り替えることができます。
このソリューションは、Linux ボックスを使用していることを前提としていますが、マイナーな変更を加えることで別の OS に移植できる必要があります。また、 Django の Test Runner Docsをチェックして、テスト ランナーでできることを拡張することをお勧めします。
現在、neo4j にはインスタンスごとに 1 つのスキーマしかないため、neomodel でテスト データベースを操作するメカニズムはありません。
ただし、次のようにテストを実行するときに、環境変数 NEO4J_REST_URL をオーバーライドできます。
export NEO4J_REST_URL= http://localhost:7473/db/data python3 manage.py テスト