github.com/SAP/jenkins-library@v1.362.0/pkg/versioning/properties_test.go (about) 1 //go:build unit 2 // +build unit 3 4 package versioning 5 6 import ( 7 "fmt" 8 "os" 9 "path/filepath" 10 "testing" 11 12 "github.com/magiconair/properties" 13 "github.com/stretchr/testify/assert" 14 ) 15 16 func TestPropertiesFileGetVersion(t *testing.T) { 17 t.Run("success case", func(t *testing.T) { 18 tmpFolder := t.TempDir() 19 20 propsFilePath := filepath.Join(tmpFolder, "my.props") 21 os.WriteFile(propsFilePath, []byte("version = 1.2.3"), 0666) 22 23 propsfile := PropertiesFile{ 24 path: propsFilePath, 25 } 26 version, err := propsfile.GetVersion() 27 28 assert.NoError(t, err) 29 assert.Equal(t, "1.2.3", version) 30 }) 31 32 t.Run("success case - custom version field", func(t *testing.T) { 33 tmpFolder := t.TempDir() 34 35 propsFilePath := filepath.Join(tmpFolder, "my.props") 36 os.WriteFile(propsFilePath, []byte("customversion = 1.2.3"), 0666) 37 38 propsfile := PropertiesFile{ 39 path: propsFilePath, 40 versionField: "customversion", 41 } 42 version, err := propsfile.GetVersion() 43 44 assert.NoError(t, err) 45 assert.Equal(t, "1.2.3", version) 46 }) 47 48 t.Run("error case - file not found", func(t *testing.T) { 49 tmpFolder := t.TempDir() 50 51 propsFilePath := filepath.Join(tmpFolder, "my.props") 52 53 propsfile := PropertiesFile{ 54 path: propsFilePath, 55 } 56 _, err := propsfile.GetVersion() 57 58 assert.Contains(t, fmt.Sprint(err), "failed to load") 59 }) 60 61 t.Run("error case - no version found", func(t *testing.T) { 62 tmpFolder := t.TempDir() 63 64 propsFilePath := filepath.Join(tmpFolder, "my.props") 65 os.WriteFile(propsFilePath, []byte("versionx = 1.2.3"), 0666) 66 67 propsfile := PropertiesFile{ 68 path: propsFilePath, 69 } 70 _, err := propsfile.GetVersion() 71 72 assert.EqualError(t, err, "no version found in field version") 73 }) 74 } 75 76 func TestPropertiesFileSetVersion(t *testing.T) { 77 t.Run("success case", func(t *testing.T) { 78 tmpFolder := t.TempDir() 79 80 propsFilePath := filepath.Join(tmpFolder, "my.props") 81 os.WriteFile(propsFilePath, []byte("version = 0.0.1"), 0666) 82 83 var content []byte 84 propsfile := PropertiesFile{ 85 path: propsFilePath, 86 writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { content = filecontent; return nil }, 87 } 88 err := propsfile.SetVersion("1.2.3") 89 assert.NoError(t, err) 90 91 assert.Contains(t, string(content), "version = 1.2.3") 92 }) 93 94 t.Run("error case - write failed", func(t *testing.T) { 95 props := properties.LoadMap(map[string]string{"version": "0.0.1"}) 96 propsfile := PropertiesFile{ 97 content: props, 98 path: "gradle.properties", 99 versionField: "version", 100 writeFile: func(filename string, filecontent []byte, mode os.FileMode) error { return fmt.Errorf("write error") }, 101 } 102 err := propsfile.SetVersion("1.2.3") 103 assert.EqualError(t, err, "failed to write file: write error") 104 }) 105 }