misc: replaced glide with go dep

This commit is contained in:
evilsocket 2018-04-17 19:04:45 +02:00
parent a2e90769fe
commit 6b6078d30d
No known key found for this signature in database
GPG key ID: 1564D7F30393A456
533 changed files with 298 additions and 128052 deletions

View file

@ -1,2 +0,0 @@
*.test
coverage.out

View file

@ -1,29 +0,0 @@
sudo: false
language: go
go:
- 1.9.x
- 1.8.x
- 1.7.x
- master
matrix:
allow_failures:
- go: master
fast_finish: true
env:
secure: "IrnPmy/rkIP6Nrbqji+u7MCAibQlA6WvPLEllmDQ2yZP/uIe3wLwwYbTu9BOkgzoLA+f8PA6u3pp/RhY/rtaM4NzHAO2nVfGIv9UHUQ3NGq0DYS6rODjVKhq7vkhELoagRewyqFVN4rE0LnExkknRMgjQfRke6/DA7u7Xm8JyhY=" # COVERALLS_TOKEN
install:
- go get golang.org/x/tools/cmd/cover
- go get github.com/mattn/goveralls
- # Do not install go-github yet, since we want it to happen inside the script step.
script:
- go get -t -v ./...
- diff -u <(echo -n) <(gofmt -d -s .)
- go generate -x ./... && git diff --exit-code; code=$?; git checkout -- .; (exit $code) # Check that go generate ./... produces a zero diff; clean up any changes afterwards.
- go tool vet .
- go test -v -race ./...
- go test -v -tags=integration -run=^$ ./test/integration # Check that integration test builds successfully, but don't run any of the tests (they hit live GitHub API).
# Generate test coverage report. This must be after all other tests.
#- rm github/github-accessors.go # exclude generated code
#- go test -v -covermode=count -coverprofile=coverage.out ./github
#- $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN

View file

@ -1,114 +0,0 @@
# How to contribute #
We'd love to accept your patches and contributions to this project. There are
a just a few small guidelines you need to follow.
## Contributor License Agreement ##
Contributions to any Google project must be accompanied by a Contributor
License Agreement. This is not a copyright **assignment**, it simply gives
Google permission to use and redistribute your contributions as part of the
project. Head over to <https://cla.developers.google.com/> to see your current
agreements on file or to sign a new one.
You generally only need to submit a CLA once, so if you've already submitted one
(even if it was for a different project), you probably don't need to do it
again.
## Submitting a patch ##
1. It's generally best to start by opening a new issue describing the bug or
feature you're intending to fix. Even if you think it's relatively minor,
it's helpful to know what people are working on. Mention in the initial
issue that you are planning to work on that bug or feature so that it can
be assigned to you.
1. Follow the normal process of [forking][] the project, and setup a new
branch to work in. It's important that each group of changes be done in
separate branches in order to ensure that a pull request only includes the
commits related to that bug or feature.
1. Go makes it very simple to ensure properly formatted code, so always run
`go fmt` on your code before committing it. You should also run
[golint][] over your code. As noted in the [golint readme][], it's not
strictly necessary that your code be completely "lint-free", but this will
help you find common style issues.
1. Any significant changes should almost always be accompanied by tests. The
project already has good test coverage, so look at some of the existing
tests if you're unsure how to go about it. [gocov][] and [gocov-html][]
are invaluable tools for seeing which parts of your code aren't being
exercised by your tests.
1. Please run:
* `go generate github.com/google/go-github/...`
* `go test github.com/google/go-github/...`
* `go vet github.com/google/go-github/...`
1. Do your best to have [well-formed commit messages][] for each change.
This provides consistency throughout the project, and ensures that commit
messages are able to be formatted properly by various git tools.
1. Finally, push the commits to your fork and submit a [pull request][].
[forking]: https://help.github.com/articles/fork-a-repo
[golint]: https://github.com/golang/lint
[golint readme]: https://github.com/golang/lint/blob/master/README.md
[gocov]: https://github.com/axw/gocov
[gocov-html]: https://github.com/matm/gocov-html
[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
[squash]: http://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits
[pull request]: https://help.github.com/articles/creating-a-pull-request
## Other notes on code organization ##
Currently, everything is defined in the main `github` package, with API methods
broken into separate service objects. These services map directly to how
the [GitHub API documentation][] is organized, so use that as your guide for
where to put new methods.
Code is organized in files also based pretty closely on the GitHub API
documentation, following the format `{service}_{api}.go`. For example, methods
defined at <https://developer.github.com/v3/repos/hooks/> live in
[repos_hooks.go][].
[GitHub API documentation]: https://developer.github.com/v3/
[repos_hooks.go]: https://github.com/google/go-github/blob/master/github/repos_hooks.go
## Maintainer's Guide ##
(These notes are mostly only for people merging in pull requests.)
**Verify CLAs.** CLAs must be on file for the pull request submitter and commit
author(s). Google's CLA verification system should handle this automatically
and will set commit statuses as appropriate. If there's ever any question about
a pull request, ask [willnorris](https://github.com/willnorris).
**Always try to maintain a clean, linear git history.** With very few
exceptions, running `git log` should not show a bunch of branching and merging.
Never use the GitHub "merge" button, since it always creates a merge commit.
Instead, check out the pull request locally ([these git aliases
help][git-aliases]), then cherry-pick or rebase them onto master. If there are
small cleanup commits, especially as a result of addressing code review
comments, these should almost always be squashed down to a single commit. Don't
bother squashing commits that really deserve to be separate though. If needed,
feel free to amend additional small changes to the code or commit message that
aren't worth going through code review for.
If you made any changes like squashing commits, rebasing onto master, etc, then
GitHub won't recognize that this is the same commit in order to mark the pull
request as "merged". So instead, amend the commit message to include a line
"Fixes #0", referencing the pull request number. This would be in addition to
any other "Fixes" lines for closing related issues. If you forget to do this,
you can also leave a comment on the pull request [like this][rebase-comment].
If you made any other changes, it's worth noting that as well, [like
this][modified-comment].
[git-aliases]: https://github.com/willnorris/dotfiles/blob/d640d010c23b1116bdb3d4dc12088ed26120d87d/git/.gitconfig#L13-L15
[rebase-comment]: https://github.com/google/go-github/pull/277#issuecomment-183035491
[modified-comment]: https://github.com/google/go-github/pull/280#issuecomment-184859046

View file

@ -1,244 +0,0 @@
# go-github #
go-github is a Go client library for accessing the [GitHub API v3][].
**Documentation:** [![GoDoc](https://godoc.org/github.com/google/go-github/github?status.svg)](https://godoc.org/github.com/google/go-github/github)
**Mailing List:** [go-github@googlegroups.com](https://groups.google.com/group/go-github)
**Build Status:** [![Build Status](https://travis-ci.org/google/go-github.svg?branch=master)](https://travis-ci.org/google/go-github)
**Test Coverage:** [![Test Coverage](https://coveralls.io/repos/google/go-github/badge.svg?branch=master)](https://coveralls.io/r/google/go-github?branch=master)
go-github requires Go version 1.7 or greater.
If you're interested in using the [GraphQL API v4][], the recommended library is
[shurcooL/githubql][].
## Usage ##
```go
import "github.com/google/go-github/github"
```
Construct a new GitHub client, then use the various services on the client to
access different parts of the GitHub API. For example:
```go
client := github.NewClient(nil)
// list all organizations for user "willnorris"
orgs, _, err := client.Organizations.List(ctx, "willnorris", nil)
```
Some API methods have optional parameters that can be passed. For example:
```go
client := github.NewClient(nil)
// list public repositories for org "github"
opt := &github.RepositoryListByOrgOptions{Type: "public"}
repos, _, err := client.Repositories.ListByOrg(ctx, "github", opt)
```
The services of a client divide the API into logical chunks and correspond to
the structure of the GitHub API documentation at
https://developer.github.com/v3/.
### Authentication ###
The go-github library does not directly handle authentication. Instead, when
creating a new client, pass an `http.Client` that can handle authentication for
you. The easiest and recommended way to do this is using the [oauth2][]
library, but you can always use any other library that provides an
`http.Client`. If you have an OAuth2 access token (for example, a [personal
API token][]), you can use it with the oauth2 library using:
```go
import "golang.org/x/oauth2"
func main() {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: "... your access token ..."},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
// list all repositories for the authenticated user
repos, _, err := client.Repositories.List(ctx, "", nil)
}
```
Note that when using an authenticated Client, all calls made by the client will
include the specified OAuth token. Therefore, authenticated clients should
almost never be shared between different users.
See the [oauth2 docs][] for complete instructions on using that library.
For API methods that require HTTP Basic Authentication, use the
[`BasicAuthTransport`](https://godoc.org/github.com/google/go-github/github#BasicAuthTransport).
GitHub Apps authentication can be provided by the [ghinstallation](https://github.com/bradleyfalzon/ghinstallation)
package.
```go
import "github.com/bradleyfalzon/ghinstallation"
func main() {
// Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99.
itr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, "2016-10-19.private-key.pem")
if err != nil {
// Handle error.
}
// Use installation transport with client.
client := github.NewClient(&http.Client{Transport: itr})
// Use client...
}
```
### Rate Limiting ###
GitHub imposes a rate limit on all API clients. Unauthenticated clients are
limited to 60 requests per hour, while authenticated clients can make up to
5,000 requests per hour. The Search API has a custom rate limit. Unauthenticated
clients are limited to 10 requests per minute, while authenticated clients
can make up to 30 requests per minute. To receive the higher rate limit when
making calls that are not issued on behalf of a user,
use `UnauthenticatedRateLimitedTransport`.
The returned `Response.Rate` value contains the rate limit information
from the most recent API call. If a recent enough response isn't
available, you can use `RateLimits` to fetch the most up-to-date rate
limit data for the client.
To detect an API rate limit error, you can check if its type is `*github.RateLimitError`:
```go
repos, _, err := client.Repositories.List(ctx, "", nil)
if _, ok := err.(*github.RateLimitError); ok {
log.Println("hit rate limit")
}
```
Learn more about GitHub rate limiting at
https://developer.github.com/v3/#rate-limiting.
### Accepted Status ###
Some endpoints may return a 202 Accepted status code, meaning that the
information required is not yet ready and was scheduled to be gathered on
the GitHub side. Methods known to behave like this are documented specifying
this behavior.
To detect this condition of error, you can check if its type is
`*github.AcceptedError`:
```go
stats, _, err := client.Repositories.ListContributorsStats(ctx, org, repo)
if _, ok := err.(*github.AcceptedError); ok {
log.Println("scheduled on GitHub side")
}
```
### Conditional Requests ###
The GitHub API has good support for conditional requests which will help
prevent you from burning through your rate limit, as well as help speed up your
application. `go-github` does not handle conditional requests directly, but is
instead designed to work with a caching `http.Transport`. We recommend using
https://github.com/gregjones/httpcache for that.
Learn more about GitHub conditional requests at
https://developer.github.com/v3/#conditional-requests.
### Creating and Updating Resources ###
All structs for GitHub resources use pointer values for all non-repeated fields.
This allows distinguishing between unset fields and those set to a zero-value.
Helper functions have been provided to easily create these pointers for string,
bool, and int values. For example:
```go
// create a new private repository named "foo"
repo := &github.Repository{
Name: github.String("foo"),
Private: github.Bool(true),
}
client.Repositories.Create(ctx, "", repo)
```
Users who have worked with protocol buffers should find this pattern familiar.
### Pagination ###
All requests for resource collections (repos, pull requests, issues, etc.)
support pagination. Pagination options are described in the
`github.ListOptions` struct and passed to the list methods directly or as an
embedded type of a more specific list options struct (for example
`github.PullRequestListOptions`). Pages information is available via the
`github.Response` struct.
```go
client := github.NewClient(nil)
opt := &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 10},
}
// get all pages of results
var allRepos []*github.Repository
for {
repos, resp, err := client.Repositories.ListByOrg(ctx, "github", opt)
if err != nil {
return err
}
allRepos = append(allRepos, repos...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
```
For complete usage of go-github, see the full [package docs][].
[GitHub API v3]: https://developer.github.com/v3/
[oauth2]: https://github.com/golang/oauth2
[oauth2 docs]: https://godoc.org/golang.org/x/oauth2
[personal API token]: https://github.com/blog/1509-personal-api-tokens
[package docs]: https://godoc.org/github.com/google/go-github/github
[GraphQL API v4]: https://developer.github.com/v4/
[shurcooL/githubql]: https://github.com/shurcooL/githubql
### Google App Engine ###
Go on App Engine Classic (which as of this writing uses Go 1.6) can not use
the `"context"` import and still relies on `"golang.org/x/net/context"`.
As a result, if you wish to continue to use `go-github` on App Engine Classic,
you will need to rewrite all the `"context"` imports using the following command:
gofmt -w -r '"context" -> "golang.org/x/net/context"' *.go
See `with_appengine.go` for more details.
### Integration Tests ###
You can run integration tests from the `test` directory. See the integration tests [README](test/README.md).
## Roadmap ##
This library is being initially developed for an internal application at
Google, so API methods will likely be implemented in the order that they are
needed by that application. You can track the status of implementation in
[this Google spreadsheet][roadmap]. Eventually, I would like to cover the entire
GitHub API, so contributions are of course [always welcome][contributing]. The
calling pattern is pretty well established, so adding new methods is relatively
straightforward.
[roadmap]: https://docs.google.com/spreadsheet/ccc?key=0ApoVX4GOiXr-dGNKN1pObFh6ek1DR2FKUjBNZ1FmaEE&usp=sharing
[contributing]: CONTRIBUTING.md
## License ##
This library is distributed under the BSD-style license found in the [LICENSE](./LICENSE)
file.

View file

@ -1,49 +0,0 @@
// Copyright 2017 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.
// Package demo provides an app that shows how to use the github package on
// Google App Engine.
package demo
import (
"fmt"
"net/http"
"os"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
)
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
ctx := appengine.NewContext(r)
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("GITHUB_AUTH_TOKEN")},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
commits, _, err := client.Repositories.ListCommits(ctx, "google", "go-github", nil)
if err != nil {
log.Errorf(ctx, "ListCommits: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
for _, commit := range commits {
fmt.Fprintln(w, commit.GetHTMLURL())
}
}

View file

@ -1,14 +0,0 @@
# Copyright 2017 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.
runtime: go
api_version: go1
handlers:
- url: /.*
script: _go_app
env_variables:
GITHUB_AUTH_TOKEN: "-your-auth-token-here-"

View file

@ -1,55 +0,0 @@
// Copyright 2015 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.
// The basicauth command demonstrates using the github.BasicAuthTransport,
// including handling two-factor authentication. This won't currently work for
// accounts that use SMS to receive one-time passwords.
package main
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"syscall"
"github.com/google/go-github/github"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
r := bufio.NewReader(os.Stdin)
fmt.Print("GitHub Username: ")
username, _ := r.ReadString('\n')
fmt.Print("GitHub Password: ")
bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))
password := string(bytePassword)
tp := github.BasicAuthTransport{
Username: strings.TrimSpace(username),
Password: strings.TrimSpace(password),
}
client := github.NewClient(tp.Client())
ctx := context.Background()
user, _, err := client.Users.Get(ctx, "")
// Is this a two-factor auth error? If so, prompt for OTP and try again.
if _, ok := err.(*github.TwoFactorAuthError); ok {
fmt.Print("\nGitHub OTP: ")
otp, _ := r.ReadString('\n')
tp.OTP = strings.TrimSpace(otp)
user, _, err = client.Users.Get(ctx, "")
}
if err != nil {
fmt.Printf("\nerror: %v\n", err)
return
}
fmt.Printf("\n%v\n", github.Stringify(user))
}

View file

@ -1,349 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestActivityService_ListEvents(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
opt := &ListOptions{Page: 2}
events, _, err := client.Activity.ListEvents(context.Background(), opt)
if err != nil {
t.Errorf("Activities.ListEvents returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Activities.ListEvents returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListRepositoryEvents(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
opt := &ListOptions{Page: 2}
events, _, err := client.Activity.ListRepositoryEvents(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Activities.ListRepositoryEvents returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Activities.ListRepositoryEvents returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListRepositoryEvents_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Activity.ListRepositoryEvents(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestActivityService_ListIssueEventsForRepository(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":1},{"id":2}]`)
})
opt := &ListOptions{Page: 2}
events, _, err := client.Activity.ListIssueEventsForRepository(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Activities.ListIssueEventsForRepository returned error: %v", err)
}
want := []*IssueEvent{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Activities.ListIssueEventsForRepository returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListIssueEventsForRepository_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Activity.ListIssueEventsForRepository(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestActivityService_ListEventsForRepoNetwork(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/networks/o/r/events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
opt := &ListOptions{Page: 2}
events, _, err := client.Activity.ListEventsForRepoNetwork(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Activities.ListEventsForRepoNetwork returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Activities.ListEventsForRepoNetwork returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListEventsForRepoNetwork_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Activity.ListEventsForRepoNetwork(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestActivityService_ListEventsForOrganization(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
opt := &ListOptions{Page: 2}
events, _, err := client.Activity.ListEventsForOrganization(context.Background(), "o", opt)
if err != nil {
t.Errorf("Activities.ListEventsForOrganization returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Activities.ListEventsForOrganization returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListEventsForOrganization_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Activity.ListEventsForOrganization(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestActivityService_ListEventsPerformedByUser_all(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
opt := &ListOptions{Page: 2}
events, _, err := client.Activity.ListEventsPerformedByUser(context.Background(), "u", false, opt)
if err != nil {
t.Errorf("Events.ListPerformedByUser returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Events.ListPerformedByUser returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListEventsPerformedByUser_publicOnly(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/events/public", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
events, _, err := client.Activity.ListEventsPerformedByUser(context.Background(), "u", true, nil)
if err != nil {
t.Errorf("Events.ListPerformedByUser returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Events.ListPerformedByUser returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListEventsPerformedByUser_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Activity.ListEventsPerformedByUser(context.Background(), "%", false, nil)
testURLParseError(t, err)
}
func TestActivityService_ListEventsReceivedByUser_all(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/received_events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
opt := &ListOptions{Page: 2}
events, _, err := client.Activity.ListEventsReceivedByUser(context.Background(), "u", false, opt)
if err != nil {
t.Errorf("Events.ListReceivedByUser returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Events.ListReceivedUser returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListEventsReceivedByUser_publicOnly(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/received_events/public", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
events, _, err := client.Activity.ListEventsReceivedByUser(context.Background(), "u", true, nil)
if err != nil {
t.Errorf("Events.ListReceivedByUser returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Events.ListReceivedByUser returned %+v, want %+v", events, want)
}
}
func TestActivityService_ListEventsReceivedByUser_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Activity.ListEventsReceivedByUser(context.Background(), "%", false, nil)
testURLParseError(t, err)
}
func TestActivityService_ListUserEventsForOrganization(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/events/orgs/o", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`)
})
opt := &ListOptions{Page: 2}
events, _, err := client.Activity.ListUserEventsForOrganization(context.Background(), "o", "u", opt)
if err != nil {
t.Errorf("Activities.ListUserEventsForOrganization returned error: %v", err)
}
want := []*Event{{ID: String("1")}, {ID: String("2")}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Activities.ListUserEventsForOrganization returned %+v, want %+v", events, want)
}
}
func TestActivityService_EventParsePayload_typed(t *testing.T) {
raw := []byte(`{"type": "PushEvent","payload":{"push_id": 1}}`)
var event *Event
if err := json.Unmarshal(raw, &event); err != nil {
t.Fatalf("Unmarshal Event returned error: %v", err)
}
want := &PushEvent{PushID: Int64(1)}
got, err := event.ParsePayload()
if err != nil {
t.Fatalf("ParsePayload returned unexpected error: %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Event.ParsePayload returned %+v, want %+v", got, want)
}
}
// TestEvent_Payload_untyped checks that unrecognized events are parsed to an
// interface{} value (instead of being discarded or throwing an error), for
// forward compatibility with new event types.
func TestActivityService_EventParsePayload_untyped(t *testing.T) {
raw := []byte(`{"type": "UnrecognizedEvent","payload":{"field": "val"}}`)
var event *Event
if err := json.Unmarshal(raw, &event); err != nil {
t.Fatalf("Unmarshal Event returned error: %v", err)
}
want := map[string]interface{}{"field": "val"}
got, err := event.ParsePayload()
if err != nil {
t.Fatalf("ParsePayload returned unexpected error: %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Event.ParsePayload returned %+v, want %+v", got, want)
}
}
func TestActivityService_EventParsePayload_installation(t *testing.T) {
raw := []byte(`{"type": "PullRequestEvent","payload":{"installation":{"id":1}}}`)
var event *Event
if err := json.Unmarshal(raw, &event); err != nil {
t.Fatalf("Unmarshal Event returned error: %v", err)
}
want := &PullRequestEvent{Installation: &Installation{ID: Int64(1)}}
got, err := event.ParsePayload()
if err != nil {
t.Fatalf("ParsePayload returned unexpected error: %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Event.ParsePayload returned %+v, want %+v", got, want)
}
}

View file

@ -1,204 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestActivityService_ListNotification(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"all": "true",
"participating": "true",
"since": "2006-01-02T15:04:05Z",
"before": "2007-03-04T15:04:05Z",
})
fmt.Fprint(w, `[{"id":"1", "subject":{"title":"t"}}]`)
})
opt := &NotificationListOptions{
All: true,
Participating: true,
Since: time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC),
Before: time.Date(2007, 03, 04, 15, 04, 05, 0, time.UTC),
}
notifications, _, err := client.Activity.ListNotifications(context.Background(), opt)
if err != nil {
t.Errorf("Activity.ListNotifications returned error: %v", err)
}
want := []*Notification{{ID: String("1"), Subject: &NotificationSubject{Title: String("t")}}}
if !reflect.DeepEqual(notifications, want) {
t.Errorf("Activity.ListNotifications returned %+v, want %+v", notifications, want)
}
}
func TestActivityService_ListRepositoryNotification(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/notifications", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":"1"}]`)
})
notifications, _, err := client.Activity.ListRepositoryNotifications(context.Background(), "o", "r", nil)
if err != nil {
t.Errorf("Activity.ListRepositoryNotifications returned error: %v", err)
}
want := []*Notification{{ID: String("1")}}
if !reflect.DeepEqual(notifications, want) {
t.Errorf("Activity.ListRepositoryNotifications returned %+v, want %+v", notifications, want)
}
}
func TestActivityService_MarkNotificationsRead(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
testHeader(t, r, "Content-Type", "application/json")
testBody(t, r, `{"last_read_at":"2006-01-02T15:04:05Z"}`+"\n")
w.WriteHeader(http.StatusResetContent)
})
_, err := client.Activity.MarkNotificationsRead(context.Background(), time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC))
if err != nil {
t.Errorf("Activity.MarkNotificationsRead returned error: %v", err)
}
}
func TestActivityService_MarkRepositoryNotificationsRead(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/notifications", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
testHeader(t, r, "Content-Type", "application/json")
testBody(t, r, `{"last_read_at":"2006-01-02T15:04:05Z"}`+"\n")
w.WriteHeader(http.StatusResetContent)
})
_, err := client.Activity.MarkRepositoryNotificationsRead(context.Background(), "o", "r", time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC))
if err != nil {
t.Errorf("Activity.MarkRepositoryNotificationsRead returned error: %v", err)
}
}
func TestActivityService_GetThread(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/notifications/threads/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":"1"}`)
})
notification, _, err := client.Activity.GetThread(context.Background(), "1")
if err != nil {
t.Errorf("Activity.GetThread returned error: %v", err)
}
want := &Notification{ID: String("1")}
if !reflect.DeepEqual(notification, want) {
t.Errorf("Activity.GetThread returned %+v, want %+v", notification, want)
}
}
func TestActivityService_MarkThreadRead(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/notifications/threads/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PATCH")
w.WriteHeader(http.StatusResetContent)
})
_, err := client.Activity.MarkThreadRead(context.Background(), "1")
if err != nil {
t.Errorf("Activity.MarkThreadRead returned error: %v", err)
}
}
func TestActivityService_GetThreadSubscription(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"subscribed":true}`)
})
sub, _, err := client.Activity.GetThreadSubscription(context.Background(), "1")
if err != nil {
t.Errorf("Activity.GetThreadSubscription returned error: %v", err)
}
want := &Subscription{Subscribed: Bool(true)}
if !reflect.DeepEqual(sub, want) {
t.Errorf("Activity.GetThreadSubscription returned %+v, want %+v", sub, want)
}
}
func TestActivityService_SetThreadSubscription(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Subscription{Subscribed: Bool(true)}
mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) {
v := new(Subscription)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"ignored":true}`)
})
sub, _, err := client.Activity.SetThreadSubscription(context.Background(), "1", input)
if err != nil {
t.Errorf("Activity.SetThreadSubscription returned error: %v", err)
}
want := &Subscription{Ignored: Bool(true)}
if !reflect.DeepEqual(sub, want) {
t.Errorf("Activity.SetThreadSubscription returned %+v, want %+v", sub, want)
}
}
func TestActivityService_DeleteThreadSubscription(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Activity.DeleteThreadSubscription(context.Background(), "1")
if err != nil {
t.Errorf("Activity.DeleteThreadSubscription returned error: %v", err)
}
}

View file

@ -1,184 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestActivityService_ListStargazers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/stargazers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeStarringPreview)
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","user":{"id":1}}]`)
})
stargazers, _, err := client.Activity.ListStargazers(context.Background(), "o", "r", &ListOptions{Page: 2})
if err != nil {
t.Errorf("Activity.ListStargazers returned error: %v", err)
}
want := []*Stargazer{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, User: &User{ID: Int64(1)}}}
if !reflect.DeepEqual(stargazers, want) {
t.Errorf("Activity.ListStargazers returned %+v, want %+v", stargazers, want)
}
}
func TestActivityService_ListStarred_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/starred", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeStarringPreview)
fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","repo":{"id":1}}]`)
})
repos, _, err := client.Activity.ListStarred(context.Background(), "", nil)
if err != nil {
t.Errorf("Activity.ListStarred returned error: %v", err)
}
want := []*StarredRepository{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, Repository: &Repository{ID: Int64(1)}}}
if !reflect.DeepEqual(repos, want) {
t.Errorf("Activity.ListStarred returned %+v, want %+v", repos, want)
}
}
func TestActivityService_ListStarred_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/starred", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeStarringPreview)
testFormValues(t, r, values{
"sort": "created",
"direction": "asc",
"page": "2",
})
fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","repo":{"id":2}}]`)
})
opt := &ActivityListStarredOptions{"created", "asc", ListOptions{Page: 2}}
repos, _, err := client.Activity.ListStarred(context.Background(), "u", opt)
if err != nil {
t.Errorf("Activity.ListStarred returned error: %v", err)
}
want := []*StarredRepository{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, Repository: &Repository{ID: Int64(2)}}}
if !reflect.DeepEqual(repos, want) {
t.Errorf("Activity.ListStarred returned %+v, want %+v", repos, want)
}
}
func TestActivityService_ListStarred_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Activity.ListStarred(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestActivityService_IsStarred_hasStar(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNoContent)
})
star, _, err := client.Activity.IsStarred(context.Background(), "o", "r")
if err != nil {
t.Errorf("Activity.IsStarred returned error: %v", err)
}
if want := true; star != want {
t.Errorf("Activity.IsStarred returned %+v, want %+v", star, want)
}
}
func TestActivityService_IsStarred_noStar(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
star, _, err := client.Activity.IsStarred(context.Background(), "o", "r")
if err != nil {
t.Errorf("Activity.IsStarred returned error: %v", err)
}
if want := false; star != want {
t.Errorf("Activity.IsStarred returned %+v, want %+v", star, want)
}
}
func TestActivityService_IsStarred_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Activity.IsStarred(context.Background(), "%", "%")
testURLParseError(t, err)
}
func TestActivityService_Star(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
})
_, err := client.Activity.Star(context.Background(), "o", "r")
if err != nil {
t.Errorf("Activity.Star returned error: %v", err)
}
}
func TestActivityService_Star_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Activity.Star(context.Background(), "%", "%")
testURLParseError(t, err)
}
func TestActivityService_Unstar(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Activity.Unstar(context.Background(), "o", "r")
if err != nil {
t.Errorf("Activity.Unstar returned error: %v", err)
}
}
func TestActivityService_Unstar_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Activity.Unstar(context.Background(), "%", "%")
testURLParseError(t, err)
}

View file

@ -1,129 +0,0 @@
// 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.
package github
import (
"context"
"net/http"
"reflect"
"testing"
)
func TestActivityService_List(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/feeds", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusOK)
w.Write(feedsJSON)
})
got, _, err := client.Activity.ListFeeds(context.Background())
if err != nil {
t.Errorf("Activity.ListFeeds returned error: %v", err)
}
if want := wantFeeds; !reflect.DeepEqual(got, want) {
t.Errorf("Activity.ListFeeds = %+v, want %+v", got, want)
}
}
var feedsJSON = []byte(`{
"timeline_url": "https://github.com/timeline",
"user_url": "https://github.com/{user}",
"current_user_public_url": "https://github.com/defunkt",
"current_user_url": "https://github.com/defunkt.private?token=abc123",
"current_user_actor_url": "https://github.com/defunkt.private.actor?token=abc123",
"current_user_organization_url": "",
"current_user_organization_urls": [
"https://github.com/organizations/github/defunkt.private.atom?token=abc123"
],
"_links": {
"timeline": {
"href": "https://github.com/timeline",
"type": "application/atom+xml"
},
"user": {
"href": "https://github.com/{user}",
"type": "application/atom+xml"
},
"current_user_public": {
"href": "https://github.com/defunkt",
"type": "application/atom+xml"
},
"current_user": {
"href": "https://github.com/defunkt.private?token=abc123",
"type": "application/atom+xml"
},
"current_user_actor": {
"href": "https://github.com/defunkt.private.actor?token=abc123",
"type": "application/atom+xml"
},
"current_user_organization": {
"href": "",
"type": ""
},
"current_user_organizations": [
{
"href": "https://github.com/organizations/github/defunkt.private.atom?token=abc123",
"type": "application/atom+xml"
}
]
}
}`)
var wantFeeds = &Feeds{
TimelineURL: String("https://github.com/timeline"),
UserURL: String("https://github.com/{user}"),
CurrentUserPublicURL: String("https://github.com/defunkt"),
CurrentUserURL: String("https://github.com/defunkt.private?token=abc123"),
CurrentUserActorURL: String("https://github.com/defunkt.private.actor?token=abc123"),
CurrentUserOrganizationURL: String(""),
CurrentUserOrganizationURLs: []string{
"https://github.com/organizations/github/defunkt.private.atom?token=abc123",
},
Links: &struct {
Timeline *FeedLink `json:"timeline,omitempty"`
User *FeedLink `json:"user,omitempty"`
CurrentUserPublic *FeedLink `json:"current_user_public,omitempty"`
CurrentUser *FeedLink `json:"current_user,omitempty"`
CurrentUserActor *FeedLink `json:"current_user_actor,omitempty"`
CurrentUserOrganization *FeedLink `json:"current_user_organization,omitempty"`
CurrentUserOrganizations []FeedLink `json:"current_user_organizations,omitempty"`
}{
Timeline: &FeedLink{
HRef: String("https://github.com/timeline"),
Type: String("application/atom+xml"),
},
User: &FeedLink{
HRef: String("https://github.com/{user}"),
Type: String("application/atom+xml"),
},
CurrentUserPublic: &FeedLink{
HRef: String("https://github.com/defunkt"),
Type: String("application/atom+xml"),
},
CurrentUser: &FeedLink{
HRef: String("https://github.com/defunkt.private?token=abc123"),
Type: String("application/atom+xml"),
},
CurrentUserActor: &FeedLink{
HRef: String("https://github.com/defunkt.private.actor?token=abc123"),
Type: String("application/atom+xml"),
},
CurrentUserOrganization: &FeedLink{
HRef: String(""),
Type: String(""),
},
CurrentUserOrganizations: []FeedLink{
{
HRef: String("https://github.com/organizations/github/defunkt.private.atom?token=abc123"),
Type: String("application/atom+xml"),
},
},
},
}

View file

@ -1,184 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestActivityService_ListWatchers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/subscribers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
watchers, _, err := client.Activity.ListWatchers(context.Background(), "o", "r", &ListOptions{Page: 2})
if err != nil {
t.Errorf("Activity.ListWatchers returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(watchers, want) {
t.Errorf("Activity.ListWatchers returned %+v, want %+v", watchers, want)
}
}
func TestActivityService_ListWatched_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/subscriptions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
watched, _, err := client.Activity.ListWatched(context.Background(), "", &ListOptions{Page: 2})
if err != nil {
t.Errorf("Activity.ListWatched returned error: %v", err)
}
want := []*Repository{{ID: Int64(1)}}
if !reflect.DeepEqual(watched, want) {
t.Errorf("Activity.ListWatched returned %+v, want %+v", watched, want)
}
}
func TestActivityService_ListWatched_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/subscriptions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
watched, _, err := client.Activity.ListWatched(context.Background(), "u", &ListOptions{Page: 2})
if err != nil {
t.Errorf("Activity.ListWatched returned error: %v", err)
}
want := []*Repository{{ID: Int64(1)}}
if !reflect.DeepEqual(watched, want) {
t.Errorf("Activity.ListWatched returned %+v, want %+v", watched, want)
}
}
func TestActivityService_GetRepositorySubscription_true(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"subscribed":true}`)
})
sub, _, err := client.Activity.GetRepositorySubscription(context.Background(), "o", "r")
if err != nil {
t.Errorf("Activity.GetRepositorySubscription returned error: %v", err)
}
want := &Subscription{Subscribed: Bool(true)}
if !reflect.DeepEqual(sub, want) {
t.Errorf("Activity.GetRepositorySubscription returned %+v, want %+v", sub, want)
}
}
func TestActivityService_GetRepositorySubscription_false(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
sub, _, err := client.Activity.GetRepositorySubscription(context.Background(), "o", "r")
if err != nil {
t.Errorf("Activity.GetRepositorySubscription returned error: %v", err)
}
var want *Subscription
if !reflect.DeepEqual(sub, want) {
t.Errorf("Activity.GetRepositorySubscription returned %+v, want %+v", sub, want)
}
}
func TestActivityService_GetRepositorySubscription_error(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusBadRequest)
})
_, _, err := client.Activity.GetRepositorySubscription(context.Background(), "o", "r")
if err == nil {
t.Errorf("Expected HTTP 400 response")
}
}
func TestActivityService_SetRepositorySubscription(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Subscription{Subscribed: Bool(true)}
mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) {
v := new(Subscription)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"ignored":true}`)
})
sub, _, err := client.Activity.SetRepositorySubscription(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Activity.SetRepositorySubscription returned error: %v", err)
}
want := &Subscription{Ignored: Bool(true)}
if !reflect.DeepEqual(sub, want) {
t.Errorf("Activity.SetRepositorySubscription returned %+v, want %+v", sub, want)
}
}
func TestActivityService_DeleteRepositorySubscription(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Activity.DeleteRepositorySubscription(context.Background(), "o", "r")
if err != nil {
t.Errorf("Activity.DeleteRepositorySubscription returned error: %v", err)
}
}

View file

