From 11fc55d67994fdc8e7766420bd1afb3a8826e11d Mon Sep 17 00:00:00 2001 From: James Shubin Date: Tue, 5 Mar 2019 11:34:31 -0500 Subject: [PATCH] lang: funcs: Add a new test for readfile and fix a small bug This adds a new test for readfile. Interestingly, it actually caught a small bug, which was also fixed with this commit. I think the bug was actually always masked, because it only occurred on shutdown, and in this case we often don't care about how the stream exited, but it's a good example of how a test case focused on just one small aspect can be important. As an aside, this test case also would have caught the bug fixed in 94c40909cc3a925fa315e6f912bb6a750d304cb8 and by reverting that patch it indeed fails. --- lang/funcs/core/core_test.go | 36 +++++++++++++++++++++++++++++ lang/funcs/core/os/readfile_func.go | 3 ++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lang/funcs/core/core_test.go b/lang/funcs/core/core_test.go index 6823aab7..0e41fc85 100644 --- a/lang/funcs/core/core_test.go +++ b/lang/funcs/core/core_test.go @@ -454,7 +454,43 @@ func TestLiveFuncExec0(t *testing.T) { cleanup: func() error { return nil }, }) } + { + p := "/tmp/somefiletoread" + content := "hello world!\n" + timeline := []Step{ + NewSendInputs([]types.Value{ + vog(p), + }), + NewWaitForNValues(1, timeout), // more than 1 blocks here + NewWaitForNSeconds(5, 10), // wait longer just to be sure + + // pass in a custom validation function + NewRangeExpect(func(args []types.Value) error { + //fmt.Printf("range: %+v\n", args) // debugging + if c := len(args); c != 1 { + return fmt.Errorf("wrong args count, got: %d", c) + } + if args[0].Type().Kind != types.KindStr { + return fmt.Errorf("expected str, got: %+v", args[0]) + } + if err := vog(content).Cmp(args[0]); err != nil { + return errwrap.Wrapf(err, "got different expected value: %+v", args[0]) + } + return nil + }), + } + + testCases = append(testCases, test{ + name: "readfile", + hostname: "", // not needed for this func + funcname: "os.readfile", + timeline: timeline, + expect: func() error { return nil }, + startup: func() error { return ioutil.WriteFile(p, []byte(content), 0666) }, + cleanup: func() error { return os.Remove(p) }, + }) + } names := []string{} for index, tc := range testCases { // run all the tests if tc.name == "" { diff --git a/lang/funcs/core/os/readfile_func.go b/lang/funcs/core/os/readfile_func.go index a328f221..77779916 100644 --- a/lang/funcs/core/os/readfile_func.go +++ b/lang/funcs/core/os/readfile_func.go @@ -206,7 +206,8 @@ func (obj *ReadFileFunc) Stream() error { // Close runs some shutdown code for this function and turns off the stream. func (obj *ReadFileFunc) Close() error { - close(obj.events) // clean up for fun close(obj.closeChan) + obj.wg.Wait() // block so we don't exit by the closure of obj.events + close(obj.events) // clean up for fun return nil }