[#302] pkg/container/id: Convert nil ID to nil message

Document that `ID.ToV2` method returns
`nil` when is called on `nil`. Document
 that `NewFromV2` method returns
`nil` when is called on `nil`. Add
corresponding unit test.

Signed-off-by: Pavel Karpy <carpawell@nspcc.ru>
This commit is contained in:
Pavel Karpy 2021-06-08 15:07:00 +03:00 committed by Alex Vanin
parent 9fae0e4f2d
commit 6ce8844654
2 changed files with 26 additions and 4 deletions

View file

@ -13,6 +13,8 @@ import (
type ID refs.ContainerID type ID refs.ContainerID
// NewFromV2 wraps v2 ContainerID message to ID. // NewFromV2 wraps v2 ContainerID message to ID.
//
// Nil refs.ContainerID converts to nil.
func NewFromV2(idV2 *refs.ContainerID) *ID { func NewFromV2(idV2 *refs.ContainerID) *ID {
return (*ID)(idV2) return (*ID)(idV2)
} }
@ -28,6 +30,8 @@ func (id *ID) SetSHA256(v [sha256.Size]byte) {
} }
// ToV2 returns the v2 container ID message. // ToV2 returns the v2 container ID message.
//
// Nil Result converts to nil.
func (id *ID) ToV2() *refs.ContainerID { func (id *ID) ToV2() *refs.ContainerID {
return (*refs.ContainerID)(id) return (*refs.ContainerID)(id)
} }

View file

@ -7,6 +7,7 @@ import (
cid "github.com/nspcc-dev/neofs-api-go/pkg/container/id" cid "github.com/nspcc-dev/neofs-api-go/pkg/container/id"
cidtest "github.com/nspcc-dev/neofs-api-go/pkg/container/id/test" cidtest "github.com/nspcc-dev/neofs-api-go/pkg/container/id/test"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -16,13 +17,22 @@ func randSHA256Checksum() (cs [sha256.Size]byte) {
} }
func TestID_ToV2(t *testing.T) { func TestID_ToV2(t *testing.T) {
checksum := randSHA256Checksum() t.Run("non-nil", func(t *testing.T) {
checksum := randSHA256Checksum()
id := cidtest.GenerateWithChecksum(checksum) id := cidtest.GenerateWithChecksum(checksum)
idV2 := id.ToV2() idV2 := id.ToV2()
require.Equal(t, id, cid.NewFromV2(idV2)) require.Equal(t, id, cid.NewFromV2(idV2))
require.Equal(t, checksum[:], idV2.GetValue())
})
t.Run("nil", func(t *testing.T) {
var x *cid.ID
require.Nil(t, x.ToV2())
})
} }
func TestID_Equal(t *testing.T) { func TestID_Equal(t *testing.T) {
@ -69,3 +79,11 @@ func TestContainerIDEncoding(t *testing.T) {
require.Equal(t, id, a2) require.Equal(t, id, a2)
}) })
} }
func TestNewFromV2(t *testing.T) {
t.Run("from nil", func(t *testing.T) {
var x *refs.ContainerID
require.Nil(t, cid.NewFromV2(x))
})
}