Skip to content

Commit 23593fb

Browse files
author
Rémi Lapeyre
committed
Fix error message on IOError
1 parent 04b2ade commit 23593fb

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

Lib/json/tool.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ def main():
3636
except ValueError as e:
3737
raise SystemExit(e)
3838

39-
outfile = sys.stdout if options.outfile == '-' else open(options.outfile, 'w')
39+
try:
40+
outfile = sys.stdout if options.outfile == '-' else open(options.outfile, 'w')
41+
except IOError as e:
42+
parser.error("can't open '{}': {}".format(options.outfile, str(e)))
4043
with outfile:
4144
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
4245
outfile.write('\n')

Lib/test/test_json/test_tool.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import unittest
55
from subprocess import Popen, PIPE
66
from test import support
7-
from test.support.script_helper import assert_python_ok
7+
from test.support.script_helper import assert_python_ok, assert_python_failure
88

99

1010
class TestTool(unittest.TestCase):
@@ -99,6 +99,15 @@ def test_infile_same_outfile(self):
9999
self.assertEqual(out, b'')
100100
self.assertEqual(err, b'')
101101

102+
def test_unavailable_outfile(self):
103+
infile = self._create_infile()
104+
rc, out, err = assert_python_failure('-m', 'json.tool', infile, '/bla/outfile')
105+
self.assertEqual(rc, 2)
106+
self.assertEqual(out, b'')
107+
err = err.decode().splitlines()
108+
self.assertEqual(err[0], 'usage: python -m json.tool [-h] [--sort-keys] [infile] [outfile]')
109+
self.assertEqual(err[1], "python -m json.tool: error: can't open '/bla/outfile': [Errno 2] No such file or directory: '/bla/outfile'")
110+
102111
def test_help_flag(self):
103112
rc, out, err = assert_python_ok('-m', 'json.tool', '-h')
104113
self.assertEqual(rc, 0)

0 commit comments

Comments
 (0)