From e870447e75b36ee743aa04039a55409e569ec97c Mon Sep 17 00:00:00 2001 From: Neur0toxine Date: Wed, 1 Dec 2021 14:50:32 +0300 Subject: [PATCH] make originator unmarshalable (#77) --- v1/types.go | 14 ++++++++++++++ v1/types_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/v1/types.go b/v1/types.go index f5d0ab0..f0e57eb 100644 --- a/v1/types.go +++ b/v1/types.go @@ -521,6 +521,20 @@ func (o Originator) MarshalText() ([]byte, error) { return nil, ErrInvalidOriginator } +// UnmarshalText unmarshals originator from text to the value. +func (o *Originator) UnmarshalText(text []byte) error { + switch string(text) { + case "customer": + *o = OriginatorCustomer + return nil + case "channel": + *o = OriginatorChannel + return nil + } + + return ErrInvalidOriginator +} + type TransportErrorCode string const ( diff --git a/v1/types_test.go b/v1/types_test.go index 64ea9b8..e504b7e 100644 --- a/v1/types_test.go +++ b/v1/types_test.go @@ -98,6 +98,37 @@ func TestOriginator(t *testing.T) { }) t.Run("MarshalJSON_Invalid", OriginatorMarshalJSONInvalid) + + t.Run("UnmarshalText_Valid", func(t *testing.T) { + cases := []struct { + value Originator + text []byte + }{ + {1, []byte("customer")}, + {2, []byte("channel")}, + } + for _, c := range cases { + var o Originator + err := o.UnmarshalText(c.text) + assert.NoError(t, err) + assert.Equal(t, c.value, o) + } + }) + + t.Run("UnmarshalText_Invalid", func(t *testing.T) { + var o Originator + err := o.UnmarshalText([]byte{}) + assert.Empty(t, o) + assert.Equal(t, err, ErrInvalidOriginator) + }) + + t.Run("UnmarshalJSON_Invalid", func(t *testing.T) { + var o Originator + err := json.Unmarshal([]byte("\"unknown\""), &o) + assert.Empty(t, o) + assert.Error(t, err) + assert.Equal(t, ErrInvalidOriginator, err) + }) } func TestTransportErrorResponse(t *testing.T) {