Skip to content

Commit

Permalink
test and doc comment for EnvsSerializeModel.Normalize
Browse files Browse the repository at this point in the history
  • Loading branch information
viktorbenei committed Dec 14, 2016
1 parent 97e7667 commit a8b2f8f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
6 changes: 5 additions & 1 deletion models/models_methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,11 @@ func (env *EnvironmentItemModel) Normalize() error {
return nil
}

// Normalize ...
// Normalize - if successful this makes the model JSON serializable.
// Without this, if the object was created with e.g. a YAML parser,
// the type of `opts` might be map[interface]interface, which is not JSON serializable.
// After this call it's ensured that the type of objects is map[string]interface,
// which is JSON serializable.
func (envsSerializeObj *EnvsSerializeModel) Normalize() error {
for _, envObj := range envsSerializeObj.Envs {
if err := envObj.Normalize(); err != nil {
Expand Down
34 changes: 34 additions & 0 deletions models/models_methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ package models
import (
"testing"

yaml "gopkg.in/yaml.v2"

"encoding/json"

"github.com/bitrise-io/go-utils/pointers"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -359,3 +363,33 @@ func TestValidate(t *testing.T) {
}
require.NoError(t, env.Validate())
}

func Test_EnvsSerializeModel_Normalize(t *testing.T) {
yamlContent := `envs:
- KEY_ONE: first value
- KEY_TWO: second value, with options
opts:
is_expand: true
`
var objFromYAML EnvsSerializeModel
require.NoError(t, yaml.Unmarshal([]byte(yamlContent), &objFromYAML))

// the objFromYAML object in this state can't be serialized to JSON directly,
// as the YAML parser parses the `opts` into map[interface]interface,
// which is not supported by JSON
{
_, err := json.Marshal(objFromYAML)
require.EqualError(t, err, `json: unsupported type: map[interface {}]interface {}`)
}

// now, if we call Normalize on this object, that will convert the map[interface]interface
// into map[string]interface, which is JSON serializable
require.NoError(t, objFromYAML.Normalize())

// let's try the serialization again - this time it will work!
{
jsonContBytes, err := json.Marshal(objFromYAML)
require.NoError(t, err)
require.Equal(t, `{"envs":[{"KEY_ONE":"first value","opts":{}},{"KEY_TWO":"second value, with options","opts":{"is_expand":true}}]}`, string(jsonContBytes))
}
}

0 comments on commit a8b2f8f

Please sign in to comment.