当前位置: 首页>>代码示例>>Golang>>正文


Golang evergreen.FindEvergreenHome函数代码示例

本文整理汇总了Golang中github.com/evergreen-ci/evergreen.FindEvergreenHome函数的典型用法代码示例。如果您正苦于以下问题:Golang FindEvergreenHome函数的具体用法?Golang FindEvergreenHome怎么用?Golang FindEvergreenHome使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了FindEvergreenHome函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestLocalScript

func TestLocalScript(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("shell command test doesn't make sense on windows")
	}

	Convey("When running local commands in script mode", t, func() {

		Convey("A multi-line script should run all lines", func() {

			stdout := &CacheLastWritten{}

			workingDir, err := filepath.Abs(evergreen.FindEvergreenHome())
			So(err, ShouldBeNil)

			command := &LocalCommand{
				CmdString:        "set -v\necho 'hi'\necho 'foo'\necho `pwd`",
				ScriptMode:       true,
				Stdout:           stdout,
				Stderr:           ioutil.Discard,
				WorkingDirectory: workingDir,
			}

			// run the command - the working directory should be as specified
			So(command.Run(), ShouldBeNil)

			reportedPwd := string(stdout.LastWritten)
			reportedPwd = reportedPwd[:len(reportedPwd)-1]
			reportedPwd, err = filepath.EvalSymlinks(reportedPwd)
			So(err, ShouldBeNil)
			So(reportedPwd, ShouldEqual, workingDir)
		})

	})
}
开发者ID:tychoish,项目名称:evergreen,代码行数:34,代码来源:local_command_test.go

示例2: TestLocalScript

func TestLocalScript(t *testing.T) {
	Convey("When running local commands in script mode", t, func() {

		Convey("A multi-line script should run all lines", func() {

			stdout := &CacheLastWritten{}

			evgHome := evergreen.FindEvergreenHome()
			workingDir := filepath.Join(evgHome, "command/testdata")

			command := &LocalCommand{
				CmdString:        "set -v\necho 'hi'\necho 'foo'\necho `pwd`",
				ScriptMode:       true,
				Stdout:           stdout,
				Stderr:           ioutil.Discard,
				WorkingDirectory: workingDir,
			}

			// run the command - the working directory should be as specified
			So(command.Run(), ShouldBeNil)
			So(string(stdout.LastWritten), ShouldEqual, workingDir+"\n")
		})

	})
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:25,代码来源:local_command_test.go

示例3: main

func main() {
	settings := evergreen.GetSettingsOrExit()
	if settings.Ui.LogFile != "" {
		evergreen.SetLogger(settings.Ui.LogFile)
	}
	db.SetGlobalSessionProvider(db.SessionFactoryFromConfig(settings))

	home := evergreen.FindEvergreenHome()

	userManager, err := auth.LoadUserManager(settings.AuthConfig)
	if err != nil {
		fmt.Println("Failed to create user manager:", err)
		os.Exit(1)
	}

	cookieStore := sessions.NewCookieStore([]byte(settings.Ui.Secret))

	uis := ui.UIServer{
		nil,             // render
		settings.Ui.Url, // RootURL
		userManager,     // User Manager
		*settings,       // mci settings
		cookieStore,     // cookiestore
		nil,             // plugin panel manager
	}
	router, err := uis.NewRouter()
	if err != nil {
		fmt.Println("Failed to create router:", err)
		os.Exit(1)
	}

	webHome := filepath.Join(home, "public")

	functionOptions := ui.FuncOptions{webHome, settings.Ui.HelpUrl, true, router}

	functions, err := ui.MakeTemplateFuncs(functionOptions, settings.SuperUsers)
	if err != nil {
		fmt.Println("Failed to create template function map:", err)
		os.Exit(1)
	}

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(home, ui.WebRootPath, ui.Templates),
		DisableCache: !settings.Ui.CacheTemplates,
		Funcs:        functions,
	})
	err = uis.InitPlugins()
	if err != nil {
		fmt.Println("WARNING: Error initializing plugins:", err)
	}

	n := negroni.New()
	n.Use(negroni.NewStatic(http.Dir(webHome)))
	n.Use(ui.NewLogger())
	n.Use(negroni.HandlerFunc(ui.UserMiddleware(userManager)))
	n.UseHandler(router)
	graceful.Run(settings.Ui.HttpListenAddr, requestTimeout, n)
	evergreen.Logger.Logf(slogger.INFO, "UI server cleanly terminated")
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:59,代码来源:ui.go

