github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/versioning/jsonfile_test.go (about) 1 //go:build unit 2 // +build unit 3 4 package versioning 5 6 import ( 7 "fmt" 8 "os" 9 "testing" 10 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func TestJSONfileGetVersion(t *testing.T) { 15 t.Run("success case", func(t *testing.T) { 16 jsonfile := JSONfile{ 17 path: "my.json", 18 readFile: func(filename string) ([]byte, error) { return []byte(`{"version": "1.2.3"}`), nil }, 19 } 20 version, err := jsonfile.GetVersion() 21 assert.NoError(t, err) 22 assert.Equal(t, "1.2.3", version) 23 }) 24 25 t.Run("error case", func(t *testing.T) { 26 jsonfile := JSONfile{ 27 path: "my.json", 28 versionField: "theversion", 29 readFile: func(filename string) ([]byte, error) { return []byte{}, fmt.Errorf("read error") }, 30 } 31 _, err := jsonfile.GetVersion() 32 assert.EqualError(t, err, "failed to read file 'my.json': read error") 33 }) 34 } 35 36 func TestJSONfileSetVersion(t *testing.T) { 37 t.Run("success case", func(t *testing.T) { 38 var content []byte 39 jsonfile := JSONfile{ 40 path: "my.json", 41 versionField: "theversion", 42 readFile: func(filename string) ([]byte, error) { return []byte(`{"theversion": "1.2.3"}`), nil }, 43 writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { content = filecontent; return nil }, 44 } 45 err := jsonfile.SetVersion("1.2.4") 46 assert.NoError(t, err) 47 assert.Contains(t, string(content), `"theversion": "1.2.4"`) 48 }) 49 50 t.Run("error case", func(t *testing.T) { 51 jsonfile := JSONfile{ 52 path: "my.json", 53 versionField: "theversion", 54 readFile: func(filename string) ([]byte, error) { return []byte(`{"theversion": "1.2.3"}`), nil }, 55 writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { return fmt.Errorf("write error") }, 56 } 57 err := jsonfile.SetVersion("1.2.4") 58 assert.EqualError(t, err, "failed to write file 'my.json': write error") 59 }) 60 }