How to use Imports method of model Package

Best Mock code snippet using model.Imports

parse.go

Source:parse.go Github

copy

Full Screen

...53		auxInterfaces:      make(map[string]map[string]*ast.InterfaceType),54		srcDir:             srcDir,55	}56	// Handle -imports.57	dotImports := make(map[string]bool)58	if *imports != "" {59		for _, kv := range strings.Split(*imports, ",") {60			eq := strings.Index(kv, "=")61			k, v := kv[:eq], kv[eq+1:]62			if k == "." {63				// TODO: Catch dupes?64				dotImports[v] = true65			} else {66				// TODO: Catch dupes?67				p.imports[k] = v68			}69		}70	}71	// Handle -aux_files.72	if err := p.parseAuxFiles(*auxFiles); err != nil {73		return nil, err74	}75	p.addAuxInterfacesFromFile(packageImport, file) // this file76	pkg, err := p.parseFile(packageImport, file)77	if err != nil {78		return nil, err79	}80	for path := range dotImports {81		pkg.DotImports = append(pkg.DotImports, path)82	}83	return pkg, nil84}85type fileParser struct {86	fileSet            *token.FileSet87	imports            map[string]string                        // package name => import path88	importedInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface89	auxFiles      []*ast.File90	auxInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface91	srcDir string92}93func (p *fileParser) errorf(pos token.Pos, format string, args ...interface{}) error {94	ps := p.fileSet.Position(pos)95	format = "%s:%d:%d: " + format96	args = append([]interface{}{ps.Filename, ps.Line, ps.Column}, args...)97	return fmt.Errorf(format, args...)98}99func (p *fileParser) parseAuxFiles(auxFiles string) error {100	auxFiles = strings.TrimSpace(auxFiles)101	if auxFiles == "" {102		return nil103	}104	for _, kv := range strings.Split(auxFiles, ",") {105		parts := strings.SplitN(kv, "=", 2)106		if len(parts) != 2 {107			return fmt.Errorf("bad aux file spec: %v", kv)108		}109		pkg, fpath := parts[0], parts[1]110		file, err := parser.ParseFile(p.fileSet, fpath, nil, 0)111		if err != nil {112			return err113		}114		p.auxFiles = append(p.auxFiles, file)115		p.addAuxInterfacesFromFile(pkg, file)116	}117	return nil118}119func (p *fileParser) addAuxInterfacesFromFile(pkg string, file *ast.File) {120	if _, ok := p.auxInterfaces[pkg]; !ok {121		p.auxInterfaces[pkg] = make(map[string]*ast.InterfaceType)122	}123	for ni := range iterInterfaces(file) {124		p.auxInterfaces[pkg][ni.name.Name] = ni.it125	}126}127// parseFile loads all file imports and auxiliary files import into the128// fileParser, parses all file interfaces and returns package model.129func (p *fileParser) parseFile(importPath string, file *ast.File) (*model.Package, error) {130	allImports, dotImports := importsOfFile(file)131	// Don't stomp imports provided by -imports. Those should take precedence.132	for pkg, path := range allImports {133		if _, ok := p.imports[pkg]; !ok {134			p.imports[pkg] = path135		}136	}137	// Add imports from auxiliary files, which might be needed for embedded interfaces.138	// Don't stomp any other imports.139	for _, f := range p.auxFiles {140		auxImports, _ := importsOfFile(f)141		for pkg, path := range auxImports {142			if _, ok := p.imports[pkg]; !ok {143				p.imports[pkg] = path144			}145		}146	}147	var is []*model.Interface148	for ni := range iterInterfaces(file) {149		i, err := p.parseInterface(ni.name.String(), importPath, ni.it)150		if err != nil {151			return nil, err152		}153		is = append(is, i)154	}155	return &model.Package{156		Name:       file.Name.String(),157		Interfaces: is,158		DotImports: dotImports,159	}, nil160}161// parsePackage loads package specified by path, parses it and populates162// corresponding imports and importedInterfaces into the fileParser.163func (p *fileParser) parsePackage(path string) error {164	var pkgs map[string]*ast.Package165	if imp, err := build.Import(path, p.srcDir, build.FindOnly); err != nil {166		return err167	} else if pkgs, err = parser.ParseDir(p.fileSet, imp.Dir, nil, 0); err != nil {168		return err169	}170	for _, pkg := range pkgs {171		file := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates|ast.FilterUnassociatedComments|ast.FilterImportDuplicates)172		if _, ok := p.importedInterfaces[path]; !ok {173			p.importedInterfaces[path] = make(map[string]*ast.InterfaceType)174		}175		for ni := range iterInterfaces(file) {176			p.importedInterfaces[path][ni.name.Name] = ni.it177		}178		imports, _ := importsOfFile(file)179		for pkgName, pkgPath := range imports {180			if _, ok := p.imports[pkgName]; !ok {181				p.imports[pkgName] = pkgPath182			}183		}184	}185	return nil186}187func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*model.Interface, error) {188	intf := &model.Interface{Name: name}189	for _, field := range it.Methods.List {190		switch v := field.Type.(type) {191		case *ast.FuncType:192			if nn := len(field.Names); nn != 1 {193				return nil, fmt.Errorf("expected one name for interface %v, got %d", intf.Name, nn)194			}195			m := &model.Method{196				Name: field.Names[0].String(),197			}198			var err error199			m.In, m.Variadic, m.Out, err = p.parseFunc(pkg, v)200			if err != nil {201				return nil, err202			}203			intf.Methods = append(intf.Methods, m)204		case *ast.Ident:205			// Embedded interface in this package.206			ei := p.auxInterfaces[pkg][v.String()]207			if ei == nil {208				if ei = p.importedInterfaces[pkg][v.String()]; ei == nil {209					return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String())210				}211			}212			eintf, err := p.parseInterface(v.String(), pkg, ei)213			if err != nil {214				return nil, err215			}216			// Copy the methods.217			// TODO: apply shadowing rules.218			for _, m := range eintf.Methods {219				intf.Methods = append(intf.Methods, m)220			}221		case *ast.SelectorExpr:222			// Embedded interface in another package.223			fpkg, sel := v.X.(*ast.Ident).String(), v.Sel.String()224			epkg, ok := p.imports[fpkg]225			if !ok {226				return nil, p.errorf(v.X.Pos(), "unknown package %s", fpkg)227			}228			ei := p.auxInterfaces[fpkg][sel]229			if ei == nil {230				fpkg = epkg231				if _, ok = p.importedInterfaces[epkg]; !ok {232					if err := p.parsePackage(epkg); err != nil {233						return nil, p.errorf(v.Pos(), "could not parse package %s: %v", fpkg, err)234					}235				}236				if ei = p.importedInterfaces[epkg][sel]; ei == nil {237					return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", fpkg, sel)238				}239			}240			eintf, err := p.parseInterface(sel, fpkg, ei)241			if err != nil {242				return nil, err243			}244			// Copy the methods.245			// TODO: apply shadowing rules.246			for _, m := range eintf.Methods {247				intf.Methods = append(intf.Methods, m)248			}249		default:250			return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type)251		}252	}253	return intf, nil254}255func (p *fileParser) parseFunc(pkg string, f *ast.FuncType) (in []*model.Parameter, variadic *model.Parameter, out []*model.Parameter, err error) {256	if f.Params != nil {257		regParams := f.Params.List258		if isVariadic(f) {259			n := len(regParams)260			varParams := regParams[n-1:]261			regParams = regParams[:n-1]262			vp, err := p.parseFieldList(pkg, varParams)263			if err != nil {264				return nil, nil, nil, p.errorf(varParams[0].Pos(), "failed parsing variadic argument: %v", err)265			}266			variadic = vp[0]267		}268		in, err = p.parseFieldList(pkg, regParams)269		if err != nil {270			return nil, nil, nil, p.errorf(f.Pos(), "failed parsing arguments: %v", err)271		}272	}273	if f.Results != nil {274		out, err = p.parseFieldList(pkg, f.Results.List)275		if err != nil {276			return nil, nil, nil, p.errorf(f.Pos(), "failed parsing returns: %v", err)277		}278	}279	return280}281func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field) ([]*model.Parameter, error) {282	nf := 0283	for _, f := range fields {284		nn := len(f.Names)285		if nn == 0 {286			nn = 1 // anonymous parameter287		}288		nf += nn289	}290	if nf == 0 {291		return nil, nil292	}293	ps := make([]*model.Parameter, nf)294	i := 0 // destination index295	for _, f := range fields {296		t, err := p.parseType(pkg, f.Type)297		if err != nil {298			return nil, err299		}300		if len(f.Names) == 0 {301			// anonymous arg302			ps[i] = &model.Parameter{Type: t}303			i++304			continue305		}306		for _, name := range f.Names {307			ps[i] = &model.Parameter{Name: name.Name, Type: t}308			i++309		}310	}311	return ps, nil312}313func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) {314	switch v := typ.(type) {315	case *ast.ArrayType:316		ln := -1317		if v.Len != nil {318			x, err := strconv.Atoi(v.Len.(*ast.BasicLit).Value)319			if err != nil {320				return nil, p.errorf(v.Len.Pos(), "bad array size: %v", err)321			}322			ln = x323		}324		t, err := p.parseType(pkg, v.Elt)325		if err != nil {326			return nil, err327		}328		return &model.ArrayType{Len: ln, Type: t}, nil329	case *ast.ChanType:330		t, err := p.parseType(pkg, v.Value)331		if err != nil {332			return nil, err333		}334		var dir model.ChanDir335		if v.Dir == ast.SEND {336			dir = model.SendDir337		}338		if v.Dir == ast.RECV {339			dir = model.RecvDir340		}341		return &model.ChanType{Dir: dir, Type: t}, nil342	case *ast.Ellipsis:343		// assume we're parsing a variadic argument344		return p.parseType(pkg, v.Elt)345	case *ast.FuncType:346		in, variadic, out, err := p.parseFunc(pkg, v)347		if err != nil {348			return nil, err349		}350		return &model.FuncType{In: in, Out: out, Variadic: variadic}, nil351	case *ast.Ident:352		if v.IsExported() {353			// `pkg` may be an aliased imported pkg354			// if so, patch the import w/ the fully qualified import355			maybeImportedPkg, ok := p.imports[pkg]356			if ok {357				pkg = maybeImportedPkg358			}359			// assume type in this package360			return &model.NamedType{Package: pkg, Type: v.Name}, nil361		} else {362			// assume predeclared type363			return model.PredeclaredType(v.Name), nil364		}365	case *ast.InterfaceType:366		if v.Methods != nil && len(v.Methods.List) > 0 {367			return nil, p.errorf(v.Pos(), "can't handle non-empty unnamed interface types")368		}369		return model.PredeclaredType("interface{}"), nil370	case *ast.MapType:371		key, err := p.parseType(pkg, v.Key)372		if err != nil {373			return nil, err374		}375		value, err := p.parseType(pkg, v.Value)376		if err != nil {377			return nil, err378		}379		return &model.MapType{Key: key, Value: value}, nil380	case *ast.SelectorExpr:381		pkgName := v.X.(*ast.Ident).String()382		pkg, ok := p.imports[pkgName]383		if !ok {384			return nil, p.errorf(v.Pos(), "unknown package %q", pkgName)385		}386		return &model.NamedType{Package: pkg, Type: v.Sel.String()}, nil387	case *ast.StarExpr:388		t, err := p.parseType(pkg, v.X)389		if err != nil {390			return nil, err391		}392		return &model.PointerType{Type: t}, nil393	case *ast.StructType:394		if v.Fields != nil && len(v.Fields.List) > 0 {395			return nil, p.errorf(v.Pos(), "can't handle non-empty unnamed struct types")396		}397		return model.PredeclaredType("struct{}"), nil398	}399	return nil, fmt.Errorf("don't know how to parse type %T", typ)400}401// importsOfFile returns a map of package name to import path402// of the imports in file.403func importsOfFile(file *ast.File) (normalImports map[string]string, dotImports []string) {404	normalImports = make(map[string]string)405	dotImports = make([]string, 0)406	for _, is := range file.Imports {407		var pkgName string408		importPath := is.Path.Value[1 : len(is.Path.Value)-1] // remove quotes409		if is.Name != nil {410			// Named imports are always certain.411			if is.Name.Name == "_" {412				continue413			}414			pkgName = is.Name.Name415		} else {416			pkg, err := build.Import(importPath, "", 0)417			if err != nil {418				// Fallback to import path suffix. Note that this is uncertain.419				_, last := path.Split(importPath)420				// If the last path component has dots, the first dot-delimited421				// field is used as the name.422				pkgName = strings.SplitN(last, ".", 2)[0]423			} else {424				pkgName = pkg.Name425			}426		}427		if pkgName == "." {428			dotImports = append(dotImports, importPath)429		} else {430			if _, ok := normalImports[pkgName]; ok {431				log.Fatalf("imported package collision: %q imported twice", pkgName)432			}433			normalImports[pkgName] = importPath434		}435	}436	return437}438type namedInterface struct {439	name *ast.Ident440	it   *ast.InterfaceType441}442// Create an iterator over all interfaces in file.443func iterInterfaces(file *ast.File) <-chan namedInterface {444	ch := make(chan namedInterface)445	go func() {446		for _, decl := range file.Decls {447			gd, ok := decl.(*ast.GenDecl)...

