diff --git a/main.go b/main.go index e8bf674..ea60a8f 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "github.com/geplauder/lithium/settings" "github.com/geplauder/lithium/storage" "github.com/gorilla/mux" + "github.com/spf13/afero" ) const Name string = "Lithium" @@ -43,7 +44,7 @@ func RegisterPipelineRoutes(r *mux.Router, pipelines []pipelines.IPipeline, stor } func main() { - settings := settings.LoadSettings() + settings := settings.LoadSettings(afero.NewOsFs()) var storageProvider storage.IStorageProvider diff --git a/settings/settings.go b/settings/settings.go index 35e960d..b0006b1 100644 --- a/settings/settings.go +++ b/settings/settings.go @@ -4,6 +4,8 @@ import ( "encoding/json" "os" "path/filepath" + + "github.com/spf13/afero" ) const ( @@ -31,12 +33,12 @@ func parseSettings(data []byte) Settings { return settings } -func LoadSettings() Settings { +func LoadSettings(fileSystem afero.Fs) Settings { workingDirectory, _ := os.Getwd() path := filepath.Join(workingDirectory, "settings.json") // Load file and parse file - data, err := os.ReadFile(path) + data, err := afero.ReadFile(fileSystem, path) if err == nil { return parseSettings(data) @@ -53,7 +55,7 @@ func LoadSettings() Settings { } serializedSettings, err := json.MarshalIndent(defaultSettings, "", "\t") - os.WriteFile(path, serializedSettings, os.ModePerm) + afero.WriteFile(fileSystem, path, serializedSettings, os.ModePerm) return defaultSettings } diff --git a/settings/settings_test.go b/settings/settings_test.go index 96e667a..2610eab 100644 --- a/settings/settings_test.go +++ b/settings/settings_test.go @@ -1,12 +1,15 @@ package settings import ( + "os" + "path/filepath" "testing" + "github.com/spf13/afero" "github.com/stretchr/testify/assert" ) -func TestSettingsLoading(t *testing.T) { +func TestSettingsParsing(t *testing.T) { const file string = `{ "endpoint": "0.0.0.0:8000", "token": "foobar", @@ -24,3 +27,22 @@ func TestSettingsLoading(t *testing.T) { assert.Equal(t, "assets", settings.StorageProvider.BasePath) }) } + +func TestSettingsLoading(t *testing.T) { + t.Run("Settings loading creates default settings.json when none is present", func(t *testing.T) { + fileSystem := afero.NewMemMapFs() + workingDirectory, _ := os.Getwd() + + path := filepath.Join(workingDirectory, "settings.json") + + // Settings file does not exist in the beginning + doesFileExist, _ := afero.Exists(fileSystem, path) + assert.False(t, doesFileExist) + + LoadSettings(fileSystem) + + // Settings file should be present after calling LoadSettings + doesFileExist, _ = afero.Exists(fileSystem, path) + assert.True(t, doesFileExist) + }) +}