github.com/blend/go-sdk@v1.20220411.3/ansi/table_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package ansi
     9  
    10  import (
    11  	"bytes"
    12  	"fmt"
    13  	"testing"
    14  
    15  	"github.com/blend/go-sdk/assert"
    16  )
    17  
    18  func TestTable(t *testing.T) {
    19  	assert := assert.New(t)
    20  
    21  	buffer := new(bytes.Buffer)
    22  
    23  	err := Table(buffer, []string{"foo", "bar"}, [][]string{{"1", "2"}, {"3", "4"}})
    24  	assert.Nil(err)
    25  	assert.NotEmpty(buffer.String())
    26  }
    27  
    28  func TestTableEmptyErr(t *testing.T) {
    29  	assert := assert.New(t)
    30  
    31  	buffer := new(bytes.Buffer)
    32  
    33  	err := Table(buffer, nil, [][]string{{"1", "2"}, {"3", "4"}})
    34  	assert.NotNil(err)
    35  }
    36  
    37  func TestTableWriteErr(t *testing.T) {
    38  	assert := assert.New(t)
    39  
    40  	failAfter := &failAfter{MaxBytes: 32}
    41  
    42  	err := Table(failAfter, []string{"foo", "bar", "baz"}, [][]string{
    43  		{"1", "2", "3"},
    44  		{"4", "5", "6"},
    45  		{"7", "8", "9"},
    46  	})
    47  	assert.NotNil(err)
    48  	assert.Equal("did fail", err.Error())
    49  }
    50  
    51  type failAfter struct {
    52  	Written  []byte
    53  	MaxBytes int
    54  }
    55  
    56  func (fa *failAfter) Write(contents []byte) (int, error) {
    57  	fa.Written = append(fa.Written, contents...)
    58  	if len(fa.Written) > fa.MaxBytes {
    59  		return len(contents), fmt.Errorf("did fail")
    60  	}
    61  	return len(contents), nil
    62  }
    63  
    64  func TestTableForSlice(t *testing.T) {
    65  	assert := assert.New(t)
    66  
    67  	objects := []struct {
    68  		ID   int
    69  		Name string
    70  	}{
    71  		{1, "Foo"},
    72  		{2, "Bar"},
    73  		{3, "Baz"},
    74  	}
    75  
    76  	output := new(bytes.Buffer)
    77  	assert.Nil(TableForSlice(output, objects))
    78  	assert.Equal(
    79  		"┌──┬────┐\n│ID│Name│\n├──┼────┤\n│1 │Foo │\n│2 │Bar │\n│3 │Baz │\n└──┴────┘\n",
    80  		output.String(),
    81  	)
    82  }
    83  
    84  func TestTableForSliceUnicode(t *testing.T) {
    85  	assert := assert.New(t)
    86  
    87  	objects := []struct {
    88  		ID    string
    89  		Count int
    90  	}{
    91  		{"モ foo", 1},
    92  		{"ふ bar", 1},
    93  		{"ス baz", 3},
    94  	}
    95  
    96  	output := new(bytes.Buffer)
    97  	assert.Nil(TableForSlice(output, objects))
    98  	assert.Equal(
    99  		"┌──────┬─────┐\n│ID    │Count│\n├──────┼─────┤\n│モ foo│1    │\n│ふ bar│1    │\n│ス baz│3    │\n└──────┴─────┘\n",
   100  		output.String(),
   101  	)
   102  }