func main() { flag.Parse() projectInit.SetWorkingDir(*workingDir) initPackageFlags() validGaugeProject := true err := config.SetProjectRoot(flag.Args()) if err != nil { validGaugeProject = false } env.LoadEnv(*currentEnv) logger.Initialize(*logLevel) if *gaugeVersion { printVersion() } else if *initialize != "" { projectInit.InitializeProject(*initialize) } else if *installZip != "" && *installPlugin != "" { install.InstallPluginZip(*installZip, *installPlugin) } else if *installPlugin != "" { install.DownloadAndInstallPlugin(*installPlugin, *pluginVersion, "Successfully installed plugin => %s") } else if *uninstallPlugin != "" { install.UninstallPlugin(*uninstallPlugin, *pluginVersion) } else if *installAll { install.InstallAllPlugins() } else if *update != "" { install.DownloadAndInstallPlugin(*update, *pluginVersion, "Successfully updated plugin => %s") } else if *updateAll { install.UpdatePlugins() } else if *checkUpdates { install.PrintUpdateInfoWithDetails() } else if *addPlugin != "" { install.AddPluginToProject(*addPlugin, *pluginArgs) } else if *listTemplates { projectInit.ListTemplates() } else if flag.NFlag() == 0 && len(flag.Args()) == 0 { printUsage() os.Exit(0) } else if validGaugeProject { if *refactorSteps != "" { startChan := api.StartAPI() if len(flag.Args()) != 1 { logger.Error("flag needs two arguments: --refactor\n.Usage : gauge --refactor {old step} {new step}") os.Exit(1) } refactor.RefactorSteps(*refactorSteps, flag.Args()[0], startChan) } else if *daemonize { api.RunInBackground(*apiPort) } else if *specFilesToFormat != "" { formatter.FormatSpecFilesIn(*specFilesToFormat) } else if *validate { execution.Validate(flag.Args()) } else { exitCode := execution.ExecuteSpecs(flag.Args()) os.Exit(exitCode) } } else { logger.Error(err.Error()) os.Exit(1) } }
func printValidationFailures(validationErrors validationErrors) { logger.Error("Validation failed. The following steps have errors") for _, stepValidationErrors := range validationErrors { for _, stepValidationError := range stepValidationErrors { s := stepValidationError.step logger.Error("%s:%d: %s. %s", stepValidationError.fileName, s.LineNo, stepValidationError.message, s.LineText) } } }
func (self *parallelInfo) isValid() bool { if self.numberOfStreams < 1 { logger.Error("Invalid input(%s) to --n flag.", strconv.Itoa(self.numberOfStreams)) return false } currentStrategy := strings.ToLower(Strategy) if currentStrategy != LAZY && currentStrategy != EAGER { logger.Error("Invalid input(%s) to --strategy flag.", Strategy) return false } return true }
func addPluginToTheProject(pluginName string, pluginArgs map[string]string, manifest *manifest.Manifest) error { if !plugin.IsPluginInstalled(pluginName, pluginArgs["version"]) { logger.Info("Plugin %s %s is not installed. Downloading the plugin.... \n", pluginName, pluginArgs["version"]) result := InstallPlugin(pluginName, pluginArgs["version"]) if !result.Success { logger.Error(result.getMessage()) } } pd, err := plugin.GetPluginDescriptor(pluginName, pluginArgs["version"]) if err != nil { return err } if plugin.IsPluginAdded(manifest, pd) { logger.Info("Plugin " + pd.Name + " is already added.") return nil } action := setupScope if err := plugin.SetEnvForPlugin(action, pd, manifest, pluginArgs); err != nil { return err } if _, err := plugin.StartPlugin(pd, action, true); err != nil { return err } manifest.Plugins = append(manifest.Plugins, pd.Id) return manifest.Save() }
func printExecutionStatus(suiteResult *result.SuiteResult, errMap *validationErrMaps) int { nSkippedScenarios := len(errMap.scenarioErrs) nSkippedSpecs := len(errMap.specErrs) nExecutedSpecs := len(suiteResult.SpecResults) - nSkippedSpecs nFailedSpecs := suiteResult.SpecsFailedCount nPassedSpecs := nExecutedSpecs - nFailedSpecs nExecutedScenarios := 0 nFailedScenarios := 0 nPassedScenarios := 0 for _, specResult := range suiteResult.SpecResults { nExecutedScenarios += specResult.ScenarioCount nFailedScenarios += specResult.ScenarioFailedCount } nExecutedScenarios -= nSkippedScenarios nPassedScenarios = nExecutedScenarios - nFailedScenarios logger.Info("Specifications:\t%d executed\t%d passed\t%d failed\t%d skipped", nExecutedSpecs, nPassedSpecs, nFailedSpecs, nSkippedSpecs) logger.Info("Scenarios:\t%d executed\t%d passed\t%d failed\t%d skipped", nExecutedScenarios, nPassedScenarios, nFailedScenarios, nSkippedScenarios) logger.Info("\nTotal time taken: %s", time.Millisecond*time.Duration(suiteResult.ExecutionTime)) for _, unhandledErr := range suiteResult.UnhandledErrors { logger.Error(unhandledErr.Error()) } exitCode := 0 if suiteResult.IsFailed || (nSkippedSpecs+nSkippedScenarios) > 0 { exitCode = 1 } return exitCode }
func DownloadAndInstallPlugin(plugin, version, messageFormat string) { err := downloadAndInstall(plugin, version, fmt.Sprintf(messageFormat, plugin)) if err != nil { logger.Error(err.Error()) os.Exit(1) } os.Exit(0) }
func (handler *Handler) killPlugin(pluginId string) { plugin := handler.pluginsMap[pluginId] logger.Debug("Killing Plugin %s %s\n", plugin.descriptor.Name, plugin.descriptor.Version) err := plugin.pluginCmd.Process.Kill() if err != nil { logger.Error("Failed to kill plugin %s %s. %s\n", plugin.descriptor.Name, plugin.descriptor.Version, err.Error()) } handler.removePlugin(pluginId) }
func (handler *Handler) NotifyPlugins(message *gauge_messages.Message) { for id, plugin := range handler.pluginsMap { err := plugin.sendMessage(message) if err != nil { logger.Error("Unable to connect to plugin %s %s. %s\n", plugin.descriptor.Name, plugin.descriptor.Version, err.Error()) handler.killPlugin(id) } } }
func UpdatePlugins() { var failedPlugin []string for _, pluginInfo := range plugin.GetPluginsInfo() { logger.Info("Updating plugin '%s'", pluginInfo.Name) err := downloadAndInstall(pluginInfo.Name, "", fmt.Sprintf("Successfully updated plugin => %s", pluginInfo.Name)) if err != nil { logger.Error(err.Error()) failedPlugin = append(failedPlugin, pluginInfo.Name) } fmt.Println() } if len(failedPlugin) > 0 { logger.Error("Failed to update '%s' plugins.", strings.Join(failedPlugin, ", ")) os.Exit(1) } logger.Info("Successfully updated all the plugins.") os.Exit(0) }
func getDataTableRows(rowCount int) indexRange { if TableRows == "" { return indexRange{start: 0, end: rowCount - 1} } indexes, err := getDataTableRowsRange(TableRows, rowCount) if err != nil { logger.Error("Table rows validation failed. %s\n", err.Error()) } return indexes }
func executeAndGetStatus(runner *runner.TestRunner, message *gauge_messages.Message) *gauge_messages.ProtoExecutionResult { response, err := conn.GetResponseForGaugeMessage(message, runner.Connection) if err != nil { return &gauge_messages.ProtoExecutionResult{Failed: proto.Bool(true), ErrorMessage: proto.String(err.Error())} } if response.GetMessageType() == gauge_messages.Message_ExecutionStatusResponse { executionResult := response.GetExecutionStatusResponse().GetExecutionResult() if executionResult == nil { errMsg := "ProtoExecutionResult obtained is nil" logger.Error(errMsg) return errorResult(errMsg) } return executionResult } errMsg := fmt.Sprintf("Expected ExecutionStatusResponse. Obtained: %s", response.GetMessageType()) logger.Error(errMsg) return errorResult(errMsg) }
func (e *specExecutor) createSkippedSpecResult(err error) *result.SpecResult { logger.Error(err.Error()) validationError := newValidationError(&gauge.Step{LineNo: e.specification.Heading.LineNo, LineText: e.specification.Heading.Value}, err.Error(), e.specification.FileName, nil) for _, scenario := range e.specification.Scenarios { e.errMap.scenarioErrs[scenario] = []*stepValidationError{validationError} } e.errMap.specErrs[e.specification] = []*stepValidationError{validationError} return e.getSkippedSpecResult() }
func (e *parallelSpecExecution) startSpecsExecution(specCollection *filter.SpecCollection, suiteResults chan *result.SuiteResult, reporter reporter.Reporter) { testRunner, err := runner.StartRunnerAndMakeConnection(e.manifest, reporter, make(chan bool)) if err != nil { logger.Error("Failed: " + err.Error()) logger.Debug("Skipping %s specifications", strconv.Itoa(len(specCollection.Specs))) suiteResults <- &result.SuiteResult{UnhandledErrors: []error{streamExecError{specsSkipped: specCollection.SpecNames(), message: fmt.Sprintf("Failed to start runner. %s", err.Error())}}} return } e.startSpecsExecutionWithRunner(specCollection, suiteResults, testRunner, reporter) }
func (e *parallelExecution) startStream(specStore *specStore, reporter reporter.Reporter, suiteResultChannel chan *result.SuiteResult) { defer e.wg.Done() testRunner, err := runner.StartRunnerAndMakeConnection(e.manifest, reporter, make(chan bool)) if err != nil { logger.Error("Failed to start runner. Reason: %s", err.Error()) suiteResultChannel <- &result.SuiteResult{UnhandledErrors: []error{fmt.Errorf("Failed to start runner. %s", err.Error())}} return } e.startSpecsExecutionWithRunner(specStore, suiteResultChannel, testRunner, reporter) }
func (e *parallelSpecExecution) startStream(specs *specList, reporter reporter.Reporter, suiteResultChannel chan *result.SuiteResult) { defer e.wg.Done() testRunner, err := runner.StartRunnerAndMakeConnection(e.manifest, reporter, make(chan bool)) if err != nil { logger.Error("Failed to start runner. Reason: %s", err.Error()) suiteResultChannel <- &result.SuiteResult{UnhandledErrors: []error{fmt.Errorf("Failed to start runner. %s", err.Error())}} return } simpleExecution := newSimpleExecution(&executionInfo{e.manifest, make([]*parser.Specification, 0), testRunner, e.pluginHandler, nil, reporter, e.errMaps}) result := simpleExecution.executeStream(specs) suiteResultChannel <- result testRunner.Kill() }
func CreateConceptsDictionary(shouldIgnoreErrors bool) (*ConceptDictionary, *ParseResult) { conceptFiles := util.FindConceptFilesIn(filepath.Join(config.ProjectRoot, common.SpecsDirectoryName)) conceptsDictionary := NewConceptDictionary() for _, conceptFile := range conceptFiles { if err := AddConcepts(conceptFile, conceptsDictionary); err != nil { if shouldIgnoreErrors { logger.ApiLog.Error("Concept parse failure: %s %s", conceptFile, err) continue } logger.Error(err.Error()) return nil, &ParseResult{ParseError: err, FileName: conceptFile} } } return conceptsDictionary, &ParseResult{Ok: true} }
func printRefactoringSummary(refactoringResult *refactoringResult) { exitCode := 0 if !refactoringResult.Success { exitCode = 1 for _, err := range refactoringResult.Errors { logger.Error("%s \n", err) } } for _, warning := range refactoringResult.warnings { logger.Warning("%s \n", warning) } logger.Info("%d specifications changed.\n", len(refactoringResult.specsChanged)) logger.Info("%d concepts changed.\n", len(refactoringResult.conceptsChanged)) logger.Info("%d files in code changed.\n", len(refactoringResult.runnerFilesChanged)) os.Exit(exitCode) }
func HandleParseResult(results ...*ParseResult) { var failed = false for _, result := range results { if !result.Ok { logger.Error(result.Error()) failed = true } if result.Warnings != nil { for _, warning := range result.Warnings { logger.Warning("%s : %v", result.FileName, warning) } } } if failed { os.Exit(1) } }
func addPluginToTheProject(pluginName string, pluginArgs map[string]string, manifest *manifest.Manifest) error { if !plugin.IsPluginInstalled(pluginName, pluginArgs["version"]) { logger.Info("Plugin %s %s is not installed. Downloading the plugin.... \n", pluginName, pluginArgs["version"]) result := InstallPlugin(pluginName, pluginArgs["version"]) if !result.Success { logger.Error(result.getMessage()) } } pd, err := plugin.GetPluginDescriptor(pluginName, pluginArgs["version"]) if err != nil { return err } if plugin.IsPluginAdded(manifest, pd) { return fmt.Errorf("Plugin %s is already added.", pd.Name) } manifest.Plugins = append(manifest.Plugins, pd.Id) return manifest.Save() }
func installPluginsFromManifest(manifest *manifest.Manifest) { pluginsMap := make(map[string]bool, 0) pluginsMap[manifest.Language] = true for _, plugin := range manifest.Plugins { pluginsMap[plugin] = false } for pluginName, isRunner := range pluginsMap { if !isCompatiblePluginInstalled(pluginName, "", isRunner) { logger.Info("Compatible version of plugin %s not found. Installing plugin %s...", pluginName, pluginName) installResult := InstallPlugin(pluginName, "") if installResult.Success { logger.Info("Successfully installed the plugin %s.", pluginName) } else { logger.Error("Failed to install the %s plugin.", pluginName) } } else { logger.Info("Plugin %s is already installed.", pluginName) } } }
func SaveFile(fileName string, content string, backup bool) { err := common.SaveFile(fileName, content, backup) if err != nil { logger.Error("Failed to refactor '%s': %s\n", fileName, err.Error()) } }
func main() { flag.Parse() projectInit.SetWorkingDir(*workingDir) initPackageFlags() validGaugeProject := true err := config.SetProjectRoot(flag.Args()) if err != nil { validGaugeProject = false } env.LoadEnv(true) logger.Initialize(*verbosity, *logLevel) if *gaugeVersion { version.PrintVersion() } else if *daemonize { if validGaugeProject { api.RunInBackground(*apiPort) } else { logger.Error(err.Error()) } } else if *specFilesToFormat != "" { if validGaugeProject { formatter.FormatSpecFilesIn(*specFilesToFormat) } else { logger.Error(err.Error()) } } else if *initialize != "" { projectInit.InitializeProject(*initialize) } else if *installZip != "" && *installPlugin != "" { install.InstallPluginZip(*installZip, *installPlugin) } else if *installPlugin != "" { install.DownloadAndInstallPlugin(*installPlugin, *pluginVersion, "Successfully installed plugin => %s") } else if *uninstallPlugin != "" { install.UninstallPlugin(*uninstallPlugin, *pluginVersion) } else if *installAll { install.InstallAllPlugins() } else if *update != "" { install.DownloadAndInstallPlugin(*update, *pluginVersion, "Successfully updated plugin => %s") } else if *updateAll { install.UpdatePlugins() } else if *checkUpdates { install.PrintUpdateInfoWithDetails() } else if *addPlugin != "" { install.AddPluginToProject(*addPlugin, *pluginArgs) } else if *refactorSteps != "" { if validGaugeProject { startChan := api.StartAPI() refactor.RefactorSteps(*refactorSteps, newStepName(), startChan) } else { logger.Error(err.Error()) } } else if *check { if validGaugeProject { execution.CheckSpecs(flag.Args()) } else { logger.Error(err.Error()) } } else { if len(flag.Args()) == 0 { printUsage() } if validGaugeProject { exitCode := execution.ExecuteSpecs(*parallel, flag.Args()) os.Exit(exitCode) } else { logger.Error(err.Error()) } } }
func handleUninstallFailure(err error, pluginName string) { logger.Error("%s plugin uninstallation failed", pluginName) logger.Fatalf(err.Error()) }