crossplane
118 строк · 2.7 Кб
1/*
2Copyright 2020 The Crossplane Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package xpkg
18
19import (
20"os"
21"testing"
22
23"github.com/google/go-cmp/cmp"
24"github.com/spf13/afero"
25
26"github.com/crossplane/crossplane-runtime/pkg/errors"
27"github.com/crossplane/crossplane-runtime/pkg/test"
28)
29
30func TestFindXpkgInDir(t *testing.T) {
31match := afero.NewMemMapFs()
32_ = afero.WriteFile(match, "one.xpkg", []byte{}, StreamFileMode)
33
34multi := afero.NewMemMapFs()
35_ = afero.WriteFile(multi, "one.xpkg", []byte{}, StreamFileMode)
36_ = afero.WriteFile(multi, "two.xpkg", []byte{}, StreamFileMode)
37
38type args struct {
39root string
40fs afero.Fs
41}
42
43type want struct {
44path string
45err error
46}
47
48cases := map[string]struct {
49reason string
50args args
51want want
52}{
53"NoMatch": {
54reason: "We should return an error if no matches.",
55args: args{
56root: ".",
57fs: afero.NewMemMapFs(),
58},
59want: want{
60err: errors.New(errNoMatch),
61},
62},
63"MultiMatch": {
64reason: "We should return an error if multiple matches.",
65args: args{
66root: ".",
67fs: multi,
68},
69want: want{
70err: errors.New(errMultiMatch),
71},
72},
73"NotExist": {
74reason: "We should return an error root does not exist.",
75args: args{
76root: "/test",
77fs: afero.NewMemMapFs(),
78},
79want: want{
80err: &os.PathError{Op: "open", Path: "/test", Err: os.ErrNotExist},
81},
82},
83"NotDir": {
84reason: "We should return an error if root is not a directory.",
85args: args{
86root: "one.xpkg",
87fs: multi,
88},
89want: want{
90err: &os.PathError{Op: "readdir", Path: "one.xpkg", Err: errors.New("not a dir")},
91},
92},
93"Successful": {
94reason: "We should return file path if one package exists.",
95args: args{
96root: ".",
97fs: match,
98},
99want: want{
100path: "one.xpkg",
101},
102},
103}
104
105for name, tc := range cases {
106t.Run(name, func(t *testing.T) {
107path, err := FindXpkgInDir(tc.args.fs, tc.args.root)
108
109if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" {
110t.Errorf("\n%s\nFindXpkgInDir(...): -want, +got:\n%s", tc.reason, diff)
111}
112
113if diff := cmp.Diff(tc.want.path, path); diff != "" {
114t.Errorf("\n%s\nFindXpkgInDir(...): -want, +got:\n%s", tc.reason, diff)
115}
116})
117}
118}
119