Skip to content

🧪 [Add unit tests and implementation for get_pr_status.py]#193

Merged
sheepdestroyer merged 8 commits into
masterfrom
chore/get-pr-status-tests-18330387033569416831
Jul 1, 2026
Merged

🧪 [Add unit tests and implementation for get_pr_status.py]#193
sheepdestroyer merged 8 commits into
masterfrom
chore/get-pr-status-tests-18330387033569416831

Conversation

@sheepdestroyer

@sheepdestroyer sheepdestroyer commented Jul 1, 2026

Copy link
Copy Markdown
Owner

🎯 What:

  • Implemented get_pr_status in scripts/get_pr_status.py to fetch PR status (state, reviews, checks) using the gh CLI.
  • Added a main entrypoint to scripts/get_pr_status.py for CLI usage.
  • Added comprehensive unit tests in tests/test_get_pr_status.py for run_cmd and get_pr_status.

📊 Coverage:

  • run_cmd: success, whitespace stripping, error handling, timeout.
  • get_pr_status: success (mocked gh output), no PR ID handling, error handling, invalid JSON handling.

Result:

  • scripts/get_pr_status.py is now a functional utility for querying PR status.
  • Robust unit tests ensure the script behaves correctly and handles errors gracefully.
  • All tests in the repository (146 total) are passing.

Fixes #191


PR created automatically by Jules for task 18330387033569416831 started by @sheepdestroyer

Summary by Sourcery

Implement a CLI-backed script to report GitHub pull request status and add tests to validate its command execution and error handling behavior.

New Features:

  • Add a get_pr_status utility that queries GitHub PR state, review decision, and status checks via the gh CLI and prints a summary.
  • Expose a main CLI entrypoint in get_pr_status.py to allow fetching PR status optionally for a specific PR ID from the command line.

Enhancements:

  • Enhance run_cmd to enforce a stripped stdout return and support robust timeout and failure handling for subprocess calls.

Tests:

  • Add unit tests for run_cmd covering success, whitespace stripping, error, and timeout behavior.
  • Add unit tests for get_pr_status covering normal operation, missing PR ID, command errors, and invalid JSON output handling.

Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai

sourcery-ai Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implements a functional CLI utility to fetch and summarize GitHub PR status via the gh CLI, and adds unit tests covering command execution and PR status handling, including error and edge cases.

Sequence diagram for get_pr_status CLI interaction

sequenceDiagram
    actor Developer
    participant Shell
    participant get_pr_status_py as get_pr_status_py
    participant gh_cli as gh

    Developer->>Shell: run get_pr_status.py [pr_id]
    Shell->>get_pr_status_py: main
    get_pr_status_py->>get_pr_status_py: get_pr_status(pr_id)
    get_pr_status_py->>gh_cli: run_cmd(["gh","pr","view",pr_id,"--json","state,reviewDecision,statusCheckRollup"])
    gh_cli-->>get_pr_status_py: JSON stdout
    get_pr_status_py->>get_pr_status_py: json.loads(output)
    get_pr_status_py->>Developer: print PR Status summary

    alt subprocess.CalledProcessError
        get_pr_status_py->>Developer: print error to stderr
        get_pr_status_py->>Developer: sys.exit(1)
    else json.JSONDecodeError
        get_pr_status_py->>Developer: print parse error to stderr
        get_pr_status_py->>Developer: sys.exit(1)
    else unexpected Exception
        get_pr_status_py->>Developer: print unexpected error to stderr
        get_pr_status_py->>Developer: sys.exit(1)
    end
Loading

File-Level Changes

Change Details Files
Implement PR status fetching and CLI entrypoint backed by a hardened subprocess wrapper.
  • Enhance run_cmd to use subprocess.run with shell=False, capture_output, text, check=True, and a 30s timeout, returning stripped stdout.
  • Add get_pr_status function that builds a gh pr view command, parses JSON output, summarizes review decision and status checks, and prints a human-readable status report.
  • Add error handling in get_pr_status for subprocess failures, invalid JSON, and unexpected exceptions, emitting messages to stderr and exiting with status 1.
  • Introduce a main function that parses an optional PR ID from argv and invokes get_pr_status, with a standard main guard.
scripts/get_pr_status.py
Add unit tests to validate run_cmd behavior and get_pr_status output and error handling via mocking.
  • Test run_cmd success path, whitespace stripping, failure (CalledProcessError), and timeout (TimeoutExpired).
  • Mock run_cmd to verify get_pr_status correctly constructs gh CLI arguments, parses successful responses, and formats output for PR status, review decisions, and check summaries.
  • Test get_pr_status behavior when no PR ID is provided, ensuring default CLI invocation and fallback review decision value.
  • Test get_pr_status error paths for subprocess errors and invalid JSON, asserting SystemExit and stderr messages.
tests/test_get_pr_status.py

Assessment against linked issues

Issue Objective Addressed Explanation
#191 Add unit tests for run_cmd in scripts/get_pr_status.py, including whitespace stripping, non-zero exit code raising subprocess.CalledProcessError, and timeout raising subprocess.TimeoutExpired.
#191 Evaluate/implement get_pr_status.py logic by either expanding it with actual PR query functionality and an entrypoint, or refactoring/removing the helper if obsolete.

