Skip to content

Commit 0c2092e

Browse files
committed
add tests to cover environment selection
extract a repoList interface to simplify tests Signed-off-by: Yves Brissaud <yves@dagger.io>
1 parent 3261484 commit 0c2092e

File tree

2 files changed

+96
-2
lines changed

2 files changed

+96
-2
lines changed

cmd/cu/env.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,14 @@ import (
44
"context"
55
"fmt"
66

7-
"github.com/dagger/container-use/repository"
7+
"github.com/dagger/container-use/environment"
88
)
99

10-
func envOrDefault(ctx context.Context, arg string, repo *repository.Repository) (string, error) {
10+
type repoLister interface {
11+
List(ctx context.Context) ([]*environment.EnvironmentInfo, error)
12+
}
13+
14+
func envOrDefault(ctx context.Context, arg string, repo repoLister) (string, error) {
1115
if arg != "" {
1216
return arg, nil
1317
}

cmd/cu/env_test.go

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/dagger/container-use/environment"
8+
)
9+
10+
func TestEnvironmentFromArgs(t *testing.T) {
11+
ctx := context.Background()
12+
tests := []struct {
13+
name string
14+
arg string
15+
repo repoLister
16+
expected string
17+
expectedError bool
18+
}{
19+
{
20+
name: "arg defined and not environments",
21+
arg: "fancy-mallard",
22+
repo: &repo{},
23+
expected: "fancy-mallard",
24+
expectedError: false,
25+
},
26+
{
27+
name: "arg defined and environments",
28+
arg: "fancy-mallard",
29+
repo: &repo{
30+
list: []*environment.EnvironmentInfo{
31+
{ID: "foo"},
32+
{ID: "bar"},
33+
},
34+
},
35+
expected: "fancy-mallard",
36+
expectedError: false,
37+
},
38+
{
39+
name: "no arg, no environment",
40+
arg: "",
41+
repo: &repo{},
42+
expected: "",
43+
expectedError: true,
44+
},
45+
{
46+
name: "no arg, one environment",
47+
arg: "",
48+
repo: &repo{
49+
list: []*environment.EnvironmentInfo{
50+
{ID: "fancy-mallard"},
51+
},
52+
},
53+
expected: "fancy-mallard",
54+
expectedError: false,
55+
},
56+
{
57+
name: "no arg, more than one environment",
58+
arg: "",
59+
repo: &repo{
60+
list: []*environment.EnvironmentInfo{
61+
{ID: "fancy-mallard"},
62+
{ID: "bar"},
63+
},
64+
},
65+
expected: "",
66+
expectedError: true,
67+
},
68+
}
69+
70+
for _, tt := range tests {
71+
t.Run(tt.name, func(t *testing.T) {
72+
env, err := envOrDefault(ctx, tt.arg, tt.repo)
73+
if (err != nil) != tt.expectedError {
74+
t.Errorf("envOrDefault() error = %v, wantErr %v", err, tt.expectedError)
75+
return
76+
}
77+
if env != tt.expected {
78+
t.Errorf("envOrDefault() = %v, want %v", env, tt.expected)
79+
}
80+
})
81+
}
82+
}
83+
84+
type repo struct {
85+
list []*environment.EnvironmentInfo
86+
}
87+
88+
func (r *repo) List(_ context.Context) ([]*environment.EnvironmentInfo, error) {
89+
return r.list, nil
90+
}

0 commit comments

Comments
 (0)