Full Screen

Full Screen

execute_test.go

Source:execute_test.go Github

copy

Full Screen

1package execute2/*func TestSMTOk(t *testing.T) {3	test := `(declare-fun imports_fl3_vault_value_0 () Real)4	(declare-fun imports_fl3_vault_value_1 () Real)5	(declare-fun imports_fl3_vault_value_2 () Real)(assert (= imports_fl3_vault_value_0 30.0))6	(assert (= imports_fl3_vault_value_1 (+ imports_fl3_vault_value_0 10.0)))7	(assert (= imports_fl3_vault_value_2 (+ imports_fl3_vault_value_1 10.0)))8	`9	model := prepTest(test, make(map[string][]float64))10	response, err := model.Check()11	if err != nil {12		t.Fatalf("SMT Solver failed on valid expression. got=%s", err)13	}14	if !response {15		t.Fatalf("SMT Solver failed on valid expression.")16	}17	solution, err := model.Solve()18	if err != nil {19		t.Fatalf("SMT Solver failed to provide solution. got=%s", err)20	}21	if solution["imports_fl3_vault_value"] == nil {22		t.Fatal("SMT Solver failed to provide solution.")23	}24	got := solution["imports_fl3_vault_value"].(*FloatTrace).Get()25	expected := map[int64]float64{0: 30.0, 1: 40.0, 2: 50.0}26	if got[0] != expected[0] {27		t.Fatalf("SMT Solver solution not expected. want=%f got=%f", expected[0], got[0])28	}29}30func TestProbability(t *testing.T) {31	test := `(declare-fun imports_fl3_vault_value_0 () Real)32	(declare-fun imports_fl3_vault_value_1 () Real)33	(declare-fun imports_fl3_vault_value_2 () Real)(assert (= imports_fl3_vault_value_0 30.0))34	(assert (= imports_fl3_vault_value_1 (+ imports_fl3_vault_value_0 10.0)))35	(assert (= imports_fl3_vault_value_2 (+ imports_fl3_vault_value_1 10.0)))36	`37	uncertains := make(map[string][]float64)38	uncertains["imports_fl3_vault_value"] = []float64{30.0, 5}39	model := prepTest(test, uncertains)40	model.Check()41	solution, _ := model.Solve()42	filter := model.Filter(solution)43	got := filter["imports_fl3_vault_value"].(*FloatTrace).GetWeights()44	expected := map[int64]float64{0: 0.07978845608028654, 1: 0.010798193302637605, 2: 2.6766045152977058e-05}45	if got[0] != expected[0] {46		t.Fatalf("Probability distribution not weighting correctly. want=%f got=%f", expected[0], got[0])47	}48}49func prepTest(smt string, uncertains map[string][]float64) *ModelChecker {50	ex := NewModelChecker("z3")51	ex.LoadModel(smt, uncertains)52	return ex53}*/...