Possibly linked issues

  • #[Maintenance] Add unit tests for scripts/get_pr_status.py and resolve placeholder status: PR fulfills the issue by implementing get_pr_status logic and adding the specified run_cmd unit tests.

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

@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@sheepdestroyer, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 52 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d608c680-198e-4db8-9237-a7cfccfc0cca

📥 Commits

Reviewing files that changed from the base of the PR and between c465873 and 38234c5.

📒 Files selected for processing (5)
  • .gitignore
  • get_pr_status.py
  • scripts/README.md
  • scripts/get_pr_status.py
  • tests/test_get_pr_status.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/get-pr-status-tests-18330387033569416831

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

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:

  • Catching a bare Exception in get_pr_status hides unexpected errors; consider letting them propagate or logging more detail while only handling the known CalledProcessError and JSONDecodeError explicitly.
  • get_pr_status currently mixes data retrieval and printing/exit logic; consider refactoring to return a structured result and have main() handle formatting and process exit to make the function more reusable.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Catching a bare `Exception` in `get_pr_status` hides unexpected errors; consider letting them propagate or logging more detail while only handling the known `CalledProcessError` and `JSONDecodeError` explicitly.
- `get_pr_status` currently mixes data retrieval and printing/exit logic; consider refactoring to return a structured result and have `main()` handle formatting and process exit to make the function more reusable.

## Individual Comments

### Comment 1
<location path="tests/test_get_pr_status.py" line_range="19-22" />
<code_context>
+    with pytest.raises(subprocess.CalledProcessError):
+        run_cmd(["false"])
+
+def test_run_cmd_timeout():
+    # run_cmd has a 30s timeout.
+    with pytest.raises(subprocess.TimeoutExpired):
+        run_cmd(["sleep", "31"])
+
+@patch("scripts.get_pr_status.run_cmd")
</code_context>
<issue_to_address>
**suggestion (testing):** Avoid using a real 31-second sleep for the timeout test by mocking `subprocess.run` instead.

This test currently depends on actually running `sleep 31`, which makes the suite slower and can behave inconsistently across environments. Instead, patch `subprocess.run` to immediately raise `subprocess.TimeoutExpired` (e.g. via `@patch("scripts.get_pr_status.subprocess.run")` and `mock_run.side_effect = subprocess.TimeoutExpired('cmd', 30)`) and assert that `run_cmd([...])` propagates the exception. This keeps the test fast and deterministic while still exercising the timeout handling.

Suggested implementation:

```python
@patch("scripts.get_pr_status.subprocess.run")
def test_run_cmd_timeout(mock_run):
    # Simulate subprocess.run timing out immediately instead of sleeping.
    mock_run.side_effect = subprocess.TimeoutExpired("cmd", 30)
    # run_cmd has a 30s timeout.
    with pytest.raises(subprocess.TimeoutExpired):
        run_cmd(["sleep", "31"])

```

