Test pagination in resolve flow - #137
Conversation
Reviewer's GuideAdds an integration test that simulates paginated GraphQL responses for the resolve command, verifying that multiple pages of review comments are fetched and the appropriate number of GraphQL calls are made. File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
Warning Rate limit exceeded@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 38 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
Summary by CodeRabbit
WalkthroughIntroduce a pagination-driven test harness for resolve flows and a MITM capture helper: add a Page model and run_resolve_flow in Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant T as Test Runner
participant V as vk CLI
participant M as MITM Capture Server
participant H as CaptureHandler (test-provided)
Note over T,M: Test starts MITM capture and supplies a CaptureHandler
T->>M: Start server, register CaptureHandler
T->>V: Spawn vk_cmd resolve flow
V->>M: POST /graphql (query page 1)
M->>H: Reconstructed Request<Bytes> passed to handler
H-->>M: Respond with page 1 (hasNextPage=true, endCursor="c1")
M-->>V: Page 1 response
V->>M: POST /graphql (query with after="c1")
M->>H: Reconstructed Request<Bytes> passed to handler
H-->>M: Respond with final page (no next cursor)
M-->>V: Final page response
V->>M: POST /graphql (resolveReviewThread mutation)
M->>H: Reconstructed Request<Bytes> passed to handler
H-->>M: Respond with resolve mutation payload
M-->>V: Mutation response
T->>M: Shutdown and collect captured calls
M-->>T: Return recorded POST /graphql calls count
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (1)
tests/resolve.rs(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (AGENTS.md)
**/*.rs: Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Place function attributes after doc comments.
Do not usereturnin single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Prefer immutable data and avoid unnecessarymutbindings.
Handle errors with theResulttype instead of panicking where feasible.
Prefer semantic error enums: Derivestd::error::Error(via thethiserrorcrate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Useeyre::Reportfor human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and toeyreonly in the mainmain()entrypoint or top-level async task.
Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider usingArcto reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Avoidunsafecode unless absolutely necessary and document any usage clearly.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Preferexpectoverallow.
Prefer.expect()over.unwrap().
Useconcat!()to combine long string literals rather than escaping newlines with a backslash.
Files:
tests/resolve.rs
⚙️ CodeRabbit configuration file
**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.
Adhere to single responsibility and CQRS
Place function attributes after doc comments.
Do not use
returnin single-line functions.Move conditionals with >2 branches into a predicate function.
Avoid
unsafeunless absolutely necessary.Every module must begin with a
//!doc comment that explains the module's purpose and utility.Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
Lints must not be silenced except as a last resort.
#[allow]is forbidden.- Only narrowly scoped
#[expect(lint, reason = "...")]is allowed.- No lint groups, no blanket or file-wide suppression.
- Include
FIXME:with link if a fix is expected.Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.
Use
rstestfixtures for shared setup and to avoid repetition between tests.Replace duplicated tests with
#[rstest(...)]parameterised cases.Prefer
mockallfor mocks/stubs.Prefer
.expect()over.unwrap()Ensure that any API or behavioural changes are reflected in the documentation in
docs/Ensure that any completed roadmap steps are recorded in the appropriate roadmap in
docs/Files must not exceed 400 lines in length
- Large modules must be decomposed
- Long match statements or dispatch tables should be decomposed by domain and collocated with targets
- Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such
- For testing of functionality depending upon environment variables, dependency injection and the
mockablecrate are the preferred option.- If mockable cannot be used, env mutations in tests ...
Files:
tests/resolve.rs
🧬 Code graph analysis (1)
tests/resolve.rs (1)
tests/utils/mod.rs (3)
shutdown(30-33)start_mitm(49-98)vk_cmd(109-117)
🔍 Remote MCP Ref
Additional context (concise)
- PR #137 (codex/add-test-for-pagination-in-get_thread_id → main) adds an integration test that exercises pagination in the resolve flow and references/closes issue #130.
- File changed: tests/resolve.rs (branch) — new test resolve_flows_paginates added; it drives the same vk resolve command used by existing tests but with a mocked MITM GitHub /graphql endpoint.
- Mock behavior in the test (sequenced by a shared gql_calls counter): (1) first POST /graphql returns a page with endCursor "c1" and hasNextPage=true; (2) second POST returns a page with hasNextPage=false; (3) subsequent POST(s) return the resolveReviewThread mutation response. The test asserts three POST /graphql requests were observed.
- The test reuses existing test infra (start_mitm, vk_cmd, Response builder) and leaves the original resolve_flows logic intact while exercising the pagination loop/cursor path.
- PR includes standard test hygiene steps (make fmt, make lint, make test) in the description.
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: Sourcery review
- GitHub Check: unstable-rest-resolve
- GitHub Check: build-test
🔇 Additional comments (1)
tests/resolve.rs (1)
55-74: Exercise two-page pagination and mutation — LGTMMock sequencing via
match gql_callscorrectly drives: page 1 (hasNextPage=true) → page 2 (target found) → mutation. This hits the pagination path end-to-end.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tests/resolve.rs (1)
58-111: Strengthen the pagination assertion and remove O(n) pops.
- Parse the GraphQL body and assert variables.after equals the previous endCursor (and is absent on the first call) rather than doing a substring match.
- Use VecDeque + pop_front() instead of remove(0) to avoid O(n) shifts.
Apply this diff:
- let pages = Arc::new(Mutex::new(pages)); + let pages = Arc::new(Mutex::new(std::collections::VecDeque::from(pages))); @@ - if let Some(ref cursor) = *after { - let body_str = std::str::from_utf8(req.body().as_ref()).expect("utf8 body"); - assert!( - body_str.contains(&format!("\"after\":\"{cursor}\"")), - "second page query must include after={cursor}; got body: {body_str}" - ); - } + // Assert 'after' presence/absence structurally. + let body_bytes = req.body().as_ref(); + let v: serde_json::Value = + serde_json::from_slice(body_bytes).expect("JSON body for /graphql"); + let got_after = v + .pointer("/variables/after") + .and_then(|x| x.as_str()) + .map(ToOwned::to_owned); + match after.as_deref() { + Some(cursor) => assert_eq!( + got_after.as_deref(), + Some(cursor), + "query must include variables.after={cursor}; got: {v}" + ), + None => assert!( + got_after.is_none(), + "first page query must not include variables.after; got: {v}" + ), + } @@ - if pages.is_empty() { + if pages.is_empty() { r#"{"data":{"resolveReviewThread":{"clientMutationId":null}}}"#.to_owned() } else { - let page = pages.remove(0); + let page = pages.pop_front().expect("non-empty script"); *after = page.end_cursor.map(std::string::ToString::to_string); page.body() }Add outside the diff:
use std::collections::VecDeque; use serde_json::Value;Run this to verify no regressions and Clippy happiness:
#!/bin/bash set -euo pipefail cargo test -q --features unstable-rest-resolve cargo clippy --features unstable-rest-resolve -- -D warnings
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (2)
tests/resolve.rs(2 hunks)tests/utils/mod.rs(2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.rs
📄 CodeRabbit inference engine (AGENTS.md)
**/*.rs: Clarity over cleverness: favour explicit, readable Rust over terse or obscure idioms
Use functions and composition; extract reusable logic; prefer declarative iterator-based code when readable
Keep functions small, single-responsibility, and obey command/query segregation
Name things precisely; use is/has/should prefixes for booleans
Use consistent en-GB-oxendict spelling and grammar in code comments (except external API references)
Function documentation must include clear examples; omit redundant examples in test docs
Keep code files ≤ 400 lines; split long switches/dispatch tables; move large test data to external files
Disallow Clippy warnings; fix warnings in code instead of silencing
Extract helper functions when functions are too long; maintain separation of concerns and CQRS
Group numerous related parameters into meaningful structs
Consider using Arc for large error values to reduce returned data size
Begin every module with a module-level //! comment describing purpose and utility
Document public APIs with /// Rustdoc so cargo doc can generate docs
Prefer immutable data; avoid unnecessary mut
Use Result for error handling; avoid panicking where feasible
Avoid unsafe unless absolutely necessary; document any usage clearly
Place function attributes after doc comments
Do not use return in single-line functions
Use predicate functions for conditionals with more than two branches
Do not silence lints except as a last resort
Scope lint suppressions narrowly and include a clear reason
Prefer #[expect(...)] over #[allow(...)] for lint suppression
Prefer .expect() over .unwrap()
Use concat!() for long string literals instead of backslash newline escapes
Prefer semantic error enums deriving std::error::Error via thiserror for caller-inspectable conditions
Never export eyre::Report from libraries; convert to domain error enums at API boundaries; use eyre only in main()/top-level async task
Files:
tests/resolve.rstests/utils/mod.rs
⚙️ CodeRabbit configuration file
**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.
Adhere to single responsibility and CQRS
Place function attributes after doc comments.
Do not use
returnin single-line functions.Move conditionals with >2 branches into a predicate function.
Avoid
unsafeunless absolutely necessary.Every module must begin with a
//!doc comment that explains the module's purpose and utility.Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
Lints must not be silenced except as a last resort.
#[allow]is forbidden.- Only narrowly scoped
#[expect(lint, reason = "...")]is allowed.- No lint groups, no blanket or file-wide suppression.
- Include
FIXME:with link if a fix is expected.Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.
Use
rstestfixtures for shared setup and to avoid repetition between tests.Replace duplicated tests with
#[rstest(...)]parameterised cases.Prefer
mockallfor mocks/stubs.Prefer
.expect()over.unwrap()Ensure that any API or behavioural changes are reflected in the documentation in
docs/Ensure that any completed roadmap steps are recorded in the appropriate roadmap in
docs/Files must not exceed 400 lines in length
- Large modules must be decomposed
- Long match statements or dispatch tables should be decomposed by domain and collocated with targets
- Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such
- For testing of functionality depending upon environment variables, dependency injection and the
mockablecrate are the preferred option.- If mockable cannot be used, env mutations in tests ...
Files:
tests/resolve.rstests/utils/mod.rs
{src,tests}/**/*.rs
📄 CodeRabbit inference engine (AGENTS.md)
{src,tests}/**/*.rs: Write unit and behavioural tests for new functionality; run both before and after changes
Use an opaque error (eyre::Report) only at app boundary; not in public APIs
Files:
tests/resolve.rstests/utils/mod.rs
tests/**/*.rs
📄 CodeRabbit inference engine (AGENTS.md)
tests/**/*.rs: Use rstest fixtures for shared setup
Replace duplicated tests with #[rstest(...)] parameterised cases
Prefer mockall for mocks/stubs
Files:
tests/resolve.rstests/utils/mod.rs
🧬 Code graph analysis (1)
tests/resolve.rs (1)
tests/utils/mod.rs (4)
start_mitm(53-102)start_mitm_capture(118-174)vk_cmd(184-192)shutdown(34-37)
🔍 Remote MCP Ref
Summary of additional relevant context for review
-
PR adds a parameterized integration test to exercise GraphQL pagination in the resolve flow (tests/resolve.rs). The test introduces a Page model and run_resolve_flow to simulate paginated /graphql responses and asserts the number of POST /graphql calls when the target comment is on a later page.
-
Tests reuse and extend the MITM test harness by introducing start_mitm_capture (tests/utils/mod.rs) and a CaptureHandler type so tests can capture and inspect request bodies (service rebuilds Request and delegates to the CaptureHandler). This enables assertions on GraphQL request payloads in the pagination test.
-
The new test replaces the previous hard-coded two-call resolve test with an rstest parameterized case set:
- no_pagination: single final page -> expect 2 GraphQL calls
- two_pages: one page with endCursor and a final page -> expect 3 GraphQL calls
The test asserts observed POST /graphql calls equal expected_posts.
-
No public API changes; edits are test-only and add test helper exports (CaptureHandler, start_mitm_capture). PR closes issue #130 (add test coverage for pagination when target comment appears on later page).
Files / locations to inspect in review
- tests/resolve.rs — new Page struct, run_resolve_flow, parameterized tests.
- tests/utils/mod.rs — CaptureHandler type alias and start_mitm_capture implementation.
- Existing tests referencing start_mitm to ensure no regressions where start_mitm_capture is now used.
Caveats / review focuses
- Ensure start_mitm_capture shutdown semantics and error handling mirror start_mitm to avoid test flakiness.
- Verify request body rebuilding (Request) preserves headers/method/path expected by existing handlers.
- Confirm tests clean up/shutdown servers to avoid port conflicts across test runs.
Sources
- PR file listing and diffs for PR #137
🔇 Additional comments (5)
tests/resolve.rs (2)
12-12: Imports look correct for the new capture flow—LGTM.
113-119: Parameterise the resolve-flow test—LGTM.Readable cases and expected call counts clearly exercise the pagination loop.
tests/utils/mod.rs (3)
22-25: CaptureHandler alias is appropriate—LGTM.The bounds (Fn + Send + Sync) match the capture server’s usage.
118-174: Propagate only immutable access to the handler; avoid needless mutability.Lock the handler as immutable (as you already do) and keep the Fn bound; this is consistent and thread-safe. No changes required here beyond the lint fix above.
Confirm parity with start_mitm by running both servers in a smoke test:
#!/bin/bash set -euo pipefail rg -n 'start_mitm\(|start_mitm_capture\(' tests -g '!**/target/**'
113-117: Replace broad #[allow(...)] with narrowly scoped #[expect(...)] or remove itFile: tests/utils/mod.rs (lines 113–117). Remove the #[allow(dead_code, clippy::type_complexity, reason = "used only in some tests")] attribute. Keep the existing #[expect(clippy::integer_division_remainder_used, reason = "tokio::select! uses % internally")] and add a targeted #[expect(clippy::type_complexity, reason = "public alias CaptureHandler documents the type")] only if Clippy still emits that warning. Run cargo clippy -- -D warnings to verify.
-#[allow(dead_code, clippy::type_complexity, reason = "used only in some tests")] -#[expect( - clippy::integer_division_remainder_used, - reason = "tokio::select! uses % internally" -)] +#[expect( + clippy::integer_division_remainder_used, + reason = "tokio::select! uses % internally" +)] +#[expect( + clippy::type_complexity, + reason = "public alias CaptureHandler documents the type" +)]
Summary
Testing
make fmtmake lintmake testcloses #130
https://chatgpt.com/codex/tasks/task_e_68c45cf54cf48322a9cb8eb0350bdf5b
Summary by Sourcery
Tests: