Skip to content

Commit

Permalink
test: add negative case UT for filewatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
ScottZhuMS committed Jan 7, 2025
1 parent e0ba16b commit 92aa680
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 16 deletions.
5 changes: 5 additions & 0 deletions pkg/filewatcher/filewatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ var exit = func(code int) {

var watchCertificateFileOnce sync.Once

// resetWatchCertificateFileOnce resets the watchCertificateFileOnce variable. This is used for testing purposes.
func resetWatchCertificateFileOnce() {
watchCertificateFileOnce = sync.Once{}
}

// WatchFileForChanges watches the file, fileToWatch, for changes. If the file contents have changed, the pod this
// function is running on will be restarted.
func WatchFileForChanges(fileToWatch string) error {
Expand Down
46 changes: 30 additions & 16 deletions pkg/filewatcher/filewatcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package filewatcher

import (
"os"
"strings"
"testing"
"time"
)
Expand All @@ -28,23 +29,36 @@ func TestWatchFileForChanges(t *testing.T) {
// 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())
t.Run("ExistingFile", func(t *testing.T) {
// 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)
}
// 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)
}
// 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(100 * time.Millisecond)
})

t.Run("NonExistentFile", func(t *testing.T) {
// Reset the watcher once before the test
resetWatchCertificateFileOnce()

// Let the watcher see the change
time.Sleep(1 * time.Second)
err := WatchFileForChanges("nonexistentfile")
if err == nil || (!strings.Contains(err.Error(), "no such file or directory") &&
!strings.Contains(err.Error(), "The system cannot find the file specified")) {
t.Errorf("expected error to contain 'no such file or directory' or 'The system cannot find the file specified', got %v", err)
}
})
}

0 comments on commit 92aa680

Please sign in to comment.