Skip to content

Commit

Permalink
Merge pull request #1339 from mesg-foundation/fix/hash-unmarshal
Browse files Browse the repository at this point in the history
Fix hash.Unmarshal when using proto.Unmarshal
  • Loading branch information
Nicolas Mahé authored Sep 16, 2019
2 parents 9e33cad + e5996b2 commit 8ed2614
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
32 changes: 32 additions & 0 deletions database/process_db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,35 @@ func TestProcessDB(t *testing.T) {
require.NoError(t, db.Delete(p.Hash))
})
}

func TestHashIsDifferent(t *testing.T) {
dir, _ := ioutil.TempDir("", "process.db.test")
defer os.Remove(dir)

db, err := NewProcessDB(dir)
require.NoError(t, err)
defer db.Close()

p1 := &process.Process{
Hash: hash.Int(1),
Key: "1",
}

p2 := &process.Process{
Hash: hash.Int(2),
Key: "2",
}

db.Save(p1)
db.Save(p2)

list, err := db.All()
require.NoError(t, err)
require.Len(t, list, 2)

require.Equal(t, list[0].Key, p1.Key)
require.Equal(t, list[0].Hash, p1.Hash)

require.Equal(t, list[1].Key, p2.Key)
require.Equal(t, list[1].Hash, p2.Hash)
}
3 changes: 2 additions & 1 deletion hash/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ func (h Hash) MarshalTo(data []byte) (int, error) {

// Unmarshal unmarshals slice of bytes into hash. It's used by protobuf.
func (h *Hash) Unmarshal(data []byte) error {
*h = data
*h = make([]byte, len(data))
copy(*h, data)
return nil
}

Expand Down
9 changes: 9 additions & 0 deletions hash/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,12 @@ func TestUnmarshalJSON(t *testing.T) {
assert.NoError(t, json.Unmarshal([]byte("\"4uQeVj5tqViQh7yWWGStvkEG1Zmhx6uasJtWCJziofM\""), &h))
assert.Equal(t, Int(1), h)
}

func TestUnmarshal(t *testing.T) {
var hash Hash
data := []byte(Int(1))
hash.Unmarshal(data)
// check if unmarshal copy the data
// test if two slises do not share the same address
assert.True(t, &hash[cap(hash)-1] != &data[cap(data)-1])
}

0 comments on commit 8ed2614

Please sign in to comment.