From daf2c244862d0a42e871c629239e9da04f2fc993 Mon Sep 17 00:00:00 2001 From: lyt122 <2747177214@qq.com> Date: Sun, 7 Jul 2024 22:34:48 +0800 Subject: [PATCH] add test codes --- plugins/pkg/file/fs_test.go | 51 +++----------------------------- plugins/plugins/casbin/filter.go | 4 ++- 2 files changed, 7 insertions(+), 48 deletions(-) diff --git a/plugins/pkg/file/fs_test.go b/plugins/pkg/file/fs_test.go index f0a96978..33f2acdd 100644 --- a/plugins/pkg/file/fs_test.go +++ b/plugins/pkg/file/fs_test.go @@ -22,19 +22,8 @@ import ( "github.com/fsnotify/fsnotify" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" ) -// MockWatcher is a mock implementation of fsnotify.Watcher -type MockWatcher struct { - mock.Mock -} - -func (m *MockWatcher) Close() error { - args := m.Called() - return args.Error(0) -} - func TestFileIsChanged(t *testing.T) { var wg sync.WaitGroup var mu sync.Mutex @@ -77,7 +66,10 @@ func TestFileIsChanged(t *testing.T) { WatchedFiles: make(map[string]struct{}), Watcher: watcher, } - tmpDir := filepath.Dir(file.Name) + tmpfile, err = os.CreateTemp("/tmp", "test") + assert.Nil(t, err) + defer os.Remove(tmpfile.Name()) + tmpDir := filepath.Dir(tmpfile.Name()) fs.WatchedFiles[tmpDir] = struct{}{} err = fs.AddFiles(tmpDir) assert.NoError(t, err) @@ -94,39 +86,4 @@ func TestFileIsChanged(t *testing.T) { assert.True(t, exists) assert.False(t, onChangeCalled) - err = WatchFiles(func() {}, file, nil) - assert.Error(t, err, "file pointer cannot be nil") -} - -func TestClose(t *testing.T) { - dir := "./" - mockWatcher := new(MockWatcher) - - mockWatcher.On("Close").Return(nil) - - defaultfsnotify := struct { - WatchedFiles map[string]bool - }{ - WatchedFiles: map[string]bool{dir: true}, - } - - f := struct { - mu sync.Mutex - }{} - - func(w *MockWatcher) { - defer func(w *MockWatcher) { - f.mu.Lock() - defer f.mu.Unlock() - delete(defaultfsnotify.WatchedFiles, dir) - err := w.Close() - if err != nil { - t.Errorf("failed to close fsnotify watcher: %v", err) - } - }(w) - }(mockWatcher) - - assert.NotContains(t, defaultFsnotify.WatchedFiles, dir) - - mockWatcher.AssertExpectations(t) } diff --git a/plugins/plugins/casbin/filter.go b/plugins/plugins/casbin/filter.go index 25752428..f0efdcde 100644 --- a/plugins/plugins/casbin/filter.go +++ b/plugins/plugins/casbin/filter.go @@ -39,8 +39,8 @@ var Changed = false func reloadEnforcer(f *filter) { conf := f.config + conf.lock.Lock() if !conf.updating.Load() { - conf.lock.Lock() conf.updating.Store(true) conf.lock.Unlock() api.LogWarnf("policy %s or model %s Changed, reload enforcer", conf.policyFile.Name, conf.modelFile.Name) @@ -74,6 +74,8 @@ func reloadEnforcer(f *filter) { api.LogWarnf("policy %s or model %s Changed, enforcer reloaded", conf.policyFile.Name, conf.modelFile.Name) } }() + } else { + conf.lock.Unlock() } }