How to use generateTestFiles method of generators Package

Best Ginkgo code snippet using generators.generateTestFiles

Run Ginkgo automation tests on LambdaTest cloud grid

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

generate_command.go

Source: generate_command.go Github

copy
1package generators
2
3import (
4	"bytes"
5	"fmt"
6	"os"
7	"path/filepath"
8	"strconv"
9	"strings"
10	"text/template"
11
12	sprig "github.com/go-task/slim-sprig"
13	"github.com/onsi/ginkgo/v2/ginkgo/command"
14	"github.com/onsi/ginkgo/v2/ginkgo/internal"
15	"github.com/onsi/ginkgo/v2/types"
16)
17
18func BuildGenerateCommand() command.Command {
19	conf := GeneratorsConfig{}
20	flags, err := types.NewGinkgoFlagSet(
21		types.GinkgoFlags{
22			{Name: "agouti", KeyPath: "Agouti",
23				Usage: "If set, generate will create a test file for writing Agouti tests"},
24			{Name: "nodot", KeyPath: "NoDot",
25				Usage: "If set, generate will create a test file that does not dot-import ginkgo and gomega"},
26			{Name: "internal", KeyPath: "Internal",
27				Usage: "If set, generate will create a test file that uses the regular package name (i.e. `package X`, not `package X_test`)"},
28			{Name: "template", KeyPath: "CustomTemplate",
29				UsageArgument: "template-file",
30				Usage:         "If specified, generate will use the contents of the file passed as the test file template"},
31		},
32		&conf,
33		types.GinkgoFlagSections{},
34	)
35
36	if err != nil {
37		panic(err)
38	}
39
40	return command.Command{
41		Name:     "generate",
42		Usage:    "ginkgo generate <filename(s)>",
43		ShortDoc: "Generate a test file named <filename>_test.go",
44		Documentation: `If the optional <filename> argument is omitted, a file named after the package in the current directory will be created.
45
46You can pass multiple <filename(s)> to generate multiple files simultaneously.  The resulting files are named <filename>_test.go.
47
48You can also pass a <filename> of the form "file.go" and generate will emit "file_test.go".`,
49		DocLink: "generators",
50		Flags:   flags,
51		Command: func(args []string, _ []string) {
52			generateTestFiles(conf, args)
53		},
54	}
55}
56
57type specData struct {
58	Package           string
59	Subject           string
60	PackageImportPath string
61	ImportPackage     bool
62
63	GinkgoImport  string
64	GomegaImport  string
65	GinkgoPackage string
66	GomegaPackage string
67}
68
69func generateTestFiles(conf GeneratorsConfig, args []string) {
70	subjects := args
71	if len(subjects) == 0 {
72		subjects = []string{""}
73	}
74	for _, subject := range subjects {
75		generateTestFileForSubject(subject, conf)
76	}
77}
78
79func generateTestFileForSubject(subject string, conf GeneratorsConfig) {
80	packageName, specFilePrefix, formattedName := getPackageAndFormattedName()
81	if subject != "" {
82		specFilePrefix = formatSubject(subject)
83		formattedName = prettifyName(specFilePrefix)
84	}
85
86	if conf.Internal {
87		specFilePrefix = specFilePrefix + "_internal"
88	}
89
90	data := specData{
91		Package:           determinePackageName(packageName, conf.Internal),
92		Subject:           formattedName,
93		PackageImportPath: getPackageImportPath(),
94		ImportPackage:     !conf.Internal,
95
96		GinkgoImport:  `. "github.com/onsi/ginkgo/v2"`,
97		GomegaImport:  `. "github.com/onsi/gomega"`,
98		GinkgoPackage: "",
99		GomegaPackage: "",
100	}
101
102	if conf.NoDot {
103		data.GinkgoImport = `"github.com/onsi/ginkgo/v2"`
104		data.GomegaImport = `"github.com/onsi/gomega"`
105		data.GinkgoPackage = `ginkgo.`
106		data.GomegaPackage = `gomega.`
107	}
108
109	targetFile := fmt.Sprintf("%s_test.go", specFilePrefix)
110	if internal.FileExists(targetFile) {
111		command.AbortWith("{{bold}}%s{{/}} already exists", targetFile)
112	} else {
113		fmt.Printf("Generating ginkgo test for %s in:\n  %s\n", data.Subject, targetFile)
114	}
115
116	f, err := os.Create(targetFile)
117	command.AbortIfError("Failed to create test file:", err)
118	defer f.Close()
119
120	var templateText string
121	if conf.CustomTemplate != "" {
122		tpl, err := os.ReadFile(conf.CustomTemplate)
123		command.AbortIfError("Failed to read custom template file:", err)
124		templateText = string(tpl)
125	} else if conf.Agouti {
126		templateText = agoutiSpecText
127	} else {
128		templateText = specText
129	}
130
131	specTemplate, err := template.New("spec").Funcs(sprig.TxtFuncMap()).Parse(templateText)
132	command.AbortIfError("Failed to read parse test template:", err)
133
134	specTemplate.Execute(f, data)
135	internal.GoFmt(targetFile)
136}
137
138func formatSubject(name string) string {
139	name = strings.ReplaceAll(name, "-", "_")
140	name = strings.ReplaceAll(name, " ", "_")
141	name = strings.Split(name, ".go")[0]
142	name = strings.Split(name, "_test")[0]
143	return name
144}
145
146// moduleName returns module name from go.mod from given module root directory
147func moduleName(modRoot string) string {
148	modFile, err := os.Open(filepath.Join(modRoot, "go.mod"))
149	if err != nil {
150		return ""
151	}
152
153	mod := make([]byte, 128)
154	_, err = modFile.Read(mod)
155	if err != nil {
156		return ""
157	}
158
159	slashSlash := []byte("//")
160	moduleStr := []byte("module")
161
162	for len(mod) > 0 {
163		line := mod
164		mod = nil
165		if i := bytes.IndexByte(line, '\n'); i >= 0 {
166			line, mod = line[:i], line[i+1:]
167		}
168		if i := bytes.Index(line, slashSlash); i >= 0 {
169			line = line[:i]
170		}
171		line = bytes.TrimSpace(line)
172		if !bytes.HasPrefix(line, moduleStr) {
173			continue
174		}
175		line = line[len(moduleStr):]
176		n := len(line)
177		line = bytes.TrimSpace(line)
178		if len(line) == n || len(line) == 0 {
179			continue
180		}
181
182		if line[0] == '"' || line[0] == '`' {
183			p, err := strconv.Unquote(string(line))
184			if err != nil {
185				return "" // malformed quoted string or multiline module path
186			}
187			return p
188		}
189
190		return string(line)
191	}
192
193	return "" // missing module path
194}
195
196func findModuleRoot(dir string) (root string) {
197	dir = filepath.Clean(dir)
198
199	// Look for enclosing go.mod.
200	for {
201		if fi, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil && !fi.IsDir() {
202			return dir
203		}
204		d := filepath.Dir(dir)
205		if d == dir {
206			break
207		}
208		dir = d
209	}
210	return ""
211}
212
213func getPackageImportPath() string {
214	workingDir, err := os.Getwd()
215	if err != nil {
216		panic(err.Error())
217	}
218
219	sep := string(filepath.Separator)
220
221	// Try go.mod file first
222	modRoot := findModuleRoot(workingDir)
223	if modRoot != "" {
224		modName := moduleName(modRoot)
225		if modName != "" {
226			cd := strings.ReplaceAll(workingDir, modRoot, "")
227			cd = strings.ReplaceAll(cd, sep, "/")
228			return modName + cd
229		}
230	}
231
232	// Fallback to GOPATH structure
233	paths := strings.Split(workingDir, sep+"src"+sep)
234	if len(paths) == 1 {
235		fmt.Printf("\nCouldn't identify package import path.\n\n\tginkgo generate\n\nMust be run within a package directory under $GOPATH/src/...\nYou're going to have to change UNKNOWN_PACKAGE_PATH in the generated file...\n\n")
236		return "UNKNOWN_PACKAGE_PATH"
237	}
238	return filepath.ToSlash(paths[len(paths)-1])
239}
240
Full Screen

