blob: 7744b4bfac32e4331a76817a52c8401fe23244b2 [file] [log] [blame]
Jingwen Chenbf61afb2021-05-06 13:31:18 +00001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package config
16
17import (
18 "testing"
19)
20
21func TestExpandVars(t *testing.T) {
22 testCases := []struct {
23 description string
24 exportedVars map[string]variableValue
25 toExpand string
26 expectedValues []string
27 }{
28 {
29 description: "single level expansion",
30 exportedVars: map[string]variableValue{
31 "foo": variableValue([]string{"bar"}),
32 },
33 toExpand: "${foo}",
34 expectedValues: []string{"bar"},
35 },
36 {
37 description: "double level expansion",
38 exportedVars: map[string]variableValue{
39 "foo": variableValue([]string{"${bar}"}),
40 "bar": variableValue([]string{"baz"}),
41 },
42 toExpand: "${foo}",
43 expectedValues: []string{"baz"},
44 },
45 {
46 description: "double level expansion with a literal",
47 exportedVars: map[string]variableValue{
48 "a": variableValue([]string{"${b}", "c"}),
49 "b": variableValue([]string{"d"}),
50 },
51 toExpand: "${a}",
52 expectedValues: []string{"d", "c"},
53 },
54 {
55 description: "double level expansion, with two variables in a string",
56 exportedVars: map[string]variableValue{
57 "a": variableValue([]string{"${b} ${c}"}),
58 "b": variableValue([]string{"d"}),
59 "c": variableValue([]string{"e"}),
60 },
61 toExpand: "${a}",
62 expectedValues: []string{"d", "e"},
63 },
64 {
65 description: "triple level expansion with two variables in a string",
66 exportedVars: map[string]variableValue{
67 "a": variableValue([]string{"${b} ${c}"}),
68 "b": variableValue([]string{"${c}", "${d}"}),
69 "c": variableValue([]string{"${d}"}),
70 "d": variableValue([]string{"foo"}),
71 },
72 toExpand: "${a}",
73 expectedValues: []string{"foo", "foo", "foo"},
74 },
75 }
76
77 for _, testCase := range testCases {
78 t.Run(testCase.description, func(t *testing.T) {
79 output := expandVar(testCase.toExpand, testCase.exportedVars)
80 if len(output) != len(testCase.expectedValues) {
81 t.Errorf("Expected %d values, got %d", len(testCase.expectedValues), len(output))
82 }
83 for i, actual := range output {
84 expectedValue := testCase.expectedValues[i]
85 if actual != expectedValue {
86 t.Errorf("Actual value '%s' doesn't match expected value '%s'", actual, expectedValue)
87 }
88 }
89 })
90 }
91}