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

     1  package action
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"os"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/mithrandie/csvq/lib/file"
    11  
    12  	"github.com/mithrandie/csvq/lib/query"
    13  )
    14  
    15  var executeTests = []struct {
    16  	Name    string
    17  	Input   string
    18  	OutFile string
    19  	Output  string
    20  	Stats   bool
    21  	Content string
    22  	Error   string
    23  }{
    24  	{
    25  		Name:    "Select Query Output To File",
    26  		Input:   "select 1 from dual",
    27  		OutFile: GetTestFilePath("select_query_output_file.csv"),
    28  		Content: "" +
    29  			"+---+\n" +
    30  			"| 1 |\n" +
    31  			"+---+\n" +
    32  			"| 1 |\n" +
    33  			"+---+\n",
    34  	},
    35  	{
    36  		Name:   "Print",
    37  		Input:  "var @a := 1; print @a;",
    38  		Output: "1\n",
    39  	},
    40  	{
    41  		Name:  "Query Execution Error",
    42  		Input: "select from",
    43  		Error: "[L:1 C:8] syntax error: unexpected token \"from\"",
    44  	},
    45  	{
    46  		Name:  "Show Statistics",
    47  		Input: "select 1",
    48  		Stats: true,
    49  	},
    50  }
    51  
    52  func TestRun(t *testing.T) {
    53  	tx, _ := query.NewTransaction(context.Background(), file.DefaultWaitTimeout, file.DefaultRetryDelay, query.NewSession())
    54  	tx.UseColor(false)
    55  	ctx := context.Background()
    56  
    57  	for _, v := range executeTests {
    58  		if v.Stats {
    59  			tx.Flags.Stats = v.Stats
    60  		}
    61  
    62  		tx.Session.SetOutFile(nil)
    63  
    64  		out := query.NewOutput()
    65  		tx.Session.SetStdout(out)
    66  
    67  		proc := query.NewProcessor(tx)
    68  		err := Run(ctx, proc, v.Input, "", v.OutFile)
    69  
    70  		stdout := out.String()
    71  
    72  		if err != nil {
    73  			if len(v.Error) < 1 {
    74  				t.Errorf("%s: unexpected error %q", v.Name, err)
    75  			} else if err.Error() != v.Error {
    76  				t.Errorf("%s: error %q, want error %q", v.Name, err.Error(), v.Error)
    77  			}
    78  			continue
    79  		}
    80  		if 0 < len(v.Error) {
    81  			t.Errorf("%s: no error, want error %q", v.Name, v.Error)
    82  			continue
    83  		}
    84  
    85  		if v.Stats {
    86  			if !strings.Contains(stdout, "Time:") {
    87  				t.Errorf("%s: output = %q, want statistics", v.Name, stdout)
    88  			}
    89  		} else {
    90  			if stdout != v.Output {
    91  				t.Errorf("%s: output = %q, want %q", v.Name, stdout, v.Output)
    92  			}
    93  
    94  			if 0 < len(v.OutFile) {
    95  				fp, _ := os.Open(v.OutFile)
    96  				buf, _ := io.ReadAll(fp)
    97  				if string(buf) != v.Content {
    98  					t.Errorf("%s: content = %q, want %q", v.Name, string(buf), v.Content)
    99  				}
   100  			}
   101  		}
   102  	}
   103  }