python—如何修补方法,以便第一次引发异常,而第二次调用底层方法

0kjbasz6  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(178)

我想模拟一个将对象保存到数据库的方法。我试图Assert失败时的重试行为。在第一次尝试时,我想提出一个例外。在第二次尝试中,我希望调用底层方法,即保存到数据库中。
例如

  1. # production code
  2. import time
  3. class Model(Base):
  4. def save(self):
  5. for i in range(3):
  6. try:
  7. super().save()
  8. except Exception as e:
  9. time.sleep(1)
  10. else:
  11. break
  12. # test code
  13. from unittest import mock
  14. def test_saving():
  15. model = Model()
  16. with mock.patch("module.Model.save", ...): # ... <- what to put here
  17. model.save()
  18. # assert the model was persisted

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题