github.com/hazelops/ize@v1.1.12-0.20230915191306-97d7c0e48f11/internal/requirements/helpers_test.go (about) 1 //go:build !e2e 2 // +build !e2e 3 4 package requirements 5 6 import ( 7 "bytes" 8 "fmt" 9 "github.com/pterm/pterm" 10 "log" 11 "os" 12 "path/filepath" 13 "testing" 14 ) 15 16 func TestCheckCommand(t *testing.T) { 17 type args struct { 18 command string 19 subcommand []string 20 } 21 tests := []struct { 22 name string 23 args args 24 want bool 25 wantOut string 26 }{ 27 { 28 name: "failed", 29 args: args{ 30 command: "error_case", 31 subcommand: []string{}, 32 }, 33 want: false, 34 }, 35 { 36 name: "success echo", 37 args: args{ 38 command: "echo", 39 subcommand: []string{"test"}, 40 }, 41 want: true, 42 wantOut: "test\n", 43 }, 44 {name: "failed ssm plugin", args: args{command: "session-manager-plugin"}, want: false, wantOut: ""}, 45 {name: "success ssm plugin", args: args{command: "session-manager-plugin"}, want: true, wantOut: "session-manager-plugin\n"}, 46 } 47 for _, tt := range tests { 48 t.Run(tt.name, func(t *testing.T) { 49 if tt.name == "success ssm plugin" { 50 temp, err := os.MkdirTemp("", "test") 51 if err != nil { 52 t.Fail() 53 } 54 err = os.WriteFile(filepath.Join(temp, "session-manager-plugin"), []byte("#!/bin/bash\necho \"session-manager-plugin\""), 0777) 55 if err != nil { 56 t.Error(err) 57 } 58 err = os.Setenv("PATH", fmt.Sprintf("%s:$PATH", temp)) 59 if err != nil { 60 t.Fail() 61 } 62 } 63 if tt.name == "failed ssm plugin" { 64 err := os.Setenv("PATH", "") 65 if err != nil { 66 t.Fail() 67 } 68 } 69 exist, out := CheckCommand(tt.args.command, tt.args.subcommand) 70 if exist != tt.want { 71 t.Errorf("CheckCommand() got = %v, want %v", exist, tt.want) 72 return 73 } 74 if out != tt.wantOut { 75 t.Errorf("CheckCommand() got = %v, want %v", out, tt.wantOut) 76 return 77 } 78 }) 79 } 80 } 81 82 func Test_isStructured(t *testing.T) { 83 tests := []struct { 84 name string 85 dirName string 86 wantWarning bool 87 }{ 88 {name: "success .infra", dirName: ".infra", wantWarning: false}, 89 {name: "success .ize", dirName: ".ize", wantWarning: false}, 90 {name: "with warning", dirName: ".test", wantWarning: true}, 91 } 92 for _, tt := range tests { 93 t.Run(tt.name, func(t *testing.T) { 94 dir, err := os.MkdirTemp("", "example") 95 if err != nil { 96 log.Fatal(err) 97 } 98 defer os.RemoveAll(dir) // clean up 99 projectDir := filepath.Join(dir, tt.dirName) 100 err = os.Mkdir(projectDir, 0665) 101 if err != nil { 102 return 103 } 104 105 err = os.Chdir(dir) 106 if err != nil { 107 return 108 } 109 110 buffer := &bytes.Buffer{} 111 112 pterm.SetDefaultOutput(buffer) 113 isStructured() 114 115 if buffer.String() == pterm.Warning.Sprint("is not an ize-structured directory. Please run ize init or cd into an ize-structured directory.\n") { 116 if !tt.wantWarning { 117 t.Fail() 118 } 119 } else { 120 return 121 } 122 }) 123 } 124 }