If `patch` is not already imported at the top of `tests/test_get_pr_status.py`, add:
`from unittest.mock import patch`.
</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_get_pr_status.py Outdated
Comment on lines +19 to +22
def test_run_cmd_timeout():
# run_cmd has a 30s timeout.
with pytest.raises(subprocess.TimeoutExpired):
run_cmd(["sleep", "31"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Avoid using a real 31-second sleep for the timeout test by mocking subprocess.run instead.

This test currently depends on actually running sleep 31, which makes the suite slower and can behave inconsistently across environments. Instead, patch subprocess.run to immediately raise subprocess.TimeoutExpired (e.g. via @patch("scripts.get_pr_status.subprocess.run") and mock_run.side_effect = subprocess.TimeoutExpired('cmd', 30)) and assert that run_cmd([...]) propagates the exception. This keeps the test fast and deterministic while still exercising the timeout handling.

Suggested implementation:

@patch("scripts.get_pr_status.subprocess.run")
def test_run_cmd_timeout(mock_run):
    # Simulate subprocess.run timing out immediately instead of sleeping.
    mock_run.side_effect = subprocess.TimeoutExpired("cmd", 30)
    # run_cmd has a 30s timeout.
    with pytest.raises(subprocess.TimeoutExpired):
        run_cmd(["sleep", "31"])

If patch is not already imported at the top of tests/test_get_pr_status.py, add:
from unittest.mock import patch.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a script get_pr_status.py to fetch and display GitHub PR status using the gh CLI, along with a comprehensive test suite. The review feedback highlights several critical improvements: mocking the timeout test to prevent a 30-second test suite delay, handling potential null values for statusCheckRollup to avoid a TypeError, correcting the status check evaluation logic (replacing the invalid CLEAN state with standard states like SUCCESS or SKIPPED), and safely handling potentially None stderr values during subprocess error handling.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread tests/test_get_pr_status.py Outdated
Comment on lines +19 to +22
def test_run_cmd_timeout():
# run_cmd has a 30s timeout.
with pytest.raises(subprocess.TimeoutExpired):
run_cmd(["sleep", "31"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Running a real sleep 31 command causes this unit test to block for 30 seconds before timing out, which severely slows down the test suite.

Instead of executing a real slow subprocess, mock subprocess.run to raise subprocess.TimeoutExpired immediately.

Suggested change
def test_run_cmd_timeout():
# run_cmd has a 30s timeout.
with pytest.raises(subprocess.TimeoutExpired):
run_cmd(["sleep", "31"])
@patch("scripts.get_pr_status.subprocess.run")
def test_run_cmd_timeout(mock_run):
mock_run.side_effect = subprocess.TimeoutExpired(["sleep", "31"], 30)
with pytest.raises(subprocess.TimeoutExpired):
run_cmd(["sleep", "31"])

Comment thread scripts/get_pr_status.py

state = data.get("state")
review = data.get("reviewDecision") or "NONE"
checks = data.get("statusCheckRollup", [])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

If statusCheckRollup is present in the JSON but has a null value (which is common when there are no status checks), data.get("statusCheckRollup", []) will return None instead of []. This will cause a TypeError when calling len(checks) or iterating over checks.

Using data.get("statusCheckRollup") or [] ensures checks is always a list.

Suggested change
checks = data.get("statusCheckRollup", [])
checks = data.get("statusCheckRollup") or []

Comment thread scripts/get_pr_status.py
Comment on lines +38 to +40
conclusion = check.get("conclusion") or check.get("state")
if conclusion in ["SUCCESS", "CLEAN"]:
success_count += 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

CLEAN is a merge state status (e.g., mergeStateStatus), not a valid status check state or conclusion. The valid successful states/conclusions for status checks are SUCCESS (and potentially SKIPPED or NEUTRAL). Checking for CLEAN here is incorrect and will not match any actual status check.

Suggested change
conclusion = check.get("conclusion") or check.get("state")
if conclusion in ["SUCCESS", "CLEAN"]:
success_count += 1
conclusion = check.get("conclusion") or check.get("state")
if conclusion in ["SUCCESS", "SKIPPED", "NEUTRAL"]:
success_count += 1

Comment on lines +29 to +33
"statusCheckRollup": [
{"conclusion": "SUCCESS", "name": "test1"},
{"state": "CLEAN", "name": "test2"},
{"conclusion": "FAILURE", "name": "test3"}
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Update the mocked status check data to use a valid state/conclusion (such as SUCCESS or SKIPPED) instead of CLEAN, which is a merge state status rather than a status check state.

Suggested change
"statusCheckRollup": [
{"conclusion": "SUCCESS", "name": "test1"},
{"state": "CLEAN", "name": "test2"},
{"conclusion": "FAILURE", "name": "test3"}
]
"statusCheckRollup": [
{"conclusion": "SUCCESS", "name": "test1"},
{"state": "SUCCESS", "name": "test2"},
{"conclusion": "FAILURE", "name": "test3"}
]

Comment thread scripts/get_pr_status.py
Comment on lines +46 to +47
except subprocess.CalledProcessError as e:
print(f"Error: Failed to fetch PR status: {e.stderr.strip()}", file=sys.stderr)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If e.stderr is None (which can happen if CalledProcessError is raised without a stderr string, e.g., in some mock scenarios or custom exceptions), calling e.stderr.strip() will raise an AttributeError.

Using (e.stderr or "").strip() prevents potential crashes.

Suggested change
except subprocess.CalledProcessError as e:
print(f"Error: Failed to fetch PR status: {e.stderr.strip()}", file=sys.stderr)
except subprocess.CalledProcessError as e:
stderr_msg = (e.stderr or "").strip()
print(f"Error: Failed to fetch PR status: {stderr_msg}", file=sys.stderr)

@sheepdestroyer

Copy link
Copy Markdown
Owner Author

@jules

  • There are unaddressed Reviews & Comments on this PR#
    Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.
    Make sure you did not miss any reviews or comments.

Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@users.noreply.github.com>
@sheepdestroyer

Copy link
Copy Markdown
Owner Author

@jules

  • This branch has conflicts that must be resolved. Merge master changes & Resolve all conflicts before continuing.

Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@users.noreply.github.com>
@sheepdestroyer

Copy link
Copy Markdown
Owner Author

@jules

  • This branch has conflicts that must be resolved. Merge master changes & Resolve all conflicts before continuing.

Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@users.noreply.github.com>
@sheepdestroyer

Copy link
Copy Markdown
Owner Author

@jules

  • This branch has conflicts that must be resolved. Merge master changes & Resolve all conflicts before continuing.

Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@users.noreply.github.com>
@sheepdestroyer

Copy link
Copy Markdown
Owner Author

@jules

  • This branch has conflicts that must be resolved. Merge master changes & Resolve all conflicts before continuing.

google-labs-jules Bot and others added 3 commits July 1, 2026 12:56
Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@users.noreply.github.com>
…6831 & resolve conflicts by tracking scripts/get_pr_status.py and ignoring root get_pr_status.py
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.

[Maintenance] Add unit tests for scripts/get_pr_status.py and resolve placeholder status

1 participant