-
Notifications
You must be signed in to change notification settings - Fork 141
[common] Introduce testlogger as a workaround of poor lifecycle #1398
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
Merged
3vilhamster
merged 9 commits into
cadence-workflow:master
from
3vilhamster:introduce-testlogger
Nov 11, 2024
Merged
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9ec9816
[common] Introduce testlogger as a workaround of poor lifecycle
3vilhamster 83e76d2
maybe fix autoscaler tests
3vilhamster 2287430
fix tests
3vilhamster f7eb168
make test logs thread safe
3vilhamster 56e6dde
fmt
3vilhamster 02ceb76
Merge branch 'master' into introduce-testlogger
3vilhamster 27b16db
switched to RWMutex to ensure switch to fallback on the test stop
3vilhamster d2b87f4
fmt
3vilhamster e209ff6
add a nil case to ValueFromPtr
3vilhamster File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
// Copyright (c) 2017-2021 Uber Technologies Inc. | ||
// | ||
// Permission is hereby granted, free of charge, to any person obtaining a copy | ||
// of this software and associated documentation files (the "Software"), to deal | ||
// in the Software without restriction, including without limitation the rights | ||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
// copies of the Software, and to permit persons to whom the Software is | ||
// furnished to do so, subject to the following conditions: | ||
// | ||
// The above copyright notice and this permission notice shall be included in | ||
// all copies or substantial portions of the Software. | ||
// | ||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
// THE SOFTWARE. | ||
|
||
package testlogger | ||
|
||
import ( | ||
"fmt" | ||
"slices" | ||
"strings" | ||
"sync" | ||
|
||
"github.com/stretchr/testify/require" | ||
"go.uber.org/atomic" | ||
"go.uber.org/zap" | ||
"go.uber.org/zap/zapcore" | ||
"go.uber.org/zap/zaptest" | ||
"go.uber.org/zap/zaptest/observer" | ||
) | ||
|
||
type TestingT interface { | ||
zaptest.TestingT | ||
Cleanup(func()) // not currently part of zaptest.TestingT | ||
} | ||
|
||
// NewZap makes a new test-oriented logger that prevents bad-lifecycle logs from failing tests. | ||
func NewZap(t TestingT) *zap.Logger { | ||
/* | ||
HORRIBLE HACK due to async shutdown, both in our code and in libraries: | ||
normally, logs produced after a test finishes will *intentionally* fail the test and/or | ||
cause data to race on the test's internal `t.done` field. | ||
|
||
that's a good thing, it reveals possibly-dangerously-flawed lifecycle management. | ||
|
||
unfortunately some of our code and some libraries do not have good lifecycle management, | ||
and this cannot easily be patched from the outside. | ||
|
||
so this logger cheats: after a test completes, it logs to stderr rather than TestingT. | ||
EVERY ONE of these logs is bad and we should not produce them, but it's causing many | ||
otherwise-useful tests to be flaky, and that's a larger interruption than is useful. | ||
*/ | ||
logAfterComplete, err := zap.NewDevelopment() | ||
require.NoError(t, err, "could not build a fallback zap logger") | ||
replaced := &fallbackTestCore{ | ||
t: t, | ||
fallback: logAfterComplete.Core(), | ||
testing: zaptest.NewLogger(t).Core(), | ||
completed: &atomic.Bool{}, | ||
} | ||
|
||
t.Cleanup(replaced.UseFallback) // switch to fallback before ending the test | ||
|
||
return zap.New(replaced) | ||
} | ||
|
||
// NewObserved makes a new test logger that both logs to `t` and collects logged | ||
// events for asserting in tests. | ||
func NewObserved(t TestingT) (*zap.Logger, *observer.ObservedLogs) { | ||
obsCore, obs := observer.New(zapcore.DebugLevel) | ||
z := NewZap(t) | ||
z = z.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core { | ||
return zapcore.NewTee(core, obsCore) | ||
})) | ||
return z, obs | ||
} | ||
|
||
type fallbackTestCore struct { | ||
sync.Mutex | ||
t TestingT | ||
fallback zapcore.Core | ||
testing zapcore.Core | ||
completed *atomic.Bool | ||
} | ||
|
||
var _ zapcore.Core = (*fallbackTestCore)(nil) | ||
|
||
func (f *fallbackTestCore) UseFallback() { | ||
f.completed.Store(true) | ||
} | ||
|
||
func (f *fallbackTestCore) Enabled(level zapcore.Level) bool { | ||
if f.completed.Load() { | ||
return f.fallback.Enabled(level) | ||
} | ||
return f.testing.Enabled(level) | ||
} | ||
|
||
func (f *fallbackTestCore) With(fields []zapcore.Field) zapcore.Core { | ||
// need to copy and defer, else the returned core will be used at an | ||
// arbitrarily later point in time, possibly after the test has completed. | ||
return &fallbackTestCore{ | ||
t: f.t, | ||
fallback: f.fallback.With(fields), | ||
testing: f.testing.With(fields), | ||
completed: f.completed, | ||
} | ||
} | ||
|
||
func (f *fallbackTestCore) Check(entry zapcore.Entry, checked *zapcore.CheckedEntry) *zapcore.CheckedEntry { | ||
// see other Check impls, all look similar. | ||
// this defers the "where to log" decision to Write, as `f` is the core that will write. | ||
if f.fallback.Enabled(entry.Level) { | ||
return checked.AddCore(entry, f) | ||
} | ||
return checked // do not add any cores | ||
} | ||
|
||
func (f *fallbackTestCore) Write(entry zapcore.Entry, fields []zapcore.Field) error { | ||
if f.completed.Load() { | ||
entry.Message = fmt.Sprintf("COULD FAIL TEST %q, logged too late: %v", f.t.Name(), entry.Message) | ||
|
||
hasStack := slices.ContainsFunc(fields, func(field zapcore.Field) bool { | ||
// no specific stack-trace type, so just look for probable fields. | ||
return strings.Contains(strings.ToLower(field.Key), "stack") | ||
}) | ||
if !hasStack { | ||
fields = append(fields, zap.Stack("log_stack")) | ||
} | ||
return f.fallback.Write(entry, fields) | ||
} | ||
// Ensure no concurrent writes to the test logger. | ||
f.Lock() | ||
defer f.Unlock() | ||
return f.testing.Write(entry, fields) | ||
} | ||
|
||
func (f *fallbackTestCore) Sync() error { | ||
if f.completed.Load() { | ||
return f.fallback.Sync() | ||
} | ||
return f.testing.Sync() | ||
} |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.