github.com/bchainhub/blockbook@v0.3.2/bchain/baseparser_test.go (about)

     1  package bchain
     2  
     3  import (
     4  	"encoding/json"
     5  	"math/big"
     6  	"testing"
     7  )
     8  
     9  func NewBaseParser(adp int) *BaseParser {
    10  	return &BaseParser{
    11  		AmountDecimalPoint: adp,
    12  	}
    13  }
    14  
    15  var amounts = []struct {
    16  	a           *big.Int
    17  	s           string
    18  	adp         int
    19  	alternative string
    20  }{
    21  	{big.NewInt(123456789), "1.23456789", 8, "!"},
    22  	{big.NewInt(2), "0.00000002", 8, "!"},
    23  	{big.NewInt(300000000), "3", 8, "!"},
    24  	{big.NewInt(498700000), "4.987", 8, "!"},
    25  	{big.NewInt(567890), "0.00000000000056789", 18, "!"},
    26  	{big.NewInt(-100000000), "-1", 8, "!"},
    27  	{big.NewInt(-8), "-0.00000008", 8, "!"},
    28  	{big.NewInt(-89012345678), "-890.12345678", 8, "!"},
    29  	{big.NewInt(-12345), "-0.00012345", 8, "!"},
    30  	{big.NewInt(12345678), "0.123456789012", 8, "0.12345678"},                       // test of truncation of too many decimal places
    31  	{big.NewInt(12345678), "0.0000000000000000000000000000000012345678", 1234, "!"}, // test of too big number decimal places
    32  }
    33  
    34  func TestBaseParser_AmountToDecimalString(t *testing.T) {
    35  	for _, tt := range amounts {
    36  		t.Run(tt.s, func(t *testing.T) {
    37  			if got := NewBaseParser(tt.adp).AmountToDecimalString(tt.a); got != tt.s && got != tt.alternative {
    38  				t.Errorf("BaseParser.AmountToDecimalString() = %v, want %v", got, tt.s)
    39  			}
    40  		})
    41  	}
    42  }
    43  
    44  func TestBaseParser_AmountToBigInt(t *testing.T) {
    45  	for _, tt := range amounts {
    46  		t.Run(tt.s, func(t *testing.T) {
    47  			got, err := NewBaseParser(tt.adp).AmountToBigInt(json.Number(tt.s))
    48  			if err != nil {
    49  				t.Errorf("BaseParser.AmountToBigInt() error = %v", err)
    50  				return
    51  			}
    52  			if got.Cmp(tt.a) != 0 {
    53  				t.Errorf("BaseParser.AmountToBigInt() = %v, want %v", got, tt.a)
    54  			}
    55  		})
    56  	}
    57  }