github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/configobserver_test.go (about) 1 package utils 2 3 import ( 4 "os" 5 "testing" 6 "time" 7 8 "github.com/stretchr/testify/require" 9 ) 10 11 const testConfig0 = `foo: a` 12 const testConfig1 = `foo: b` 13 14 type TestConfig struct { 15 Foo string `yaml:"foo"` 16 Bar string `yaml:"bar"` 17 } 18 19 type testConfigBuilder struct{} 20 21 func (testConfigBuilder) New() (*TestConfig, error) { 22 return &TestConfig{}, nil 23 } 24 25 func (testConfigBuilder) InitDefaults(c *TestConfig) error { 26 c.Bar = "c" 27 return nil 28 } 29 30 func TestConfigObserver(t *testing.T) { 31 f, err := os.CreateTemp(os.TempDir(), "lk-test-*.yaml") 32 t.Cleanup(func() { 33 _ = f.Close() 34 }) 35 require.NoError(t, err) 36 _, err = f.WriteString(testConfig0) 37 require.NoError(t, err) 38 39 obs, conf, err := NewConfigObserver(f.Name(), testConfigBuilder{}) 40 require.NoError(t, err) 41 42 require.Equal(t, "a", conf.Foo) 43 require.Equal(t, "c", conf.Bar) 44 45 done := make(chan struct{}) 46 obs.Observe(func(c *TestConfig) { 47 require.Equal(t, "b", c.Foo) 48 require.Equal(t, "c", c.Bar) 49 close(done) 50 }) 51 52 _, err = f.WriteAt([]byte(testConfig1), 0) 53 require.NoError(t, err) 54 55 select { 56 case <-done: 57 case <-time.After(100 * time.Millisecond): 58 require.FailNow(t, "timed out waiting for config update") 59 } 60 }