Skip to content

Document spec_string; accept stdin on validate - - #172

Merged
RonnyPfannschmidt merged 1 commit into
mainfrom
docs-spec-string-and-cli-stdin
Jul 19, 2026
Merged

RonnyPfannschmidt merged 1 commit into
mainfrom
docs-spec-string-and-cli-stdin

Conversation

@RonnyPfannschmidt

@RonnyPfannschmidt RonnyPfannschmidt commented Jul 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Document Python API spec_string= for in-memory validation (already supported)
  • CLI: prance validate - reads a spec from stdin via Click (Path(allow_dash=True) + get_text_stream("stdin"))
  • Reject combining - with other paths / using - more than once

Closes #157

Test plan

  • pytest tests/test_cli.py (includes stdin cases)
  • echo '...' | prance validate - / prance validate - < file.yml

Made with Cursor

Summary by Sourcery

Enable stdin-based spec validation in the CLI, centralize parser construction for URL and in-memory specs, and document the spec_string API and new CLI usage while covering the behavior with tests.

New Features:

  • Support validating specs from stdin via the prance validate - CLI convention

Enhancements:

  • Refactor parser creation into shared helpers to support URL and in-memory spec parsing consistently

Documentation:

  • Document the Python API spec_string parameter and the CLI dash-means-stdin behavior in the changelog

Tests:

  • Add CLI tests for validating specs from stdin and for rejecting combinations of stdin with file paths

Document in-memory validation with BaseParser(spec_string=...) and
teach `prance validate -` to read a spec from stdin using Click's
dash convention (Path allow_dash + get_text_stream).

Co-authored-by: Cursor AI <ai@cursor.sh>
Co-authored-by: Cursor Grok 4.5 <grok@x.ai>
@sourcery-ai

sourcery-ai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Refactors CLI parser construction to support validating specs from stdin using the dash convention, centralizes parser configuration, and documents the new behavior and existing spec_string API, with tests enforcing stdin usage rules.

Sequence diagram for prance validate handling stdin dash input

sequenceDiagram
    actor User
    participant prance_cli_validate as validate
    participant Click as click
    participant Stdin as stdin
    participant Parser as BaseParser_ResolvingParser

    User->>prance_cli_validate: prance validate -
    prance_cli_validate->>Click: click.Path(allow_dash=True)
    prance_cli_validate->>prance_cli_validate: urls.count("-")
    alt [stdin used more than once]
        prance_cli_validate-->>User: click.UsageError("stdin (-) can only be used once.")
    else [stdin combined with other urls]
        prance_cli_validate-->>User: click.UsageError("stdin (-) cannot be combined...")
    else [single "-" argument]
        prance_cli_validate->>prance_cli_validate: __parser_for_stdin(resolve, backend, strict, encoding, allow_recursion)
        prance_cli_validate->>Click: click.get_text_stream("stdin", encoding)
        Click-->>Stdin: open text stream
        Stdin-->>prance_cli_validate: stream.read() (spec_string)
        prance_cli_validate->>prance_cli_validate: __make_parser(spec_string)
        prance_cli_validate->>Parser: BaseParser_ResolvingParser(url=None, spec_string, **kwargs)
        prance_cli_validate->>prance_cli_validate: __validate(parser, "-")
        prance_cli_validate-->>User: validation result
    end

    User->>prance_cli_validate: prance validate path.yml
    prance_cli_validate->>prance_cli_validate: __parser_for_url(url, resolve, backend, strict, encoding, allow_recursion)
    prance_cli_validate->>prance_cli_validate: __make_parser(url)
    prance_cli_validate->>Parser: BaseParser_ResolvingParser(url, spec_string=None, **kwargs)
    prance_cli_validate->>prance_cli_validate: __validate(parser, formatted_url)
    prance_cli_validate-->>User: validation result
Loading

File-Level Changes