@ -1,142 +0,0 @@
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestAdminService_GetAdminStats(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/enterprise/stats/all", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `
{
"repos": {
"total_repos": 212,
"root_repos": 194,
"fork_repos": 18,
"org_repos": 51,
"total_pushes": 3082,
"total_wikis": 15
},
"hooks": {
"total_hooks": 27,
"active_hooks": 23,
"inactive_hooks": 4
},
"pages": {
"total_pages": 36
},
"orgs": {
"total_orgs": 33,
"disabled_orgs": 0,
"total_teams": 60,
"total_team_members": 314
},
"users": {
"total_users": 254,
"admin_users": 45,
"suspended_users": 21
},
"pulls": {
"total_pulls": 86,
"merged_pulls": 60,
"mergeable_pulls": 21,
"unmergeable_pulls": 3
},
"issues": {
"total_issues": 179,
"open_issues": 83,
"closed_issues": 96
},
"milestones": {
"total_milestones": 7,
"open_milestones": 6,
"closed_milestones": 1
},
"gists": {
"total_gists": 178,
"private_gists": 151,
"public_gists": 25
},
"comments": {
"total_commit_comments": 6,
"total_gist_comments": 28,
"total_issue_comments": 366,
"total_pull_request_comments": 30
}
}
`)
})
stats, _, err := client.Admin.GetAdminStats(context.Background())
if err != nil {
t.Errorf("AdminService.GetAdminStats returned error: %v", err)
}
want := &AdminStats{
Repos: &RepoStats{
TotalRepos: Int(212),
RootRepos: Int(194),
ForkRepos: Int(18),
OrgRepos: Int(51),
TotalPushes: Int(3082),
TotalWikis: Int(15),
},
Hooks: &HookStats{
TotalHooks: Int(27),
ActiveHooks: Int(23),
InactiveHooks: Int(4),
},
Pages: &PageStats{
TotalPages: Int(36),
},
Orgs: &OrgStats{
TotalOrgs: Int(33),
DisabledOrgs: Int(0),
TotalTeams: Int(60),
TotalTeamMembers: Int(314),
},
Users: &UserStats{
TotalUsers: Int(254),
AdminUsers: Int(45),
SuspendedUsers: Int(21),
},
Pulls: &PullStats{
TotalPulls: Int(86),
MergedPulls: Int(60),
MergablePulls: Int(21),
UnmergablePulls: Int(3),
},
Issues: &IssueStats{
TotalIssues: Int(179),
OpenIssues: Int(83),
ClosedIssues: Int(96),
},
Milestones: &MilestoneStats{
TotalMilestones: Int(7),
OpenMilestones: Int(6),
ClosedMilestones: Int(1),
},
Gists: &GistStats{
TotalGists: Int(178),
PrivateGists: Int(151),
PublicGists: Int(25),
},
Comments: &CommentStats{
TotalCommitComments: Int(6),
TotalGistComments: Int(28),
TotalIssueComments: Int(366),
TotalPullRequestComments: Int(30),
},
}
if !reflect.DeepEqual(stats, want) {
t.Errorf("AdminService.GetAdminStats returned %+v, want %+v", stats, want)
}
}

View file

@ -1,81 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestAdminService_UpdateUserLDAPMapping(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &UserLDAPMapping{
LDAPDN: String("uid=asdf,ou=users,dc=github,dc=com"),
}
mux.HandleFunc("/admin/ldap/users/u/mapping", func(w http.ResponseWriter, r *http.Request) {
v := new(UserLDAPMapping)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1,"ldap_dn":"uid=asdf,ou=users,dc=github,dc=com"}`)
})
mapping, _, err := client.Admin.UpdateUserLDAPMapping(context.Background(), "u", input)
if err != nil {
t.Errorf("Admin.UpdateUserLDAPMapping returned error: %v", err)
}
want := &UserLDAPMapping{
ID: Int64(1),
LDAPDN: String("uid=asdf,ou=users,dc=github,dc=com"),
}
if !reflect.DeepEqual(mapping, want) {
t.Errorf("Admin.UpdateUserLDAPMapping returned %+v, want %+v", mapping, want)
}
}
func TestAdminService_UpdateTeamLDAPMapping(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &TeamLDAPMapping{
LDAPDN: String("cn=Enterprise Ops,ou=teams,dc=github,dc=com"),
}
mux.HandleFunc("/admin/ldap/teams/1/mapping", func(w http.ResponseWriter, r *http.Request) {
v := new(TeamLDAPMapping)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1,"ldap_dn":"cn=Enterprise Ops,ou=teams,dc=github,dc=com"}`)
})
mapping, _, err := client.Admin.UpdateTeamLDAPMapping(context.Background(), 1, input)
if err != nil {
t.Errorf("Admin.UpdateTeamLDAPMapping returned error: %v", err)
}
want := &TeamLDAPMapping{
ID: Int64(1),
LDAPDN: String("cn=Enterprise Ops,ou=teams,dc=github,dc=com"),
}
if !reflect.DeepEqual(mapping, want) {
t.Errorf("Admin.UpdateTeamLDAPMapping returned %+v, want %+v", mapping, want)
}
}

View file

@ -1,101 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestAppsService_ListRepos(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/installation/repositories", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeIntegrationPreview)
testFormValues(t, r, values{
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `{"repositories": [{"id":1}]}`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
repositories, _, err := client.Apps.ListRepos(context.Background(), opt)
if err != nil {
t.Errorf("Apps.ListRepos returned error: %v", err)
}
want := []*Repository{{ID: Int64(1)}}
if !reflect.DeepEqual(repositories, want) {
t.Errorf("Apps.ListRepos returned %+v, want %+v", repositories, want)
}
}
func TestAppsService_ListUserRepos(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/installations/1/repositories", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeIntegrationPreview)
testFormValues(t, r, values{
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `{"repositories": [{"id":1}]}`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
repositories, _, err := client.Apps.ListUserRepos(context.Background(), 1, opt)
if err != nil {
t.Errorf("Apps.ListUserRepos returned error: %v", err)
}
want := []*Repository{{ID: Int64(1)}}
if !reflect.DeepEqual(repositories, want) {
t.Errorf("Apps.ListUserRepos returned %+v, want %+v", repositories, want)
}
}
func TestAppsService_AddRepository(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/apps/installations/1/repositories/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
fmt.Fprint(w, `{"id":1,"name":"n","description":"d","owner":{"login":"l"},"license":{"key":"mit"}}`)
})
repo, _, err := client.Apps.AddRepository(context.Background(), 1, 1)
if err != nil {
t.Errorf("Apps.AddRepository returned error: %v", err)
}
want := &Repository{ID: Int64(1), Name: String("n"), Description: String("d"), Owner: &User{Login: String("l")}, License: &License{Key: String("mit")}}
if !reflect.DeepEqual(repo, want) {
t.Errorf("AddRepository returned %+v, want %+v", repo, want)
}
}
func TestAppsService_RemoveRepository(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/apps/installations/1/repositories/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Apps.RemoveRepository(context.Background(), 1, 1)
if err != nil {
t.Errorf("Apps.RemoveRepository returned error: %v", err)
}
}

View file

@ -1,202 +0,0 @@
// Copyright 2017 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestMarketplaceService_ListPlans(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/marketplace_listing/plans", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMarketplacePreview)
testFormValues(t, r, values{
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
client.Marketplace.Stubbed = false
plans, _, err := client.Marketplace.ListPlans(context.Background(), opt)
if err != nil {
t.Errorf("Marketplace.ListPlans returned error: %v", err)
}
want := []*MarketplacePlan{{ID: Int64(1)}}
if !reflect.DeepEqual(plans, want) {
t.Errorf("Marketplace.ListPlans returned %+v, want %+v", plans, want)
}
}
func TestMarketplaceService_Stubbed_ListPlans(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/marketplace_listing/stubbed/plans", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMarketplacePreview)
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
client.Marketplace.Stubbed = true
plans, _, err := client.Marketplace.ListPlans(context.Background(), opt)
if err != nil {
t.Errorf("Marketplace.ListPlans (Stubbed) returned error: %v", err)
}
want := []*MarketplacePlan{{ID: Int64(1)}}
if !reflect.DeepEqual(plans, want) {
t.Errorf("Marketplace.ListPlans (Stubbed) returned %+v, want %+v", plans, want)
}
}
func TestMarketplaceService_ListPlanAccountsForPlan(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/marketplace_listing/plans/1/accounts", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMarketplacePreview)
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
client.Marketplace.Stubbed = false
accounts, _, err := client.Marketplace.ListPlanAccountsForPlan(context.Background(), 1, opt)
if err != nil {
t.Errorf("Marketplace.ListPlanAccountsForPlan returned error: %v", err)
}
want := []*MarketplacePlanAccount{{ID: Int64(1)}}
if !reflect.DeepEqual(accounts, want) {
t.Errorf("Marketplace.ListPlanAccountsForPlan returned %+v, want %+v", accounts, want)
}
}
func TestMarketplaceService_Stubbed_ListPlanAccountsForPlan(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/marketplace_listing/stubbed/plans/1/accounts", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMarketplacePreview)
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
client.Marketplace.Stubbed = true
accounts, _, err := client.Marketplace.ListPlanAccountsForPlan(context.Background(), 1, opt)
if err != nil {
t.Errorf("Marketplace.ListPlanAccountsForPlan (Stubbed) returned error: %v", err)
}
want := []*MarketplacePlanAccount{{ID: Int64(1)}}
if !reflect.DeepEqual(accounts, want) {
t.Errorf("Marketplace.ListPlanAccountsForPlan (Stubbed) returned %+v, want %+v", accounts, want)
}
}
func TestMarketplaceService_ListPlanAccountsForAccount(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/marketplace_listing/accounts/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMarketplacePreview)
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
client.Marketplace.Stubbed = false
accounts, _, err := client.Marketplace.ListPlanAccountsForAccount(context.Background(), 1, opt)
if err != nil {
t.Errorf("Marketplace.ListPlanAccountsForAccount returned error: %v", err)
}
want := []*MarketplacePlanAccount{{ID: Int64(1)}}
if !reflect.DeepEqual(accounts, want) {
t.Errorf("Marketplace.ListPlanAccountsForAccount returned %+v, want %+v", accounts, want)
}
}
func TestMarketplaceService_Stubbed_ListPlanAccountsForAccount(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/marketplace_listing/stubbed/accounts/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMarketplacePreview)
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
client.Marketplace.Stubbed = true
accounts, _, err := client.Marketplace.ListPlanAccountsForAccount(context.Background(), 1, opt)
if err != nil {
t.Errorf("Marketplace.ListPlanAccountsForAccount (Stubbed) returned error: %v", err)
}
want := []*MarketplacePlanAccount{{ID: Int64(1)}}
if !reflect.DeepEqual(accounts, want) {
t.Errorf("Marketplace.ListPlanAccountsForAccount (Stubbed) returned %+v, want %+v", accounts, want)
}
}
func TestMarketplaceService_ListMarketplacePurchasesForUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/marketplace_purchases", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMarketplacePreview)
fmt.Fprint(w, `[{"billing_cycle":"monthly"}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
client.Marketplace.Stubbed = false
purchases, _, err := client.Marketplace.ListMarketplacePurchasesForUser(context.Background(), opt)
if err != nil {
t.Errorf("Marketplace.ListMarketplacePurchasesForUser returned error: %v", err)
}
want := []*MarketplacePurchase{{BillingCycle: String("monthly")}}
if !reflect.DeepEqual(purchases, want) {
t.Errorf("Marketplace.ListMarketplacePurchasesForUser returned %+v, want %+v", purchases, want)
}
}
func TestMarketplaceService_Stubbed_ListMarketplacePurchasesForUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/marketplace_purchases/stubbed", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMarketplacePreview)
fmt.Fprint(w, `[{"billing_cycle":"monthly"}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
client.Marketplace.Stubbed = true
purchases, _, err := client.Marketplace.ListMarketplacePurchasesForUser(context.Background(), opt)
if err != nil {
t.Errorf("Marketplace.ListMarketplacePurchasesForUser returned error: %v", err)
}
want := []*MarketplacePurchase{{BillingCycle: String("monthly")}}
if !reflect.DeepEqual(purchases, want) {
t.Errorf("Marketplace.ListMarketplacePurchasesForUser returned %+v, want %+v", purchases, want)
}
}

View file

@ -1,150 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestAppsService_Get_authenticatedApp(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/app", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeIntegrationPreview)
fmt.Fprint(w, `{"id":1}`)
})
app, _, err := client.Apps.Get(context.Background(), "")
if err != nil {
t.Errorf("Apps.Get returned error: %v", err)
}
want := &App{ID: Int64(1)}
if !reflect.DeepEqual(app, want) {
t.Errorf("Apps.Get returned %+v, want %+v", app, want)
}
}
func TestAppsService_Get_specifiedApp(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/apps/a", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeIntegrationPreview)
fmt.Fprint(w, `{"html_url":"https://github.com/apps/a"}`)
})
app, _, err := client.Apps.Get(context.Background(), "a")
if err != nil {
t.Errorf("Apps.Get returned error: %v", err)
}
want := &App{HTMLURL: String("https://github.com/apps/a")}
if !reflect.DeepEqual(app, want) {
t.Errorf("Apps.Get returned %+v, want %+v", *app.HTMLURL, *want.HTMLURL)
}
}
func TestAppsService_ListInstallations(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/app/installations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeIntegrationPreview)
testFormValues(t, r, values{
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
installations, _, err := client.Apps.ListInstallations(context.Background(), opt)
if err != nil {
t.Errorf("Apps.ListInstallations returned error: %v", err)
}
want := []*Installation{{ID: Int64(1)}}
if !reflect.DeepEqual(installations, want) {
t.Errorf("Apps.ListInstallations returned %+v, want %+v", installations, want)
}
}
func TestAppsService_GetInstallation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/app/installations/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeIntegrationPreview)
fmt.Fprint(w, `{"id":1}`)
})
installation, _, err := client.Apps.GetInstallation(context.Background(), 1)
if err != nil {
t.Errorf("Apps.GetInstallation returned error: %v", err)
}
want := &Installation{ID: Int64(1)}
if !reflect.DeepEqual(installation, want) {
t.Errorf("Apps.GetInstallation returned %+v, want %+v", installation, want)
}
}
func TestAppsService_ListUserInstallations(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/installations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeIntegrationPreview)
testFormValues(t, r, values{
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `{"installations":[{"id":1}]}`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
installations, _, err := client.Apps.ListUserInstallations(context.Background(), opt)
if err != nil {
t.Errorf("Apps.ListUserInstallations returned error: %v", err)
}
want := []*Installation{{ID: Int64(1)}}
if !reflect.DeepEqual(installations, want) {
t.Errorf("Apps.ListUserInstallations returned %+v, want %+v", installations, want)
}
}
func TestAppsService_CreateInstallationToken(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/installations/1/access_tokens", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeIntegrationPreview)
fmt.Fprint(w, `{"token":"t"}`)
})
token, _, err := client.Apps.CreateInstallationToken(context.Background(), 1)
if err != nil {
t.Errorf("Apps.CreateInstallationToken returned error: %v", err)
}
want := &InstallationToken{Token: String("t")}
if !reflect.DeepEqual(token, want) {
t.Errorf("Apps.CreateInstallationToken returned %+v, want %+v", token, want)
}
}

View file

@ -1,359 +0,0 @@
// Copyright 2015 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestAuthorizationsService_List(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/authorizations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "1", "per_page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
got, _, err := client.Authorizations.List(context.Background(), opt)
if err != nil {
t.Errorf("Authorizations.List returned error: %v", err)
}
want := []*Authorization{{ID: Int64(1)}}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorizations.List returned %+v, want %+v", *got[0].ID, *want[0].ID)
}
}
func TestAuthorizationsService_Get(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/authorizations/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
got, _, err := client.Authorizations.Get(context.Background(), 1)
if err != nil {
t.Errorf("Authorizations.Get returned error: %v", err)
}
want := &Authorization{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorizations.Get returned auth %+v, want %+v", got, want)
}
}
func TestAuthorizationsService_Create(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &AuthorizationRequest{
Note: String("test"),
}
mux.HandleFunc("/authorizations", func(w http.ResponseWriter, r *http.Request) {
v := new(AuthorizationRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"ID":1}`)
})
got, _, err := client.Authorizations.Create(context.Background(), input)
if err != nil {
t.Errorf("Authorizations.Create returned error: %v", err)
}
want := &Authorization{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorization.Create returned %+v, want %+v", got, want)
}
}
func TestAuthorizationsService_GetOrCreateForApp(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &AuthorizationRequest{
Note: String("test"),
}
mux.HandleFunc("/authorizations/clients/id", func(w http.ResponseWriter, r *http.Request) {
v := new(AuthorizationRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"ID":1}`)
})
got, _, err := client.Authorizations.GetOrCreateForApp(context.Background(), "id", input)
if err != nil {
t.Errorf("Authorizations.GetOrCreateForApp returned error: %v", err)
}
want := &Authorization{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorization.GetOrCreateForApp returned %+v, want %+v", got, want)
}
}
func TestAuthorizationsService_GetOrCreateForApp_Fingerprint(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &AuthorizationRequest{
Note: String("test"),
Fingerprint: String("fp"),
}
mux.HandleFunc("/authorizations/clients/id/fp", func(w http.ResponseWriter, r *http.Request) {
v := new(AuthorizationRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"ID":1}`)
})
got, _, err := client.Authorizations.GetOrCreateForApp(context.Background(), "id", input)
if err != nil {
t.Errorf("Authorizations.GetOrCreateForApp returned error: %v", err)
}
want := &Authorization{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorization.GetOrCreateForApp returned %+v, want %+v", got, want)
}
}
func TestAuthorizationsService_Edit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &AuthorizationUpdateRequest{
Note: String("test"),
}
mux.HandleFunc("/authorizations/1", func(w http.ResponseWriter, r *http.Request) {
v := new(AuthorizationUpdateRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"ID":1}`)
})
got, _, err := client.Authorizations.Edit(context.Background(), 1, input)
if err != nil {
t.Errorf("Authorizations.Edit returned error: %v", err)
}
want := &Authorization{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorization.Update returned %+v, want %+v", got, want)
}
}
func TestAuthorizationsService_Delete(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/authorizations/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Authorizations.Delete(context.Background(), 1)
if err != nil {
t.Errorf("Authorizations.Delete returned error: %v", err)
}
}
func TestAuthorizationsService_Check(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/applications/id/tokens/t", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
got, _, err := client.Authorizations.Check(context.Background(), "id", "t")
if err != nil {
t.Errorf("Authorizations.Check returned error: %v", err)
}
want := &Authorization{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorizations.Check returned auth %+v, want %+v", got, want)
}
}
func TestAuthorizationsService_Reset(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/applications/id/tokens/t", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
fmt.Fprint(w, `{"ID":1}`)
})
got, _, err := client.Authorizations.Reset(context.Background(), "id", "t")
if err != nil {
t.Errorf("Authorizations.Reset returned error: %v", err)
}
want := &Authorization{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorizations.Reset returned auth %+v, want %+v", got, want)
}
}
func TestAuthorizationsService_Revoke(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/applications/id/tokens/t", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Authorizations.Revoke(context.Background(), "id", "t")
if err != nil {
t.Errorf("Authorizations.Revoke returned error: %v", err)
}
}
func TestListGrants(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/applications/grants", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id": 1}]`)
})
got, _, err := client.Authorizations.ListGrants(context.Background(), nil)
if err != nil {
t.Errorf("OAuthAuthorizations.ListGrants returned error: %v", err)
}
want := []*Grant{{ID: Int64(1)}}
if !reflect.DeepEqual(got, want) {
t.Errorf("OAuthAuthorizations.ListGrants = %+v, want %+v", got, want)
}
}
func TestListGrants_withOptions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/applications/grants", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id": 1}]`)
})
_, _, err := client.Authorizations.ListGrants(context.Background(), &ListOptions{Page: 2})
if err != nil {
t.Errorf("OAuthAuthorizations.ListGrants returned error: %v", err)
}
}
func TestGetGrant(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/applications/grants/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id": 1}`)
})
got, _, err := client.Authorizations.GetGrant(context.Background(), 1)
if err != nil {
t.Errorf("OAuthAuthorizations.GetGrant returned error: %v", err)
}
want := &Grant{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("OAuthAuthorizations.GetGrant = %+v, want %+v", got, want)
}
}
func TestDeleteGrant(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/applications/grants/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Authorizations.DeleteGrant(context.Background(), 1)
if err != nil {
t.Errorf("OAuthAuthorizations.DeleteGrant returned error: %v", err)
}
}
func TestAuthorizationsService_CreateImpersonation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/admin/users/u/authorizations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
fmt.Fprint(w, `{"id":1}`)
})
req := &AuthorizationRequest{Scopes: []Scope{ScopePublicRepo}}
got, _, err := client.Authorizations.CreateImpersonation(context.Background(), "u", req)
if err != nil {
t.Errorf("Authorizations.CreateImpersonation returned error: %+v", err)
}
want := &Authorization{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Authorizations.CreateImpersonation returned %+v, want %+v", *got.ID, *want.ID)
}
}
func TestAuthorizationsService_DeleteImpersonation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/admin/users/u/authorizations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Authorizations.DeleteImpersonation(context.Background(), "u")
if err != nil {
t.Errorf("Authorizations.DeleteImpersonation returned error: %+v", err)
}
}

View file

@ -1,76 +0,0 @@
// 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.
package github_test
import (
"context"
"fmt"
"log"
"github.com/google/go-github/github"
)
func ExampleClient_Markdown() {
client := github.NewClient(nil)
input := "# heading #\n\nLink to issue #1"
opt := &github.MarkdownOptions{Mode: "gfm", Context: "google/go-github"}
output, _, err := client.Markdown(context.Background(), input, opt)
if err != nil {
fmt.Println(err)
}
fmt.Println(output)
}
func ExampleRepositoriesService_GetReadme() {
client := github.NewClient(nil)
readme, _, err := client.Repositories.GetReadme(context.Background(), "google", "go-github", nil)
if err != nil {
fmt.Println(err)
return
}
content, err := readme.GetContent()
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("google/go-github README:\n%v\n", content)
}
func ExampleRepositoriesService_List() {
client := github.NewClient(nil)
user := "willnorris"
opt := &github.RepositoryListOptions{Type: "owner", Sort: "updated", Direction: "desc"}
repos, _, err := client.Repositories.List(context.Background(), user, opt)
if err != nil {
fmt.Println(err)
}
fmt.Printf("Recently updated repositories by %q: %v", user, github.Stringify(repos))
}
func ExampleUsersService_ListAll() {
client := github.NewClient(nil)
opts := &github.UserListOptions{}
for {
users, _, err := client.Users.ListAll(context.Background(), opts)
if err != nil {
log.Fatalf("error listing users: %v", err)
}
if len(users) == 0 {
break
}
opts.Since = *users[len(users)-1].ID
// Process users...
}
}

View file

@ -1,169 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestGistsService_ListComments(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id": 1}]`)
})
opt := &ListOptions{Page: 2}
comments, _, err := client.Gists.ListComments(context.Background(), "1", opt)
if err != nil {
t.Errorf("Gists.Comments returned error: %v", err)
}
want := []*GistComment{{ID: Int64(1)}}
if !reflect.DeepEqual(comments, want) {
t.Errorf("Gists.ListComments returned %+v, want %+v", comments, want)
}
}
func TestGistsService_ListComments_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.ListComments(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestGistsService_GetComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id": 1}`)
})
comment, _, err := client.Gists.GetComment(context.Background(), "1", 2)
if err != nil {
t.Errorf("Gists.GetComment returned error: %v", err)
}
want := &GistComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Gists.GetComment returned %+v, want %+v", comment, want)
}
}
func TestGistsService_GetComment_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.GetComment(context.Background(), "%", 1)
testURLParseError(t, err)
}
func TestGistsService_CreateComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &GistComment{ID: Int64(1), Body: String("b")}
mux.HandleFunc("/gists/1/comments", func(w http.ResponseWriter, r *http.Request) {
v := new(GistComment)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.Gists.CreateComment(context.Background(), "1", input)
if err != nil {
t.Errorf("Gists.CreateComment returned error: %v", err)
}
want := &GistComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Gists.CreateComment returned %+v, want %+v", comment, want)
}
}
func TestGistsService_CreateComment_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.CreateComment(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestGistsService_EditComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &GistComment{ID: Int64(1), Body: String("b")}
mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) {
v := new(GistComment)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.Gists.EditComment(context.Background(), "1", 2, input)
if err != nil {
t.Errorf("Gists.EditComment returned error: %v", err)
}
want := &GistComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Gists.EditComment returned %+v, want %+v", comment, want)
}
}
func TestGistsService_EditComment_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.EditComment(context.Background(), "%", 1, nil)
testURLParseError(t, err)
}
func TestGistsService_DeleteComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Gists.DeleteComment(context.Background(), "1", 2)
if err != nil {
t.Errorf("Gists.Delete returned error: %v", err)
}
}
func TestGistsService_DeleteComment_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Gists.DeleteComment(context.Background(), "%", 1)
testURLParseError(t, err)
}

View file

@ -1,546 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestGistsService_List_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
since := "2013-01-01T00:00:00Z"
mux.HandleFunc("/users/u/gists", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{
"since": since,
})
fmt.Fprint(w, `[{"id": "1"}]`)
})
opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)}
gists, _, err := client.Gists.List(context.Background(), "u", opt)
if err != nil {
t.Errorf("Gists.List returned error: %v", err)
}
want := []*Gist{{ID: String("1")}}
if !reflect.DeepEqual(gists, want) {
t.Errorf("Gists.List returned %+v, want %+v", gists, want)
}
}
func TestGistsService_List_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `[{"id": "1"}]`)
})
gists, _, err := client.Gists.List(context.Background(), "", nil)
if err != nil {
t.Errorf("Gists.List returned error: %v", err)
}
want := []*Gist{{ID: String("1")}}
if !reflect.DeepEqual(gists, want) {
t.Errorf("Gists.List returned %+v, want %+v", gists, want)
}
}
func TestGistsService_List_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.List(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestGistsService_ListAll(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
since := "2013-01-01T00:00:00Z"
mux.HandleFunc("/gists/public", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{
"since": since,
})
fmt.Fprint(w, `[{"id": "1"}]`)
})
opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)}
gists, _, err := client.Gists.ListAll(context.Background(), opt)
if err != nil {
t.Errorf("Gists.ListAll returned error: %v", err)
}
want := []*Gist{{ID: String("1")}}
if !reflect.DeepEqual(gists, want) {
t.Errorf("Gists.ListAll returned %+v, want %+v", gists, want)
}
}
func TestGistsService_ListStarred(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
since := "2013-01-01T00:00:00Z"
mux.HandleFunc("/gists/starred", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{
"since": since,
})
fmt.Fprint(w, `[{"id": "1"}]`)
})
opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)}
gists, _, err := client.Gists.ListStarred(context.Background(), opt)
if err != nil {
t.Errorf("Gists.ListStarred returned error: %v", err)
}
want := []*Gist{{ID: String("1")}}
if !reflect.DeepEqual(gists, want) {
t.Errorf("Gists.ListStarred returned %+v, want %+v", gists, want)
}
}
func TestGistsService_Get(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"id": "1"}`)
})
gist, _, err := client.Gists.Get(context.Background(), "1")
if err != nil {
t.Errorf("Gists.Get returned error: %v", err)
}
want := &Gist{ID: String("1")}
if !reflect.DeepEqual(gist, want) {
t.Errorf("Gists.Get returned %+v, want %+v", gist, want)
}
}
func TestGistsService_Get_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.Get(context.Background(), "%")
testURLParseError(t, err)
}
func TestGistsService_GetRevision(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/s", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"id": "1"}`)
})
gist, _, err := client.Gists.GetRevision(context.Background(), "1", "s")
if err != nil {
t.Errorf("Gists.Get returned error: %v", err)
}
want := &Gist{ID: String("1")}
if !reflect.DeepEqual(gist, want) {
t.Errorf("Gists.Get returned %+v, want %+v", gist, want)
}
}
func TestGistsService_GetRevision_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.GetRevision(context.Background(), "%", "%")
testURLParseError(t, err)
}
func TestGistsService_Create(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Gist{
Description: String("Gist description"),
Public: Bool(false),
Files: map[GistFilename]GistFile{
"test.txt": {Content: String("Gist file content")},
},
}
mux.HandleFunc("/gists", func(w http.ResponseWriter, r *http.Request) {
v := new(Gist)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w,
`
{
"id": "1",
"description": "Gist description",
"public": false,
"files": {
"test.txt": {
"filename": "test.txt"
}
}
}`)
})
gist, _, err := client.Gists.Create(context.Background(), input)
if err != nil {
t.Errorf("Gists.Create returned error: %v", err)
}
want := &Gist{
ID: String("1"),
Description: String("Gist description"),
Public: Bool(false),
Files: map[GistFilename]GistFile{
"test.txt": {Filename: String("test.txt")},
},
}
if !reflect.DeepEqual(gist, want) {
t.Errorf("Gists.Create returned %+v, want %+v", gist, want)
}
}
func TestGistsService_Edit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Gist{
Description: String("New description"),
Files: map[GistFilename]GistFile{
"new.txt": {Content: String("new file content")},
},
}
mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) {
v := new(Gist)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w,
`
{
"id": "1",
"description": "new description",
"public": false,
"files": {
"test.txt": {
"filename": "test.txt"
},
"new.txt": {
"filename": "new.txt"
}
}
}`)
})
gist, _, err := client.Gists.Edit(context.Background(), "1", input)
if err != nil {
t.Errorf("Gists.Edit returned error: %v", err)
}
want := &Gist{
ID: String("1"),
Description: String("new description"),
Public: Bool(false),
Files: map[GistFilename]GistFile{
"test.txt": {Filename: String("test.txt")},
"new.txt": {Filename: String("new.txt")},
},
}
if !reflect.DeepEqual(gist, want) {
t.Errorf("Gists.Edit returned %+v, want %+v", gist, want)
}
}
func TestGistsService_Edit_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.Edit(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestGistsService_ListCommits(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/commits", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, nil)
fmt.Fprint(w, `
[
{
"url": "https://api.github.com/gists/1/1",
"version": "1",
"user": {
"id": 1
},
"change_status": {
"deletions": 0,
"additions": 180,
"total": 180
},
"committed_at": "2010-01-01T00:00:00Z"
}
]
`)
})
gistCommits, _, err := client.Gists.ListCommits(context.Background(), "1", nil)
if err != nil {
t.Errorf("Gists.ListCommits returned error: %v", err)
}
want := []*GistCommit{{
URL: String("https://api.github.com/gists/1/1"),
Version: String("1"),
User: &User{ID: Int64(1)},
CommittedAt: &Timestamp{time.Date(2010, 1, 1, 00, 00, 00, 0, time.UTC)},
ChangeStatus: &CommitStats{
Additions: Int(180),
Deletions: Int(0),
Total: Int(180),
}}}
if !reflect.DeepEqual(gistCommits, want) {
t.Errorf("Gists.ListCommits returned %+v, want %+v", gistCommits, want)
}
}
func TestGistsService_ListCommits_withOptions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/commits", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[]`)
})
_, _, err := client.Gists.ListCommits(context.Background(), "1", &ListOptions{Page: 2})
if err != nil {
t.Errorf("Gists.ListCommits returned error: %v", err)
}
}
func TestGistsService_Delete(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Gists.Delete(context.Background(), "1")
if err != nil {
t.Errorf("Gists.Delete returned error: %v", err)
}
}
func TestGistsService_Delete_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Gists.Delete(context.Background(), "%")
testURLParseError(t, err)
}
func TestGistsService_Star(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
})
_, err := client.Gists.Star(context.Background(), "1")
if err != nil {
t.Errorf("Gists.Star returned error: %v", err)
}
}
func TestGistsService_Star_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Gists.Star(context.Background(), "%")
testURLParseError(t, err)
}
func TestGistsService_Unstar(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Gists.Unstar(context.Background(), "1")
if err != nil {
t.Errorf("Gists.Unstar returned error: %v", err)
}
}
func TestGistsService_Unstar_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Gists.Unstar(context.Background(), "%")
testURLParseError(t, err)
}
func TestGistsService_IsStarred_hasStar(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNoContent)
})
star, _, err := client.Gists.IsStarred(context.Background(), "1")
if err != nil {
t.Errorf("Gists.Starred returned error: %v", err)
}
if want := true; star != want {
t.Errorf("Gists.Starred returned %+v, want %+v", star, want)
}
}
func TestGistsService_IsStarred_noStar(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
star, _, err := client.Gists.IsStarred(context.Background(), "1")
if err != nil {
t.Errorf("Gists.Starred returned error: %v", err)
}
if want := false; star != want {
t.Errorf("Gists.Starred returned %+v, want %+v", star, want)
}
}
func TestGistsService_IsStarred_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.IsStarred(context.Background(), "%")
testURLParseError(t, err)
}
func TestGistsService_Fork(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/forks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"id": "2"}`)
})
gist, _, err := client.Gists.Fork(context.Background(), "1")
if err != nil {
t.Errorf("Gists.Fork returned error: %v", err)
}
want := &Gist{ID: String("2")}
if !reflect.DeepEqual(gist, want) {
t.Errorf("Gists.Fork returned %+v, want %+v", gist, want)
}
}
func TestGistsService_ListForks(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gists/1/forks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, nil)
fmt.Fprint(w, `
[
{"url": "https://api.github.com/gists/1",
"user": {"id": 1},
"id": "1",
"created_at": "2010-01-01T00:00:00Z",
"updated_at": "2013-01-01T00:00:00Z"
}
]
`)
})
gistForks, _, err := client.Gists.ListForks(context.Background(), "1")
if err != nil {
t.Errorf("Gists.ListForks returned error: %v", err)
}
want := []*GistFork{{
URL: String("https://api.github.com/gists/1"),
ID: String("1"),
User: &User{ID: Int64(1)},
CreatedAt: &Timestamp{time.Date(2010, 1, 1, 00, 00, 00, 0, time.UTC)},
UpdatedAt: &Timestamp{time.Date(2013, 1, 1, 00, 00, 00, 0, time.UTC)}}}
if !reflect.DeepEqual(gistForks, want) {
t.Errorf("Gists.ListForks returned %+v, want %+v", gistForks, want)
}
}
func TestGistsService_Fork_invalidID(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gists.Fork(context.Background(), "%")
testURLParseError(t, err)
}

View file

@ -1,103 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestGitService_GetBlob(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/blobs/s", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{
"sha": "s",
"content": "blob content"
}`)
})
blob, _, err := client.Git.GetBlob(context.Background(), "o", "r", "s")
if err != nil {
t.Errorf("Git.GetBlob returned error: %v", err)
}
want := Blob{
SHA: String("s"),
Content: String("blob content"),
}
if !reflect.DeepEqual(*blob, want) {
t.Errorf("Blob.Get returned %+v, want %+v", *blob, want)
}
}
func TestGitService_GetBlob_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Git.GetBlob(context.Background(), "%", "%", "%")
testURLParseError(t, err)
}
func TestGitService_CreateBlob(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Blob{
SHA: String("s"),
Content: String("blob content"),
Encoding: String("utf-8"),
Size: Int(12),
}
mux.HandleFunc("/repos/o/r/git/blobs", func(w http.ResponseWriter, r *http.Request) {
v := new(Blob)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
want := input
if !reflect.DeepEqual(v, want) {
t.Errorf("Git.CreateBlob request body: %+v, want %+v", v, want)
}
fmt.Fprint(w, `{
"sha": "s",
"content": "blob content",
"encoding": "utf-8",
"size": 12
}`)
})
blob, _, err := client.Git.CreateBlob(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Git.CreateBlob returned error: %v", err)
}
want := input
if !reflect.DeepEqual(*blob, *want) {
t.Errorf("Git.CreateBlob returned %+v, want %+v", *blob, *want)
}
}
func TestGitService_CreateBlob_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Git.CreateBlob(context.Background(), "%", "%", &Blob{})
testURLParseError(t, err)
}

View file

@ -1,93 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
)
func TestGitService_GetCommit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
acceptHeaders := []string{mediaTypeGitSigningPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/repos/o/r/git/commits/s", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
fmt.Fprint(w, `{"sha":"s","message":"m","author":{"name":"n"}}`)
})
commit, _, err := client.Git.GetCommit(context.Background(), "o", "r", "s")
if err != nil {
t.Errorf("Git.GetCommit returned error: %v", err)
}
want := &Commit{SHA: String("s"), Message: String("m"), Author: &CommitAuthor{Name: String("n")}}
if !reflect.DeepEqual(commit, want) {
t.Errorf("Git.GetCommit returned %+v, want %+v", commit, want)
}
}
func TestGitService_GetCommit_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Git.GetCommit(context.Background(), "%", "%", "%")
testURLParseError(t, err)
}
func TestGitService_CreateCommit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Commit{
Message: String("m"),
Tree: &Tree{SHA: String("t")},
Parents: []Commit{{SHA: String("p")}},
}
mux.HandleFunc("/repos/o/r/git/commits", func(w http.ResponseWriter, r *http.Request) {
v := new(createCommit)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
want := &createCommit{
Message: input.Message,
Tree: String("t"),
Parents: []string{"p"},
}
if !reflect.DeepEqual(v, want) {
t.Errorf("Request body = %+v, want %+v", v, want)
}
fmt.Fprint(w, `{"sha":"s"}`)
})
commit, _, err := client.Git.CreateCommit(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Git.CreateCommit returned error: %v", err)
}
want := &Commit{SHA: String("s")}
if !reflect.DeepEqual(commit, want) {
t.Errorf("Git.CreateCommit returned %+v, want %+v", commit, want)
}
}
func TestGitService_CreateCommit_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Git.CreateCommit(context.Background(), "%", "%", &Commit{})
testURLParseError(t, err)
}

View file

