From 3e7f1a0a7f1858f280af35419eef36c1730daddf Mon Sep 17 00:00:00 2001 From: Fabian Vowie Date: Mon, 17 Jan 2022 17:01:54 +0100 Subject: [PATCH] Improve testability for LoadSettings function --- main.go | 3 ++- settings/settings.go | 8 +++++--- settings/settings_test.go | 24 +++++++++++++++++++++++- 3 files changed, 30 insertions(+), 5 deletions(-) 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) + }) +}