1
0
Fork 0
mirror of https://github.com/documize/community.git synced 2025-07-23 07:09:43 +02:00

initial commit

This commit is contained in:
Harvey Kandola 2016-07-07 18:54:16 -07:00
commit 18933c6767
1841 changed files with 810642 additions and 0 deletions

View file

@ -0,0 +1,140 @@
// Copyright 2014 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build integration
package tests
import (
"testing"
"github.com/google/go-github/github"
)
const (
owner = "google"
repo = "go-github"
)
func TestActivity_Starring(t *testing.T) {
stargazers, _, err := client.Activity.ListStargazers(owner, repo, nil)
if err != nil {
t.Fatalf("Activity.ListStargazers returned error: %v", err)
}
if len(stargazers) == 0 {
t.Errorf("Activity.ListStargazers(%q, %q) returned no stargazers", owner, repo)
}
// the rest of the tests requires auth
if !checkAuth("TestActivity_Starring") {
return
}
// first, check if already starred the target repository
star, _, err := client.Activity.IsStarred(owner, repo)
if err != nil {
t.Fatalf("Activity.IsStarred returned error: %v", err)
}
if star {
t.Fatalf("Already starring %v/%v. Please manually unstar it first.", owner, repo)
}
// star the target repository
_, err = client.Activity.Star(owner, repo)
if err != nil {
t.Fatalf("Activity.Star returned error: %v", err)
}
// check again and verify starred
star, _, err = client.Activity.IsStarred(owner, repo)
if err != nil {
t.Fatalf("Activity.IsStarred returned error: %v", err)
}
if !star {
t.Fatalf("Not starred %v/%v after starring it.", owner, repo)
}
// unstar
_, err = client.Activity.Unstar(owner, repo)
if err != nil {
t.Fatalf("Activity.Unstar returned error: %v", err)
}
// check again and verify not watching
star, _, err = client.Activity.IsStarred(owner, repo)
if err != nil {
t.Fatalf("Activity.IsStarred returned error: %v", err)
}
if star {
t.Fatalf("Still starred %v/%v after unstarring it.", owner, repo)
}
}
func deleteSubscription(t *testing.T) {
// delete subscription
_, err := client.Activity.DeleteRepositorySubscription(owner, repo)
if err != nil {
t.Fatalf("Activity.DeleteRepositorySubscription returned error: %v", err)
}
// check again and verify not watching
sub, _, err := client.Activity.GetRepositorySubscription(owner, repo)
if err != nil {
t.Fatalf("Activity.GetRepositorySubscription returned error: %v", err)
}
if sub != nil {
t.Fatalf("Still watching %v/%v after deleting subscription.", owner, repo)
}
}
func createSubscription(t *testing.T) {
// watch the target repository
sub := &github.Subscription{Subscribed: github.Bool(true)}
_, _, err := client.Activity.SetRepositorySubscription(owner, repo, sub)
if err != nil {
t.Fatalf("Activity.SetRepositorySubscription returned error: %v", err)
}
// check again and verify watching
sub, _, err = client.Activity.GetRepositorySubscription(owner, repo)
if err != nil {
t.Fatalf("Activity.GetRepositorySubscription returned error: %v", err)
}
if sub == nil || !*sub.Subscribed {
t.Fatalf("Not watching %v/%v after setting subscription.", owner, repo)
}
}
func TestActivity_Watching(t *testing.T) {
watchers, _, err := client.Activity.ListWatchers(owner, repo, nil)
if err != nil {
t.Fatalf("Activity.ListWatchers returned error: %v", err)
}
if len(watchers) == 0 {
t.Errorf("Activity.ListWatchers(%q, %q) returned no watchers", owner, repo)
}
// the rest of the tests requires auth
if !checkAuth("TestActivity_Watching") {
return
}
// first, check if already watching the target repository
sub, _, err := client.Activity.GetRepositorySubscription(owner, repo)
if err != nil {
t.Fatalf("Activity.GetRepositorySubscription returned error: %v", err)
}
switch {
case sub != nil: // If already subscribing, delete then recreate subscription.
deleteSubscription(t)
createSubscription(t)
case sub == nil: // Otherwise, create subscription and then delete it.
createSubscription(t)
deleteSubscription(t)
}
}

