Skip to content

Commit 319009e

Browse files
Talha MalikTalha Malik
Talha Malik
authored and
Talha Malik
committed
Get input from commandline when instance(s) not provided
1 parent fe76b21 commit 319009e

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

jsonschema/cli.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ def _json_file(path):
2222
return json.load(file)
2323

2424

25+
def _read_from_stdin():
26+
return json.loads(sys.stdin.read())
27+
28+
2529
parser = argparse.ArgumentParser(
2630
description="JSON Schema Validation CLI",
2731
)
@@ -83,8 +87,9 @@ def run(arguments, stdout=sys.stdout, stderr=sys.stderr):
8387
validator.check_schema(arguments["schema"])
8488

8589
errored = False
86-
for instance in arguments["instances"] or ():
90+
for instance in arguments["instances"] or (_read_from_stdin(),):
8791
for error in validator.iter_errors(instance):
8892
stderr.write(error_format.format(error=error))
8993
errored = True
94+
9095
return errored

jsonschema/tests/test_cli.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from unittest import TestCase
1+
from unittest import TestCase, mock
22
import json
33
import subprocess
44
import sys
@@ -149,3 +149,22 @@ def test_version(self):
149149
)
150150
version = version.decode("utf-8").strip()
151151
self.assertEqual(version, __version__)
152+
153+
@mock.patch("sys.stdin")
154+
def test_piping(self, mock_stdin):
155+
mock_stdin.read.return_value = "{}"
156+
stdout, stderr = NativeIO(), NativeIO()
157+
exit_code = cli.run(
158+
{
159+
"validator": fake_validator(),
160+
"schema": {},
161+
"instances": [],
162+
"error_format": "{error.message}",
163+
},
164+
stdout=stdout,
165+
stderr=stderr,
166+
)
167+
mock_stdin.read.assert_called_once_with()
168+
self.assertFalse(stdout.getvalue())
169+
self.assertFalse(stderr.getvalue())
170+
self.assertEqual(exit_code, 0)

0 commit comments

Comments
 (0)