@ -1,438 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestGitService_GetRef_singleRef(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `
{
"ref": "refs/heads/b",
"url": "https://api.github.com/repos/o/r/git/refs/heads/b",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
}`)
})
ref, _, err := client.Git.GetRef(context.Background(), "o", "r", "refs/heads/b")
if err != nil {
t.Fatalf("Git.GetRef returned error: %v", err)
}
want := &Reference{
Ref: String("refs/heads/b"),
URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"),
Object: &GitObject{
Type: String("commit"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
}
if !reflect.DeepEqual(ref, want) {
t.Errorf("Git.GetRef returned %+v, want %+v", ref, want)
}
// without 'refs/' prefix
if _, _, err := client.Git.GetRef(context.Background(), "o", "r", "heads/b"); err != nil {
t.Errorf("Git.GetRef returned error: %v", err)
}
}
func TestGitService_GetRef_multipleRefs(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `
[
{
"ref": "refs/heads/booger",
"url": "https://api.github.com/repos/o/r/git/refs/heads/booger",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
},
{
"ref": "refs/heads/bandsaw",
"url": "https://api.github.com/repos/o/r/git/refs/heads/bandsaw",
"object": {
"type": "commit",
"sha": "612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac",
"url": "https://api.github.com/repos/o/r/git/commits/612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac"
}
}
]
`)
})
_, _, err := client.Git.GetRef(context.Background(), "o", "r", "refs/heads/b")
want := "no exact match found for this ref"
if err.Error() != want {
t.Errorf("Git.GetRef returned %+v, want %+v", err, want)
}
}
func TestGitService_GetRefs_singleRef(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `
{
"ref": "refs/heads/b",
"url": "https://api.github.com/repos/o/r/git/refs/heads/b",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
}`)
})
refs, _, err := client.Git.GetRefs(context.Background(), "o", "r", "refs/heads/b")
if err != nil {
t.Fatalf("Git.GetRefs returned error: %v", err)
}
ref := refs[0]
want := &Reference{
Ref: String("refs/heads/b"),
URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"),
Object: &GitObject{
Type: String("commit"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
}
if !reflect.DeepEqual(ref, want) {
t.Errorf("Git.GetRefs returned %+v, want %+v", ref, want)
}
// without 'refs/' prefix
if _, _, err := client.Git.GetRefs(context.Background(), "o", "r", "heads/b"); err != nil {
t.Errorf("Git.GetRefs returned error: %v", err)
}
}
func TestGitService_GetRefs_multipleRefs(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `
[
{
"ref": "refs/heads/booger",
"url": "https://api.github.com/repos/o/r/git/refs/heads/booger",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
},
{
"ref": "refs/heads/bandsaw",
"url": "https://api.github.com/repos/o/r/git/refs/heads/bandsaw",
"object": {
"type": "commit",
"sha": "612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac",
"url": "https://api.github.com/repos/o/r/git/commits/612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac"
}
}
]
`)
})
refs, _, err := client.Git.GetRefs(context.Background(), "o", "r", "refs/heads/b")
if err != nil {
t.Errorf("Git.GetRefs returned error: %v", err)
}
want := &Reference{
Ref: String("refs/heads/booger"),
URL: String("https://api.github.com/repos/o/r/git/refs/heads/booger"),
Object: &GitObject{
Type: String("commit"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
}
if !reflect.DeepEqual(refs[0], want) {
t.Errorf("Git.GetRefs returned %+v, want %+v", refs[0], want)
}
}
// TestGitService_GetRefs_noRefs tests for behaviour resulting from an unexpected GH response. This should never actually happen.
func TestGitService_GetRefs_noRefs(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, "[]")
})
_, _, err := client.Git.GetRefs(context.Background(), "o", "r", "refs/heads/b")
want := "unexpected response from GitHub API: an array of refs with length 0"
if err.Error() != want {
t.Errorf("Git.GetRefs returned %+v, want %+v", err, want)
}
}
func TestGitService_ListRefs(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/refs", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `
[
{
"ref": "refs/heads/branchA",
"url": "https://api.github.com/repos/o/r/git/refs/heads/branchA",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
},
{
"ref": "refs/heads/branchB",
"url": "https://api.github.com/repos/o/r/git/refs/heads/branchB",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
}
]`)
})
refs, _, err := client.Git.ListRefs(context.Background(), "o", "r", nil)
if err != nil {
t.Errorf("Git.ListRefs returned error: %v", err)
}
want := []*Reference{
{
Ref: String("refs/heads/branchA"),
URL: String("https://api.github.com/repos/o/r/git/refs/heads/branchA"),
Object: &GitObject{
Type: String("commit"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
},
{
Ref: String("refs/heads/branchB"),
URL: String("https://api.github.com/repos/o/r/git/refs/heads/branchB"),
Object: &GitObject{
Type: String("commit"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
},
}
if !reflect.DeepEqual(refs, want) {
t.Errorf("Git.ListRefs returned %+v, want %+v", refs, want)
}
}
func TestGitService_ListRefs_options(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/refs/t", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"ref": "r"}]`)
})
opt := &ReferenceListOptions{Type: "t", ListOptions: ListOptions{Page: 2}}
refs, _, err := client.Git.ListRefs(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Git.ListRefs returned error: %v", err)
}
want := []*Reference{{Ref: String("r")}}
if !reflect.DeepEqual(refs, want) {
t.Errorf("Git.ListRefs returned %+v, want %+v", refs, want)
}
}
func TestGitService_CreateRef(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
args := &createRefRequest{
Ref: String("refs/heads/b"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
}
mux.HandleFunc("/repos/o/r/git/refs", func(w http.ResponseWriter, r *http.Request) {
v := new(createRefRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, args) {
t.Errorf("Request body = %+v, want %+v", v, args)
}
fmt.Fprint(w, `
{
"ref": "refs/heads/b",
"url": "https://api.github.com/repos/o/r/git/refs/heads/b",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
}`)
})
ref, _, err := client.Git.CreateRef(context.Background(), "o", "r", &Reference{
Ref: String("refs/heads/b"),
Object: &GitObject{
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
})
if err != nil {
t.Errorf("Git.CreateRef returned error: %v", err)
}
want := &Reference{
Ref: String("refs/heads/b"),
URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"),
Object: &GitObject{
Type: String("commit"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
}
if !reflect.DeepEqual(ref, want) {
t.Errorf("Git.CreateRef returned %+v, want %+v", ref, want)
}
// without 'refs/' prefix
_, _, err = client.Git.CreateRef(context.Background(), "o", "r", &Reference{
Ref: String("heads/b"),
Object: &GitObject{
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
})
if err != nil {
t.Errorf("Git.CreateRef returned error: %v", err)
}
}
func TestGitService_UpdateRef(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
args := &updateRefRequest{
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
Force: Bool(true),
}
mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) {
v := new(updateRefRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, args) {
t.Errorf("Request body = %+v, want %+v", v, args)
}
fmt.Fprint(w, `
{
"ref": "refs/heads/b",
"url": "https://api.github.com/repos/o/r/git/refs/heads/b",
"object": {
"type": "commit",
"sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
"url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
}
}`)
})
ref, _, err := client.Git.UpdateRef(context.Background(), "o", "r", &Reference{
Ref: String("refs/heads/b"),
Object: &GitObject{SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd")},
}, true)
if err != nil {
t.Errorf("Git.UpdateRef returned error: %v", err)
}
want := &Reference{
Ref: String("refs/heads/b"),
URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"),
Object: &GitObject{
Type: String("commit"),
SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"),
URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"),
},
}
if !reflect.DeepEqual(ref, want) {
t.Errorf("Git.UpdateRef returned %+v, want %+v", ref, want)
}
// without 'refs/' prefix
_, _, err = client.Git.UpdateRef(context.Background(), "o", "r", &Reference{
Ref: String("heads/b"),
Object: &GitObject{SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd")},
}, true)
if err != nil {
t.Errorf("Git.UpdateRef returned error: %v", err)
}
}
func TestGitService_DeleteRef(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Git.DeleteRef(context.Background(), "o", "r", "refs/heads/b")
if err != nil {
t.Errorf("Git.DeleteRef returned error: %v", err)
}
// without 'refs/' prefix
if _, err := client.Git.DeleteRef(context.Background(), "o", "r", "heads/b"); err != nil {
t.Errorf("Git.DeleteRef returned error: %v", err)
}
}

View file

@ -1,72 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
)
func TestGitService_GetTag(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
acceptHeaders := []string{mediaTypeGitSigningPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/repos/o/r/git/tags/s", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
fmt.Fprint(w, `{"tag": "t"}`)
})
tag, _, err := client.Git.GetTag(context.Background(), "o", "r", "s")
if err != nil {
t.Errorf("Git.GetTag returned error: %v", err)
}
want := &Tag{Tag: String("t")}
if !reflect.DeepEqual(tag, want) {
t.Errorf("Git.GetTag returned %+v, want %+v", tag, want)
}
}
func TestGitService_CreateTag(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &createTagRequest{Tag: String("t"), Object: String("s")}
mux.HandleFunc("/repos/o/r/git/tags", func(w http.ResponseWriter, r *http.Request) {
v := new(createTagRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"tag": "t"}`)
})
tag, _, err := client.Git.CreateTag(context.Background(), "o", "r", &Tag{
Tag: input.Tag,
Object: &GitObject{SHA: input.Object},
})
if err != nil {
t.Errorf("Git.CreateTag returned error: %v", err)
}
want := &Tag{Tag: String("t")}
if !reflect.DeepEqual(tag, want) {
t.Errorf("Git.GetTag returned %+v, want %+v", tag, want)
}
}

View file

@ -1,191 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestGitService_GetTree(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/git/trees/s", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{
"sha": "s",
"tree": [ { "type": "blob" } ]
}`)
})
tree, _, err := client.Git.GetTree(context.Background(), "o", "r", "s", true)
if err != nil {
t.Errorf("Git.GetTree returned error: %v", err)
}
want := Tree{
SHA: String("s"),
Entries: []TreeEntry{
{
Type: String("blob"),
},
},
}
if !reflect.DeepEqual(*tree, want) {
t.Errorf("Tree.Get returned %+v, want %+v", *tree, want)
}
}
func TestGitService_GetTree_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Git.GetTree(context.Background(), "%", "%", "%", false)
testURLParseError(t, err)
}
func TestGitService_CreateTree(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := []TreeEntry{
{
Path: String("file.rb"),
Mode: String("100644"),
Type: String("blob"),
SHA: String("7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b"),
},
}
mux.HandleFunc("/repos/o/r/git/trees", func(w http.ResponseWriter, r *http.Request) {
v := new(createTree)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
want := &createTree{
BaseTree: "b",
Entries: input,
}
if !reflect.DeepEqual(v, want) {
t.Errorf("Git.CreateTree request body: %+v, want %+v", v, want)
}
fmt.Fprint(w, `{
"sha": "cd8274d15fa3ae2ab983129fb037999f264ba9a7",
"tree": [
{
"path": "file.rb",
"mode": "100644",
"type": "blob",
"size": 132,
"sha": "7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b"
}
]
}`)
})
tree, _, err := client.Git.CreateTree(context.Background(), "o", "r", "b", input)
if err != nil {
t.Errorf("Git.CreateTree returned error: %v", err)
}
want := Tree{
String("cd8274d15fa3ae2ab983129fb037999f264ba9a7"),
[]TreeEntry{
{
Path: String("file.rb"),
Mode: String("100644"),
Type: String("blob"),
Size: Int(132),
SHA: String("7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b"),
},
},
}
if !reflect.DeepEqual(*tree, want) {
t.Errorf("Git.CreateTree returned %+v, want %+v", *tree, want)
}
}
func TestGitService_CreateTree_Content(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := []TreeEntry{
{
Path: String("content.md"),
Mode: String("100644"),
Content: String("file content"),
},
}
mux.HandleFunc("/repos/o/r/git/trees", func(w http.ResponseWriter, r *http.Request) {
v := new(createTree)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
want := &createTree{
BaseTree: "b",
Entries: input,
}
if !reflect.DeepEqual(v, want) {
t.Errorf("Git.CreateTree request body: %+v, want %+v", v, want)
}
fmt.Fprint(w, `{
"sha": "5c6780ad2c68743383b740fd1dab6f6a33202b11",
"url": "https://api.github.com/repos/o/r/git/trees/5c6780ad2c68743383b740fd1dab6f6a33202b11",
"tree": [
{
"mode": "100644",
"type": "blob",
"sha": "aad8feacf6f8063150476a7b2bd9770f2794c08b",
"path": "content.md",
"size": 12,
"url": "https://api.github.com/repos/o/r/git/blobs/aad8feacf6f8063150476a7b2bd9770f2794c08b"
}
]
}`)
})
tree, _, err := client.Git.CreateTree(context.Background(), "o", "r", "b", input)
if err != nil {
t.Errorf("Git.CreateTree returned error: %v", err)
}
want := Tree{
String("5c6780ad2c68743383b740fd1dab6f6a33202b11"),
[]TreeEntry{
{
Path: String("content.md"),
Mode: String("100644"),
Type: String("blob"),
Size: Int(12),
SHA: String("aad8feacf6f8063150476a7b2bd9770f2794c08b"),
URL: String("https://api.github.com/repos/o/r/git/blobs/aad8feacf6f8063150476a7b2bd9770f2794c08b"),
},
},
}
if !reflect.DeepEqual(*tree, want) {
t.Errorf("Git.CreateTree returned %+v, want %+v", *tree, want)
}
}
func TestGitService_CreateTree_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Git.CreateTree(context.Background(), "%", "%", "", nil)
testURLParseError(t, err)
}

File diff suppressed because it is too large Load diff

View file

@ -1,62 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestGitignoresService_List(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gitignore/templates", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `["C", "Go"]`)
})
available, _, err := client.Gitignores.List(context.Background())
if err != nil {
t.Errorf("Gitignores.List returned error: %v", err)
}
want := []string{"C", "Go"}
if !reflect.DeepEqual(available, want) {
t.Errorf("Gitignores.List returned %+v, want %+v", available, want)
}
}
func TestGitignoresService_Get(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/gitignore/templates/name", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"name":"Name","source":"template source"}`)
})
gitignore, _, err := client.Gitignores.Get(context.Background(), "name")
if err != nil {
t.Errorf("Gitignores.List returned error: %v", err)
}
want := &Gitignore{Name: String("Name"), Source: String("template source")}
if !reflect.DeepEqual(gitignore, want) {
t.Errorf("Gitignores.Get returned %+v, want %+v", gitignore, want)
}
}
func TestGitignoresService_Get_invalidTemplate(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Gitignores.Get(context.Background(), "%")
testURLParseError(t, err)
}

View file

@ -1,164 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestIssuesService_ListAssignees(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/assignees", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
assignees, _, err := client.Issues.ListAssignees(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Issues.ListAssignees returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(assignees, want) {
t.Errorf("Issues.ListAssignees returned %+v, want %+v", assignees, want)
}
}
func TestIssuesService_ListAssignees_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ListAssignees(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}
func TestIssuesService_IsAssignee_true(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
})
assignee, _, err := client.Issues.IsAssignee(context.Background(), "o", "r", "u")
if err != nil {
t.Errorf("Issues.IsAssignee returned error: %v", err)
}
if want := true; assignee != want {
t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want)
}
}
func TestIssuesService_IsAssignee_false(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
assignee, _, err := client.Issues.IsAssignee(context.Background(), "o", "r", "u")
if err != nil {
t.Errorf("Issues.IsAssignee returned error: %v", err)
}
if want := false; assignee != want {
t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want)
}
}
func TestIssuesService_IsAssignee_error(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
http.Error(w, "BadRequest", http.StatusBadRequest)
})
assignee, _, err := client.Issues.IsAssignee(context.Background(), "o", "r", "u")
if err == nil {
t.Errorf("Expected HTTP 400 response")
}
if want := false; assignee != want {
t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want)
}
}
func TestIssuesService_IsAssignee_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.IsAssignee(context.Background(), "%", "r", "u")
testURLParseError(t, err)
}
func TestIssuesService_AddAssignees(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/assignees", func(w http.ResponseWriter, r *http.Request) {
var assignees struct {
Assignees []string `json:"assignees,omitempty"`
}
json.NewDecoder(r.Body).Decode(&assignees)
testMethod(t, r, "POST")
want := []string{"user1", "user2"}
if !reflect.DeepEqual(assignees.Assignees, want) {
t.Errorf("assignees = %+v, want %+v", assignees, want)
}
fmt.Fprint(w, `{"number":1,"assignees":[{"login":"user1"},{"login":"user2"}]}`)
})
got, _, err := client.Issues.AddAssignees(context.Background(), "o", "r", 1, []string{"user1", "user2"})
if err != nil {
t.Errorf("Issues.AddAssignees returned error: %v", err)
}
want := &Issue{Number: Int(1), Assignees: []*User{{Login: String("user1")}, {Login: String("user2")}}}
if !reflect.DeepEqual(got, want) {
t.Errorf("Issues.AddAssignees = %+v, want %+v", got, want)
}
}
func TestIssuesService_RemoveAssignees(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/assignees", func(w http.ResponseWriter, r *http.Request) {
var assignees struct {
Assignees []string `json:"assignees,omitempty"`
}
json.NewDecoder(r.Body).Decode(&assignees)
testMethod(t, r, "DELETE")
want := []string{"user1", "user2"}
if !reflect.DeepEqual(assignees.Assignees, want) {
t.Errorf("assignees = %+v, want %+v", assignees, want)
}
fmt.Fprint(w, `{"number":1,"assignees":[]}`)
})
got, _, err := client.Issues.RemoveAssignees(context.Background(), "o", "r", 1, []string{"user1", "user2"})
if err != nil {
t.Errorf("Issues.RemoveAssignees returned error: %v", err)
}
want := &Issue{Number: Int(1), Assignees: []*User{}}
if !reflect.DeepEqual(got, want) {
t.Errorf("Issues.RemoveAssignees = %+v, want %+v", got, want)
}
}

View file

@ -1,203 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestIssuesService_ListComments_allIssues(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
testFormValues(t, r, values{
"sort": "updated",
"direction": "desc",
"since": "2002-02-10T15:30:00Z",
"page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &IssueListCommentsOptions{
Sort: "updated",
Direction: "desc",
Since: time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC),
ListOptions: ListOptions{Page: 2},
}
comments, _, err := client.Issues.ListComments(context.Background(), "o", "r", 0, opt)
if err != nil {
t.Errorf("Issues.ListComments returned error: %v", err)
}
want := []*IssueComment{{ID: Int64(1)}}
if !reflect.DeepEqual(comments, want) {
t.Errorf("Issues.ListComments returned %+v, want %+v", comments, want)
}
}
func TestIssuesService_ListComments_specificIssue(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
fmt.Fprint(w, `[{"id":1}]`)
})
comments, _, err := client.Issues.ListComments(context.Background(), "o", "r", 1, nil)
if err != nil {
t.Errorf("Issues.ListComments returned error: %v", err)
}
want := []*IssueComment{{ID: Int64(1)}}
if !reflect.DeepEqual(comments, want) {
t.Errorf("Issues.ListComments returned %+v, want %+v", comments, want)
}
}
func TestIssuesService_ListComments_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ListComments(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestIssuesService_GetComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.Issues.GetComment(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Issues.GetComment returned error: %v", err)
}
want := &IssueComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Issues.GetComment returned %+v, want %+v", comment, want)
}
}
func TestIssuesService_GetComment_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.GetComment(context.Background(), "%", "r", 1)
testURLParseError(t, err)
}
func TestIssuesService_CreateComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &IssueComment{Body: String("b")}
mux.HandleFunc("/repos/o/r/issues/1/comments", func(w http.ResponseWriter, r *http.Request) {
v := new(IssueComment)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.Issues.CreateComment(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Issues.CreateComment returned error: %v", err)
}
want := &IssueComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Issues.CreateComment returned %+v, want %+v", comment, want)
}
}
func TestIssuesService_CreateComment_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.CreateComment(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestIssuesService_EditComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &IssueComment{Body: String("b")}
mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) {
v := new(IssueComment)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.Issues.EditComment(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Issues.EditComment returned error: %v", err)
}
want := &IssueComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Issues.EditComment returned %+v, want %+v", comment, want)
}
}
func TestIssuesService_EditComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.EditComment(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestIssuesService_DeleteComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Issues.DeleteComment(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Issues.DeleteComments returned error: %v", err)
}
}
func TestIssuesService_DeleteComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Issues.DeleteComment(context.Background(), "%", "r", 1)
testURLParseError(t, err)
}

View file

@ -1,84 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestIssuesService_ListIssueEvents(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
events, _, err := client.Issues.ListIssueEvents(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("Issues.ListIssueEvents returned error: %v", err)
}
want := []*IssueEvent{{ID: Int64(1)}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Issues.ListIssueEvents returned %+v, want %+v", events, want)
}
}
func TestIssuesService_ListRepositoryEvents(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/events", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
events, _, err := client.Issues.ListRepositoryEvents(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Issues.ListRepositoryEvents returned error: %v", err)
}
want := []*IssueEvent{{ID: Int64(1)}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Issues.ListRepositoryEvents returned %+v, want %+v", events, want)
}
}
func TestIssuesService_GetEvent(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/events/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
event, _, err := client.Issues.GetEvent(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Issues.GetEvent returned error: %v", err)
}
want := &IssueEvent{ID: Int64(1)}
if !reflect.DeepEqual(event, want) {
t.Errorf("Issues.GetEvent returned %+v, want %+v", event, want)
}
}

View file

@ -1,358 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestIssuesService_ListLabels(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"name": "a"},{"name": "b"}]`)
})
opt := &ListOptions{Page: 2}
labels, _, err := client.Issues.ListLabels(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Issues.ListLabels returned error: %v", err)
}
want := []*Label{{Name: String("a")}, {Name: String("b")}}
if !reflect.DeepEqual(labels, want) {
t.Errorf("Issues.ListLabels returned %+v, want %+v", labels, want)
}
}
func TestIssuesService_ListLabels_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ListLabels(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestIssuesService_GetLabel(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"url":"u", "name": "n", "color": "c"}`)
})
label, _, err := client.Issues.GetLabel(context.Background(), "o", "r", "n")
if err != nil {
t.Errorf("Issues.GetLabel returned error: %v", err)
}
want := &Label{URL: String("u"), Name: String("n"), Color: String("c")}
if !reflect.DeepEqual(label, want) {
t.Errorf("Issues.GetLabel returned %+v, want %+v", label, want)
}
}
func TestIssuesService_GetLabel_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.GetLabel(context.Background(), "%", "%", "%")
testURLParseError(t, err)
}
func TestIssuesService_CreateLabel(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Label{Name: String("n")}
mux.HandleFunc("/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) {
v := new(Label)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"url":"u"}`)
})
label, _, err := client.Issues.CreateLabel(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Issues.CreateLabel returned error: %v", err)
}
want := &Label{URL: String("u")}
if !reflect.DeepEqual(label, want) {
t.Errorf("Issues.CreateLabel returned %+v, want %+v", label, want)
}
}
func TestIssuesService_CreateLabel_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.CreateLabel(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestIssuesService_EditLabel(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Label{Name: String("z")}
mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) {
v := new(Label)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"url":"u"}`)
})
label, _, err := client.Issues.EditLabel(context.Background(), "o", "r", "n", input)
if err != nil {
t.Errorf("Issues.EditLabel returned error: %v", err)
}
want := &Label{URL: String("u")}
if !reflect.DeepEqual(label, want) {
t.Errorf("Issues.EditLabel returned %+v, want %+v", label, want)
}
}
func TestIssuesService_EditLabel_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.EditLabel(context.Background(), "%", "%", "%", nil)
testURLParseError(t, err)
}
func TestIssuesService_DeleteLabel(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Issues.DeleteLabel(context.Background(), "o", "r", "n")
if err != nil {
t.Errorf("Issues.DeleteLabel returned error: %v", err)
}
}
func TestIssuesService_DeleteLabel_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Issues.DeleteLabel(context.Background(), "%", "%", "%")
testURLParseError(t, err)
}
func TestIssuesService_ListLabelsByIssue(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"name":"a","id":1},{"name":"b","id":2}]`)
})
opt := &ListOptions{Page: 2}
labels, _, err := client.Issues.ListLabelsByIssue(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("Issues.ListLabelsByIssue returned error: %v", err)
}
want := []*Label{
{Name: String("a"), ID: Int64(1)},
{Name: String("b"), ID: Int64(2)},
}
if !reflect.DeepEqual(labels, want) {
t.Errorf("Issues.ListLabelsByIssue returned %+v, want %+v", labels, want)
}
}
func TestIssuesService_ListLabelsByIssue_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ListLabelsByIssue(context.Background(), "%", "%", 1, nil)
testURLParseError(t, err)
}
func TestIssuesService_AddLabelsToIssue(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := []string{"a", "b"}
mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) {
var v []string
json.NewDecoder(r.Body).Decode(&v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `[{"url":"u"}]`)
})
labels, _, err := client.Issues.AddLabelsToIssue(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Issues.AddLabelsToIssue returned error: %v", err)
}
want := []*Label{{URL: String("u")}}
if !reflect.DeepEqual(labels, want) {
t.Errorf("Issues.AddLabelsToIssue returned %+v, want %+v", labels, want)
}
}
func TestIssuesService_AddLabelsToIssue_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.AddLabelsToIssue(context.Background(), "%", "%", 1, nil)
testURLParseError(t, err)
}
func TestIssuesService_RemoveLabelForIssue(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/labels/l", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Issues.RemoveLabelForIssue(context.Background(), "o", "r", 1, "l")
if err != nil {
t.Errorf("Issues.RemoveLabelForIssue returned error: %v", err)
}
}
func TestIssuesService_RemoveLabelForIssue_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Issues.RemoveLabelForIssue(context.Background(), "%", "%", 1, "%")
testURLParseError(t, err)
}
func TestIssuesService_ReplaceLabelsForIssue(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := []string{"a", "b"}
mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) {
var v []string
json.NewDecoder(r.Body).Decode(&v)
testMethod(t, r, "PUT")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `[{"url":"u"}]`)
})
labels, _, err := client.Issues.ReplaceLabelsForIssue(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Issues.ReplaceLabelsForIssue returned error: %v", err)
}
want := []*Label{{URL: String("u")}}
if !reflect.DeepEqual(labels, want) {
t.Errorf("Issues.ReplaceLabelsForIssue returned %+v, want %+v", labels, want)
}
}
func TestIssuesService_ReplaceLabelsForIssue_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ReplaceLabelsForIssue(context.Background(), "%", "%", 1, nil)
testURLParseError(t, err)
}
func TestIssuesService_RemoveLabelsForIssue(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Issues.RemoveLabelsForIssue(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Issues.RemoveLabelsForIssue returned error: %v", err)
}
}
func TestIssuesService_RemoveLabelsForIssue_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Issues.RemoveLabelsForIssue(context.Background(), "%", "%", 1)
testURLParseError(t, err)
}
func TestIssuesService_ListLabelsForMilestone(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/milestones/1/labels", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"name": "a"},{"name": "b"}]`)
})
opt := &ListOptions{Page: 2}
labels, _, err := client.Issues.ListLabelsForMilestone(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("Issues.ListLabelsForMilestone returned error: %v", err)
}
want := []*Label{{Name: String("a")}, {Name: String("b")}}
if !reflect.DeepEqual(labels, want) {
t.Errorf("Issues.ListLabelsForMilestone returned %+v, want %+v", labels, want)
}
}
func TestIssuesService_ListLabelsForMilestone_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ListLabelsForMilestone(context.Background(), "%", "%", 1, nil)
testURLParseError(t, err)
}

View file

@ -1,178 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestIssuesService_ListMilestones(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/milestones", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{
"state": "closed",
"sort": "due_date",
"direction": "asc",
"page": "2",
})
fmt.Fprint(w, `[{"number":1}]`)
})
opt := &MilestoneListOptions{"closed", "due_date", "asc", ListOptions{Page: 2}}
milestones, _, err := client.Issues.ListMilestones(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("IssuesService.ListMilestones returned error: %v", err)
}
want := []*Milestone{{Number: Int(1)}}
if !reflect.DeepEqual(milestones, want) {
t.Errorf("IssuesService.ListMilestones returned %+v, want %+v", milestones, want)
}
}
func TestIssuesService_ListMilestones_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ListMilestones(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}
func TestIssuesService_GetMilestone(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"number":1}`)
})
milestone, _, err := client.Issues.GetMilestone(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("IssuesService.GetMilestone returned error: %v", err)
}
want := &Milestone{Number: Int(1)}
if !reflect.DeepEqual(milestone, want) {
t.Errorf("IssuesService.GetMilestone returned %+v, want %+v", milestone, want)
}
}
func TestIssuesService_GetMilestone_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.GetMilestone(context.Background(), "%", "r", 1)
testURLParseError(t, err)
}
func TestIssuesService_CreateMilestone(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Milestone{Title: String("t")}
mux.HandleFunc("/repos/o/r/milestones", func(w http.ResponseWriter, r *http.Request) {
v := new(Milestone)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"number":1}`)
})
milestone, _, err := client.Issues.CreateMilestone(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("IssuesService.CreateMilestone returned error: %v", err)
}
want := &Milestone{Number: Int(1)}
if !reflect.DeepEqual(milestone, want) {
t.Errorf("IssuesService.CreateMilestone returned %+v, want %+v", milestone, want)
}
}
func TestIssuesService_CreateMilestone_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.CreateMilestone(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}
func TestIssuesService_EditMilestone(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Milestone{Title: String("t")}
mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) {
v := new(Milestone)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"number":1}`)
})
milestone, _, err := client.Issues.EditMilestone(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("IssuesService.EditMilestone returned error: %v", err)
}
want := &Milestone{Number: Int(1)}
if !reflect.DeepEqual(milestone, want) {
t.Errorf("IssuesService.EditMilestone returned %+v, want %+v", milestone, want)
}
}
func TestIssuesService_EditMilestone_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.EditMilestone(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestIssuesService_DeleteMilestone(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Issues.DeleteMilestone(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("IssuesService.DeleteMilestone returned error: %v", err)
}
}
func TestIssuesService_DeleteMilestone_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Issues.DeleteMilestone(context.Background(), "%", "r", 1)
testURLParseError(t, err)
}

View file

@ -1,311 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
"time"
)
func TestIssuesService_List_all(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/issues", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
testFormValues(t, r, values{
"filter": "all",
"state": "closed",
"labels": "a,b",
"sort": "updated",
"direction": "asc",
"since": "2002-02-10T15:30:00Z",
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `[{"number":1}]`)
})
opt := &IssueListOptions{
"all", "closed", []string{"a", "b"}, "updated", "asc",
time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC),
ListOptions{Page: 1, PerPage: 2},
}
issues, _, err := client.Issues.List(context.Background(), true, opt)
if err != nil {
t.Errorf("Issues.List returned error: %v", err)
}
want := []*Issue{{Number: Int(1)}}
if !reflect.DeepEqual(issues, want) {
t.Errorf("Issues.List returned %+v, want %+v", issues, want)
}
}
func TestIssuesService_List_owned(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/user/issues", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
fmt.Fprint(w, `[{"number":1}]`)
})
issues, _, err := client.Issues.List(context.Background(), false, nil)
if err != nil {
t.Errorf("Issues.List returned error: %v", err)
}
want := []*Issue{{Number: Int(1)}}
if !reflect.DeepEqual(issues, want) {
t.Errorf("Issues.List returned %+v, want %+v", issues, want)
}
}
func TestIssuesService_ListByOrg(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/orgs/o/issues", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
fmt.Fprint(w, `[{"number":1}]`)
})
issues, _, err := client.Issues.ListByOrg(context.Background(), "o", nil)
if err != nil {
t.Errorf("Issues.ListByOrg returned error: %v", err)
}
want := []*Issue{{Number: Int(1)}}
if !reflect.DeepEqual(issues, want) {
t.Errorf("Issues.List returned %+v, want %+v", issues, want)
}
}
func TestIssuesService_ListByOrg_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ListByOrg(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestIssuesService_ListByRepo(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
testFormValues(t, r, values{
"milestone": "*",
"state": "closed",
"assignee": "a",
"creator": "c",
"mentioned": "m",
"labels": "a,b",
"sort": "updated",
"direction": "asc",
"since": "2002-02-10T15:30:00Z",
})
fmt.Fprint(w, `[{"number":1}]`)
})
opt := &IssueListByRepoOptions{
"*", "closed", "a", "c", "m", []string{"a", "b"}, "updated", "asc",
time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC),
ListOptions{0, 0},
}
issues, _, err := client.Issues.ListByRepo(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Issues.ListByOrg returned error: %v", err)
}
want := []*Issue{{Number: Int(1)}}
if !reflect.DeepEqual(issues, want) {
t.Errorf("Issues.List returned %+v, want %+v", issues, want)
}
}
func TestIssuesService_ListByRepo_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.ListByRepo(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}
func TestIssuesService_Get(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/repos/o/r/issues/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
fmt.Fprint(w, `{"number":1, "labels": [{"url": "u", "name": "n", "color": "c"}]}`)
})
issue, _, err := client.Issues.Get(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Issues.Get returned error: %v", err)
}
want := &Issue{
Number: Int(1),
Labels: []Label{{
URL: String("u"),
Name: String("n"),
Color: String("c"),
}},
}
if !reflect.DeepEqual(issue, want) {
t.Errorf("Issues.Get returned %+v, want %+v", issue, want)
}
}
func TestIssuesService_Get_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.Get(context.Background(), "%", "r", 1)
testURLParseError(t, err)
}
func TestIssuesService_Create(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &IssueRequest{
Title: String("t"),
Body: String("b"),
Assignee: String("a"),
Labels: &[]string{"l1", "l2"},
}
mux.HandleFunc("/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
v := new(IssueRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"number":1}`)
})
issue, _, err := client.Issues.Create(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Issues.Create returned error: %v", err)
}
want := &Issue{Number: Int(1)}
if !reflect.DeepEqual(issue, want) {
t.Errorf("Issues.Create returned %+v, want %+v", issue, want)
}
}
func TestIssuesService_Create_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.Create(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}
func TestIssuesService_Edit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &IssueRequest{Title: String("t")}
mux.HandleFunc("/repos/o/r/issues/1", func(w http.ResponseWriter, r *http.Request) {
v := new(IssueRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"number":1}`)
})
issue, _, err := client.Issues.Edit(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Issues.Edit returned error: %v", err)
}
want := &Issue{Number: Int(1)}
if !reflect.DeepEqual(issue, want) {
t.Errorf("Issues.Edit returned %+v, want %+v", issue, want)
}
}
func TestIssuesService_Edit_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Issues.Edit(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestIssuesService_Lock(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/lock", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
w.WriteHeader(http.StatusNoContent)
})
if _, err := client.Issues.Lock(context.Background(), "o", "r", 1); err != nil {
t.Errorf("Issues.Lock returned error: %v", err)
}
}
func TestIssuesService_Unlock(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/lock", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
if _, err := client.Issues.Unlock(context.Background(), "o", "r", 1); err != nil {
t.Errorf("Issues.Unlock returned error: %v", err)
}
}
func TestIsPullRequest(t *testing.T) {
i := new(Issue)
if i.IsPullRequest() == true {
t.Errorf("expected i.IsPullRequest (%v) to return false, got true", i)
}
i.PullRequestLinks = &PullRequestLinks{URL: String("http://example.com")}
if i.IsPullRequest() == false {
t.Errorf("expected i.IsPullRequest (%v) to return true, got false", i)
}
}

View file

@ -1,40 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestIssuesService_ListIssueTimeline(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/timeline", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeTimelinePreview)
testFormValues(t, r, values{
"page": "1",
"per_page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1, PerPage: 2}
events, _, err := client.Issues.ListIssueTimeline(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("Issues.ListIssueTimeline returned error: %v", err)
}
want := []*Timeline{{ID: Int64(1)}}
if !reflect.DeepEqual(events, want) {
t.Errorf("Issues.ListIssueTimeline = %+v, want %+v", events, want)
}
}

View file

@ -1,70 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestLicensesService_List(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/licenses", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeLicensesPreview)
fmt.Fprint(w, `[{"key":"mit","name":"MIT","spdx_id":"MIT","url":"https://api.github.com/licenses/mit","featured":true}]`)
})
licenses, _, err := client.Licenses.List(context.Background())
if err != nil {
t.Errorf("Licenses.List returned error: %v", err)
}
want := []*License{{
Key: String("mit"),
Name: String("MIT"),
SPDXID: String("MIT"),
URL: String("https://api.github.com/licenses/mit"),
Featured: Bool(true),
}}
if !reflect.DeepEqual(licenses, want) {
t.Errorf("Licenses.List returned %+v, want %+v", licenses, want)
}
}
func TestLicensesService_Get(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/licenses/mit", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeLicensesPreview)
fmt.Fprint(w, `{"key":"mit","name":"MIT"}`)
})
license, _, err := client.Licenses.Get(context.Background(), "mit")
if err != nil {
t.Errorf("Licenses.Get returned error: %v", err)
}
want := &License{Key: String("mit"), Name: String("MIT")}
if !reflect.DeepEqual(license, want) {
t.Errorf("Licenses.Get returned %+v, want %+v", license, want)
}
}
func TestLicensesService_Get_invalidTemplate(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Licenses.Get(context.Background(), "%")
testURLParseError(t, err)
}

View file

@ -1,330 +0,0 @@
// 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.
package github
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"reflect"
"strings"
"testing"
)
func TestValidatePayload(t *testing.T) {
const defaultBody = `{"yo":true}` // All tests below use the default request body and signature.
const defaultSignature = "sha1=126f2c800419c60137ce748d7672e77b65cf16d6"
secretKey := []byte("0123456789abcdef")
tests := []struct {
signature string
eventID string
event string
wantEventID string
wantEvent string
wantPayload string
}{
// The following tests generate expected errors:
{}, // Missing signature
{signature: "yo"}, // Missing signature prefix
{signature: "sha1=yo"}, // Signature not hex string
{signature: "sha1=012345"}, // Invalid signature
// The following tests expect err=nil:
{
signature: defaultSignature,
eventID: "dead-beef",
event: "ping",
wantEventID: "dead-beef",
wantEvent: "ping",
wantPayload: defaultBody,
},
{
signature: defaultSignature,
event: "ping",
wantEvent: "ping",
wantPayload: defaultBody,
},
{
signature: "sha256=b1f8020f5b4cd42042f807dd939015c4a418bc1ff7f604dd55b0a19b5d953d9b",
event: "ping",
wantEvent: "ping",
wantPayload: defaultBody,
},
{
signature: "sha512=8456767023c1195682e182a23b3f5d19150ecea598fde8cb85918f7281b16079471b1329f92b912c4d8bd7455cb159777db8f29608b20c7c87323ba65ae62e1f",
event: "ping",
wantEvent: "ping",
wantPayload: defaultBody,
},
}
for _, test := range tests {
buf := bytes.NewBufferString(defaultBody)
req, err := http.NewRequest("GET", "http://localhost/event", buf)
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
if test.signature != "" {
req.Header.Set(signatureHeader, test.signature)
}
req.Header.Set("Content-Type", "application/json")
got, err := ValidatePayload(req, secretKey)
if err != nil {
if test.wantPayload != "" {
t.Errorf("ValidatePayload(%#v): err = %v, want nil", test, err)
}
continue
}
if string(got) != test.wantPayload {
t.Errorf("ValidatePayload = %q, want %q", got, test.wantPayload)
}
}
}
func TestValidatePayload_FormGet(t *testing.T) {
payload := `{"yo":true}`
signature := "sha1=3374ef144403e8035423b23b02e2c9d7a4c50368"
secretKey := []byte("0123456789abcdef")
form := url.Values{}
form.Add("payload", payload)
req, err := http.NewRequest("POST", "http://localhost/event", strings.NewReader(form.Encode()))
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
req.PostForm = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set(signatureHeader, signature)
got, err := ValidatePayload(req, secretKey)
if err != nil {
t.Errorf("ValidatePayload(%#v): err = %v, want nil", payload, err)
}
if string(got) != payload {
t.Errorf("ValidatePayload = %q, want %q", got, payload)
}
// check that if payload is invalid we get error
req.Header.Set(signatureHeader, "invalid signature")
if _, err = ValidatePayload(req, nil); err == nil {
t.Error("ValidatePayload = nil, want err")
}
}
func TestValidatePayload_FormPost(t *testing.T) {
payload := `{"yo":true}`
signature := "sha1=3374ef144403e8035423b23b02e2c9d7a4c50368"
secretKey := []byte("0123456789abcdef")
form := url.Values{}
form.Set("payload", payload)
buf := bytes.NewBufferString(form.Encode())
req, err := http.NewRequest("POST", "http://localhost/event", buf)
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set(signatureHeader, signature)
got, err := ValidatePayload(req, secretKey)
if err != nil {
t.Errorf("ValidatePayload(%#v): err = %v, want nil", payload, err)
}
if string(got) != payload {
t.Errorf("ValidatePayload = %q, want %q", got, payload)
}
// check that if payload is invalid we get error
req.Header.Set(signatureHeader, "invalid signature")
if _, err = ValidatePayload(req, nil); err == nil {
t.Error("ValidatePayload = nil, want err")
}
}
func TestValidatePayload_InvalidContentType(t *testing.T) {
req, err := http.NewRequest("POST", "http://localhost/event", nil)
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
req.Header.Set("Content-Type", "invalid content type")
if _, err = ValidatePayload(req, nil); err == nil {
t.Error("ValidatePayload = nil, want err")
}
}
func TestParseWebHook(t *testing.T) {
tests := []struct {
payload interface{}
messageType string
}{
{
payload: &CommitCommentEvent{},
messageType: "commit_comment",
},
{
payload: &CreateEvent{},
messageType: "create",
},
{
payload: &DeleteEvent{},
messageType: "delete",
},
{
payload: &DeploymentEvent{},
messageType: "deployment",
},
{
payload: &DeploymentStatusEvent{},
messageType: "deployment_status",
},
{
payload: &ForkEvent{},
messageType: "fork",
},
{
payload: &GollumEvent{},
messageType: "gollum",
},
{
payload: &InstallationEvent{},
messageType: "installation",
},
{
payload: &InstallationRepositoriesEvent{},
messageType: "installation_repositories",
},
{
payload: &IssueCommentEvent{},
messageType: "issue_comment",
},
{
payload: &IssuesEvent{},
messageType: "issues",
},
{
payload: &LabelEvent{},
messageType: "label",
},
{
payload: &MarketplacePurchaseEvent{},
messageType: "marketplace_purchase",
},
{
payload: &MemberEvent{},
messageType: "member",
},
{
payload: &MembershipEvent{},
messageType: "membership",
},
{
payload: &MilestoneEvent{},
messageType: "milestone",
},
{
payload: &OrganizationEvent{},
messageType: "organization",
},
{
payload: &OrgBlockEvent{},
messageType: "org_block",
},
{
payload: &PageBuildEvent{},
messageType: "page_build",
},
{
payload: &PingEvent{},
messageType: "ping",
},
{
payload: &ProjectEvent{},
messageType: "project",
},
{
payload: &ProjectCardEvent{},
messageType: "project_card",
},
{
payload: &ProjectColumnEvent{},
messageType: "project_column",
},
{
payload: &PublicEvent{},
messageType: "public",
},
{
payload: &PullRequestEvent{},
messageType: "pull_request",
},
{
payload: &PullRequestReviewEvent{},
messageType: "pull_request_review",
},
{
payload: &PullRequestReviewCommentEvent{},
messageType: "pull_request_review_comment",
},
{
payload: &PushEvent{},
messageType: "push",
},
{
payload: &ReleaseEvent{},
messageType: "release",
},
{
payload: &RepositoryEvent{},
messageType: "repository",
},
{
payload: &StatusEvent{},
messageType: "status",
},
{
payload: &TeamEvent{},
messageType: "team",
},
{
payload: &TeamAddEvent{},
messageType: "team_add",
},
{
payload: &WatchEvent{},
messageType: "watch",
},
}
for _, test := range tests {
p, err := json.Marshal(test.payload)
if err != nil {
t.Fatalf("Marshal(%#v): %v", test.payload, err)
}
got, err := ParseWebHook(test.messageType, p)
if err != nil {
t.Fatalf("ParseWebHook: %v", err)
}
if want := test.payload; !reflect.DeepEqual(got, want) {
t.Errorf("ParseWebHook(%#v, %#v) = %#v, want %#v", test.messageType, p, got, want)
}
}
}
func TestDeliveryID(t *testing.T) {
id := "8970a780-244e-11e7-91ca-da3aabcb9793"
req, err := http.NewRequest("POST", "http://localhost", nil)
if err != nil {
t.Fatalf("DeliveryID: %v", err)
}
req.Header.Set("X-Github-Delivery", id)
got := DeliveryID(req)
if got != id {
t.Errorf("DeliveryID(%#v) = %q, want %q", req, got, id)
}
}

View file

@ -1,226 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestMigrationService_StartImport(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Import{
VCS: String("git"),
VCSURL: String("url"),
VCSUsername: String("u"),
VCSPassword: String("p"),
}
mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) {
v := new(Import)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
testHeader(t, r, "Accept", mediaTypeImportPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, `{"status":"importing"}`)
})
got, _, err := client.Migrations.StartImport(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("StartImport returned error: %v", err)
}
want := &Import{Status: String("importing")}
if !reflect.DeepEqual(got, want) {
t.Errorf("StartImport = %+v, want %+v", got, want)
}
}
func TestMigrationService_ImportProgress(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeImportPreview)
fmt.Fprint(w, `{"status":"complete"}`)
})
got, _, err := client.Migrations.ImportProgress(context.Background(), "o", "r")
if err != nil {
t.Errorf("ImportProgress returned error: %v", err)
}
want := &Import{Status: String("complete")}
if !reflect.DeepEqual(got, want) {
t.Errorf("ImportProgress = %+v, want %+v", got, want)
}
}
func TestMigrationService_UpdateImport(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Import{
VCS: String("git"),
VCSURL: String("url"),
VCSUsername: String("u"),
VCSPassword: String("p"),
}
mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) {
v := new(Import)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeImportPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, `{"status":"importing"}`)
})
got, _, err := client.Migrations.UpdateImport(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("UpdateImport returned error: %v", err)
}
want := &Import{Status: String("importing")}
if !reflect.DeepEqual(got, want) {
t.Errorf("UpdateImport = %+v, want %+v", got, want)
}
}
func TestMigrationService_CommitAuthors(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/import/authors", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeImportPreview)
fmt.Fprint(w, `[{"id":1,"name":"a"},{"id":2,"name":"b"}]`)
})
got, _, err := client.Migrations.CommitAuthors(context.Background(), "o", "r")
if err != nil {
t.Errorf("CommitAuthors returned error: %v", err)
}
want := []*SourceImportAuthor{
{ID: Int64(1), Name: String("a")},
{ID: Int64(2), Name: String("b")},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("CommitAuthors = %+v, want %+v", got, want)
}
}
func TestMigrationService_MapCommitAuthor(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &SourceImportAuthor{Name: String("n"), Email: String("e")}
mux.HandleFunc("/repos/o/r/import/authors/1", func(w http.ResponseWriter, r *http.Request) {
v := new(SourceImportAuthor)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeImportPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id": 1}`)
})
got, _, err := client.Migrations.MapCommitAuthor(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("MapCommitAuthor returned error: %v", err)
}
want := &SourceImportAuthor{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("MapCommitAuthor = %+v, want %+v", got, want)
}
}
func TestMigrationService_SetLFSPreference(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Import{UseLFS: String("opt_in")}
mux.HandleFunc("/repos/o/r/import/lfs", func(w http.ResponseWriter, r *http.Request) {
v := new(Import)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeImportPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, `{"status":"importing"}`)
})
got, _, err := client.Migrations.SetLFSPreference(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("SetLFSPreference returned error: %v", err)
}
want := &Import{Status: String("importing")}
if !reflect.DeepEqual(got, want) {
t.Errorf("SetLFSPreference = %+v, want %+v", got, want)
}
}
func TestMigrationService_LargeFiles(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/import/large_files", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeImportPreview)
fmt.Fprint(w, `[{"oid":"a"},{"oid":"b"}]`)
})
got, _, err := client.Migrations.LargeFiles(context.Background(), "o", "r")
if err != nil {
t.Errorf("LargeFiles returned error: %v", err)
}
want := []*LargeFile{
{OID: String("a")},
{OID: String("b")},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("LargeFiles = %+v, want %+v", got, want)
}
}
func TestMigrationService_CancelImport(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeImportPreview)
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Migrations.CancelImport(context.Background(), "o", "r")
if err != nil {
t.Errorf("CancelImport returned error: %v", err)
}
}

