Skip to content

Commit

Permalink
Make it clear when using default input
Browse files Browse the repository at this point in the history
  • Loading branch information
abravalheri committed May 18, 2023
1 parent 4436d64 commit d2469d3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/validate_pyproject/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ def critical_logging():
raise


_STDIN = argparse.FileType("r")("-")

META: Dict[str, dict] = {
"version": dict(
flags=("-V", "--version"),
Expand All @@ -67,7 +69,7 @@ def critical_logging():
"input_file": dict(
dest="input_file",
nargs="*",
default=[argparse.FileType("r")("-")],
# default=[_STDIN], # postponed to facilitate testing
type=argparse.FileType("r"),
help="TOML file to be verified (`stdin` by default)",
),
Expand Down Expand Up @@ -120,6 +122,7 @@ def __meta__(plugins: Sequence[PluginWrapper]) -> Dict[str, dict]:
"""'Hyper parameters' to instruct :mod:`argparse` how to create the CLI"""
meta = {k: v.copy() for k, v in META.items()}
meta["enable"]["choices"] = set([p.tool for p in plugins])
meta["input_file"]["default"] = [_STDIN] # lazily defined to facilitate testing
return meta


Expand Down Expand Up @@ -216,12 +219,7 @@ def run(args: Sequence[str] = ()):
exceptions = _ExceptionGroup()
for file in params.input_file:
try:
toml_equivalent = loads(file.read())
validator(toml_equivalent)
if params.dump_json:
print(json.dumps(toml_equivalent, indent=2))
else:
print(f"Valid {_format_file(file)}")
_run_on_file(validator, params, file)
except _REGULAR_EXCEPTIONS as ex:
exceptions.add(f"Invalid {_format_file(file)}", ex)

Expand All @@ -230,6 +228,18 @@ def run(args: Sequence[str] = ()):
return 0


def _run_on_file(validator: Validator, params: CliParams, file: io.TextIOBase):
if file in (sys.stdin, _STDIN):
print("Expecting input via `stdin`...", file=sys.stderr, flush=True)

toml_equivalent = loads(file.read())
validator(toml_equivalent)
if params.dump_json:
print(json.dumps(toml_equivalent, indent=2))
else:
print(f"Valid {_format_file(file)}")


main = exceptions2exit()(run)


Expand Down
15 changes: 15 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import inspect
import io
import logging
import sys
from pathlib import Path
from unittest.mock import Mock
from uuid import uuid4

import pytest
Expand Down Expand Up @@ -120,6 +122,19 @@ def test_invalid_disabled(self, invalid_example):
assert cli.main([str(invalid_example), "-D", "setuptools"]) == 0


class TestInput:
def test_inform_user_about_stdin(self, monkeypatch):
print_mock = Mock()
fake_stdin = io.StringIO('[project]\nname="test"\nversion="0.42"\n')
with monkeypatch.context() as ctx:
ctx.setattr("validate_pyproject.cli._STDIN", fake_stdin)
ctx.setattr("sys.argv", ["validate-pyproject"])
ctx.setattr("builtins.print", print_mock)
cli.run()
calls = print_mock.call_args_list
assert any("input via `stdin`" in x.args[0] for x in calls)


class TestOutput:
def test_valid(self, capsys, valid_example):
cli.main([str(valid_example)])
Expand Down

0 comments on commit d2469d3

Please sign in to comment.