【发布时间】:2016-02-17 09:57:54
【问题描述】:
我的 Django 应用程序需要连接一个非托管(非 Django)外部 Postgres 数据库。
为了测试我的项目,我需要使用原始 SQL 创建外部数据库和表,然后删除数据库。
通过阅读 Django 文档,可以使用现有的 DiscoverRunner 类创建您自己的 TestRunner 类。可以重写 setup_test_environment 和 teardown_test_environment 方法以执行 SQL 以创建外部数据库:
from psycopg2 import connect
from django.test.runner import DiscoverRunner
class CustomTestRunner(DiscoverRunner):
"""
Test runner that helps to setup external db if doesn`t exist.
"""
def setup_test_environment(self, *args, **kwargs):
conn = connect(database='postgres', host='localhost', user='my_user', password='password123')
try:
with conn.cursor() as c:
query = """CREATE DATABASE "test_db" """
query += """WITH OWNER = my_user """
query += """ENCODING = 'UTF8' TABLESPACE = pg_default """
query += """LC_COLLATE = 'en_ZA.UTF-8' LC_CTYPE = 'en_ZA.UTF-8' """
query += """CONNECTION LIMIT = -1;"""
c.execute(query)
except Exception as e:
print e
conn.close()
super(CustomTestRunner, self).setup_test_environment(*args,
**kwargs)
def teardown_test_environment(self, *args, **kwargs):
super(CustomTestRunner, self).teardown_test_environment(*args,
**kwargs)
# Delete external database after tests
try:
conn = connect(database='postgres', host='localhost', user='my_user', password='password123')
with conn.cursor() as c:
query = """DROP DATABASE test_db;"""
c.execute(query)
except Exception as e:
print e
conn.close()
conn.close()
但是,当我运行测试时,我收到以下错误消息:
CREATE DATABASE cannot run inside a transaction block
是否可以在 Django TestRunner 中运行和提交 SQL?如果没有,在哪里创建这样一个外部数据库的合适位置?
【问题讨论】:
标签: python django postgresql testing