| // Copyright 2023 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| package main |
| |
| import ( |
| "encoding/json" |
| "os" |
| "testing" |
| |
| "github.com/google/go-cmp/cmp" |
| "github.com/google/go-cmp/cmp/cmpopts" |
| "go.fuchsia.dev/infra/cmd/recipe_wrapper/cipd" |
| ) |
| |
| func TestOpenFilesInDir(t *testing.T) { |
| tests := []struct { |
| name string |
| // One step to one file. |
| // This makes the test simpler to reason about. |
| steps []*cipd.DeferredStep |
| }{ |
| { |
| name: "Steps should be read back", |
| steps: []*cipd.DeferredStep{ |
| { |
| Name: "foo/bar/pkg", |
| Command: []string{"cipd", "help"}, |
| Environment: map[string]string{"CURL_SSL": "baz"}, |
| }, |
| { |
| Name: "alice/bob/charlie/pkg", |
| Command: []string{"cipd", "help", "-advanced"}, |
| Environment: map[string]string{"CFLEWIS_IS_COOL": "true"}, |
| }, |
| }, |
| }, |
| { |
| name: "Empty files should be acceptable", |
| steps: []*cipd.DeferredStep{ |
| {}, |
| { |
| Name: "foo/bar/pkg", |
| Command: []string{"cipd", "help"}, |
| Environment: map[string]string{"CURL_SSL": "baz"}, |
| }, |
| {}, |
| }, |
| }, |
| } |
| |
| for _, test := range tests { |
| t.Run(test.name, func(t *testing.T) { |
| tmpdir, err := os.MkdirTemp("", "main_test") |
| if err != nil { |
| t.Fatalf("couldn't make tempfile: %v", err) |
| } |
| |
| for _, step := range test.steps { |
| f, err := os.CreateTemp(tmpdir, "") |
| if err != nil { |
| t.Fatalf("couldn't create tempfile: %v", err) |
| } |
| stepsJSON, err := json.Marshal(step) |
| if err != nil { |
| t.Fatalf("couldn't marshal to JSON: %v", err) |
| } |
| _, err = f.WriteString(string(stepsJSON)) |
| if err != nil { |
| t.Fatalf("couldn't write JSON: %v", err) |
| } |
| t.Logf("wrote to %q\n", f.Name()) |
| f.Close() |
| } |
| |
| got, err := stepsInDir(tmpdir) |
| if err != nil { |
| t.Errorf("got error %q, want nil", err) |
| } |
| if diff := cmp.Diff(got, test.steps, cmpopts.SortSlices(func(x, y *cipd.DeferredStep) bool { |
| return x.Name > y.Name |
| })); diff != "" { |
| t.Errorf("got diff: %v", diff) |
| } |
| }) |
| } |
| |
| } |