@@ -24,6 +24,7 @@ import (
2424 "testing"
2525 "time"
2626
27+ "github.com/fsnotify/fsnotify"
2728 "github.com/intel/intel-device-plugins-for-kubernetes/cmd/internal/pluginutils"
2829)
2930
@@ -715,6 +716,31 @@ func TestCreateAndRun(t *testing.T) {
715716 CreateAndPrintLabels (sysfs )
716717 })
717718
719+ waitForFileOp := func (directory , file string , eventType fsnotify.Op , duration time.Duration ) bool {
720+ watcher , err := fsnotify .NewWatcher ()
721+ if err != nil {
722+ t .Fatal (err )
723+ }
724+ defer watcher .Close ()
725+
726+ if err := watcher .Add (directory ); err != nil {
727+ t .Fatal (err )
728+ }
729+
730+ timer := time .NewTimer (duration )
731+
732+ for {
733+ select {
734+ case event := <- watcher .Events :
735+ if filepath .Base (event .Name ) == file && event .Has (eventType ) {
736+ return true
737+ }
738+ case <- timer .C :
739+ return false
740+ }
741+ }
742+ }
743+
718744 t .Run ("Run" , func (t * testing.T ) {
719745 err := os .MkdirAll (path .Join (subroot , "0" ), 0750 )
720746 if err != nil {
@@ -726,16 +752,13 @@ func TestCreateAndRun(t *testing.T) {
726752
727753 c := make (chan bool , 1 )
728754
729- nfdLabelFile := filepath .Join (root , "nfd-labelfile.txt" )
755+ nfdLabelBase := "nfd-labelfile.txt"
756+ nfdLabelFile := filepath .Join (root , nfdLabelBase )
730757
731758 go Run (sysfs , nfdLabelFile , time .Millisecond , c , nil , func () {})
732759
733760 // Wait for the labeling timeout to trigger
734- time .Sleep (time .Millisecond * 2 )
735-
736- // Make sure the file has been created
737- _ , err = os .Stat (nfdLabelFile )
738- if err != nil {
761+ if ! waitForFileOp (root , nfdLabelBase , fsnotify .Create , time .Second * 2 ) {
739762 t .Error ("Run didn't create label file" )
740763 }
741764
@@ -744,12 +767,9 @@ func TestCreateAndRun(t *testing.T) {
744767 t .Error ("Calling Kill failed" )
745768 }
746769
747- time .Sleep (time .Millisecond * 2 )
748-
749- // Make sure the label file has been deleted
750- _ , err = os .Stat (nfdLabelFile )
751- if err == nil {
752- t .Error ("Run didn't remove label file on exit" )
770+ // Wait for the labeling timeout to trigger
771+ if ! waitForFileOp (root , nfdLabelBase , fsnotify .Remove , time .Second * 2 ) {
772+ t .Error ("Run didn't remove label file" )
753773 }
754774 })
755775}
0 commit comments