파이썬 라이브러리에 대한 단위 테스트를 작성 중이며 특정 경고가 예외로 발생하도록하고 싶습니다. 이는 simplefilter 함수로 쉽게 할 수 있습니다. 그러나 한 가지 테스트에서는 경고를 사용하지 않고 테스트를 실행 한 다음 경고를 다시 사용하고 싶습니다.경고를 비활성화 한 다음 다시 활성화하려면 어떻게합니까?
저는 파이썬 2.6을 사용하고 있습니다. 따라서 catch_warnings 컨텍스트 관리자를 사용하여이 작업을 수행 할 수 있어야하지만, 저에게는 효과적이지 않습니다. 그래도 실패해도 resetwarnings으로 전화를 걸어 내 필터를 다시 설정해야합니다.
>>> import warnings
>>> warnings.simplefilter("error", UserWarning)
>>>
>>> def f():
... warnings.warn("Boo!", UserWarning)
...
>>>
>>> f() # raises UserWarning as an exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UserWarning: Boo!
>>>
>>> f() # still raises the exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UserWarning: Boo!
>>>
>>> with warnings.catch_warnings():
... warnings.simplefilter("ignore")
... f() # no warning is raised or printed
...
>>>
>>> f() # this should raise the warning as an exception, but doesn't
>>>
>>> warnings.resetwarnings()
>>> warnings.simplefilter("error", UserWarning)
>>>
>>> f() # even after resetting, I'm still getting nothing
>>>
누군가가 내가이 작업을 수행 할 수있는 방법을 설명 할 수 :
여기에 문제를 설명하는 간단한 예제가있다?
편집 : http://bugs.python.org/issue4180
경고 모듈에 약간의 버그가있을 수 있습니다. 나는 셸에서 코드를 가지고 놀고 있었고 경고 메시지가 동일한 다른 함수를 선언한다고해도 경고 (경고 없음)와 동일한 효과가 있었지만 경고 메시지를 변경하면 작동 할 수 있다는 것을 알았습니다. –