Skip to content

Commit

Permalink
add JSON marshaler to corim.Roles
Browse files Browse the repository at this point in the history
  • Loading branch information
thomas-fossati committed Oct 7, 2021
1 parent 2e1cbfb commit e0163b1
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
1 change: 0 additions & 1 deletion comid/role_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ func TestRoles_ToCBOR_ok(t *testing.T) {

assert.Nil(t, err)
assert.Equal(t, tv.expected, actual)

}
}

Expand Down
21 changes: 21 additions & 0 deletions corim/role.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,17 @@ var (
stringToRole = map[string]Role{
"manifestCreator": RoleManifestCreator,
}
roleToString = map[Role]string{
RoleManifestCreator: "manifestCreator",
}
)

type Roles []Role

func NewRoles() *Roles {
return &Roles{}
}

// Add appends the supplied roles to Roles list.
func (o *Roles) Add(roles ...Role) *Roles {
if o != nil {
Expand Down Expand Up @@ -76,3 +83,17 @@ func (o *Roles) UnmarshalJSON(data []byte) error {

return nil
}

func (o Roles) MarshalJSON() ([]byte, error) {
roles := []string{}

for _, r := range o {
s, ok := roleToString[r]
if !ok {
return nil, fmt.Errorf("unknown role %d", r)
}
roles = append(roles, s)
}

return json.Marshal(roles)
}
29 changes: 29 additions & 0 deletions corim/role_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2021 Contributors to the Veraison project.
// SPDX-License-Identifier: Apache-2.0

package corim

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestRoles_MarshalJSON_ok(t *testing.T) {
tvs := []struct {
roles *Roles
expected string
}{
{
roles: NewRoles().Add(RoleManifestCreator),
expected: `[ "manifestCreator" ]`,
},
}

for _, tv := range tvs {
actual, err := tv.roles.MarshalJSON()

assert.Nil(t, err)
assert.JSONEq(t, tv.expected, string(actual))
}
}

0 comments on commit e0163b1

Please sign in to comment.