Skip to content

Commit

Permalink
id: fix String() and add tests for edge cases while unmarshaling byte…
Browse files Browse the repository at this point in the history
…s into ids
  • Loading branch information
iwasaki-kenta committed Jan 29, 2020
1 parent cd7c313 commit 6c30632
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 4 deletions.
4 changes: 3 additions & 1 deletion .codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ codecov:
max_report_age: off

ignore:
- "./cmd"
- "./cmd/basic"
- "./cmd/benchmark_rpc"
- "./cmd/benchmark_send"

comment: false

Expand Down
6 changes: 3 additions & 3 deletions id.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ func (e ID) Size() int {
// String returns a JSON representation of this ID.
func (e ID) String() string {
var builder strings.Builder
builder.WriteString(`{"public_key": `)
builder.WriteString(`{"public_key": "`)
builder.WriteString(hex.EncodeToString(e.ID[:]))
builder.WriteString(`, "address": `)
builder.WriteString(`", "address": "`)
builder.WriteString(e.Address)
builder.WriteString("}")
builder.WriteString(`"}`)
return builder.String()
}

Expand Down
55 changes: 55 additions & 0 deletions id_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package noise_test

import (
"fmt"
"github.com/perlin-network/noise"
"github.com/stretchr/testify/assert"
"io"
"net"
"strconv"
"testing"
"testing/quick"
)

func TestID_String(t *testing.T) {
t.Parallel()

f := func(publicKey noise.PublicKey, host net.IP, port uint16) bool {
h := host.String() // Make-shift 'normalizeIP(net.IP)'.
if h == "<nil>" {
h = ""
}

id := noise.NewID(publicKey, host, port)

if !assert.Equal(t,
fmt.Sprintf(
`{"public_key": "%s", "address": "%s"}`,
publicKey, net.JoinHostPort(h, strconv.FormatUint(uint64(port), 10)),
),
id.String(),
) {
return false
}

return true
}

assert.NoError(t, quick.Check(f, nil))
}

func TestUnmarshalID(t *testing.T) {
t.Parallel()

_, err := noise.UnmarshalID(nil)
assert.EqualError(t, err, io.ErrUnexpectedEOF.Error())

_, err = noise.UnmarshalID(append(noise.ZeroPublicKey[:], 1))
assert.EqualError(t, err, io.ErrUnexpectedEOF.Error())

_, err = noise.UnmarshalID(append(noise.ZeroPublicKey[:], append(net.IPv6loopback, 1)...))
assert.EqualError(t, err, io.ErrUnexpectedEOF.Error())

_, err = noise.UnmarshalID(append(noise.ZeroPublicKey[:], append(net.IPv6loopback, 1, 2)...))
assert.NoError(t, err)
}

0 comments on commit 6c30632

Please sign in to comment.