talos
109 строк · 2.5 Кб
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5package conditions_test
6
7import (
8"context"
9"testing"
10"time"
11
12"github.com/stretchr/testify/suite"
13
14"github.com/siderolabs/talos/pkg/conditions"
15)
16
17type AllSuite struct {
18suite.Suite
19}
20
21type MockCondition struct {
22description string
23errCh chan error
24}
25
26func (mc *MockCondition) String() string {
27return mc.description
28}
29
30func (mc *MockCondition) Wait(ctx context.Context) error {
31select {
32case <-ctx.Done():
33return ctx.Err()
34case err := <-mc.errCh:
35return err
36}
37}
38
39func (suite *AllSuite) TestString() {
40suite.Require().Equal("A, B", conditions.WaitForAll(
41&MockCondition{description: "A"},
42&MockCondition{description: "B"},
43).String())
44
45suite.Require().Equal("A", conditions.WaitForAll(
46&MockCondition{description: "A"},
47).String())
48
49conds := []conditions.Condition{
50&MockCondition{description: "A", errCh: make(chan error)},
51&MockCondition{description: "B", errCh: make(chan error)},
52}
53
54waiter := conditions.WaitForAll(conds...)
55
56done := make(chan error)
57
58go func() {
59done <- waiter.Wait(context.Background())
60}()
61
62suite.Require().Equal("A, B", waiter.String())
63conds[0].(*MockCondition).errCh <- nil
64time.Sleep(50 * time.Millisecond)
65
66// done waiting for 'A', so description should now be shorter
67suite.Require().Equal("B", waiter.String())
68
69conds[1].(*MockCondition).errCh <- nil
70<-done
71}
72
73func (suite *AllSuite) TestFlatten() {
74conds1 := []conditions.Condition{
75&MockCondition{description: "A", errCh: make(chan error)},
76&MockCondition{description: "B", errCh: make(chan error)},
77}
78conds2 := []conditions.Condition{
79&MockCondition{description: "C", errCh: make(chan error)},
80&MockCondition{description: "D", errCh: make(chan error)},
81}
82
83waiter := conditions.WaitForAll(conditions.WaitForAll(conds1...), conditions.WaitForAll(conds2...))
84suite.Require().Equal("A, B, C, D", waiter.String())
85
86ctx, ctxCancel := context.WithCancel(context.Background())
87defer ctxCancel()
88
89done := make(chan error)
90
91go func() {
92done <- waiter.Wait(ctx)
93}()
94
95conds1[0].(*MockCondition).errCh <- nil
96conds2[1].(*MockCondition).errCh <- nil
97
98time.Sleep(50 * time.Millisecond)
99
100suite.Require().Equal("B, C", waiter.String())
101
102ctxCancel()
103
104suite.Require().Equal(context.Canceled, <-done)
105}
106
107func TestAllSuite(t *testing.T) {
108suite.Run(t, new(AllSuite))
109}
110