Skip to content

Reduce test helper duplication using macros#243

Merged
leynos merged 6 commits intomainfrom
codex/refactor-forwarding-functions-with-macros
Aug 3, 2025
Merged

Reduce test helper duplication using macros#243
leynos merged 6 commits intomainfrom
codex/refactor-forwarding-functions-with-macros

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 1, 2025

Summary

  • define forward_default! and forward_with_capacity! macros
  • use these macros to generate the forwarding helpers in wireframe_testing

Testing

  • make fmt
  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_688cd80f49288322a8d2a89c0849b68e

Summary by Sourcery

Introduce macros to consolidate and auto-generate test helper functions in wireframe_testing, eliminating repetitive boilerplate

Enhancements:

  • Define forward_default! and forward_with_capacity! macros to abstract common forwarding patterns with and without capacity parameters
  • Replace explicit drive_* and run_app_* helper implementations with concise macro invocations
  • Remove duplicated async helper code and streamline the test helpers module

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 1, 2025

Reviewer's Guide

This PR abstracts repetitive async helper functions in wireframe_testing by introducing two macros (forward_default! and forward_with_capacity!) to generate forwarding functions, replacing explicit implementations with concise macro invocations.

File-Level Changes

Change Details Files
Define forward_default! macro for default-capacity forwarding functions
  • Added macro pattern matching for function name, docs, vis, args, and return type
  • Injected generic bounds (S: TestSerializer, C: Send + 'static, E: Packet)
  • Forwarded calls to _with_capacity variants with DEFAULT_CAPACITY
wireframe_testing/src/helpers.rs
Define forward_with_capacity! macro for capacity-parameterized forwarding
  • Added macro pattern matching for capacity argument
  • Injected same generic bounds as default macro
  • Forwarded calls directly to inner helpers with provided capacity
wireframe_testing/src/helpers.rs
Replace explicit async helper functions with macro invocations
  • Removed manual implementations of drive_with_* and run_app_with_* variants
  • Replaced them with forward_default! or forward_with_capacity! calls retaining docs
  • Ensured all original docs and signatures are preserved via macros
wireframe_testing/src/helpers.rs

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
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 1, 2025

Summary by CodeRabbit

  • Refactor
    • Streamlined internal helper functions for app testing, reducing repetitive code while maintaining existing functionality and documentation.
  • Chores
    • Updated the ignore list to exclude files or directories named .crush.
    • Added a new, currently empty, documentation file.
  • Style
    • Improved formatting in documentation for better readability.

Walkthrough

Refactor the asynchronous helper functions in wireframe_testing/src/helpers.rs by replacing explicit function definitions with two macros: forward_default! and forward_with_capacity!. These macros generate forwarding async functions, centralising repetitive patterns and preserving original documentation and signatures without altering behaviour.

Changes

Cohort / File(s) Change Summary
Async Helper Refactor (Macroisation)
wireframe_testing/src/helpers.rs
Replace all explicit async helper functions with macro-generated equivalents using forward_default! and forward_with_capacity! macros. Remove boilerplate while keeping function signatures, documentation, and logic unchanged. Add the two new macros to generate the forwarding functions.
Git Ignore Update
.gitignore
Add .crush pattern to ignore files or directories named .crush in the repository.
New Empty Documentation File
CRUSH.md
Add new empty documentation file named CRUSH.md.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Code
    participant Helpers as Macro-Generated Helper
    participant Impl as Underlying Implementation

    Test->>Helpers: Call drive_with_frame(...)
    Helpers->>Impl: Forward call with default capacity
    Impl-->>Helpers: Return result
    Helpers-->>Test: Return result
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Poem

Macros march in, boilerplate out,
Async helpers streamlined, without a doubt.
Forwarding flows, as clean as can be,
Less code to write, more time for tea!
🦀✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/refactor-forwarding-functions-with-macros

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @leynos - I've reviewed your changes and found some issues that need to be addressed.

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `wireframe_testing/src/helpers.rs:36` </location>
<code_context>
-    E: Packet,
-{
-    drive_with_frame_with_capacity(app, frame, DEFAULT_CAPACITY).await
+macro_rules! forward_default {
+    (
+        $(#[$docs:meta])* $vis:vis fn $name:ident(
</code_context>

<issue_to_address>
Consider removing the forwarding macros and writing each forwarding function as a simple one-liner directly.

Here’s a concrete way to collapse all of this indirection back down into plain one-liner functions (you can rip out both `forward_default!` and `forward_with_capacity!` entirely—each forwarding fn is trivial enough to just write out):

```rust
/// Drive `app` with a single length-prefixed `frame` and return the bytes produced by the server.
pub async fn drive_with_frame<S, C, E>(
    app: WireframeApp<S, C, E>,
    frame: Vec<u8>,
) -> io::Result<Vec<u8>>
where
    S: TestSerializer,
    C: Send + 'static,
    E: Packet,
{
    drive_with_frame_with_capacity(app, frame, DEFAULT_CAPACITY).await
}

/// Drive `app` with a single frame using a duplex buffer of `capacity` bytes.
pub async fn drive_with_frame_with_capacity<S, C, E>(
    app: WireframeApp<S, C, E>,
    frame: Vec<u8>,
    capacity: usize,
) -> io::Result<Vec<u8>>
where
    S: TestSerializer,
    C: Send + 'static,
    E: Packet,
{
    drive_with_frames_with_capacity(app, vec![frame], capacity).await
}

/// Drive `app` with multiple frames using the default buffer size.
pub async fn drive_with_frames<S, C, E>(
    app: WireframeApp<S, C, E>,
    frames: Vec<Vec<u8>>,
) -> io::Result<Vec<u8>>
where
    S: TestSerializer,
    C: Send + 'static,
    E: Packet,
{
    drive_with_frames_with_capacity(app, frames, DEFAULT_CAPACITY).await
}
```

Repeat the same pattern for the `*_mut` and `run_*` variants. This removes two nearly-identical macros and makes each forwarder immediately obvious.
</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 wireframe_testing/src/helpers.rs
@leynos leynos force-pushed the codex/refactor-forwarding-functions-with-macros branch from f34dfd4 to 27119d6 Compare August 1, 2025 20:57
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (2)
wireframe_testing/src/helpers.rs (2)

121-131: Remove duplicate function definition causing compilation error.

This explicit function definition conflicts with the macro-generated version at lines 158-176, causing compiler error E0428. Remove this duplicate definition to resolve the compilation failure.

-/// Drive `app` with a single length-prefixed `frame` and return the bytes
-/// produced by the server.
-///
-/// The app runs on an in-memory duplex stream so tests need not open real
-/// sockets.
-///
-/// ```rust
-/// # use wireframe_testing::{drive_with_frame, processor};
-/// # use wireframe::app::WireframeApp;
-/// # async fn demo() -> tokio::io::Result<()> {
-/// let app = WireframeApp::new().frame_processor(processor()).unwrap();
-/// let bytes = drive_with_frame(app, vec![1, 2, 3]).await?;
-/// # Ok(())
-/// # }
-/// ```
-pub async fn drive_with_frame<S, C, E>(
-    app: WireframeApp<S, C, E>,
-    frame: Vec<u8>,
-) -> io::Result<Vec<u8>>
-where
-    S: TestSerializer,
-    C: Send + 'static,
-    E: Packet,
-{
-    drive_with_frame_with_capacity(app, frame, DEFAULT_CAPACITY).await
-}

158-422: Implement missing run_app_with_frames_with_capacity or revert to explicit forwarding fns

The macros generate run_app_with_frames_with_capacity calls, but no such async fn exists in wireframe_testing/src/helpers.rs. This causes compilation failures and reduces clarity. Either:

• Add an async implementation for
pub async fn run_app_with_frames_with_capacity<S, C, E>(…)-> io::Result<Vec<u8>>
mirroring your drive_with_frames_with_capacity (i.e. call run_app_internal or equivalent).
• Or remove the forward_* macros for the run_app_* fns and replace them with simple one-liner fwd functions.

Pinpoint in code:

  • Missing definition for run_app_with_frames_with_capacity (referenced by both forward_with_capacity! and forward_default!).
♻️ Duplicate comments (2)
wireframe_testing/src/helpers.rs (2)

36-57: Reconsider macro complexity in favour of simple forwarding functions.

This macro adds significant complexity for minimal benefit. The past review comment suggests replacing these macros with simple one-liner forwarding functions, which would be more readable and maintainable.


133-156: Reconsider macro complexity in favour of simple forwarding functions.

This macro similarly adds unnecessary complexity. Simple async forwarding functions would be more straightforward and align with the previous reviewer's recommendation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5e850f5 and 27119d6.

📒 Files selected for processing (1)
  • wireframe_testing/src/helpers.rs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: 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 using Arc to reduce the amount of data returned.
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.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for 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 to eyre only in the main main() entrypoint or top-level async task.

Files:

  • wireframe_testing/src/helpers.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 return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless 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.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for 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.

Files:

  • wireframe_testing/src/helpers.rs
🪛 GitHub Actions: CI
wireframe_testing/src/helpers.rs

[error] 121-121: Rust compiler error E0428: the name drive_with_frame is defined multiple times.

Comment thread wireframe_testing/src/helpers.rs
@leynos leynos force-pushed the codex/refactor-forwarding-functions-with-macros branch from 89017d9 to 2d5ec04 Compare August 3, 2025 21:57
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
CRUSH.md (1)

31-31: Correct the spelling error.

"managable" should be "manageable".

-  - **Keep file size managable.** No single code file may be longer than 400
+  - **Keep file size manageable.** No single code file may be longer than 400
♻️ Duplicate comments (3)
wireframe_testing/src/helpers.rs (3)

36-57: Reconsider the macro complexity based on past feedback.

Previous review feedback suggested removing these forwarding macros in favour of simple one-liner functions. The macros add indirection and complexity for what are essentially trivial forwarding calls.

Replace the macro with direct function implementations as suggested in the previous review.


107-130: Apply the same simplification to this macro.

Like the first macro, this adds unnecessary complexity for simple forwarding functions.

Replace with direct function implementations as previously suggested.


377-377: Replace #[allow(dead_code)] with #[expect] or remove entirely.

The coding guidelines forbid #[allow] attributes. Use #[expect(dead_code, reason = "...")] with clear justification, or remove if the function is actually needed.

-    #[allow(dead_code)]
+    #[expect(dead_code, reason = "FIXME: determine if this function is actually needed")]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 27119d6 and 2d5ec04.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • .gitignore (1 hunks)
  • CRUSH.md (1 hunks)
  • wireframe_testing/src/helpers.rs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.md: Documentation must use en-GB-oxendict spelling and grammar. (EXCEPTION: the naming of the LICENSE file, which is to be left unchanged for community consistency.)
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks in Markdown files must be wrapped at 120 columns.
Tables and headings in Markdown files must not be wrapped.
Use dashes (-) for list bullets in Markdown files.
Use GitHub-flavoured Markdown footnotes ([^1]) for references and footnotes.

Files:

  • CRUSH.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Paragraphs and bullets must be wrapped to 80 columns, except where a long URL would prevent this (in which case, silence MD013 for that line)
  • Code blocks should be wrapped to 120 columns.
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • CRUSH.md
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Function documentation must include clear examples demonstrating the usage and outcome of the function. Test documentation should omit examples where the example serves only to reiterate the test logic.
No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents colocated with targets. Large blocks of test data should be moved to external data files.
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 using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
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.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums. Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status....

Files:

  • wireframe_testing/src/helpers.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 return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless 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.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for 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.

Files:

  • wireframe_testing/src/helpers.rs
🪛 GitHub Actions: CI
wireframe_testing/src/helpers.rs

[warning] 103-103: cargo fmt formatting check failed. Diff detected at line 103. Run 'cargo fmt --all' to fix code style issues.

🔇 Additional comments (1)
.gitignore (1)

3-3: LGTM!

The addition of .crush to the gitignore is appropriate and correctly formatted.

Comment thread wireframe_testing/src/helpers.rs
Comment thread wireframe_testing/src/helpers.rs
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (4)
wireframe_testing/src/helpers.rs (4)

36-57: Remove the macro and implement forwarding functions directly.

Past feedback explicitly requested removing forwarding macros in favour of simple one-liner functions. The macro adds unnecessary complexity for trivial async forwarding calls.

Replace this macro with direct function implementations as suggested in previous reviews.


106-129: Remove the macro and implement forwarding functions directly.

This macro suffers from the same complexity issues as forward_default!. Direct async function implementations are clearer and easier to maintain.

Replace this macro with direct function implementations as suggested in previous reviews.


131-149: Replace macro-generated function with direct implementation.

Following previous feedback, implement this as a simple one-liner instead of using the macro.

-forward_default! {
-    /// Drive `app` with a single length-prefixed `frame` and return the bytes
-    /// produced by the server.
-    ///
-    /// The app runs on an in-memory duplex stream so tests need not open real
-    /// sockets.
-    ///
-    /// ```rust
-    /// # use wireframe_testing::{drive_with_frame, processor};
-    /// # use wireframe::app::WireframeApp;
-    /// # async fn demo() -> tokio::io::Result<()> {
-    /// let app = WireframeApp::new().frame_processor(processor()).unwrap();
-    /// let bytes = drive_with_frame(app, vec![1, 2, 3]).await?;
-    /// # Ok(())
-    /// # }
-    /// ```
-    pub fn drive_with_frame(app: WireframeApp<S, C, E>, frame: Vec<u8>) -> io::Result<Vec<u8>>
-    => drive_with_frame_with_capacity(app, frame)
-}
+/// Drive `app` with a single length-prefixed `frame` and return the bytes
+/// produced by the server.
+///
+/// The app runs on an in-memory duplex stream so tests need not open real
+/// sockets.
+///
+/// ```rust
+/// # use wireframe_testing::{drive_with_frame, processor};
+/// # use wireframe::app::WireframeApp;
+/// # async fn demo() -> tokio::io::Result<()> {
+/// let app = WireframeApp::new().frame_processor(processor()).unwrap();
+/// let bytes = drive_with_frame(app, vec![1, 2, 3]).await?;
+/// # Ok(())
+/// # }
+/// ```
+pub async fn drive_with_frame<S, C, E>(
+    app: WireframeApp<S, C, E>,
+    frame: Vec<u8>,
+) -> io::Result<Vec<u8>>
+where
+    S: TestSerializer,
+    C: Send + 'static,
+    E: Packet,
+{
+    drive_with_frame_with_capacity(app, frame, DEFAULT_CAPACITY).await
+}

376-376: Replace #[allow(dead_code)] with #[expect] or remove the attribute.

The coding guidelines forbid #[allow] attributes. Use #[expect(dead_code, reason = "...")] with a clear justification, or remove the attribute entirely if the function is genuinely needed.

-    #[allow(dead_code)]
+    #[expect(dead_code, reason = "FIXME: determine if this function is actually needed")]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d5ec04 and d3de319.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • AGENTS.md (1 hunks)
  • wireframe_testing/src/helpers.rs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.md: Documentation must use en-GB-oxendict spelling and grammar. (EXCEPTION: the naming of the LICENSE file, which is to be left unchanged for community consistency.)
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks in Markdown files must be wrapped at 120 columns.
Tables and headings in Markdown files must not be wrapped.
Use dashes (-) for list bullets in Markdown files.
Use GitHub-flavoured Markdown footnotes ([^1]) for references and footnotes.

Files:

  • AGENTS.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Paragraphs and bullets must be wrapped to 80 columns, except where a long URL would prevent this (in which case, silence MD013 for that line)
  • Code blocks should be wrapped to 120 columns.
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • AGENTS.md
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Function documentation must include clear examples demonstrating the usage and outcome of the function. Test documentation should omit examples where the example serves only to reiterate the test logic.
No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents colocated with targets. Large blocks of test data should be moved to external data files.
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 using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
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.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums. Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status....

Files:

  • wireframe_testing/src/helpers.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 return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless 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.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for 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.

Files:

  • wireframe_testing/src/helpers.rs
🧠 Learnings (4)
📚 Learning: keep file size manageable. no single code file may be longer than 400 lines. long switch statements ...
Learnt from: CR
PR: leynos/femtologging#0
File: AGENTS.md:0-0
Timestamp: 2025-07-28T19:14:46.188Z
Learning: Keep file size manageable. No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents colocated with targets. Large blocks of test data should be moved to external data files.

Applied to files:

  • AGENTS.md
📚 Learning: keep file size manageable: no single code file may be longer than 400 lines. long switch statements ...
Learnt from: CR
PR: leynos/vk#0
File: AGENTS.md:0-0
Timestamp: 2025-07-27T00:37:06.651Z
Learning: Keep file size manageable: No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents colocated with targets. Large blocks of test data should be moved to external data files.

Applied to files:

  • AGENTS.md
📚 Learning: keep file size manageable: no single code file may be longer than 400 lines. long switch statements ...
Learnt from: CR
PR: leynos/mdtablefix#0
File: AGENTS.md:0-0
Timestamp: 2025-08-03T19:10:35.310Z
Learning: Keep file size manageable: No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents co-located with targets. Large blocks of test data should be moved to external data files.

Applied to files:

  • AGENTS.md
📚 Learning: applies to **/*.rs : no single code file may be longer than 400 lines. long switch statements or dis...
Learnt from: CR
PR: leynos/wireframe#0
File: AGENTS.md:0-0
Timestamp: 2025-08-03T14:15:20.583Z
Learning: Applies to **/*.rs : No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents colocated with targets. Large blocks of test data should be moved to external data files.

Applied to files:

  • AGENTS.md
⏰ Context from checks skipped due to timeout of 240000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-test
🔇 Additional comments (1)
AGENTS.md (1)

33-33: LGTM! Formatting improvement enhances readability.

The added blank line properly separates the file size limit guideline from its elaboration, improving document structure.

Comment thread wireframe_testing/src/helpers.rs
@leynos leynos merged commit e085c92 into main Aug 3, 2025
5 checks passed
@leynos leynos deleted the codex/refactor-forwarding-functions-with-macros branch August 3, 2025 22:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant