github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/versioning/versionfile_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 TestVersionfileInit(t *testing.T) { 15 t.Run("default", func(t *testing.T) { 16 versionfile := Versionfile{} 17 versionfile.init() 18 assert.Equal(t, "VERSION", versionfile.path) 19 }) 20 21 t.Run("no default", func(t *testing.T) { 22 versionfile := Versionfile{path: "my/VERSION"} 23 versionfile.init() 24 assert.Equal(t, "my/VERSION", versionfile.path) 25 }) 26 } 27 28 func TestVersionfileVersioningScheme(t *testing.T) { 29 versionfile := Versionfile{} 30 assert.Equal(t, "semver2", versionfile.VersioningScheme()) 31 } 32 33 func TestVersionfileGetVersion(t *testing.T) { 34 t.Run("success case", func(t *testing.T) { 35 versionfile := Versionfile{ 36 path: "my/VERSION", 37 readFile: func(filename string) ([]byte, error) { return []byte("1.2.3"), nil }, 38 } 39 version, err := versionfile.GetVersion() 40 assert.NoError(t, err) 41 assert.Equal(t, "1.2.3", version) 42 }) 43 44 t.Run("success case - trimming", func(t *testing.T) { 45 versionfile := Versionfile{ 46 path: "my/VERSION", 47 readFile: func(filename string) ([]byte, error) { return []byte("1.2.3 \n"), nil }, 48 } 49 version, err := versionfile.GetVersion() 50 assert.NoError(t, err) 51 assert.Equal(t, "1.2.3", version) 52 }) 53 54 t.Run("error case", func(t *testing.T) { 55 versionfile := Versionfile{ 56 path: "my/VERSION", 57 readFile: func(filename string) ([]byte, error) { return []byte{}, fmt.Errorf("read error") }, 58 } 59 _, err := versionfile.GetVersion() 60 assert.EqualError(t, err, "failed to read file 'my/VERSION': read error") 61 }) 62 } 63 64 func TestVersionfileSetVersion(t *testing.T) { 65 t.Run("success case", func(t *testing.T) { 66 var content []byte 67 versionfile := Versionfile{ 68 path: "my/VERSION", 69 readFile: func(filename string) ([]byte, error) { return []byte("1.2.3"), nil }, 70 writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { content = filecontent; return nil }, 71 } 72 err := versionfile.SetVersion("1.2.4") 73 assert.NoError(t, err) 74 assert.Contains(t, string(content), "1.2.4") 75 }) 76 77 t.Run("error case", func(t *testing.T) { 78 versionfile := Versionfile{ 79 path: "my/VERSION", 80 readFile: func(filename string) ([]byte, error) { return []byte("1.2.3"), nil }, 81 writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { return fmt.Errorf("write error") }, 82 } 83 err := versionfile.SetVersion("1.2.4") 84 assert.EqualError(t, err, "failed to write file 'my/VERSION': write error") 85 }) 86 }