我的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)
有unique(name, parent)
. 我Test
的是
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
,但它不会
另外,当我在最后一行断言时(在上面的代码中省略)我在表中有多少条目
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