github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/cmds/core/which/which_test.go (about) 1 // Copyright 2016 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 // created by Rafael Campos Nunes <rafaelnunes@engineer.com> 6 7 package main 8 9 import ( 10 "bytes" 11 "os" 12 "os/exec" 13 "reflect" 14 "strings" 15 "testing" 16 ) 17 18 type commands struct { 19 name string 20 pathOnSys []byte 21 } 22 23 // in setup we fill the pathOnSys variables with their corresponding path on the system. 24 var ( 25 tests = []commands{ 26 { 27 "cat", 28 []byte{}, 29 }, 30 { 31 "which", 32 []byte{}, 33 }, 34 { 35 "sed", 36 []byte{}, 37 }, 38 { 39 "ldd", 40 []byte{}, 41 }, 42 } 43 44 p = os.Getenv("PATH") 45 ) 46 47 func setup() error { 48 var err error 49 50 for i, t := range tests { 51 tests[i].pathOnSys, err = exec.Command("which", "-a", t.name).Output() 52 if err != nil { 53 return err 54 } 55 } 56 57 return nil 58 } 59 60 // TestWhichUnique tests `which` command against one POSIX command that are included in Linux. 61 // The output of which.go has to be exactly equal to the output of which itself. 62 func TestWhichUnique(t *testing.T) { 63 err := setup() 64 65 if err != nil { 66 t.Fatalf("setup has failed, %v", err) 67 } 68 69 commands := []string{"cat"} 70 var b bytes.Buffer 71 if err := which(&b, strings.Split(p, ":"), commands[:], true); err != nil { 72 t.Fatal(err) 73 } 74 75 // Comparing against only the cat command. 76 if !reflect.DeepEqual(b.Bytes(), tests[0].pathOnSys) { 77 t.Fatalf("Locating commands has failed, wants: %v, got: %v", string(tests[0].pathOnSys), b.String()) 78 } 79 } 80 81 // TestWhichMultiple tests `which` command against the three POSIX commands that are included in Linux. 82 // The output of which.go has to be exactly equal to the output of which itself. If it works with 83 // three, it should work with more commands as well. 84 func TestWhichMultiple(t *testing.T) { 85 err := setup() 86 87 if err != nil { 88 t.Fatalf("setup has failed, %v", err) 89 } 90 91 pathsCombined := []byte{} 92 commands := []string{} 93 for _, t := range tests { 94 pathsCombined = append(pathsCombined, t.pathOnSys...) 95 commands = append(commands, t.name) 96 } 97 98 var b bytes.Buffer 99 if err := which(&b, strings.Split(p, ":"), commands[:], true); err != nil { 100 t.Fatal(err) 101 } 102 103 if !reflect.DeepEqual(b.Bytes(), pathsCombined) { 104 t.Fatalf("Locating commands has failed, wants: %v, got: %v", string(pathsCombined), b.String()) 105 } 106 }