github.com/yunabe/lgo@v0.0.0-20190709125917-42c42d410fdf/converter/errors_test.go (about)

     1  // This file tests lgo compile error messages
     2  
     3  package converter
     4  
     5  import (
     6  	"go/scanner"
     7  	"reflect"
     8  	"strings"
     9  	"testing"
    10  )
    11  
    12  func TestConvertErrors(t *testing.T) {
    13  	tests := []struct {
    14  		name   string
    15  		src    string
    16  		errors []string
    17  	}{
    18  		{
    19  			name: "syntax errors",
    20  			src: `
    21  			func f() {
    22  				x := y +
    23  			}
    24  			func f() {`,
    25  			errors: []string{
    26  				"3:4: expected operand, found '}'",
    27  				"4:14: expected ';', found 'EOF'",
    28  			},
    29  		},
    30  		{
    31  			name: "undefined",
    32  			src: `
    33  			x := y
    34  			x := 10
    35  			`,
    36  			errors: []string{
    37  				"1:6: undeclared name: y",
    38  				"2:6: no new variables on left side of :=",
    39  			},
    40  		},
    41  		{
    42  			name: "inside function",
    43  			src: `
    44  			func f(x int) int {
    45  				return 1.23 * x
    46  			}
    47  			`,
    48  			errors: []string{
    49  				"2:12: 1.23 (untyped float constant) truncated to int",
    50  			},
    51  		},
    52  	}
    53  	for _, tt := range tests {
    54  		t.Run(tt.name, func(t *testing.T) {
    55  			result := Convert(strings.TrimSpace(tt.src), &Config{})
    56  			err := result.Err
    57  			if err == nil {
    58  				t.Error("No error is reported")
    59  				return
    60  			}
    61  			var errs []string
    62  			if lst, ok := err.(ErrorList); ok {
    63  				for _, e := range lst {
    64  					errs = append(errs, e.Error())
    65  				}
    66  			} else if lst, ok := err.(scanner.ErrorList); ok {
    67  				for _, e := range lst {
    68  					errs = append(errs, e.Error())
    69  				}
    70  			} else {
    71  				errs = []string{err.Error()}
    72  			}
    73  			if !reflect.DeepEqual(errs, tt.errors) {
    74  				t.Errorf("Expected %#v but got %#v", tt.errors, errs)
    75  			}
    76  		})
    77  	}
    78  
    79  }