View file

@ -1,178 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
)
func TestMigrationService_StartMigration(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/migrations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeMigrationsPreview)
w.WriteHeader(http.StatusCreated)
w.Write(migrationJSON)
})
opt := &MigrationOptions{
LockRepositories: true,
ExcludeAttachments: false,
}
got, _, err := client.Migrations.StartMigration(context.Background(), "o", []string{"r"}, opt)
if err != nil {
t.Errorf("StartMigration returned error: %v", err)
}
if want := wantMigration; !reflect.DeepEqual(got, want) {
t.Errorf("StartMigration = %+v, want %+v", got, want)
}
}
func TestMigrationService_ListMigrations(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/migrations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMigrationsPreview)
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("[%s]", migrationJSON)))
})
got, _, err := client.Migrations.ListMigrations(context.Background(), "o")
if err != nil {
t.Errorf("ListMigrations returned error: %v", err)
}
if want := []*Migration{wantMigration}; !reflect.DeepEqual(got, want) {
t.Errorf("ListMigrations = %+v, want %+v", got, want)
}
}
func TestMigrationService_MigrationStatus(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/migrations/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMigrationsPreview)
w.WriteHeader(http.StatusOK)
w.Write(migrationJSON)
})
got, _, err := client.Migrations.MigrationStatus(context.Background(), "o", 1)
if err != nil {
t.Errorf("MigrationStatus returned error: %v", err)
}
if want := wantMigration; !reflect.DeepEqual(got, want) {
t.Errorf("MigrationStatus = %+v, want %+v", got, want)
}
}
func TestMigrationService_MigrationArchiveURL(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/migrations/1/archive", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeMigrationsPreview)
http.Redirect(w, r, "/yo", http.StatusFound)
})
mux.HandleFunc("/yo", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusOK)
w.Write([]byte("0123456789abcdef"))
})
got, err := client.Migrations.MigrationArchiveURL(context.Background(), "o", 1)
if err != nil {
t.Errorf("MigrationStatus returned error: %v", err)
}
if want := "/yo"; !strings.HasSuffix(got, want) {
t.Errorf("MigrationArchiveURL = %+v, want %+v", got, want)
}
}
func TestMigrationService_DeleteMigration(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/migrations/1/archive", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeMigrationsPreview)
w.WriteHeader(http.StatusNoContent)
})
if _, err := client.Migrations.DeleteMigration(context.Background(), "o", 1); err != nil {
t.Errorf("DeleteMigration returned error: %v", err)
}
}
func TestMigrationService_UnlockRepo(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/migrations/1/repos/r/lock", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeMigrationsPreview)
w.WriteHeader(http.StatusNoContent)
})
if _, err := client.Migrations.UnlockRepo(context.Background(), "o", 1, "r"); err != nil {
t.Errorf("UnlockRepo returned error: %v", err)
}
}
var migrationJSON = []byte(`{
"id": 79,
"guid": "0b989ba4-242f-11e5-81e1-c7b6966d2516",
"state": "pending",
"lock_repositories": true,
"exclude_attachments": false,
"url": "https://api.github.com/orgs/octo-org/migrations/79",
"created_at": "2015-07-06T15:33:38-07:00",
"updated_at": "2015-07-06T15:33:38-07:00",
"repositories": [
{
"id": 1296269,
"name": "Hello-World",
"full_name": "octocat/Hello-World",
"description": "This your first repo!"
}
]
}`)
var wantMigration = &Migration{
ID: Int64(79),
GUID: String("0b989ba4-242f-11e5-81e1-c7b6966d2516"),
State: String("pending"),
LockRepositories: Bool(true),
ExcludeAttachments: Bool(false),
URL: String("https://api.github.com/orgs/octo-org/migrations/79"),
CreatedAt: String("2015-07-06T15:33:38-07:00"),
UpdatedAt: String("2015-07-06T15:33:38-07:00"),
Repositories: []*Repository{
{
ID: Int64(1296269),
Name: String("Hello-World"),
FullName: String("octocat/Hello-World"),
Description: String("This your first repo!"),
},
},
}

View file

@ -1,232 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestMarkdown(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &markdownRequest{
Text: String("# text #"),
Mode: String("gfm"),
Context: String("google/go-github"),
}
mux.HandleFunc("/markdown", func(w http.ResponseWriter, r *http.Request) {
v := new(markdownRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `<h1>text</h1>`)
})
md, _, err := client.Markdown(context.Background(), "# text #", &MarkdownOptions{
Mode: "gfm",
Context: "google/go-github",
})
if err != nil {
t.Errorf("Markdown returned error: %v", err)
}
if want := "<h1>text</h1>"; want != md {
t.Errorf("Markdown returned %+v, want %+v", md, want)
}
}
func TestListEmojis(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/emojis", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"+1": "+1.png"}`)
})
emoji, _, err := client.ListEmojis(context.Background())
if err != nil {
t.Errorf("ListEmojis returned error: %v", err)
}
want := map[string]string{"+1": "+1.png"}
if !reflect.DeepEqual(want, emoji) {
t.Errorf("ListEmojis returned %+v, want %+v", emoji, want)
}
}
func TestListCodesOfConduct(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/codes_of_conduct", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeCodesOfConductPreview)
fmt.Fprint(w, `[{
"key": "key",
"name": "name",
"url": "url"}
]`)
})
cs, _, err := client.ListCodesOfConduct(context.Background())
if err != nil {
t.Errorf("ListCodesOfConduct returned error: %v", err)
}
want := []*CodeOfConduct{
{
Key: String("key"),
Name: String("name"),
URL: String("url"),
}}
if !reflect.DeepEqual(want, cs) {
t.Errorf("ListCodesOfConduct returned %+v, want %+v", cs, want)
}
}
func TestGetCodeOfConduct(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/codes_of_conduct/k", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeCodesOfConductPreview)
fmt.Fprint(w, `{
"key": "key",
"name": "name",
"url": "url",
"body": "body"}`,
)
})
coc, _, err := client.GetCodeOfConduct(context.Background(), "k")
if err != nil {
t.Errorf("ListCodesOfConduct returned error: %v", err)
}
want := &CodeOfConduct{
Key: String("key"),
Name: String("name"),
URL: String("url"),
Body: String("body"),
}
if !reflect.DeepEqual(want, coc) {
t.Errorf("GetCodeOfConductByKey returned %+v, want %+v", coc, want)
}
}
func TestAPIMeta(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/meta", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"hooks":["h"], "git":["g"], "pages":["p"], "verifiable_password_authentication": true}`)
})
meta, _, err := client.APIMeta(context.Background())
if err != nil {
t.Errorf("APIMeta returned error: %v", err)
}
want := &APIMeta{
Hooks: []string{"h"},
Git: []string{"g"},
Pages: []string{"p"},
VerifiablePasswordAuthentication: Bool(true),
}
if !reflect.DeepEqual(want, meta) {
t.Errorf("APIMeta returned %+v, want %+v", meta, want)
}
}
func TestOctocat(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := "input"
output := "sample text"
mux.HandleFunc("/octocat", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"s": input})
w.Header().Set("Content-Type", "application/octocat-stream")
fmt.Fprint(w, output)
})
got, _, err := client.Octocat(context.Background(), input)
if err != nil {
t.Errorf("Octocat returned error: %v", err)
}
if want := output; got != want {
t.Errorf("Octocat returned %+v, want %+v", got, want)
}
}
func TestZen(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
output := "sample text"
mux.HandleFunc("/zen", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.Header().Set("Content-Type", "text/plain;charset=utf-8")
fmt.Fprint(w, output)
})
got, _, err := client.Zen(context.Background())
if err != nil {
t.Errorf("Zen returned error: %v", err)
}
if want := output; got != want {
t.Errorf("Zen returned %+v, want %+v", got, want)
}
}
func TestListServiceHooks(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/hooks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{
"name":"n",
"events":["e"],
"supported_events":["s"],
"schema":[
["a", "b"]
]
}]`)
})
hooks, _, err := client.ListServiceHooks(context.Background())
if err != nil {
t.Errorf("ListServiceHooks returned error: %v", err)
}
want := []*ServiceHook{{
Name: String("n"),
Events: []string{"e"},
SupportedEvents: []string{"s"},
Schema: [][]string{{"a", "b"}},
}}
if !reflect.DeepEqual(hooks, want) {
t.Errorf("ListServiceHooks returned %+v, want %+v", hooks, want)
}
}

View file

@ -1,147 +0,0 @@
// Copyright 2015 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestOrganizationsService_ListHooks(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/hooks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}, {"id":2}]`)
})
opt := &ListOptions{Page: 2}
hooks, _, err := client.Organizations.ListHooks(context.Background(), "o", opt)
if err != nil {
t.Errorf("Organizations.ListHooks returned error: %v", err)
}
want := []*Hook{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(hooks, want) {
t.Errorf("Organizations.ListHooks returned %+v, want %+v", hooks, want)
}
}
func TestOrganizationsService_ListHooks_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.ListHooks(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestOrganizationsService_GetHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
hook, _, err := client.Organizations.GetHook(context.Background(), "o", 1)
if err != nil {
t.Errorf("Organizations.GetHook returned error: %v", err)
}
want := &Hook{ID: Int64(1)}
if !reflect.DeepEqual(hook, want) {
t.Errorf("Organizations.GetHook returned %+v, want %+v", hook, want)
}
}
func TestOrganizationsService_GetHook_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.GetHook(context.Background(), "%", 1)
testURLParseError(t, err)
}
func TestOrganizationsService_EditHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Hook{Name: String("t")}
mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) {
v := new(Hook)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
hook, _, err := client.Organizations.EditHook(context.Background(), "o", 1, input)
if err != nil {
t.Errorf("Organizations.EditHook returned error: %v", err)
}
want := &Hook{ID: Int64(1)}
if !reflect.DeepEqual(hook, want) {
t.Errorf("Organizations.EditHook returned %+v, want %+v", hook, want)
}
}
func TestOrganizationsService_EditHook_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.EditHook(context.Background(), "%", 1, nil)
testURLParseError(t, err)
}
func TestOrganizationsService_PingHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/hooks/1/pings", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
})
_, err := client.Organizations.PingHook(context.Background(), "o", 1)
if err != nil {
t.Errorf("Organizations.PingHook returned error: %v", err)
}
}
func TestOrganizationsService_DeleteHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Organizations.DeleteHook(context.Background(), "o", 1)
if err != nil {
t.Errorf("Organizations.DeleteHook returned error: %v", err)
}
}
func TestOrganizationsService_DeleteHook_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Organizations.DeleteHook(context.Background(), "%", 1)
testURLParseError(t, err)
}

View file

@ -1,446 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestOrganizationsService_ListMembers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/members", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"filter": "2fa_disabled",
"role": "admin",
"page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListMembersOptions{
PublicOnly: false,
Filter: "2fa_disabled",
Role: "admin",
ListOptions: ListOptions{Page: 2},
}
members, _, err := client.Organizations.ListMembers(context.Background(), "o", opt)
if err != nil {
t.Errorf("Organizations.ListMembers returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(members, want) {
t.Errorf("Organizations.ListMembers returned %+v, want %+v", members, want)
}
}
func TestOrganizationsService_ListMembers_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.ListMembers(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestOrganizationsService_ListMembers_public(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/public_members", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListMembersOptions{PublicOnly: true}
members, _, err := client.Organizations.ListMembers(context.Background(), "o", opt)
if err != nil {
t.Errorf("Organizations.ListMembers returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(members, want) {
t.Errorf("Organizations.ListMembers returned %+v, want %+v", members, want)
}
}
func TestOrganizationsService_IsMember(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNoContent)
})
member, _, err := client.Organizations.IsMember(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.IsMember returned error: %v", err)
}
if want := true; member != want {
t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want)
}
}
// ensure that a 404 response is interpreted as "false" and not an error
func TestOrganizationsService_IsMember_notMember(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
member, _, err := client.Organizations.IsMember(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.IsMember returned error: %+v", err)
}
if want := false; member != want {
t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want)
}
}
// ensure that a 400 response is interpreted as an actual error, and not simply
// as "false" like the above case of a 404
func TestOrganizationsService_IsMember_error(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
http.Error(w, "BadRequest", http.StatusBadRequest)
})
member, _, err := client.Organizations.IsMember(context.Background(), "o", "u")
if err == nil {
t.Errorf("Expected HTTP 400 response")
}
if want := false; member != want {
t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want)
}
}
func TestOrganizationsService_IsMember_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.IsMember(context.Background(), "%", "u")
testURLParseError(t, err)
}
func TestOrganizationsService_IsPublicMember(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNoContent)
})
member, _, err := client.Organizations.IsPublicMember(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.IsPublicMember returned error: %v", err)
}
if want := true; member != want {
t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want)
}
}
// ensure that a 404 response is interpreted as "false" and not an error
func TestOrganizationsService_IsPublicMember_notMember(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
member, _, err := client.Organizations.IsPublicMember(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.IsPublicMember returned error: %v", err)
}
if want := false; member != want {
t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want)
}
}
// ensure that a 400 response is interpreted as an actual error, and not simply
// as "false" like the above case of a 404
func TestOrganizationsService_IsPublicMember_error(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
http.Error(w, "BadRequest", http.StatusBadRequest)
})
member, _, err := client.Organizations.IsPublicMember(context.Background(), "o", "u")
if err == nil {
t.Errorf("Expected HTTP 400 response")
}
if want := false; member != want {
t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want)
}
}
func TestOrganizationsService_IsPublicMember_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.IsPublicMember(context.Background(), "%", "u")
testURLParseError(t, err)
}
func TestOrganizationsService_RemoveMember(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Organizations.RemoveMember(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.RemoveMember returned error: %v", err)
}
}
func TestOrganizationsService_RemoveMember_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Organizations.RemoveMember(context.Background(), "%", "u")
testURLParseError(t, err)
}
func TestOrganizationsService_ListOrgMemberships(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/memberships/orgs", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"state": "active",
"page": "2",
})
fmt.Fprint(w, `[{"url":"u"}]`)
})
opt := &ListOrgMembershipsOptions{
State: "active",
ListOptions: ListOptions{Page: 2},
}
memberships, _, err := client.Organizations.ListOrgMemberships(context.Background(), opt)
if err != nil {
t.Errorf("Organizations.ListOrgMemberships returned error: %v", err)
}
want := []*Membership{{URL: String("u")}}
if !reflect.DeepEqual(memberships, want) {
t.Errorf("Organizations.ListOrgMemberships returned %+v, want %+v", memberships, want)
}
}
func TestOrganizationsService_GetOrgMembership_AuthenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/memberships/orgs/o", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"url":"u"}`)
})
membership, _, err := client.Organizations.GetOrgMembership(context.Background(), "", "o")
if err != nil {
t.Errorf("Organizations.GetOrgMembership returned error: %v", err)
}
want := &Membership{URL: String("u")}
if !reflect.DeepEqual(membership, want) {
t.Errorf("Organizations.GetOrgMembership returned %+v, want %+v", membership, want)
}
}
func TestOrganizationsService_GetOrgMembership_SpecifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"url":"u"}`)
})
membership, _, err := client.Organizations.GetOrgMembership(context.Background(), "u", "o")
if err != nil {
t.Errorf("Organizations.GetOrgMembership returned error: %v", err)
}
want := &Membership{URL: String("u")}
if !reflect.DeepEqual(membership, want) {
t.Errorf("Organizations.GetOrgMembership returned %+v, want %+v", membership, want)
}
}
func TestOrganizationsService_EditOrgMembership_AuthenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Membership{State: String("active")}
mux.HandleFunc("/user/memberships/orgs/o", func(w http.ResponseWriter, r *http.Request) {
v := new(Membership)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"url":"u"}`)
})
membership, _, err := client.Organizations.EditOrgMembership(context.Background(), "", "o", input)
if err != nil {
t.Errorf("Organizations.EditOrgMembership returned error: %v", err)
}
want := &Membership{URL: String("u")}
if !reflect.DeepEqual(membership, want) {
t.Errorf("Organizations.EditOrgMembership returned %+v, want %+v", membership, want)
}
}
func TestOrganizationsService_EditOrgMembership_SpecifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Membership{State: String("active")}
mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) {
v := new(Membership)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"url":"u"}`)
})
membership, _, err := client.Organizations.EditOrgMembership(context.Background(), "u", "o", input)
if err != nil {
t.Errorf("Organizations.EditOrgMembership returned error: %v", err)
}
want := &Membership{URL: String("u")}
if !reflect.DeepEqual(membership, want) {
t.Errorf("Organizations.EditOrgMembership returned %+v, want %+v", membership, want)
}
}
func TestOrganizationsService_RemoveOrgMembership(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Organizations.RemoveOrgMembership(context.Background(), "u", "o")
if err != nil {
t.Errorf("Organizations.RemoveOrgMembership returned error: %v", err)
}
}
func TestOrganizationsService_ListPendingOrgInvitations(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/invitations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "1"})
fmt.Fprint(w, `[
{
"id": 1,
"login": "monalisa",
"email": "octocat@github.com",
"role": "direct_member",
"created_at": "2017-01-21T00:00:00Z",
"inviter": {
"login": "other_user",
"id": 1,
"avatar_url": "https://github.com/images/error/other_user_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/other_user",
"html_url": "https://github.com/other_user",
"followers_url": "https://api.github.com/users/other_user/followers",
"following_url": "https://api.github.com/users/other_user/following/other_user",
"gists_url": "https://api.github.com/users/other_user/gists/gist_id",
"starred_url": "https://api.github.com/users/other_user/starred/owner/repo",
"subscriptions_url": "https://api.github.com/users/other_user/subscriptions",
"organizations_url": "https://api.github.com/users/other_user/orgs",
"repos_url": "https://api.github.com/users/other_user/repos",
"events_url": "https://api.github.com/users/other_user/events/privacy",
"received_events_url": "https://api.github.com/users/other_user/received_events/privacy",
"type": "User",
"site_admin": false
}
}
]`)
})
opt := &ListOptions{Page: 1}
invitations, _, err := client.Organizations.ListPendingOrgInvitations(context.Background(), "o", opt)
if err != nil {
t.Errorf("Organizations.ListPendingOrgInvitations returned error: %v", err)
}
createdAt := time.Date(2017, 01, 21, 0, 0, 0, 0, time.UTC)
want := []*Invitation{
{
ID: Int64(1),
Login: String("monalisa"),
Email: String("octocat@github.com"),
Role: String("direct_member"),
CreatedAt: &createdAt,
Inviter: &User{
Login: String("other_user"),
ID: Int64(1),
AvatarURL: String("https://github.com/images/error/other_user_happy.gif"),
GravatarID: String(""),
URL: String("https://api.github.com/users/other_user"),
HTMLURL: String("https://github.com/other_user"),
FollowersURL: String("https://api.github.com/users/other_user/followers"),
FollowingURL: String("https://api.github.com/users/other_user/following/other_user"),
GistsURL: String("https://api.github.com/users/other_user/gists/gist_id"),
StarredURL: String("https://api.github.com/users/other_user/starred/owner/repo"),
SubscriptionsURL: String("https://api.github.com/users/other_user/subscriptions"),
OrganizationsURL: String("https://api.github.com/users/other_user/orgs"),
ReposURL: String("https://api.github.com/users/other_user/repos"),
EventsURL: String("https://api.github.com/users/other_user/events/privacy"),
ReceivedEventsURL: String("https://api.github.com/users/other_user/received_events/privacy"),
Type: String("User"),
SiteAdmin: Bool(false),
},
}}
if !reflect.DeepEqual(invitations, want) {
t.Errorf("Organizations.ListPendingOrgInvitations returned %+v, want %+v", invitations, want)
}
}

View file

@ -1,134 +0,0 @@
// Copyright 2017 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestOrganizationsService_ListOutsideCollaborators(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/outside_collaborators", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"filter": "2fa_disabled",
"page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOutsideCollaboratorsOptions{
Filter: "2fa_disabled",
ListOptions: ListOptions{Page: 2},
}
members, _, err := client.Organizations.ListOutsideCollaborators(context.Background(), "o", opt)
if err != nil {
t.Errorf("Organizations.ListOutsideCollaborators returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(members, want) {
t.Errorf("Organizations.ListOutsideCollaborators returned %+v, want %+v", members, want)
}
}
func TestOrganizationsService_ListOutsideCollaborators_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.ListOutsideCollaborators(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestOrganizationsService_RemoveOutsideCollaborator(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
handler := func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
}
mux.HandleFunc("/orgs/o/outside_collaborators/u", handler)
_, err := client.Organizations.RemoveOutsideCollaborator(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.RemoveOutsideCollaborator returned error: %v", err)
}
}
func TestOrganizationsService_RemoveOutsideCollaborator_NonMember(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
handler := func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNotFound)
}
mux.HandleFunc("/orgs/o/outside_collaborators/u", handler)
_, err := client.Organizations.RemoveOutsideCollaborator(context.Background(), "o", "u")
if err, ok := err.(*ErrorResponse); !ok {
t.Errorf("Organizations.RemoveOutsideCollaborator did not return an error")
} else if err.Response.StatusCode != http.StatusNotFound {
t.Errorf("Organizations.RemoveOutsideCollaborator did not return 404 status code")
}
}
func TestOrganizationsService_RemoveOutsideCollaborator_Member(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
handler := func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusUnprocessableEntity)
}
mux.HandleFunc("/orgs/o/outside_collaborators/u", handler)
_, err := client.Organizations.RemoveOutsideCollaborator(context.Background(), "o", "u")
if err, ok := err.(*ErrorResponse); !ok {
t.Errorf("Organizations.RemoveOutsideCollaborator did not return an error")
} else if err.Response.StatusCode != http.StatusUnprocessableEntity {
t.Errorf("Organizations.RemoveOutsideCollaborator did not return 422 status code")
}
}
func TestOrganizationsService_ConvertMemberToOutsideCollaborator(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
handler := func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
}
mux.HandleFunc("/orgs/o/outside_collaborators/u", handler)
_, err := client.Organizations.ConvertMemberToOutsideCollaborator(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.ConvertMemberToOutsideCollaborator returned error: %v", err)
}
}
func TestOrganizationsService_ConvertMemberToOutsideCollaborator_NonMemberOrLastOwner(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
handler := func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
w.WriteHeader(http.StatusForbidden)
}
mux.HandleFunc("/orgs/o/outside_collaborators/u", handler)
_, err := client.Organizations.ConvertMemberToOutsideCollaborator(context.Background(), "o", "u")
if err, ok := err.(*ErrorResponse); !ok {
t.Errorf("Organizations.ConvertMemberToOutsideCollaborator did not return an error")
} else if err.Response.StatusCode != http.StatusForbidden {
t.Errorf("Organizations.ConvertMemberToOutsideCollaborator did not return 403 status code")
}
}

View file

@ -1,68 +0,0 @@
// Copyright 2017 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestOrganizationsService_ListProjects(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/projects", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
testFormValues(t, r, values{"state": "open", "page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ProjectListOptions{State: "open", ListOptions: ListOptions{Page: 2}}
projects, _, err := client.Organizations.ListProjects(context.Background(), "o", opt)
if err != nil {
t.Errorf("Organizations.ListProjects returned error: %v", err)
}
want := []*Project{{ID: Int64(1)}}
if !reflect.DeepEqual(projects, want) {
t.Errorf("Organizations.ListProjects returned %+v, want %+v", projects, want)
}
}
func TestOrganizationsService_CreateProject(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectOptions{Name: "Project Name", Body: "Project body."}
mux.HandleFunc("/orgs/o/projects", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
project, _, err := client.Organizations.CreateProject(context.Background(), "o", input)
if err != nil {
t.Errorf("Organizations.CreateProject returned error: %v", err)
}
want := &Project{ID: Int64(1)}
if !reflect.DeepEqual(project, want) {
t.Errorf("Organizations.CreateProject returned %+v, want %+v", project, want)
}
}

View file

@ -1,663 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
"time"
)
func TestOrganizationsService_ListTeams(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/teams", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
teams, _, err := client.Organizations.ListTeams(context.Background(), "o", opt)
if err != nil {
t.Errorf("Organizations.ListTeams returned error: %v", err)
}
want := []*Team{{ID: Int64(1)}}
if !reflect.DeepEqual(teams, want) {
t.Errorf("Organizations.ListTeams returned %+v, want %+v", teams, want)
}
}
func TestOrganizationsService_ListTeams_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.ListTeams(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestOrganizationsService_GetTeam(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
fmt.Fprint(w, `{"id":1, "name":"n", "description": "d", "url":"u", "slug": "s", "permission":"p", "ldap_dn":"cn=n,ou=groups,dc=example,dc=com", "parent":null}`)
})
team, _, err := client.Organizations.GetTeam(context.Background(), 1)
if err != nil {
t.Errorf("Organizations.GetTeam returned error: %v", err)
}
want := &Team{ID: Int64(1), Name: String("n"), Description: String("d"), URL: String("u"), Slug: String("s"), Permission: String("p"), LDAPDN: String("cn=n,ou=groups,dc=example,dc=com")}
if !reflect.DeepEqual(team, want) {
t.Errorf("Organizations.GetTeam returned %+v, want %+v", team, want)
}
}
func TestOrganizationService_GetTeam_nestedTeams(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
fmt.Fprint(w, `{"id":1, "name":"n", "description": "d", "url":"u", "slug": "s", "permission":"p",
"parent": {"id":2, "name":"n", "description": "d", "parent": null}}`)
})
team, _, err := client.Organizations.GetTeam(context.Background(), 1)
if err != nil {
t.Errorf("Organizations.GetTeam returned error: %v", err)
}
want := &Team{ID: Int64(1), Name: String("n"), Description: String("d"), URL: String("u"), Slug: String("s"), Permission: String("p"),
Parent: &Team{ID: Int64(2), Name: String("n"), Description: String("d")},
}
if !reflect.DeepEqual(team, want) {
t.Errorf("Organizations.GetTeam returned %+v, want %+v", team, want)
}
}
func TestOrganizationsService_CreateTeam(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &NewTeam{Name: "n", Privacy: String("closed"), RepoNames: []string{"r"}}
mux.HandleFunc("/orgs/o/teams", func(w http.ResponseWriter, r *http.Request) {
v := new(NewTeam)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
team, _, err := client.Organizations.CreateTeam(context.Background(), "o", input)
if err != nil {
t.Errorf("Organizations.CreateTeam returned error: %v", err)
}
want := &Team{ID: Int64(1)}
if !reflect.DeepEqual(team, want) {
t.Errorf("Organizations.CreateTeam returned %+v, want %+v", team, want)
}
}
func TestOrganizationsService_CreateTeam_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.CreateTeam(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestOrganizationsService_EditTeam(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &NewTeam{Name: "n", Privacy: String("closed")}
mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) {
v := new(NewTeam)
json.NewDecoder(r.Body).Decode(v)
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
team, _, err := client.Organizations.EditTeam(context.Background(), 1, input)
if err != nil {
t.Errorf("Organizations.EditTeam returned error: %v", err)
}
want := &Team{ID: Int64(1)}
if !reflect.DeepEqual(team, want) {
t.Errorf("Organizations.EditTeam returned %+v, want %+v", team, want)
}
}
func TestOrganizationsService_DeleteTeam(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
})
_, err := client.Organizations.DeleteTeam(context.Background(), 1)
if err != nil {
t.Errorf("Organizations.DeleteTeam returned error: %v", err)
}
}
func TestOrganizationsService_ListChildTeams(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/teams", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":2}]`)
})
opt := &ListOptions{Page: 2}
teams, _, err := client.Organizations.ListChildTeams(context.Background(), 1, opt)
if err != nil {
t.Errorf("Organizations.ListTeams returned error: %v", err)
}
want := []*Team{{ID: Int64(2)}}
if !reflect.DeepEqual(teams, want) {
t.Errorf("Organizations.ListTeams returned %+v, want %+v", teams, want)
}
}
func TestOrganizationsService_ListTeamMembers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/members", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
testFormValues(t, r, values{"role": "member", "page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &OrganizationListTeamMembersOptions{Role: "member", ListOptions: ListOptions{Page: 2}}
members, _, err := client.Organizations.ListTeamMembers(context.Background(), 1, opt)
if err != nil {
t.Errorf("Organizations.ListTeamMembers returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(members, want) {
t.Errorf("Organizations.ListTeamMembers returned %+v, want %+v", members, want)
}
}
func TestOrganizationsService_IsTeamMember_true(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
})
member, _, err := client.Organizations.IsTeamMember(context.Background(), 1, "u")
if err != nil {
t.Errorf("Organizations.IsTeamMember returned error: %v", err)
}
if want := true; member != want {
t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want)
}
}
// ensure that a 404 response is interpreted as "false" and not an error
func TestOrganizationsService_IsTeamMember_false(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
member, _, err := client.Organizations.IsTeamMember(context.Background(), 1, "u")
if err != nil {
t.Errorf("Organizations.IsTeamMember returned error: %+v", err)
}
if want := false; member != want {
t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want)
}
}
// ensure that a 400 response is interpreted as an actual error, and not simply
// as "false" like the above case of a 404
func TestOrganizationsService_IsTeamMember_error(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
http.Error(w, "BadRequest", http.StatusBadRequest)
})
member, _, err := client.Organizations.IsTeamMember(context.Background(), 1, "u")
if err == nil {
t.Errorf("Expected HTTP 400 response")
}
if want := false; member != want {
t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want)
}
}
func TestOrganizationsService_IsTeamMember_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.IsTeamMember(context.Background(), 1, "%")
testURLParseError(t, err)
}
func TestOrganizationsService_PublicizeMembership(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Organizations.PublicizeMembership(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.PublicizeMembership returned error: %v", err)
}
}
func TestOrganizationsService_PublicizeMembership_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Organizations.PublicizeMembership(context.Background(), "%", "u")
testURLParseError(t, err)
}
func TestOrganizationsService_ConcealMembership(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Organizations.ConcealMembership(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.ConcealMembership returned error: %v", err)
}
}
func TestOrganizationsService_ConcealMembership_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Organizations.ConcealMembership(context.Background(), "%", "u")
testURLParseError(t, err)
}
func TestOrganizationsService_ListTeamRepos(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/repos", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
acceptHeaders := []string{mediaTypeTopicsPreview, mediaTypeNestedTeamsPreview}
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
members, _, err := client.Organizations.ListTeamRepos(context.Background(), 1, opt)
if err != nil {
t.Errorf("Organizations.ListTeamRepos returned error: %v", err)
}
want := []*Repository{{ID: Int64(1)}}
if !reflect.DeepEqual(members, want) {
t.Errorf("Organizations.ListTeamRepos returned %+v, want %+v", members, want)
}
}
func TestOrganizationsService_IsTeamRepo_true(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
acceptHeaders := []string{mediaTypeOrgPermissionRepo, mediaTypeNestedTeamsPreview}
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
fmt.Fprint(w, `{"id":1}`)
})
repo, _, err := client.Organizations.IsTeamRepo(context.Background(), 1, "o", "r")
if err != nil {
t.Errorf("Organizations.IsTeamRepo returned error: %v", err)
}
want := &Repository{ID: Int64(1)}
if !reflect.DeepEqual(repo, want) {
t.Errorf("Organizations.IsTeamRepo returned %+v, want %+v", repo, want)
}
}
func TestOrganizationsService_IsTeamRepo_false(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
repo, resp, err := client.Organizations.IsTeamRepo(context.Background(), 1, "o", "r")
if err == nil {
t.Errorf("Expected HTTP 404 response")
}
if got, want := resp.Response.StatusCode, http.StatusNotFound; got != want {
t.Errorf("Organizations.IsTeamRepo returned status %d, want %d", got, want)
}
if repo != nil {
t.Errorf("Organizations.IsTeamRepo returned %+v, want nil", repo)
}
}
func TestOrganizationsService_IsTeamRepo_error(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
http.Error(w, "BadRequest", http.StatusBadRequest)
})
repo, resp, err := client.Organizations.IsTeamRepo(context.Background(), 1, "o", "r")
if err == nil {
t.Errorf("Expected HTTP 400 response")
}
if got, want := resp.Response.StatusCode, http.StatusBadRequest; got != want {
t.Errorf("Organizations.IsTeamRepo returned status %d, want %d", got, want)
}
if repo != nil {
t.Errorf("Organizations.IsTeamRepo returned %+v, want nil", repo)
}
}
func TestOrganizationsService_IsTeamRepo_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.IsTeamRepo(context.Background(), 1, "%", "r")
testURLParseError(t, err)
}
func TestOrganizationsService_AddTeamRepo(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
opt := &OrganizationAddTeamRepoOptions{Permission: "admin"}
mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) {
v := new(OrganizationAddTeamRepoOptions)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
if !reflect.DeepEqual(v, opt) {
t.Errorf("Request body = %+v, want %+v", v, opt)
}
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Organizations.AddTeamRepo(context.Background(), 1, "o", "r", opt)
if err != nil {
t.Errorf("Organizations.AddTeamRepo returned error: %v", err)
}
}
func TestOrganizationsService_AddTeamRepo_noAccess(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
w.WriteHeader(http.StatusUnprocessableEntity)
})
_, err := client.Organizations.AddTeamRepo(context.Background(), 1, "o", "r", nil)
if err == nil {
t.Errorf("Expcted error to be returned")
}
}
func TestOrganizationsService_AddTeamRepo_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Organizations.AddTeamRepo(context.Background(), 1, "%", "r", nil)
testURLParseError(t, err)
}
func TestOrganizationsService_RemoveTeamRepo(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Organizations.RemoveTeamRepo(context.Background(), 1, "o", "r")
if err != nil {
t.Errorf("Organizations.RemoveTeamRepo returned error: %v", err)
}
}
func TestOrganizationsService_RemoveTeamRepo_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Organizations.RemoveTeamRepo(context.Background(), 1, "%", "r")
testURLParseError(t, err)
}
func TestOrganizationsService_GetTeamMembership(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
fmt.Fprint(w, `{"url":"u", "state":"active"}`)
})
membership, _, err := client.Organizations.GetTeamMembership(context.Background(), 1, "u")
if err != nil {
t.Errorf("Organizations.GetTeamMembership returned error: %v", err)
}
want := &Membership{URL: String("u"), State: String("active")}
if !reflect.DeepEqual(membership, want) {
t.Errorf("Organizations.GetTeamMembership returned %+v, want %+v", membership, want)
}
}
func TestOrganizationsService_AddTeamMembership(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
opt := &OrganizationAddTeamMembershipOptions{Role: "maintainer"}
mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) {
v := new(OrganizationAddTeamMembershipOptions)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
if !reflect.DeepEqual(v, opt) {
t.Errorf("Request body = %+v, want %+v", v, opt)
}
fmt.Fprint(w, `{"url":"u", "state":"pending"}`)
})
membership, _, err := client.Organizations.AddTeamMembership(context.Background(), 1, "u", opt)
if err != nil {
t.Errorf("Organizations.AddTeamMembership returned error: %v", err)
}
want := &Membership{URL: String("u"), State: String("pending")}
if !reflect.DeepEqual(membership, want) {
t.Errorf("Organizations.AddTeamMembership returned %+v, want %+v", membership, want)
}
}
func TestOrganizationsService_RemoveTeamMembership(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Organizations.RemoveTeamMembership(context.Background(), 1, "u")
if err != nil {
t.Errorf("Organizations.RemoveTeamMembership returned error: %v", err)
}
}
func TestOrganizationsService_ListUserTeams(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/teams", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
testFormValues(t, r, values{"page": "1"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 1}
teams, _, err := client.Organizations.ListUserTeams(context.Background(), opt)
if err != nil {
t.Errorf("Organizations.ListUserTeams returned error: %v", err)
}
want := []*Team{{ID: Int64(1)}}
if !reflect.DeepEqual(teams, want) {
t.Errorf("Organizations.ListUserTeams returned %+v, want %+v", teams, want)
}
}
func TestOrganizationsService_ListPendingTeamInvitations(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/teams/1/invitations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "1"})
fmt.Fprint(w, `[
{
"id": 1,
"login": "monalisa",
"email": "octocat@github.com",
"role": "direct_member",
"created_at": "2017-01-21T00:00:00Z",
"inviter": {
"login": "other_user",
"id": 1,
"avatar_url": "https://github.com/images/error/other_user_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/other_user",
"html_url": "https://github.com/other_user",
"followers_url": "https://api.github.com/users/other_user/followers",
"following_url": "https://api.github.com/users/other_user/following/other_user",
"gists_url": "https://api.github.com/users/other_user/gists/gist_id",
"starred_url": "https://api.github.com/users/other_user/starred/owner/repo",
"subscriptions_url": "https://api.github.com/users/other_user/subscriptions",
"organizations_url": "https://api.github.com/users/other_user/orgs",
"repos_url": "https://api.github.com/users/other_user/repos",
"events_url": "https://api.github.com/users/other_user/events/privacy",
"received_events_url": "https://api.github.com/users/other_user/received_events/privacy",
"type": "User",
"site_admin": false
}
}
]`)
})
opt := &ListOptions{Page: 1}
invitations, _, err := client.Organizations.ListPendingTeamInvitations(context.Background(), 1, opt)
if err != nil {
t.Errorf("Organizations.ListPendingTeamInvitations returned error: %v", err)
}
createdAt := time.Date(2017, 01, 21, 0, 0, 0, 0, time.UTC)
want := []*Invitation{
{
ID: Int64(1),
Login: String("monalisa"),
Email: String("octocat@github.com"),
Role: String("direct_member"),
CreatedAt: &createdAt,
Inviter: &User{
Login: String("other_user"),
ID: Int64(1),
AvatarURL: String("https://github.com/images/error/other_user_happy.gif"),
GravatarID: String(""),
URL: String("https://api.github.com/users/other_user"),
HTMLURL: String("https://github.com/other_user"),
FollowersURL: String("https://api.github.com/users/other_user/followers"),
FollowingURL: String("https://api.github.com/users/other_user/following/other_user"),
GistsURL: String("https://api.github.com/users/other_user/gists/gist_id"),
StarredURL: String("https://api.github.com/users/other_user/starred/owner/repo"),
SubscriptionsURL: String("https://api.github.com/users/other_user/subscriptions"),
OrganizationsURL: String("https://api.github.com/users/other_user/orgs"),
ReposURL: String("https://api.github.com/users/other_user/repos"),
EventsURL: String("https://api.github.com/users/other_user/events/privacy"),
ReceivedEventsURL: String("https://api.github.com/users/other_user/received_events/privacy"),
Type: String("User"),
SiteAdmin: Bool(false),
},
}}
if !reflect.DeepEqual(invitations, want) {
t.Errorf("Organizations.ListPendingTeamInvitations returned %+v, want %+v", invitations, want)
}
}

