pomerium/internal/testutil/log.go
dependabot[bot] 615c6257e6
chore(deps): bump github.com/spf13/viper from 1.16.0 to 1.18.2 (#4861)
* chore(deps): bump github.com/spf13/viper from 1.16.0 to 1.18.2

Bumps [github.com/spf13/viper](https://github.com/spf13/viper) from 1.16.0 to 1.18.2.
- [Release notes](https://github.com/spf13/viper/releases)
- [Commits](https://github.com/spf13/viper/compare/v1.16.0...v1.18.2)

---
updated-dependencies:
- dependency-name: github.com/spf13/viper
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* fix race

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Caleb Doxsey <cdoxsey@pomerium.com>
2023-12-27 16:16:38 -07:00

50 lines
775 B
Go

package testutil
import (
"bytes"
"encoding/json"
"io"
"sync"
"testing"
"github.com/pomerium/pomerium/internal/log"
)
// CaptureLogs captures any logs made during the test. Time will be stripped.
// Any tests that use it should not be run in parallel.
func CaptureLogs(t *testing.T, f func()) string {
t.Helper()
pr, pw := io.Pipe()
log.Writer.Add(pw)
defer log.Writer.Remove(pw)
var buf bytes.Buffer
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
d := json.NewDecoder(pr)
for {
var m map[string]any
if d.Decode(&m) != nil {
break
}
delete(m, "time")
bs, _ := json.Marshal(m)
buf.Write(bs)
buf.WriteByte('\n')
}
}()
go func() {
defer wg.Done()
f()
pw.Close()
}()
wg.Wait()
return buf.String()
}