func (c githubClientMock) ListTeams(owner string, repo string, opt *github.ListOptions) ([]github.Team, *github.Response, error) { a := github.Team{ID: github.Int(1), Name: github.String("team_1"), Permission: github.String("pull")} b := github.Team{ID: github.Int(2), Name: github.String("team_2"), Permission: github.String("push")} if repo == "repo_1" { return []github.Team{a}, nil, nil } if repo == "repo_2" { return []github.Team{b}, nil, nil } if repo == "repo_3" { return []github.Team{a, b}, nil, nil } return []github.Team{}, nil, nil }
func newDraftRepositoryRelease(id int, version string) github.RepositoryRelease { return github.RepositoryRelease{ TagName: github.String(version), Draft: github.Bool(true), ID: github.Int(id), } }
func TestContextUser(t *testing.T) { expectedUser := &github.User{ID: github.Int(917408), Name: github.String("Github User")} ctx := WithUser(context.Background(), expectedUser) user, err := UserFromContext(ctx) assert.Equal(t, expectedUser, user) assert.Nil(t, err) }
func TestGithubHandler(t *testing.T) { jsonData := `{"id": 917408, "name": "Alyssa Hacker"}` expectedUser := &github.User{ID: github.Int(917408), Name: github.String("Alyssa Hacker")} proxyClient, server := newGithubTestServer(jsonData) defer server.Close() // oauth2 Client will use the proxy client's base Transport ctx := context.WithValue(context.Background(), oauth2.HTTPClient, proxyClient) anyToken := &oauth2.Token{AccessToken: "any-token"} ctx = oauth2Login.WithToken(ctx, anyToken) config := &oauth2.Config{} success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) { githubUser, err := UserFromContext(ctx) assert.Nil(t, err) assert.Equal(t, expectedUser, githubUser) fmt.Fprintf(w, "success handler called") } failure := testutils.AssertFailureNotCalled(t) // GithubHandler assert that: // - Token is read from the ctx and passed to the Github API // - github User is obtained from the Github API // - success handler is called // - github User is added to the ctx of the success handler githubHandler := githubHandler(config, ctxh.ContextHandlerFunc(success), failure) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/", nil) githubHandler.ServeHTTP(ctx, w, req) assert.Equal(t, "success handler called", w.Body.String()) }
// Test handler with correct input. func TestMain(t *testing.T) { pullrequest := github.PullRequestEvent{ Action: github.String("opened"), Number: github.Int(0), Repo: &github.Repository{ FullName: github.String("test"), }, } reqbody, _ := json.Marshal(pullrequest) handler := New(Configuration{}) runner := func(handler *Handler, event github.PullRequestEvent) {} ts := httptest.NewServer(mainHandler(handler, runner)) defer ts.Close() req, _ := http.NewRequest("GET", ts.URL, bytes.NewBuffer(reqbody)) resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("HTTP Request failed: %s", err) } if resp.StatusCode != http.StatusAccepted { t.Errorf("Expected HTTP %d, got HTTP %d", http.StatusAccepted, resp.StatusCode) } }
func TestValidateResponse(t *testing.T) { validUser := &github.User{ID: github.Int(123)} validResponse := &github.Response{Response: &http.Response{StatusCode: 200}} invalidResponse := &github.Response{Response: &http.Response{StatusCode: 500}} assert.Equal(t, nil, validateResponse(validUser, validResponse, nil)) assert.Equal(t, ErrUnableToGetGithubUser, validateResponse(validUser, validResponse, fmt.Errorf("Server error"))) assert.Equal(t, ErrUnableToGetGithubUser, validateResponse(validUser, invalidResponse, nil)) assert.Equal(t, ErrUnableToGetGithubUser, validateResponse(&github.User{}, validResponse, nil)) }
func GetGitHubCommitRepoForTest(login string) GitHubCommitRepo { d := time.Now() return GitHubCommitRepo{ RepoName: "someuser/somerepo", RepositoryCommit: github.RepositoryCommit{ SHA: github.String("ffffffffffffffffffffffffffffffffffffffff"), Author: &github.User{ Login: github.String(login), }, Commit: &github.Commit{ SHA: github.String("ffffffffffffffffffffffffffffffffffffffff"), Author: &github.CommitAuthor{Date: &d}, Message: github.String("Some commit message."), }, Stats: &github.CommitStats{ Additions: github.Int(5), Deletions: github.Int(5), Total: github.Int(10), }, Files: []github.CommitFile{{ SHA: github.String("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"), Filename: github.String("some file name"), Additions: github.Int(5), Deletions: github.Int(5), Changes: github.Int(10), Status: github.String("modified"), Patch: github.String("Some patch"), }}, }, } }
func TestGitHub_InstallHook_Edit(t *testing.T) { r := new(mockRepositoriesService) g := &GitHub{ Repositories: r, } existingHook := NewHook("http://localhost", "secret") existingHook.ID = github.Int(1) hook := NewHook("http://localhost", "secret") r.On("ListHooks", "remind101", "acme-inc").Return([]github.Hook{*existingHook}, nil) r.On("EditHook", "remind101", "acme-inc", 1, hook).Return(nil) err := g.InstallHook("remind101", "acme-inc", hook) assert.NoError(t, err) r.AssertExpectations(t) }
// CreateRepo will create a new repository in the organization on github. // // TODO: When the hook option is activated, it can only create a push hook. // Extend this to include a optional event hook. func (o *Organization) CreateRepo(opt RepositoryOptions) (err error) { err = o.connectAdminToGithub() if err != nil { return } if opt.Name == "" { return errors.New("Missing required name field. ") } repo := &github.Repository{} repo.Name = github.String(opt.Name) repo.Private = github.Bool(opt.Private) repo.AutoInit = github.Bool(opt.AutoInit) repo.HasIssues = github.Bool(opt.Issues) if opt.TeamID != 0 { repo.TeamID = github.Int(opt.TeamID) } _, _, err = o.githubadmin.Repositories.Create(o.Name, repo) if err != nil { return } if opt.Hook != "" { config := make(map[string]interface{}) config["url"] = global.Hostname + "/event/hook" config["content_type"] = "json" hook := github.Hook{ Name: github.String("web"), Config: config, Events: []string{ opt.Hook, }, } _, _, err = o.githubadmin.Repositories.CreateHook(o.Name, opt.Name, &hook) } return }
func TestEnable_Exists(t *testing.T) { hook := &github.Hook{ Name: github.String("web"), Config: map[string]interface{}{ "url": "http://www.google.com", }, } g := new(mockHooker) h := &Enable{ Hook: hook, hooker: g, } g.On("ListHooks", "remind101", "acme-inc").Return([]github.Hook{ { ID: github.Int(1), Name: github.String("web"), Config: map[string]interface{}{ "url": "http://www.google.com", }, }, }, nil) g.On("EditHook", "remind101", "acme-inc", 1, hook).Return(nil) ctx := slash.WithParams(context.Background(), map[string]string{ "owner": "remind101", "repo": "acme-inc", }) resp, err := h.ServeCommand(ctx, nil, slash.Command{ Token: slackToken, Command: "/conveyor", Text: "setup remind101/acme-inc", }) assert.NoError(t, err) assert.Equal(t, "Updated webhook on remind101/acme-inc", resp.Text) g.AssertExpectations(t) }
request resource.OutRequest ) BeforeEach(func() { var err error githubClient = &fakes.FakeGitHub{} command = resource.NewOutCommand(githubClient, ioutil.Discard) sourcesDir, err = ioutil.TempDir("", "github-release") Ω(err).ShouldNot(HaveOccurred()) githubClient.CreateReleaseStub = func(gh github.RepositoryRelease) (*github.RepositoryRelease, error) { createdRel := gh createdRel.ID = github.Int(112) createdRel.HTMLURL = github.String("http://google.com") createdRel.Name = github.String("release-name") createdRel.Body = github.String("*markdown*") return &createdRel, nil } githubClient.UpdateReleaseStub = func(gh github.RepositoryRelease) (*github.RepositoryRelease, error) { return &gh, nil } }) AfterEach(func() { Ω(os.RemoveAll(sourcesDir)).Should(Succeed()) })
func TestRunGH(t *testing.T) { const ( expOwner = "cockroachdb" expRepo = "cockroach" envPkg = "foo/bar/baz" envPropEvalKV = "true" envTags = "deadlock" envGoFlags = "race" sha = "abcd123" serverURL = "https://teamcity.example.com" buildID = 8008135 issueID = 1337 ) for key, value := range map[string]string{ teamcityVCSNumberEnv: sha, teamcityServerURLEnv: serverURL, teamcityBuildIDEnv: strconv.Itoa(buildID), pkgEnv: envPkg, propEvalKVEnv: envPropEvalKV, tagsEnv: envTags, goFlagsEnv: envGoFlags, } { if val, ok := os.LookupEnv(key); ok { defer func() { if err := os.Setenv(key, val); err != nil { t.Error(err) } }() } else { defer func() { if err := os.Unsetenv(key); err != nil { t.Error(err) } }() } if err := os.Setenv(key, value); err != nil { t.Fatal(err) } } parameters := "```\n" + strings.Join([]string{ propEvalKVEnv + "=" + envPropEvalKV, tagsEnv + "=" + envTags, goFlagsEnv + "=" + envGoFlags, }, "\n") + "\n```" for fileName, expectations := range map[string]struct { packageName string testName string body string }{ "stress-failure": { packageName: envPkg, testName: "TestReplicateQueueRebalance", body: " <autogenerated>:12: storage/replicate_queue_test.go:103, condition failed to evaluate within 45s: not balanced: [10 1 10 1 8]", }, "stress-fatal": { packageName: envPkg, testName: "TestRaftRemoveRace", body: "F161007 00:27:33.243126 449 storage/store.go:2446 [s3] [n3,s3,r1:/M{in-ax}]: could not remove placeholder after preemptive snapshot", }, } { t.Run(fileName, func(t *testing.T) { file, err := os.Open(filepath.Join("testdata", fileName)) if err != nil { t.Fatal(err) } issueBodyRe, err := regexp.Compile( fmt.Sprintf(`(?s)\ASHA: https://github.com/cockroachdb/cockroach/commits/%s Parameters: %s Stress build found a failed test: %s .* %s `, regexp.QuoteMeta(sha), regexp.QuoteMeta(parameters), regexp.QuoteMeta(fmt.Sprintf("%s/viewLog.html?buildId=%d&tab=buildLog", serverURL, buildID)), regexp.QuoteMeta(expectations.body), ), ) if err != nil { t.Fatal(err) } count := 0 if err := runGH( file, func(owner string, repo string, issue *github.IssueRequest) (*github.Issue, *github.Response, error) { count++ if owner != expOwner { t.Fatalf("got %s, expected %s", owner, expOwner) } if repo != expRepo { t.Fatalf("got %s, expected %s", repo, expRepo) } if expected := fmt.Sprintf("%s: %s failed under stress", expectations.packageName, expectations.testName); *issue.Title != expected { t.Fatalf("got %s, expected %s", *issue.Title, expected) } if !issueBodyRe.MatchString(*issue.Body) { t.Fatalf("got:\n%s\nexpected:\n%s", *issue.Body, issueBodyRe) } if length := len(*issue.Body); length > githubIssueBodyMaximumLength { t.Fatalf("issue length %d exceeds (undocumented) maximum %d", length, githubIssueBodyMaximumLength) } return &github.Issue{ID: github.Int(issueID)}, nil, nil }, ); err != nil { t.Fatal(err) } if expected := 1; count != expected { t.Fatalf("%d issues were posted, expected %d", count, expected) } }) } }
Ω(err).ShouldNot(HaveOccurred()) destDir = filepath.Join(tmpDir, "destination") githubClient.DownloadReleaseAssetReturns(ioutil.NopCloser(bytes.NewBufferString("some-content")), nil) inRequest = resource.InRequest{} }) AfterEach(func() { Ω(os.RemoveAll(tmpDir)).Should(Succeed()) }) buildRelease := func(id int, tag string, draft bool) *github.RepositoryRelease { return &github.RepositoryRelease{ ID: github.Int(id), TagName: github.String(tag), HTMLURL: github.String("http://google.com"), Name: github.String("release-name"), Body: github.String("*markdown*"), Draft: github.Bool(draft), } } buildNilTagRelease := func(id int) *github.RepositoryRelease { return &github.RepositoryRelease{ ID: github.Int(id), HTMLURL: github.String("http://google.com"), Name: github.String("release-name"), Body: github.String("*markdown*"), Draft: github.Bool(true),
func newDraftWithNilTagRepositoryRelease(id int) github.RepositoryRelease { return github.RepositoryRelease{ Draft: github.Bool(true), ID: github.Int(id), } }
func TestRunGH(t *testing.T) { f, err := os.Open("testdata/fatal") if err != nil { t.Fatal(err) } const ( expOwner = "cockroachdb" expRepo = "cockroach" pkg = "foo/bar/baz" sha = "abcd123" issueID = 1337 ) issueBodyRe := regexp.MustCompile(fmt.Sprintf(`(?s)\ASHA: https://github.com/cockroachdb/cockroach/commits/%s Stress build found a failed test: .* F161007 00:27:33\.243126 449 storage/store\.go:2446 \[s3\] \[n3,s3,r1:/M{in-ax}\]: could not remove placeholder after preemptive snapshot goroutine 449 \[running\]: `, sha)) if val, ok := os.LookupEnv(teamcityVCSNumberEnv); ok { defer func() { if err := os.Setenv(teamcityVCSNumberEnv, val); err != nil { t.Error(err) } }() } else { defer func() { if err := os.Unsetenv(teamcityVCSNumberEnv); err != nil { t.Error(err) } }() } if err := os.Setenv(teamcityVCSNumberEnv, sha); err != nil { t.Fatal(err) } if err := runGH( f, func(owner string, repo string, issue *github.IssueRequest) (*github.Issue, *github.Response, error) { if owner != expOwner { t.Fatalf("got %s, expected %s", owner, expOwner) } if repo != expRepo { t.Fatalf("got %s, expected %s", repo, expRepo) } if expected := fmt.Sprintf("%s: %s failed under stress", pkg, "TestRaftRemoveRace"); *issue.Title != expected { t.Fatalf("got %s, expected %s", *issue.Title, expected) } if !issueBodyRe.MatchString(*issue.Body) { t.Fatalf("got:\n%s\nexpected:\n%s", *issue.Body, issueBodyRe) } return &github.Issue{ID: github.Int(issueID)}, nil, nil }, ); err != nil { t.Fatal(err) } }