我的 PostgreSQL
表看起来像
Table "public.categories"
Column | Type | Modifiers
------------+--------------------------+-----------
uuid | uuid | not null
name | character varying | not null
parent | character varying | not null
created_on | timestamp with time zone | not null
Indexes:
"categories_pkey" PRIMARY KEY, btree (uuid)
"categories_name_parent_key" UNIQUE CONSTRAINT, btree (name, parent)
Referenced by:
TABLE "transactions" CONSTRAINT "transactions_category_id_fkey" FOREIGN KEY (category_id) REFERENCES categories(uuid)
具有唯一(名称,父级)
。
我的测试
是
def setUp(self):
db.create_all()
def session_commit(self):
# noinspection PyBroadException
try:
db.session.commit()
except:
db.session.rollback()
finally:
pass
def test_insert_same_category_twice(self):
"""
category, parent relationship is unique
"""
db.session.add(Category('test_insert_same_category_twice', 'parent1'))
self.session_commit()
self.assertEquals(1, len(db.session.query(Category).all()))
db.session.add(Category('test_insert_same_category_twice', 'parent1')) # should fail
self.session_commit()
def tearDown(self):
db.session.close()
for tbl in reversed(db.metadata.sorted_tables):
db.engine.execute(tbl.delete())
当我尝试插入具有相同name
和parent
的新类别时,由于数据库中的UniqueConstraint
,它应该会失败,但事实并非如此。 t
此外,当我在最后一行断言(在上面的代码中省略)表中有多少条目时
self.assertEquals(2, len(db.session.query(Category).all()))
失败了
self.assertEquals(2, len(db.session.query(Category).all()))
AssertionError: 2 != 1
这意味着它会覆盖现有条目?
这里出了什么问题?
更新
根据@sr2222的回答,我解决了以下方法中的错误
def session_commit(self):
# noinspection PyBroadException
try:
db.session.commit()
except:
db.session.rollback()
raise # added error to propagate up
finally:
pass
最佳答案
您的 session_commit 函数在数据库提交周围有一个包罗万象的 except block 。除非回滚失败,否则这一切都会过去。至于你的断言,你的提交正在默默地失败,因为你正在压制错误,所以你找到的单行应该是原始的、未经编辑的条目。如果您想在验证中有条件地处理异常状态,则需要捕获它并适当处理它,而不是直接将其丢弃。
关于python,插入同一行两次时测试不会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15744246/