Ensure that files are always closed explicitly.

This is needed on Pythons without reference
counting garbage collectors (e.g. PyPy).

Change-Id: Ieb563ace9f65a4ad204b01be32bf7a9d5f226005
This commit is contained in:
Alex Gaynor 2013-07-22 14:59:30 -07:00
parent 3a339e9e4d
commit 6384b192b5
2 changed files with 4 additions and 3 deletions

View File

@ -1013,7 +1013,8 @@ class RingBuilder(object):
:param builder_file: path to builder file to save
"""
pickle.dump(self.to_dict(), open(builder_file, 'wb'), protocol=2)
with open(builder_file, 'wb') as f:
pickle.dump(self.to_dict(), f, protocol=2)
def search_devs(self, search_values):
"""Search devices by parameters.

View File

@ -731,7 +731,7 @@ class TestRingBuilder(unittest.TestCase):
@mock.patch('__builtin__.open', autospec=True)
@mock.patch('swift.common.ring.builder.pickle.dump', autospec=True)
def test_save(self, mock_pickle_dump, mock_open):
mock_open.return_value = mock_fh = mock.Mock()
mock_open.return_value = mock_fh = mock.MagicMock()
rb = ring.RingBuilder(8, 3, 1)
devs = [{'id': 0, 'region': 0, 'zone': 0, 'weight': 1,
'ip': '127.0.0.0', 'port': 10000, 'device': 'sda1',
@ -749,7 +749,7 @@ class TestRingBuilder(unittest.TestCase):
rb.rebalance()
rb.save('some.builder')
mock_open.assert_called_once_with('some.builder', 'wb')
mock_pickle_dump.assert_called_once_with(rb.to_dict(), mock_fh,
mock_pickle_dump.assert_called_once_with(rb.to_dict(), mock_fh.__enter__(),
protocol=2)
def test_search_devs(self):