| // 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 ( |
| "context" |
| "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. |
| files []*cipd.PkgFile |
| }{ |
| { |
| name: "Steps should be read back", |
| files: []*cipd.PkgFile{ |
| { |
| PackageName: "foo/bar", |
| InstanceID: "baz", |
| Path: "/tmp/foo/bar.pkg", |
| }, |
| { |
| PackageName: "alice/bob/charlie", |
| InstanceID: "dave", |
| Path: "/alice/bob/charlie.pkg", |
| }, |
| }, |
| }, |
| { |
| name: "Empty files should be acceptable", |
| files: []*cipd.PkgFile{ |
| {}, |
| { |
| PackageName: "foo/bar", |
| InstanceID: "baz", |
| Path: "/tmp/foo/bar.pkg", |
| }, |
| {}, |
| }, |
| }, |
| } |
| |
| 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 _, pkgFile := range test.files { |
| f, err := os.CreateTemp(tmpdir, "") |
| if err != nil { |
| t.Fatalf("couldn't create tempfile: %v", err) |
| } |
| pkgJSON, err := json.Marshal(pkgFile) |
| if err != nil { |
| t.Fatalf("couldn't marshal to JSON: %v", err) |
| } |
| _, err = f.WriteString(string(pkgJSON)) |
| if err != nil { |
| t.Fatalf("couldn't write JSON: %v", err) |
| } |
| t.Logf("wrote to %q\n", f.Name()) |
| f.Close() |
| } |
| |
| got, err := pkgsInDir(context.Background(), tmpdir) |
| if err != nil { |
| t.Errorf("got error %q, want nil", err) |
| } |
| if diff := cmp.Diff(got, test.files, cmpopts.SortSlices(func(x, y *cipd.PkgFile) bool { |
| return x.PackageName > y.PackageName |
| })); diff != "" { |
| t.Errorf("got diff: %v", diff) |
| } |
| }) |
| } |
| |
| } |