Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(client): use command's configured output #22334

Merged
merged 1 commit into from
Oct 22, 2024

Conversation

mark-rushakoff
Copy link
Member

@mark-rushakoff mark-rushakoff commented Oct 22, 2024

Description

I have some external tests that invoke some of the SDK's cobra commands. Those tests often involve creating the command, calling cmd.SetOutput, executing the command, and then inspecting its output.

This change updates the client context to prefer cmd.Output if set (which should only happen in tests), falling back to stdout otherwise; so it should not change any existing client-facing behavior, but it does otherwise make command output testable.

Summary by CodeRabbit

  • New Features

    • Enhanced command context to include output capabilities, improving how outputs are handled in the application.
  • Tests

    • Introduced a new test to verify command output when using the updated context, ensuring reliability in output handling.

I have some external tests that invoke some of the SDK's cobra commands.
Those tests often involve creating the command, calling cmd.SetOutput,
executing the command, and then inspecting its output.

This change updates the client context to prefer cmd.Output if set
(which should only happen in tests), falling back to stdout otherwise;
so it should not change any existing client-facing behavior, but it does
otherwise make command output testable.
Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications to the GetClientTxContext function in client/cmd.go, enhancing the context retrieval by adding output capabilities. Additionally, a new test function, TestContext_usesCobraCommandOutput, is introduced in client/cmd_test.go to validate the command output when executed with the updated context. These changes improve the handling of command output without altering existing logic or error handling.

Changes

File Change Summary
client/cmd.go Modified GetClientTxContext to include output stream from command: ctx := GetClientContextFromCmd(cmd).WithOutput(cmd.OutOrStdout())
client/cmd_test.go Added new test function TestContext_usesCobraCommandOutput to verify command output handling.

Suggested labels

backport/v0.52.x

Suggested reviewers

  • akhilkumarpilli
  • testinginprod

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

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
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: 0

🧹 Outside diff range and nitpick comments (1)
client/cmd_test.go (1)

142-165: Consider enhancing test coverage

While the current test case is good, consider adding:

  1. Test documentation explaining the test's purpose
  2. Negative test cases (e.g., when PrintString returns an error)
  3. Additional test cases with different output content

Example enhancement:

+// TestContext_usesCobraCommandOutput verifies that the client context correctly
+// uses the cobra command's configured output when printing strings.
 func TestContext_usesCobraCommandOutput(t *testing.T) {
     var initCtx client.Context
+
+    testCases := []struct {
+        name           string
+        outputContent  string
+        expectedError  bool
+    }{
+        {"basic output", "hello", false},
+        {"empty output", "", false},
+        {"multiline output", "hello\nworld", false},
+    }
+
+    for _, tc := range testCases {
+        t.Run(tc.name, func(t *testing.T) {
             cmd := &cobra.Command{
                 PreRunE: func(cmd *cobra.Command, args []string) error {
                     return client.SetCmdClientContextHandler(initCtx, cmd)
                 },
                 RunE: func(cmd *cobra.Command, _ []string) error {
                     cctx, err := client.GetClientTxContext(cmd)
                     if err != nil {
                         return err
                     }
-                    return cctx.PrintString("hello")
+                    return cctx.PrintString(tc.outputContent)
                 },
             }
             var outBuf bytes.Buffer
             cmd.SetOutput(&outBuf)
             require.NoError(t, cmd.Execute())
-            require.Equal(t, "hello", outBuf.String())
+            require.Equal(t, tc.outputContent, outBuf.String())
+        })
+    }
 }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cd3ce0c and e3b626c.

📒 Files selected for processing (2)
  • client/cmd.go (1 hunks)
  • client/cmd_test.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
client/cmd.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/cmd_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🔇 Additional comments (3)
client/cmd_test.go (2)

4-4: LGTM: Import addition is appropriate

The bytes package import is correctly placed and necessary for the new test implementation.


142-165: LGTM: Test implementation is well-structured

The test correctly verifies the command output functionality with proper setup and assertions.

client/cmd.go (1)

348-348: LGTM! Good improvement for testability.

The change to use cmd.OutOrStdout() is a good improvement that:

  1. Enhances testability by respecting the command's configured output
  2. Maintains backward compatibility by falling back to stdout when no output is configured
  3. Follows best practices by utilizing cobra's built-in methods

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

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cd3ce0c and e3b626c.

📒 Files selected for processing (2)
  • client/cmd.go (1 hunks)
  • client/cmd_test.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
client/cmd.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/cmd_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🔇 Additional comments (2)
client/cmd_test.go (1)

4-4: LGTM: Import follows Go conventions

The new bytes import is correctly grouped with standard library imports.

client/cmd.go (1)

348-348: LGTM! The change enhances testability while maintaining backward compatibility.

The modification correctly uses cmd.OutOrStdout() to respect the command's configured output while defaulting to stdout, which aligns with the PR objectives of improving testing capabilities without affecting existing behavior.

Let's verify that the change doesn't affect existing command output behavior:

✅ Verification successful

Let me analyze the results and generate additional verification scripts to ensure we have a complete understanding of the impact.


The change is safe and correctly implements output handling