View file

@ -1,179 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestOrganizationsService_ListAll(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
since := 1342004
mux.HandleFunc("/organizations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{"since": "1342004"})
fmt.Fprint(w, `[{"id":4314092}]`)
})
opt := &OrganizationsListOptions{Since: since}
orgs, _, err := client.Organizations.ListAll(context.Background(), opt)
if err != nil {
t.Errorf("Organizations.ListAll returned error: %v", err)
}
want := []*Organization{{ID: Int64(4314092)}}
if !reflect.DeepEqual(orgs, want) {
t.Errorf("Organizations.ListAll returned %+v, want %+v", orgs, want)
}
}
func TestOrganizationsService_List_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/orgs", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `[{"id":1},{"id":2}]`)
})
orgs, _, err := client.Organizations.List(context.Background(), "", nil)
if err != nil {
t.Errorf("Organizations.List returned error: %v", err)
}
want := []*Organization{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(orgs, want) {
t.Errorf("Organizations.List returned %+v, want %+v", orgs, want)
}
}
func TestOrganizationsService_List_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/orgs", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1},{"id":2}]`)
})
opt := &ListOptions{Page: 2}
orgs, _, err := client.Organizations.List(context.Background(), "u", opt)
if err != nil {
t.Errorf("Organizations.List returned error: %v", err)
}
want := []*Organization{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(orgs, want) {
t.Errorf("Organizations.List returned %+v, want %+v", orgs, want)
}
}
func TestOrganizationsService_List_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.List(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestOrganizationsService_Get(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"id":1, "login":"l", "url":"u", "avatar_url": "a", "location":"l"}`)
})
org, _, err := client.Organizations.Get(context.Background(), "o")
if err != nil {
t.Errorf("Organizations.Get returned error: %v", err)
}
want := &Organization{ID: Int64(1), Login: String("l"), URL: String("u"), AvatarURL: String("a"), Location: String("l")}
if !reflect.DeepEqual(org, want) {
t.Errorf("Organizations.Get returned %+v, want %+v", org, want)
}
}
func TestOrganizationsService_Get_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.Get(context.Background(), "%")
testURLParseError(t, err)
}
func TestOrganizationsService_GetByID(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/organizations/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"id":1, "login":"l", "url":"u", "avatar_url": "a", "location":"l"}`)
})
org, _, err := client.Organizations.GetByID(context.Background(), 1)
if err != nil {
t.Fatalf("Organizations.GetByID returned error: %v", err)
}
want := &Organization{ID: Int64(1), Login: String("l"), URL: String("u"), AvatarURL: String("a"), Location: String("l")}
if !reflect.DeepEqual(org, want) {
t.Errorf("Organizations.GetByID returned %+v, want %+v", org, want)
}
}
func TestOrganizationsService_Edit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Organization{Login: String("l")}
mux.HandleFunc("/orgs/o", func(w http.ResponseWriter, r *http.Request) {
v := new(Organization)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
org, _, err := client.Organizations.Edit(context.Background(), "o", input)
if err != nil {
t.Errorf("Organizations.Edit returned error: %v", err)
}
want := &Organization{ID: Int64(1)}
if !reflect.DeepEqual(org, want) {
t.Errorf("Organizations.Edit returned %+v, want %+v", org, want)
}
}
func TestOrganizationsService_Edit_invalidOrg(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Organizations.Edit(context.Background(), "%", nil)
testURLParseError(t, err)
}

View file

@ -1,90 +0,0 @@
// Copyright 2017 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestOrganizationsService_ListBlockedUsers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/blocks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeBlockUsersPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{
"login": "octocat"
}]`)
})
opt := &ListOptions{Page: 2}
blockedUsers, _, err := client.Organizations.ListBlockedUsers(context.Background(), "o", opt)
if err != nil {
t.Errorf("Organizations.ListBlockedUsers returned error: %v", err)
}
want := []*User{{Login: String("octocat")}}
if !reflect.DeepEqual(blockedUsers, want) {
t.Errorf("Organizations.ListBlockedUsers returned %+v, want %+v", blockedUsers, want)
}
}
func TestOrganizationsService_IsBlocked(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/blocks/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeBlockUsersPreview)
w.WriteHeader(http.StatusNoContent)
})
isBlocked, _, err := client.Organizations.IsBlocked(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.IsBlocked returned error: %v", err)
}
if want := true; isBlocked != want {
t.Errorf("Organizations.IsBlocked returned %+v, want %+v", isBlocked, want)
}
}
func TestOrganizationsService_BlockUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/blocks/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
testHeader(t, r, "Accept", mediaTypeBlockUsersPreview)
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Organizations.BlockUser(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.BlockUser returned error: %v", err)
}
}
func TestOrganizationsService_UnblockUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/orgs/o/blocks/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeBlockUsersPreview)
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Organizations.UnblockUser(context.Background(), "o", "u")
if err != nil {
t.Errorf("Organizations.UnblockUser returned error: %v", err)
}
}

View file

@ -1,371 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestProjectsService_UpdateProject(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectOptions{Name: "Project Name", Body: "Project body.", State: "open"}
mux.HandleFunc("/projects/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
project, _, err := client.Projects.UpdateProject(context.Background(), 1, input)
if err != nil {
t.Errorf("Projects.UpdateProject returned error: %v", err)
}
want := &Project{ID: Int64(1)}
if !reflect.DeepEqual(project, want) {
t.Errorf("Projects.UpdateProject returned %+v, want %+v", project, want)
}
}
func TestProjectsService_GetProject(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/projects/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
fmt.Fprint(w, `{"id":1}`)
})
project, _, err := client.Projects.GetProject(context.Background(), 1)
if err != nil {
t.Errorf("Projects.GetProject returned error: %v", err)
}
want := &Project{ID: Int64(1)}
if !reflect.DeepEqual(project, want) {
t.Errorf("Projects.GetProject returned %+v, want %+v", project, want)
}
}
func TestProjectsService_DeleteProject(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/projects/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
})
_, err := client.Projects.DeleteProject(context.Background(), 1)
if err != nil {
t.Errorf("Projects.DeleteProject returned error: %v", err)
}
}
func TestProjectsService_ListProjectColumns(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/projects/1/columns", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
columns, _, err := client.Projects.ListProjectColumns(context.Background(), 1, opt)
if err != nil {
t.Errorf("Projects.ListProjectColumns returned error: %v", err)
}
want := []*ProjectColumn{{ID: Int64(1)}}
if !reflect.DeepEqual(columns, want) {
t.Errorf("Projects.ListProjectColumns returned %+v, want %+v", columns, want)
}
}
func TestProjectsService_GetProjectColumn(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/projects/columns/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
fmt.Fprint(w, `{"id":1}`)
})
column, _, err := client.Projects.GetProjectColumn(context.Background(), 1)
if err != nil {
t.Errorf("Projects.GetProjectColumn returned error: %v", err)
}
want := &ProjectColumn{ID: Int64(1)}
if !reflect.DeepEqual(column, want) {
t.Errorf("Projects.GetProjectColumn returned %+v, want %+v", column, want)
}
}
func TestProjectsService_CreateProjectColumn(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectColumnOptions{Name: "Column Name"}
mux.HandleFunc("/projects/1/columns", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectColumnOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
column, _, err := client.Projects.CreateProjectColumn(context.Background(), 1, input)
if err != nil {
t.Errorf("Projects.CreateProjectColumn returned error: %v", err)
}
want := &ProjectColumn{ID: Int64(1)}
if !reflect.DeepEqual(column, want) {
t.Errorf("Projects.CreateProjectColumn returned %+v, want %+v", column, want)
}
}
func TestProjectsService_UpdateProjectColumn(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectColumnOptions{Name: "Column Name"}
mux.HandleFunc("/projects/columns/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectColumnOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
column, _, err := client.Projects.UpdateProjectColumn(context.Background(), 1, input)
if err != nil {
t.Errorf("Projects.UpdateProjectColumn returned error: %v", err)
}
want := &ProjectColumn{ID: Int64(1)}
if !reflect.DeepEqual(column, want) {
t.Errorf("Projects.UpdateProjectColumn returned %+v, want %+v", column, want)
}
}
func TestProjectsService_DeleteProjectColumn(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/projects/columns/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
})
_, err := client.Projects.DeleteProjectColumn(context.Background(), 1)
if err != nil {
t.Errorf("Projects.DeleteProjectColumn returned error: %v", err)
}
}
func TestProjectsService_MoveProjectColumn(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectColumnMoveOptions{Position: "after:12345"}
mux.HandleFunc("/projects/columns/1/moves", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectColumnMoveOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
})
_, err := client.Projects.MoveProjectColumn(context.Background(), 1, input)
if err != nil {
t.Errorf("Projects.MoveProjectColumn returned error: %v", err)
}
}
func TestProjectsService_ListProjectCards(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/projects/columns/1/cards", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
cards, _, err := client.Projects.ListProjectCards(context.Background(), 1, opt)
if err != nil {
t.Errorf("Projects.ListProjectCards returned error: %v", err)
}
want := []*ProjectCard{{ID: Int64(1)}}
if !reflect.DeepEqual(cards, want) {
t.Errorf("Projects.ListProjectCards returned %+v, want %+v", cards, want)
}
}
func TestProjectsService_GetProjectCard(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/projects/columns/cards/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
fmt.Fprint(w, `{"id":1}`)
})
card, _, err := client.Projects.GetProjectCard(context.Background(), 1)
if err != nil {
t.Errorf("Projects.GetProjectCard returned error: %v", err)
}
want := &ProjectCard{ID: Int64(1)}
if !reflect.DeepEqual(card, want) {
t.Errorf("Projects.GetProjectCard returned %+v, want %+v", card, want)
}
}
func TestProjectsService_CreateProjectCard(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectCardOptions{
ContentID: 12345,
ContentType: "Issue",
}
mux.HandleFunc("/projects/columns/1/cards", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectCardOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
card, _, err := client.Projects.CreateProjectCard(context.Background(), 1, input)
if err != nil {
t.Errorf("Projects.CreateProjectCard returned error: %v", err)
}
want := &ProjectCard{ID: Int64(1)}
if !reflect.DeepEqual(card, want) {
t.Errorf("Projects.CreateProjectCard returned %+v, want %+v", card, want)
}
}
func TestProjectsService_UpdateProjectCard(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectCardOptions{
ContentID: 12345,
ContentType: "Issue",
}
mux.HandleFunc("/projects/columns/cards/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectCardOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
card, _, err := client.Projects.UpdateProjectCard(context.Background(), 1, input)
if err != nil {
t.Errorf("Projects.UpdateProjectCard returned error: %v", err)
}
want := &ProjectCard{ID: Int64(1)}
if !reflect.DeepEqual(card, want) {
t.Errorf("Projects.UpdateProjectCard returned %+v, want %+v", card, want)
}
}
func TestProjectsService_DeleteProjectCard(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/projects/columns/cards/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
})
_, err := client.Projects.DeleteProjectCard(context.Background(), 1)
if err != nil {
t.Errorf("Projects.DeleteProjectCard returned error: %v", err)
}
}
func TestProjectsService_MoveProjectCard(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectCardMoveOptions{Position: "after:12345"}
mux.HandleFunc("/projects/columns/cards/1/moves", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectCardMoveOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
})
_, err := client.Projects.MoveProjectCard(context.Background(), 1, input)
if err != nil {
t.Errorf("Projects.MoveProjectCard returned error: %v", err)
}
}

View file

@ -1,203 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestPullRequestsService_ListComments_allPulls(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
testFormValues(t, r, values{
"sort": "updated",
"direction": "desc",
"since": "2002-02-10T15:30:00Z",
"page": "2",
})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &PullRequestListCommentsOptions{
Sort: "updated",
Direction: "desc",
Since: time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC),
ListOptions: ListOptions{Page: 2},
}
pulls, _, err := client.PullRequests.ListComments(context.Background(), "o", "r", 0, opt)
if err != nil {
t.Errorf("PullRequests.ListComments returned error: %v", err)
}
want := []*PullRequestComment{{ID: Int64(1)}}
if !reflect.DeepEqual(pulls, want) {
t.Errorf("PullRequests.ListComments returned %+v, want %+v", pulls, want)
}
}
func TestPullRequestsService_ListComments_specificPull(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
fmt.Fprint(w, `[{"id":1}]`)
})
pulls, _, err := client.PullRequests.ListComments(context.Background(), "o", "r", 1, nil)
if err != nil {
t.Errorf("PullRequests.ListComments returned error: %v", err)
}
want := []*PullRequestComment{{ID: Int64(1)}}
if !reflect.DeepEqual(pulls, want) {
t.Errorf("PullRequests.ListComments returned %+v, want %+v", pulls, want)
}
}
func TestPullRequestsService_ListComments_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.ListComments(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestPullRequestsService_GetComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.PullRequests.GetComment(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("PullRequests.GetComment returned error: %v", err)
}
want := &PullRequestComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("PullRequests.GetComment returned %+v, want %+v", comment, want)
}
}
func TestPullRequestsService_GetComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.GetComment(context.Background(), "%", "r", 1)
testURLParseError(t, err)
}
func TestPullRequestsService_CreateComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &PullRequestComment{Body: String("b")}
mux.HandleFunc("/repos/o/r/pulls/1/comments", func(w http.ResponseWriter, r *http.Request) {
v := new(PullRequestComment)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.PullRequests.CreateComment(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("PullRequests.CreateComment returned error: %v", err)
}
want := &PullRequestComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("PullRequests.CreateComment returned %+v, want %+v", comment, want)
}
}
func TestPullRequestsService_CreateComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.CreateComment(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestPullRequestsService_EditComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &PullRequestComment{Body: String("b")}
mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) {
v := new(PullRequestComment)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.PullRequests.EditComment(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("PullRequests.EditComment returned error: %v", err)
}
want := &PullRequestComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("PullRequests.EditComment returned %+v, want %+v", comment, want)
}
}
func TestPullRequestsService_EditComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.EditComment(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestPullRequestsService_DeleteComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.PullRequests.DeleteComment(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("PullRequests.DeleteComment returned error: %v", err)
}
}
func TestPullRequestsService_DeleteComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.PullRequests.DeleteComment(context.Background(), "%", "r", 1)
testURLParseError(t, err)
}

View file

@ -1,104 +0,0 @@
// Copyright 2017 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRequestReviewers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testBody(t, r, `{"reviewers":["octocat","googlebot"],"team_reviewers":["justice-league","injustice-league"]}`+"\n")
testHeader(t, r, "Accept", mediaTypeTeamReviewPreview)
fmt.Fprint(w, `{"number":1}`)
})
// This returns a PR, unmarshalling of which is tested elsewhere
pull, _, err := client.PullRequests.RequestReviewers(context.Background(), "o", "r", 1, ReviewersRequest{Reviewers: []string{"octocat", "googlebot"}, TeamReviewers: []string{"justice-league", "injustice-league"}})
if err != nil {
t.Errorf("PullRequests.RequestReviewers returned error: %v", err)
}
want := &PullRequest{Number: Int(1)}
if !reflect.DeepEqual(pull, want) {
t.Errorf("PullRequests.RequestReviewers returned %+v, want %+v", pull, want)
}
}
func TestRemoveReviewers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeTeamReviewPreview)
testBody(t, r, `{"reviewers":["octocat","googlebot"],"team_reviewers":["justice-league"]}`+"\n")
})
_, err := client.PullRequests.RemoveReviewers(context.Background(), "o", "r", 1, ReviewersRequest{Reviewers: []string{"octocat", "googlebot"}, TeamReviewers: []string{"justice-league"}})
if err != nil {
t.Errorf("PullRequests.RemoveReviewers returned error: %v", err)
}
}
func TestListReviewers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeTeamReviewPreview)
fmt.Fprint(w, `{"users":[{"login":"octocat","id":1}],"teams":[{"id":1,"name":"Justice League"}]}`)
})
reviewers, _, err := client.PullRequests.ListReviewers(context.Background(), "o", "r", 1, nil)
if err != nil {
t.Errorf("PullRequests.ListReviewers returned error: %v", err)
}
want := &Reviewers{
Users: []*User{
{
Login: String("octocat"),
ID: Int64(1),
},
},
Teams: []*Team{
{
ID: Int64(1),
Name: String("Justice League"),
},
},
}
if !reflect.DeepEqual(reviewers, want) {
t.Errorf("PullRequests.ListReviewers returned %+v, want %+v", reviewers, want)
}
}
func TestListReviewers_withOptions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `{}`)
})
_, _, err := client.PullRequests.ListReviewers(context.Background(), "o", "r", 1, &ListOptions{Page: 2})
if err != nil {
t.Errorf("PullRequests.ListReviewers returned error: %v", err)
}
}

View file

@ -1,273 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestPullRequestsService_ListReviews(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/reviews", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[{"id":1},{"id":2}]`)
})
opt := &ListOptions{Page: 2}
reviews, _, err := client.PullRequests.ListReviews(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("PullRequests.ListReviews returned error: %v", err)
}
want := []*PullRequestReview{
{ID: Int64(1)},
{ID: Int64(2)},
}
if !reflect.DeepEqual(reviews, want) {
t.Errorf("PullRequests.ListReviews returned %+v, want %+v", reviews, want)
}
}
func TestPullRequestsService_ListReviews_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.ListReviews(context.Background(), "%", "r", 1, nil)
testURLParseError(t, err)
}
func TestPullRequestsService_GetReview(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/reviews/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
review, _, err := client.PullRequests.GetReview(context.Background(), "o", "r", 1, 1)
if err != nil {
t.Errorf("PullRequests.GetReview returned error: %v", err)
}
want := &PullRequestReview{ID: Int64(1)}
if !reflect.DeepEqual(review, want) {
t.Errorf("PullRequests.GetReview returned %+v, want %+v", review, want)
}
}
func TestPullRequestsService_GetReview_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.GetReview(context.Background(), "%", "r", 1, 1)
testURLParseError(t, err)
}
func TestPullRequestsService_DeletePendingReview(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/reviews/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
fmt.Fprint(w, `{"id":1}`)
})
review, _, err := client.PullRequests.DeletePendingReview(context.Background(), "o", "r", 1, 1)
if err != nil {
t.Errorf("PullRequests.DeletePendingReview returned error: %v", err)
}
want := &PullRequestReview{ID: Int64(1)}
if !reflect.DeepEqual(review, want) {
t.Errorf("PullRequests.DeletePendingReview returned %+v, want %+v", review, want)
}
}
func TestPullRequestsService_DeletePendingReview_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.DeletePendingReview(context.Background(), "%", "r", 1, 1)
testURLParseError(t, err)
}
func TestPullRequestsService_ListReviewComments(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":1},{"id":2}]`)
})
comments, _, err := client.PullRequests.ListReviewComments(context.Background(), "o", "r", 1, 1, nil)
if err != nil {
t.Errorf("PullRequests.ListReviewComments returned error: %v", err)
}
want := []*PullRequestComment{
{ID: Int64(1)},
{ID: Int64(2)},
}
if !reflect.DeepEqual(comments, want) {
t.Errorf("PullRequests.ListReviewComments returned %+v, want %+v", comments, want)
}
}
func TestPullRequestsService_ListReviewComments_withOptions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[]`)
})
_, _, err := client.PullRequests.ListReviewComments(context.Background(), "o", "r", 1, 1, &ListOptions{Page: 2})
if err != nil {
t.Errorf("PullRequests.ListReviewComments returned error: %v", err)
}
}
func TestPullRequestsService_ListReviewComments_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.ListReviewComments(context.Background(), "%", "r", 1, 1, nil)
testURLParseError(t, err)
}
func TestPullRequestsService_CreateReview(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &PullRequestReviewRequest{
CommitID: String("commit_id"),
Body: String("b"),
Event: String("APPROVE"),
}
mux.HandleFunc("/repos/o/r/pulls/1/reviews", func(w http.ResponseWriter, r *http.Request) {
v := new(PullRequestReviewRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
review, _, err := client.PullRequests.CreateReview(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("PullRequests.CreateReview returned error: %v", err)
}
want := &PullRequestReview{ID: Int64(1)}
if !reflect.DeepEqual(review, want) {
t.Errorf("PullRequests.CreateReview returned %+v, want %+v", review, want)
}
}
func TestPullRequestsService_CreateReview_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.CreateReview(context.Background(), "%", "r", 1, &PullRequestReviewRequest{})
testURLParseError(t, err)
}
func TestPullRequestsService_SubmitReview(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &PullRequestReviewRequest{
Body: String("b"),
Event: String("APPROVE"),
}
mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/events", func(w http.ResponseWriter, r *http.Request) {
v := new(PullRequestReviewRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
review, _, err := client.PullRequests.SubmitReview(context.Background(), "o", "r", 1, 1, input)
if err != nil {
t.Errorf("PullRequests.SubmitReview returned error: %v", err)
}
want := &PullRequestReview{ID: Int64(1)}
if !reflect.DeepEqual(review, want) {
t.Errorf("PullRequests.SubmitReview returned %+v, want %+v", review, want)
}
}
func TestPullRequestsService_SubmitReview_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.SubmitReview(context.Background(), "%", "r", 1, 1, &PullRequestReviewRequest{})
testURLParseError(t, err)
}
func TestPullRequestsService_DismissReview(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &PullRequestReviewDismissalRequest{Message: String("m")}
mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/dismissals", func(w http.ResponseWriter, r *http.Request) {
v := new(PullRequestReviewDismissalRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
review, _, err := client.PullRequests.DismissReview(context.Background(), "o", "r", 1, 1, input)
if err != nil {
t.Errorf("PullRequests.DismissReview returned error: %v", err)
}
want := &PullRequestReview{ID: Int64(1)}
if !reflect.DeepEqual(review, want) {
t.Errorf("PullRequests.DismissReview returned %+v, want %+v", review, want)
}
}
func TestPullRequestsService_DismissReview_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.DismissReview(context.Background(), "%", "r", 1, 1, &PullRequestReviewDismissalRequest{})
testURLParseError(t, err)
}

View file

@ -1,529 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"testing"
)
func TestPullRequestsService_List(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{
"state": "closed",
"head": "h",
"base": "b",
"sort": "created",
"direction": "desc",
"page": "2",
})
fmt.Fprint(w, `[{"number":1}]`)
})
opt := &PullRequestListOptions{"closed", "h", "b", "created", "desc", ListOptions{Page: 2}}
pulls, _, err := client.PullRequests.List(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("PullRequests.List returned error: %v", err)
}
want := []*PullRequest{{Number: Int(1)}}
if !reflect.DeepEqual(pulls, want) {
t.Errorf("PullRequests.List returned %+v, want %+v", pulls, want)
}
}
func TestPullRequestsService_List_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.List(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}
func TestPullRequestsService_Get(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"number":1}`)
})
pull, _, err := client.PullRequests.Get(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("PullRequests.Get returned error: %v", err)
}
want := &PullRequest{Number: Int(1)}
if !reflect.DeepEqual(pull, want) {
t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want)
}
}
func TestPullRequestsService_GetRaw_diff(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
const rawStr = "@@diff content"
mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeV3Diff)
fmt.Fprint(w, rawStr)
})
got, _, err := client.PullRequests.GetRaw(context.Background(), "o", "r", 1, RawOptions{Diff})
if err != nil {
t.Fatalf("PullRequests.GetRaw returned error: %v", err)
}
want := rawStr
if got != want {
t.Errorf("PullRequests.GetRaw returned %s want %s", got, want)
}
}
func TestPullRequestsService_GetRaw_patch(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
const rawStr = "@@patch content"
mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeV3Patch)
fmt.Fprint(w, rawStr)
})
got, _, err := client.PullRequests.GetRaw(context.Background(), "o", "r", 1, RawOptions{Patch})
if err != nil {
t.Fatalf("PullRequests.GetRaw returned error: %v", err)
}
want := rawStr
if got != want {
t.Errorf("PullRequests.GetRaw returned %s want %s", got, want)
}
}
func TestPullRequestsService_GetRaw_invalid(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.GetRaw(context.Background(), "o", "r", 1, RawOptions{100})
if err == nil {
t.Fatal("PullRequests.GetRaw should return error")
}
if !strings.Contains(err.Error(), "unsupported raw type") {
t.Error("PullRequests.GetRaw should return unsupported raw type error")
}
}
func TestPullRequestsService_Get_headAndBase(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"number":1,"head":{"ref":"r2","repo":{"id":2}},"base":{"ref":"r1","repo":{"id":1}}}`)
})
pull, _, err := client.PullRequests.Get(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("PullRequests.Get returned error: %v", err)
}
want := &PullRequest{
Number: Int(1),
Head: &PullRequestBranch{
Ref: String("r2"),
Repo: &Repository{ID: Int64(2)},
},
Base: &PullRequestBranch{
Ref: String("r1"),
Repo: &Repository{ID: Int64(1)},
},
}
if !reflect.DeepEqual(pull, want) {
t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want)
}
}
func TestPullRequestsService_Get_urlFields(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"number":1,
"url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347",
"html_url": "https://github.com/octocat/Hello-World/pull/1347",
"issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347",
"statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e",
"diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff",
"patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch",
"review_comments_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments",
"review_comment_url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}"}`)
})
pull, _, err := client.PullRequests.Get(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("PullRequests.Get returned error: %v", err)
}
want := &PullRequest{
Number: Int(1),
URL: String("https://api.github.com/repos/octocat/Hello-World/pulls/1347"),
HTMLURL: String("https://github.com/octocat/Hello-World/pull/1347"),
IssueURL: String("https://api.github.com/repos/octocat/Hello-World/issues/1347"),
StatusesURL: String("https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e"),
DiffURL: String("https://github.com/octocat/Hello-World/pull/1347.diff"),
PatchURL: String("https://github.com/octocat/Hello-World/pull/1347.patch"),
ReviewCommentsURL: String("https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments"),
ReviewCommentURL: String("https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}"),
}
if !reflect.DeepEqual(pull, want) {
t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want)
}
}
func TestPullRequestsService_Get_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.Get(context.Background(), "%", "r", 1)
testURLParseError(t, err)
}
func TestPullRequestsService_Create(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &NewPullRequest{Title: String("t")}
mux.HandleFunc("/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) {
v := new(NewPullRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"number":1}`)
})
pull, _, err := client.PullRequests.Create(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("PullRequests.Create returned error: %v", err)
}
want := &PullRequest{Number: Int(1)}
if !reflect.DeepEqual(pull, want) {
t.Errorf("PullRequests.Create returned %+v, want %+v", pull, want)
}
}
func TestPullRequestsService_Create_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.Create(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}
func TestPullRequestsService_Edit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
tests := []struct {
input *PullRequest
sendResponse string
wantUpdate string
want *PullRequest
}{
{
input: &PullRequest{Title: String("t")},
sendResponse: `{"number":1}`,
wantUpdate: `{"title":"t"}`,
want: &PullRequest{Number: Int(1)},
},
{
// base update
input: &PullRequest{Base: &PullRequestBranch{Ref: String("master")}},
sendResponse: `{"number":1,"base":{"ref":"master"}}`,
wantUpdate: `{"base":"master"}`,
want: &PullRequest{
Number: Int(1),
Base: &PullRequestBranch{Ref: String("master")},
},
},
}
for i, tt := range tests {
madeRequest := false
mux.HandleFunc(fmt.Sprintf("/repos/o/r/pulls/%v", i), func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testBody(t, r, tt.wantUpdate+"\n")
io.WriteString(w, tt.sendResponse)
madeRequest = true
})
pull, _, err := client.PullRequests.Edit(context.Background(), "o", "r", i, tt.input)
if err != nil {
t.Errorf("%d: PullRequests.Edit returned error: %v", i, err)
}
if !reflect.DeepEqual(pull, tt.want) {
t.Errorf("%d: PullRequests.Edit returned %+v, want %+v", i, pull, tt.want)
}
if !madeRequest {
t.Errorf("%d: PullRequest.Edit did not make the expected request", i)
}
}
}
func TestPullRequestsService_Edit_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.PullRequests.Edit(context.Background(), "%", "r", 1, &PullRequest{})
testURLParseError(t, err)
}
func TestPullRequestsService_ListCommits(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/commits", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGitSigningPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `
[
{
"sha": "3",
"parents": [
{
"sha": "2"
}
]
},
{
"sha": "2",
"parents": [
{
"sha": "1"
}
]
}
]`)
})
opt := &ListOptions{Page: 2}
commits, _, err := client.PullRequests.ListCommits(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("PullRequests.ListCommits returned error: %v", err)
}
want := []*RepositoryCommit{
{
SHA: String("3"),
Parents: []Commit{
{
SHA: String("2"),
},
},
},
{
SHA: String("2"),
Parents: []Commit{
{
SHA: String("1"),
},
},
},
}
if !reflect.DeepEqual(commits, want) {
t.Errorf("PullRequests.ListCommits returned %+v, want %+v", commits, want)
}
}
func TestPullRequestsService_ListFiles(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/files", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `
[
{
"sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
"filename": "file1.txt",
"status": "added",
"additions": 103,
"deletions": 21,
"changes": 124,
"patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"
},
{
"sha": "f61aebed695e2e4193db5e6dcb09b5b57875f334",
"filename": "file2.txt",
"status": "modified",
"additions": 5,
"deletions": 3,
"changes": 103,
"patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"
}
]`)
})
opt := &ListOptions{Page: 2}
commitFiles, _, err := client.PullRequests.ListFiles(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("PullRequests.ListFiles returned error: %v", err)
}
want := []*CommitFile{
{
SHA: String("6dcb09b5b57875f334f61aebed695e2e4193db5e"),
Filename: String("file1.txt"),
Additions: Int(103),
Deletions: Int(21),
Changes: Int(124),
Status: String("added"),
Patch: String("@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"),
},
{
SHA: String("f61aebed695e2e4193db5e6dcb09b5b57875f334"),
Filename: String("file2.txt"),
Additions: Int(5),
Deletions: Int(3),
Changes: Int(103),
Status: String("modified"),
Patch: String("@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"),
},
}
if !reflect.DeepEqual(commitFiles, want) {
t.Errorf("PullRequests.ListFiles returned %+v, want %+v", commitFiles, want)
}
}
func TestPullRequestsService_IsMerged(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/merge", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNoContent)
})
isMerged, _, err := client.PullRequests.IsMerged(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("PullRequests.IsMerged returned error: %v", err)
}
want := true
if !reflect.DeepEqual(isMerged, want) {
t.Errorf("PullRequests.IsMerged returned %+v, want %+v", isMerged, want)
}
}
func TestPullRequestsService_Merge(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/1/merge", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
fmt.Fprint(w, `
{
"sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
"merged": true,
"message": "Pull Request successfully merged"
}`)
})
options := &PullRequestOptions{MergeMethod: "rebase"}
merge, _, err := client.PullRequests.Merge(context.Background(), "o", "r", 1, "merging pull request", options)
if err != nil {
t.Errorf("PullRequests.Merge returned error: %v", err)
}
want := &PullRequestMergeResult{
SHA: String("6dcb09b5b57875f334f61aebed695e2e4193db5e"),
Merged: Bool(true),
Message: String("Pull Request successfully merged"),
}
if !reflect.DeepEqual(merge, want) {
t.Errorf("PullRequests.Merge returned %+v, want %+v", merge, want)
}
}
// Test that different merge options produce expected PUT requests. See issue https://github.com/google/go-github/issues/500.
func TestPullRequestsService_Merge_options(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
tests := []struct {
options *PullRequestOptions
wantBody string
}{
{
options: nil,
wantBody: `{"commit_message":"merging pull request"}`,
},
{
options: &PullRequestOptions{},
wantBody: `{"commit_message":"merging pull request"}`,
},
{
options: &PullRequestOptions{MergeMethod: "rebase"},
wantBody: `{"commit_message":"merging pull request","merge_method":"rebase"}`,
},
{
options: &PullRequestOptions{SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e"},
wantBody: `{"commit_message":"merging pull request","sha":"6dcb09b5b57875f334f61aebed695e2e4193db5e"}`,
},
{
options: &PullRequestOptions{
CommitTitle: "Extra detail",
SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e",
MergeMethod: "squash",
},
wantBody: `{"commit_message":"merging pull request","commit_title":"Extra detail","merge_method":"squash","sha":"6dcb09b5b57875f334f61aebed695e2e4193db5e"}`,
},
}
for i, test := range tests {
madeRequest := false
mux.HandleFunc(fmt.Sprintf("/repos/o/r/pulls/%d/merge", i), func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
testBody(t, r, test.wantBody+"\n")
madeRequest = true
})
_, _, _ = client.PullRequests.Merge(context.Background(), "o", "r", i, "merging pull request", test.options)
if !madeRequest {
t.Errorf("%d: PullRequests.Merge(%#v): expected request was not made", i, test.options)
}
}
}

View file

@ -1,201 +0,0 @@
// 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.
package github
import (
"context"
"net/http"
"reflect"
"testing"
)
func TestReactionsService_ListCommentReactions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusOK)
w.Write([]byte(`[{"id":1,"user":{"login":"l","id":2},"content":"+1"}]`))
})
got, _, err := client.Reactions.ListCommentReactions(context.Background(), "o", "r", 1, nil)
if err != nil {
t.Errorf("ListCommentReactions returned error: %v", err)
}
if want := []*Reaction{{ID: Int64(1), User: &User{Login: String("l"), ID: Int64(2)}, Content: String("+1")}}; !reflect.DeepEqual(got, want) {
t.Errorf("ListCommentReactions = %+v, want %+v", got, want)
}
}
func TestReactionsService_CreateCommentReaction(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"id":1,"user":{"login":"l","id":2},"content":"+1"}`))
})
got, _, err := client.Reactions.CreateCommentReaction(context.Background(), "o", "r", 1, "+1")
if err != nil {
t.Errorf("CreateCommentReaction returned error: %v", err)
}
want := &Reaction{ID: Int64(1), User: &User{Login: String("l"), ID: Int64(2)}, Content: String("+1")}
if !reflect.DeepEqual(got, want) {
t.Errorf("CreateCommentReaction = %+v, want %+v", got, want)
}
}
func TestReactionsService_ListIssueReactions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/reactions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusOK)
w.Write([]byte(`[{"id":1,"user":{"login":"l","id":2},"content":"+1"}]`))
})
got, _, err := client.Reactions.ListIssueReactions(context.Background(), "o", "r", 1, nil)
if err != nil {
t.Errorf("ListIssueReactions returned error: %v", err)
}
if want := []*Reaction{{ID: Int64(1), User: &User{Login: String("l"), ID: Int64(2)}, Content: String("+1")}}; !reflect.DeepEqual(got, want) {
t.Errorf("ListIssueReactions = %+v, want %+v", got, want)
}
}
func TestReactionsService_CreateIssueReaction(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/1/reactions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"id":1,"user":{"login":"l","id":2},"content":"+1"}`))
})
got, _, err := client.Reactions.CreateIssueReaction(context.Background(), "o", "r", 1, "+1")
if err != nil {
t.Errorf("CreateIssueReaction returned error: %v", err)
}
want := &Reaction{ID: Int64(1), User: &User{Login: String("l"), ID: Int64(2)}, Content: String("+1")}
if !reflect.DeepEqual(got, want) {
t.Errorf("CreateIssueReaction = %+v, want %+v", got, want)
}
}
func TestReactionsService_ListIssueCommentReactions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusOK)
w.Write([]byte(`[{"id":1,"user":{"login":"l","id":2},"content":"+1"}]`))
})
got, _, err := client.Reactions.ListIssueCommentReactions(context.Background(), "o", "r", 1, nil)
if err != nil {
t.Errorf("ListIssueCommentReactions returned error: %v", err)
}
if want := []*Reaction{{ID: Int64(1), User: &User{Login: String("l"), ID: Int64(2)}, Content: String("+1")}}; !reflect.DeepEqual(got, want) {
t.Errorf("ListIssueCommentReactions = %+v, want %+v", got, want)
}
}
func TestReactionsService_CreateIssueCommentReaction(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/issues/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"id":1,"user":{"login":"l","id":2},"content":"+1"}`))
})
got, _, err := client.Reactions.CreateIssueCommentReaction(context.Background(), "o", "r", 1, "+1")
if err != nil {
t.Errorf("CreateIssueCommentReaction returned error: %v", err)
}
want := &Reaction{ID: Int64(1), User: &User{Login: String("l"), ID: Int64(2)}, Content: String("+1")}
if !reflect.DeepEqual(got, want) {
t.Errorf("CreateIssueCommentReaction = %+v, want %+v", got, want)
}
}
func TestReactionsService_ListPullRequestCommentReactions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusOK)
w.Write([]byte(`[{"id":1,"user":{"login":"l","id":2},"content":"+1"}]`))
})
got, _, err := client.Reactions.ListPullRequestCommentReactions(context.Background(), "o", "r", 1, nil)
if err != nil {
t.Errorf("ListPullRequestCommentReactions returned error: %v", err)
}
if want := []*Reaction{{ID: Int64(1), User: &User{Login: String("l"), ID: Int64(2)}, Content: String("+1")}}; !reflect.DeepEqual(got, want) {
t.Errorf("ListPullRequestCommentReactions = %+v, want %+v", got, want)
}
}
func TestReactionsService_CreatePullRequestCommentReaction(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pulls/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"id":1,"user":{"login":"l","id":2},"content":"+1"}`))
})
got, _, err := client.Reactions.CreatePullRequestCommentReaction(context.Background(), "o", "r", 1, "+1")
if err != nil {
t.Errorf("CreatePullRequestCommentReaction returned error: %v", err)
}
want := &Reaction{ID: Int64(1), User: &User{Login: String("l"), ID: Int64(2)}, Content: String("+1")}
if !reflect.DeepEqual(got, want) {
t.Errorf("CreatePullRequestCommentReaction = %+v, want %+v", got, want)
}
}
func TestReactionsService_DeleteReaction(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/reactions/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
w.WriteHeader(http.StatusNoContent)
})
if _, err := client.Reactions.DeleteReaction(context.Background(), 1); err != nil {
t.Errorf("DeleteReaction returned error: %v", err)
}
}

View file

@ -1,201 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_ListCollaborators(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/collaborators", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeNestedTeamsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprintf(w, `[{"id":1}, {"id":2}]`)
})
opt := &ListCollaboratorsOptions{
ListOptions: ListOptions{Page: 2},
}
users, _, err := client.Repositories.ListCollaborators(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListCollaborators returned error: %v", err)
}
want := []*User{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(users, want) {
t.Errorf("Repositori es.ListCollaborators returned %+v, want %+v", users, want)
}
}
func TestRepositoriesService_ListCollaborators_withAffiliation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/collaborators", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"affiliation": "all", "page": "2"})
fmt.Fprintf(w, `[{"id":1}, {"id":2}]`)
})
opt := &ListCollaboratorsOptions{
ListOptions: ListOptions{Page: 2},
Affiliation: "all",
}
users, _, err := client.Repositories.ListCollaborators(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListCollaborators returned error: %v", err)
}
want := []*User{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(users, want) {
t.Errorf("Repositories.ListCollaborators returned %+v, want %+v", users, want)
}
}
func TestRepositoriesService_ListCollaborators_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.ListCollaborators(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_IsCollaborator_True(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNoContent)
})
isCollab, _, err := client.Repositories.IsCollaborator(context.Background(), "o", "r", "u")
if err != nil {
t.Errorf("Repositories.IsCollaborator returned error: %v", err)
}
if !isCollab {
t.Errorf("Repositories.IsCollaborator returned false, want true")
}
}
func TestRepositoriesService_IsCollaborator_False(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
isCollab, _, err := client.Repositories.IsCollaborator(context.Background(), "o", "r", "u")
if err != nil {
t.Errorf("Repositories.IsCollaborator returned error: %v", err)
}
if isCollab {
t.Errorf("Repositories.IsCollaborator returned true, want false")
}
}
func TestRepositoriesService_IsCollaborator_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.IsCollaborator(context.Background(), "%", "%", "%")
testURLParseError(t, err)
}
func TestRepositoryService_GetPermissionLevel(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/collaborators/u/permission", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprintf(w, `{"permission":"admin","user":{"login":"u"}}`)
})
rpl, _, err := client.Repositories.GetPermissionLevel(context.Background(), "o", "r", "u")
if err != nil {
t.Errorf("Repositories.GetPermissionLevel returned error: %v", err)
}
want := &RepositoryPermissionLevel{
Permission: String("admin"),
User: &User{
Login: String("u"),
},
}
if !reflect.DeepEqual(rpl, want) {
t.Errorf("Repositories.GetPermissionLevel returned %+v, want %+v", rpl, want)
}
}
func TestRepositoriesService_AddCollaborator(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
opt := &RepositoryAddCollaboratorOptions{Permission: "admin"}
mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) {
v := new(RepositoryAddCollaboratorOptions)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PUT")
testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview)
if !reflect.DeepEqual(v, opt) {
t.Errorf("Request body = %+v, want %+v", v, opt)
}
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Repositories.AddCollaborator(context.Background(), "o", "r", "u", opt)
if err != nil {
t.Errorf("Repositories.AddCollaborator returned error: %v", err)
}
}
func TestRepositoriesService_AddCollaborator_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Repositories.AddCollaborator(context.Background(), "%", "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_RemoveCollaborator(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Repositories.RemoveCollaborator(context.Background(), "o", "r", "u")
if err != nil {
t.Errorf("Repositories.RemoveCollaborator returned error: %v", err)
}
}
func TestRepositoriesService_RemoveCollaborator_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Repositories.RemoveCollaborator(context.Background(), "%", "%", "%")
testURLParseError(t, err)
}

View file

@ -1,202 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_ListComments(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}, {"id":2}]`)
})
opt := &ListOptions{Page: 2}
comments, _, err := client.Repositories.ListComments(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListComments returned error: %v", err)
}
want := []*RepositoryComment{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(comments, want) {
t.Errorf("Repositories.ListComments returned %+v, want %+v", comments, want)
}
}
func TestRepositoriesService_ListComments_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.ListComments(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_ListCommitComments(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/commits/s/comments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}, {"id":2}]`)
})
opt := &ListOptions{Page: 2}
comments, _, err := client.Repositories.ListCommitComments(context.Background(), "o", "r", "s", opt)
if err != nil {
t.Errorf("Repositories.ListCommitComments returned error: %v", err)
}
want := []*RepositoryComment{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(comments, want) {
t.Errorf("Repositories.ListCommitComments returned %+v, want %+v", comments, want)
}
}
func TestRepositoriesService_ListCommitComments_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.ListCommitComments(context.Background(), "%", "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_CreateComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &RepositoryComment{Body: String("b")}
mux.HandleFunc("/repos/o/r/commits/s/comments", func(w http.ResponseWriter, r *http.Request) {
v := new(RepositoryComment)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.Repositories.CreateComment(context.Background(), "o", "r", "s", input)
if err != nil {
t.Errorf("Repositories.CreateComment returned error: %v", err)
}
want := &RepositoryComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Repositories.CreateComment returned %+v, want %+v", comment, want)
}
}
func TestRepositoriesService_CreateComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.CreateComment(context.Background(), "%", "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_GetComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeReactionsPreview)
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.Repositories.GetComment(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.GetComment returned error: %v", err)
}
want := &RepositoryComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Repositories.GetComment returned %+v, want %+v", comment, want)
}
}
func TestRepositoriesService_GetComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.GetComment(context.Background(), "%", "%", 1)
testURLParseError(t, err)
}
func TestRepositoriesService_UpdateComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &RepositoryComment{Body: String("b")}
mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) {
v := new(RepositoryComment)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
comment, _, err := client.Repositories.UpdateComment(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Repositories.UpdateComment returned error: %v", err)
}
want := &RepositoryComment{ID: Int64(1)}
if !reflect.DeepEqual(comment, want) {
t.Errorf("Repositories.UpdateComment returned %+v, want %+v", comment, want)
}
}
func TestRepositoriesService_UpdateComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.UpdateComment(context.Background(), "%", "%", 1, nil)
testURLParseError(t, err)
}
func TestRepositoriesService_DeleteComment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Repositories.DeleteComment(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.DeleteComment returned error: %v", err)
}
}
func TestRepositoriesService_DeleteComment_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Repositories.DeleteComment(context.Background(), "%", "%", 1)
testURLParseError(t, err)
}

View file

@ -1,325 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
"time"
)
func TestRepositoriesService_ListCommits(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
// given
mux.HandleFunc("/repos/o/r/commits", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGitSigningPreview)
testFormValues(t, r,
values{
"sha": "s",
"path": "p",
"author": "a",
"since": "2013-08-01T00:00:00Z",
"until": "2013-09-03T00:00:00Z",
})
fmt.Fprintf(w, `[{"sha": "s"}]`)
})
opt := &CommitsListOptions{
SHA: "s",
Path: "p",
Author: "a",
Since: time.Date(2013, time.August, 1, 0, 0, 0, 0, time.UTC),
Until: time.Date(2013, time.September, 3, 0, 0, 0, 0, time.UTC),
}
commits, _, err := client.Repositories.ListCommits(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListCommits returned error: %v", err)
}
want := []*RepositoryCommit{{SHA: String("s")}}
if !reflect.DeepEqual(commits, want) {
t.Errorf("Repositories.ListCommits returned %+v, want %+v", commits, want)
}
}
func TestRepositoriesService_GetCommit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/commits/s", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGitSigningPreview)
fmt.Fprintf(w, `{
"sha": "s",
"commit": { "message": "m" },
"author": { "login": "l" },
"committer": { "login": "l" },
"parents": [ { "sha": "s" } ],
"stats": { "additions": 104, "deletions": 4, "total": 108 },
"files": [
{
"filename": "f",
"additions": 10,
"deletions": 2,
"changes": 12,
"status": "s",
"patch": "p",
"blob_url": "b",
"raw_url": "r",
"contents_url": "c"
}
]
}`)
})
commit, _, err := client.Repositories.GetCommit(context.Background(), "o", "r", "s")
if err != nil {
t.Errorf("Repositories.GetCommit returned error: %v", err)
}
want := &RepositoryCommit{
SHA: String("s"),
Commit: &Commit{
Message: String("m"),
},
Author: &User{
Login: String("l"),
},
Committer: &User{
Login: String("l"),
},
Parents: []Commit{
{
SHA: String("s"),
},
},
Stats: &CommitStats{
Additions: Int(104),
Deletions: Int(4),
Total: Int(108),
},
Files: []CommitFile{
{
Filename: String("f"),
Additions: Int(10),
Deletions: Int(2),
Changes: Int(12),
Status: String("s"),
Patch: String("p"),
BlobURL: String("b"),
RawURL: String("r"),
ContentsURL: String("c"),
},
},
}
if !reflect.DeepEqual(commit, want) {
t.Errorf("Repositories.GetCommit returned \n%+v, want \n%+v", commit, want)
}
}
func TestRepositoriesService_GetCommitRaw_diff(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
const rawStr = "@@diff content"
mux.HandleFunc("/repos/o/r/commits/s", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeV3Diff)
fmt.Fprint(w, rawStr)
})
got, _, err := client.Repositories.GetCommitRaw(context.Background(), "o", "r", "s", RawOptions{Type: Diff})
if err != nil {
t.Fatalf("Repositories.GetCommitRaw returned error: %v", err)
}
want := rawStr
if got != want {
t.Errorf("Repositories.GetCommitRaw returned %s want %s", got, want)
}
}
func TestRepositoriesService_GetCommitRaw_patch(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
const rawStr = "@@patch content"
mux.HandleFunc("/repos/o/r/commits/s", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeV3Patch)
fmt.Fprint(w, rawStr)
})
got, _, err := client.Repositories.GetCommitRaw(context.Background(), "o", "r", "s", RawOptions{Type: Patch})
if err != nil {
t.Fatalf("Repositories.GetCommitRaw returned error: %v", err)
}
want := rawStr
if got != want {
t.Errorf("Repositories.GetCommitRaw returned %s want %s", got, want)
}
}
func TestRepositoriesService_GetCommitRaw_invalid(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.GetCommitRaw(context.Background(), "o", "r", "s", RawOptions{100})
if err == nil {
t.Fatal("Repositories.GetCommitRaw should return error")
}
if !strings.Contains(err.Error(), "unsupported raw type") {
t.Error("Repositories.GetCommitRaw should return unsupported raw type error")
}
}
func TestRepositoriesService_GetCommitSHA1(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
const sha1 = "01234abcde"
mux.HandleFunc("/repos/o/r/commits/master", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeV3SHA)
fmt.Fprintf(w, sha1)
})
got, _, err := client.Repositories.GetCommitSHA1(context.Background(), "o", "r", "master", "")
if err != nil {
t.Errorf("Repositories.GetCommitSHA1 returned error: %v", err)
}
want := sha1
if got != want {
t.Errorf("Repositories.GetCommitSHA1 = %v, want %v", got, want)
}
mux.HandleFunc("/repos/o/r/commits/tag", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeV3SHA)
testHeader(t, r, "If-None-Match", `"`+sha1+`"`)
w.WriteHeader(http.StatusNotModified)
})
got, _, err = client.Repositories.GetCommitSHA1(context.Background(), "o", "r", "tag", sha1)
if err == nil {
t.Errorf("Expected HTTP 304 response")
}
want = ""
if got != want {
t.Errorf("Repositories.GetCommitSHA1 = %v, want %v", got, want)
}
}
func TestRepositoriesService_CompareCommits(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/compare/b...h", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprintf(w, `{
"base_commit": {
"sha": "s",
"commit": {
"author": { "name": "n" },
"committer": { "name": "n" },
"message": "m",
"tree": { "sha": "t" }
},
"author": { "login": "l" },
"committer": { "login": "l" },
"parents": [ { "sha": "s" } ]
},
"status": "s",
"ahead_by": 1,
"behind_by": 2,
"total_commits": 1,
"commits": [
{
"sha": "s",
"commit": { "author": { "name": "n" } },
"author": { "login": "l" },
"committer": { "login": "l" },
"parents": [ { "sha": "s" } ]
}
],
"files": [ { "filename": "f" } ],
"html_url": "https://github.com/o/r/compare/b...h",
"permalink_url": "https://github.com/o/r/compare/o:bbcd538c8e72b8c175046e27cc8f907076331401...o:0328041d1152db8ae77652d1618a02e57f745f17",
"diff_url": "https://github.com/o/r/compare/b...h.diff",
"patch_url": "https://github.com/o/r/compare/b...h.patch",
"url": "https://api.github.com/repos/o/r/compare/b...h"
}`)
})
got, _, err := client.Repositories.CompareCommits(context.Background(), "o", "r", "b", "h")
if err != nil {
t.Errorf("Repositories.CompareCommits returned error: %v", err)
}
want := &CommitsComparison{
BaseCommit: &RepositoryCommit{
SHA: String("s"),
Commit: &Commit{
Author: &CommitAuthor{Name: String("n")},
Committer: &CommitAuthor{Name: String("n")},
Message: String("m"),
Tree: &Tree{SHA: String("t")},
},
Author: &User{Login: String("l")},
Committer: &User{Login: String("l")},
Parents: []Commit{
{
SHA: String("s"),
},
},
},
Status: String("s"),
AheadBy: Int(1),
BehindBy: Int(2),
TotalCommits: Int(1),
Commits: []RepositoryCommit{
{
SHA: String("s"),
Commit: &Commit{
Author: &CommitAuthor{Name: String("n")},
},
Author: &User{Login: String("l")},
Committer: &User{Login: String("l")},
Parents: []Commit{
{
SHA: String("s"),
},
},
},
},
Files: []CommitFile{
{
Filename: String("f"),
},
},
HTMLURL: String("https://github.com/o/r/compare/b...h"),
PermalinkURL: String("https://github.com/o/r/compare/o:bbcd538c8e72b8c175046e27cc8f907076331401...o:0328041d1152db8ae77652d1618a02e57f745f17"),
DiffURL: String("https://github.com/o/r/compare/b...h.diff"),
PatchURL: String("https://github.com/o/r/compare/b...h.patch"),
URL: String("https://api.github.com/repos/o/r/compare/b...h"),
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Repositories.CompareCommits returned \n%+v, want \n%+v", got, want)
}
}

View file

@ -1,86 +0,0 @@
// Copyright 2017 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestRepositoriesService_GetCommunityHealthMetrics(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/community/profile", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeRepositoryCommunityHealthMetricsPreview)
fmt.Fprintf(w, `{
"health_percentage": 100,
"files": {
"code_of_conduct": {
"name": "Contributor Covenant",
"key": "contributor_covenant",
"url": null,
"html_url": "https://github.com/octocat/Hello-World/blob/master/CODE_OF_CONDUCT.md"
},
"contributing": {
"url": "https://api.github.com/repos/octocat/Hello-World/contents/CONTRIBUTING",
"html_url": "https://github.com/octocat/Hello-World/blob/master/CONTRIBUTING"
},
"license": {
"name": "MIT License",
"key": "mit",
"url": "https://api.github.com/licenses/mit",
"html_url": "https://github.com/octocat/Hello-World/blob/master/LICENSE"
},
"readme": {
"url": "https://api.github.com/repos/octocat/Hello-World/contents/README.md",
"html_url": "https://github.com/octocat/Hello-World/blob/master/README.md"
}
},
"updated_at": "2017-02-28T00:00:00Z"
}`)
})
got, _, err := client.Repositories.GetCommunityHealthMetrics(context.Background(), "o", "r")
if err != nil {
t.Errorf("Repositories.GetCommunityHealthMetrics returned error: %v", err)
}
updatedAt := time.Date(2017, 02, 28, 0, 0, 0, 0, time.UTC)
want := &CommunityHealthMetrics{
HealthPercentage: Int(100),
UpdatedAt: &updatedAt,
Files: &CommunityHealthFiles{
CodeOfConduct: &Metric{
Name: String("Contributor Covenant"),
Key: String("contributor_covenant"),
HTMLURL: String("https://github.com/octocat/Hello-World/blob/master/CODE_OF_CONDUCT.md"),
},
Contributing: &Metric{
URL: String("https://api.github.com/repos/octocat/Hello-World/contents/CONTRIBUTING"),
HTMLURL: String("https://github.com/octocat/Hello-World/blob/master/CONTRIBUTING"),
},
License: &Metric{
Name: String("MIT License"),
Key: String("mit"),
URL: String("https://api.github.com/licenses/mit"),
HTMLURL: String("https://github.com/octocat/Hello-World/blob/master/LICENSE"),
},
Readme: &Metric{
URL: String("https://api.github.com/repos/octocat/Hello-World/contents/README.md"),
HTMLURL: String("https://github.com/octocat/Hello-World/blob/master/README.md"),
},
},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Repositories.GetCommunityHealthMetrics:\ngot:\n%v\nwant:\n%v", Stringify(got), Stringify(want))
}
}

View file

@ -1,378 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"testing"
)
func TestRepositoryContent_GetContent(t *testing.T) {
tests := []struct {
encoding, content *string // input encoding and content
want string // desired output
wantErr bool // whether an error is expected
}{
{
encoding: String(""),
content: String("hello"),
want: "hello",
wantErr: false,
},
{
encoding: nil,
content: String("hello"),
want: "hello",
wantErr: false,
},
{
encoding: nil,
content: nil,
want: "",
wantErr: false,
},
{
encoding: String("base64"),
content: String("aGVsbG8="),
want: "hello",
wantErr: false,
},
{
encoding: String("bad"),
content: String("aGVsbG8="),
want: "",
wantErr: true,
},
}
for _, tt := range tests {
r := RepositoryContent{Encoding: tt.encoding, Content: tt.content}
got, err := r.GetContent()
if err != nil && !tt.wantErr {
t.Errorf("RepositoryContent(%q, %q) returned unexpected error: %v", tt.encoding, tt.content, err)
}
if err == nil && tt.wantErr {
t.Errorf("RepositoryContent(%q, %q) did not return unexpected error", tt.encoding, tt.content)
}
if want := tt.want; got != want {
t.Errorf("RepositoryContent.GetContent returned %+v, want %+v", got, want)
}
}
}
func TestRepositoriesService_GetReadme(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/readme", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{
"type": "file",
"encoding": "base64",
"size": 5362,
"name": "README.md",
"path": "README.md"
}`)
})
readme, _, err := client.Repositories.GetReadme(context.Background(), "o", "r", &RepositoryContentGetOptions{})
if err != nil {
t.Errorf("Repositories.GetReadme returned error: %v", err)
}
want := &RepositoryContent{Type: String("file"), Name: String("README.md"), Size: Int(5362), Encoding: String("base64"), Path: String("README.md")}
if !reflect.DeepEqual(readme, want) {
t.Errorf("Repositories.GetReadme returned %+v, want %+v", readme, want)
}
}
func TestRepositoriesService_DownloadContents_Success(t *testing.T) {
client, mux, serverURL, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{
"type": "file",
"name": "f",
"download_url": "`+serverURL+baseURLPath+`/download/f"
}]`)
})
mux.HandleFunc("/download/f", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, "foo")
})
r, err := client.Repositories.DownloadContents(context.Background(), "o", "r", "d/f", nil)
if err != nil {
t.Errorf("Repositories.DownloadContents returned error: %v", err)
}
bytes, err := ioutil.ReadAll(r)
if err != nil {
t.Errorf("Error reading response body: %v", err)
}
r.Close()
if got, want := string(bytes), "foo"; got != want {
t.Errorf("Repositories.DownloadContents returned %v, want %v", got, want)
}
}
func TestRepositoriesService_DownloadContents_NoDownloadURL(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{
"type": "file",
"name": "f",
}]`)
})
_, err := client.Repositories.DownloadContents(context.Background(), "o", "r", "d/f", nil)
if err == nil {
t.Errorf("Repositories.DownloadContents did not return expected error")
}
}
func TestRepositoriesService_DownloadContents_NoFile(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[]`)
})
_, err := client.Repositories.DownloadContents(context.Background(), "o", "r", "d/f", nil)
if err == nil {
t.Errorf("Repositories.DownloadContents did not return expected error")
}
}
func TestRepositoriesService_GetContents_File(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{
"type": "file",
"encoding": "base64",
"size": 20678,
"name": "LICENSE",
"path": "LICENSE"
}`)
})
fileContents, _, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "p", &RepositoryContentGetOptions{})
if err != nil {
t.Errorf("Repositories.GetContents returned error: %v", err)
}
want := &RepositoryContent{Type: String("file"), Name: String("LICENSE"), Size: Int(20678), Encoding: String("base64"), Path: String("LICENSE")}
if !reflect.DeepEqual(fileContents, want) {
t.Errorf("Repositories.GetContents returned %+v, want %+v", fileContents, want)
}
}
func TestRepositoriesService_GetContents_FilenameNeedsEscape(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/p#?%/中.go", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{}`)
})
_, _, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "p#?%/中.go", &RepositoryContentGetOptions{})
if err != nil {
t.Fatalf("Repositories.GetContents returned error: %v", err)
}
}
func TestRepositoriesService_GetContents_DirectoryWithSpaces(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/some directory/file.go", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{}`)
})
_, _, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "some directory/file.go", &RepositoryContentGetOptions{})
if err != nil {
t.Fatalf("Repositories.GetContents returned error: %v", err)
}
}
func TestRepositoriesService_GetContents_DirectoryWithPlusChars(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/some directory+name/file.go", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{}`)
})
_, _, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "some directory+name/file.go", &RepositoryContentGetOptions{})
if err != nil {
t.Fatalf("Repositories.GetContents returned error: %v", err)
}
}
func TestRepositoriesService_GetContents_Directory(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{
"type": "dir",
"name": "lib",
"path": "lib"
},
{
"type": "file",
"size": 20678,
"name": "LICENSE",
"path": "LICENSE"
}]`)
})
_, directoryContents, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "p", &RepositoryContentGetOptions{})
if err != nil {
t.Errorf("Repositories.GetContents returned error: %v", err)
}
want := []*RepositoryContent{{Type: String("dir"), Name: String("lib"), Path: String("lib")},
{Type: String("file"), Name: String("LICENSE"), Size: Int(20678), Path: String("LICENSE")}}
if !reflect.DeepEqual(directoryContents, want) {
t.Errorf("Repositories.GetContents_Directory returned %+v, want %+v", directoryContents, want)
}
}
func TestRepositoriesService_CreateFile(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
fmt.Fprint(w, `{
"content":{
"name":"p"
},
"commit":{
"message":"m",
"sha":"f5f369044773ff9c6383c087466d12adb6fa0828"
}
}`)
})
message := "m"
content := []byte("c")
repositoryContentsOptions := &RepositoryContentFileOptions{
Message: &message,
Content: content,
Committer: &CommitAuthor{Name: String("n"), Email: String("e")},
}
createResponse, _, err := client.Repositories.CreateFile(context.Background(), "o", "r", "p", repositoryContentsOptions)
if err != nil {
t.Errorf("Repositories.CreateFile returned error: %v", err)
}
want := &RepositoryContentResponse{
Content: &RepositoryContent{Name: String("p")},
Commit: Commit{
Message: String("m"),
SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"),
},
}
if !reflect.DeepEqual(createResponse, want) {
t.Errorf("Repositories.CreateFile returned %+v, want %+v", createResponse, want)
}
}
func TestRepositoriesService_UpdateFile(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
fmt.Fprint(w, `{
"content":{
"name":"p"
},
"commit":{
"message":"m",
"sha":"f5f369044773ff9c6383c087466d12adb6fa0828"
}
}`)
})
message := "m"
content := []byte("c")
sha := "f5f369044773ff9c6383c087466d12adb6fa0828"
repositoryContentsOptions := &RepositoryContentFileOptions{
Message: &message,
Content: content,
SHA: &sha,
Committer: &CommitAuthor{Name: String("n"), Email: String("e")},
}
updateResponse, _, err := client.Repositories.UpdateFile(context.Background(), "o", "r", "p", repositoryContentsOptions)
if err != nil {
t.Errorf("Repositories.UpdateFile returned error: %v", err)
}
want := &RepositoryContentResponse{
Content: &RepositoryContent{Name: String("p")},
Commit: Commit{
Message: String("m"),
SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"),
},
}
if !reflect.DeepEqual(updateResponse, want) {
t.Errorf("Repositories.UpdateFile returned %+v, want %+v", updateResponse, want)
}
}
func TestRepositoriesService_DeleteFile(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
fmt.Fprint(w, `{
"content": null,
"commit":{
"message":"m",
"sha":"f5f369044773ff9c6383c087466d12adb6fa0828"
}
}`)
})
message := "m"
sha := "f5f369044773ff9c6383c087466d12adb6fa0828"
repositoryContentsOptions := &RepositoryContentFileOptions{
Message: &message,
SHA: &sha,
Committer: &CommitAuthor{Name: String("n"), Email: String("e")},
}
deleteResponse, _, err := client.Repositories.DeleteFile(context.Background(), "o", "r", "p", repositoryContentsOptions)
if err != nil {
t.Errorf("Repositories.DeleteFile returned error: %v", err)
}
want := &RepositoryContentResponse{
Content: nil,
Commit: Commit{
Message: String("m"),
SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"),
},
}
if !reflect.DeepEqual(deleteResponse, want) {
t.Errorf("Repositories.DeleteFile returned %+v, want %+v", deleteResponse, want)
}
}
func TestRepositoriesService_GetArchiveLink(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/tarball", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
http.Redirect(w, r, "http://github.com/a", http.StatusFound)
})
url, resp, err := client.Repositories.GetArchiveLink(context.Background(), "o", "r", Tarball, &RepositoryContentGetOptions{})
if err != nil {
t.Errorf("Repositories.GetArchiveLink returned error: %v", err)
}
if resp.StatusCode != http.StatusFound {
t.Errorf("Repositories.GetArchiveLink returned status: %d, want %d", resp.StatusCode, http.StatusFound)
}
want := "http://github.com/a"
if url.String() != want {
t.Errorf("Repositories.GetArchiveLink returned %+v, want %+v", url.String(), want)
}
}

View file

@ -1,168 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
)
func TestRepositoriesService_ListDeployments(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/deployments", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{"environment": "test"})
fmt.Fprint(w, `[{"id":1}, {"id":2}]`)
})
opt := &DeploymentsListOptions{Environment: "test"}
deployments, _, err := client.Repositories.ListDeployments(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListDeployments returned error: %v", err)
}
want := []*Deployment{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(deployments, want) {
t.Errorf("Repositories.ListDeployments returned %+v, want %+v", deployments, want)
}
}
func TestRepositoriesService_GetDeployment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/deployments/3", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
fmt.Fprint(w, `{"id":3}`)
})
deployment, _, err := client.Repositories.GetDeployment(context.Background(), "o", "r", 3)
if err != nil {
t.Errorf("Repositories.GetDeployment returned error: %v", err)
}
want := &Deployment{ID: Int64(3)}
if !reflect.DeepEqual(deployment, want) {
t.Errorf("Repositories.GetDeployment returned %+v, want %+v", deployment, want)
}
}
func TestRepositoriesService_CreateDeployment(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &DeploymentRequest{Ref: String("1111"), Task: String("deploy"), TransientEnvironment: Bool(true)}
acceptHeaders := []string{mediaTypeDeploymentStatusPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/repos/o/r/deployments", func(w http.ResponseWriter, r *http.Request) {
v := new(DeploymentRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"ref": "1111", "task": "deploy"}`)
})
deployment, _, err := client.Repositories.CreateDeployment(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Repositories.CreateDeployment returned error: %v", err)
}
want := &Deployment{Ref: String("1111"), Task: String("deploy")}
if !reflect.DeepEqual(deployment, want) {
t.Errorf("Repositories.CreateDeployment returned %+v, want %+v", deployment, want)
}
}
func TestRepositoriesService_ListDeploymentStatuses(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/deployments/1/statuses", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGraphQLNodeIDPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}, {"id":2}]`)
})
opt := &ListOptions{Page: 2}
statutses, _, err := client.Repositories.ListDeploymentStatuses(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("Repositories.ListDeploymentStatuses returned error: %v", err)
}
want := []*DeploymentStatus{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(statutses, want) {
t.Errorf("Repositories.ListDeploymentStatuses returned %+v, want %+v", statutses, want)
}
}
func TestRepositoriesService_GetDeploymentStatus(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
acceptHeaders := []string{mediaTypeDeploymentStatusPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/repos/o/r/deployments/3/statuses/4", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
fmt.Fprint(w, `{"id":4}`)
})
deploymentStatus, _, err := client.Repositories.GetDeploymentStatus(context.Background(), "o", "r", 3, 4)
if err != nil {
t.Errorf("Repositories.GetDeploymentStatus returned error: %v", err)
}
want := &DeploymentStatus{ID: Int64(4)}
if !reflect.DeepEqual(deploymentStatus, want) {
t.Errorf("Repositories.GetDeploymentStatus returned %+v, want %+v", deploymentStatus, want)
}
}
func TestRepositoriesService_CreateDeploymentStatus(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &DeploymentStatusRequest{State: String("inactive"), Description: String("deploy"), AutoInactive: Bool(false)}
acceptHeaders := []string{mediaTypeDeploymentStatusPreview, mediaTypeGraphQLNodeIDPreview}
mux.HandleFunc("/repos/o/r/deployments/1/statuses", func(w http.ResponseWriter, r *http.Request) {
v := new(DeploymentStatusRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", strings.Join(acceptHeaders, ", "))
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"state": "inactive", "description": "deploy"}`)
})
deploymentStatus, _, err := client.Repositories.CreateDeploymentStatus(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Repositories.CreateDeploymentStatus returned error: %v", err)
}
want := &DeploymentStatus{State: String("inactive"), Description: String("deploy")}
if !reflect.DeepEqual(deploymentStatus, want) {
t.Errorf("Repositories.CreateDeploymentStatus returned %+v, want %+v", deploymentStatus, want)
}
}

View file

@ -1,81 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_ListForks(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/forks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeTopicsPreview)
testFormValues(t, r, values{
"sort": "newest",
"page": "3",
})
fmt.Fprint(w, `[{"id":1},{"id":2}]`)
})
opt := &RepositoryListForksOptions{
Sort: "newest",
ListOptions: ListOptions{Page: 3},
}
repos, _, err := client.Repositories.ListForks(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListForks returned error: %v", err)
}
want := []*Repository{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(repos, want) {
t.Errorf("Repositories.ListForks returned %+v, want %+v", repos, want)
}
}
func TestRepositoriesService_ListForks_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.ListForks(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_CreateFork(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/forks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testFormValues(t, r, values{"organization": "o"})
fmt.Fprint(w, `{"id":1}`)
})
opt := &RepositoryCreateForkOptions{Organization: "o"}
repo, _, err := client.Repositories.CreateFork(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.CreateFork returned error: %v", err)
}
want := &Repository{ID: Int64(1)}
if !reflect.DeepEqual(repo, want) {
t.Errorf("Repositories.CreateFork returned %+v, want %+v", repo, want)
}
}
func TestRepositoriesService_CreateFork_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.CreateFork(context.Background(), "%", "r", nil)
testURLParseError(t, err)
}

View file

@ -1,206 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_CreateHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Hook{Name: String("t")}
mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) {
v := new(Hook)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
hook, _, err := client.Repositories.CreateHook(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Repositories.CreateHook returned error: %v", err)
}
want := &Hook{ID: Int64(1)}
if !reflect.DeepEqual(hook, want) {
t.Errorf("Repositories.CreateHook returned %+v, want %+v", hook, want)
}
}
func TestRepositoriesService_CreateHook_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.CreateHook(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_ListHooks(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}, {"id":2}]`)
})
opt := &ListOptions{Page: 2}
hooks, _, err := client.Repositories.ListHooks(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListHooks returned error: %v", err)
}
want := []*Hook{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(hooks, want) {
t.Errorf("Repositories.ListHooks returned %+v, want %+v", hooks, want)
}
}
func TestRepositoriesService_ListHooks_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.ListHooks(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_GetHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
hook, _, err := client.Repositories.GetHook(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.GetHook returned error: %v", err)
}
want := &Hook{ID: Int64(1)}
if !reflect.DeepEqual(hook, want) {
t.Errorf("Repositories.GetHook returned %+v, want %+v", hook, want)
}
}
func TestRepositoriesService_GetHook_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.GetHook(context.Background(), "%", "%", 1)
testURLParseError(t, err)
}
func TestRepositoriesService_EditHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Hook{Name: String("t")}
mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) {
v := new(Hook)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
hook, _, err := client.Repositories.EditHook(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Repositories.EditHook returned error: %v", err)
}
want := &Hook{ID: Int64(1)}
if !reflect.DeepEqual(hook, want) {
t.Errorf("Repositories.EditHook returned %+v, want %+v", hook, want)
}
}
func TestRepositoriesService_EditHook_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.EditHook(context.Background(), "%", "%", 1, nil)
testURLParseError(t, err)
}
func TestRepositoriesService_DeleteHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Repositories.DeleteHook(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.DeleteHook returned error: %v", err)
}
}
func TestRepositoriesService_DeleteHook_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Repositories.DeleteHook(context.Background(), "%", "%", 1)
testURLParseError(t, err)
}
func TestRepositoriesService_PingHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/hooks/1/pings", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
})
_, err := client.Repositories.PingHook(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.PingHook returned error: %v", err)
}
}
func TestRepositoriesService_TestHook(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/hooks/1/tests", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
})
_, err := client.Repositories.TestHook(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.TestHook returned error: %v", err)
}
}
func TestRepositoriesService_TestHook_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Repositories.TestHook(context.Background(), "%", "%", 1)
testURLParseError(t, err)
}

