Skip to content

Commit

Permalink
test: add UT for filewatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
ScottZhuMS committed Jan 6, 2025
1 parent 0ae36d7 commit 4a1375f
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 4 deletions.
11 changes: 7 additions & 4 deletions pkg/filewatcher/filewatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ import (
"k8s.io/klog/v2"
)

// exit is a separate function to handle program termination
var exit = func(code int) {
os.Exit(code)
}

var watchCertificateFileOnce sync.Once

// WatchFileForChanges watches the file, fileToWatch, for changes. If the file contents have changed, the pod this
Expand All @@ -44,9 +49,7 @@ func WatchFileForChanges(fileToWatch string) error {
klog.V(2).Infof("Watching file, %s", fileToWatch)

// Start the file watcher to monitor file changes
go func() {
err = checkForFileChanges(fileToWatch)
}()
err = checkForFileChanges(fileToWatch)
})
return err
}
Expand All @@ -64,7 +67,7 @@ func checkForFileChanges(path string) error {
case event, ok := <-watcher.Events:
if ok && (event.Has(fsnotify.Write) || event.Has(fsnotify.Chmod) || event.Has(fsnotify.Remove)) {
klog.V(2).Infof("file, %s, was modified, exiting...", event.Name)
os.Exit(0)
exit(0)
}
case err, ok := <-watcher.Errors:
if ok {
Expand Down
50 changes: 50 additions & 0 deletions pkg/filewatcher/filewatcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package filewatcher

import (
"os"
"testing"
"time"
)

func TestWatchFileForChanges(t *testing.T) {
// Set mock exit once.
exit = func(_ int) {
// Mock, do nothing
}

// Create a temporary file to watch
tmpfile, err := os.CreateTemp("", "testfile")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())

// Now call the watcher
if err = WatchFileForChanges(tmpfile.Name()); err != nil {
t.Errorf("Failed to watch file: %v", err)
}

// Trigger the watcher
if err = os.WriteFile(tmpfile.Name(), []byte("new content"), 0644); err != nil {
t.Fatal(err)
}

// Let the watcher see the change
time.Sleep(1 * time.Second)
}

0 comments on commit 4a1375f

Please sign in to comment.