github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/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 "math/big" 21 "testing" 22 ) 23 24 func TestBytesConversion(t *testing.T) { 25 bytes := []byte{5} 26 hash := BytesToHash(bytes) 27 28 var exp Hash 29 exp[31] = 5 30 31 if hash != exp { 32 t.Errorf("expected %x got %x", exp, hash) 33 } 34 } 35 36 func TestHashJsonValidation(t *testing.T) { 37 var h Hash 38 var tests = []struct { 39 Prefix string 40 Size int 41 Error error 42 }{ 43 {"", 2, hashJsonLengthErr}, 44 {"", 62, hashJsonLengthErr}, 45 {"", 66, hashJsonLengthErr}, 46 {"", 65, hashJsonLengthErr}, 47 {"0X", 64, nil}, 48 {"0x", 64, nil}, 49 {"0x", 62, hashJsonLengthErr}, 50 } 51 for i, test := range tests { 52 if err := h.UnmarshalJSON(append([]byte(test.Prefix), make([]byte, test.Size)...)); err != test.Error { 53 t.Errorf("test #%d: error mismatch: have %v, want %v", i, err, test.Error) 54 } 55 } 56 } 57 58 func TestAddressUnmarshalJSON(t *testing.T) { 59 var a Address 60 var tests = []struct { 61 Input string 62 ShouldErr bool 63 Output *big.Int 64 }{ 65 {"", true, nil}, 66 {`""`, true, nil}, 67 {`"0x"`, true, nil}, 68 {`"0x00"`, true, nil}, 69 {`"0xG000000000000000000000000000000000000000"`, true, nil}, 70 {`"0x0000000000000000000000000000000000000000"`, false, big.NewInt(0)}, 71 {`"0x0000000000000000000000000000000000000010"`, false, big.NewInt(16)}, 72 } 73 for i, test := range tests { 74 err := a.UnmarshalJSON([]byte(test.Input)) 75 if err != nil && !test.ShouldErr { 76 t.Errorf("test #%d: unexpected error: %v", i, err) 77 } 78 if err == nil { 79 if test.ShouldErr { 80 t.Errorf("test #%d: expected error, got none", i) 81 } 82 if a.Big().Cmp(test.Output) != 0 { 83 t.Errorf("test #%d: address mismatch: have %v, want %v", i, a.Big(), test.Output) 84 } 85 } 86 } 87 }