View file

@ -1,74 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_ListInvitations(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/invitations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprintf(w, `[{"id":1}, {"id":2}]`)
})
opt := &ListOptions{Page: 2}
got, _, err := client.Repositories.ListInvitations(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListInvitations returned error: %v", err)
}
want := []*RepositoryInvitation{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(got, want) {
t.Errorf("Repositories.ListInvitations = %+v, want %+v", got, want)
}
}
func TestRepositoriesService_DeleteInvitation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/invitations/2", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview)
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Repositories.DeleteInvitation(context.Background(), "o", "r", 2)
if err != nil {
t.Errorf("Repositories.DeleteInvitation returned error: %v", err)
}
}
func TestRepositoriesService_UpdateInvitation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/invitations/2", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview)
fmt.Fprintf(w, `{"id":1}`)
})
got, _, err := client.Repositories.UpdateInvitation(context.Background(), "o", "r", 2, "write")
if err != nil {
t.Errorf("Repositories.UpdateInvitation returned error: %v", err)
}
want := &RepositoryInvitation{ID: Int64(1)}
if !reflect.DeepEqual(got, want) {
t.Errorf("Repositories.UpdateInvitation = %+v, want %+v", got, want)
}
}

View file

@ -1,169 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_ListKeys(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/keys", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
keys, _, err := client.Repositories.ListKeys(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListKeys returned error: %v", err)
}
want := []*Key{{ID: Int64(1)}}
if !reflect.DeepEqual(keys, want) {
t.Errorf("Repositories.ListKeys returned %+v, want %+v", keys, want)
}
}
func TestRepositoriesService_ListKeys_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.ListKeys(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_GetKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
key, _, err := client.Repositories.GetKey(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.GetKey returned error: %v", err)
}
want := &Key{ID: Int64(1)}
if !reflect.DeepEqual(key, want) {
t.Errorf("Repositories.GetKey returned %+v, want %+v", key, want)
}
}
func TestRepositoriesService_GetKey_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.GetKey(context.Background(), "%", "%", 1)
testURLParseError(t, err)
}
func TestRepositoriesService_CreateKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Key{Key: String("k"), Title: String("t")}
mux.HandleFunc("/repos/o/r/keys", func(w http.ResponseWriter, r *http.Request) {
v := new(Key)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
key, _, err := client.Repositories.CreateKey(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Repositories.GetKey returned error: %v", err)
}
want := &Key{ID: Int64(1)}
if !reflect.DeepEqual(key, want) {
t.Errorf("Repositories.GetKey returned %+v, want %+v", key, want)
}
}
func TestRepositoriesService_CreateKey_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.CreateKey(context.Background(), "%", "%", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_EditKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Key{Key: String("k"), Title: String("t")}
mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) {
v := new(Key)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
key, _, err := client.Repositories.EditKey(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Repositories.EditKey returned error: %v", err)
}
want := &Key{ID: Int64(1)}
if !reflect.DeepEqual(key, want) {
t.Errorf("Repositories.EditKey returned %+v, want %+v", key, want)
}
}
func TestRepositoriesService_EditKey_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.EditKey(context.Background(), "%", "%", 1, nil)
testURLParseError(t, err)
}
func TestRepositoriesService_DeleteKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Repositories.DeleteKey(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.DeleteKey returned error: %v", err)
}
}
func TestRepositoriesService_DeleteKey_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Repositories.DeleteKey(context.Background(), "%", "%", 1)
testURLParseError(t, err)
}

