github.com/haya14busa/reviewdog@v0.0.0-20180723114510-ffb00ef78fd3/github_test.go (about)

     1  package reviewdog
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"net/url"
     9  	"os"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/google/go-github/github"
    14  	"github.com/kylelemons/godebug/pretty"
    15  	"golang.org/x/oauth2"
    16  )
    17  
    18  const notokenSkipTestMes = "skipping test (requires actual Personal access tokens. export REVIEWDOG_TEST_GITHUB_API_TOKEN=<GitHub Personal Access Token>)"
    19  
    20  func setupGitHubClient() *github.Client {
    21  	token := os.Getenv("REVIEWDOG_TEST_GITHUB_API_TOKEN")
    22  	if token == "" {
    23  		return nil
    24  	}
    25  	ts := oauth2.StaticTokenSource(
    26  		&oauth2.Token{AccessToken: token},
    27  	)
    28  	tc := oauth2.NewClient(oauth2.NoContext, ts)
    29  	return github.NewClient(tc)
    30  }
    31  
    32  func TestGitHubPullRequest_Post(t *testing.T) {
    33  	t.Skip("skipping test which post comments actually")
    34  	client := setupGitHubClient()
    35  	if client == nil {
    36  		t.Skip(notokenSkipTestMes)
    37  	}
    38  
    39  	// https://github.com/haya14busa/reviewdog/pull/2
    40  	owner := "haya14busa"
    41  	repo := "reviewdog"
    42  	pr := 2
    43  	sha := "cce89afa9ac5519a7f5b1734db2e3aa776b138a7"
    44  
    45  	g, err := NewGitHubPullReqest(client, owner, repo, pr, sha)
    46  	if err != nil {
    47  		t.Fatal(err)
    48  	}
    49  	comment := &Comment{
    50  		CheckResult: &CheckResult{
    51  			Path: "watchdogs.go",
    52  		},
    53  		LnumDiff: 17,
    54  		Body:     "[reviewdog] test",
    55  	}
    56  	// https://github.com/haya14busa/reviewdog/pull/2/files#diff-ed1d019a10f54464cfaeaf6a736b7d27L20
    57  	if err := g.Post(context.Background(), comment); err != nil {
    58  		t.Error(err)
    59  	}
    60  	if err := g.Flush(context.Background()); err != nil {
    61  		t.Error(err)
    62  	}
    63  }
    64  
    65  func TestGitHubPullRequest_Diff(t *testing.T) {
    66  	if testing.Short() {
    67  		t.Skip("skipping test which contains actual API requests in short mode")
    68  	}
    69  	client := setupGitHubClient()
    70  	if client == nil {
    71  		t.Skip(notokenSkipTestMes)
    72  	}
    73  
    74  	want := `diff --git a/diff.go b/diff.go
    75  index b380b67..6abc0f1 100644
    76  --- a/diff.go
    77  +++ b/diff.go
    78  @@ -4,6 +4,9 @@ import (
    79   	"os/exec"
    80   )
    81   
    82  +func TestNewExportedFunc() {
    83  +}
    84  +
    85   var _ DiffService = &DiffString{}
    86   
    87   type DiffString struct {
    88  diff --git a/reviewdog.go b/reviewdog.go
    89  index 61450f3..f63f149 100644
    90  --- a/reviewdog.go
    91  +++ b/reviewdog.go
    92  @@ -10,18 +10,18 @@ import (
    93   	"github.com/haya14busa/reviewdog/diff"
    94   )
    95   
    96  +var TestExportedVarWithoutComment = 1
    97  +
    98  +func NewReviewdog(p Parser, c CommentService, d DiffService) *Reviewdog {
    99  +	return &Reviewdog{p: p, c: c, d: d}
   100  +}
   101  +
   102   type Reviewdog struct {
   103   	p Parser
   104   	c CommentService
   105   	d DiffService
   106   }
   107   
   108  -func NewReviewdog(p Parser, c CommentService, d DiffService) *Reviewdog {
   109  -	return &Reviewdog{p: p, c: c, d: d}
   110  -}
   111  -
   112  -// CheckResult represents a checked result of static analysis tools.
   113  -// :h error-file-format
   114   type CheckResult struct {
   115   	Path    string   // file path
   116   	Lnum    int      // line number
   117  `
   118  
   119  	// https://github.com/haya14busa/reviewdog/pull/2
   120  	owner := "haya14busa"
   121  	repo := "reviewdog"
   122  	pr := 2
   123  	g, err := NewGitHubPullReqest(client, owner, repo, pr, "")
   124  	if err != nil {
   125  		t.Fatal(err)
   126  	}
   127  	b, err := g.Diff(context.Background())
   128  	if err != nil {
   129  		t.Fatal(err)
   130  	}
   131  	if got := string(b); got != want {
   132  		t.Errorf("got:\n%v\nwant:\n%v", got, want)
   133  	}
   134  }
   135  
   136  func TestGitHubPullRequest_comment(t *testing.T) {
   137  	if testing.Short() {
   138  		t.Skip("skipping test which contains actual API requests in short mode")
   139  	}
   140  	client := setupGitHubClient()
   141  	if client == nil {
   142  		t.Skip(notokenSkipTestMes)
   143  	}
   144  	// https://github.com/haya14busa/reviewdog/pull/2
   145  	owner := "haya14busa"
   146  	repo := "reviewdog"
   147  	pr := 2
   148  	g, err := NewGitHubPullReqest(client, owner, repo, pr, "")
   149  	if err != nil {
   150  		t.Fatal(err)
   151  	}
   152  	comments, err := g.comment(context.Background())
   153  	if err != nil {
   154  		t.Fatal(err)
   155  	}
   156  	for _, c := range comments {
   157  		t.Log("---")
   158  		t.Log(*c.Body)
   159  		t.Log(*c.Path)
   160  		if c.Position != nil {
   161  			t.Log(*c.Position)
   162  		}
   163  		t.Log(*c.CommitID)
   164  	}
   165  }
   166  
   167  func TestGitHubPullRequest_Post_Flush_review_api(t *testing.T) {
   168  	listCommentsAPICalled := 0
   169  	postCommentsAPICalled := 0
   170  	mux := http.NewServeMux()
   171  	mux.HandleFunc("/repos/o/r/pulls/14/comments", func(w http.ResponseWriter, r *http.Request) {
   172  		listCommentsAPICalled++
   173  		if r.Method != "GET" {
   174  			t.Errorf("unexpected access: %v %v", r.Method, r.URL)
   175  		}
   176  		switch r.URL.Query().Get("page") {
   177  		default:
   178  			cs := []*github.PullRequestComment{
   179  				{
   180  					Path:     github.String("reviewdog.go"),
   181  					Position: github.Int(1),
   182  					Body:     github.String(bodyPrefix + "\nalready commented"),
   183  				},
   184  			}
   185  			w.Header().Add("Link", `<https://api.github.com/repos/o/r/pulls/14/comments?page=2>; rel="next"`)
   186  			if err := json.NewEncoder(w).Encode(cs); err != nil {
   187  				t.Fatal(err)
   188  			}
   189  		case "2":
   190  			cs := []*github.PullRequestComment{
   191  				{
   192  					Path:     github.String("reviewdog.go"),
   193  					Position: github.Int(14),
   194  					Body:     github.String(bodyPrefix + "\nalready commented 2"),
   195  				},
   196  			}
   197  			if err := json.NewEncoder(w).Encode(cs); err != nil {
   198  				t.Fatal(err)
   199  			}
   200  		}
   201  	})
   202  	mux.HandleFunc("/repos/o/r/pulls/14/reviews", func(w http.ResponseWriter, r *http.Request) {
   203  		postCommentsAPICalled++
   204  		if r.Method != "POST" {
   205  			t.Errorf("unexpected access: %v %v", r.Method, r.URL)
   206  		}
   207  		var req github.PullRequestReviewRequest
   208  		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
   209  			t.Error(err)
   210  		}
   211  		if *req.Event != "COMMENT" {
   212  			t.Errorf("PullRequestReviewRequest.Event = %v, want COMMENT", *req.Event)
   213  		}
   214  		if req.Body != nil {
   215  			t.Errorf("PullRequestReviewRequest.Body = %v, want empty", *req.Body)
   216  		}
   217  		if *req.CommitID != "sha" {
   218  			t.Errorf("PullRequestReviewRequest.Body = %v, want empty", *req.Body)
   219  		}
   220  		want := []*github.DraftReviewComment{
   221  			{
   222  				Path:     github.String("reviewdog.go"),
   223  				Position: github.Int(14),
   224  				Body:     github.String(bodyPrefix + "\nnew comment"),
   225  			},
   226  		}
   227  		if diff := pretty.Compare(want, req.Comments); diff != "" {
   228  			t.Errorf("req.Comments diff: (-got +want)\n%s", diff)
   229  		}
   230  	})
   231  	ts := httptest.NewServer(mux)
   232  	defer ts.Close()
   233  
   234  	cli := github.NewClient(nil)
   235  	cli.BaseURL, _ = url.Parse(ts.URL + "/")
   236  	g, err := NewGitHubPullReqest(cli, "o", "r", 14, "sha")
   237  	if err != nil {
   238  		t.Fatal(err)
   239  	}
   240  	comments := []*Comment{
   241  		{
   242  			CheckResult: &CheckResult{
   243  				Path: "reviewdog.go",
   244  			},
   245  			LnumDiff: 1,
   246  			Body:     "already commented",
   247  		},
   248  		{
   249  			CheckResult: &CheckResult{
   250  				Path: "reviewdog.go",
   251  			},
   252  			LnumDiff: 14,
   253  			Body:     "already commented 2",
   254  		},
   255  		{
   256  			CheckResult: &CheckResult{
   257  				Path: "reviewdog.go",
   258  			},
   259  			LnumDiff: 14,
   260  			Body:     "new comment",
   261  		},
   262  	}
   263  	for _, c := range comments {
   264  		if err := g.Post(context.Background(), c); err != nil {
   265  			t.Error(err)
   266  		}
   267  	}
   268  	if err := g.Flush(context.Background()); err != nil {
   269  		t.Error(err)
   270  	}
   271  	if listCommentsAPICalled != 2 {
   272  		t.Errorf("GitHub List PullRequest comments API called %v times, want 2 times", listCommentsAPICalled)
   273  	}
   274  	if postCommentsAPICalled != 1 {
   275  		t.Errorf("GitHub post PullRequest comments API called %v times, want 1 times", postCommentsAPICalled)
   276  	}
   277  }
   278  
   279  func TestGitRelWorkdir(t *testing.T) {
   280  	cwd, _ := os.Getwd()
   281  	defer os.Chdir(cwd)
   282  
   283  	wd, err := gitRelWorkdir()
   284  	if err != nil {
   285  		t.Fatal(err)
   286  	}
   287  	if wd != "" {
   288  		t.Fatalf("gitRelWorkdir() = %q, want empty", wd)
   289  	}
   290  	subDir := "cmd/"
   291  	if err := os.Chdir(subDir); err != nil {
   292  		t.Fatal(err)
   293  	}
   294  	if wd, _ := gitRelWorkdir(); wd != subDir {
   295  		t.Fatalf("gitRelWorkdir() = %q, want %q", wd, subDir)
   296  	}
   297  }
   298  
   299  func TestGitHubPullReqest_workdir(t *testing.T) {
   300  	cwd, _ := os.Getwd()
   301  	defer os.Chdir(cwd)
   302  
   303  	g, err := NewGitHubPullReqest(nil, "", "", 0, "")
   304  	if err != nil {
   305  		t.Fatal(err)
   306  	}
   307  	if g.wd != "" {
   308  		t.Fatalf("g.wd = %q, want empty", g.wd)
   309  	}
   310  	ctx := context.Background()
   311  	want := "a/b/c"
   312  	g.Post(ctx, &Comment{CheckResult: &CheckResult{Path: want}})
   313  	if got := g.postComments[0].Path; got != want {
   314  		t.Errorf("wd=%q path=%q, want %q", g.wd, got, want)
   315  	}
   316  
   317  	subDir := "cmd/"
   318  	if err := os.Chdir(subDir); err != nil {
   319  		t.Fatal(err)
   320  	}
   321  	g, _ = NewGitHubPullReqest(nil, "", "", 0, "")
   322  	if g.wd != subDir {
   323  		t.Fatalf("gitRelWorkdir() = %q, want %q", g.wd, subDir)
   324  	}
   325  	path := "a/b/c"
   326  	wantPath := "cmd/" + path
   327  	g.Post(ctx, &Comment{CheckResult: &CheckResult{Path: path}})
   328  	if got := g.postComments[0].Path; got != wantPath {
   329  		t.Errorf("wd=%q path=%q, want %q", g.wd, got, wantPath)
   330  	}
   331  }
   332  
   333  func TestGitHubPullRequest_Diff_fake(t *testing.T) {
   334  	apiCalled := 0
   335  	mux := http.NewServeMux()
   336  	mux.HandleFunc("/repos/o/r/pulls/14", func(w http.ResponseWriter, r *http.Request) {
   337  		apiCalled++
   338  		if r.Method != "GET" {
   339  			t.Errorf("unexpected access: %v %v", r.Method, r.URL)
   340  		}
   341  		if accept := r.Header.Get("Accept"); !strings.Contains(accept, "diff") {
   342  			t.Errorf("Accept header doesn't contain 'diff': %v", accept)
   343  		}
   344  		w.Write([]byte("Pull Request diff"))
   345  	})
   346  	ts := httptest.NewServer(mux)
   347  	defer ts.Close()
   348  
   349  	cli := github.NewClient(nil)
   350  	cli.BaseURL, _ = url.Parse(ts.URL + "/")
   351  	g, err := NewGitHubPullReqest(cli, "o", "r", 14, "sha")
   352  	if err != nil {
   353  		t.Fatal(err)
   354  	}
   355  	if _, err := g.Diff(context.Background()); err != nil {
   356  		t.Fatal(err)
   357  	}
   358  	if apiCalled != 1 {
   359  		t.Errorf("GitHub API should be called once; called %v times", apiCalled)
   360  	}
   361  }