github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/cmds/core/backoff/main_test.go (about) 1 // Copyright 2021 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "bytes" 9 "errors" 10 "fmt" 11 "regexp" 12 "strings" 13 "testing" 14 15 "github.com/mvdan/u-root-coreutils/pkg/testutil" 16 ) 17 18 func TestRunIt(t *testing.T) { 19 for _, tt := range []struct { 20 name string 21 timeout string 22 cmd string 23 args []string 24 wantErr error 25 }{ 26 { 27 name: "_date", 28 timeout: "3s", 29 cmd: "date", 30 }, 31 { 32 name: "noCmd", 33 timeout: "3s", 34 cmd: "", 35 wantErr: ErrNoCmd, 36 }, 37 { 38 name: "echo", 39 timeout: "3s", 40 cmd: "echo", 41 args: []string{"hi"}, 42 }, 43 { 44 name: "echo_missing_unit", 45 timeout: "3", 46 cmd: "echo", 47 args: []string{"hi"}, 48 wantErr: fmt.Errorf("time: missing unit in duration \"3\""), 49 }, 50 } { 51 t.Run(tt.name, func(t *testing.T) { 52 if err := runit(tt.timeout, tt.cmd, tt.args...); !errors.Is(err, tt.wantErr) { 53 if err != nil { 54 if !strings.Contains(err.Error(), tt.wantErr.Error()) { 55 t.Errorf("runit(%s, %s, %s)= %q, want %q", tt.timeout, tt.cmd, tt.args, err, tt.wantErr) 56 } 57 } 58 } 59 }) 60 } 61 } 62 63 // TestOK for now just runs a simple successful test with 0 args or more than one arg. 64 func TestOK(t *testing.T) { 65 var tests = []struct { 66 args []string 67 stdout string 68 stderr string 69 exitok bool 70 }{ 71 {args: []string{}, stdout: "", exitok: false}, 72 {args: []string{"date"}, stdout: ".*", exitok: true}, 73 {args: []string{"-t", "wh", "date"}, stdout: ".*", stderr: ".*invalid.*duration.*wh", exitok: false}, 74 {args: []string{"echo", "hi"}, stdout: ".*hi", exitok: true}, 75 {args: []string{"-t", "3s", "false"}, exitok: false}, 76 } 77 78 for _, v := range tests { 79 c := testutil.Command(t, v.args...) 80 stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} 81 c.Stdout, c.Stderr = stdout, stderr 82 err := c.Run() 83 if (err != nil) && v.exitok { 84 t.Errorf("%v: got %v, want nil", v, err) 85 } 86 if (err == nil) && !v.exitok { 87 t.Errorf("%v: got nil, want err", v) 88 } 89 m, err := regexp.MatchString(v.stderr, stderr.String()) 90 if err != nil { 91 t.Errorf("stderr: %v: got %v, want nil", v, err) 92 } else { 93 if !m { 94 t.Errorf("%v: regexp.MatchString(%s, %s) false, wanted match", v, v.stderr, stderr) 95 } 96 } 97 98 m, err = regexp.MatchString(v.stdout, stdout.String()) 99 if err != nil { 100 t.Errorf("stdout: %v: got %v, want nil", v, err) 101 } 102 if !m { 103 t.Errorf("%v: regexp.MatchString(%s, %s) false, wanted match", v, v.stdout, stderr.String()) 104 } 105 } 106 } 107 108 // If you really like fork-bombing your machine, remove these lines :-) 109 func TestMain(m *testing.M) { 110 testutil.Run(m, main) 111 }