From acaf00cbaf32e7a14e39bcc0a5fd774a5385faa0 Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Sat, 28 Oct 2017 17:07:09 -0700 Subject: Fix unclosed file warnings discovered during tests Appear as: ResourceWarning: unclosed file ... Always explicitly close files or detach file wrappers. --- sqlparse/cli.py | 7 +++++-- tests/test_cli.py | 7 ++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/sqlparse/cli.py b/sqlparse/cli.py index ad6bc7a..f73f5d4 100755 --- a/sqlparse/cli.py +++ b/sqlparse/cli.py @@ -150,8 +150,11 @@ def main(args=None): if PY2: data = getreader(args.encoding)(sys.stdin).read() else: - data = TextIOWrapper( - sys.stdin.buffer, encoding=args.encoding).read() + wrapper = TextIOWrapper(sys.stdin.buffer, encoding=args.encoding) + try: + data = wrapper.read() + finally: + wrapper.detach() else: try: with open(args.filename, 'r', args.encoding) as f: diff --git a/tests/test_cli.py b/tests/test_cli.py index 18c6fcb..485afd3 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -115,9 +115,10 @@ def test_encoding_stdin_utf8(filepath, load_file, capfd): path = filepath('encoding_utf8.sql') expected = load_file('encoding_utf8.sql', 'utf-8') old_stdin = sys.stdin - sys.stdin = open(path, 'r') - sys.stdout.encoding = 'utf-8' - sqlparse.cli.main(['-']) + with open(path, 'r') as f: + sys.stdin = f + sys.stdout.encoding = 'utf-8' + sqlparse.cli.main(['-']) sys.stdin = old_stdin out, _ = capfd.readouterr() assert out == expected -- cgit v1.2.1