From 48977b6641b1434c3a13ee9647a3f46bcf052636 Mon Sep 17 00:00:00 2001 From: Ronald Bradford Date: Fri, 26 Feb 2016 16:58:31 +0000 Subject: [PATCH] Cleanup open file handles in test cases Use with for file handling avoiding need to manually close open files and catch situations where files were also not being closed. Change-Id: I942c97ce93e4a4311f7d0ab8cd748ea04ef7babb --- oslo_config/tests/test_generator.py | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/oslo_config/tests/test_generator.py b/oslo_config/tests/test_generator.py index 72ae1d39..14c86e4d 100644 --- a/oslo_config/tests/test_generator.py +++ b/oslo_config/tests/test_generator.py @@ -782,8 +782,9 @@ class GeneratorTestCase(base.BaseTestCase): if self.stdout: self.assertEqual(self.expected, stdout.getvalue()) else: - content = open(output_file).read() - self.assertEqual(self.expected, content) + with open(output_file, 'r') as f: + actual = f.read() + self.assertEqual(self.expected, actual) log_warning = getattr(self, 'log_warning', None) if log_warning is not None: @@ -907,14 +908,14 @@ class GeneratorAdditionalTestCase(base.BaseTestCase): groups = generator._get_groups(config) fd, tmp_file = tempfile.mkstemp() - f = open(tmp_file, 'w+') - formatter = generator._OptFormatter(output_file=f) + with open(tmp_file, 'w+') as f: + formatter = generator._OptFormatter(output_file=f) + generator._output_opts(formatter, 'DEFAULT', groups.pop('DEFAULT')) expected = '''[DEFAULT] ''' - generator._output_opts(formatter, 'DEFAULT', groups.pop('DEFAULT')) - f.close() - content = open(tmp_file).read() - self.assertEqual(expected, content) + with open(tmp_file, 'r') as f: + actual = f.read() + self.assertEqual(expected, actual) def test_output_opts_group(self): @@ -923,8 +924,9 @@ class GeneratorAdditionalTestCase(base.BaseTestCase): groups = generator._get_groups(config) fd, tmp_file = tempfile.mkstemp() - f = open(tmp_file, 'w+') - formatter = generator._OptFormatter(output_file=f) + with open(tmp_file, 'w+') as f: + formatter = generator._OptFormatter(output_file=f) + generator._output_opts(formatter, 'alpha', groups.pop('alpha')) expected = '''[alpha] # @@ -934,10 +936,9 @@ class GeneratorAdditionalTestCase(base.BaseTestCase): # foo option (string value) #foo = fred ''' - generator._output_opts(formatter, 'alpha', groups.pop('alpha')) - f.close() - content = open(tmp_file).read() - self.assertEqual(expected, content) + with open(tmp_file, 'r') as f: + actual = f.read() + self.assertEqual(expected, actual) class GeneratorMutableOptionTestCase(base.BaseTestCase):