示例4: Run

// Run loops while there are any unprocessed alerts and attempts to deliver them.
func (qp *QueueProcessor) Run(config *evergreen.Settings) error {
	evergreen.Logger.Logf(slogger.INFO, "Starting alert queue processor run")
	home := evergreen.FindEvergreenHome()
	qp.config = config
	qp.render = render.New(render.Options{
		Directory:    filepath.Join(home, "alerts", "templates"),
		DisableCache: !config.Ui.CacheTemplates,
		TextFuncs:    nil,
		HtmlFuncs:    nil,
	})

	if len(qp.config.SuperUsers) == 0 {
		evergreen.Logger.Logf(slogger.WARN, "WARNING: No superusers configured, some alerts may have no recipient")
	}
	superUsers, err := user.Find(user.ByIds(qp.config.SuperUsers...))
	if err != nil {
		evergreen.Logger.Logf(slogger.ERROR, "Error getting superuser list: %v", err)
		return err
	}
	qp.superUsersConfigs = []model.AlertConfig{}
	for _, u := range superUsers {
		qp.superUsersConfigs = append(qp.superUsersConfigs, model.AlertConfig{"email", bson.M{"rcpt": u.Email()}})
	}
	evergreen.Logger.Logf(slogger.INFO, "Super-users config for outgoing alerts is: %#v", qp.superUsersConfigs)

	evergreen.Logger.Logf(slogger.INFO, "Running alert queue processing")
	for {
		nextAlert, err := alert.DequeueAlertRequest()

		if err != nil {
			evergreen.Logger.Logf(slogger.ERROR, "Failed to dequeue alert request: %v", err)
			return err
		}
		if nextAlert == nil {
			evergreen.Logger.Logf(slogger.INFO, "Reached end of queue items - stopping.")
			break
		}

		evergreen.Logger.Logf(slogger.DEBUG, "Processing queue item %v", nextAlert.Id.Hex())

		alertContext, err := qp.loadAlertContext(nextAlert)
		if err != nil {
			evergreen.Logger.Logf(slogger.ERROR, "Failed to load alert context: %v", err)
			return err
		}

		evergreen.Logger.Logf(slogger.DEBUG, "Delivering queue item %v", nextAlert.Id.Hex())
		err = qp.Deliver(nextAlert, alertContext)
		if err != nil {
			evergreen.Logger.Logf(slogger.ERROR, "Got error delivering message: %v", err)
		}

	}
	evergreen.Logger.Logf(slogger.INFO, "Finished alert queue processor run.")
	return nil
}
开发者ID:pritten,项目名称:evergreen,代码行数:57,代码来源:alerts.go

示例5: NewTaskRunner

func NewTaskRunner(settings *evergreen.Settings) *TaskRunner {
	// get mci home, and set the source and destination for the agent
	// executables
	evgHome := evergreen.FindEvergreenHome()

	return &TaskRunner{
		settings,
		&DBHostFinder{},
		&DBTaskQueueFinder{},
		&AgentBasedHostGateway{
			ExecutablesDir: filepath.Join(evgHome, settings.AgentExecutablesDir),
		},
	}
}
开发者ID:sr527,项目名称:evergreen,代码行数:14,代码来源:task_runner.go

示例6: main

func main() {

	settings := evergreen.GetSettingsOrExit()
	home := evergreen.FindEvergreenHome()
	uis, err := ui.New(settings, home)
	if err != nil {
		fmt.Println("Failed to create ui server: %v", err)
		os.Exit(1)
	}
	router, err := uis.NewRouter()
	if err != nil {
		fmt.Println("Failed to create router:", err)
		os.Exit(1)
	}

	webHome := filepath.Join(uis.Home, "public")

	functionOptions := ui.FuncOptions{webHome, uis.Settings.Ui.HelpUrl, true, router}

	functions, err := ui.MakeTemplateFuncs(functionOptions, uis.Settings.SuperUsers)
	htmlFunctions := htmlTemplate.FuncMap(functions)
	textFunctions := textTemplate.FuncMap(functions)

	if err != nil {
		fmt.Println("Failed to create template function map:", err)
		os.Exit(1)
	}

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(uis.Home, ui.WebRootPath, ui.Templates),
		DisableCache: !uis.Settings.Ui.CacheTemplates,
		HtmlFuncs:    htmlFunctions,
		TextFuncs:    textFunctions,
	})
	err = uis.InitPlugins()
	if err != nil {
		fmt.Println("WARNING: Error initializing plugins:", err)
	}

	n := negroni.New()
	n.Use(negroni.NewStatic(http.Dir(webHome)))
	n.Use(ui.NewLogger())
	n.Use(negroni.HandlerFunc(ui.UserMiddleware(uis.UserManager)))
	n.UseHandler(router)
	graceful.Run(uis.Settings.Ui.HttpListenAddr, requestTimeout, n)
	evergreen.Logger.Logf(slogger.INFO, "UI server cleanly terminated")
}
开发者ID:tychoish,项目名称:evergreen,代码行数:47,代码来源:ui.go

