python,插入同一行两次测试未失败
我的python,插入同一行两次测试未失败,python,unit-testing,sqlalchemy,Python,Unit Testing,Sqlalchemy,我的PostgreSQL表如下所示 Table "public.categories" Column | Type | Modifiers ------------+--------------------------+----------- uuid | uuid | not null name | character varying |
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())
由于数据库中的UniqueConstraint
,当我尝试插入具有相同名称和父项的新类别时,它应该失败,但它没有成功
另外,当我在最后一行断言(在上面的代码中省略)表中有多少个条目时
self.assertEquals(2, len(db.session.query(Category).all()))
它失败了
self.assertEquals(2, len(db.session.query(Category).all()))
AssertionError: 2 != 1
这意味着它将覆盖现有条目
这里出了什么问题
更新
根据@sr2222的回答,我用下面的方法解决了这个bug
def session_commit(self):
# noinspection PyBroadException
try:
db.session.commit()
except:
db.session.rollback()
raise # added error to propagate up
finally:
pass
您的session\u commit
函数有一个catchall,除了DB commit周围的
块。除非回滚失败,否则这将始终通过。至于断言,由于您正在压制错误,您的提交正在悄无声息地失败,因此您找到的单行应该是原始的、未编辑的条目。如果您想在验证中有条件地处理异常状态,您需要捕获它并适当地处理它,而不仅仅是丢弃它。您的会话_commit
函数在DB commit周围有一个catchall块,但
块除外。除非回滚失败,否则这将始终通过。至于断言,由于您正在压制错误,您的提交正在悄无声息地失败,因此您找到的单行应该是原始的、未编辑的条目。如果您想在验证中有条件地处理异常状态,您需要捕获它并适当地处理它,而不仅仅是扔掉它。完美答案!这肯定是一个错误,我修正了它完美的答案!这肯定是一个错误,我修复了它