pomerium/config/config_source_test.go
Eng Zer Jun 45ce6f693a
test: use T.TempDir to create temporary test directory (#3725)
Prior to this commit, temporary directories in tests were created using
`filepath.Join` and `os.MkdirAll`.

This commit replaces `os.MkdirAll` with `t.TempDir` in tests. The
directory created by `t.TempDir` is automatically removed when the test
and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2022-11-08 09:16:32 -07:00

80 lines
1.7 KiB
Go

package config
import (
"context"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestFileWatcherSource(t *testing.T) {
ctx := context.Background()
tmpdir := t.TempDir()
err := os.WriteFile(filepath.Join(tmpdir, "example.txt"), []byte{1, 2, 3, 4}, 0o600)
if !assert.NoError(t, err) {
return
}
err = os.WriteFile(filepath.Join(tmpdir, "kubernetes-example.txt"), []byte{1, 2, 3, 4}, 0o600)
if !assert.NoError(t, err) {
return
}
ssrc := NewStaticSource(&Config{
Options: &Options{
CAFile: filepath.Join(tmpdir, "example.txt"),
Policies: []Policy{{
KubernetesServiceAccountTokenFile: filepath.Join(tmpdir, "kubernetes-example.txt"),
}},
},
})
src := NewFileWatcherSource(ssrc)
var closeOnce sync.Once
ch := make(chan struct{})
src.OnConfigChange(context.Background(), func(ctx context.Context, cfg *Config) {
closeOnce.Do(func() {
close(ch)
})
})
err = os.WriteFile(filepath.Join(tmpdir, "example.txt"), []byte{5, 6, 7, 8}, 0o600)
if !assert.NoError(t, err) {
return
}
select {
case <-ch:
case <-time.After(time.Second):
t.Error("expected OnConfigChange to be fired after modifying a file")
}
err = os.WriteFile(filepath.Join(tmpdir, "kubernetes-example.txt"), []byte{5, 6, 7, 8}, 0o600)
if !assert.NoError(t, err) {
return
}
select {
case <-ch:
case <-time.After(time.Second):
t.Error("expected OnConfigChange to be fired after modifying a policy file")
}
ssrc.SetConfig(ctx, &Config{
Options: &Options{
CAFile: filepath.Join(tmpdir, "example.txt"),
},
})
select {
case <-ch:
case <-time.After(time.Second):
t.Error("expected OnConfigChange to be fired after triggering a change to the underlying source")
}
}