|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/stretchr/testify/assert" |
| 6 | + "io/ioutil" |
| 7 | + "os" |
| 8 | + "strings" |
| 9 | + "testing" |
| 10 | +) |
| 11 | + |
| 12 | +func TestNewConfig(t *testing.T) { |
| 13 | + file, err := ioutil.TempFile("", "testconfig.yml") |
| 14 | + defer os.Remove(file.Name()) |
| 15 | + if err != nil { |
| 16 | + fmt.Println(err) |
| 17 | + assert.Fail(t, "failed to parse valid test file") |
| 18 | + } |
| 19 | + cfg, err := NewConfig(file.Name()) |
| 20 | + assert.Nil(t, cfg) |
| 21 | + assert.NotNil(t, err) |
| 22 | + cfg, err = NewConfig(file.Name() + "bad_file") |
| 23 | + assert.Nil(t, cfg) |
| 24 | + assert.NotNil(t, err) |
| 25 | + |
| 26 | + cfg, err = NewConfig("config.yml") |
| 27 | + assert.NotNil(t, cfg) |
| 28 | + assert.Nil(t, err) |
| 29 | +} |
| 30 | + |
| 31 | +func TestValidateConfigPath(t *testing.T) { |
| 32 | + var tests = []struct { |
| 33 | + path string |
| 34 | + error error |
| 35 | + }{ |
| 36 | + {".", fmt.Errorf("'.' is a directory, not a normal file")}, |
| 37 | + {"./config", fmt.Errorf("./config is a directory, not a normal file")}, |
| 38 | + {"./config.yml", nil}, |
| 39 | + } |
| 40 | + for _, tt := range tests { |
| 41 | + t.Run(tt.path, func(t *testing.T) { |
| 42 | + err := validateConfigPath(tt.path) |
| 43 | + if err == nil && tt.error != nil { |
| 44 | + assert.Fail(t, err.Error()) |
| 45 | + } |
| 46 | + |
| 47 | + }) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +//TestConfigLoadFunction ... Test if config is read correctly |
| 52 | +func TestConfigLoadFunction(t *testing.T) { |
| 53 | + var test Config |
| 54 | + test.Csv.Name = "etcdoperator.v0.9.4" |
| 55 | + test.Csv.Namespace = "my-etcd" |
| 56 | + test.Csv.Status = "Succeeded" |
| 57 | + path, _ := os.Getwd() |
| 58 | + |
| 59 | + var tests = []struct { |
| 60 | + args []string |
| 61 | + conf Config |
| 62 | + error string |
| 63 | + }{ |
| 64 | + {[]string{"./operator-test"}, test, "no such file or directory"}, |
| 65 | + {[]string{"./operator-test", "-config", "config_not_exists"}, test, "no such file or directory"}, |
| 66 | + {[]string{"./operator-test", "-config", path}, test, "is a directory, not a normal file"}, |
| 67 | + {[]string{"./operator-test", "-config", "config.yml"}, test, ""}, |
| 68 | + {[]string{"./operator-test", "-config", path + "/config.yml"}, test, ""}, |
| 69 | + } |
| 70 | + for _, tt := range tests { |
| 71 | + t.Run(strings.Join(tt.args, " "), func(t *testing.T) { |
| 72 | + os.Args = tt.args |
| 73 | + if len(tt.args) > 2 { |
| 74 | + configPath = &tt.args[2] |
| 75 | + } |
| 76 | + testConfig, err := GetConfig() |
| 77 | + if err == nil { |
| 78 | + assert.Nil(t, err) |
| 79 | + assert.NotNil(t, testConfig) |
| 80 | + assert.Equal(t, *testConfig, tt.conf) |
| 81 | + } else { |
| 82 | + assert.NotNil(t, err) |
| 83 | + assert.Contains(t, err.Error(), tt.error) |
| 84 | + } |
| 85 | + }) |
| 86 | + } |
| 87 | +} |
0 commit comments