diff --git a/jsonschema/cli.py b/jsonschema/cli.py index ab3335b27..6f09c7bec 100644 --- a/jsonschema/cli.py +++ b/jsonschema/cli.py @@ -22,6 +22,10 @@ def _json_file(path): return json.load(file) +def _read_from_stdin(stdin): + return json.loads(stdin.read()) + + parser = argparse.ArgumentParser( description="JSON Schema Validation CLI", ) @@ -76,15 +80,16 @@ def main(args=sys.argv[1:]): sys.exit(run(arguments=parse_args(args=args))) -def run(arguments, stdout=sys.stdout, stderr=sys.stderr): +def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin): error_format = arguments["error_format"] validator = arguments["validator"](schema=arguments["schema"]) validator.check_schema(arguments["schema"]) errored = False - for instance in arguments["instances"] or (): + for instance in arguments["instances"] or (_read_from_stdin(stdin),): for error in validator.iter_errors(instance): stderr.write(error_format.format(error=error)) errored = True + return errored diff --git a/jsonschema/tests/test_cli.py b/jsonschema/tests/test_cli.py index ed820ba3f..ed3b5c1ab 100644 --- a/jsonschema/tests/test_cli.py +++ b/jsonschema/tests/test_cli.py @@ -149,3 +149,20 @@ def test_version(self): ) version = version.decode("utf-8").strip() self.assertEqual(version, __version__) + + def test_piping(self): + stdout, stderr, stdin = NativeIO(), NativeIO(), NativeIO("{}") + exit_code = cli.run( + { + "validator": fake_validator(), + "schema": {}, + "instances": [], + "error_format": "{error.message}", + }, + stdout=stdout, + stderr=stderr, + stdin=stdin, + ) + self.assertFalse(stdout.getvalue()) + self.assertFalse(stderr.getvalue()) + self.assertEqual(exit_code, 0)