Skip to content

Commit

Permalink
add config observer test (#645)
Browse files Browse the repository at this point in the history
* add config observer test

* cleanup
  • Loading branch information
paulwe authored Mar 11, 2024
1 parent 76870e1 commit 34e705a
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
2 changes: 1 addition & 1 deletion utils/configobserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type ConfigBuilder[T any] interface {
}

type ConfigDefaulter[T any] interface {
InitDefaults(*T)
InitDefaults(*T) error
}

type ConfigObserver[T any] struct {
Expand Down
60 changes: 60 additions & 0 deletions utils/configobserver_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package utils

import (
"os"
"testing"
"time"

"github.com/stretchr/testify/require"
)

const testConfig0 = `foo: a`
const testConfig1 = `foo: b`

type TestConfig struct {
Foo string `yaml:"foo"`
Bar string `yaml:"bar"`
}

type testConfigBuilder struct{}

func (testConfigBuilder) New() (*TestConfig, error) {
return &TestConfig{}, nil
}

func (testConfigBuilder) InitDefaults(c *TestConfig) error {
c.Bar = "c"
return nil
}

func TestConfigObserver(t *testing.T) {
f, err := os.CreateTemp(os.TempDir(), "lk-test-*.yaml")
t.Cleanup(func() {
_ = f.Close()
})
require.NoError(t, err)
_, err = f.WriteString(testConfig0)
require.NoError(t, err)

obs, conf, err := NewConfigObserver(f.Name(), testConfigBuilder{})
require.NoError(t, err)

require.Equal(t, "a", conf.Foo)
require.Equal(t, "c", conf.Bar)

done := make(chan struct{})
obs.Observe(func(c *TestConfig) {
require.Equal(t, "b", c.Foo)
require.Equal(t, "c", c.Bar)
close(done)
})

_, err = f.WriteAt([]byte(testConfig1), 0)
require.NoError(t, err)

select {
case <-done:
case <-time.After(100 * time.Millisecond):
require.FailNow(t, "timed out waiting for config update")
}
}

0 comments on commit 34e705a

Please sign in to comment.