Skip to content

Commit bf9ce73

Browse files
committed
Close files during tests.
1 parent 097478e commit bf9ce73

File tree

3 files changed

+17
-11
lines changed

3 files changed

+17
-11
lines changed

sqlparse/cli.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,17 @@ def main(args=None):
154154
sys.stdin.buffer, encoding=args.encoding).read()
155155
else:
156156
try:
157-
data = ''.join(open(args.filename, 'r', args.encoding).readlines())
157+
with open(args.filename, 'r', args.encoding) as f:
158+
data = ''.join(f.readlines())
158159
except IOError as e:
159160
return _error(
160161
u'Failed to read {0}: {1}'.format(args.filename, e))
161162

163+
close_stream = False
162164
if args.outfile:
163165
try:
164166
stream = open(args.outfile, 'w', args.encoding)
167+
close_stream = True
165168
except IOError as e:
166169
return _error(u'Failed to open {0}: {1}'.format(args.outfile, e))
167170
else:
@@ -176,4 +179,6 @@ def main(args=None):
176179
s = sqlparse.format(data, **formatter_opts)
177180
stream.write(s)
178181
stream.flush()
182+
if close_stream:
183+
stream.close()
179184
return 0

tests/test_cli.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,10 +127,11 @@ def test_encoding_stdin_gbk(filepath, load_file, capfd):
127127
path = filepath('encoding_gbk.sql')
128128
expected = load_file('encoding_gbk.sql', 'gbk')
129129
old_stdin = sys.stdin
130-
sys.stdin = open(path, 'r')
131-
sys.stdout.encoding = 'gbk'
132-
sqlparse.cli.main(['-', '--encoding', 'gbk'])
133-
sys.stdin = old_stdin
130+
with open(path, 'r') as stream:
131+
sys.stdin = stream
132+
sys.stdout.encoding = 'gbk'
133+
sqlparse.cli.main(['-', '--encoding', 'gbk'])
134+
sys.stdin = old_stdin
134135
out, _ = capfd.readouterr()
135136
assert out == expected
136137

tests/test_regressions.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -186,9 +186,9 @@ def test_format_accepts_encoding(load_file):
186186

187187

188188
def test_stream(get_stream):
189-
stream = get_stream("stream.sql")
190-
p = sqlparse.parse(stream)[0]
191-
assert p.get_type() == 'INSERT'
189+
with get_stream("stream.sql") as stream:
190+
p = sqlparse.parse(stream)[0]
191+
assert p.get_type() == 'INSERT'
192192

193193

194194
def test_issue90():
@@ -238,9 +238,9 @@ def test_null_with_as():
238238

239239
def test_issue190_open_file(filepath):
240240
path = filepath('stream.sql')
241-
stream = open(path)
242-
p = sqlparse.parse(stream)[0]
243-
assert p.get_type() == 'INSERT'
241+
with open(path) as stream:
242+
p = sqlparse.parse(stream)[0]
243+
assert p.get_type() == 'INSERT'
244244

245245

246246
def test_issue193_splitting_function():

0 commit comments

Comments
 (0)