Full Screen

Full Screen

Imports

Using AI Code Generation

copy

Full Screen

1import "model"2func main() {3    model.Imports()4}5import "model"6func main() {7    model.Imports()8}9import "model"10func main() {11    model.Imports()12}13import "model"14func main() {15    model.Imports()16}17import "model"18func main() {19    model.Imports()20}21import "model"22func main() {23    model.Imports()24}25import "model"26func main() {27    model.Imports()28}29import "model"30func main() {31    model.Imports()32}33import "model"34func main() {35    model.Imports()36}37import "model"38func main() {39    model.Imports()40}41import "model"42func main() {43    model.Imports()44}45import "model"46func main() {47    model.Imports()48}

Full Screen

Full Screen

Imports

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	fmt.Println("Hello, World!")4	fmt.Println(m.Imports())5}6type Model struct {7}8func (m *Model) Imports() []string {9	return []string{"fmt", "model"}10}

Full Screen

Full Screen

Imports

Using AI Code Generation

copy

Full Screen

1import ( 2func main(){3	fmt.Println(model.Imports())4}5import "fmt"6func Imports() string{7	return fmt.Sprintf("Hello World")8}9import "testing"10func TestImports(t *testing.T){11	if Imports() != "Hello World"{12		t.Error("Unexpected output")13	}14}15--- PASS: TestImports (0.00s)

Full Screen

Full Screen

Imports

Using AI Code Generation

copy

Full Screen

1import com.aspose.words.ImportFormatMode;2import com.aspose.words.NodeImporter;3import com.aspose.words.NodeType;4import com.aspose.words.Section;5import com.aspose.words.Document;6import com.aspose.words.DocumentBuilder;7import com.aspose.words.Paragraph;8import com.aspose.words.Run;9import com.aspose.words.Section;10import com.aspose.words.Body;11import com.aspose.words.Node;12import com.aspose.words.NodeCollection;13import com.aspose.words.Document;14import com.aspose.words.DocumentBuilder;15import com.aspose.words.Paragraph;16import com.aspose.words.Run;17import com.aspose.words.Section;18import com.aspose.words.Body;19import com.aspose.words.Node;20import com.aspose.words.NodeCollection;21import com.aspose.words.Document;22import com.aspose.words.DocumentBuilder;23import com.aspose.words.Paragraph;24import com.aspose.words.Run;25import com.aspose.words.Section;26import com.aspose.words.Body;27import com.aspose.words.Node;28import com.aspose.words.NodeCollection;29import com.aspose.words.Document;30import com.aspose.words.DocumentBuilder;31import com.aspose.words.Paragraph;32import com.aspose.words.Run;33import com.aspose.words.Section;34import com.aspose.words.Body;35import com.aspose.words.Node;36import com.aspose.words.NodeCollection;37import com.aspose.words.Document;38import com.aspose.words.DocumentBuilder;39import com.aspose.words.Paragraph;40import com.aspose.words.Run;

Full Screen

Full Screen

Imports

Using AI Code Generation

copy

Full Screen

1var importModel = new Imports();2var imports = importModel.Imports();3foreach (var import in imports)4{5    Console.WriteLine(import);6}7var importModel = new Imports();8var imports = importModel.Imports();9foreach (var import in imports)10{11    Console.WriteLine(import);12}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful