gitee.com/wgliang/goreporter@v0.0.0-20180902115603-df1b20f7c5d0/linters/simpler/ssa/ssautil/switch_test.go (about)

     1  // Copyright 2013 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  // No testdata on Android.
     6  
     7  // +build !android
     8  
     9  package ssautil_test
    10  
    11  import (
    12  	"go/parser"
    13  	"strings"
    14  	"testing"
    15  
    16  	"github.com/360EntSecGroup-Skylar/goreporter/linters/simpler/ssa"
    17  	"github.com/360EntSecGroup-Skylar/goreporter/linters/simpler/ssa/ssautil"
    18  	"golang.org/x/tools/go/loader"
    19  )
    20  
    21  func TestSwitches(t *testing.T) {
    22  	conf := loader.Config{ParserMode: parser.ParseComments}
    23  	f, err := conf.ParseFile("testdata/switches.go", nil)
    24  	if err != nil {
    25  		t.Error(err)
    26  		return
    27  	}
    28  
    29  	conf.CreateFromFiles("main", f)
    30  	iprog, err := conf.Load()
    31  	if err != nil {
    32  		t.Error(err)
    33  		return
    34  	}
    35  
    36  	prog := ssautil.CreateProgram(iprog, 0)
    37  	mainPkg := prog.Package(iprog.Created[0].Pkg)
    38  	mainPkg.Build()
    39  
    40  	for _, mem := range mainPkg.Members {
    41  		if fn, ok := mem.(*ssa.Function); ok {
    42  			if fn.Synthetic != "" {
    43  				continue // e.g. init()
    44  			}
    45  			// Each (multi-line) "switch" comment within
    46  			// this function must match the printed form
    47  			// of a ConstSwitch.
    48  			var wantSwitches []string
    49  			for _, c := range f.Comments {
    50  				if fn.Syntax().Pos() <= c.Pos() && c.Pos() < fn.Syntax().End() {
    51  					text := strings.TrimSpace(c.Text())
    52  					if strings.HasPrefix(text, "switch ") {
    53  						wantSwitches = append(wantSwitches, text)
    54  					}
    55  				}
    56  			}
    57  
    58  			switches := ssautil.Switches(fn)
    59  			if len(switches) != len(wantSwitches) {
    60  				t.Errorf("in %s, found %d switches, want %d", fn, len(switches), len(wantSwitches))
    61  			}
    62  			for i, sw := range switches {
    63  				got := sw.String()
    64  				if i >= len(wantSwitches) {
    65  					continue
    66  				}
    67  				want := wantSwitches[i]
    68  				if got != want {
    69  					t.Errorf("in %s, found switch %d: got <<%s>>, want <<%s>>", fn, i, got, want)
    70  				}
    71  			}
    72  		}
    73  	}
    74  }