示例7: LocateCLIBinary

// LocateCLIBinary returns the (absolute) path to the CLI binary for the given architecture, based
// on the system settings. Returns an error if the file does not exist.
func LocateCLIBinary(settings *evergreen.Settings, architecture string) (string, error) {
	clientsSubDir := "clients"
	if settings.ClientBinariesDir != "" {
		clientsSubDir = settings.ClientBinariesDir
	}

	var path string
	if filepath.IsAbs(clientsSubDir) {
		path = filepath.Join(clientsSubDir, architecture, "main")
	} else {
		path = filepath.Join(evergreen.FindEvergreenHome(), clientsSubDir, architecture, "main")
	}
	_, err := os.Stat(path)
	if err != nil {
		return path, err
	}
	return filepath.Abs(path)
}
开发者ID:tychoish,项目名称:evergreen,代码行数:20,代码来源:setup.go

示例8: createEnvironment

func createEnvironment(settings *evergreen.Settings, globals map[string]interface{}) (*web.App, error) {
	home := evergreen.FindEvergreenHome()
	templateHome := filepath.Join(home, TemplatePath)

	funcs, err := web.MakeCommonFunctionMap(settings)
	if err != nil {
		return nil, fmt.Errorf("error creating templating functions: %v", err)
	}
	// Overwrite globals
	funcs["Global"] = func(input string) interface{} {
		return globals[input]
	}

	app := web.NewApp()
	app.TemplateFuncs = funcs
	app.TemplateFolder = templateHome
	app.CacheTemplates = true
	return app, nil
}
开发者ID:tychoish,项目名称:evergreen,代码行数:19,代码来源:email_template.go

示例9: RunTaskOnHost

// Start the task specified, on the host specified.  First runs any necessary
// preparation on the remote machine, then kicks off the agent process on the
// machine.
// Returns an error if any step along the way fails.
func (self *AgentBasedHostGateway) RunTaskOnHost(settings *evergreen.Settings,
	taskToRun model.Task, hostObj host.Host) (string, error) {

	// cache mci home
	evgHome := evergreen.FindEvergreenHome()

	// get the host's SSH options
	cloudHost, err := providers.GetCloudHost(&hostObj, settings)
	if err != nil {
		return "", fmt.Errorf("Failed to get cloud host for %v: %v", hostObj.Id, err)
	}
	sshOptions, err := cloudHost.GetSSHOptions()
	if err != nil {
		return "", fmt.Errorf("Error getting ssh options for host %v: %v", hostObj.Id, err)
	}

	// prep the remote host
	evergreen.Logger.Logf(slogger.INFO, "Prepping remote host %v...", hostObj.Id)
	agentRevision, err := self.prepRemoteHost(settings, hostObj, sshOptions, evgHome)
	if err != nil {
		return "", fmt.Errorf("error prepping remote host %v: %v", hostObj.Id, err)
	}
	evergreen.Logger.Logf(slogger.INFO, "Prepping host finished successfully")

	// start the agent on the remote machine
	evergreen.Logger.Logf(slogger.INFO, "Starting agent on host %v for task %v...",
		hostObj.Id, taskToRun.Id)

	err = self.startAgentOnRemote(settings, &taskToRun, &hostObj, sshOptions)
	if err != nil {
		return "", fmt.Errorf("error starting agent on %v for task %v: %v",
			hostObj.Id, taskToRun.Id, err)
	}
	evergreen.Logger.Logf(slogger.INFO, "Agent successfully started")

	return agentRevision, nil
}
开发者ID:MauroJr,项目名称:evergreen,代码行数:41,代码来源:host_gateway.go

示例10: TestGetVersionStatus

func TestGetVersionStatus(t *testing.T) {

	userManager, err := auth.LoadUserManager(versionTestConfig.AuthConfig)
	testutil.HandleTestingErr(err, t, "Failure in loading UserManager from config")

	uis := UIServer{
		RootURL:     versionTestConfig.Ui.Url,
		Settings:    *versionTestConfig,
		UserManager: userManager,
	}

	home := evergreen.FindEvergreenHome()

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(home, WebRootPath, Templates),
		DisableCache: true,
		Funcs:        nil,
	})

	router, err := uis.NewRouter()
	testutil.HandleTestingErr(err, t, "Failure in uis.NewRouter()")

	Convey("When finding the status of a particular version", t, func() {
		testutil.HandleTestingErr(db.Clear(build.Collection), t,
			"Error clearing '%v' collection", build.Collection)

		versionId := "my-version"

		task := build.TaskCache{
			Id:          "some-task-id",
			DisplayName: "some-task-name",
			Status:      "success",
			TimeTaken:   time.Duration(100 * time.Millisecond),
		}
		build := &build.Build{
			Id:           "some-build-id",
			Version:      versionId,
			BuildVariant: "some-build-variant",
			DisplayName:  "Some Build Variant",
			Tasks:        []build.TaskCache{task},
		}
		So(build.Insert(), ShouldBeNil)

		Convey("grouped by tasks", func() {
			groupBy := "tasks"

			url, err := router.Get("version_status").URL("version_id", versionId)
			So(err, ShouldBeNil)

			query := url.Query()
			query.Set("groupby", groupBy)
			url.RawQuery = query.Encode()

			request, err := http.NewRequest("GET", url.String(), nil)
			So(err, ShouldBeNil)

			response := httptest.NewRecorder()
			// Need match variables to be set so can call mux.Vars(request)
			// in the actual handler function
			router.ServeHTTP(response, request)

			So(response.Code, ShouldEqual, http.StatusOK)

			Convey("response should match contents of database", func() {
				var jsonBody map[string]interface{}
				err = json.Unmarshal(response.Body.Bytes(), &jsonBody)
				So(err, ShouldBeNil)

				So(jsonBody["version_id"], ShouldEqual, versionId)

				_jsonTasks, ok := jsonBody["tasks"]
				So(ok, ShouldBeTrue)
				jsonTasks, ok := _jsonTasks.(map[string]interface{})
				So(ok, ShouldBeTrue)
				So(len(jsonTasks), ShouldEqual, 1)

				_jsonTask, ok := jsonTasks[task.DisplayName]
				So(ok, ShouldBeTrue)
				jsonTask, ok := _jsonTask.(map[string]interface{})
				So(ok, ShouldBeTrue)

				_jsonBuild, ok := jsonTask[build.BuildVariant]
				So(ok, ShouldBeTrue)
				jsonBuild, ok := _jsonBuild.(map[string]interface{})
				So(ok, ShouldBeTrue)

				So(jsonBuild["task_id"], ShouldEqual, task.Id)
				So(jsonBuild["status"], ShouldEqual, task.Status)
				So(jsonBuild["time_taken"], ShouldEqual, task.TimeTaken)
			})

			Convey("is the default option", func() {
				url, err := router.Get("version_status").URL("version_id", versionId)
				So(err, ShouldBeNil)

				request, err := http.NewRequest("GET", url.String(), nil)
				So(err, ShouldBeNil)

				_response := httptest.NewRecorder()
				// Need match variables to be set so can call mux.Vars(request)
//.........这里部分代码省略.........
开发者ID:tessavitabile,项目名称:evergreen,代码行数:101,代码来源:rest_version_test.go

示例11: TestGetTaskInfo

func TestGetTaskInfo(t *testing.T) {

	userManager, err := auth.LoadUserManager(taskTestConfig.AuthConfig)
	testutil.HandleTestingErr(err, t, "Failure in loading UserManager from config")

	uis := UIServer{
		RootURL:     taskTestConfig.Ui.Url,
		Settings:    *taskTestConfig,
		UserManager: userManager,
	}

	home := evergreen.FindEvergreenHome()

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(home, WebRootPath, Templates),
		DisableCache: true,
		Funcs:        nil,
	})

	router, err := uis.NewRouter()
	testutil.HandleTestingErr(err, t, "Failure in uis.NewRouter()")

	Convey("When finding info on a particular task", t, func() {
		testutil.HandleTestingErr(db.Clear(model.TasksCollection), t,
			"Error clearing '%v' collection", model.TasksCollection)

		taskId := "my-task"
		versionId := "my-version"
		projectName := "project_test"

		testResult := model.TestResult{
			Status:    "success",
			TestFile:  "some-test",
			URL:       "some-url",
			StartTime: float64(time.Now().Add(-9 * time.Minute).Unix()),
			EndTime:   float64(time.Now().Add(-1 * time.Minute).Unix()),
		}
		task := &model.Task{
			Id:                  taskId,
			CreateTime:          time.Now().Add(-20 * time.Minute),
			ScheduledTime:       time.Now().Add(-15 * time.Minute),
			DispatchTime:        time.Now().Add(-14 * time.Minute),
			StartTime:           time.Now().Add(-10 * time.Minute),
			FinishTime:          time.Now().Add(-5 * time.Second),
			PushTime:            time.Now().Add(-1 * time.Millisecond),
			Version:             versionId,
			Project:             projectName,
			Revision:            fmt.Sprintf("%x", rand.Int()),
			Priority:            10,
			LastHeartbeat:       time.Now(),
			Activated:           false,
			BuildId:             "some-build-id",
			DistroId:            "some-distro-id",
			BuildVariant:        "some-build-variant",
			DependsOn:           []model.Dependency{{"some-other-task", ""}},
			DisplayName:         "My task",
			HostId:              "some-host-id",
			Restarts:            0,
			Execution:           0,
			Archived:            false,
			RevisionOrderNumber: 42,
			Requester:           evergreen.RepotrackerVersionRequester,
			Status:              "success",
			Details: apimodels.TaskEndDetail{
				TimedOut:    false,
				Description: "some-stage",
			},
			Aborted:          false,
			TimeTaken:        time.Duration(100 * time.Millisecond),
			ExpectedDuration: time.Duration(99 * time.Millisecond),
			TestResults:      []model.TestResult{testResult},
			MinQueuePos:      0,
		}
		So(task.Insert(), ShouldBeNil)

		file := artifact.File{
			Name: "Some Artifact",
			Link: "some-url",
		}
		artifact := artifact.Entry{
			TaskId: taskId,
			Files:  []artifact.File{file},
		}
		So(artifact.Upsert(), ShouldBeNil)

		url, err := router.Get("task_info").URL("task_id", taskId)
		So(err, ShouldBeNil)

		request, err := http.NewRequest("GET", url.String(), nil)
		So(err, ShouldBeNil)

		response := httptest.NewRecorder()
		// Need match variables to be set so can call mux.Vars(request)
		// in the actual handler function
		router.ServeHTTP(response, request)

		So(response.Code, ShouldEqual, http.StatusOK)

		Convey("response should match contents of database", func() {
			var jsonBody map[string]interface{}
//.........这里部分代码省略.........
开发者ID:amidvidy,项目名称:evergreen,代码行数:101,代码来源:rest_task_test.go

示例12: TestGetBuildInfo

func TestGetBuildInfo(t *testing.T) {

	userManager, err := auth.LoadUserManager(buildTestConfig.AuthConfig)
	testutil.HandleTestingErr(err, t, "Failure in loading UserManager from config")

	uis := UIServer{
		RootURL:     buildTestConfig.Ui.Url,
		Settings:    *buildTestConfig,
		UserManager: userManager,
	}
	uis.InitPlugins()

	home := evergreen.FindEvergreenHome()

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(home, WebRootPath, Templates),
		DisableCache: true,
	})

	router, err := uis.NewRouter()
	testutil.HandleTestingErr(err, t, "Failed to create ui server router")

	Convey("When finding info on a particular build", t, func() {
		testutil.HandleTestingErr(db.Clear(build.Collection), t,
			"Error clearing '%v' collection", build.Collection)

		buildId := "my-build"
		versionId := "my-version"
		projectName := "mci-test"

		err := modelutil.CreateTestLocalConfig(buildTestConfig, "mci-test", "")
		So(err, ShouldBeNil)

		err = modelutil.CreateTestLocalConfig(buildTestConfig, "render", "")
		So(err, ShouldBeNil)

		err = modelutil.CreateTestLocalConfig(buildTestConfig, "project_test", "")

		task := build.TaskCache{
			Id:          "some-task-id",
			DisplayName: "some-task-name",
			Status:      "success",
			TimeTaken:   time.Duration(100 * time.Millisecond),
		}
		build := &build.Build{
			Id:                  buildId,
			CreateTime:          time.Now().Add(-20 * time.Minute),
			StartTime:           time.Now().Add(-10 * time.Minute),
			FinishTime:          time.Now().Add(-5 * time.Second),
			PushTime:            time.Now().Add(-1 * time.Millisecond),
			Version:             versionId,
			Project:             projectName,
			Revision:            fmt.Sprintf("%x", rand.Int()),
			BuildVariant:        "some-build-variant",
			BuildNumber:         "42",
			Status:              "success",
			Activated:           true,
			ActivatedTime:       time.Now().Add(-15 * time.Minute),
			RevisionOrderNumber: rand.Int(),
			Tasks:               []build.TaskCache{task},
			TimeTaken:           time.Duration(10 * time.Minute),
			DisplayName:         "My build",
			Requester:           evergreen.RepotrackerVersionRequester,
		}
		So(build.Insert(), ShouldBeNil)

		url, err := router.Get("build_info").URL("build_id", buildId)
		So(err, ShouldBeNil)

		request, err := http.NewRequest("GET", url.String(), nil)
		So(err, ShouldBeNil)

		response := httptest.NewRecorder()
		// Need match variables to be set so can call mux.Vars(request)
		// in the actual handler function
		router.ServeHTTP(response, request)

		So(response.Code, ShouldEqual, http.StatusOK)

		Convey("response should match contents of database", func() {
			var jsonBody map[string]interface{}
			err = json.Unmarshal(response.Body.Bytes(), &jsonBody)
			So(err, ShouldBeNil)

			var rawJsonBody map[string]*json.RawMessage
			err = json.Unmarshal(response.Body.Bytes(), &rawJsonBody)
			So(err, ShouldBeNil)

			So(jsonBody["id"], ShouldEqual, build.Id)

			var createTime time.Time
			err = json.Unmarshal(*rawJsonBody["create_time"], &createTime)
			So(err, ShouldBeNil)
			So(createTime, ShouldHappenWithin, TimePrecision, build.CreateTime)

			var startTime time.Time
			err = json.Unmarshal(*rawJsonBody["start_time"], &startTime)
			So(err, ShouldBeNil)
			So(startTime, ShouldHappenWithin, TimePrecision, build.StartTime)

//.........这里部分代码省略.........
开发者ID:tychoish,项目名称:evergreen,代码行数:101,代码来源:rest_build_test.go

示例13: init

func init() {
	evgHome := evergreen.FindEvergreenHome()
	goxc = filepath.Join(evgHome, "src/github.com/laher/goxc/goxc.go")
}
开发者ID:amidvidy,项目名称:evergreen,代码行数:4,代码来源:agent_compiler.go

示例14: TestActivateVersion

func TestActivateVersion(t *testing.T) {

	uis := UIServer{
		RootURL:     versionTestConfig.Ui.Url,
		Settings:    *versionTestConfig,
		UserManager: MockUserManager{},
	}

	home := evergreen.FindEvergreenHome()

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(home, WebRootPath, Templates),
		DisableCache: true,
	})
	uis.InitPlugins()

	router, err := uis.NewRouter()
	testutil.HandleTestingErr(err, t, "Failed to create ui server router")

	n := negroni.New()
	n.Use(negroni.HandlerFunc(UserMiddleware(uis.UserManager)))
	n.UseHandler(router)

	Convey("When marking a particular version as active", t, func() {
		testutil.HandleTestingErr(db.ClearCollections(version.Collection, build.Collection), t,
			"Error clearing collections")

		versionId := "my-version"
		projectName := "project_test"

		build := &build.Build{
			Id:           "some-build-id",
			BuildVariant: "some-build-variant",
		}
		So(build.Insert(), ShouldBeNil)

		v := &version.Version{
			Id:                  versionId,
			CreateTime:          time.Now().Add(-20 * time.Minute),
			StartTime:           time.Now().Add(-10 * time.Minute),
			FinishTime:          time.Now().Add(-5 * time.Second),
			Revision:            fmt.Sprintf("%x", rand.Int()),
			Author:              "some-author",
			AuthorEmail:         "some-email",
			Message:             "some-message",
			Status:              "success",
			BuildIds:            []string{build.Id},
			BuildVariants:       []version.BuildStatus{{"some-build-variant", true, time.Now().Add(-20 * time.Minute), "some-build-id"}},
			RevisionOrderNumber: rand.Int(),
			Owner:               "some-owner",
			Repo:                "some-repo",
			Branch:              "some-branch",
			RepoKind:            "github",
			Identifier:          projectName,
			Remote:              false,
			RemotePath:          "",
			Requester:           evergreen.RepotrackerVersionRequester,
		}
		So(v.Insert(), ShouldBeNil)

		url, err := router.Get("version_info").URL("version_id", versionId)
		So(err, ShouldBeNil)

		var body = map[string]interface{}{
			"activated": true,
		}
		jsonBytes, err := json.Marshal(body)
		So(err, ShouldBeNil)
		bodyReader := bytes.NewReader(jsonBytes)

		request, err := http.NewRequest("PATCH", url.String(), bodyReader)
		So(err, ShouldBeNil)
		// add auth cookie--this can be anything if we are using a MockUserManager
		request.AddCookie(&http.Cookie{Name: evergreen.AuthTokenCookie, Value: "token"})

		response := httptest.NewRecorder()
		// Need match variables to be set so can call mux.Vars(request)
		// in the actual handler function
		n.ServeHTTP(response, request)

		So(response.Code, ShouldEqual, http.StatusOK)

		validateVersionInfo(v, response)
	})

	Convey("When marking a nonexistent version as active", t, func() {
		versionId := "not-present"

		url, err := router.Get("version_info").URL("version_id", versionId)
		So(err, ShouldBeNil)

		var body = map[string]interface{}{
			"activated": true,
		}
		jsonBytes, err := json.Marshal(body)
		So(err, ShouldBeNil)
		bodyReader := bytes.NewReader(jsonBytes)

		request, err := http.NewRequest("PATCH", url.String(), bodyReader)
		So(err, ShouldBeNil)
//.........这里部分代码省略.........
开发者ID:tychoish,项目名称:evergreen,代码行数:101,代码来源:rest_version_test.go

示例15: TestLocalCommands

func TestLocalCommands(t *testing.T) {

	Convey("When running local commands", t, func() {

		Convey("the preparation step should replace expansions and forward"+
			" slashes in the command string", func() {

			command := &LocalCommand{
				CmdString: "one ${two} \\three${four|five}",
			}

			expansions := NewExpansions(map[string]string{
				"two": "TWO",
				"six": "SIX",
			})

			// run the preparation stage, and make sure the replacements are
			// correctly made
			So(command.PrepToRun(expansions), ShouldBeNil)
			So(command.CmdString, ShouldEqual, "one TWO /threefive")

		})

		Convey("the specified environment should be used", func() {

			stdout := &CacheLastWritten{}

			command := &LocalCommand{
				CmdString: "echo $local_command_test",
				Stdout:    stdout,
				Stderr:    ioutil.Discard,
			}

			// get the current env
			command.Environment = os.Environ()

			// run the command - the environment variable should be empty
			So(command.Run(), ShouldBeNil)
			So(string(stdout.LastWritten), ShouldEqual, "\n")

			// add the environment variable to the env
			command.Environment = append(command.Environment,
				"local_command_test=hello")

			// run the command again - the environment variable should be set
			// correctly
			So(command.Run(), ShouldBeNil)
			So(string(stdout.LastWritten), ShouldEqual, "hello\n")

		})

		Convey("the specified working directory should be used", func() {

			stdout := &CacheLastWritten{}

			evgHome := evergreen.FindEvergreenHome()
			workingDir := filepath.Join(evgHome, "command/testdata")

			command := &LocalCommand{
				CmdString:        "pwd",
				Stdout:           stdout,
				Stderr:           ioutil.Discard,
				WorkingDirectory: workingDir,
			}

			// run the command - the working directory should be as specified
			So(command.Run(), ShouldBeNil)
			So(string(stdout.LastWritten), ShouldEqual, workingDir+"\n")

		})

	})

}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:74,代码来源:local_command_test.go


注:本文中的github.com/evergreen-ci/evergreen.FindEvergreenHome函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。