| package osutils |
| |
| import ( |
| "os" |
| "reflect" |
| "testing" |
| ) |
| |
| func TestRun(t *testing.T) { |
| tests := []struct { |
| desc string |
| cmd string |
| args []string |
| wantErr bool |
| hideStderr bool |
| wantStdout string |
| wantStderr string |
| }{ |
| { |
| desc: "Executes command successfully and returns output", |
| cmd: "echo", |
| args: []string{"-n", "Hello world"}, |
| wantErr: false, |
| hideStderr: false, |
| wantStdout: "Hello world", |
| }, |
| { |
| desc: "Fails and returns error when command with unknown argument is given", |
| cmd: "ls", |
| wantErr: true, |
| args: []string{"nonexistent"}, |
| hideStderr: false, |
| }, |
| { |
| desc: "Does not error when hideStderr is true", |
| cmd: "ls", |
| wantErr: false, |
| args: []string{"nonexistent"}, |
| hideStderr: true, |
| }, |
| { |
| desc: "Fails and returns error when unknown command is given ", |
| cmd: "Echo", |
| wantErr: true, |
| args: []string{"Hello world"}, |
| hideStderr: false, |
| }, |
| } |
| |
| for _, test := range tests { |
| t.Run(test.desc, func(t *testing.T) { |
| stdout, err := Run(test.cmd, test.args, test.hideStderr) |
| if gotErr := err != nil; gotErr != test.wantErr { |
| t.Errorf("TestRun(%s): Error: %s\n gotErr: %t\n wantErr: %t", test.desc, err, gotErr, test.wantErr) |
| } |
| |
| if stdout != test.wantStdout { |
| t.Errorf("TestRun(%s): returned unexpected difference;\n gotStdout: %v\n wantStdout: %v\n", test.desc, stdout, test.wantStdout) |
| } |
| }) |
| } |
| } |
| |
| func TestParseFileExists(t *testing.T) { |
| |
| tmpFile, err := os.CreateTemp("", "os-file") |
| if err != nil { |
| t.Fatalf("Failed to create temp file: %v", err) |
| } |
| defer os.Remove(tmpFile.Name()) |
| if _, err := tmpFile.WriteString(`ID=cos`); err != nil { |
| t.Fatalf("Failed to write into temp file: %v", err) |
| } |
| parsedFile, err := Parse(tmpFile.Name()) |
| if err != nil { |
| t.Fatalf("Unable to read os file: %v", err) |
| } |
| want := map[string]string{ |
| "ID": "cos", |
| } |
| if !reflect.DeepEqual(parsedFile, want) { |
| t.Errorf("TestParseFileExists returned unexpected difference;\n Want: %s\n, got:%s\n", want, parsedFile) |
| } |
| } |
| |
| func TestParseFileNotExists(t *testing.T) { |
| _, err := Parse("os-file-nonexistent") |
| if err == nil { |
| t.Fatalf("Expected error when reading from nonexistent file.") |
| } |
| } |