Convert Python 3 ResourceWarnings into exception

python, python-3.x

Solution

Here's a unit test that fails if `ResourceWarning` is generated by the code in `with catch_warning()` statement:

#!/usr/bin/env python3
import gc
import socket
import unittest
import warnings

class Test(unittest.TestCase):
    def test_resource_warning(self):
        s = socket.socket()
        ####s.close() #XXX uncomment to pass the test

        # generate resource warning when s is deleted
        with warnings.catch_warnings(record=True) as w:
            warnings.resetwarnings() # clear all filters
            warnings.simplefilter('ignore') # ignore all
            warnings.simplefilter('always', ResourceWarning) # add filter
            del s        # remove reference
            gc.collect() # run garbage collection (for pypy3)
            self.assertFalse(w and str(w[-1])) # test fails if there
                                               # are warnings

if __name__=="__main__":
    unittest.main()

Problem

Is there a way to force a Python 3 unittest to fail, rather than simply print a warning to stderr, if it causes any ResourceWarning? I've tried the following: ``` import warnings warnings.simplefilter(action='error', category=ResourceWarning) ``` Which results in this output from unittest: ``` my_test (__main__.MyTest) ... Exception ignored in: <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 54065), raddr=('127.0.0.1', 27017)> ResourceWarning: unclosed <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 54065), raddr=('127.0.0.1', 27017)> ok ---------------------------------------------------------------------- Ran 1 test in 0.110s ``` Note the "Exception ignored" message. I'd rather the test failed, instead of requiring me to read its output looking for ResourceWarnings.

Original source