github.com/iotexproject/iotex-core@v1.14.1-rc1/state/factory/patchstore_test.go (about)

     1  package factory
     2  
     3  import (
     4  	"encoding/csv"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/require"
     9  
    10  	"github.com/iotexproject/iotex-core/testutil"
    11  )
    12  
    13  func TestPatchStore(t *testing.T) {
    14  	require := require.New(t)
    15  	patchTest := [][]string{
    16  		{"1", "DELETE", "test", "74657374"},
    17  		{"2", "PUT", "test", "74657374", "7465737432"},
    18  	}
    19  
    20  	filePath, _ := testutil.PathOfTempFile("test")
    21  	defer testutil.CleanupPath(filePath)
    22  	f, err := os.Create(filePath)
    23  	require.NoError(err)
    24  
    25  	w := csv.NewWriter(f)
    26  	err = w.WriteAll(patchTest)
    27  	require.NoError(err)
    28  	patch, _ := newPatchStore(filePath)
    29  	require.Equal(len(patch.Get(1)), 1)
    30  	require.Equal(patch.Get(1)[0].Namespace, "test")
    31  	require.Equal(patch.Get(1)[0].Type, _Delete)
    32  	require.Equal(string(patch.Get(1)[0].Key), "test")
    33  	require.Equal(len(patch.Get(1)[0].Value), 0)
    34  	require.Equal(len(patch.Get(3)), 0)
    35  	require.NoError(f.Close())
    36  	require.NoError(os.RemoveAll(filePath))
    37  
    38  	// empty filePath
    39  	patch, err = newPatchStore("")
    40  	require.NoError(err)
    41  	require.Equal(len(patch.patchs), 0)
    42  
    43  	// incorrect format of patch file
    44  	patchTest2 := []struct {
    45  		input  [][]string
    46  		errMsg string
    47  	}{
    48  		{
    49  			input: [][]string{
    50  				{"1", "DEL", "test", "74657374"},
    51  			},
    52  			errMsg: "invalid patch type",
    53  		},
    54  		{
    55  			input: [][]string{
    56  				{"1", "DEL", "test"},
    57  			},
    58  			errMsg: "wrong format",
    59  		},
    60  		{
    61  			input: [][]string{
    62  				{"2", "PUT", "test", "74657374", "7465737432", "12332"},
    63  			},
    64  			errMsg: "wrong put format",
    65  		},
    66  		{
    67  			input: [][]string{
    68  				{"1", "PUT", "test", "0x74", "0x74"},
    69  			},
    70  			errMsg: "failed to parse value",
    71  		},
    72  	}
    73  
    74  	for _, test := range patchTest2 {
    75  		filePath, _ = testutil.PathOfTempFile("test")
    76  		defer testutil.CleanupPath(filePath)
    77  		f, err = os.Create(filePath)
    78  		require.NoError(err)
    79  
    80  		w = csv.NewWriter(f)
    81  		err = w.WriteAll(test.input)
    82  		require.NoError(err)
    83  		_, err := newPatchStore(filePath)
    84  		require.Error(err)
    85  		require.Contains(err.Error(), test.errMsg)
    86  		require.NoError(f.Close())
    87  		require.NoError(os.RemoveAll(filePath))
    88  	}
    89  
    90  }