github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/ezmap/csv_test.go (about)

     1  package ezmap
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  func TestMarshalCSV(t *testing.T) {
    11  	type AString string
    12  	type AStruct struct {
    13  		A bool
    14  		B AString
    15  	}
    16  	records := []Map{
    17  		{
    18  			"bool":   true,
    19  			"int":    1234,
    20  			"str":    "12345",
    21  			"str_2":  AString("23456"),
    22  			"struct": AStruct{A: true, B: "23456"},
    23  		},
    24  		{
    25  			"int":    4321,
    26  			"str_2":  AString("65432"),
    27  			"bool":   false,
    28  			"struct": AStruct{A: false, B: "65432"},
    29  			"str":    "12345",
    30  		},
    31  	}
    32  	got, err := MarshalCSV(records)
    33  	require.Nil(t, err)
    34  
    35  	want := `bool,int,str,str_2,struct
    36  true,1234,12345,23456,"{""A"":true,""B"":""23456""}"
    37  false,4321,12345,65432,"{""A"":false,""B"":""65432""}"
    38  `
    39  	assert.Equal(t, want, string(got))
    40  }
    41  
    42  func TestUnmarshalCSV(t *testing.T) {
    43  	t.Run("success", func(t *testing.T) {
    44  		data := `bool,int,str,str_2,struct
    45  true,1234,12345,23456,"{""A"":true,""B"":""23456""}"
    46  false,4321,12345,65432,"{""A"":false,""B"":""65432""}"
    47  `
    48  		got, err := UnmarshalCVS([]byte(data))
    49  		require.Nil(t, err)
    50  
    51  		want := []Map{
    52  			{
    53  				"bool":   "true",
    54  				"int":    "1234",
    55  				"str":    "12345",
    56  				"str_2":  "23456",
    57  				"struct": `{"A":true,"B":"23456"}`,
    58  			},
    59  			{
    60  				"int":    "4321",
    61  				"str_2":  "65432",
    62  				"bool":   "false",
    63  				"struct": `{"A":false,"B":"65432"}`,
    64  				"str":    "12345",
    65  			},
    66  		}
    67  		assert.Equal(t, want, got)
    68  	})
    69  
    70  	t.Run("duplicate header", func(t *testing.T) {
    71  		data := `bool,int,str,int
    72  true,123,"abc",456
    73  `
    74  		_, err := UnmarshalCVS([]byte(data))
    75  		require.NotNil(t, err)
    76  		assert.Contains(t, err.Error(), "duplicate header: int")
    77  	})
    78  }