【发布时间】:2015-10-21 01:40:00
【问题描述】:
我使用 Python 2.7,使用 psycopg2 连接到 Amazon Redshift 数据库。我有单元测试,在这个测试类的 setUp 和 tearDown 方法中,我删除了为此测试创建的表。所以方案是:
def setUp(self):
drop_specific_tables()
create_specific_tables()
def tearDown(self):
drop_specific_tables()
删除 setUp 和 tearDown 的原因是,如果测试不安全地退出并跳过 tearDown,我们仍然可以知道,无论何时再次运行,它仍然会以全新的状态开始。
这是 drop_specific_tables 方法,而 rcur 是指向我们的 redshift 数据库的 psycopg2 游标。
def drop_specific_tables(rcur):
rcur.execute("BEGIN;")
rcur.execute("SELECT table_name "
" FROM information_schema.tables "
" WHERE table_schema='public' ")
tables = [row for row, in rcur]
rcur.execute("DROP TABLE IF EXISTS " + ", ".join(tables) + " CASCADE;")
rcur.execute("END;")
运行单个测试时,它会通过。但是当整个类运行时,setUp或tearDown中的某些测试错误(不确定哪个测试错误和哪个drop_specific_tables),在drop_specific_tables()中,与
rcur.execute("SELECT table_name "
" FROM information_schema.tables "
" WHERE table_schema='public' ")
产生错误ProgrammingError: Relation with OID 1454844 does not exist. 我打印了“information_schema.tables”的 OID,它与错误消息中的 OID 不同。
为什么会发生这种情况?我明白关系不存在意味着什么,但是这个查询正在寻找它找不到的关系是什么?为什么有时它不存在,导致查询出错?
更新:我还把每张表的OID在drop前都打印出来了,也都不是报错信息中的OID!
【问题讨论】:
标签: python postgresql psycopg2 amazon-redshift python-unittest