[#168] session: Implement binary/JSON encoders/decoders on TokenBody

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-11-13 16:49:46 +03:00 committed by Alex Vanin
parent 20bf21e5e4
commit 4e163617d1
4 changed files with 45 additions and 4 deletions

View file

@ -44,3 +44,23 @@ func (l *TokenLifetime) UnmarshalJSON(data []byte) error {
return nil
}
func (t *SessionTokenBody) MarshalJSON() ([]byte, error) {
return protojson.MarshalOptions{
EmitUnpopulated: true,
}.Marshal(
SessionTokenBodyToGRPCMessage(t),
)
}
func (t *SessionTokenBody) UnmarshalJSON(data []byte) error {
msg := new(session.SessionToken_Body)
if err := protojson.Unmarshal(data, msg); err != nil {
return err
}
*t = *SessionTokenBodyFromGRPCMessage(msg)
return nil
}

View file

@ -30,3 +30,15 @@ func TestTokenLifetimeJSON(t *testing.T) {
require.Equal(t, l, l2)
}
func TestSessionTokenBodyJSON(t *testing.T) {
b := generateSessionTokenBody("id")
data, err := b.MarshalJSON()
require.NoError(t, err)
b2 := new(session.SessionTokenBody)
require.NoError(t, b2.UnmarshalJSON(data))
require.Equal(t, b, b2)
}

View file

@ -366,6 +366,17 @@ func (t *SessionTokenBody) StableSize() (size int) {
return size
}
func (t *SessionTokenBody) Unmarshal(data []byte) error {
m := new(session.SessionToken_Body)
if err := goproto.Unmarshal(data, m); err != nil {
return err
}
*t = *SessionTokenBodyFromGRPCMessage(m)
return nil
}
func (t *SessionToken) StableMarshal(buf []byte) ([]byte, error) {
if t == nil {
return []byte{}, nil

View file

@ -90,16 +90,14 @@ func TestObjectSessionContext_StableMarshal(t *testing.T) {
func TestSessionTokenBody_StableMarshal(t *testing.T) {
sessionTokenBodyFrom := generateSessionTokenBody("Session Token Body")
transport := new(grpc.SessionToken_Body)
t.Run("non empty", func(t *testing.T) {
wire, err := sessionTokenBodyFrom.StableMarshal(nil)
require.NoError(t, err)
err = goproto.Unmarshal(wire, transport)
require.NoError(t, err)
sessionTokenBodyTo := new(session.SessionTokenBody)
require.NoError(t, sessionTokenBodyTo.Unmarshal(wire))
sessionTokenBodyTo := session.SessionTokenBodyFromGRPCMessage(transport)
require.Equal(t, sessionTokenBodyFrom, sessionTokenBodyTo)
})
}