Browse Source

Improve testability for LoadSettings function

feature/update-route-registration
Fabian Vowie 3 years ago
parent
commit
3e7f1a0a7f
No known key found for this signature in database GPG Key ID: C27317C33B27C410
  1. 3
      main.go
  2. 8
      settings/settings.go
  3. 24
      settings/settings_test.go

3
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

8
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
}

24
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)
})
}
Loading…
Cancel
Save