github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/go/pointer/query_test.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package pointer
     6  
     7  import (
     8  	"reflect"
     9  	"testing"
    10  
    11  	"github.com/powerman/golang-tools/go/loader"
    12  )
    13  
    14  func TestParseExtendedQuery(t *testing.T) {
    15  	const myprog = `
    16  package pkg
    17  
    18  import "reflect"
    19  
    20  type T []*int
    21  
    22  var V1 *int
    23  var V2 **int
    24  var V3 []*int
    25  var V4 chan []*int
    26  var V5 struct {F1, F2 chan *int}
    27  var V6 [1]chan *int
    28  var V7 int
    29  var V8 T
    30  var V9 reflect.Value
    31  `
    32  	tests := []struct {
    33  		in    string
    34  		out   []interface{}
    35  		v     string
    36  		valid bool
    37  	}{
    38  		{`x`, []interface{}{"x"}, "V1", true},
    39  		{`x`, []interface{}{"x"}, "V9", true},
    40  		{`*x`, []interface{}{"x", "load"}, "V2", true},
    41  		{`x[0]`, []interface{}{"x", "sliceelem"}, "V3", true},
    42  		{`x[0]`, []interface{}{"x", "sliceelem"}, "V8", true},
    43  		{`<-x`, []interface{}{"x", "recv"}, "V4", true},
    44  		{`(<-x)[0]`, []interface{}{"x", "recv", "sliceelem"}, "V4", true},
    45  		{`<-x.F2`, []interface{}{"x", "field", 1, "recv"}, "V5", true},
    46  		{`<-x[0]`, []interface{}{"x", "arrayelem", "recv"}, "V6", true},
    47  		{`x`, nil, "V7", false},
    48  		{`y`, nil, "V1", false},
    49  		{`x; x`, nil, "V1", false},
    50  		{`x()`, nil, "V1", false},
    51  		{`close(x)`, nil, "V1", false},
    52  	}
    53  
    54  	var conf loader.Config
    55  	f, err := conf.ParseFile("file.go", myprog)
    56  	if err != nil {
    57  		t.Fatal(err)
    58  	}
    59  	conf.CreateFromFiles("main", f)
    60  	lprog, err := conf.Load()
    61  	if err != nil {
    62  		t.Fatal(err)
    63  	}
    64  	pkg := lprog.Created[0].Pkg
    65  
    66  	for _, test := range tests {
    67  		typ := pkg.Scope().Lookup(test.v).Type()
    68  		ops, _, err := parseExtendedQuery(typ, test.in)
    69  		if test.valid && err != nil {
    70  			t.Errorf("parseExtendedQuery(%q) = %s, expected no error", test.in, err)
    71  		}
    72  		if !test.valid && err == nil {
    73  			t.Errorf("parseExtendedQuery(%q) succeeded, expected error", test.in)
    74  		}
    75  
    76  		if !reflect.DeepEqual(ops, test.out) {
    77  			t.Errorf("parseExtendedQuery(%q) = %#v, want %#v", test.in, ops, test.out)
    78  		}
    79  	}
    80  }