View file

@ -0,0 +1,305 @@
// Copyright 2016 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build integration
package tests
import (
"math/rand"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/google/go-github/github"
)
const msgEnvMissing = "Skipping test because the required environment variable (%v) is not present."
const envKeyGitHubUsername = "GITHUB_USERNAME"
const envKeyGitHubPassword = "GITHUB_PASSWORD"
const envKeyClientID = "GITHUB_CLIENT_ID"
const envKeyClientSecret = "GITHUB_CLIENT_SECRET"
const InvalidTokenValue = "iamnotacroken"
// TestAuthorizationsBasicOperations tests the basic CRUD operations of the API (mostly for
// the Personal Access Token scenario).
func TestAuthorizationsBasicOperations(t *testing.T) {
client := getUserPassClient(t)
auths, resp, err := client.Authorizations.List(nil)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
initialAuthCount := len(auths)
authReq := generatePersonalAuthTokenRequest()
createdAuth, resp, err := client.Authorizations.Create(authReq)
failOnError(t, err)
failIfNotStatusCode(t, resp, 201)
if *authReq.Note != *createdAuth.Note {
t.Fatal("Returned Authorization does not match the requested Authorization.")
}
auths, resp, err = client.Authorizations.List(nil)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
if len(auths) != initialAuthCount+1 {
t.Fatalf("The number of Authorizations should have increased. Expected [%v], was [%v]", initialAuthCount+1, len(auths))
}
// Test updating the authorization
authUpdate := new(github.AuthorizationUpdateRequest)
authUpdate.Note = github.String("Updated note: " + randString())
updatedAuth, resp, err := client.Authorizations.Edit(*createdAuth.ID, authUpdate)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
if *updatedAuth.Note != *authUpdate.Note {
t.Fatal("The returned Authorization does not match the requested updated value.")
}
// Verify that the Get operation also reflects the update
retrievedAuth, resp, err := client.Authorizations.Get(*createdAuth.ID)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
if *retrievedAuth.Note != *updatedAuth.Note {
t.Fatal("The retrieved Authorization does not match the expected (updated) value.")
}
// Now, let's delete...
resp, err = client.Authorizations.Delete(*createdAuth.ID)
failOnError(t, err)
failIfNotStatusCode(t, resp, 204)
// Verify that we can no longer retrieve the auth
retrievedAuth, resp, err = client.Authorizations.Get(*createdAuth.ID)
if err == nil {
t.Fatal("Should have failed due to 404")
}
failIfNotStatusCode(t, resp, 404)
// Verify that our count reset back to the initial value
auths, resp, err = client.Authorizations.List(nil)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
if len(auths) != initialAuthCount {
t.Fatalf("The number of Authorizations should match the initial count Expected [%v], got [%v]", initialAuthCount, len(auths))
}
}
// TestAuthorizationsAppOperations tests the application/token related operations, such
// as creating, testing, resetting and revoking application OAuth tokens.
func TestAuthorizationsAppOperations(t *testing.T) {
userAuthenticatedClient := getUserPassClient(t)
appAuthenticatedClient := getOAuthAppClient(t)
// We know these vars are set because getOAuthAppClient would have
// skipped the test by now
clientID := os.Getenv(envKeyClientID)
clientSecret := os.Getenv(envKeyClientSecret)
authRequest := generateAppAuthTokenRequest(clientID, clientSecret)
createdAuth, resp, err := userAuthenticatedClient.Authorizations.GetOrCreateForApp(clientID, authRequest)
failOnError(t, err)
failIfNotStatusCode(t, resp, 201)
// Quick sanity check:
if *createdAuth.Note != *authRequest.Note {
t.Fatal("The returned auth does not match expected value.")
}
// Let's try the same request again, this time it should return the same
// auth instead of creating a new one
secondAuth, resp, err := userAuthenticatedClient.Authorizations.GetOrCreateForApp(clientID, authRequest)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
// Verify that the IDs are the same
if *createdAuth.ID != *secondAuth.ID {
t.Fatalf("The ID of the second returned auth should be the same as the first. Expected [%v], got [%v]", createdAuth.ID, secondAuth.ID)
}
// Verify the token
appAuth, resp, err := appAuthenticatedClient.Authorizations.Check(clientID, *createdAuth.Token)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
// Quick sanity check
if *appAuth.ID != *createdAuth.ID || *appAuth.Token != *createdAuth.Token {
t.Fatal("The returned auth/token does not match.")
}
// Let's verify that we get a 404 for a non-existent token
_, resp, err = appAuthenticatedClient.Authorizations.Check(clientID, InvalidTokenValue)
if err == nil {
t.Fatal("An error should have been returned because of the invalid token.")
}
failIfNotStatusCode(t, resp, 404)
// Let's reset the token
resetAuth, resp, err := appAuthenticatedClient.Authorizations.Reset(clientID, *createdAuth.Token)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
// Let's verify that we get a 404 for a non-existent token
_, resp, err = appAuthenticatedClient.Authorizations.Reset(clientID, InvalidTokenValue)
if err == nil {
t.Fatal("An error should have been returned because of the invalid token.")
}
failIfNotStatusCode(t, resp, 404)
// Verify that the token has changed
if resetAuth.Token == createdAuth.Token {
t.Fatal("The reset token should be different from the original.")
}
// Verify that we do have a token value
if *resetAuth.Token == "" {
t.Fatal("A token value should have been returned.")
}
// Verify that the original token is now invalid
_, resp, err = appAuthenticatedClient.Authorizations.Check(clientID, *createdAuth.Token)
if err == nil {
t.Fatal("The original token should be invalid.")
}
failIfNotStatusCode(t, resp, 404)
// Check that the reset token is valid
_, resp, err = appAuthenticatedClient.Authorizations.Check(clientID, *resetAuth.Token)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
// Let's revoke the token
resp, err = appAuthenticatedClient.Authorizations.Revoke(clientID, *resetAuth.Token)
failOnError(t, err)
failIfNotStatusCode(t, resp, 204)
// Sleep for two seconds... I've seen cases where the revocation appears not
// to have take place immediately.
time.Sleep(time.Second * 2)
// Now, the reset token should also be invalid
_, resp, err = appAuthenticatedClient.Authorizations.Check(clientID, *resetAuth.Token)
if err == nil {
t.Fatal("The reset token should be invalid.")
}
failIfNotStatusCode(t, resp, 404)
}
// generatePersonalAuthTokenRequest is a helper function that generates an
// AuthorizationRequest for a Personal Access Token (no client id).
func generatePersonalAuthTokenRequest() *github.AuthorizationRequest {
rand := randString()
auth := github.AuthorizationRequest{
Note: github.String("Personal token: Note generated by test: " + rand),
Scopes: []github.Scope{github.ScopePublicRepo},
Fingerprint: github.String("Personal token: Fingerprint generated by test: " + rand),
}
return &auth
}
// generatePersonalAuthTokenRequest is a helper function that generates an
// AuthorizationRequest for an OAuth application Token (uses client id).
func generateAppAuthTokenRequest(clientID string, clientSecret string) *github.AuthorizationRequest {
rand := randString()
auth := github.AuthorizationRequest{
Note: github.String("App token: Note generated by test: " + rand),
Scopes: []github.Scope{github.ScopePublicRepo},
Fingerprint: github.String("App token: Fingerprint generated by test: " + rand),
ClientID: github.String(clientID),
ClientSecret: github.String(clientSecret),
}
return &auth
}
// randString returns a (kinda) random string for uniqueness purposes.
func randString() string {
return strconv.FormatInt(rand.NewSource(time.Now().UnixNano()).Int63(), 10)
}
// failOnError invokes t.Fatal() if err is present.
func failOnError(t *testing.T, err error) {
if err != nil {
t.Fatal(err)
}
}
// failIfNotStatusCode invokes t.Fatal() if the response's status code doesn't match the expected code.
func failIfNotStatusCode(t *testing.T, resp *github.Response, expectedCode int) {
if resp.StatusCode != expectedCode {
t.Fatalf("Expected HTTP status code [%v] but received [%v]", expectedCode, resp.StatusCode)
}
}
// getUserPassClient returns a GitHub client for authorization testing. The client
// uses BasicAuth via GH username and password passed in environment variables
// (and will skip the calling test if those vars are not present).
func getUserPassClient(t *testing.T) *github.Client {
username, ok := os.LookupEnv(envKeyGitHubUsername)
if !ok {
t.Skipf(msgEnvMissing, envKeyGitHubUsername)
}
password, ok := os.LookupEnv(envKeyGitHubPassword)
if !ok {
t.Skipf(msgEnvMissing, envKeyGitHubPassword)
}
tp := github.BasicAuthTransport{
Username: strings.TrimSpace(username),
Password: strings.TrimSpace(password),
}
return github.NewClient(tp.Client())
}
// getOAuthAppClient returns a GitHub client for authorization testing. The client
// uses BasicAuth, but instead of username and password, it uses the client id
// and client secret passed in via environment variables
// (and will skip the calling test if those vars are not present). Certain API operations (check
// an authorization; reset an authorization; revoke an authorization for an app)
// require this authentication mechanism.
//
// See GitHub API docs: https://developer.com/v3/oauth_authorizations/#check-an-authorization
func getOAuthAppClient(t *testing.T) *github.Client {
username, ok := os.LookupEnv(envKeyClientID)
if !ok {
t.Skipf(msgEnvMissing, envKeyClientID)
}
password, ok := os.LookupEnv(envKeyClientSecret)
if !ok {
t.Skipf(msgEnvMissing, envKeyClientSecret)
}
tp := github.BasicAuthTransport{
Username: strings.TrimSpace(username),
Password: strings.TrimSpace(password),
}
return github.NewClient(tp.Client())
}

