[test] Add tests for logger.JSONLLogger.logEntry error paths#4384
Open
github-actions[bot] wants to merge 1 commit intomainfrom
Open
[test] Add tests for logger.JSONLLogger.logEntry error paths#4384github-actions[bot] wants to merge 1 commit intomainfrom
github-actions[bot] wants to merge 1 commit intomainfrom
Conversation
Cover three previously-untested error branches in the private
logEntry method of JSONLLogger, plus two uncovered paths in
LogDifcFilteredItem:
- logEntry: nil logFile (uninitialized logger)
- logEntry: json.Encoder.Encode failure (un-marshallable type)
- logEntry: logFile.Sync failure (OS pipe as log file)
- logEntry: concurrent access safety
- logEntry: error wrapping exposes json.UnsupportedTypeError
- LogDifcFilteredItem: nil entry guard (no panic)
- LogDifcFilteredItem: sets Timestamp and Type fields correctly
- LogDifcFilteredItem: no logger initialised (no panic)
Coverage improvement for jsonl_logger:
logEntry: 66.7% → 100.0%
LogDifcFilteredItem: 87.5% (nil-logger branch is unreachable
because withGlobalLogger already checks for non-nil before
invoking the callback)
internal/logger package: 97.0% → 97.6%
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Contributor
There was a problem hiding this comment.
Pull request overview
This PR improves test coverage in internal/logger by adding focused unit tests for (*JSONLLogger).logEntry error paths and for LogDifcFilteredItem’s nil-entry guard and field population behavior.
Changes:
- Added tests covering
logEntry’s nillogFile, JSON encode failure, sync failure, happy path, and concurrent access behavior. - Added tests ensuring
LogDifcFilteredItem(nil)does not panic and that non-nil entries getTimestampandTypepopulated before being written.
Show a summary per file
| File | Description |
|---|---|
| internal/logger/jsonl_logger_test.go | Adds new unit tests for JSONLLogger.logEntry error branches and LogDifcFilteredItem behavior. |
Copilot's findings
Tip
Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comments suppressed due to low confidence (1)
internal/logger/jsonl_logger_test.go:917
- TestLogEntry_ConcurrentAccess closes the file via require.NoError(t, f.Close()) and also schedules t.Cleanup(func() { f.Close() }). This double-close is harmless but can mask close errors and makes the test harder to reason about. Prefer closing exactly once (either cleanup/defer OR the explicit Close with an assertion).
f, err := os.Create(logPath)
require.NoError(t, err, "failed to create log file")
t.Cleanup(func() { f.Close() })
jl := &JSONLLogger{
logFile: f,
encoder: json.NewEncoder(f),
}
const numGoroutines = 20
done := make(chan error, numGoroutines)
for i := 0; i < numGoroutines; i++ {
i := i
go func() {
done <- jl.logEntry(map[string]int{"n": i})
}()
}
for i := 0; i < numGoroutines; i++ {
assert.NoError(t, <-done, "concurrent logEntry call should not error")
}
// Count lines written: each successful logEntry writes exactly one JSONL line.
require.NoError(t, f.Close())
data, err := os.ReadFile(logPath)
- Files reviewed: 1/1 changed files
- Comments generated: 2
Comment on lines
+833
to
+852
| // os.Pipe returns a connected pair of Files. Calling Sync on the write end | ||
| // returns EINVAL on Linux because pipes do not support fsync. | ||
| r, w, err := os.Pipe() | ||
| require.NoError(t, err, "failed to create OS pipe") | ||
| t.Cleanup(func() { | ||
| r.Close() | ||
| w.Close() | ||
| }) | ||
|
|
||
| jl := &JSONLLogger{ | ||
| logFile: w, | ||
| encoder: json.NewEncoder(w), | ||
| } | ||
|
|
||
| // A simple JSON-encodable value: Encode should succeed, but Sync must fail. | ||
| syncErr := jl.logEntry(map[string]string{"event": "test"}) | ||
|
|
||
| require.Error(t, syncErr, "logEntry should return an error when Sync fails") | ||
| assert.Contains(t, syncErr.Error(), "failed to sync log file", "error should be wrapped with sync context") | ||
| } |
Comment on lines
+859
to
+878
| f, err := os.Create(logPath) | ||
| require.NoError(t, err, "failed to create log file") | ||
| t.Cleanup(func() { f.Close() }) | ||
|
|
||
| jl := &JSONLLogger{ | ||
| logFile: f, | ||
| encoder: json.NewEncoder(f), | ||
| } | ||
|
|
||
| type testPayload struct { | ||
| Event string `json:"event"` | ||
| Count int `json:"count"` | ||
| } | ||
|
|
||
| err = jl.logEntry(testPayload{Event: "test-event", Count: 42}) | ||
| require.NoError(t, err, "logEntry should succeed for valid logger and encodable entry") | ||
|
|
||
| // Flush and verify the file content. | ||
| require.NoError(t, f.Close(), "close should succeed") | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Test Coverage Improvement:
logger.JSONLLogger.logEntryFunction Analyzed
internal/loggerlogEntry(private method on*JSONLLogger)Why This Function?
logEntryis the core write method for all JSONL audit-log entries (RPC messages and DIFC filter events). Its three error branches — uninitialized logger, JSON encode failure, andfsyncfailure — were completely untested despite being critical for robust log-write error handling. It was the lowest-coverage non-trivial function (66.7%) in the packages that can currently be compiled in the offline CI environment.LogDifcFilteredItemwas also improved from 87.5% by covering the nil-entry guard and additional execution paths.Tests Added
logEntry(66.7% → 100%)"JSONL logger not initialized"errorchan int(un-marshallable) returns"failed to encode JSON: ..."wrapping a*json.UnsupportedTypeErroros.Pipewrite-end as the log file —Encodesucceeds into the pipe buffer butSyncreturnsEINVAL(pipes don't supportfsync)logEntryconcurrently; mutex must prevent data races and all writes must succeederrors.Asunwraps to*json.UnsupportedTypeErrorfrom the encode-error pathLogDifcFilteredItem(87.5% — nil-logger branch is unreachable dead code)nilmust not panic — even with no global loggerType == "DIFC_FILTERED"and a non-empty RFC 3339 timestampInitJSONLLoggerCoverage Report
The
logger == nilbranch inside thewithGlobalLoggercallback ofLogDifcFilteredItemis unreachable:withGlobalLoggeralready guards the callback invocation withif *logger != nil, so the inner nil check can never be triggered.Test Execution
All pre-existing tests continue to pass. No production code was modified.
Generated by Test Coverage Improver
Next run should target
internal/sys.DetectContainerID(59.1%) orinternal/version.BuildVersionString(68.2%)Warning
The following domains were blocked by the firewall during workflow execution:
go.opentelemetry.iogo.yaml.ingolang.orggoogle.golang.orggopkg.inproxy.golang.orgTo allow these domains, add them to the
network.allowedlist in your workflow frontmatter:See Network Configuration for more information.