Fixed NodeID and PieceID marshaling from JSON (#1995)

This commit is contained in:
3bl3gamer 2019-05-20 19:48:10 +03:00 committed by Kaloyan Raev
parent 8e023b8bbf
commit 46ab933363
4 changed files with 36 additions and 2 deletions

View File

@ -8,6 +8,7 @@ import (
"crypto/x509/pkix"
"database/sql/driver"
"math/bits"
"strings"
"github.com/btcsuite/btcutil/base58"
"github.com/zeebo/errs"
@ -220,7 +221,7 @@ func (id *NodeID) Scan(src interface{}) (err error) {
// UnmarshalJSON deserializes a json string (as bytes) to a node ID
func (id *NodeID) UnmarshalJSON(data []byte) error {
var err error
*id, err = NodeIDFromString(string(data))
*id, err = NodeIDFromString(strings.Trim(string(data), `"`))
if err != nil {
return err
}

View File

@ -6,6 +6,7 @@ package storj_test
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"testing"
"github.com/btcsuite/btcutil/base58"
@ -140,6 +141,20 @@ func TestNodeID_String_Version(t *testing.T) {
}
}
func TestNodeID_MarshalJSON(t *testing.T) {
nodeID, _ := storj.NodeIDFromString("12vha9oTFnerxYRgeQ2BZqoFrLrnmmf5UWTCY2jA77dF3YvWew7")
buf, err := json.Marshal(nodeID)
require.NoError(t, err)
assert.Equal(t, string(buf), `"12vha9oTFnerxYRgeQ2BZqoFrLrnmmf5UWTCY2jA77dF3YvWew7"`)
}
func TestNodeID_UnmarshalJSON(t *testing.T) {
var nodeID storj.NodeID
err := json.Unmarshal([]byte(`"12vha9oTFnerxYRgeQ2BZqoFrLrnmmf5UWTCY2jA77dF3YvWew7"`), &nodeID)
require.NoError(t, err)
assert.Equal(t, nodeID.String(), "12vha9oTFnerxYRgeQ2BZqoFrLrnmmf5UWTCY2jA77dF3YvWew7")
}
func TestNewVersionedID(t *testing.T) {
nodeID := storj.NodeID{}
_, err := rand.Read(nodeID[:])

View File

@ -9,6 +9,7 @@ import (
"crypto/sha512"
"database/sql/driver"
"encoding/base32"
"strings"
"github.com/zeebo/errs"
)
@ -106,7 +107,7 @@ func (id PieceID) MarshalJSON() ([]byte, error) {
// UnmarshalJSON deserializes a json string (as bytes) to a piece ID
func (id *PieceID) UnmarshalJSON(data []byte) error {
var err error
*id, err = PieceIDFromString(string(data))
*id, err = PieceIDFromString(strings.Trim(string(data), `"`))
if err != nil {
return err
}

View File

@ -4,9 +4,11 @@
package storj_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"storj.io/storj/internal/testidentity"
"storj.io/storj/pkg/storj"
@ -59,3 +61,18 @@ func TestPieceID_Derive(t *testing.T) {
assert.Equal(t, b.Derive(n0), b.Derive(n0), "b(n0)")
assert.Equal(t, b.Derive(n1), b.Derive(n1), "b(n1)")
}
func TestPieceID_MarshalJSON(t *testing.T) {
pieceid := storj.NewPieceID()
buf, err := json.Marshal(pieceid)
require.NoError(t, err)
assert.Equal(t, string(buf), `"`+pieceid.String()+`"`)
}
func TestPieceID_UnmarshalJSON(t *testing.T) {
originalPieceID := storj.NewPieceID()
var pieceid storj.PieceID
err := json.Unmarshal([]byte(`"`+originalPieceID.String()+`"`), &pieceid)
require.NoError(t, err)
assert.Equal(t, pieceid.String(), originalPieceID.String())
}