Change Details Files
Centralize parser construction and shared configuration for URL and in-memory specs.
  • Introduce a helper to build common parser keyword arguments and emit resolve-related messages.
  • Add a factory function that returns the appropriate BaseParser or ResolvingParser for a URL or spec_string.
  • Refactor the existing URL-based parser helper to use the new factory instead of duplicating logic.
prance/cli.py
Support validating a single spec from stdin in the CLI and enforce dash usage constraints.
  • Allow '-' as a click.Path argument in the validate command and document dash-means-stdin in the command help.
  • Add a stdin-specific parser helper that reads from click.get_text_stream and passes spec_string into the parser.
  • Route '-' inputs to the new stdin helper and disallow multiple uses of '-' or combining '-' with other URLs, raising UsageError in those cases.
prance/cli.py
Add tests for stdin validation behavior and dash usage errors.
  • Add a test that validates a spec provided via stdin and asserts the expected output messages.
  • Add a test that verifies combining '-' with another path fails with a usage error.
tests/test_cli.py
Document the new feature and spec_string behavior in the changelog.
  • Create a changelog entry describing stdin validation and spec_string documentation.
changelog.d/157.feature.rst

Assessment against linked issues

Issue Objective Addressed Explanation
#157 Provide a way in the Python API to validate a spec supplied as an in-memory string (and document how to use it). ✅
#157 Provide a way in the CLI to validate a spec supplied as a string (e.g., via stdin) in addition to file paths/URLs. ✅

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • The new parser helpers (__parser_kwargs/__make_parser) mix building kwargs with emitting CLI output; consider separating side-effectful logging from argument construction so the functions stay easier to reuse and reason about.
  • In validate, the repeated unpacking of ctx.obj when calling __parser_for_url and __parser_for_stdin could be simplified by passing a single options object or using a small helper to avoid duplicating the same argument list in multiple places.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new parser helpers (`__parser_kwargs`/`__make_parser`) mix building kwargs with emitting CLI output; consider separating side-effectful logging from argument construction so the functions stay easier to reuse and reason about.
- In `validate`, the repeated unpacking of `ctx.obj` when calling `__parser_for_url` and `__parser_for_stdin` could be simplified by passing a single options object or using a small helper to avoid duplicating the same argument list in multiple places.

## Individual Comments

### Comment 1
<location path="tests/test_cli.py" line_range="118-127" />
<code_context>
             assert result.exit_code == 0


+@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
+def test_validate_from_stdin(runner):
+    from prance import cli
+
+    with open("tests/specs/petstore.yaml", encoding="utf-8") as f:
+        content = f.read()
+
+    result = runner.invoke(cli.validate, ["-"], input=content)
+    assert result.exit_code == 0
+    assert 'Processing "-" (stdin)...' in result.output
+    assert "Validates OK as Swagger/OpenAPI 2.0!" in result.output
+
+
+@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
+def test_validate_stdin_cannot_combine_with_paths(runner):
+    from prance import cli
+
+    result = runner.invoke(
+        cli.validate, ["-", "tests/specs/petstore.yaml"], input="openapi: 3.0.0\n"
+    )
+    assert result.exit_code == 2
+    assert "cannot be combined" in result.output
+
+
</code_context>
<issue_to_address>
**suggestion (testing):** Add a test for the case where stdin (`-`) is used more than once to cover the `urls.count("-") > 1` guard.

The new `urls.count("-") > 1` guard is only indirectly tested via mixing `-` with a path. Please add a test (e.g. `test_validate_stdin_cannot_be_used_twice`) that calls `cli.validate(['-', '-'])` and asserts `exit_code == 2` and that the "stdin (-) can only be used once." message appears, so this specific error path is covered and guarded against regressions.

Suggested implementation:

```python
@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
def test_validate_from_stdin(runner):
    from prance import cli

    with open("tests/specs/petstore.yaml", encoding="utf-8") as f:
        content = f.read()

    result = runner.invoke(cli.validate, ["-"], input=content)
    assert result.exit_code == 0


@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
def test_validate_stdin_cannot_be_used_twice(runner):
    from prance import cli

    result = runner.invoke(cli.validate, ["-", "-"], input="openapi: 3.0.0\n")
    assert result.exit_code == 2
    assert "stdin (-) can only be used once." in result.output

```