View file

@ -1,48 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_Merge(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &RepositoryMergeRequest{
Base: String("b"),
Head: String("h"),
CommitMessage: String("c"),
}
mux.HandleFunc("/repos/o/r/merges", func(w http.ResponseWriter, r *http.Request) {
v := new(RepositoryMergeRequest)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"sha":"s"}`)
})
commit, _, err := client.Repositories.Merge(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Repositories.Merge returned error: %v", err)
}
want := &RepositoryCommit{SHA: String("s")}
if !reflect.DeepEqual(commit, want) {
t.Errorf("Repositories.Merge returned %+v, want %+v", commit, want)
}
}

View file

@ -1,134 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_GetPagesInfo(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pages", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypePagesPreview)
fmt.Fprint(w, `{"url":"u","status":"s","cname":"c","custom_404":false,"html_url":"h"}`)
})
page, _, err := client.Repositories.GetPagesInfo(context.Background(), "o", "r")
if err != nil {
t.Errorf("Repositories.GetPagesInfo returned error: %v", err)
}
want := &Pages{URL: String("u"), Status: String("s"), CNAME: String("c"), Custom404: Bool(false), HTMLURL: String("h")}
if !reflect.DeepEqual(page, want) {
t.Errorf("Repositories.GetPagesInfo returned %+v, want %+v", page, want)
}
}
func TestRepositoriesService_ListPagesBuilds(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pages/builds", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"url":"u","status":"s","commit":"c"}]`)
})
pages, _, err := client.Repositories.ListPagesBuilds(context.Background(), "o", "r", nil)
if err != nil {
t.Errorf("Repositories.ListPagesBuilds returned error: %v", err)
}
want := []*PagesBuild{{URL: String("u"), Status: String("s"), Commit: String("c")}}
if !reflect.DeepEqual(pages, want) {
t.Errorf("Repositories.ListPagesBuilds returned %+v, want %+v", pages, want)
}
}
func TestRepositoriesService_ListPagesBuilds_withOptions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pages/builds", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
fmt.Fprint(w, `[]`)
})
_, _, err := client.Repositories.ListPagesBuilds(context.Background(), "o", "r", &ListOptions{Page: 2})
if err != nil {
t.Errorf("Repositories.ListPagesBuilds returned error: %v", err)
}
}
func TestRepositoriesService_GetLatestPagesBuild(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pages/builds/latest", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"url":"u","status":"s","commit":"c"}`)
})
build, _, err := client.Repositories.GetLatestPagesBuild(context.Background(), "o", "r")
if err != nil {
t.Errorf("Repositories.GetLatestPagesBuild returned error: %v", err)
}
want := &PagesBuild{URL: String("u"), Status: String("s"), Commit: String("c")}
if !reflect.DeepEqual(build, want) {
t.Errorf("Repositories.GetLatestPagesBuild returned %+v, want %+v", build, want)
}
}
func TestRepositoriesService_GetPageBuild(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pages/builds/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"url":"u","status":"s","commit":"c"}`)
})
build, _, err := client.Repositories.GetPageBuild(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.GetPageBuild returned error: %v", err)
}
want := &PagesBuild{URL: String("u"), Status: String("s"), Commit: String("c")}
if !reflect.DeepEqual(build, want) {
t.Errorf("Repositories.GetPageBuild returned %+v, want %+v", build, want)
}
}
func TestRepositoriesService_RequestPageBuild(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/pages/builds", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypePagesPreview)
fmt.Fprint(w, `{"url":"u","status":"s"}`)
})
build, _, err := client.Repositories.RequestPageBuild(context.Background(), "o", "r")
if err != nil {
t.Errorf("Repositories.RequestPageBuild returned error: %v", err)
}
want := &PagesBuild{URL: String("u"), Status: String("s")}
if !reflect.DeepEqual(build, want) {
t.Errorf("Repositories.RequestPageBuild returned %+v, want %+v", build, want)
}
}

View file

@ -1,68 +0,0 @@
// Copyright 2017 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_ListProjects(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/projects", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ProjectListOptions{ListOptions: ListOptions{Page: 2}}
projects, _, err := client.Repositories.ListProjects(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListProjects returned error: %v", err)
}
want := []*Project{{ID: Int64(1)}}
if !reflect.DeepEqual(projects, want) {
t.Errorf("Repositories.ListProjects returned %+v, want %+v", projects, want)
}
}
func TestRepositoriesService_CreateProject(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ProjectOptions{Name: "Project Name", Body: "Project body."}
mux.HandleFunc("/repos/o/r/projects", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeProjectsPreview)
v := &ProjectOptions{}
json.NewDecoder(r.Body).Decode(v)
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
project, _, err := client.Repositories.CreateProject(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Repositories.CreateProject returned error: %v", err)
}
want := &Project{ID: Int64(1)}
if !reflect.DeepEqual(project, want) {
t.Errorf("Repositories.CreateProject returned %+v, want %+v", project, want)
}
}

View file

@ -1,353 +0,0 @@
// Copyright 2013 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.
package github
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"reflect"
"strings"
"testing"
)
func TestRepositoriesService_ListReleases(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
releases, _, err := client.Repositories.ListReleases(context.Background(), "o", "r", opt)
if err != nil {
t.Errorf("Repositories.ListReleases returned error: %v", err)
}
want := []*RepositoryRelease{{ID: Int64(1)}}
if !reflect.DeepEqual(releases, want) {
t.Errorf("Repositories.ListReleases returned %+v, want %+v", releases, want)
}
}
func TestRepositoriesService_GetRelease(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1,"author":{"login":"l"}}`)
})
release, resp, err := client.Repositories.GetRelease(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.GetRelease returned error: %v\n%v", err, resp.Body)
}
want := &RepositoryRelease{ID: Int64(1), Author: &User{Login: String("l")}}
if !reflect.DeepEqual(release, want) {
t.Errorf("Repositories.GetRelease returned %+v, want %+v", release, want)
}
}
func TestRepositoriesService_GetLatestRelease(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/latest", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":3}`)
})
release, resp, err := client.Repositories.GetLatestRelease(context.Background(), "o", "r")
if err != nil {
t.Errorf("Repositories.GetLatestRelease returned error: %v\n%v", err, resp.Body)
}
want := &RepositoryRelease{ID: Int64(3)}
if !reflect.DeepEqual(release, want) {
t.Errorf("Repositories.GetLatestRelease returned %+v, want %+v", release, want)
}
}
func TestRepositoriesService_GetReleaseByTag(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/tags/foo", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":13}`)
})
release, resp, err := client.Repositories.GetReleaseByTag(context.Background(), "o", "r", "foo")
if err != nil {
t.Errorf("Repositories.GetReleaseByTag returned error: %v\n%v", err, resp.Body)
}
want := &RepositoryRelease{ID: Int64(13)}
if !reflect.DeepEqual(release, want) {
t.Errorf("Repositories.GetReleaseByTag returned %+v, want %+v", release, want)
}
}
func TestRepositoriesService_CreateRelease(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &RepositoryRelease{Name: String("v1.0")}
mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) {
v := new(RepositoryRelease)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
release, _, err := client.Repositories.CreateRelease(context.Background(), "o", "r", input)
if err != nil {
t.Errorf("Repositories.CreateRelease returned error: %v", err)
}
want := &RepositoryRelease{ID: Int64(1)}
if !reflect.DeepEqual(release, want) {
t.Errorf("Repositories.CreateRelease returned %+v, want %+v", release, want)
}
}
func TestRepositoriesService_EditRelease(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &RepositoryRelease{Name: String("n")}
mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) {
v := new(RepositoryRelease)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
release, _, err := client.Repositories.EditRelease(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Repositories.EditRelease returned error: %v", err)
}
want := &RepositoryRelease{ID: Int64(1)}
if !reflect.DeepEqual(release, want) {
t.Errorf("Repositories.EditRelease returned = %+v, want %+v", release, want)
}
}
func TestRepositoriesService_DeleteRelease(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Repositories.DeleteRelease(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.DeleteRelease returned error: %v", err)
}
}
func TestRepositoriesService_ListReleaseAssets(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/1/assets", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
assets, _, err := client.Repositories.ListReleaseAssets(context.Background(), "o", "r", 1, opt)
if err != nil {
t.Errorf("Repositories.ListReleaseAssets returned error: %v", err)
}
want := []*ReleaseAsset{{ID: Int64(1)}}
if !reflect.DeepEqual(assets, want) {
t.Errorf("Repositories.ListReleaseAssets returned %+v, want %+v", assets, want)
}
}
func TestRepositoriesService_GetReleaseAsset(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
asset, _, err := client.Repositories.GetReleaseAsset(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.GetReleaseAsset returned error: %v", err)
}
want := &ReleaseAsset{ID: Int64(1)}
if !reflect.DeepEqual(asset, want) {
t.Errorf("Repositories.GetReleaseAsset returned %+v, want %+v", asset, want)
}
}
func TestRepositoriesService_DownloadReleaseAsset_Stream(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", defaultMediaType)
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename=hello-world.txt")
fmt.Fprint(w, "Hello World")
})
reader, _, err := client.Repositories.DownloadReleaseAsset(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.DownloadReleaseAsset returned error: %v", err)
}
want := []byte("Hello World")
content, err := ioutil.ReadAll(reader)
if err != nil {
t.Errorf("Repositories.DownloadReleaseAsset returned bad reader: %v", err)
}
if !bytes.Equal(want, content) {
t.Errorf("Repositories.DownloadReleaseAsset returned %+v, want %+v", content, want)
}
}
func TestRepositoriesService_DownloadReleaseAsset_Redirect(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", defaultMediaType)
http.Redirect(w, r, "/yo", http.StatusFound)
})
_, got, err := client.Repositories.DownloadReleaseAsset(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.DownloadReleaseAsset returned error: %v", err)
}
want := "/yo"
if !strings.HasSuffix(got, want) {
t.Errorf("Repositories.DownloadReleaseAsset returned %+v, want %+v", got, want)
}
}
func TestRepositoriesService_DownloadReleaseAsset_APIError(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", defaultMediaType)
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, `{"message":"Not Found","documentation_url":"https://developer.github.com/v3"}`)
})
resp, loc, err := client.Repositories.DownloadReleaseAsset(context.Background(), "o", "r", 1)
if err == nil {
t.Error("Repositories.DownloadReleaseAsset did not return an error")
}
if resp != nil {
resp.Close()
t.Error("Repositories.DownloadReleaseAsset returned stream, want nil")
}
if loc != "" {
t.Errorf(`Repositories.DownloadReleaseAsset returned "%s", want empty ""`, loc)
}
}
func TestRepositoriesService_EditReleaseAsset(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &ReleaseAsset{Name: String("n")}
mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) {
v := new(ReleaseAsset)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
asset, _, err := client.Repositories.EditReleaseAsset(context.Background(), "o", "r", 1, input)
if err != nil {
t.Errorf("Repositories.EditReleaseAsset returned error: %v", err)
}
want := &ReleaseAsset{ID: Int64(1)}
if !reflect.DeepEqual(asset, want) {
t.Errorf("Repositories.EditReleaseAsset returned = %+v, want %+v", asset, want)
}
}
func TestRepositoriesService_DeleteReleaseAsset(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Repositories.DeleteReleaseAsset(context.Background(), "o", "r", 1)
if err != nil {
t.Errorf("Repositories.DeleteReleaseAsset returned error: %v", err)
}
}
func TestRepositoriesService_UploadReleaseAsset(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/releases/1/assets", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testHeader(t, r, "Content-Type", "text/plain; charset=utf-8")
testHeader(t, r, "Content-Length", "12")
testFormValues(t, r, values{"name": "n"})
testBody(t, r, "Upload me !\n")
fmt.Fprintf(w, `{"id":1}`)
})
file, dir, err := openTestFile("upload.txt", "Upload me !\n")
if err != nil {
t.Fatalf("Unable to create temp file: %v", err)
}
defer os.RemoveAll(dir)
opt := &UploadOptions{Name: "n"}
asset, _, err := client.Repositories.UploadReleaseAsset(context.Background(), "o", "r", 1, opt, file)
if err != nil {
t.Errorf("Repositories.UploadReleaseAssert returned error: %v", err)
}
want := &ReleaseAsset{ID: Int64(1)}
if !reflect.DeepEqual(asset, want) {
t.Errorf("Repositories.UploadReleaseAssert returned %+v, want %+v", asset, want)
}
}

View file

@ -1,211 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestRepositoriesService_ListContributorsStats(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/stats/contributors", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `
[
{
"author": {
"id": 1
},
"total": 135,
"weeks": [
{
"w": 1367712000,
"a": 6898,
"d": 77,
"c": 10
}
]
}
]
`)
})
stats, _, err := client.Repositories.ListContributorsStats(context.Background(), "o", "r")
if err != nil {
t.Errorf("RepositoriesService.ListContributorsStats returned error: %v", err)
}
want := []*ContributorStats{
{
Author: &Contributor{
ID: Int64(1),
},
Total: Int(135),
Weeks: []WeeklyStats{
{
Week: &Timestamp{time.Date(2013, 05, 05, 00, 00, 00, 0, time.UTC).Local()},
Additions: Int(6898),
Deletions: Int(77),
Commits: Int(10),
},
},
},
}
if !reflect.DeepEqual(stats, want) {
t.Errorf("RepositoriesService.ListContributorsStats returned %+v, want %+v", stats, want)
}
}
func TestRepositoriesService_ListCommitActivity(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/stats/commit_activity", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `
[
{
"days": [0, 3, 26, 20, 39, 1, 0],
"total": 89,
"week": 1336280400
}
]
`)
})
activity, _, err := client.Repositories.ListCommitActivity(context.Background(), "o", "r")
if err != nil {
t.Errorf("RepositoriesService.ListCommitActivity returned error: %v", err)
}
want := []*WeeklyCommitActivity{
{
Days: []int{0, 3, 26, 20, 39, 1, 0},
Total: Int(89),
Week: &Timestamp{time.Date(2012, 05, 06, 05, 00, 00, 0, time.UTC).Local()},
},
}
if !reflect.DeepEqual(activity, want) {
t.Errorf("RepositoriesService.ListCommitActivity returned %+v, want %+v", activity, want)
}
}
func TestRepositoriesService_ListCodeFrequency(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/stats/code_frequency", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[[1302998400, 1124, -435]]`)
})
code, _, err := client.Repositories.ListCodeFrequency(context.Background(), "o", "r")
if err != nil {
t.Errorf("RepositoriesService.ListCodeFrequency returned error: %v", err)
}
want := []*WeeklyStats{{
Week: &Timestamp{time.Date(2011, 04, 17, 00, 00, 00, 0, time.UTC).Local()},
Additions: Int(1124),
Deletions: Int(-435),
}}
if !reflect.DeepEqual(code, want) {
t.Errorf("RepositoriesService.ListCodeFrequency returned %+v, want %+v", code, want)
}
}
func TestRepositoriesService_Participation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/stats/participation", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `
{
"all": [
11,21,15,2,8,1,8,23,17,21,11,10,33,
91,38,34,22,23,32,3,43,87,71,18,13,5,
13,16,66,27,12,45,110,117,13,8,18,9,19,
26,39,12,20,31,46,91,45,10,24,9,29,7
],
"owner": [
3,2,3,0,2,0,5,14,7,9,1,5,0,
48,19,2,0,1,10,2,23,40,35,8,8,2,
10,6,30,0,2,9,53,104,3,3,10,4,7,
11,21,4,4,22,26,63,11,2,14,1,10,3
]
}
`)
})
participation, _, err := client.Repositories.ListParticipation(context.Background(), "o", "r")
if err != nil {
t.Errorf("RepositoriesService.ListParticipation returned error: %v", err)
}
want := &RepositoryParticipation{
All: []int{
11, 21, 15, 2, 8, 1, 8, 23, 17, 21, 11, 10, 33,
91, 38, 34, 22, 23, 32, 3, 43, 87, 71, 18, 13, 5,
13, 16, 66, 27, 12, 45, 110, 117, 13, 8, 18, 9, 19,
26, 39, 12, 20, 31, 46, 91, 45, 10, 24, 9, 29, 7,
},
Owner: []int{
3, 2, 3, 0, 2, 0, 5, 14, 7, 9, 1, 5, 0,
48, 19, 2, 0, 1, 10, 2, 23, 40, 35, 8, 8, 2,
10, 6, 30, 0, 2, 9, 53, 104, 3, 3, 10, 4, 7,
11, 21, 4, 4, 22, 26, 63, 11, 2, 14, 1, 10, 3,
},
}
if !reflect.DeepEqual(participation, want) {
t.Errorf("RepositoriesService.ListParticipation returned %+v, want %+v", participation, want)
}
}
func TestRepositoriesService_ListPunchCard(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/stats/punch_card", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[
[0, 0, 5],
[0, 1, 43],
[0, 2, 21]
]`)
})
card, _, err := client.Repositories.ListPunchCard(context.Background(), "o", "r")
if err != nil {
t.Errorf("RepositoriesService.ListPunchCard returned error: %v", err)
}
want := []*PunchCard{
{Day: Int(0), Hour: Int(0), Commits: Int(5)},
{Day: Int(0), Hour: Int(1), Commits: Int(43)},
{Day: Int(0), Hour: Int(2), Commits: Int(21)},
}
if !reflect.DeepEqual(card, want) {
t.Errorf("RepositoriesService.ListPunchCard returned %+v, want %+v", card, want)
}
}

View file

@ -1,103 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestRepositoriesService_ListStatuses(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/commits/r/statuses", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
statuses, _, err := client.Repositories.ListStatuses(context.Background(), "o", "r", "r", opt)
if err != nil {
t.Errorf("Repositories.ListStatuses returned error: %v", err)
}
want := []*RepoStatus{{ID: Int64(1)}}
if !reflect.DeepEqual(statuses, want) {
t.Errorf("Repositories.ListStatuses returned %+v, want %+v", statuses, want)
}
}
func TestRepositoriesService_ListStatuses_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.ListStatuses(context.Background(), "%", "r", "r", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_CreateStatus(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &RepoStatus{State: String("s"), TargetURL: String("t"), Description: String("d")}
mux.HandleFunc("/repos/o/r/statuses/r", func(w http.ResponseWriter, r *http.Request) {
v := new(RepoStatus)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
status, _, err := client.Repositories.CreateStatus(context.Background(), "o", "r", "r", input)
if err != nil {
t.Errorf("Repositories.CreateStatus returned error: %v", err)
}
want := &RepoStatus{ID: Int64(1)}
if !reflect.DeepEqual(status, want) {
t.Errorf("Repositories.CreateStatus returned %+v, want %+v", status, want)
}
}
func TestRepositoriesService_CreateStatus_invalidOwner(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Repositories.CreateStatus(context.Background(), "%", "r", "r", nil)
testURLParseError(t, err)
}
func TestRepositoriesService_GetCombinedStatus(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/commits/r/status", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `{"state":"success", "statuses":[{"id":1}]}`)
})
opt := &ListOptions{Page: 2}
status, _, err := client.Repositories.GetCombinedStatus(context.Background(), "o", "r", "r", opt)
if err != nil {
t.Errorf("Repositories.GetCombinedStatus returned error: %v", err)
}
want := &CombinedStatus{State: String("success"), Statuses: []RepoStatus{{ID: Int64(1)}}}
if !reflect.DeepEqual(status, want) {
t.Errorf("Repositories.GetCombinedStatus returned %+v, want %+v", status, want)
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,145 +0,0 @@
// 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
"time"
)
func TestRepositoriesService_ListTrafficReferrers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/traffic/popular/referrers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprintf(w, `[{
"referrer": "Google",
"count": 4,
"uniques": 3
}]`)
})
referrers, _, err := client.Repositories.ListTrafficReferrers(context.Background(), "o", "r")
if err != nil {
t.Errorf("Repositories.ListPaths returned error: %+v", err)
}
want := []*TrafficReferrer{{
Referrer: String("Google"),
Count: Int(4),
Uniques: Int(3),
}}
if !reflect.DeepEqual(referrers, want) {
t.Errorf("Repositories.ListReferrers returned %+v, want %+v", referrers, want)
}
}
func TestRepositoriesService_ListTrafficPaths(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/traffic/popular/paths", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprintf(w, `[{
"path": "/github/hubot",
"title": "github/hubot: A customizable life embetterment robot.",
"count": 3542,
"uniques": 2225
}]`)
})
paths, _, err := client.Repositories.ListTrafficPaths(context.Background(), "o", "r")
if err != nil {
t.Errorf("Repositories.ListPaths returned error: %+v", err)
}
want := []*TrafficPath{{
Path: String("/github/hubot"),
Title: String("github/hubot: A customizable life embetterment robot."),
Count: Int(3542),
Uniques: Int(2225),
}}
if !reflect.DeepEqual(paths, want) {
t.Errorf("Repositories.ListPaths returned %+v, want %+v", paths, want)
}
}
func TestRepositoriesService_ListTrafficViews(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/traffic/views", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprintf(w, `{"count": 7,
"uniques": 6,
"views": [{
"timestamp": "2016-05-31T16:00:00.000Z",
"count": 7,
"uniques": 6
}]}`)
})
views, _, err := client.Repositories.ListTrafficViews(context.Background(), "o", "r", nil)
if err != nil {
t.Errorf("Repositories.ListPaths returned error: %+v", err)
}
want := &TrafficViews{
Views: []*TrafficData{{
Timestamp: &Timestamp{time.Date(2016, time.May, 31, 16, 0, 0, 0, time.UTC)},
Count: Int(7),
Uniques: Int(6),
}},
Count: Int(7),
Uniques: Int(6),
}
if !reflect.DeepEqual(views, want) {
t.Errorf("Repositories.ListViews returned %+v, want %+v", views, want)
}
}
func TestRepositoriesService_ListTrafficClones(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/repos/o/r/traffic/clones", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprintf(w, `{"count": 7,
"uniques": 6,
"clones": [{
"timestamp": "2016-05-31T16:00:00.00Z",
"count": 7,
"uniques": 6
}]}`)
})
clones, _, err := client.Repositories.ListTrafficClones(context.Background(), "o", "r", nil)
if err != nil {
t.Errorf("Repositories.ListPaths returned error: %+v", err)
}
want := &TrafficClones{
Clones: []*TrafficData{{
Timestamp: &Timestamp{time.Date(2016, time.May, 31, 16, 0, 0, 0, time.UTC)},
Count: Int(7),
Uniques: Int(6),
}},
Count: Int(7),
Uniques: Int(6),
}
if !reflect.DeepEqual(clones, want) {
t.Errorf("Repositories.ListViews returned %+v, want %+v", clones, want)
}
}

View file

@ -1,268 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestSearchService_Repositories(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/search/repositories", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"q": "blah",
"sort": "forks",
"order": "desc",
"page": "2",
"per_page": "2",
})
fmt.Fprint(w, `{"total_count": 4, "incomplete_results": false, "items": [{"id":1},{"id":2}]}`)
})
opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}}
result, _, err := client.Search.Repositories(context.Background(), "blah", opts)
if err != nil {
t.Errorf("Search.Repositories returned error: %v", err)
}
want := &RepositoriesSearchResult{
Total: Int(4),
IncompleteResults: Bool(false),
Repositories: []Repository{{ID: Int64(1)}, {ID: Int64(2)}},
}
if !reflect.DeepEqual(result, want) {
t.Errorf("Search.Repositories returned %+v, want %+v", result, want)
}
}
func TestSearchService_Commits(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/search/commits", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"q": "blah",
"sort": "author-date",
"order": "desc",
})
fmt.Fprint(w, `{"total_count": 4, "incomplete_results": false, "items": [{"sha":"random_hash1"},{"sha":"random_hash2"}]}`)
})
opts := &SearchOptions{Sort: "author-date", Order: "desc"}
result, _, err := client.Search.Commits(context.Background(), "blah", opts)
if err != nil {
t.Errorf("Search.Commits returned error: %v", err)
}
want := &CommitsSearchResult{
Total: Int(4),
IncompleteResults: Bool(false),
Commits: []*CommitResult{{SHA: String("random_hash1")}, {SHA: String("random_hash2")}},
}
if !reflect.DeepEqual(result, want) {
t.Errorf("Search.Commits returned %+v, want %+v", result, want)
}
}
func TestSearchService_Issues(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/search/issues", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"q": "blah",
"sort": "forks",
"order": "desc",
"page": "2",
"per_page": "2",
})
fmt.Fprint(w, `{"total_count": 4, "incomplete_results": true, "items": [{"number":1},{"number":2}]}`)
})
opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}}
result, _, err := client.Search.Issues(context.Background(), "blah", opts)
if err != nil {
t.Errorf("Search.Issues returned error: %v", err)
}
want := &IssuesSearchResult{
Total: Int(4),
IncompleteResults: Bool(true),
Issues: []Issue{{Number: Int(1)}, {Number: Int(2)}},
}
if !reflect.DeepEqual(result, want) {
t.Errorf("Search.Issues returned %+v, want %+v", result, want)
}
}
func TestSearchService_Issues_withQualifiers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/search/issues", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"q": "gopher is:issue label:bug language:go",
})
fmt.Fprint(w, `{"total_count": 4, "incomplete_results": true, "items": [{"number":1},{"number":2}]}`)
})
opts := &SearchOptions{}
result, _, err := client.Search.Issues(context.Background(), "gopher is:issue label:bug language:go", opts)
if err != nil {
t.Errorf("Search.Issues returned error: %v", err)
}
want := &IssuesSearchResult{
Total: Int(4),
IncompleteResults: Bool(true),
Issues: []Issue{{Number: Int(1)}, {Number: Int(2)}},
}
if !reflect.DeepEqual(result, want) {
t.Errorf("Search.Issues returned %+v, want %+v", result, want)
}
}
func TestSearchService_Users(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/search/users", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"q": "blah",
"sort": "forks",
"order": "desc",
"page": "2",
"per_page": "2",
})
fmt.Fprint(w, `{"total_count": 4, "incomplete_results": false, "items": [{"id":1},{"id":2}]}`)
})
opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}}
result, _, err := client.Search.Users(context.Background(), "blah", opts)
if err != nil {
t.Errorf("Search.Issues returned error: %v", err)
}
want := &UsersSearchResult{
Total: Int(4),
IncompleteResults: Bool(false),
Users: []User{{ID: Int64(1)}, {ID: Int64(2)}},
}
if !reflect.DeepEqual(result, want) {
t.Errorf("Search.Users returned %+v, want %+v", result, want)
}
}
func TestSearchService_Code(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/search/code", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"q": "blah",
"sort": "forks",
"order": "desc",
"page": "2",
"per_page": "2",
})
fmt.Fprint(w, `{"total_count": 4, "incomplete_results": false, "items": [{"name":"1"},{"name":"2"}]}`)
})
opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}}
result, _, err := client.Search.Code(context.Background(), "blah", opts)
if err != nil {
t.Errorf("Search.Code returned error: %v", err)
}
want := &CodeSearchResult{
Total: Int(4),
IncompleteResults: Bool(false),
CodeResults: []CodeResult{{Name: String("1")}, {Name: String("2")}},
}
if !reflect.DeepEqual(result, want) {
t.Errorf("Search.Code returned %+v, want %+v", result, want)
}
}
func TestSearchService_CodeTextMatch(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/search/code", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
textMatchResponse := `
{
"total_count": 1,
"incomplete_results": false,
"items": [
{
"name":"gopher1",
"text_matches": [
{
"fragment": "I'm afraid my friend what you have found\nIs a gopher who lives to feed",
"matches": [
{
"text": "gopher",
"indices": [
14,
21
]
}
]
}
]
}
]
}
`
fmt.Fprint(w, textMatchResponse)
})
opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}, TextMatch: true}
result, _, err := client.Search.Code(context.Background(), "blah", opts)
if err != nil {
t.Errorf("Search.Code returned error: %v", err)
}
wantedCodeResult := CodeResult{
Name: String("gopher1"),
TextMatches: []TextMatch{{
Fragment: String("I'm afraid my friend what you have found\nIs a gopher who lives to feed"),
Matches: []Match{{Text: String("gopher"), Indices: []int{14, 21}}},
},
},
}
want := &CodeSearchResult{
Total: Int(1),
IncompleteResults: Bool(false),
CodeResults: []CodeResult{wantedCodeResult},
}
if !reflect.DeepEqual(result, want) {
t.Errorf("Search.Code returned %+v, want %+v", result, want)
}
}

View file

@ -1,141 +0,0 @@
// Copyright 2013 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.
package github
import (
"fmt"
"testing"
"time"
)
func TestStringify(t *testing.T) {
var nilPointer *string
var tests = []struct {
in interface{}
out string
}{
// basic types
{"foo", `"foo"`},
{123, `123`},
{1.5, `1.5`},
{false, `false`},
{
[]string{"a", "b"},
`["a" "b"]`,
},
{
struct {
A []string
}{nil},
// nil slice is skipped
`{}`,
},
{
struct {
A string
}{"foo"},
// structs not of a named type get no prefix
`{A:"foo"}`,
},
// pointers
{nilPointer, `<nil>`},
{String("foo"), `"foo"`},
{Int(123), `123`},
{Bool(false), `false`},
{
[]*string{String("a"), String("b")},
`["a" "b"]`,
},
// actual GitHub structs
{
Timestamp{time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)},
`github.Timestamp{2006-01-02 15:04:05 +0000 UTC}`,
},
{
&Timestamp{time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)},
`github.Timestamp{2006-01-02 15:04:05 +0000 UTC}`,
},
{
User{ID: Int64(123), Name: String("n")},
`github.User{ID:123, Name:"n"}`,
},
{
Repository{Owner: &User{ID: Int64(123)}},
`github.Repository{Owner:github.User{ID:123}}`,
},
}
for i, tt := range tests {
s := Stringify(tt.in)
if s != tt.out {
t.Errorf("%d. Stringify(%q) => %q, want %q", i, tt.in, s, tt.out)
}
}
}
// Directly test the String() methods on various GitHub types. We don't do an
// exaustive test of all the various field types, since TestStringify() above
// takes care of that. Rather, we just make sure that Stringify() is being
// used to build the strings, which we do by verifying that pointers are
// stringified as their underlying value.
func TestString(t *testing.T) {
var tests = []struct {
in interface{}
out string
}{
{CodeResult{Name: String("n")}, `github.CodeResult{Name:"n"}`},
{CommitAuthor{Name: String("n")}, `github.CommitAuthor{Name:"n"}`},
{CommitFile{SHA: String("s")}, `github.CommitFile{SHA:"s"}`},
{CommitStats{Total: Int(1)}, `github.CommitStats{Total:1}`},
{CommitsComparison{TotalCommits: Int(1)}, `github.CommitsComparison{TotalCommits:1}`},
{Commit{SHA: String("s")}, `github.Commit{SHA:"s"}`},
{Event{ID: String("1")}, `github.Event{ID:"1"}`},
{GistComment{ID: Int64(1)}, `github.GistComment{ID:1}`},
{GistFile{Size: Int(1)}, `github.GistFile{Size:1}`},
{Gist{ID: String("1")}, `github.Gist{ID:"1", Files:map[]}`},
{GitObject{SHA: String("s")}, `github.GitObject{SHA:"s"}`},
{Gitignore{Name: String("n")}, `github.Gitignore{Name:"n"}`},
{Hook{ID: Int64(1)}, `github.Hook{Config:map[], ID:1}`},
{IssueComment{ID: Int64(1)}, `github.IssueComment{ID:1}`},
{Issue{Number: Int(1)}, `github.Issue{Number:1}`},
{Key{ID: Int64(1)}, `github.Key{ID:1}`},
{Label{ID: Int64(1), Name: String("l")}, `github.Label{ID:1, Name:"l"}`},
{Organization{ID: Int64(1)}, `github.Organization{ID:1}`},
{PullRequestComment{ID: Int64(1)}, `github.PullRequestComment{ID:1}`},
{PullRequest{Number: Int(1)}, `github.PullRequest{Number:1}`},
{PullRequestReview{ID: Int64(1)}, `github.PullRequestReview{ID:1}`},
{DraftReviewComment{Position: Int(1)}, `github.DraftReviewComment{Position:1}`},
{PullRequestReviewRequest{Body: String("r")}, `github.PullRequestReviewRequest{Body:"r"}`},
{PullRequestReviewDismissalRequest{Message: String("r")}, `github.PullRequestReviewDismissalRequest{Message:"r"}`},
{PushEventCommit{SHA: String("s")}, `github.PushEventCommit{SHA:"s"}`},
{PushEvent{PushID: Int64(1)}, `github.PushEvent{PushID:1}`},
{Reference{Ref: String("r")}, `github.Reference{Ref:"r"}`},
{ReleaseAsset{ID: Int64(1)}, `github.ReleaseAsset{ID:1}`},
{RepoStatus{ID: Int64(1)}, `github.RepoStatus{ID:1}`},
{RepositoryComment{ID: Int64(1)}, `github.RepositoryComment{ID:1}`},
{RepositoryCommit{SHA: String("s")}, `github.RepositoryCommit{SHA:"s"}`},
{RepositoryContent{Name: String("n")}, `github.RepositoryContent{Name:"n"}`},
{RepositoryRelease{ID: Int64(1)}, `github.RepositoryRelease{ID:1}`},
{Repository{ID: Int64(1)}, `github.Repository{ID:1}`},
{Team{ID: Int64(1)}, `github.Team{ID:1}`},
{TreeEntry{SHA: String("s")}, `github.TreeEntry{SHA:"s"}`},
{Tree{SHA: String("s")}, `github.Tree{SHA:"s"}`},
{User{ID: Int64(1)}, `github.User{ID:1}`},
{WebHookAuthor{Name: String("n")}, `github.WebHookAuthor{Name:"n"}`},
{WebHookCommit{ID: String("1")}, `github.WebHookCommit{ID:"1"}`},
{WebHookPayload{Ref: String("r")}, `github.WebHookPayload{Ref:"r"}`},
}
for i, tt := range tests {
s := tt.in.(fmt.Stringer).String()
if s != tt.out {
t.Errorf("%d. String() => %q, want %q", i, tt.in, tt.out)
}
}
}

View file

@ -1,189 +0,0 @@
// Copyright 2013 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.
package github
import (
"encoding/json"
"fmt"
"testing"
"time"
)
const (
emptyTimeStr = `"0001-01-01T00:00:00Z"`
referenceTimeStr = `"2006-01-02T15:04:05Z"`
referenceTimeStrFractional = `"2006-01-02T15:04:05.000Z"` // This format was returned by the Projects API before October 1, 2017.
referenceUnixTimeStr = `1136214245`
)
var (
referenceTime = time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)
unixOrigin = time.Unix(0, 0).In(time.UTC)
)
func TestTimestamp_Marshal(t *testing.T) {
testCases := []struct {
desc string
data Timestamp
want string
wantErr bool
equal bool
}{
{"Reference", Timestamp{referenceTime}, referenceTimeStr, false, true},
{"Empty", Timestamp{}, emptyTimeStr, false, true},
{"Mismatch", Timestamp{}, referenceTimeStr, false, false},
}
for _, tc := range testCases {
out, err := json.Marshal(tc.data)
if gotErr := err != nil; gotErr != tc.wantErr {
t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err)
}
got := string(out)
equal := got == tc.want
if (got == tc.want) != tc.equal {
t.Errorf("%s: got=%s, want=%s, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal)
}
}
}
func TestTimestamp_Unmarshal(t *testing.T) {
testCases := []struct {
desc string
data string
want Timestamp
wantErr bool
equal bool
}{
{"Reference", referenceTimeStr, Timestamp{referenceTime}, false, true},
{"ReferenceUnix", referenceUnixTimeStr, Timestamp{referenceTime}, false, true},
{"ReferenceFractional", referenceTimeStrFractional, Timestamp{referenceTime}, false, true},
{"Empty", emptyTimeStr, Timestamp{}, false, true},
{"UnixStart", `0`, Timestamp{unixOrigin}, false, true},
{"Mismatch", referenceTimeStr, Timestamp{}, false, false},
{"MismatchUnix", `0`, Timestamp{}, false, false},
{"Invalid", `"asdf"`, Timestamp{referenceTime}, true, false},
}
for _, tc := range testCases {
var got Timestamp
err := json.Unmarshal([]byte(tc.data), &got)
if gotErr := err != nil; gotErr != tc.wantErr {
t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err)
continue
}
equal := got.Equal(tc.want)
if equal != tc.equal {
t.Errorf("%s: got=%#v, want=%#v, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal)
}
}
}
func TestTimstamp_MarshalReflexivity(t *testing.T) {
testCases := []struct {
desc string
data Timestamp
}{
{"Reference", Timestamp{referenceTime}},
{"Empty", Timestamp{}},
}
for _, tc := range testCases {
data, err := json.Marshal(tc.data)
if err != nil {
t.Errorf("%s: Marshal err=%v", tc.desc, err)
}
var got Timestamp
err = json.Unmarshal(data, &got)
if err != nil {
t.Errorf("%s: Unmarshal err=%v", tc.desc, err)
}
if !got.Equal(tc.data) {
t.Errorf("%s: %+v != %+v", tc.desc, got, data)
}
}
}
type WrappedTimestamp struct {
A int
Time Timestamp
}
func TestWrappedTimstamp_Marshal(t *testing.T) {
testCases := []struct {
desc string
data WrappedTimestamp
want string
wantErr bool
equal bool
}{
{"Reference", WrappedTimestamp{0, Timestamp{referenceTime}}, fmt.Sprintf(`{"A":0,"Time":%s}`, referenceTimeStr), false, true},
{"Empty", WrappedTimestamp{}, fmt.Sprintf(`{"A":0,"Time":%s}`, emptyTimeStr), false, true},
{"Mismatch", WrappedTimestamp{}, fmt.Sprintf(`{"A":0,"Time":%s}`, referenceTimeStr), false, false},
}
for _, tc := range testCases {
out, err := json.Marshal(tc.data)
if gotErr := err != nil; gotErr != tc.wantErr {
t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err)
}
got := string(out)
equal := got == tc.want
if equal != tc.equal {
t.Errorf("%s: got=%s, want=%s, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal)
}
}
}
func TestWrappedTimstamp_Unmarshal(t *testing.T) {
testCases := []struct {
desc string
data string
want WrappedTimestamp
wantErr bool
equal bool
}{
{"Reference", referenceTimeStr, WrappedTimestamp{0, Timestamp{referenceTime}}, false, true},
{"ReferenceUnix", referenceUnixTimeStr, WrappedTimestamp{0, Timestamp{referenceTime}}, false, true},
{"Empty", emptyTimeStr, WrappedTimestamp{0, Timestamp{}}, false, true},
{"UnixStart", `0`, WrappedTimestamp{0, Timestamp{unixOrigin}}, false, true},
{"Mismatch", referenceTimeStr, WrappedTimestamp{0, Timestamp{}}, false, false},
{"MismatchUnix", `0`, WrappedTimestamp{0, Timestamp{}}, false, false},
{"Invalid", `"asdf"`, WrappedTimestamp{0, Timestamp{referenceTime}}, true, false},
}
for _, tc := range testCases {
var got Timestamp
err := json.Unmarshal([]byte(tc.data), &got)
if gotErr := err != nil; gotErr != tc.wantErr {
t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err)
continue
}
equal := got.Time.Equal(tc.want.Time.Time)
if equal != tc.equal {
t.Errorf("%s: got=%#v, want=%#v, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal)
}
}
}
func TestWrappedTimstamp_MarshalReflexivity(t *testing.T) {
testCases := []struct {
desc string
data WrappedTimestamp
}{
{"Reference", WrappedTimestamp{0, Timestamp{referenceTime}}},
{"Empty", WrappedTimestamp{0, Timestamp{}}},
}
for _, tc := range testCases {
bytes, err := json.Marshal(tc.data)
if err != nil {
t.Errorf("%s: Marshal err=%v", tc.desc, err)
}
var got WrappedTimestamp
err = json.Unmarshal(bytes, &got)
if err != nil {
t.Errorf("%s: Unmarshal err=%v", tc.desc, err)
}
if !got.Time.Equal(tc.data.Time) {
t.Errorf("%s: %+v != %+v", tc.desc, got, tc.data)
}
}
}

View file

@ -1,72 +0,0 @@
// 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.
package github
import (
"context"
"net/http"
"testing"
)
func TestUsersService_PromoteSiteAdmin(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/site_admin", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Users.PromoteSiteAdmin(context.Background(), "u")
if err != nil {
t.Errorf("Users.PromoteSiteAdmin returned error: %v", err)
}
}
func TestUsersService_DemoteSiteAdmin(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/site_admin", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Users.DemoteSiteAdmin(context.Background(), "u")
if err != nil {
t.Errorf("Users.DemoteSiteAdmin returned error: %v", err)
}
}
func TestUsersService_Suspend(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/suspended", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Users.Suspend(context.Background(), "u")
if err != nil {
t.Errorf("Users.Suspend returned error: %v", err)
}
}
func TestUsersService_Unsuspend(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/suspended", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Users.Unsuspend(context.Background(), "u")
if err != nil {
t.Errorf("Users.Unsuspend returned error: %v", err)
}
}

View file

@ -1,90 +0,0 @@
// Copyright 2017 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestUsersService_ListBlockedUsers(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/blocks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeBlockUsersPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{
"login": "octocat"
}]`)
})
opt := &ListOptions{Page: 2}
blockedUsers, _, err := client.Users.ListBlockedUsers(context.Background(), opt)
if err != nil {
t.Errorf("Users.ListBlockedUsers returned error: %v", err)
}
want := []*User{{Login: String("octocat")}}
if !reflect.DeepEqual(blockedUsers, want) {
t.Errorf("Users.ListBlockedUsers returned %+v, want %+v", blockedUsers, want)
}
}
func TestUsersService_IsBlocked(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/blocks/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeBlockUsersPreview)
w.WriteHeader(http.StatusNoContent)
})
isBlocked, _, err := client.Users.IsBlocked(context.Background(), "u")
if err != nil {
t.Errorf("Users.IsBlocked returned error: %v", err)
}
if want := true; isBlocked != want {
t.Errorf("Users.IsBlocked returned %+v, want %+v", isBlocked, want)
}
}
func TestUsersService_BlockUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/blocks/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
testHeader(t, r, "Accept", mediaTypeBlockUsersPreview)
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Users.BlockUser(context.Background(), "u")
if err != nil {
t.Errorf("Users.BlockUser returned error: %v", err)
}
}
func TestUsersService_UnblockUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/blocks/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeBlockUsersPreview)
w.WriteHeader(http.StatusNoContent)
})
_, err := client.Users.UnblockUser(context.Background(), "u")
if err != nil {
t.Errorf("Users.UnblockUser returned error: %v", err)
}
}