Based on the verification results:

  • The WithOutput implementation in client/context.go is straightforward and correctly sets the output writer
  • Existing tests already use cmd.SetOutput() for controlling command output in test scenarios
  • The change aligns with existing patterns where tests need to capture or discard output
  • All usages of GetClientTxContext across the codebase follow the same pattern and will benefit from this enhancement

The modification maintains backward compatibility since:

  1. cmd.OutOrStdout() defaults to stdout when no custom output is set
  2. The WithOutput method simply updates the context without side effects
  3. Existing test patterns demonstrate this is a common and safe approach
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that commands still output to stdout by default
# and that the output can be customized in tests.

# Test 1: Search for test files that verify command output behavior
rg -g '**/*_test.go' -l 'cmd\.SetOutput'

# Test 2: Search for any direct usage of GetClientTxContext
# to ensure we're not breaking any existing patterns
rg 'GetClientTxContext\(' --type go

Length of output: 2984


Script:

#!/bin/bash
# Let's examine the test files that use SetOutput to understand
# how the output is being tested and verify our change aligns with existing patterns

# Check test implementations
rg -g '**/*_test.go' -B 3 -A 3 'cmd\.SetOutput'

# Also check the implementation of WithOutput to ensure
# it's properly handling the output configuration
ast-grep --pattern 'func (ctx $_) WithOutput($_) $_'

Length of output: 3715

Comment on lines +142 to +165
func TestContext_usesCobraCommandOutput(t *testing.T) {
var initCtx client.Context

cmd := &cobra.Command{
PreRunE: func(cmd *cobra.Command, args []string) error {
return client.SetCmdClientContextHandler(initCtx, cmd)
},
RunE: func(cmd *cobra.Command, _ []string) error {
cctx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}

return cctx.PrintString("hello")
},
}

var outBuf bytes.Buffer
cmd.SetOutput(&outBuf)

require.NoError(t, cmd.Execute())

require.Equal(t, "hello", outBuf.String())
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider expanding test coverage with additional test cases

The test effectively validates the basic functionality of using command's configured output. However, consider enhancing it with the following improvements:

  1. Add test cases for when cmd.Output is not set to verify default stdout behavior
  2. Include error scenarios (e.g., when context setup fails)
  3. Convert to table-driven tests to cover multiple scenarios
  4. Add documentation explaining the test's purpose and scenarios covered

Here's a suggested enhancement:

+// TestContext_usesCobraCommandOutput verifies that the client context correctly
+// uses the command's configured output when set, and falls back to stdout when not set.
 func TestContext_usesCobraCommandOutput(t *testing.T) {
-    var initCtx client.Context
-
-    cmd := &cobra.Command{
+    testCases := []struct {
+        name           string
+        setupOutput    bool
+        expectedOut    string
+        expectedError  error
+    }{
+        {
+            name:        "with configured output",
+            setupOutput: true,
+            expectedOut: "hello",
+        },
+        {
+            name:        "without configured output",
+            setupOutput: false,
+            expectedOut: "hello",
+        },
+    }
+
+    for _, tc := range testCases {
+        t.Run(tc.name, func(t *testing.T) {
+            var initCtx client.Context
+            cmd := &cobra.Command{

Committable suggestion was skipped due to low confidence.

Copy link
Contributor

@JulianToledano JulianToledano left a comment

Choose a reason for hiding this comment

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

utACK

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Oct 22, 2024
@julienrbrt julienrbrt added this pull request to the merge queue Oct 22, 2024
Merged via the queue into main with commit 1c949f7 Oct 22, 2024
82 of 83 checks passed
@julienrbrt julienrbrt deleted the mr/client-context-output branch October 22, 2024 23:14
mergify bot pushed a commit that referenced this pull request Oct 22, 2024
julienrbrt pushed a commit that referenced this pull request Oct 22, 2024
)

Co-authored-by: Mark Rushakoff <mark.rushakoff@gmail.com>
alpe added a commit that referenced this pull request Oct 25, 2024
* main: (157 commits)
  feat(core): add ConfigMap type (#22361)
  test: migrate e2e/genutil to systemtest (#22325)
  feat(accounts): re-introduce bundler (#21562)
  feat(log): add slog-backed Logger type (#22347)
  fix(x/tx): add feePayer as signer (#22311)
  test: migrate e2e/baseapp to integration tests (#22357)
  test: add x/circuit system tests (#22331)
  test: migrate e2e/tx tests to systemtest (#22152)
  refactor(simdv2): allow non-comet server components (#22351)
  build(deps): Bump rtCamp/action-slack-notify from 2.3.1 to 2.3.2 (#22352)
  fix(server/v2): respect context cancellation in start command (#22346)
  chore(simdv2): allow overriding the --home flag (#22348)
  feat(server/v2): add SimulateWithState to AppManager (#22335)
  docs(x/accounts): improve comments (#22339)
  chore: remove unused local variables (#22340)
  test: x/accounts systemtests (#22320)
  chore(client): use command's configured output (#22334)
  perf(log): use sonic json lib  (#22233)
  build(deps): bump x/tx (#22327)
  fix(x/accounts/lockup): fix proto path (#22319)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:CLI
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants