1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-14 11:03:09 +02:00

fix(config) fail on incorrect conversions (#2239)

* fix(config) fail for incorrect conversions

* update error handling

* add comment
This commit is contained in:
Oliver Nocon 2020-10-27 15:14:00 +01:00 committed by GitHub
parent 2f83ba56da
commit e5f1f16738
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 3 deletions

View File

@ -365,8 +365,17 @@ func convertValueFromString(config map[string]interface{}, optionsField *reflect
func convertValueFromFloat(config map[string]interface{}, optionsField *reflect.StructField, paramName string, paramValue float64) error {
switch optionsField.Type.Kind() {
case reflect.String:
config[paramName] = strconv.FormatFloat(paramValue, 'f', -1, 64)
return nil
val := strconv.FormatFloat(paramValue, 'f', -1, 64)
// allow float numbers containing a decimal separator
if strings.Contains(val, ".") {
config[paramName] = val
return nil
}
// if no decimal separator is available we cannot be sure that the result is correct:
// long numbers like e.g. 73554900100200011600 will not be represented correctly after reading the yaml
// thus we cannot assume that the string is correct.
// short numbers will be handled as int anyway
return errIncompatibleTypes
case reflect.Float32:
config[paramName] = float32(paramValue)
return nil

View File

@ -4,12 +4,13 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/SAP/jenkins-library/pkg/log"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/mock"
"github.com/ghodss/yaml"
@ -358,6 +359,32 @@ bar: 42
assert.Equal(t, 1.1, stepConfig["foo"])
assert.True(t, hasFailed, "Expected checkTypes() to exit via logging framework")
})
t.Run("Exits in case number beyond length", func(t *testing.T) {
// Init
hasFailed := false
exitFunc := log.Entry().Logger.ExitFunc
log.Entry().Logger.ExitFunc = func(int) {
hasFailed = true
}
defer func() { log.Entry().Logger.ExitFunc = exitFunc }()
options := struct {
Foo string `json:"foo,omitempty"`
}{}
stepConfig := map[string]interface{}{}
content := []byte("foo: 73554900100200011600")
err := yaml.Unmarshal(content, &stepConfig)
assert.NoError(t, err)
// Test
stepConfig = checkTypes(stepConfig, options)
// Assert
assert.True(t, hasFailed, "Expected checkTypes() to exit via logging framework")
})
t.Run("Ignores nil values", func(t *testing.T) {
// Init
hasFailed := false