Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 1 | // Copyright 2020 The Monogon Project Authors. |
| 2 | // |
| 3 | // SPDX-License-Identifier: Apache-2.0 |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | package supervisor |
Serge Bazanski | f8a8e65 | 2021-07-06 16:23:43 +0200 | [diff] [blame] | 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "errors" |
| 22 | "testing" |
| 23 | |
| 24 | "source.monogon.dev/metropolis/pkg/logtree" |
| 25 | ) |
| 26 | |
| 27 | // TestHarness runs a supervisor in a harness designed for unit testing |
| 28 | // runnables and runnable trees. |
| 29 | // |
| 30 | // The given runnable will be run in a new supervisor, and the logs from this |
| 31 | // supervisor will be streamed to stderr. If the runnable returns a non-context |
| 32 | // error, the harness will throw a test error, but will not abort the test. |
| 33 | // |
| 34 | // The harness also returns a context cancel function that can be used to |
| 35 | // terminate the started supervisor early. Regardless of manual cancellation, |
| 36 | // the supervisor will always be terminated up at the end of the test/benchmark |
| 37 | // it's running in. |
| 38 | // |
| 39 | // The second returned value is the logtree used by this supervisor. It can be |
| 40 | // used to assert some log messages are emitted in tests that exercise some |
| 41 | // log-related functionality. |
| 42 | func TestHarness(t *testing.T, r func(ctx context.Context) error) (context.CancelFunc, *logtree.LogTree) { |
| 43 | t.Helper() |
| 44 | |
| 45 | ctx, ctxC := context.WithCancel(context.Background()) |
| 46 | t.Cleanup(ctxC) |
| 47 | |
| 48 | lt := logtree.New() |
| 49 | logtree.PipeAllToStderr(t, lt) |
| 50 | |
| 51 | New(ctx, func(ctx context.Context) error { |
| 52 | if err := r(ctx); err != nil && !errors.Is(err, ctx.Err()) { |
| 53 | t.Errorf("Supervised runnable in harness returned error: %v", err) |
| 54 | } |
| 55 | return nil |
| 56 | }, WithExistingLogtree(lt)) |
| 57 | return ctxC, lt |
| 58 | } |