Skip to content

Find, verify, and analyze leaked credentials

Use shared logtest helpers in source debug logging tests (#5519)

Kashif Khan474461030c41
diff --git a/docs/source_logging.md b/docs/source_logging.md
index cc68056ea..da9d79263 100644
--- a/docs/source_logging.md
+++ b/docs/source_logging.md
@@ -51,15 +51,22 @@ the findings are warnings. If a source really needs a new context, add a `// nos
## Testing
-Use `logtest.DebugContext()` to run a source with debug turned on and look at what it logged:
+Use the `logtest` helpers to run a source and check what it logged. They check what must hold for every source, not
+the text or the number of lines, so renaming a log message never breaks a test:
```go
-ctx, logs := logtest.DebugContext()
-err := s.Init(ctx, "test source", 0, 0, false, conn, 1)
-require.NoError(t, err)
-
-assert.Equal(t, 1, logs.FilterMessage("listing repositories").Len())
-for _, entry := range logs.All() {
- assert.NotContains(t, entry.Message, testSecret)
-}
+ctx, logs := logtest.SourceContext(true) // false for a normal run
+require.NoError(t, s.Init(ctx, "test source", 0, 0, false, conn, 1))
+logtest.CheckInitLine(t, logs.All()) // Init logged a V(1) line
+
+// scan with Chunks, Enumerate or ChunkUnit
+
+logtest.CheckSourceLines(t, logs.All(), testSecret) // every line has the source fields, and no secret
```
+
+With debug off, call `logtest.CheckNoDebugLines` to check that nothing below `V(0)` was written. A normal run may
+log nothing, and the debug run already checks its lines, so it needs no other check.
+
+Give the source fake data that makes it log the lines support relies on, like an API error, a retry and a skipped
+item, so those lines get checked too. Check real behavior, such as a skipped item not being scanned, through the
+chunks the source sends, not through log lines.
diff --git a/pkg/log/logtest/logtest.go b/pkg/log/logtest/logtest.go
index f401d0ecd..e491e9fa2 100644
--- a/pkg/log/logtest/logtest.go
+++ b/pkg/log/logtest/logtest.go
@@ -2,7 +2,11 @@
package logtest
import (
+ "fmt"
+ "testing"
+
"github.com/go-logr/zapr"
+ "github.com/stretchr/testify/assert"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
@@ -25,3 +29,74 @@ func DebugContext() (context.Context, *observer.ObservedLogs) {
ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
return context.WithLogLevel(ctx, log.DebugLevel), logs
}
+
+// SourceFields are the fields the source manager adds to every source's context. Every line a source logs through
+// its context carries them.
+var SourceFields = []string{"job_id", "source_id", "source_name", "source_type"}
+
+// SourceContext returns a Context with the source fields set, the way the source manager sets them, plus the logs
+// written to it. With debug true, debug logging is turned on, like DebugContext. With debug false, the context
+// writes only V(0) and above, like a normal run.
+//
+// Source tests use it with the Check functions below, which check what must hold for every source, never the text
+// or the number of lines:
+//
+// ctx, logs := logtest.SourceContext(true)
+// require.NoError(t, s.Init(ctx, ...))
+// logtest.CheckInitLine(t, logs.All())
+// // scan
+// logtest.CheckSourceLines(t, logs.All(), testSecret)
+func SourceContext(debug bool) (context.Context, *observer.ObservedLogs) {
+ core, logs := observer.New(zapcore.InfoLevel)
+ ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
+ if debug {
+ ctx = context.WithLogLevel(ctx, log.DebugLevel)
+ }
+ return context.WithValues(ctx,
+ "job_id", 1,
+ "source_id", 1,
+ "source_name", "test source",
+ "source_type", "test",
+ ), logs
+}
+
+// CheckInitLine fails the test if entries has no V(1) line. Pass it the lines logged by Init only, so the line is
+// known to come from Init.
+func CheckInitLine(t testing.TB, entries []observer.LoggedEntry) {
+ t.Helper()
+ for _, entry := range entries {
+ if entry.Level == zapcore.Level(-1) {
+ return
+ }
+ }
+ t.Errorf("Init logged no V(1) line, got %d lines", len(entries))
+}
+
+// CheckSourceLines fails the test if a line is missing one of the SourceFields, or if its message or fields contain
+// one of secrets. A missing field means the line was not logged through the context the source was given. It also
+// fails with no lines at all, since then nothing was checked.
+func CheckSourceLines(t testing.TB, entries []observer.LoggedEntry, secrets ...string) {
+ t.Helper()
+ if len(entries) == 0 {
+ t.Errorf("no lines were logged, so there is nothing to check")
+ return
+ }
+ for _, entry := range entries {
+ fields := entry.ContextMap()
+ for _, key := range SourceFields {
+ assert.Contains(t, fields, key, "line %q", entry.Message)
+ }
+ for _, secret := range secrets {
+ assert.NotContains(t, entry.Message, secret, "line %q", entry.Message)
+ assert.NotContains(t, fmt.Sprint(fields), secret, "line %q", entry.Message)
+ }
+ }
+}
+
+// CheckNoDebugLines fails the test if any line is more verbose than V(0). Use it on a run with debug off.
+func CheckNoDebugLines(t testing.TB, entries []observer.LoggedEntry) {
+ t.Helper()
+ for _, entry := range entries {
+ assert.GreaterOrEqual(t, entry.Level, zapcore.InfoLevel, "debug line %q with debug off", entry.Message)
+ }
+}
diff --git a/pkg/log/logtest/logtest_test.go b/pkg/log/logtest/logtest_test.go
index 61417c102..67a4a1e6b 100644
--- a/pkg/log/logtest/logtest_test.go
+++ b/pkg/log/logtest/logtest_test.go
@@ -4,6 +4,10 @@ import (
"testing"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/log"
)
func TestDebugContext(t *testing.T) {
@@ -16,3 +20,93 @@ func TestDebugContext(t *testing.T) {
assert.Equal(t, "value", entries[0].ContextMap()["key"])
}
}
+
+// recorder is a testing.TB that records failures instead of failing the test.
+type recorder struct {
+ testing.TB
+ failed bool
+}
+
+func (r *recorder) Helper() {}
+
+func (r *recorder) Errorf(string, ...any) { r.failed = true }
+
+func TestSourceContext(t *testing.T) {
+ ctx, logs := SourceContext(true)
+ ctx.Logger().V(1).Info("init line")
+ ctx.Logger().V(5).Info("debug line", "token", "not-a-secret")
+
+ r := &recorder{TB: t}
+ CheckInitLine(r, logs.All())
+ CheckSourceLines(r, logs.All(), "secret-value")
+ assert.False(t, r.failed)
+
+ ctx, logs = SourceContext(false)
+ ctx.Logger().V(5).Info("debug line")
+ ctx.Logger().Info("info line")
+ assert.Equal(t, 1, logs.Len())
+}
+
+func TestCheckInitLine(t *testing.T) {
+ ctx, logs := SourceContext(true)
+ ctx.Logger().V(2).Info("not an init line")
+
+ r := &recorder{TB: t}
+ CheckInitLine(r, logs.All())
+ assert.True(t, r.failed)
+}
+
+func TestCheckSourceLines(t *testing.T) {
+ t.Run("missing field", func(t *testing.T) {
+ _, logs := SourceContext(true)
+ // a logger that did not come from the source's context has no source fields
+ other, otherLogs := DebugContext()
+ other.Logger().Info("line from another logger")
+
+ r := &recorder{TB: t}
+ CheckSourceLines(r, append(logs.All(), otherLogs.All()...))
+ assert.True(t, r.failed)
+ })
+
+ t.Run("no lines", func(t *testing.T) {
+ _, logs := SourceContext(true)
+
+ r := &recorder{TB: t}
+ CheckSourceLines(r, logs.All())
+ assert.True(t, r.failed)
+ })
+
+ t.Run("secret in message", func(t *testing.T) {
+ ctx, logs := SourceContext(true)
+ ctx.Logger().Info("found secret-value")
+
+ r := &recorder{TB: t}
+ CheckSourceLines(r, logs.All(), "secret-value")
+ assert.True(t, r.failed)
+ })
+
+ t.Run("secret in field", func(t *testing.T) {
+ ctx, logs := SourceContext(true)
+ ctx.Logger().Info("line", "value", "secret-value")
+
+ r := &recorder{TB: t}
+ CheckSourceLines(r, logs.All(), "secret-value")
+ assert.True(t, r.failed)
+ })
+}
+
+func TestCheckNoDebugLines(t *testing.T) {
+ // a source that turns on debug by itself leaks debug lines into a normal run
+ ctx, logs := SourceContext(false)
+ context.WithLogLevel(ctx, log.DebugLevel).Logger().V(5).Info("leaked debug line")
+ ctx.Logger().Info("info line")
+ require.Equal(t, 2, logs.Len())
+
+ r := &recorder{TB: t}
+ CheckNoDebugLines(r, logs.All())
+ assert.True(t, r.failed)
+
+ r = &recorder{TB: t}
+ CheckNoDebugLines(r, logs.FilterMessage("info line").All())
+ assert.False(t, r.failed)
+}
diff --git a/pkg/sources/docker/docker_test.go b/pkg/sources/docker/docker_test.go
index 6372d98b7..e79c5ca58 100644
--- a/pkg/sources/docker/docker_test.go
+++ b/pkg/sources/docker/docker_test.go
@@ -3,7 +3,6 @@ package docker
import (
"archive/tar"
"bytes"
- "fmt"
"io"
stdlog "log"
"net/http"
@@ -13,7 +12,6 @@ import (
"sync/atomic"
"testing"
- "github.com/go-logr/zapr"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/registry"
v1 "github.com/google/go-containerregistry/pkg/v1"
@@ -24,8 +22,6 @@ import (
dockerClient "github.com/moby/moby/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"google.golang.org/protobuf/types/known/anypb"
@@ -497,7 +493,8 @@ func TestSource_DebugLogging(t *testing.T) {
return ref
}
- runSource := func(t *testing.T, ctx context.Context) {
+ runSource := func(t *testing.T, debug bool) []observer.LoggedEntry {
+ ctx, logs := logtest.SourceContext(debug)
conn, err := anypb.New(&sourcespb.Docker{
Credential: &sourcespb.Docker_Unauthenticated{
Unauthenticated: &credentialspb.Unauthenticated{},
@@ -509,83 +506,27 @@ func TestSource_DebugLogging(t *testing.T) {
s := &Source{}
require.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))
+ if debug {
+ logtest.CheckInitLine(t, logs.All())
+ }
chunksChan := make(chan *sources.Chunk, 8)
require.NoError(t, s.Chunks(ctx, chunksChan))
close(chunksChan)
-
- var files []string
- for chunk := range chunksChan {
- files = append(files, chunk.SourceMetadata.GetDocker().GetFile())
- }
- assert.ElementsMatch(t, []string{"image-metadata:history:0:created-by", "/secret.txt"}, files)
+ return logs.All()
}
t.Run("debug on", func(t *testing.T) {
- ctx, logs := logtest.DebugContext()
- ctx = context.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)
- runSource(t, ctx)
-
- // lines from each level show up
- for _, msg := range []string{
- "Docker source initialized", // V(1)
- "Scanning image", // V(2)
- "Finished scanning image", // V(2)
- "Scanning image history entry", // V(3)
- "Scanning layer", // V(3)
- "Finished scanning layer", // V(3)
- "Skipping file", // V(4)
- "Registry request failed", // V(4)
- "Loading image", // V(5)
- "Scanning file", // V(5)
- } {
- assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)
- }
-
- // the skip says why, and carries the layer
- skips := logs.FilterMessage("Skipping file").All()
- require.Len(t, skips, 1)
- assert.Equal(t, "/skip/me.txt", skips[0].ContextMap()["file"])
- assert.Equal(t, "matches exclude pattern", skips[0].ContextMap()["reason"])
- assert.Contains(t, skips[0].ContextMap(), "layer")
-
- layerDone := logs.FilterMessage("Finished scanning layer").All()
- require.Len(t, layerDone, 1)
- assert.EqualValues(t, 2, layerDone[0].ContextMap()["files"])
- assert.EqualValues(t, 1, layerDone[0].ContextMap()["skipped"])
-
- // the failed manifest request says what failed
- var manifestFailed bool
- for _, entry := range logs.FilterMessage("Registry request failed").All() {
- if entry.ContextMap()["status"] == int64(http.StatusServiceUnavailable) {
- manifestFailed = true
- assert.Equal(t, "/v2/test/image/manifests/v1", entry.ContextMap()["path"])
- }
- }
- assert.True(t, manifestFailed, "missing 503 registry line")
-
- // every line came from the context logger, so it carries the source fields,
- // and none of them contain the secret
- for _, entry := range logs.All() {
- fields := entry.ContextMap()
- assert.Contains(t, fields, "source_name", "line %q", entry.Message)
- assert.Contains(t, fields, "job_id", "line %q", entry.Message)
- assert.NotContains(t, entry.Message, testSecret)
- assert.NotContains(t, fmt.Sprint(fields), testSecret)
- }
+ logtest.CheckSourceLines(t, runSource(t, true), testSecret)
})
t.Run("debug off", func(t *testing.T) {
- core, logs := observer.New(zapcore.InfoLevel)
- ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
- runSource(t, ctx)
-
- assert.Zero(t, logs.Len(), "unexpected lines: %v", logs.All())
+ logtest.CheckNoDebugLines(t, runSource(t, false))
})
}
func TestDockerHub_ListImagesDebugLogging(t *testing.T) {
- ctx, logs := logtest.DebugContext()
+ ctx, logs := logtest.SourceContext(true)
hub := &DockerHub{Client: &http.Client{Transport: common.FakeTransport{
CreateResponse: func(req *http.Request) (*http.Response, error) {
@@ -601,15 +542,8 @@ func TestDockerHub_ListImagesDebugLogging(t *testing.T) {
},
}}}
- images, err := hub.ListImages(ctx, "acme")
+ _, err := hub.ListImages(ctx, "acme")
require.NoError(t, err)
- assert.Equal(t, []string{"acme/one", "acme/two", "acme/three"}, images)
-
- pages := logs.FilterMessage("Listed registry page").All()
- require.Len(t, pages, 2)
- for i, want := range []int{2, 1} {
- assert.EqualValues(t, i+1, pages[i].ContextMap()["page"])
- assert.EqualValues(t, want, pages[i].ContextMap()["images"])
- assert.Equal(t, "Dockerhub", pages[i].ContextMap()["registry"])
- }
+
+ logtest.CheckSourceLines(t, logs.All())
}
diff --git a/pkg/sources/filesystem/filesystem_test.go b/pkg/sources/filesystem/filesystem_test.go
index a61f24b01..8b1938b15 100644
--- a/pkg/sources/filesystem/filesystem_test.go
+++ b/pkg/sources/filesystem/filesystem_test.go
@@ -11,12 +11,9 @@ import (
"time"
"github.com/go-logr/logr"
- "github.com/go-logr/zapr"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/anypb"
@@ -914,9 +911,13 @@ func TestSource_DebugLogging(t *testing.T) {
require.NoError(t, err)
// run the source with both Chunks and ChunkUnit, draining chunks the way the engine does
- runSource := func(ctx trContext.Context) {
+ runSource := func(t *testing.T, debug bool) []observer.LoggedEntry {
+ ctx, logs := logtest.SourceContext(debug)
s := Source{}
require.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))
+ if debug {
+ logtest.CheckInitLine(t, logs.All())
+ }
chunksCh := make(chan *sources.Chunk, 64)
go func() {
@@ -929,55 +930,14 @@ func TestSource_DebugLogging(t *testing.T) {
reporter := sourcestest.TestReporter{}
require.NoError(t, s.ChunkUnit(ctx, sources.CommonSourceUnit{ID: dir}, &reporter))
require.Empty(t, reporter.ChunkErrs)
+ return logs.All()
}
t.Run("debug on", func(t *testing.T) {
- ctx, logs := logtest.DebugContext()
- ctx = trContext.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)
- runSource(ctx)
-
- // lines from each level show up
- for _, msg := range []string{
- "filesystem source initialized", // V(1)
- "scanning path", // V(2)
- "finished scanning path", // V(2)
- "scanning directory", // V(3)
- "scanning file", // V(3)
- "finished scanning file", // V(5)
- } {
- assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)
- }
-
- // every skip says why, at V(4)
- var reasons []string
- for _, entry := range logs.FilterMessage("skipping file").All() {
- reasons = append(reasons, fmt.Sprint(entry.ContextMap()["reason"]))
- }
- for _, entry := range logs.FilterMessage("skipping symlink").All() {
- reasons = append(reasons, fmt.Sprint(entry.ContextMap()["reason"]))
- }
- assert.Contains(t, reasons, "binary files are skipped")
- assert.Contains(t, reasons, "excluded by path filter")
- assert.Contains(t, reasons, "following symlinks is not enabled")
-
- // every line came from the context logger, so it carries the source fields,
- // and none of them contain the secret
- for _, entry := range logs.All() {
- fields := entry.ContextMap()
- assert.Contains(t, fields, "source_name", "line %q", entry.Message)
- assert.Contains(t, fields, "job_id", "line %q", entry.Message)
- assert.NotContains(t, entry.Message, testSecret)
- assert.NotContains(t, fmt.Sprint(fields), testSecret)
- }
+ logtest.CheckSourceLines(t, runSource(t, true), testSecret)
})
t.Run("debug off", func(t *testing.T) {
- core, logs := observer.New(zapcore.InfoLevel)
- ctx := trContext.WithLogger(trContext.Background(), zapr.NewLogger(zap.New(core)))
- runSource(ctx)
-
- assert.Zero(t, logs.FilterMessage("scanning file").Len())
- assert.Zero(t, logs.FilterMessage("skipping file").Len())
- assert.Zero(t, logs.FilterMessage("finished scanning file").Len())
+ logtest.CheckNoDebugLines(t, runSource(t, false))
})
}
diff --git a/pkg/sources/gcs/gcs_test.go b/pkg/sources/gcs/gcs_test.go
index 8b5173698..a8eab17b0 100644
--- a/pkg/sources/gcs/gcs_test.go
+++ b/pkg/sources/gcs/gcs_test.go
@@ -15,13 +15,10 @@ import (
"testing"
"time"
- "github.com/go-logr/zapr"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"google.golang.org/protobuf/types/known/anypb"
@@ -537,8 +534,9 @@ func TestSource_DebugLogging(t *testing.T) {
defer srv.Close()
t.Setenv("STORAGE_EMULATOR_HOST", srv.Listener.Addr().String())
- runSource := func(t *testing.T, ctx context.Context) {
+ runSource := func(t *testing.T, debug bool) []observer.LoggedEntry {
t.Helper()
+ ctx, logs := logtest.SourceContext(debug)
s, conn := createTestSource(&sourcespb.GCS{
IncludeBuckets: []string{bkt},
ExcludeObjects: []string{"skip/*"},
@@ -546,78 +544,21 @@ func TestSource_DebugLogging(t *testing.T) {
Credential: &sourcespb.GCS_Unauthenticated{},
})
require.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))
+ if debug {
+ logtest.CheckInitLine(t, logs.All())
+ }
chunksCh := make(chan *sources.Chunk, 10)
require.NoError(t, s.Chunks(ctx, chunksCh))
close(chunksCh)
-
- var files []string
- for chunk := range chunksCh {
- files = append(files, chunk.SourceMetadata.GetGcs().GetFilename())
- }
- assert.Equal(t, []string{"secret.txt"}, files)
+ return logs.All()
}
t.Run("debug on", func(t *testing.T) {
- ctx, logs := logtest.DebugContext()
- ctx = context.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)
- runSource(t, ctx)
-
- // lines from each level show up
- for _, msg := range []string{
- "GCS source finished processing objects", // V(0)
- "GCS source initialized", // V(1)
- "Enumerating buckets", // V(1)
- "Finished enumerating buckets", // V(1)
- "Using configured buckets, listing needs auth", // V(1)
- "Enumerated bucket", // V(2)
- "Listing objects in bucket", // V(2)
- "Finished listing objects in bucket", // V(2)
- "Scanning object", // V(3)
- "Skipping object", // V(4)
- "Retrying GCS request", // V(4)
- } {
- assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)
- }
-
- // each skip says why, and carries the bucket and object
- reasons := map[string]string{}
- for _, entry := range logs.FilterMessage("Skipping object").All() {
- fields := entry.ContextMap()
- assert.Equal(t, bkt, fields["bucket"])
- reasons[fmt.Sprint(fields["object"])] = fmt.Sprint(fields["reason"])
- }
- assert.Equal(t, map[string]string{
- "video.mp4": "file type is skipped",
- "big.txt": "size out of range",
- "skip/x.txt": "matches filter",
- }, reasons)
-
- listed := logs.FilterMessage("Finished listing objects in bucket").All()
- require.Len(t, listed, 1)
- assert.EqualValues(t, 1, listed[0].ContextMap()["objects"])
- assert.EqualValues(t, 3, listed[0].ContextMap()["skipped"])
-
- // skipped objects are not errors
- assert.Zero(t, logs.FilterLevelExact(zapcore.ErrorLevel).Len(), "unexpected errors: %v", logs.FilterLevelExact(zapcore.ErrorLevel).All())
-
- // every line came from the context logger, so it carries the source fields,
- // and none of them contain the secret
- for _, entry := range logs.All() {
- fields := entry.ContextMap()
- assert.Contains(t, fields, "source_name", "line %q", entry.Message)
- assert.Contains(t, fields, "job_id", "line %q", entry.Message)
- assert.NotContains(t, entry.Message, testSecret)
- assert.NotContains(t, fmt.Sprint(fields), testSecret)
- }
+ logtest.CheckSourceLines(t, runSource(t, true), testSecret)
})
t.Run("debug off", func(t *testing.T) {
- core, logs := observer.New(zapcore.InfoLevel)
- ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
- runSource(t, ctx)
-
- require.Equal(t, 1, logs.Len(), "unexpected lines: %v", logs.All())
- assert.Equal(t, "GCS source finished processing objects", logs.All()[0].Message)
+ logtest.CheckNoDebugLines(t, runSource(t, false))
})
}
diff --git a/pkg/sources/git/git_test.go b/pkg/sources/git/git_test.go
index 35db28700..320dc507c 100644
--- a/pkg/sources/git/git_test.go
+++ b/pkg/sources/git/git_test.go
@@ -13,12 +13,9 @@ import (
"testing"
"time"
- "github.com/go-logr/zapr"
"github.com/kylelemons/godebug/pretty"
"github.com/stretchr/testify/assert"
"github.com/trufflesecurity/trufflehog/v3/pkg/feature"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"google.golang.org/protobuf/types/known/anypb"
@@ -2345,9 +2342,13 @@ func TestSource_DebugLogging(t *testing.T) {
assert.NoError(t, err)
// run the source and drain its chunks, the way the engine does
- runSource := func(ctx context.Context) {
+ runSource := func(t *testing.T, debug bool) []observer.LoggedEntry {
+ ctx, logs := logtest.SourceContext(debug)
s := Source{}
assert.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))
+ if debug {
+ logtest.CheckInitLine(t, logs.All())
+ }
chunksCh := make(chan *sources.Chunk, 64)
go func() {
@@ -2356,49 +2357,22 @@ func TestSource_DebugLogging(t *testing.T) {
}()
assert.NoError(t, s.Chunks(ctx, chunksCh))
close(chunksCh)
+ return logs.All()
}
t.Run("debug on", func(t *testing.T) {
- ctx, logs := logtest.DebugContext()
- ctx = context.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)
- runSource(ctx)
-
- // lines from each level we care about show up
- for _, msg := range []string{
- "git source initialized", // V(1)
- "successfully cloned repo", // V(2)
- "scanning commit", // V(3)
- "git subcommand finished", // V(5)
- "scanning git repo complete", // V(2)
- } {
- assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)
- }
-
- // every line came from the context logger, so it carries the source fields,
- // and none of them contain the secret
- for _, entry := range logs.All() {
- fields := entry.ContextMap()
- assert.Contains(t, fields, "source_name", "line %q", entry.Message)
- assert.Contains(t, fields, "job_id", "line %q", entry.Message)
- assert.NotContains(t, entry.Message, testSecret)
- assert.NotContains(t, fmt.Sprint(fields), testSecret)
- }
+ logtest.CheckSourceLines(t, runSource(t, true), testSecret)
})
t.Run("debug off", func(t *testing.T) {
- core, logs := observer.New(zapcore.InfoLevel)
- ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
- runSource(ctx)
-
- assert.Zero(t, logs.FilterMessage("git subcommand finished").Len())
- assert.Zero(t, logs.FilterMessage("scanning commit").Len())
+ logtest.CheckNoDebugLines(t, runSource(t, false))
})
}
func TestCloneRepo_DoesNotLogToken(t *testing.T) {
const token = "TESTTOKEN-do-not-log-1234567890"
- ctx, logs := logtest.DebugContext()
+ ctx, logs := logtest.SourceContext(true)
// nothing listens on port 1, so the clone fails fast and is not retried;
// the token is passed separately and only added to the URL inside CloneRepo
@@ -2406,11 +2380,7 @@ func TestCloneRepo_DoesNotLogToken(t *testing.T) {
assert.Error(t, err)
assert.NotContains(t, err.Error(), token)
- assert.NotZero(t, logs.FilterMessage("git clone attempt failed").Len())
- for _, entry := range logs.All() {
- assert.NotContains(t, entry.Message, token)
- assert.NotContains(t, fmt.Sprint(entry.ContextMap()), token)
- }
+ logtest.CheckSourceLines(t, logs.All(), token)
}
func TestRedactPasswords(t *testing.T) {
diff --git a/pkg/sources/github/github_test.go b/pkg/sources/github/github_test.go
index b00ba3908..92c2aa8bf 100644
--- a/pkg/sources/github/github_test.go
+++ b/pkg/sources/github/github_test.go
@@ -19,12 +19,10 @@ import (
"testing"
"time"
- "github.com/go-logr/zapr"
"github.com/google/go-cmp/cmp"
"github.com/google/go-github/v67/github"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"golang.org/x/sync/errgroup"
@@ -3084,8 +3082,12 @@ func TestEnumerateWithToken_DebugLogging(t *testing.T) {
JSON(`[]`)
}
- // init the source with the given context and list the repos
- runEnumerate := func(t *testing.T, ctx context.Context) *Source {
+ // init the source and list the repos
+ runEnumerate := func(t *testing.T, debug bool) []observer.LoggedEntry {
+ defer gock.Off()
+ mockAPI()
+
+ ctx, logs := logtest.SourceContext(debug)
s, conn := createTestSource(&sourcespb.GitHub{
Endpoint: "https://api.github.com",
Credential: &sourcespb.GitHub_Token{Token: testToken},
@@ -3093,65 +3095,22 @@ func TestEnumerateWithToken_DebugLogging(t *testing.T) {
IgnoreRepos: []string{"test-user/ignored-repo"},
})
assert.NoError(t, s.Init(ctx, "test - github", 1, 1337, false, conn, 1))
+ if debug {
+ logtest.CheckInitLine(t, logs.All())
+ }
gock.InterceptClient(s.connector.APIClient().Client())
assert.NoError(t, s.enumerateWithToken(ctx, false, noopReporter()))
assert.True(t, gock.IsDone())
- return s
+ return logs.All()
}
t.Run("debug on", func(t *testing.T) {
- defer gock.Off()
- mockAPI()
-
- ctx, logs := logtest.DebugContext()
- ctx = context.WithValues(ctx, "source_name", "test - github", "job_id", 1)
- s := runEnumerate(t, ctx)
- assert.True(t, s.filteredRepoCache.Exists("test-user/kept-repo"))
-
- // the config line from Init shows the auth type and filters, not the token
- initLines := logs.FilterMessage("github source initialized").All()
- if assert.Len(t, initLines, 1) {
- fields := initLines[0].ContextMap()
- assert.Equal(t, "*sourcespb.GitHub_Token", fields["auth_type"])
- assert.Equal(t, int64(1), fields["ignore_repo_count"])
- assert.Equal(t, true, fields["exclude_archived"])
- }
-
- // the page line and one skip line for each skipped repo, with the reason
- assert.Equal(t, 1, logs.FilterMessage("Listed repos").Len())
- reasons := map[string]string{}
- for _, entry := range logs.FilterMessage("skipping repository").All() {
- fields := entry.ContextMap()
- reasons[fields["repo"].(string)] = fields["reason"].(string)
- }
- assert.Equal(t, map[string]string{
- "test-user/forked-repo": "forks are not included",
- "test-user/archived-repo": "archived repos are excluded",
- "test-user/ignored-repo": "excluded by include or ignore filter",
- }, reasons)
-
- // every line came from the context logger, so it has the source fields,
- // and no line contains the token
- for _, entry := range logs.All() {
- fields := entry.ContextMap()
- assert.Contains(t, fields, "source_name", "line %q", entry.Message)
- assert.Contains(t, fields, "job_id", "line %q", entry.Message)
- assert.NotContains(t, entry.Message, testToken)
- assert.NotContains(t, fmt.Sprint(fields), testToken)
- }
+ logtest.CheckSourceLines(t, runEnumerate(t, true), testToken)
})
t.Run("debug off", func(t *testing.T) {
- defer gock.Off()
- mockAPI()
-
- core, logs := observer.New(zapcore.InfoLevel)
- ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
- runEnumerate(t, ctx)
-
- assert.Zero(t, logs.FilterMessage("Listed repos").Len())
- assert.Zero(t, logs.FilterMessage("skipping repository").Len())
+ logtest.CheckNoDebugLines(t, runEnumerate(t, false))
})
}
@@ -3173,7 +3132,7 @@ func TestScan_LogsResumeAndCancelSkips(t *testing.T) {
// cancel before the scan starts, so no repo is cloned and each one is
// skipped with a log line instead
- debugCtx, logs := logtest.DebugContext()
+ debugCtx, logs := logtest.SourceContext(true)
ctx, cancel := context.WithCancel(debugCtx)
cancel()
@@ -3185,17 +3144,7 @@ func TestScan_LogsResumeAndCancelSkips(t *testing.T) {
assert.Equal(t, int64(2), resumeLines[0].ContextMap()["remaining"])
}
- var cancelled []string
- for _, entry := range logs.FilterMessage("skipping repo").All() {
- assert.Equal(t, "scan cancelled", entry.ContextMap()["reason"])
- cancelled = append(cancelled, entry.ContextMap()["repo"].(string))
- }
- assert.ElementsMatch(t, []string{"https://github.com/org/b.git", "https://github.com/org/c.git"}, cancelled)
-
- for _, entry := range logs.All() {
- assert.NotContains(t, entry.Message, testToken)
- assert.NotContains(t, fmt.Sprint(entry.ContextMap()), testToken)
- }
+ logtest.CheckSourceLines(t, logs.All(), testToken)
}
func TestInit_InvalidRepoErrorDoesNotLogToken(t *testing.T) {
@@ -3209,19 +3158,11 @@ func TestInit_InvalidRepoErrorDoesNotLogToken(t *testing.T) {
Repositories: []string{"https://" + testToken + "@github.com/org"},
})
- ctx, logs := logtest.DebugContext()
+ ctx, logs := logtest.SourceContext(true)
assert.NoError(t, s.Init(ctx, "test - github", 0, 1337, false, conn, 1))
- errLines := logs.FilterMessage("invalid repository").All()
- if assert.Len(t, errLines, 1) {
- fields := errLines[0].ContextMap()
- assert.Equal(t, "https://github.com/org", fields["repo"])
- assert.Contains(t, fields["error"], "missing the repo name")
- }
- for _, entry := range logs.All() {
- assert.NotContains(t, entry.Message, testToken)
- assert.NotContains(t, fmt.Sprint(entry.ContextMap()), testToken)
- }
+ logtest.CheckInitLine(t, logs.All())
+ logtest.CheckSourceLines(t, logs.All(), testToken)
}
func TestAddReposForMembers_StopsOnCancel(t *testing.T) {
@@ -3232,12 +3173,12 @@ func TestAddReposForMembers_StopsOnCancel(t *testing.T) {
s.memberCache = map[string]struct{}{"member1": {}, "member2": {}}
// cancel before the loop starts, so no member is fetched and no error is logged
- debugCtx, logs := logtest.DebugContext()
+ debugCtx, logs := logtest.SourceContext(true)
ctx, cancel := context.WithCancel(debugCtx)
cancel()
s.addReposForMembers(ctx, noopReporter())
- assert.Equal(t, 1, logs.FilterMessage("skipping remaining members").Len())
assert.Zero(t, logs.FilterLevelExact(zapcore.ErrorLevel).Len())
+ logtest.CheckSourceLines(t, logs.All())
}
diff --git a/pkg/sources/gitlab/gitlab_test.go b/pkg/sources/gitlab/gitlab_test.go
index fdb639c21..723712324 100644
--- a/pkg/sources/gitlab/gitlab_test.go
+++ b/pkg/sources/gitlab/gitlab_test.go
@@ -3,18 +3,14 @@ package gitlab
import (
stdctx "context"
"encoding/json"
- "fmt"
"net/http"
"net/http/httptest"
"reflect"
"sync/atomic"
"testing"
- "github.com/go-logr/zapr"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
@@ -239,7 +235,8 @@ func TestSource_DebugLogging(t *testing.T) {
return srv
}
- runSource := func(t *testing.T, ctx context.Context) sourcestest.TestReporter {
+ runSource := func(t *testing.T, debug bool) []observer.LoggedEntry {
+ ctx, logs := logtest.SourceContext(debug)
srv := newFakeGitLab(t)
conn, err := anypb.New(&sourcespb.GitLab{
Credential: &sourcespb.GitLab_Token{Token: testToken},
@@ -251,83 +248,28 @@ func TestSource_DebugLogging(t *testing.T) {
s := Source{}
require.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))
+ if debug {
+ logtest.CheckInitLine(t, logs.All())
+ }
// Init only accepts https, so point the client at the fake server afterwards.
s.url = srv.URL + "/"
reporter := sourcestest.TestReporter{}
require.NoError(t, s.Enumerate(ctx, &reporter))
require.Empty(t, reporter.UnitErrs)
- require.Len(t, reporter.Units, 2)
// an ignored unit returns before cloning
ignored := git.SourceUnit{Kind: git.UnitRepo, ID: "https://gitlab.example.com/org/ignored.git"}
require.NoError(t, s.ChunkUnit(ctx, ignored, &reporter))
- return reporter
+ return logs.All()
}
t.Run("debug on", func(t *testing.T) {
- ctx, logs := logtest.DebugContext()
- ctx = context.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)
- runSource(t, ctx)
-
- // lines from each level show up
- for _, msg := range []string{
- "GitLab source initialized", // V(1)
- "starting group projects enumeration", // V(1)
- "processing group", // V(2)
- "accepting project", // V(3)
- "listed group projects", // V(4)
- "skipping project", // V(4)
- "GitLab API request failed", // V(4)
- "Retrying GitLab API request", // V(4)
- "cache set: added project metadata in the cache", // V(5)
- } {
- assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)
- }
-
- // both pages were logged, with their group
- pages := logs.FilterMessage("listed group projects").All()
- require.Len(t, pages, 2)
- for i, entry := range pages {
- assert.EqualValues(t, i+1, entry.ContextMap()["page"])
- assert.Equal(t, "1", entry.ContextMap()["group_id"])
- }
-
- // the failed request says what failed
- failed := logs.FilterMessage("GitLab API request failed").All()
- require.Len(t, failed, 1)
- assert.EqualValues(t, http.StatusServiceUnavailable, failed[0].ContextMap()["status"])
- assert.Equal(t, "/api/v4/groups/1/projects", failed[0].ContextMap()["path"])
-
- // both skips (in enumeration and in ChunkUnit) say why
- skips := logs.FilterMessage("skipping project").All()
- require.Len(t, skips, 2)
- for _, entry := range skips {
- assert.Equal(t, "ignored in config", entry.ContextMap()["reason"])
- }
- assert.Equal(t, "https://gitlab.example.com/org/ignored.git", skips[1].ContextMap()["repo"])
-
- // every line came from the context logger, so it carries the source fields,
- // and none of them contain the token
- for _, entry := range logs.All() {
- fields := entry.ContextMap()
- assert.Contains(t, fields, "source_name", "line %q", entry.Message)
- assert.Contains(t, fields, "job_id", "line %q", entry.Message)
- assert.NotContains(t, entry.Message, testToken)
- assert.NotContains(t, fmt.Sprint(fields), testToken)
- }
+ logtest.CheckSourceLines(t, runSource(t, true), testToken)
})
t.Run("debug off", func(t *testing.T) {
- core, logs := observer.New(zapcore.InfoLevel)
- ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
- runSource(t, ctx)
-
- assert.Zero(t, logs.FilterMessage("skipping project").Len())
- assert.Zero(t, logs.FilterMessage("listed group projects").Len())
- assert.Zero(t, logs.FilterMessage("GitLab API request failed").Len())
- assert.Zero(t, logs.FilterMessage("Retrying GitLab API request").Len())
- assert.Zero(t, logs.FilterMessage("cache set: added project metadata in the cache").Len())
+ logtest.CheckNoDebugLines(t, runSource(t, false))
})
}
diff --git a/pkg/sources/postman/postman_test.go b/pkg/sources/postman/postman_test.go
index 3cbb386df..52019adae 100644
--- a/pkg/sources/postman/postman_test.go
+++ b/pkg/sources/postman/postman_test.go
@@ -2,7 +2,6 @@ package postman
import (
"fmt"
- "net/http"
"reflect"
"sort"
"strings"
@@ -10,12 +9,9 @@ import (
"time"
"github.com/go-errors/errors"
- "github.com/go-logr/zapr"
"github.com/hashicorp/go-retryablehttp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
@@ -1072,8 +1068,9 @@ func TestSource_DebugLogging(t *testing.T) {
}})
}
- runSource := func(t *testing.T, ctx context.Context) {
+ runSource := func(t *testing.T, debug bool) []observer.LoggedEntry {
t.Helper()
+ ctx, logs := logtest.SourceContext(debug)
defer gock.Off()
mockAPI()
@@ -1086,6 +1083,9 @@ func TestSource_DebugLogging(t *testing.T) {
// data is only sent with a detector keyword next to it, the engine sets these
s.DetectorKeywords = map[string]struct{}{"api_key": {}}
require.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))
+ if debug {
+ logtest.CheckInitLine(t, logs.All())
+ }
// intercept the client inside the retryable client, so the retry and response
// hooks still run
@@ -1097,73 +1097,16 @@ func TestSource_DebugLogging(t *testing.T) {
require.NoError(t, s.Chunks(ctx, chunksCh))
close(chunksCh)
- var found bool
- for chunk := range chunksCh {
- if strings.Contains(string(chunk.Data), testSecret) {
- found = true
- }
- }
- assert.True(t, found, "secret was not scanned")
assert.True(t, gock.IsDone(), "pending mocks: %v", gock.Pending())
+ return logs.All()
}
t.Run("debug on", func(t *testing.T) {
- ctx, logs := logtest.DebugContext()
- ctx = context.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)
- runSource(t, ctx)
-
- // lines from each level show up
- for _, msg := range []string{
- "Postman source initialized", // V(1)
- "Scanning workspace", // V(2)
- "Scanning collection", // V(2)
- "Scanning environment", // V(3)
- "Scanning item", // V(3)
- "Skipping collection", // V(4)
- "Skipping environment", // V(4)
- "Skipping item", // V(4)
- "Postman API request failed", // V(4)
- "Retrying Postman API request", // V(4)
- "Fetching workspace", // V(5)
- "Postman API response", // V(5)
- "Sending chunk", // V(5)
- } {
- assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)
- }
-
- failed := logs.FilterMessage("Postman API request failed").All()
- require.Len(t, failed, 1)
- assert.Equal(t, "/workspaces/ws1", failed[0].ContextMap()["path"])
- assert.EqualValues(t, http.StatusServiceUnavailable, failed[0].ContextMap()["status"])
-
- for _, msg := range []string{"Skipping collection", "Skipping environment"} {
- skips := logs.FilterMessage(msg).All()
- require.Len(t, skips, 1, msg)
- assert.Equal(t, "matches filter", skips[0].ContextMap()["reason"])
- }
- skips := logs.FilterMessage("Skipping item").All()
- require.Len(t, skips, 1)
- assert.Equal(t, "already seen", skips[0].ContextMap()["reason"])
-
- // every line came from the context logger, so it carries the source fields,
- // and none of them contain the token or the secret
- for _, entry := range logs.All() {
- fields := entry.ContextMap()
- assert.Contains(t, fields, "source_name", "line %q", entry.Message)
- assert.Contains(t, fields, "job_id", "line %q", entry.Message)
- for _, value := range []string{testToken, testSecret} {
- assert.NotContains(t, entry.Message, value)
- assert.NotContains(t, fmt.Sprint(fields), value)
- }
- }
+ logtest.CheckSourceLines(t, runSource(t, true), testToken, testSecret)
})
t.Run("debug off", func(t *testing.T) {
- core, logs := observer.New(zapcore.InfoLevel)
- ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
- runSource(t, ctx)
-
- assert.Zero(t, logs.Len(), "unexpected lines: %v", logs.All())
+ logtest.CheckNoDebugLines(t, runSource(t, false))
})
}
diff --git a/pkg/sources/s3/s3_test.go b/pkg/sources/s3/s3_test.go
index e4b3192b0..ef8ef3ada 100644
--- a/pkg/sources/s3/s3_test.go
+++ b/pkg/sources/s3/s3_test.go
@@ -16,12 +16,9 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
- "github.com/go-logr/zapr"
"github.com/kylelemons/godebug/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"google.golang.org/protobuf/types/known/anypb"
@@ -688,7 +685,8 @@ func TestSource_DebugLogging(t *testing.T) {
}}}}
// run the source with both Chunks and ChunkUnit, draining chunks the way the engine does
- runSource := func(t *testing.T, ctx context.Context) {
+ runSource := func(t *testing.T, debug bool) []observer.LoggedEntry {
+ ctx, logs := logtest.SourceContext(debug)
server := httptest.NewServer(&slowDownOnce{next: fake, key: "config.txt"})
t.Cleanup(server.Close)
conn, err := anypb.New(&sourcespb.S3{
@@ -701,6 +699,9 @@ func TestSource_DebugLogging(t *testing.T) {
s := Source{}
require.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))
+ if debug {
+ logtest.CheckInitLine(t, logs.All())
+ }
chunksCh := make(chan *sources.Chunk, 64)
go func() {
@@ -714,65 +715,14 @@ func TestSource_DebugLogging(t *testing.T) {
require.NoError(t, s.ChunkUnit(ctx, S3SourceUnit{Bucket: "bucket"}, &reporter))
require.Empty(t, reporter.ChunkErrs)
require.NotEmpty(t, reporter.Chunks)
+ return logs.All()
}
t.Run("debug on", func(t *testing.T) {
- ctx, logs := logtest.DebugContext()
- ctx = context.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)
- runSource(t, ctx)
-
- // lines from each level show up
- for _, msg := range []string{
- "S3 source initialized", // V(1)
- "Found buckets to scan", // V(1)
- "Scanning bucket", // V(2)
- "Finished scanning bucket", // V(2)
- "Scanning object", // V(3)
- "Listed page", // V(4)
- "Finished scanning object", // V(5)
- } {
- assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)
- }
-
- // every skip says why, at V(4)
- var reasons []string
- for _, entry := range logs.FilterMessage("Skipping object").All() {
- reasons = append(reasons, fmt.Sprint(entry.ContextMap()["reason"]))
- }
- assert.Contains(t, reasons, skipReasonEmptyFile)
- assert.Contains(t, reasons, skipReasonObjectFilter)
- assert.Contains(t, reasons, "directory")
-
- // the throttled GET was retried, and the retry was logged through the request's context
- var retried bool
- for _, entry := range logs.FilterMessage("AWS SDK").All() {
- fields := entry.ContextMap()
- if strings.Contains(fmt.Sprint(fields["detail"]), "retrying request") {
- retried = true
- assert.Equal(t, "config.txt", fields["key"])
- }
- }
- assert.True(t, retried, "missing retry log line")
-
- // every line came from the context logger, so it carries the source fields,
- // and none of them contain the secret
- for _, entry := range logs.All() {
- fields := entry.ContextMap()
- assert.Contains(t, fields, "source_name", "line %q", entry.Message)
- assert.Contains(t, fields, "job_id", "line %q", entry.Message)
- assert.NotContains(t, entry.Message, testSecret)
- assert.NotContains(t, fmt.Sprint(fields), testSecret)
- }
+ logtest.CheckSourceLines(t, runSource(t, true), testSecret)
})
t.Run("debug off", func(t *testing.T) {
- core, logs := observer.New(zapcore.InfoLevel)
- ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
- runSource(t, ctx)
-
- assert.Zero(t, logs.FilterMessage("Scanning object").Len())
- assert.Zero(t, logs.FilterMessage("Skipping object").Len())
- assert.Zero(t, logs.FilterMessage("Finished scanning object").Len())
- assert.Zero(t, logs.FilterMessage("AWS SDK").Len())
+ logtest.CheckNoDebugLines(t, runSource(t, false))
})
}
diff --git a/pkg/sources/source_manager_test.go b/pkg/sources/source_manager_test.go
index f28087542..44fe3e5b7 100644
--- a/pkg/sources/source_manager_test.go
+++ b/pkg/sources/source_manager_test.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
"go.uber.org/zap/zaptest/observer"
"google.golang.org/protobuf/types/known/anypb"
@@ -755,3 +756,19 @@ func TestSourceManagerAddsSourceFieldsToLogs(t *testing.T) {
assert.Equal(t, "set by caller", entry.ContextMap()["source_name"])
})
}
+
+// logtest.SourceFields must match the fields withSourceFields adds, since source
+// tests check every line for them.
+func TestSourceFieldsMatchLogtest(t *testing.T) {
+ ctx, logs := logtest.DebugContext()
+ source, err := buildDummy(&counterChunker{count: 1})
+ require.NoError(t, err)
+
+ withSourceFields(ctx, source, NewJobProgress(1, 2, "dummy")).Logger().Info("line")
+
+ var keys []string
+ for key := range logs.All()[0].ContextMap() {
+ keys = append(keys, key)
+ }
+ assert.ElementsMatch(t, logtest.SourceFields, keys)
+}