github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/cmdutil/logging_test.go (about) 1 // Copyright 2018 GRAIL, Inc. All rights reserved. 2 // Use of this source code is governed by the Apache-2.0 3 // license that can be found in the LICENSE file. 4 5 //+build !unit 6 7 package cmdutil_test 8 9 import ( 10 "io/ioutil" 11 "path/filepath" 12 "strings" 13 "testing" 14 15 "github.com/grailbio/testutil" 16 "github.com/stretchr/testify/require" 17 "v.io/x/lib/gosh" 18 ) 19 20 func TestLogging(t *testing.T) { 21 sh := gosh.NewShell(t) 22 if testing.Verbose() { 23 sh.PropagateChildOutput = true 24 } 25 tempdir := sh.MakeTempDir() 26 defer testutil.NoCleanupOnError(t, sh.Cleanup, tempdir) 27 logger := testutil.GoExecutable(t, "//go/src/github.com/Schaudge/grailbase/cmdutil/cmdline-test/cmdline-test") 28 naked := testutil.GoExecutable(t, "//go/src/github.com/Schaudge/grailbase/cmdutil/naked-test/naked-test") 29 testLogging(t, sh, tempdir, logger, naked) 30 testHelp(t, sh, tempdir, logger, naked) 31 } 32 33 func testLogging(t *testing.T, sh *gosh.Shell, tempdir, logger, naked string) { 34 for _, tc := range []struct { 35 cmd string 36 args []string 37 prefix string 38 }{ 39 {logger, []string{"logging"}, "T"}, 40 {logger, []string{"access"}, "T"}, 41 {naked, nil, "T"}, 42 } { 43 args := append(tc.args, "--log_dir="+tempdir, "a", "b") 44 cmd := sh.Cmd(tc.cmd, args...) 45 out := cmd.CombinedOutput() 46 if got, want := strings.TrimSpace(out), tempdir; got != want { 47 t.Errorf("%v: got %v, want %v", tc.cmd, got, want) 48 } 49 data, err := ioutil.ReadFile(filepath.Join(tempdir, filepath.Base(tc.cmd)+".INFO")) 50 require.NoError(t, err) 51 if got, want := string(data), tc.prefix+": 0: a\n"; !strings.Contains(got, want) { 52 t.Errorf("%v: got %v, does not contain %v", tc.cmd, got, want) 53 } 54 args = append(tc.args, "--log_dir="+tempdir, "--alsologtostderr", "a", "b") 55 cmd = sh.Cmd(tc.cmd, args...) 56 out = cmd.CombinedOutput() 57 if got, want := out, tc.prefix+": 1: b\n"; !strings.Contains(got, want) { 58 t.Errorf("%v: got %v, does not contain %v", tc.cmd, got, want) 59 } 60 } 61 } 62 63 func testHelp(t *testing.T, sh *gosh.Shell, tempdir, logger, naked string) { 64 sh.ContinueOnError = true 65 for _, test := range []struct { 66 cmd string 67 contains []string 68 }{ 69 {logger, []string{"cmdline-test [flags] <command>", "The global flags are:", "-alsologtostderr=false"}}, 70 {naked, []string{"Usage of ", "-alsologtostderr\n"}}, 71 } { 72 cmd := sh.Cmd(test.cmd, "-help") 73 got := cmd.CombinedOutput() 74 for _, want := range test.contains { 75 if !strings.Contains(got, want) { 76 t.Errorf("%v: got %v, does not contain %v", test.cmd, got, want) 77 } 78 } 79 sh.Err = nil 80 } 81 sh.ContinueOnError = false 82 }