Skip to content

test: add unit and e2e coverage for log package#1761

Open
ravindra-RKB wants to merge 1 commit into
kmesh-net:mainfrom
ravindra-RKB:test/log-e2e-test
Open

test: add unit and e2e coverage for log package#1761
ravindra-RKB wants to merge 1 commit into
kmesh-net:mainfrom
ravindra-RKB:test/log-e2e-test

Conversation

@ravindra-RKB

Copy link
Copy Markdown

What type of PR is this?

kind enhancement

What this PR does / why we need it

This PR adds automated test coverage for the Kmesh log package and resolves Issue #1235.

The implementation is split into two layers:

  1. Unit Tests (ctl/log/log_test.go)**

Validate GetLoggerNames, GetLoggerLevel, and SetLoggerLevel.
Use httptest.NewServer to simulate daemon responses.
Verify JSON parsing, HTTP error handling, and CLI output formatting.
Avoid modifications to production code and do not introduce test-only hooks.

  1. E2E Tests (test/e2e/log_test.go)**

Validate the complete kmeshctl log workflow against a live Kmesh daemon.
Verify logger discovery.
Verify logger level retrieval.
Verify runtime log level updates.
Restore the original logger level after test execution to avoid side effects.

Which issue(s) this PR fixes

Fixes #1235

Special notes for your reviewer

No production code was modified.
The implementation avoids the mock-injection approach used in previous attempts.
E2E tests use the existing Kmesh/Istio test framework and retry utilities.
Cleanup logic restores the original logger level instead of hardcoding a default value.
Unit tests intentionally avoid t.Parallel() because stdout is captured during execution.

Does this PR introduce a user-facing change?

Copilot AI review requested due to automatic review settings June 16, 2026 11:50
@kmesh-bot

Copy link
Copy Markdown
Collaborator

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign hzxuzhonghu for approval. For more information see the Kubernetes Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces automated test coverage for the Kmesh log package, addressing issue #1235. By implementing both unit tests for CLI logic and E2E tests for daemon interaction, the changes ensure robust validation of logger discovery and configuration updates without introducing production code modifications or test-only hooks.

Highlights

  • Unit Testing: Added comprehensive unit tests in ctl/log/log_test.go using httptest to validate logger management functions without modifying production code.
  • E2E Testing: Implemented end-to-end tests in test/e2e/log_test.go to verify the kmeshctl log workflow against a live daemon, including cleanup logic to restore original log levels.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.


Logs are checked with care and pride, / In unit tests where truths reside. / With E2E the flow is clear, / No bugs shall haunt the Kmesh gear.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds automated coverage for kmeshctl log behavior via a new integration/e2e test and new unit tests around the underlying HTTP-based log helpers.

Changes:

  • Added an e2e integration test validating kmeshctl log list/get/set flows against a real Kmesh daemon pod.
  • Added unit tests for logger name listing, logger level retrieval, and logger level updates using httptest.

Reviewed changes

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

File Description
test/e2e/log_test.go New integration test exercising kmeshctl log against a live pod and verifying outputs/state.
ctl/log/log_test.go New unit tests for log helper functions using an HTTP test server and captured stdout.

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

Comment thread test/e2e/log_test.go Outdated
Comment on lines +111 to +114
output := string(out)
// Note: actual output depends on daemon response, typically empty or success message.
// We check if it ran without errors.
return nil
Comment thread test/e2e/log_test.go
Comment on lines +45 to +46
cmd := exec.Command("kmeshctl", "log", podName)
out, err := cmd.CombinedOutput()
Comment thread ctl/log/log_test.go
Comment on lines +30 to +43
func captureStdout(f func()) string {
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w

f()

w.Close()
os.Stdout = oldStdout

var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}
Comment thread ctl/log/log_test.go
Comment on lines +68 to +71
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.mockStatus)
w.Write([]byte(tt.mockBody))
}))
Comment thread ctl/log/log_test.go
Comment on lines +78 to +80
if tt.expectedStdout != "" && !strings.Contains(output, tt.expectedStdout) {
t.Errorf("expected stdout to contain %q, got %q", tt.expectedStdout, output)
}

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces unit and end-to-end integration tests for the kmeshctl log command, covering retrieving logger names, getting logger levels, and setting logger levels. The review feedback highlights two main improvements: first, ensuring that os.Stdout is safely restored and resources are cleaned up in captureStdout using defer to handle potential panics; second, adding a guard check in the end-to-end test cleanup to prevent executing an invalid command if retrieving the original logger level fails.

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 ctl/log/log_test.go
Comment on lines +30 to +43
func captureStdout(f func()) string {
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w

f()

w.Close()
os.Stdout = oldStdout

var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

If the function f panics during execution, os.Stdout will not be restored to its original value, and the write end of the pipe w will not be closed. This can hijack os.Stdout for the rest of the test suite run, causing subsequent tests to fail or lose their output, and leak file descriptors.

Using defer to restore os.Stdout and close the pipe files ensures that resources are cleaned up and global state is restored even if a panic occurs.

func captureStdout(f func()) string {
	oldStdout := os.Stdout
	r, w, err := os.Pipe()
	if err != nil {
		panic(err)
	}
	os.Stdout = w

	defer func() {
		os.Stdout = oldStdout
		_ = r.Close()
	}()

	func() {
		defer w.Close()
		f()
	}()

	var buf bytes.Buffer
	_, _ = io.Copy(&buf, r)
	return buf.String()
}

Comment thread test/e2e/log_test.go
Comment on lines +93 to +103
defer func() {
if err := exec.Command(
"kmeshctl",
"log",
podName,
"--set",
"default:"+originalLevel,
).Run(); err != nil {
t.Logf("cleanup failed to restore original logger level (%s): %v", originalLevel, err)
}
}()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

If the setup step fails or times out, originalLevel will remain empty (""). Running the cleanup command with an empty level (default:) will result in an invalid command execution, which can cause confusing test logs or unexpected daemon behavior. Adding a guard check to ensure originalLevel is not empty before executing the restore command prevents this.

				defer func() {
					if originalLevel == "" {
						return
					}
					if err := exec.Command(
						"kmeshctl",
						"log",
						podName,
						"--set",
						"default:"+originalLevel,
					).Run(); err != nil {
						t.Logf("cleanup failed to restore original logger level (%s): %v", originalLevel, err)
					}
				}()

Signed-off-by: Ravindra Kumar Bundela <ravindrarkb1205@gmail.com>
@ravindra-RKB

Copy link
Copy Markdown
Author

Addressed the review feedback:

Removed the compile-blocking unused variable in test/e2e/log_test.go.
Added a guard to avoid restoring an empty logger level during cleanup.
Updated captureStdout to safely restore os.Stdout and clean up resources even in failure scenarios.

The branch has been force-pushed with the fixes. Please take another look when you have a chance. Thanks!

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.

Add e2e test for log package

3 participants