I'm modifying some code to be compatible between Python 2
and Python 3
, but have observed a warning in unit test output.
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py:601:
ResourceWarning: unclosed socket.socket fd=4,
family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6,
laddr=('1.1.2.3', 65087), raddr=('5.8.13.21', 8080)
A little research determined this was also happening from popular libraries like requests and boto3.
I could ignore the warning or filter it completely. If was my service, I could set the connection: close
header in my response (link).
Here's an example that exhibits the warning in Python 3.6.1
:
app.py
import requests
class Service(object):
def __init__(self):
self.session = requests.Session()
def get_info(self):
uri = 'http://api.stackexchange.com/2.2/info?site=stackoverflow'
response = self.session.get(uri)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def __del__(self):
self.session.close()
if __name__ == '__main__':
service = Service()
print(service.get_info())
test.py
import unittest
class TestService(unittest.TestCase):
def test_growing(self):
import app
service = app.Service()
res = service.get_info()
self.assertTrue(res['items'][0]['new_active_users'] > 1)
if __name__ == '__main__':
unittest.main()
Is there a better / correct way to manage the session so that it gets explicitly closed and not rely on __del__()
to result in this sort of warning.
Thanks for any help.