Skip to content

Commit

Permalink
add test codes
Browse files Browse the repository at this point in the history
  • Loading branch information
lyt122 committed Jul 7, 2024
1 parent 6719586 commit daf2c24
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 48 deletions.
51 changes: 4 additions & 47 deletions plugins/pkg/file/fs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
4 changes: 3 additions & 1 deletion plugins/plugins/casbin/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()

Check warning on line 78 in plugins/plugins/casbin/filter.go

View check run for this annotation

Codecov / codecov/patch

plugins/plugins/casbin/filter.go#L77-L78

Added lines #L77 - L78 were not covered by tests
}
}

Expand Down

0 comments on commit daf2c24

Please sign in to comment.