Example #1
0
func importPackage(dir string) *importData {
	installPackage()

	buildPkg, err := build.ImportDir(dir, 0)
	if err != nil {
		log.Fatalf(`build.ImportDir(%q, 0): %s`, dir, err)
	}

	// load package
	var conf loader.Config
	conf.Import(buildPkg.ImportPath)
	prog, err := conf.Load()
	if err != nil {
		log.Fatalf("conf.Load(): %s", err)
	}

	// get our single package
	packages := make([]string, 0, len(prog.Imported))
	for p := range prog.Imported {
		packages = append(packages, p)
	}
	if len(packages) != 1 {
		log.Fatalf("expected 1 package, got %d: %v", len(packages), packages)
	}
	pack := prog.Imported[packages[0]].Pkg

	// TODO compare pack and buildPkg

	tests := extractTestFunctions(pack.Scope())

	return &importData{
		PackageName:       pack.Name(),
		PackageImportPath: buildPkg.ImportPath,
		PackageDir:        buildPkg.Dir,
		Tests:             tests,
	}
}
Example #2
0
package cmd

import (
	"github.com/spf13/cobra"

	"github.com/go-gophers/gophers/utils/log"
)

var testCmd = &cobra.Command{
	Use:   "test",
	Short: "Generate main file to run tests.",

	Run: func(cmd *cobra.Command, args []string) {
		log.Default.Debug = debugF
		if len(args) != 0 {
			log.Fatalf("expected 0 arguments, got %d", len(args))
		}

		output, _ := cmd.Flags().GetString("output")
		testPackage(WD, output)
	},
}

func init() {
	RootCmd.AddCommand(testCmd)

	testCmd.Flags().StringP("output", "o", "main-test.go", "output file name")
}

func testPackage(dir string, output string) {
	data := importPackage(dir)