github.com/0xsequence/ethkit@v1.25.0/cmd/ethkit/print_test.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  var (
    13  	complex = struct {
    14  		Name    string           `json:"name"`
    15  		List    []any            `json:"list"`
    16  		Nested  Nested           `json:"nested"`
    17  		Object  map[string]any   `json:"object"`
    18  		ObjList []map[string]any `json:"objList"`
    19  	}{
    20  		Name: "complex",
    21  		List: []any{
    22  			"first",
    23  			"second",
    24  		},
    25  		Nested: Nested{
    26  			Title: "hello",
    27  			Value: 500000000,
    28  		},
    29  		Object: map[string]any{
    30  			"obj1": 1,
    31  			"obj2": -2,
    32  		},
    33  		ObjList: []map[string]any{
    34  			{
    35  				"item1": 1,
    36  				"item2": 2,
    37  			},
    38  			{
    39  				"item3": 3e7,
    40  				"item4": 2E7,
    41  				"item5": 2.123456e7,
    42  			},
    43  		},
    44  	}
    45  
    46  	s        string
    47  	rows     []string
    48  	p        Printable
    49  	minwidth = 24
    50  	tabwidth = 0
    51  	padding  = 0
    52  	padchar  = byte(' ')
    53  )
    54  
    55  type Nested struct {
    56  	Title string `json:"title"`
    57  	Value uint   `json:"value"`
    58  }
    59  
    60  func setup() {
    61  	if err := p.FromStruct(complex); err != nil {
    62  		panic(err)
    63  	}
    64  	s = p.Columnize(*NewPrintableFormat(minwidth, tabwidth, padding, padchar))
    65  	fmt.Println(s)
    66  	rows = strings.Split(s, "\n")
    67  }
    68  
    69  func Test_Columnize(t *testing.T) {
    70  	setup()
    71  	for i := 0; i < len(rows); i++ {
    72  		if rows[i] != "" {
    73  			// the delimiter should be in the same position in all the rows
    74  			assert.Equal(t, strings.Index(rows[i], "|"), minwidth)
    75  			if strings.Contains(rows[i], "item5") {
    76  				v := strconv.FormatFloat(complex.ObjList[1]["item5"].(float64), 'f', -1, 64)
    77  				// the value of the nested object should be indented to the 3rd column and it should be parsed as an integer
    78  				// left bound: 2*\t + 1*' ' = 3 , right bound: 3 + len(21234560) + 1 = 11
    79  				assert.Equal(t, rows[i][minwidth*2+3:minwidth*2+11], v)
    80  			}
    81  		}
    82  	}
    83  }
    84  
    85  func Test_GetValueByJSONTag(t *testing.T) {
    86  	setup()
    87  	tag := "title"
    88  	assert.Equal(t, GetValueByJSONTag(complex, tag), complex.Nested.Title)
    89  }
    90  
    91  func Test_GetValueByJSONTag_FailWhenNotStruct(t *testing.T) {
    92  	setup()
    93  	tag := "title"
    94  	assert.Nil(t, GetValueByJSONTag(p, tag))
    95  }