blob: f67cc84fb4531bb73c43f47edf008d3ae78dc3f2 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Serge Bazanskif8a8e652021-07-06 16:23:43 +02004package logtree
5
6import (
7 "context"
Serge Bazanskif8a8e652021-07-06 16:23:43 +02008 "testing"
9)
10
Serge Bazanski29974f32023-04-05 12:29:09 +020011// PipeAllToTest starts a goroutine that will forward all logtree entries
12// t.Logf(), in the canonical logtree payload representation.
Serge Bazanskif8a8e652021-07-06 16:23:43 +020013//
14// It's designed to be used in tests, and will automatically stop when the
15// test/benchmark it's running in exits.
Serge Bazanski29974f32023-04-05 12:29:09 +020016func PipeAllToTest(t testing.TB, lt *LogTree) {
Serge Bazanskif8a8e652021-07-06 16:23:43 +020017 t.Helper()
18
19 reader, err := lt.Read("", WithChildren(), WithStream())
20 if err != nil {
21 t.Fatalf("Failed to set up logtree reader: %v", err)
22 }
23
24 // Internal context used to cancel the goroutine. This could also be a
25 // implemented via a channel.
26 ctx, ctxC := context.WithCancel(context.Background())
27 t.Cleanup(ctxC)
28
29 go func() {
Serge Bazanski29974f32023-04-05 12:29:09 +020030 t.Helper()
Serge Bazanskif8a8e652021-07-06 16:23:43 +020031 for {
32 select {
33 case <-ctx.Done():
34 return
35 case p := <-reader.Stream:
Serge Bazanski29974f32023-04-05 12:29:09 +020036 t.Logf("%s", p.String())
Serge Bazanskif8a8e652021-07-06 16:23:43 +020037 }
38 }
39 }()
40}