github.com/avence12/go-ethereum@v1.5.10-0.20170320123548-1dfd65f6d047/common/types_test.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package common 18 19 import ( 20 "encoding/json" 21 "math/big" 22 "strings" 23 "testing" 24 25 "github.com/ethereum/go-ethereum/common/hexutil" 26 ) 27 28 func TestBytesConversion(t *testing.T) { 29 bytes := []byte{5} 30 hash := BytesToHash(bytes) 31 32 var exp Hash 33 exp[31] = 5 34 35 if hash != exp { 36 t.Errorf("expected %x got %x", exp, hash) 37 } 38 } 39 40 func TestHashJsonValidation(t *testing.T) { 41 var tests = []struct { 42 Prefix string 43 Size int 44 Error string 45 }{ 46 {"", 62, hexutil.ErrMissingPrefix.Error()}, 47 {"0x", 66, "hex string has length 66, want 64 for Hash"}, 48 {"0x", 63, hexutil.ErrOddLength.Error()}, 49 {"0x", 0, "hex string has length 0, want 64 for Hash"}, 50 {"0x", 64, ""}, 51 {"0X", 64, ""}, 52 } 53 for _, test := range tests { 54 input := `"` + test.Prefix + strings.Repeat("0", test.Size) + `"` 55 var v Hash 56 err := json.Unmarshal([]byte(input), &v) 57 if err == nil { 58 if test.Error != "" { 59 t.Errorf("%s: error mismatch: have nil, want %q", input, test.Error) 60 } 61 } else { 62 if err.Error() != test.Error { 63 t.Errorf("%s: error mismatch: have %q, want %q", input, err, test.Error) 64 } 65 } 66 } 67 } 68 69 func TestAddressUnmarshalJSON(t *testing.T) { 70 var tests = []struct { 71 Input string 72 ShouldErr bool 73 Output *big.Int 74 }{ 75 {"", true, nil}, 76 {`""`, true, nil}, 77 {`"0x"`, true, nil}, 78 {`"0x00"`, true, nil}, 79 {`"0xG000000000000000000000000000000000000000"`, true, nil}, 80 {`"0x0000000000000000000000000000000000000000"`, false, big.NewInt(0)}, 81 {`"0x0000000000000000000000000000000000000010"`, false, big.NewInt(16)}, 82 } 83 for i, test := range tests { 84 var v Address 85 err := json.Unmarshal([]byte(test.Input), &v) 86 if err != nil && !test.ShouldErr { 87 t.Errorf("test #%d: unexpected error: %v", i, err) 88 } 89 if err == nil { 90 if test.ShouldErr { 91 t.Errorf("test #%d: expected error, got none", i) 92 } 93 if v.Big().Cmp(test.Output) != 0 { 94 t.Errorf("test #%d: address mismatch: have %v, want %v", i, v.Big(), test.Output) 95 } 96 } 97 } 98 }