Skip to content

Commit b519d23

Browse files
authored
feat: unmarshal int to Entity (#369)
## Issue N/A ## Description Allow unmarshalling entities from ints as well as strings. --------- Signed-off-by: Tyler Gillson <tyler.gillson@gmail.com>
1 parent e59db3a commit b519d23

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

api/vcenter/entity/entities.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,14 @@ func (e Entity) MarshalYAML() (interface{}, error) {
8282

8383
// UnmarshalYAML implements the yaml.Unmarshaler interface.
8484
func (e *Entity) UnmarshalYAML(unmarshal func(interface{}) error) error {
85-
var entityStr string
85+
var (
86+
entityInt int
87+
entityStr string
88+
)
89+
if err := unmarshal(&entityInt); err == nil {
90+
*e = Entity(entityInt)
91+
return nil
92+
}
8693
if err := unmarshal(&entityStr); err != nil {
8794
return err
8895
}

api/vcenter/entity/entities_test.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@ func TestMarshalYAML(t *testing.T) {
4040
}
4141

4242
func TestUnMarshalYAML(t *testing.T) {
43-
// string: correct casing
44-
in := []byte("Resource Pool\n")
43+
// int
44+
in := []byte("8\n")
4545
expected := ResourcePool
4646

4747
var e Entity
@@ -52,6 +52,16 @@ func TestUnMarshalYAML(t *testing.T) {
5252
t.Errorf("got %v != expected %v", e, expected)
5353
}
5454

55+
// string: correct casing
56+
in = []byte("Resource Pool\n")
57+
58+
if err := yaml.Unmarshal(in, &e); err != nil {
59+
t.Errorf("failed to unmarshal ResourcePool: %v", err)
60+
}
61+
if !reflect.DeepEqual(e, expected) {
62+
t.Errorf("got %v != expected %v", e, expected)
63+
}
64+
5565
// struct + case-insensitive
5666
in = []byte("entityType: resource pool\n")
5767
expectedS := estruct{EntityType: ResourcePool}

0 commit comments

Comments
 (0)