github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/rpc/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 rpc
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"math/big"
    23  	"testing"
    24  )
    25  
    26  func TestNewHexNumber(t *testing.T) {
    27  	tests := []interface{}{big.NewInt(123), int64(123), uint64(123), int8(123), uint8(123)}
    28  
    29  	for i, v := range tests {
    30  		hn := NewHexNumber(v)
    31  		if hn == nil {
    32  			t.Fatalf("Unable to create hex number instance for tests[%d]", i)
    33  		}
    34  		if hn.Int64() != 123 {
    35  			t.Fatalf("expected %d, got %d on value tests[%d]", 123, hn.Int64(), i)
    36  		}
    37  	}
    38  
    39  	failures := []interface{}{"", nil, []byte{1, 2, 3, 4}}
    40  	for i, v := range failures {
    41  		hn := NewHexNumber(v)
    42  		if hn != nil {
    43  			t.Fatalf("Creating a nex number instance of %T should fail (failures[%d])", failures[i], i)
    44  		}
    45  	}
    46  }
    47  
    48  func TestHexNumberUnmarshalJSON(t *testing.T) {
    49  	tests := []string{`"0x4d2"`, "1234", `"1234"`}
    50  	for i, v := range tests {
    51  		var hn HexNumber
    52  		if err := json.Unmarshal([]byte(v), &hn); err != nil {
    53  			t.Fatalf("Test %d failed - %s", i, err)
    54  		}
    55  
    56  		if hn.Int64() != 1234 {
    57  			t.Fatalf("Expected %d, got %d for test[%d]", 1234, hn.Int64(), i)
    58  		}
    59  	}
    60  }
    61  
    62  func TestHexNumberMarshalJSON(t *testing.T) {
    63  	hn := NewHexNumber(1234567890)
    64  	got, err := json.Marshal(hn)
    65  	if err != nil {
    66  		t.Fatalf("Unable to marshal hex number - %s", err)
    67  	}
    68  
    69  	exp := []byte(`"0x499602d2"`)
    70  	if bytes.Compare(exp, got) != 0 {
    71  		t.Fatalf("Invalid json.Marshal, expected '%s', got '%s'", exp, got)
    72  	}
    73  }