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 3, 2025
1 parent 0ae36d7 commit af28bb5
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
7 changes: 6 additions & 1 deletion 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 Down Expand Up @@ -64,7 +69,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
69 changes: 69 additions & 0 deletions pkg/filewatcher/filewatcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
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) {
// Capture stdout
old := os.Stdout
_, w, _ := os.Pipe()
os.Stdout = w

// Replace exit function with mock function
var exitCode int
exit = func(code int) {
exitCode = code
}

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

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

// Simulate a file change
err = os.WriteFile(tmpfile.Name(), []byte("new content"), 0644)
if err != nil {
t.Fatal(err)
}

if exitCode != 0 {
t.Errorf("Expected exit code 0, but got %d", exitCode)
}

os.Remove(tmpfile.Name())

time.Sleep(1 * time.Second)

// Restore stdout
w.Close()
os.Stdout = old
exit = func(code int) {
os.Exit(code)
}
}

0 comments on commit af28bb5

Please sign in to comment.