1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 // Package cmdtest provides tools for testing command line tools.
13 check "gopkg.in/check.v1"
16 // LeakCheck tests for output being leaked to os.Stdout and os.Stderr
17 // that should be sent elsewhere (e.g., the stdout and stderr streams
18 // passed to a cmd.RunFunc).
20 // It redirects os.Stdout and os.Stderr to a tempfile, and returns a
21 // func, which the caller is expected to defer, that restores os.* and
22 // checks that the tempfile is empty.
26 // func (s *Suite) TestSomething(c *check.C) {
27 // defer cmdtest.LeakCheck(c)()
28 // // ... do things that shouldn't print to os.Stderr or os.Stdout
30 func LeakCheck(c *check.C) func() {
31 tmpfiles := map[string]*os.File{"stdout": nil, "stderr": nil}
32 for i := range tmpfiles {
34 tmpfiles[i], err = ioutil.TempFile("", "")
35 c.Assert(err, check.IsNil)
36 err = os.Remove(tmpfiles[i].Name())
37 c.Assert(err, check.IsNil)
40 stdout, stderr := os.Stdout, os.Stderr
41 os.Stdout, os.Stderr = tmpfiles["stdout"], tmpfiles["stderr"]
43 os.Stdout, os.Stderr = stdout, stderr
45 for i, tmpfile := range tmpfiles {
46 c.Logf("checking %s", i)
47 _, err := tmpfile.Seek(0, io.SeekStart)
48 c.Assert(err, check.IsNil)
49 leaked, err := ioutil.ReadAll(tmpfile)
50 c.Assert(err, check.IsNil)
51 c.Check(string(leaked), check.Equals, "")