View file

@ -0,0 +1,6 @@
// Package tests contains integration tests.
//
// These tests call the live GitHub API, and therefore require a little more
// setup to run. See https://github.com/google/go-github/tree/master/tests/integration
// for more information.
package tests

View file

@ -0,0 +1,83 @@
// Copyright 2014 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build integration
package tests
import (
"fmt"
"math/rand"
"net/http"
"os"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
var (
client *github.Client
// auth indicates whether tests are being run with an OAuth token.
// Tests can use this flag to skip certain tests when run without auth.
auth bool
)
func init() {
token := os.Getenv("GITHUB_AUTH_TOKEN")
if token == "" {
print("!!! No OAuth token. Some tests won't run. !!!\n\n")
client = github.NewClient(nil)
} else {
tc := oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
))
client = github.NewClient(tc)
auth = true
}
// Environment variables required for Authorization integration tests
vars := []string{envKeyGitHubUsername, envKeyGitHubPassword, envKeyClientID, envKeyClientSecret}
for _, v := range vars {
value := os.Getenv(v)
if value == "" {
print("!!! " + fmt.Sprintf(msgEnvMissing, v) + " !!!\n\n")
}
}
}
func checkAuth(name string) bool {
if !auth {
fmt.Printf("No auth - skipping portions of %v\n", name)
}
return auth
}
func createRandomTestRepository(owner string, autoinit bool) (*github.Repository, error) {
// create random repo name that does not currently exist
var repoName string
for {
repoName = fmt.Sprintf("test-%d", rand.Int())
_, resp, err := client.Repositories.Get(owner, repoName)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
// found a non-existent repo, perfect
break
}
return nil, err
}
}
// create the repository
repo, _, err := client.Repositories.Create("", &github.Repository{Name: github.String(repoName), AutoInit: github.Bool(autoinit)})
if err != nil {
return nil, err
}
return repo, nil
}

View file

@ -0,0 +1,39 @@
// Copyright 2014 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build integration
package tests
import "testing"
func TestIssueEvents(t *testing.T) {
events, _, err := client.Issues.ListRepositoryEvents("google", "go-github", nil)
if err != nil {
t.Fatalf("Issues.ListRepositoryEvents returned error: %v", err)
}
if len(events) == 0 {
t.Errorf("ListRepositoryEvents returned no events")
}
events, _, err = client.Issues.ListIssueEvents("google", "go-github", 1, nil)
if err != nil {
t.Fatalf("Issues.ListIssueEvents returned error: %v", err)
}
if len(events) == 0 {
t.Errorf("ListIssueEvents returned no events")
}
event, _, err := client.Issues.GetEvent("google", "go-github", *events[0].ID)
if err != nil {
t.Fatalf("Issues.GetEvent returned error: %v", err)
}
if *event.URL != *events[0].URL {
t.Fatalf("Issues.GetEvent returned event URL: %v, want %v", *event.URL, *events[0].URL)
}
}

View file

@ -0,0 +1,67 @@
// Copyright 2014 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build integration
package tests
import (
"testing"
"time"
)
func TestEmojis(t *testing.T) {
emoji, _, err := client.ListEmojis()
if err != nil {
t.Fatalf("ListEmojis returned error: %v", err)
}
if len(emoji) == 0 {
t.Errorf("ListEmojis returned no emojis")
}
if _, ok := emoji["+1"]; !ok {
t.Errorf("ListEmojis missing '+1' emoji")
}
}
func TestAPIMeta(t *testing.T) {
meta, _, err := client.APIMeta()
if err != nil {
t.Fatalf("APIMeta returned error: %v", err)
}
if len(meta.Hooks) == 0 {
t.Errorf("APIMeta returned no hook addresses")
}
if len(meta.Git) == 0 {
t.Errorf("APIMeta returned no git addresses")
}
if !*meta.VerifiablePasswordAuthentication {
t.Errorf("APIMeta VerifiablePasswordAuthentication is false")
}
}
func TestRateLimits(t *testing.T) {
limits, _, err := client.RateLimits()
if err != nil {
t.Fatalf("RateLimits returned error: %v", err)
}
// do some sanity checks
if limits.Core.Limit == 0 {
t.Errorf("RateLimits returned 0 core limit")
}
if limits.Core.Limit < limits.Core.Remaining {
t.Errorf("Core.Limits is less than Core.Remaining.")
}
if limits.Core.Reset.Time.Before(time.Now().Add(-1 * time.Minute)) {
t.Errorf("Core.Reset is more than 1 minute in the past; that doesn't seem right.")
}
}