View file

@ -1,95 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestUsersService_ListEmails(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{
"email": "user@example.com",
"verified": false,
"primary": true
}]`)
})
opt := &ListOptions{Page: 2}
emails, _, err := client.Users.ListEmails(context.Background(), opt)
if err != nil {
t.Errorf("Users.ListEmails returned error: %v", err)
}
want := []*UserEmail{{Email: String("user@example.com"), Verified: Bool(false), Primary: Bool(true)}}
if !reflect.DeepEqual(emails, want) {
t.Errorf("Users.ListEmails returned %+v, want %+v", emails, want)
}
}
func TestUsersService_AddEmails(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := []string{"new@example.com"}
mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) {
var v []string
json.NewDecoder(r.Body).Decode(&v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `[{"email":"old@example.com"}, {"email":"new@example.com"}]`)
})
emails, _, err := client.Users.AddEmails(context.Background(), input)
if err != nil {
t.Errorf("Users.AddEmails returned error: %v", err)
}
want := []*UserEmail{
{Email: String("old@example.com")},
{Email: String("new@example.com")},
}
if !reflect.DeepEqual(emails, want) {
t.Errorf("Users.AddEmails returned %+v, want %+v", emails, want)
}
}
func TestUsersService_DeleteEmails(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := []string{"user@example.com"}
mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) {
var v []string
json.NewDecoder(r.Body).Decode(&v)
testMethod(t, r, "DELETE")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
})
_, err := client.Users.DeleteEmails(context.Background(), input)
if err != nil {
t.Errorf("Users.DeleteEmails returned error: %v", err)
}
}

View file

@ -1,238 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestUsersService_ListFollowers_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/followers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
users, _, err := client.Users.ListFollowers(context.Background(), "", opt)
if err != nil {
t.Errorf("Users.ListFollowers returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(users, want) {
t.Errorf("Users.ListFollowers returned %+v, want %+v", users, want)
}
}
func TestUsersService_ListFollowers_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/followers", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":1}]`)
})
users, _, err := client.Users.ListFollowers(context.Background(), "u", nil)
if err != nil {
t.Errorf("Users.ListFollowers returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(users, want) {
t.Errorf("Users.ListFollowers returned %+v, want %+v", users, want)
}
}
func TestUsersService_ListFollowers_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Users.ListFollowers(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestUsersService_ListFollowing_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/following", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opts := &ListOptions{Page: 2}
users, _, err := client.Users.ListFollowing(context.Background(), "", opts)
if err != nil {
t.Errorf("Users.ListFollowing returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(users, want) {
t.Errorf("Users.ListFollowing returned %+v, want %+v", users, want)
}
}
func TestUsersService_ListFollowing_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/following", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":1}]`)
})
users, _, err := client.Users.ListFollowing(context.Background(), "u", nil)
if err != nil {
t.Errorf("Users.ListFollowing returned error: %v", err)
}
want := []*User{{ID: Int64(1)}}
if !reflect.DeepEqual(users, want) {
t.Errorf("Users.ListFollowing returned %+v, want %+v", users, want)
}
}
func TestUsersService_ListFollowing_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Users.ListFollowing(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestUsersService_IsFollowing_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/following/t", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNoContent)
})
following, _, err := client.Users.IsFollowing(context.Background(), "", "t")
if err != nil {
t.Errorf("Users.IsFollowing returned error: %v", err)
}
if want := true; following != want {
t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want)
}
}
func TestUsersService_IsFollowing_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNoContent)
})
following, _, err := client.Users.IsFollowing(context.Background(), "u", "t")
if err != nil {
t.Errorf("Users.IsFollowing returned error: %v", err)
}
if want := true; following != want {
t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want)
}
}
func TestUsersService_IsFollowing_false(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(http.StatusNotFound)
})
following, _, err := client.Users.IsFollowing(context.Background(), "u", "t")
if err != nil {
t.Errorf("Users.IsFollowing returned error: %v", err)
}
if want := false; following != want {
t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want)
}
}
func TestUsersService_IsFollowing_error(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
http.Error(w, "BadRequest", http.StatusBadRequest)
})
following, _, err := client.Users.IsFollowing(context.Background(), "u", "t")
if err == nil {
t.Errorf("Expected HTTP 400 response")
}
if want := false; following != want {
t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want)
}
}
func TestUsersService_IsFollowing_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Users.IsFollowing(context.Background(), "%", "%")
testURLParseError(t, err)
}
func TestUsersService_Follow(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/following/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PUT")
})
_, err := client.Users.Follow(context.Background(), "u")
if err != nil {
t.Errorf("Users.Follow returned error: %v", err)
}
}
func TestUsersService_Follow_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Users.Follow(context.Background(), "%")
testURLParseError(t, err)
}
func TestUsersService_Unfollow(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/following/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Users.Unfollow(context.Background(), "u")
if err != nil {
t.Errorf("Users.Follow returned error: %v", err)
}
}
func TestUsersService_Unfollow_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, err := client.Users.Unfollow(context.Background(), "%")
testURLParseError(t, err)
}

View file

@ -1,142 +0,0 @@
// 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestUsersService_ListGPGKeys_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/gpg_keys", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGitSigningPreview)
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1,"primary_key_id":2}]`)
})
opt := &ListOptions{Page: 2}
keys, _, err := client.Users.ListGPGKeys(context.Background(), "", opt)
if err != nil {
t.Errorf("Users.ListGPGKeys returned error: %v", err)
}
want := []*GPGKey{{ID: Int64(1), PrimaryKeyID: Int64(2)}}
if !reflect.DeepEqual(keys, want) {
t.Errorf("Users.ListGPGKeys = %+v, want %+v", keys, want)
}
}
func TestUsersService_ListGPGKeys_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/gpg_keys", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGitSigningPreview)
fmt.Fprint(w, `[{"id":1,"primary_key_id":2}]`)
})
keys, _, err := client.Users.ListGPGKeys(context.Background(), "u", nil)
if err != nil {
t.Errorf("Users.ListGPGKeys returned error: %v", err)
}
want := []*GPGKey{{ID: Int64(1), PrimaryKeyID: Int64(2)}}
if !reflect.DeepEqual(keys, want) {
t.Errorf("Users.ListGPGKeys = %+v, want %+v", keys, want)
}
}
func TestUsersService_ListGPGKeys_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Users.ListGPGKeys(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestUsersService_GetGPGKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/gpg_keys/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeGitSigningPreview)
fmt.Fprint(w, `{"id":1}`)
})
key, _, err := client.Users.GetGPGKey(context.Background(), 1)
if err != nil {
t.Errorf("Users.GetGPGKey returned error: %v", err)
}
want := &GPGKey{ID: Int64(1)}
if !reflect.DeepEqual(key, want) {
t.Errorf("Users.GetGPGKey = %+v, want %+v", key, want)
}
}
func TestUsersService_CreateGPGKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := `
-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: GPGTools - https://gpgtools.org
mQINBFcEd9kBEACo54TDbGhKlXKWMvJgecEUKPPcv7XdnpKdGb3LRw5MvFwT0V0f
...
=tqfb
-----END PGP PUBLIC KEY BLOCK-----`
mux.HandleFunc("/user/gpg_keys", func(w http.ResponseWriter, r *http.Request) {
var gpgKey struct {
ArmoredPublicKey *string `json:"armored_public_key,omitempty"`
}
json.NewDecoder(r.Body).Decode(&gpgKey)
testMethod(t, r, "POST")
testHeader(t, r, "Accept", mediaTypeGitSigningPreview)
if gpgKey.ArmoredPublicKey == nil || *gpgKey.ArmoredPublicKey != input {
t.Errorf("gpgKey = %+v, want %q", gpgKey, input)
}
fmt.Fprint(w, `{"id":1}`)
})
gpgKey, _, err := client.Users.CreateGPGKey(context.Background(), input)
if err != nil {
t.Errorf("Users.GetGPGKey returned error: %v", err)
}
want := &GPGKey{ID: Int64(1)}
if !reflect.DeepEqual(gpgKey, want) {
t.Errorf("Users.GetGPGKey = %+v, want %+v", gpgKey, want)
}
}
func TestUsersService_DeleteGPGKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/gpg_keys/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeGitSigningPreview)
})
_, err := client.Users.DeleteGPGKey(context.Background(), 1)
if err != nil {
t.Errorf("Users.DeleteGPGKey returned error: %v", err)
}
}

View file

@ -1,128 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestUsersService_ListKeys_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/keys", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"page": "2"})
fmt.Fprint(w, `[{"id":1}]`)
})
opt := &ListOptions{Page: 2}
keys, _, err := client.Users.ListKeys(context.Background(), "", opt)
if err != nil {
t.Errorf("Users.ListKeys returned error: %v", err)
}
want := []*Key{{ID: Int64(1)}}
if !reflect.DeepEqual(keys, want) {
t.Errorf("Users.ListKeys returned %+v, want %+v", keys, want)
}
}
func TestUsersService_ListKeys_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u/keys", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":1}]`)
})
keys, _, err := client.Users.ListKeys(context.Background(), "u", nil)
if err != nil {
t.Errorf("Users.ListKeys returned error: %v", err)
}
want := []*Key{{ID: Int64(1)}}
if !reflect.DeepEqual(keys, want) {
t.Errorf("Users.ListKeys returned %+v, want %+v", keys, want)
}
}
func TestUsersService_ListKeys_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Users.ListKeys(context.Background(), "%", nil)
testURLParseError(t, err)
}
func TestUsersService_GetKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/keys/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
key, _, err := client.Users.GetKey(context.Background(), 1)
if err != nil {
t.Errorf("Users.GetKey returned error: %v", err)
}
want := &Key{ID: Int64(1)}
if !reflect.DeepEqual(key, want) {
t.Errorf("Users.GetKey returned %+v, want %+v", key, want)
}
}
func TestUsersService_CreateKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &Key{Key: String("k"), Title: String("t")}
mux.HandleFunc("/user/keys", func(w http.ResponseWriter, r *http.Request) {
v := new(Key)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "POST")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
key, _, err := client.Users.CreateKey(context.Background(), input)
if err != nil {
t.Errorf("Users.GetKey returned error: %v", err)
}
want := &Key{ID: Int64(1)}
if !reflect.DeepEqual(key, want) {
t.Errorf("Users.GetKey returned %+v, want %+v", key, want)
}
}
func TestUsersService_DeleteKey(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/keys/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
})
_, err := client.Users.DeleteKey(context.Background(), 1)
if err != nil {
t.Errorf("Users.DeleteKey returned error: %v", err)
}
}

View file

@ -1,245 +0,0 @@
// Copyright 2013 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.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestUser_marshall(t *testing.T) {
testJSONMarshal(t, &User{}, "{}")
u := &User{
Login: String("l"),
ID: Int64(1),
URL: String("u"),
AvatarURL: String("a"),
GravatarID: String("g"),
Name: String("n"),
Company: String("c"),
Blog: String("b"),
Location: String("l"),
Email: String("e"),
Hireable: Bool(true),
PublicRepos: Int(1),
Followers: Int(1),
Following: Int(1),
CreatedAt: &Timestamp{referenceTime},
SuspendedAt: &Timestamp{referenceTime},
}
want := `{
"login": "l",
"id": 1,
"avatar_url": "a",
"gravatar_id": "g",
"name": "n",
"company": "c",
"blog": "b",
"location": "l",
"email": "e",
"hireable": true,
"public_repos": 1,
"followers": 1,
"following": 1,
"created_at": ` + referenceTimeStr + `,
"suspended_at": ` + referenceTimeStr + `,
"url": "u"
}`
testJSONMarshal(t, u, want)
}
func TestUsersService_Get_authenticatedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
user, _, err := client.Users.Get(context.Background(), "")
if err != nil {
t.Errorf("Users.Get returned error: %v", err)
}
want := &User{ID: Int64(1)}
if !reflect.DeepEqual(user, want) {
t.Errorf("Users.Get returned %+v, want %+v", user, want)
}
}
func TestUsersService_Get_specifiedUser(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users/u", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
user, _, err := client.Users.Get(context.Background(), "u")
if err != nil {
t.Errorf("Users.Get returned error: %v", err)
}
want := &User{ID: Int64(1)}
if !reflect.DeepEqual(user, want) {
t.Errorf("Users.Get returned %+v, want %+v", user, want)
}
}
func TestUsersService_Get_invalidUser(t *testing.T) {
client, _, _, teardown := setup()
defer teardown()
_, _, err := client.Users.Get(context.Background(), "%")
testURLParseError(t, err)
}
func TestUsersService_GetByID(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":1}`)
})
user, _, err := client.Users.GetByID(context.Background(), 1)
if err != nil {
t.Fatalf("Users.GetByID returned error: %v", err)
}
want := &User{ID: Int64(1)}
if !reflect.DeepEqual(user, want) {
t.Errorf("Users.GetByID returned %+v, want %+v", user, want)
}
}
func TestUsersService_Edit(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
input := &User{Name: String("n")}
mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
v := new(User)
json.NewDecoder(r.Body).Decode(v)
testMethod(t, r, "PATCH")
if !reflect.DeepEqual(v, input) {
t.Errorf("Request body = %+v, want %+v", v, input)
}
fmt.Fprint(w, `{"id":1}`)
})
user, _, err := client.Users.Edit(context.Background(), input)
if err != nil {
t.Errorf("Users.Edit returned error: %v", err)
}
want := &User{ID: Int64(1)}
if !reflect.DeepEqual(user, want) {
t.Errorf("Users.Edit returned %+v, want %+v", user, want)
}
}
func TestUsersService_ListAll(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{"since": "1", "page": "2"})
fmt.Fprint(w, `[{"id":2}]`)
})
opt := &UserListOptions{1, ListOptions{Page: 2}}
users, _, err := client.Users.ListAll(context.Background(), opt)
if err != nil {
t.Errorf("Users.Get returned error: %v", err)
}
want := []*User{{ID: Int64(2)}}
if !reflect.DeepEqual(users, want) {
t.Errorf("Users.ListAll returned %+v, want %+v", users, want)
}
}
func TestUsersService_ListInvitations(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/repository_invitations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview)
fmt.Fprintf(w, `[{"id":1}, {"id":2}]`)
})
got, _, err := client.Users.ListInvitations(context.Background(), nil)
if err != nil {
t.Errorf("Users.ListInvitations returned error: %v", err)
}
want := []*RepositoryInvitation{{ID: Int64(1)}, {ID: Int64(2)}}
if !reflect.DeepEqual(got, want) {
t.Errorf("Users.ListInvitations = %+v, want %+v", got, want)
}
}
func TestUsersService_ListInvitations_withOptions(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/repository_invitations", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
testFormValues(t, r, values{
"page": "2",
})
testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview)
fmt.Fprintf(w, `[{"id":1}, {"id":2}]`)
})
_, _, err := client.Users.ListInvitations(context.Background(), &ListOptions{Page: 2})
if err != nil {
t.Errorf("Users.ListInvitations returned error: %v", err)
}
}
func TestUsersService_AcceptInvitation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/repository_invitations/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PATCH")
testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview)
w.WriteHeader(http.StatusNoContent)
})
if _, err := client.Users.AcceptInvitation(context.Background(), 1); err != nil {
t.Errorf("Users.AcceptInvitation returned error: %v", err)
}
}
func TestUsersService_DeclineInvitation(t *testing.T) {
client, mux, _, teardown := setup()
defer teardown()
mux.HandleFunc("/user/repository_invitations/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "DELETE")
testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview)
w.WriteHeader(http.StatusNoContent)
})
if _, err := client.Users.DeclineInvitation(context.Background(), 1); err != nil {
t.Errorf("Users.DeclineInvitation returned error: %v", err)
}
}

View file

@ -1,62 +0,0 @@
go-github tests
===============
This directory contains additional test suites beyond the unit tests already in
[../github](../github). Whereas the unit tests run very quickly (since they
don't make any network calls) and are run by Travis on every commit, the tests
in this directory are only run manually.
The test packages are:
integration
-----------
This will exercise the entire go-github library (or at least as much as is
practical) against the live GitHub API. These tests will verify that the
library is properly coded against the actual behavior of the API, and will
(hopefully) fail upon any incompatible change in the API.
Because these tests are running using live data, there is a much higher
probability of false positives in test failures due to network issues, test
data having been changed, etc.
These tests send real network traffic to the GitHub API and will exhaust the
default unregistered rate limit (60 requests per hour) very quickly.
Additionally, in order to test the methods that modify data, a real OAuth token
will need to be present. While the tests will try to be well-behaved in terms
of what data they modify, it is **strongly** recommended that these tests only
be run using a dedicated test account.
Run tests using:
GITHUB_AUTH_TOKEN=XXX go test -v -tags=integration ./integration
Additionally there are a set of integration tests for the Authorizations API.
These tests require a GitHub user (username and password), and also that a
[GitHub Application](https://github.com/settings/applications/new) (with
attendant Client ID and Client Secret) be available. Then, to execute just the
Authorization tests:
GITHUB_USERNAME='<GH_USERNAME>' GITHUB_PASSWORD='<GH_PASSWORD>' GITHUB_CLIENT_ID='<CLIENT_ID>' GITHUB_CLIENT_SECRET='<CLIENT_SECRET>' go test -v -tags=integration -run=Authorizations ./integration
If some or all of these environment variables are not available, certain of the
Authorization integration tests will be skipped.
fields
------
This will identify the fields being returned by the live GitHub API that are
not currently being mapped into the relevant Go data type. Sometimes fields
are deliberately not mapped, so the results of this tool should just be taken
as a hint.
This test sends real network traffic to the GitHub API and will exhaust the
default unregistered rate limit (60 requests per hour) very quickly.
Additionally, some data is only returned for authenticated API calls. Unlike
the integration tests above, these tests only read data, so it's less
imperitive that these be run using a dedicated test account (though you still
really should).
Run the fields tool using:
GITHUB_AUTH_TOKEN=XXX go run ./fields/fields.go

View file

@ -1,148 +0,0 @@
// 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.
// This tool tests for the JSON mappings in the go-github data types. It will
// identify fields that are returned by the live GitHub API, but that are not
// currently mapped into a struct field of the relevant go-github type. This
// helps to ensure that all relevant data returned by the API is being made
// accessible, particularly new fields that are periodically (and sometimes
// quietly) added to the API over time.
//
// These tests simply aid in identifying which fields aren't being mapped; it
// is not necessarily true that every one of them should always be mapped.
// Some fields may be undocumented for a reason, either because they aren't
// actually used yet or should not be relied upon.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"reflect"
"strings"
"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
skipURLs = flag.Bool("skip_urls", false, "skip url fields")
)
func main() {
flag.Parse()
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(context.Background(), oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
))
client = github.NewClient(tc)
auth = true
}
for _, tt := range []struct {
url string
typ interface{}
}{
//{"rate_limit", &github.RateLimits{}},
{"users/octocat", &github.User{}},
{"user", &github.User{}},
{"users/willnorris/keys", &[]github.Key{}},
{"orgs/google-test", &github.Organization{}},
{"repos/google/go-github", &github.Repository{}},
{"repos/google/go-github/issues/1", &github.Issue{}},
{"/gists/9257657", &github.Gist{}},
} {
err := testType(tt.url, tt.typ)
if err != nil {
fmt.Printf("error: %v\n", err)
}
}
}
// testType fetches the JSON resource at urlStr and compares its keys to the
// struct fields of typ.
func testType(urlStr string, typ interface{}) error {
slice := reflect.Indirect(reflect.ValueOf(typ)).Kind() == reflect.Slice
req, err := client.NewRequest("GET", urlStr, nil)
if err != nil {
return err
}
// start with a json.RawMessage so we can decode multiple ways below
raw := new(json.RawMessage)
_, err = client.Do(context.Background(), req, raw)
if err != nil {
return err
}
// unmarshal directly to a map
var m1 map[string]interface{}
if slice {
var s []map[string]interface{}
err = json.Unmarshal(*raw, &s)
if err != nil {
return err
}
m1 = s[0]
} else {
err = json.Unmarshal(*raw, &m1)
if err != nil {
return err
}
}
// unmarshal to typ first, then re-marshal and unmarshal to a map
err = json.Unmarshal(*raw, typ)
if err != nil {
return err
}
var byt []byte
if slice {
// use first item in slice
v := reflect.Indirect(reflect.ValueOf(typ))
byt, err = json.Marshal(v.Index(0).Interface())
if err != nil {
return err
}
} else {
byt, err = json.Marshal(typ)
if err != nil {
return err
}
}
var m2 map[string]interface{}
err = json.Unmarshal(byt, &m2)
if err != nil {
return err
}
// now compare the two maps
for k, v := range m1 {
if *skipURLs && strings.HasSuffix(k, "_url") {
continue
}
if _, ok := m2[k]; !ok {
fmt.Printf("%v missing field for key: %v (example value: %v)\n", reflect.TypeOf(typ), k, v)
}
}
return nil
}

View file

@ -1,141 +0,0 @@
// 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 integration
import (
"context"
"testing"
"github.com/google/go-github/github"
)
const (
owner = "google"
repo = "go-github"
)
func TestActivity_Starring(t *testing.T) {
stargazers, _, err := client.Activity.ListStargazers(context.Background(), 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(context.Background(), 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(context.Background(), owner, repo)
if err != nil {
t.Fatalf("Activity.Star returned error: %v", err)
}
// check again and verify starred
star, _, err = client.Activity.IsStarred(context.Background(), 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(context.Background(), owner, repo)
if err != nil {
t.Fatalf("Activity.Unstar returned error: %v", err)
}
// check again and verify not watching
star, _, err = client.Activity.IsStarred(context.Background(), 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(context.Background(), owner, repo)
if err != nil {
t.Fatalf("Activity.DeleteRepositorySubscription returned error: %v", err)
}
// check again and verify not watching
sub, _, err := client.Activity.GetRepositorySubscription(context.Background(), 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(context.Background(), owner, repo, sub)
if err != nil {
t.Fatalf("Activity.SetRepositorySubscription returned error: %v", err)
}
// check again and verify watching
sub, _, err = client.Activity.GetRepositorySubscription(context.Background(), 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(context.Background(), 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(context.Background(), 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

@ -1,306 +0,0 @@
// 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 integration
import (
"context"
"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(context.Background(), nil)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
initialAuthCount := len(auths)
authReq := generatePersonalAuthTokenRequest()
createdAuth, resp, err := client.Authorizations.Create(context.Background(), 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(context.Background(), 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(context.Background(), *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(context.Background(), *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(context.Background(), *createdAuth.ID)
failOnError(t, err)
failIfNotStatusCode(t, resp, 204)
// Verify that we can no longer retrieve the auth
retrievedAuth, resp, err = client.Authorizations.Get(context.Background(), *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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), clientID, *resetAuth.Token)
failOnError(t, err)
failIfNotStatusCode(t, resp, 200)
// Let's revoke the token
resp, err = appAuthenticatedClient.Authorizations.Revoke(context.Background(), 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(context.Background(), 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

@ -1,11 +0,0 @@
// 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.
// Package integration 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/test#integration
// for more information.
package integration

View file

@ -1,84 +0,0 @@
// 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 integration
import (
"context"
"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(context.Background(), 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(context.Background(), 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(context.Background(), "", &github.Repository{Name: github.String(repoName), AutoInit: github.Bool(autoinit)})
if err != nil {
return nil, err
}
return repo, nil
}

View file

@ -1,42 +0,0 @@
// 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 integration
import (
"context"
"testing"
)
func TestIssueEvents(t *testing.T) {
events, _, err := client.Issues.ListRepositoryEvents(context.Background(), "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(context.Background(), "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(context.Background(), "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

@ -1,79 +0,0 @@
// 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 integration
import (
"context"
"testing"
"time"
)
func TestEmojis(t *testing.T) {
emoji, _, err := client.ListEmojis(context.Background())
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(context.Background())
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(context.Background())
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.")
}
}
func TestListServiceHooks(t *testing.T) {
hooks, _, err := client.ListServiceHooks(context.Background())
if err != nil {
t.Fatalf("ListServiceHooks returned error: %v", err)
}
if len(hooks) == 0 {
t.Fatalf("ListServiceHooks returned no hooks")
}
}

View file

@ -1,28 +0,0 @@
// 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 integration
import (
"context"
"testing"
)
func TestPullRequests_ListCommits(t *testing.T) {
commits, _, err := client.PullRequests.ListCommits(context.Background(), "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

@ -1,190 +0,0 @@
// 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 integration
import (
"context"
"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(context.Background(), "")
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(context.Background(), *repo.Owner.Login, *repo.Name, repo)
if err != nil {
t.Fatalf("Repositories.Edit() returned error: %v", err)
}
// delete the repository
_, err = client.Repositories.Delete(context.Background(), *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(context.Background(), *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(context.Background(), "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(context.Background(), "git", "git", *branches[0].Name)
if err != nil {
t.Fatalf("Repositories.GetBranch() returned error: %v", err)
}
// tags
tags, _, err := client.Repositories.ListTags(context.Background(), "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_EditBranches(t *testing.T) {
if !checkAuth("TestRepositories_EditBranches") {
return
}
// get authenticated user
me, _, err := client.Users.Get(context.Background(), "")
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(context.Background(), *repo.Owner.Login, *repo.Name, "master")
if err != nil {
t.Fatalf("Repositories.GetBranch() returned error: %v", err)
}
if *branch.Protected {
t.Fatalf("Branch %v of repo %v is already protected", "master", *repo.Name)
}
// TODO: This test fails with 422 Validation Failed [{Resource: Field: Code: Message:}].
// Someone familiar with protection requests needs to come up with
// a valid protection request that doesn't give 422 error.
protectionRequest := &github.ProtectionRequest{
RequiredStatusChecks: &github.RequiredStatusChecks{
Strict: true,
Contexts: []string{"continuous-integration"},
},
RequiredPullRequestReviews: &github.PullRequestReviewsEnforcementRequest{
DismissalRestrictionsRequest: &github.DismissalRestrictionsRequest{
Users: []string{},
Teams: []string{},
},
DismissStaleReviews: true,
},
EnforceAdmins: true,
// TODO: Only organization repositories can have users and team restrictions.
// In order to be able to test these Restrictions, need to add support
// for creating temporary organization repositories.
Restrictions: nil,
}
protection, _, err := client.Repositories.UpdateBranchProtection(context.Background(), *repo.Owner.Login, *repo.Name, "master", protectionRequest)
if err != nil {
t.Fatalf("Repositories.UpdateBranchProtection() returned error: %v", err)
}
want := &github.Protection{
RequiredStatusChecks: &github.RequiredStatusChecks{
Strict: true,
Contexts: []string{"continuous-integration"},
},
RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{
DismissalRestrictions: github.DismissalRestrictions{
Users: []*github.User{},
Teams: []*github.Team{},
},
DismissStaleReviews: true,
},
EnforceAdmins: &github.AdminEnforcement{
Enabled: true,
},
Restrictions: nil,
}
if !reflect.DeepEqual(protection, want) {
t.Errorf("Repositories.UpdateBranchProtection() returned %+v, want %+v", protection, want)
}
_, err = client.Repositories.Delete(context.Background(), *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(context.Background(), "", nil)
if err != nil {
t.Fatalf("Repositories.List('') returned error: %v", err)
}
_, _, err = client.Repositories.List(context.Background(), "google", nil)
if err != nil {
t.Fatalf("Repositories.List('google') returned error: %v", err)
}
opt := github.RepositoryListOptions{Sort: "created"}
repos, _, err := client.Repositories.List(context.Background(), "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

@ -1,244 +0,0 @@
// 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 integration
import (
"context"
"fmt"
"math/rand"
"testing"
"github.com/google/go-github/github"
)
func TestUsers_Get(t *testing.T) {
// list all users
users, _, err := client.Users.ListAll(context.Background(), 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(context.Background(), "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(context.Background(), "")
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(context.Background(), u)
if err != nil {
t.Fatalf("Users.Update returned error: %v", err)
}
// refetch user and check location value
u, _, err = client.Users.Get(context.Background(), "")
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(context.Background(), u)
if err != nil {
t.Fatalf("Users.Edit returned error: %v", err)
}
}
func TestUsers_Emails(t *testing.T) {
if !checkAuth("TestUsers_Emails") {
return
}
emails, _, err := client.Users.ListEmails(context.Background(), 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(context.Background(), []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(context.Background(), 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 address: %v", email)
}
// Remove new address
_, err = client.Users.DeleteEmails(context.Background(), []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(context.Background(), 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(context.Background(), "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(context.Background(), "", 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(context.Background(), &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(context.Background(), "", nil)
if err != nil {
t.Fatalf("Users.ListKeys('') returned error: %v", err)
}
var id int64
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(context.Background(), 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(context.Background(), 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(context.Background(), "", 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")
}
}
}