github.com/mithrandie/csvq@v1.18.1/lib/action/calc_test.go (about)

     1  package action
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/mithrandie/csvq/lib/file"
    10  
    11  	"github.com/mithrandie/csvq/lib/query"
    12  )
    13  
    14  var calcTests = []struct {
    15  	Stdin  string
    16  	Input  string
    17  	Output string
    18  	Error  string
    19  }{
    20  	{
    21  		Stdin:  "foo",
    22  		Input:  "md5(c1)",
    23  		Output: "acbd18db4cc2f85cedef654fccc4a4d8",
    24  	},
    25  	{
    26  		Stdin:  "1,\"a\",1.234,true,unknown,\"2012-01-01 01:00:00 +00:00\",",
    27  		Input:  "integer(c1),c2,float(c3),boolean(c4),null = true,datetime(c6),c7",
    28  		Output: "1,a,1.234,true,UNKNOWN,2012-01-01T01:00:00Z,NULL",
    29  	},
    30  	{
    31  		Stdin: "foo",
    32  		Input: "from",
    33  		Error: "syntax error",
    34  	},
    35  	{
    36  		Stdin: "",
    37  		Input: "md5(c1)",
    38  		Error: "STDIN is empty",
    39  	},
    40  	{
    41  		Stdin: "foo",
    42  		Input: "error",
    43  		Error: "field error does not exist",
    44  	},
    45  }
    46  
    47  func TestCalc(t *testing.T) {
    48  	tx, _ := query.NewTransaction(context.Background(), file.DefaultWaitTimeout, file.DefaultRetryDelay, query.NewSession())
    49  	scope := query.NewReferenceScope(tx)
    50  	ctx := context.Background()
    51  
    52  	for _, v := range calcTests {
    53  		_ = tx.Rollback(scope, nil)
    54  
    55  		if 0 < len(v.Stdin) {
    56  			_ = tx.Session.SetStdin(query.NewInput(strings.NewReader(v.Stdin)))
    57  		}
    58  		out := query.NewOutput()
    59  		tx.Session.SetStdout(out)
    60  
    61  		err := Calc(ctx, query.NewProcessor(tx), v.Input)
    62  
    63  		if 0 < len(v.Stdin) {
    64  			_ = tx.Session.SetStdin(os.Stdin)
    65  		}
    66  		stdout := out.String()
    67  
    68  		if err != nil {
    69  			if len(v.Error) < 1 {
    70  				t.Errorf("%s: unexpected error %q", v.Input, err)
    71  			} else if err.Error() != v.Error {
    72  				t.Errorf("%s: error %q, want error %q", v.Input, err.Error(), v.Error)
    73  			}
    74  			continue
    75  		}
    76  		if 0 < len(v.Error) {
    77  			t.Errorf("%s: no error, want error %q", v.Input, v.Error)
    78  			continue
    79  		}
    80  
    81  		if stdout != v.Output {
    82  			t.Errorf("%s: output = %q, want %q", v.Input, stdout, v.Output)
    83  		}
    84  	}
    85  }