View file

@ -0,0 +1,25 @@
// Copyright 2014 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build integration
package tests
import "testing"
func TestPullRequests_ListCommits(t *testing.T) {
commits, _, err := client.PullRequests.ListCommits("google", "go-github", 2, nil)
if err != nil {
t.Fatalf("PullRequests.ListCommits() returned error: %v", err)
}
if got, want := len(commits), 3; got != want {
t.Fatalf("PullRequests.ListCommits() returned %d commits, want %d", got, want)
}
if got, want := *commits[0].Author.Login, "sqs"; got != want {
t.Fatalf("PullRequests.ListCommits()[0].Author.Login returned %v, want %v", got, want)
}
}

View file

@ -0,0 +1,174 @@
// Copyright 2014 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build integration
package tests
import (
"net/http"
"reflect"
"testing"
"github.com/google/go-github/github"
)
func TestRepositories_CRUD(t *testing.T) {
if !checkAuth("TestRepositories_CRUD") {
return
}
// get authenticated user
me, _, err := client.Users.Get("")
if err != nil {
t.Fatalf("Users.Get('') returned error: %v", err)
}
repo, err := createRandomTestRepository(*me.Login, false)
if err != nil {
t.Fatalf("createRandomTestRepository returned error: %v", err)
}
// update the repository description
repo.Description = github.String("description")
repo.DefaultBranch = nil // FIXME: this shouldn't be necessary
_, _, err = client.Repositories.Edit(*repo.Owner.Login, *repo.Name, repo)
if err != nil {
t.Fatalf("Repositories.Edit() returned error: %v", err)
}
// delete the repository
_, err = client.Repositories.Delete(*repo.Owner.Login, *repo.Name)
if err != nil {
t.Fatalf("Repositories.Delete() returned error: %v", err)
}
// verify that the repository was deleted
_, resp, err := client.Repositories.Get(*repo.Owner.Login, *repo.Name)
if err == nil {
t.Fatalf("Test repository still exists after deleting it.")
}
if err != nil && resp.StatusCode != http.StatusNotFound {
t.Fatalf("Repositories.Get() returned error: %v", err)
}
}
func TestRepositories_BranchesTags(t *testing.T) {
// branches
branches, _, err := client.Repositories.ListBranches("git", "git", nil)
if err != nil {
t.Fatalf("Repositories.ListBranches() returned error: %v", err)
}
if len(branches) == 0 {
t.Fatalf("Repositories.ListBranches('git', 'git') returned no branches")
}
_, _, err = client.Repositories.GetBranch("git", "git", *branches[0].Name)
if err != nil {
t.Fatalf("Repositories.GetBranch() returned error: %v", err)
}
// tags
tags, _, err := client.Repositories.ListTags("git", "git", nil)
if err != nil {
t.Fatalf("Repositories.ListTags() returned error: %v", err)
}
if len(tags) == 0 {
t.Fatalf("Repositories.ListTags('git', 'git') returned no tags")
}
}
func TestRepositories_ServiceHooks(t *testing.T) {
hooks, _, err := client.Repositories.ListServiceHooks()
if err != nil {
t.Fatalf("Repositories.ListServiceHooks() returned error: %v", err)
}
if len(hooks) == 0 {
t.Fatalf("Repositories.ListServiceHooks() returned no hooks")
}
}
func TestRepositories_EditBranches(t *testing.T) {
if !checkAuth("TestRepositories_EditBranches") {
return
}
// get authenticated user
me, _, err := client.Users.Get("")
if err != nil {
t.Fatalf("Users.Get('') returned error: %v", err)
}
repo, err := createRandomTestRepository(*me.Login, true)
if err != nil {
t.Fatalf("createRandomTestRepository returned error: %v", err)
}
branch, _, err := client.Repositories.GetBranch(*repo.Owner.Login, *repo.Name, "master")
if err != nil {
t.Fatalf("Repositories.GetBranch() returned error: %v", err)
}
if *branch.Protection.Enabled {
t.Fatalf("Branch %v of repo %v is already protected", "master", *repo.Name)
}
branch.Protection.Enabled = github.Bool(true)
branch.Protection.RequiredStatusChecks = &github.RequiredStatusChecks{
EnforcementLevel: github.String("everyone"),
Contexts: &[]string{"continous-integration"},
}
branch, _, err = client.Repositories.EditBranch(*repo.Owner.Login, *repo.Name, "master", branch)
if err != nil {
t.Fatalf("Repositories.EditBranch() returned error: %v", err)
}
if !*branch.Protection.Enabled {
t.Fatalf("Branch %v of repo %v should be protected, but is not!", "master", *repo.Name)
}
if *branch.Protection.RequiredStatusChecks.EnforcementLevel != "everyone" {
t.Fatalf("RequiredStatusChecks should be enabled for everyone, set for: %v", *branch.Protection.RequiredStatusChecks.EnforcementLevel)
}
wantedContexts := []string{"continous-integration"}
if !reflect.DeepEqual(*branch.Protection.RequiredStatusChecks.Contexts, wantedContexts) {
t.Fatalf("RequiredStatusChecks.Contexts should be: %v but is: %v", wantedContexts, *branch.Protection.RequiredStatusChecks.Contexts)
}
_, err = client.Repositories.Delete(*repo.Owner.Login, *repo.Name)
if err != nil {
t.Fatalf("Repositories.Delete() returned error: %v", err)
}
}
func TestRepositories_List(t *testing.T) {
if !checkAuth("TestRepositories_List") {
return
}
_, _, err := client.Repositories.List("", nil)
if err != nil {
t.Fatalf("Repositories.List('') returned error: %v", err)
}
_, _, err = client.Repositories.List("google", nil)
if err != nil {
t.Fatalf("Repositories.List('google') returned error: %v", err)
}
opt := github.RepositoryListOptions{Sort: "created"}
repos, _, err := client.Repositories.List("google", &opt)
if err != nil {
t.Fatalf("Repositories.List('google') with Sort opt returned error: %v", err)
}
for i, repo := range repos {
if i > 0 && (*repos[i-1].CreatedAt).Time.Before((*repo.CreatedAt).Time) {
t.Fatalf("Repositories.List('google') with default descending Sort returned incorrect order")
}
}
}