None required, assuming the `validate` command already emits the "stdin (-) can only be used once." message when `urls.count("-") > 1`. If the message text differs, adjust the assertion string to match the actual output.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/test_cli.py
Comment on lines +118 to +127
@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
def test_validate_from_stdin(runner):
from prance import cli

with open("tests/specs/petstore.yaml", encoding="utf-8") as f:
content = f.read()

result = runner.invoke(cli.validate, ["-"], input=content)
assert result.exit_code == 0
assert 'Processing "-" (stdin)...' in result.output

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Add a test for the case where stdin (-) is used more than once to cover the urls.count("-") > 1 guard.

The new urls.count("-") > 1 guard is only indirectly tested via mixing - with a path. Please add a test (e.g. test_validate_stdin_cannot_be_used_twice) that calls cli.validate(['-', '-']) and asserts exit_code == 2 and that the "stdin (-) can only be used once." message appears, so this specific error path is covered and guarded against regressions.

Suggested implementation:

@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
def test_validate_from_stdin(runner):
    from prance import cli

    with open("tests/specs/petstore.yaml", encoding="utf-8") as f:
        content = f.read()

    result = runner.invoke(cli.validate, ["-"], input=content)
    assert result.exit_code == 0


@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
def test_validate_stdin_cannot_be_used_twice(runner):
    from prance import cli

    result = runner.invoke(cli.validate, ["-", "-"], input="openapi: 3.0.0\n")
    assert result.exit_code == 2
    assert "stdin (-) can only be used once." in result.output

None required, assuming the validate command already emits the "stdin (-) can only be used once." message when urls.count("-") > 1. If the message text differs, adjust the assertion string to match the actual output.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves Prance’s validation UX by documenting the already-supported spec_string= Python API for in-memory specs and extending the prance validate CLI to accept - as “read spec from stdin”, aligning with Click’s dash-means-stdin convention.

Changes:

  • Document BaseParser(spec_string=...) usage in README.rst.
  • Add prance validate - support by reading stdin and constructing a parser from the in-memory spec string.
  • Add CLI tests covering stdin success and rejecting stdin combined with file paths, plus a changelog entry.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
tests/test_cli.py Adds CLI tests for validating from stdin and rejecting invalid stdin/path combinations.
README.rst Documents spec_string usage and the new prance validate - stdin convention.
prance/cli.py Implements stdin handling for validate -, centralizes parser construction, and adds input-argument constraints.
changelog.d/157.feature.rst Adds a changelog fragment for the new documentation and stdin CLI behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread prance/cli.py
Comment on lines +104 to +107
click.echo('Processing "-" (stdin)...')
stream = click.get_text_stream("stdin", encoding=encoding)
spec_string = stream.read()
parser = __make_parser(
Comment thread tests/test_cli.py
Comment on lines +118 to +140
@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
def test_validate_from_stdin(runner):
from prance import cli

with open("tests/specs/petstore.yaml", encoding="utf-8") as f:
content = f.read()

result = runner.invoke(cli.validate, ["-"], input=content)
assert result.exit_code == 0
assert 'Processing "-" (stdin)...' in result.output
assert "Validates OK as Swagger/OpenAPI 2.0!" in result.output


@pytest.mark.skipif(none_of("click"), reason="Click does not exist")
def test_validate_stdin_cannot_combine_with_paths(runner):
from prance import cli

result = runner.invoke(
cli.validate, ["-", "tests/specs/petstore.yaml"], input="openapi: 3.0.0\n"
)
assert result.exit_code == 2
assert "cannot be combined" in result.output

@RonnyPfannschmidt
RonnyPfannschmidt merged commit e07397e into main Jul 19, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Provide option to validate schema from string along with file path and url

2 participants