有一些類似的問題,例如Pytests with context manager。我還是不明白。為什么在背景關系管理器中沒有提出這個斷言?
class foo:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return self
def test_context_manager():
with foo():
assert False # <- works outside the with statement but not here
使用:python3.9 和 pytest6.2.5
更新:它__exit__在背景關系管理器的方法不回傳 self時起作用。這有效:
class foo:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass # <- this fixes it
但問題仍然存在。為什么第一種情況會失敗。這是一個錯誤嗎?我要舉報嗎?
uj5u.com熱心網友回復:
背景關系管理器旨在捕獲這樣的例外并將其傳遞給__exit__. 如果要引發例外,則需要自己處理:
class foo:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_value:
raise exc_value # AssertionError raised here
return self
def test_context_manager():
with foo():
assert False
test_context_manager()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/349001.html
標籤:Python 蟒蛇-3.x pytest 上下文管理器