View file

@ -0,0 +1,240 @@
// Copyright 2014 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build integration
package tests
import (
"fmt"
"math/rand"
"testing"
"github.com/google/go-github/github"
)
func TestUsers_Get(t *testing.T) {
// list all users
users, _, err := client.Users.ListAll(nil)
if err != nil {
t.Fatalf("Users.ListAll returned error: %v", err)
}
if len(users) == 0 {
t.Errorf("Users.ListAll returned no users")
}
// mojombo is user #1
if want := "mojombo"; want != *users[0].Login {
t.Errorf("user[0].Login was %q, wanted %q", *users[0].Login, want)
}
// get individual user
u, _, err := client.Users.Get("octocat")
if err != nil {
t.Fatalf("Users.Get('octocat') returned error: %v", err)
}
if want := "octocat"; want != *u.Login {
t.Errorf("user.Login was %q, wanted %q", *u.Login, want)
}
if want := "The Octocat"; want != *u.Name {
t.Errorf("user.Name was %q, wanted %q", *u.Name, want)
}
}
func TestUsers_Update(t *testing.T) {
if !checkAuth("TestUsers_Get") {
return
}
u, _, err := client.Users.Get("")
if err != nil {
t.Fatalf("Users.Get('') returned error: %v", err)
}
if *u.Login == "" {
t.Errorf("wanted non-empty values for user.Login")
}
// save original location
var location string
if u.Location != nil {
location = *u.Location
}
// update location to test value
testLoc := fmt.Sprintf("test-%d", rand.Int())
u.Location = &testLoc
_, _, err = client.Users.Edit(u)
if err != nil {
t.Fatalf("Users.Update returned error: %v", err)
}
// refetch user and check location value
u, _, err = client.Users.Get("")
if err != nil {
t.Fatalf("Users.Get('') returned error: %v", err)
}
if testLoc != *u.Location {
t.Errorf("Users.Get('') has location: %v, want: %v", *u.Location, testLoc)
}
// set location back to the original value
u.Location = &location
_, _, err = client.Users.Edit(u)
}
func TestUsers_Emails(t *testing.T) {
if !checkAuth("TestUsers_Emails") {
return
}
emails, _, err := client.Users.ListEmails(nil)
if err != nil {
t.Fatalf("Users.ListEmails() returned error: %v", err)
}
// create random address not currently in user's emails
var email string
EmailLoop:
for {
email = fmt.Sprintf("test-%d@example.com", rand.Int())
for _, e := range emails {
if e.Email != nil && *e.Email == email {
continue EmailLoop
}
}
break
}
// Add new address
_, _, err = client.Users.AddEmails([]string{email})
if err != nil {
t.Fatalf("Users.AddEmails() returned error: %v", err)
}
// List emails again and verify new email is present
emails, _, err = client.Users.ListEmails(nil)
if err != nil {
t.Fatalf("Users.ListEmails() returned error: %v", err)
}
var found bool
for _, e := range emails {
if e.Email != nil && *e.Email == email {
found = true
break
}
}
if !found {
t.Fatalf("Users.ListEmails() does not contain new addres: %v", email)
}
// Remove new address
_, err = client.Users.DeleteEmails([]string{email})
if err != nil {
t.Fatalf("Users.DeleteEmails() returned error: %v", err)
}
// List emails again and verify new email was removed
emails, _, err = client.Users.ListEmails(nil)
if err != nil {
t.Fatalf("Users.ListEmails() returned error: %v", err)
}
for _, e := range emails {
if e.Email != nil && *e.Email == email {
t.Fatalf("Users.ListEmails() still contains address %v after removing it", email)
}
}
}
func TestUsers_Keys(t *testing.T) {
keys, _, err := client.Users.ListKeys("willnorris", nil)
if err != nil {
t.Fatalf("Users.ListKeys('willnorris') returned error: %v", err)
}
if len(keys) == 0 {
t.Errorf("Users.ListKeys('willnorris') returned no keys")
}
// the rest of the tests requires auth
if !checkAuth("TestUsers_Keys") {
return
}
// TODO: make this integration test work for any authenticated user.
keys, _, err = client.Users.ListKeys("", nil)
if err != nil {
t.Fatalf("Users.ListKeys('') returned error: %v", err)
}
// ssh public key for testing (fingerprint: a7:22:ad:8c:36:9f:68:65:eb:ae:a1:e4:59:73:c1:76)
key := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCy/RIqaMFj2wjkOEjx9EAU0ReLAIhodga82/feo5nnT9UUkHLbL9xrIavfdLHx28lD3xYgPfAoSicUMaAeNwuQhmuerr2c2LFGxzrdXP8pVsQ+Ol7y7OdmFPfe0KrzoZaLJs9aSiZ4VKyY4z5Se/k2UgcJTdgQVlLfw/P96aqCx8yUu94BiWqkDqYEvgWKRNHrTiIo1EXeVBCCcfgNZe1suFfNJUJSUU2T3EG2bpwBbSOCjE3FyH8+Lz3K3BOGzm3df8E7Regj9j4YIcD8cWJYO86jLJoGgQ0L5MSOq+ishNaHQXech22Ix03D1lVMjCvDT7S/C94Z1LzhI2lhvyff"
for _, k := range keys {
if k.Key != nil && *k.Key == key {
t.Fatalf("Test key already exists for user. Please manually remove it first.")
}
}
// Add new key
_, _, err = client.Users.CreateKey(&github.Key{
Title: github.String("go-github test key"),
Key: github.String(key),
})
if err != nil {
t.Fatalf("Users.CreateKey() returned error: %v", err)
}
// List keys again and verify new key is present
keys, _, err = client.Users.ListKeys("", nil)
if err != nil {
t.Fatalf("Users.ListKeys('') returned error: %v", err)
}
var id int
for _, k := range keys {
if k.Key != nil && *k.Key == key {
id = *k.ID
break
}
}
if id == 0 {
t.Fatalf("Users.ListKeys('') does not contain added test key")
}
// Verify that fetching individual key works
k, _, err := client.Users.GetKey(id)
if err != nil {
t.Fatalf("Users.GetKey(%q) returned error: %v", id, err)
}
if *k.Key != key {
t.Fatalf("Users.GetKey(%q) returned key %v, want %v", id, *k.Key, key)
}
// Remove test key
_, err = client.Users.DeleteKey(id)
if err != nil {
t.Fatalf("Users.DeleteKey(%d) returned error: %v", id, err)
}
// List keys again and verify test key was removed
keys, _, err = client.Users.ListKeys("", nil)
if err != nil {
t.Fatalf("Users.ListKeys('') returned error: %v", err)
}
for _, k := range keys {
if k.Key != nil && *k.Key == key {
t.Fatalf("Users.ListKeys('') still contains test key after removing it")
}
}
}