|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/arduino/go-paths-helper" |
| 9 | + "github.com/sirupsen/logrus" |
| 10 | + "github.com/stretchr/testify/assert" |
| 11 | +) |
| 12 | + |
| 13 | +func TestGetConfigPath(t *testing.T) { |
| 14 | + t.Run("read config.ini from ARDUINO_CREATE_AGENT_CONFIG", func(t *testing.T) { |
| 15 | + os.Setenv("ARDUINO_CREATE_AGENT_CONFIG", "./testdata/fromenv/config.ini") |
| 16 | + defer os.Unsetenv("ARDUINO_CREATE_AGENT_CONFIG") |
| 17 | + configPath := GetConfigPath() |
| 18 | + assert.Equal(t, "./testdata/fromenv/config.ini", configPath.String()) |
| 19 | + }) |
| 20 | + |
| 21 | + t.Run("panic if config.ini does not exist", func(t *testing.T) { |
| 22 | + os.Setenv("ARDUINO_CREATE_AGENT_CONFIG", "./testdata/nonexistent_config.ini") |
| 23 | + defer os.Unsetenv("ARDUINO_CREATE_AGENT_CONFIG") |
| 24 | + |
| 25 | + defer func() { |
| 26 | + if r := recover(); r != nil { |
| 27 | + entry, ok := r.(*logrus.Entry) |
| 28 | + if !ok { |
| 29 | + t.Errorf("Expected panic of type *logrus.Entry but got %T", r) |
| 30 | + } else { |
| 31 | + assert.Equal(t, "config from env var ./testdata/nonexistent_config.ini does not exists", entry.Message) |
| 32 | + } |
| 33 | + } else { |
| 34 | + t.Errorf("Expected panic but did not get one") |
| 35 | + } |
| 36 | + }() |
| 37 | + |
| 38 | + GetConfigPath() |
| 39 | + }) |
| 40 | + |
| 41 | + t.Run("read config.ini from $HOME", func(t *testing.T) { |
| 42 | + os.Setenv("HOME", "./testdata/home") |
| 43 | + defer os.Unsetenv("HOME") |
| 44 | + configPath := GetConfigPath() |
| 45 | + assert.Equal(t, "testdata/home/.config/ArduinoCreateAgent/config.ini", configPath.String()) |
| 46 | + }) |
| 47 | + |
| 48 | + t.Run("fallback old : read config.ini where the binary is launched", func(t *testing.T) { |
| 49 | + src, _ := os.Executable() |
| 50 | + paths.New(src).Parent().Join("config.ini").Create() // create a config.ini in the same directory as the binary |
| 51 | + // The fallback path is the directory where the binary is launched |
| 52 | + fmt.Println(src) |
| 53 | + os.Setenv("HOME", "./testdata/noconfig") // force to not have a config in the home directory |
| 54 | + defer os.Unsetenv("HOME") |
| 55 | + |
| 56 | + // expect it creates a config.ini in the same directory as the binary |
| 57 | + configPath := GetConfigPath() |
| 58 | + assert.Equal(t, "testdata/home/.config/ArduinoCreateAgent/config.ini", configPath.String()) |
| 59 | + }) |
| 60 | + |
| 61 | +} |
0 commit comments