generator.go

Source: generator.go Github

copy
1package usecase
2
3import (
4	"generator/entity"
5	"generator/generators"
6	"github.com/iancoleman/strcase"
7	log "github.com/sirupsen/logrus"
8	"os"
9	"path/filepath"
10	"strconv"
11	"time"
12)
13
14func GenerateEntity(packageInfo entity.PackageStruct, serviceName string, listOfStruct []entity.Struct, replaceFile bool) {
15
16	servicePath := filepath.FromSlash("./../" + serviceName)
17
18	for _, l := range listOfStruct {
19		if l.Type == entity.TypeMain {
20
21			createFunction := false
22			updateFunction := false
23
24			// Определяем нужны ли функиции для создания и обновления даннх
25			for _, tempStruct := range listOfStruct {
26				if tempStruct.Name == "Create"+l.Name+"Request" {
27					createFunction = true
28				}
29				if tempStruct.Name == "Update"+l.Name+"Request" {
30					updateFunction = true
31				}
32			}
33
34			code, err := generators.GenerateEntity(l, packageInfo, createFunction, updateFunction)
35			if err != nil {
36				log.Error(err)
37				continue
38			}
39
40			saveFilePath := servicePath + "/entity/" + strcase.ToSnake(l.Name) + ".go"
41			if replaceFile {
42				err = FileSave(saveFilePath, code)
43				if err == nil {
44					log.WithField("File", saveFilePath).Println("Entity created")
45				}
46			}
47		}
48	}
49}
50
51func GenerateServiceFiles(packageInfo entity.PackageStruct, protoInterface entity.ProtoInterface, serviceName string, replaceFile bool) {
52	var err error
53
54	servicePath := filepath.FromSlash("./../" + serviceName)
55
56	for _, pi := range protoInterface.Methods {
57		// Generate file
58
59		code := ""
60		name, action := pi.NameInterface()
61
62		saveFilePath := servicePath + "/service/" + strcase.ToSnake(name) + "_" + strcase.ToSnake(action) + ".go"
63
64		// Если не удалось определить экшн то переходим к следующему методу
65		if len(action) == 0 {
66			continue
67		}
68
69		code, err = generators.GenerateServiceCode(pi, packageInfo, action)
70
71		if err != nil {
72			log.Error(err)
73			continue
74		}
75		if replaceFile {
76			err := FileSave(saveFilePath, code)
77
78			if err == nil {
79				log.WithField("File", saveFilePath).Println("Service file created ", strcase.ToSnake(name)+"_"+strcase.ToSnake(action)+".go")
80			}
81		}
82
83	}
84}
85
86func GenerateTestFiles(packageInfo entity.PackageStruct, protoInterface entity.ProtoInterface, serviceName string, replaceFile bool) {
87	var err error
88
89	servicePath := filepath.FromSlash("./../" + serviceName)
90
91	for _, pi := range protoInterface.Methods {
92		// Generate file
93
94		name, action := pi.NameInterface()
95
96		// Если не удалось определить экшн то переходим к следующему методу
97		if len(action) == 0 {
98			continue
99		}
100
101		// Generate tests
102
103		saveFileTestPath := servicePath + "/service/" + strcase.ToSnake(name) + "_" + strcase.ToSnake(action) + "_test.go"
104		codeTest := ""
105		switch action {
106		case "Create":
107			codeTest, err = generators.GenerateTestCreateCode(pi, packageInfo)
108		case "Update":
109			codeTest, err = generators.GenerateTestUpdateCode(pi, packageInfo)
110		case "Delete":
111			codeTest, err = generators.GenerateTestDeleteCode(pi, packageInfo)
112		case "Get":
113			codeTest, err = generators.GenerateTestGetCode(pi, packageInfo)
114		case "List":
115			codeTest, err = generators.GenerateTestListCode(pi, packageInfo)
116
117		}
118
119		if len(codeTest) != 0 {
120
121			if err != nil {
122				log.Error(err)
123				continue
124			}
125			if replaceFile {
126				err = FileSave(saveFileTestPath, codeTest)
127
128				if err == nil {
129					log.WithField("File", saveFileTestPath).Println("Test file created ", strcase.ToSnake(name)+"_"+strcase.ToSnake(action)+".go")
130				}
131			}
132		}
133
134	}
135}
136
137func GenerateMigrationFile(packageInfo entity.PackageStruct, serviceName string, listOfStruct []entity.Struct, replaceFile bool) {
138	servicePath := filepath.FromSlash("./../" + serviceName)
139
140	migration := ""
141
142	for _, l := range listOfStruct {
143		if l.Type == entity.TypeMain {
144			code, err := generators.GenerateMigration(l, packageInfo)
145			if err != nil {
146				log.Error(err)
147				continue
148			}
149			migration += code
150		}
151	}
152	now := time.Now()
153
154	saveFilePath := servicePath + "/migrations/" + strconv.Itoa(int(now.Unix())) + "_init.up.sql"
155	if replaceFile {
156		err := FileSave(saveFilePath, migration)
157		if err == nil {
158			log.WithField("File", saveFilePath).Println("Entity created")
159		}
160	}
161}
162
163func GenerateGeneralFilesIfNotExist(packageInfo entity.PackageStruct, serviceName string, listOfStruct []entity.Struct, replaceFile bool) {
164
165	type GeneralFile struct {
166		FileName string
167		Replace  bool
168	}
169
170	servicePath := filepath.FromSlash("./../" + serviceName)
171
172	listFiles := []GeneralFile{
173		{".gitignore", false},
174		{"db.go", false},
175		{"envopt.json", false},
176		{"envopt_test.json", false},
177		{"go.mod", false},
178		{"go.sum", false},
179		{"main.go", false},
180		{"server.go", false},
181		{"service/service.go", false},
182		{"service/service_test.go", true},
183		//{"prometheus.go",false},
184
185	}
186
187	dbList := []string{}
188	for _, l := range listOfStruct {
189		if l.Type == entity.TypeMain {
190			dbList = append(dbList, strcase.ToSnake(l.Name))
191		}
192	}
193
194	for _, l := range listFiles {
195		saveFilePath := servicePath + "/" + strcase.ToSnake(l.FileName)
196
197		// Проверка на то что файл не существует
198		if !l.Replace {
199			if _, err := os.Stat(saveFilePath); err == nil {
200				continue
201			}
202		}
203
204		code, err := generators.GenerateGeneral(l.FileName, packageInfo, dbList)
205		if err != nil {
206			log.Error(err)
207			continue
208		}
209
210		if replaceFile {
211			err = FileSave(saveFilePath, code)
212			if err == nil {
213				log.WithField("File", saveFilePath).Println("Entity created")
214			}
215		}
216
217	}
218
219}
220
221func GeneratePathProject(serviceName string) {
222	servicePath := filepath.FromSlash("./../" + serviceName)
223	pathList := []string{
224		"entity",
225		"migrations",
226		"service",
227	}
228
229	for _, path := range pathList {
230
231		p := servicePath + "/" + path
232
233		if _, err := os.Stat(p); os.IsNotExist(err) {
234			os.Mkdir(p, os.ModePerm)
235		}
236	}
237
238}
239
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger generateTestFiles code on LambdaTest Cloud Grid

Execute automation tests with generateTestFiles on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)