测试抛出IntegrityError的SQLAlchemy代码的正确方法是什么?

2024-03-29 13:22:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了thisQ&A,并且已经尝试捕捉引发IntegrityError异常的代码的异常,方法是:

self.assertRaises(IntegrityError, db.session.commit())

但不知怎么的,我的单元测试还是失败了,并以IntegrityError异常停止。我希望它说OK,因为我已经期望在单元测试中出现异常。 这是因为代码试图插入具有相同唯一字段值的行。在

有什么想法吗?在


Tags: 方法代码selfdbsessionok单元测试段值
1条回答
网友
1楼 · 发布于 2024-03-29 13:22:40

其中一个将是关键:

# ... only if version >= 2.7
with self.assertRaises(IntegrityError):
    db.session.commit()

或者:

^{pr2}$

您的示例与正确方法的区别在于:

# Your example: You call db.session.commit(), this will raise an exception before
# assertRaises is called
self.assertRaises(IntegrityError, db.session.commit())

# Correct way: Pass what should be called to assertRaises, 
# let assertRaises invoke it and check for exception
self.assertRaises(IntegrityError, db.session.commit)

我更喜欢使用assertRaises作为上下文管理器(使用with)。在

相关问题 更多 >