1/*
2Copyright 2018 The Kubernetes 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
8    http://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 add
18
19import (
20	"strings"
21	"testing"
22
23	"sigs.k8s.io/kustomize/pkg/commands/kustfile"
24	"sigs.k8s.io/kustomize/pkg/fs"
25)
26
27const (
28	baseDirectoryPaths = "my/path/to/wonderful/base,other/path/to/even/more/wonderful/base"
29)
30
31func TestAddBaseHappyPath(t *testing.T) {
32	fakeFS := fs.MakeFakeFS()
33	bases := strings.Split(baseDirectoryPaths, ",")
34	for _, base := range bases {
35		fakeFS.Mkdir(base)
36	}
37	fakeFS.WriteTestKustomization()
38
39	cmd := newCmdAddBase(fakeFS)
40	args := []string{baseDirectoryPaths}
41	err := cmd.RunE(cmd, args)
42	if err != nil {
43		t.Errorf("unexpected cmd error: %v", err)
44	}
45	content, err := fakeFS.ReadTestKustomization()
46	if err != nil {
47		t.Errorf("unexpected read error: %v", err)
48	}
49
50	for _, base := range bases {
51		if !strings.Contains(string(content), base) {
52			t.Errorf("expected base name in kustomization")
53		}
54	}
55}
56
57func TestAddBaseAlreadyThere(t *testing.T) {
58	fakeFS := fs.MakeFakeFS()
59	// Create fake directories
60	bases := strings.Split(baseDirectoryPaths, ",")
61	for _, base := range bases {
62		fakeFS.Mkdir(base)
63	}
64	fakeFS.WriteTestKustomization()
65
66	cmd := newCmdAddBase(fakeFS)
67	args := []string{baseDirectoryPaths}
68	err := cmd.RunE(cmd, args)
69	if err != nil {
70		t.Fatalf("unexpected cmd error: %v", err)
71	}
72	// adding an existing base should return an error
73	err = cmd.RunE(cmd, args)
74	if err == nil {
75		t.Errorf("expected already there problem")
76	}
77	var expectedErrors []string
78	for _, base := range bases {
79		msg := "base " + base + " already in kustomization file"
80		expectedErrors = append(expectedErrors, msg)
81		if !kustfile.StringInSlice(msg, expectedErrors) {
82			t.Errorf("unexpected error %v", err)
83		}
84	}
85
86}
87
88func TestAddBaseNoArgs(t *testing.T) {
89	fakeFS := fs.MakeFakeFS()
90
91	cmd := newCmdAddBase(fakeFS)
92	err := cmd.Execute()
93	if err == nil {
94		t.Errorf("expected error: %v", err)
95	}
96	if err.Error() != "must specify a base directory" {
97		t.Errorf("incorrect error: %v", err.Error())
98	}
99}
100