github.com/livekit/protocol@v1.39.3/utils/configobserver_test.go (about) 1 // Copyright 2024 LiveKit, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package utils 16 17 import ( 18 "os" 19 "testing" 20 "time" 21 22 "github.com/stretchr/testify/require" 23 24 "github.com/livekit/protocol/utils/configutil" 25 ) 26 27 const testConfig0 = `foo: a` 28 const testConfig1 = `foo: b` 29 30 type TestConfig struct { 31 Foo string `yaml:"foo"` 32 Bar string `yaml:"bar"` 33 } 34 35 type testConfigBuilder struct{} 36 37 func (testConfigBuilder) New() (*TestConfig, error) { 38 return &TestConfig{}, nil 39 } 40 41 func (testConfigBuilder) InitDefaults(c *TestConfig) error { 42 c.Bar = "c" 43 return nil 44 } 45 46 func TestConfigObserver(t *testing.T) { 47 f, err := os.CreateTemp(os.TempDir(), "lk-test-*.yaml") 48 t.Cleanup(func() { 49 _ = f.Close() 50 }) 51 require.NoError(t, err) 52 _, err = f.WriteString(testConfig0) 53 require.NoError(t, err) 54 55 obs, conf, err := NewConfigObserver(f.Name(), testConfigBuilder{}) 56 require.NoError(t, err) 57 58 require.Equal(t, "a", conf.Foo) 59 require.Equal(t, "c", conf.Bar) 60 61 atomicFoo := configutil.NewAtomicValue(obs, func(c *TestConfig) string { 62 return c.Foo 63 }) 64 65 require.Equal(t, "a", atomicFoo.Load()) 66 67 done := make(chan struct{}) 68 obs.Observe(func(c *TestConfig) { 69 require.Equal(t, "b", c.Foo) 70 require.Equal(t, "c", c.Bar) 71 close(done) 72 }) 73 74 _, err = f.WriteAt([]byte(testConfig1), 0) 75 require.NoError(t, err) 76 77 select { 78 case <-done: 79 case <-time.After(100 * time.Millisecond): 80 require.FailNow(t, "timed out waiting for config update") 81 } 82 83 require.Equal(t, "b", atomicFoo.Load()) 84 }