1// Copyright 2014 The go-github AUTHORS. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file.
5
6// +build integration
7
8package integration
9
10import (
11	"context"
12	"fmt"
13	"math/rand"
14	"net/http"
15	"os"
16
17	"github.com/google/go-github/github"
18	"golang.org/x/oauth2"
19)
20
21var (
22	client *github.Client
23
24	// auth indicates whether tests are being run with an OAuth token.
25	// Tests can use this flag to skip certain tests when run without auth.
26	auth bool
27)
28
29func init() {
30	token := os.Getenv("GITHUB_AUTH_TOKEN")
31	if token == "" {
32		print("!!! No OAuth token. Some tests won't run. !!!\n\n")
33		client = github.NewClient(nil)
34	} else {
35		tc := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(
36			&oauth2.Token{AccessToken: token},
37		))
38		client = github.NewClient(tc)
39		auth = true
40	}
41
42	// Environment variables required for Authorization integration tests
43	vars := []string{envKeyGitHubUsername, envKeyGitHubPassword, envKeyClientID, envKeyClientSecret}
44
45	for _, v := range vars {
46		value := os.Getenv(v)
47		if value == "" {
48			print("!!! " + fmt.Sprintf(msgEnvMissing, v) + " !!!\n\n")
49		}
50	}
51
52}
53
54func checkAuth(name string) bool {
55	if !auth {
56		fmt.Printf("No auth - skipping portions of %v\n", name)
57	}
58	return auth
59}
60
61func createRandomTestRepository(owner string, autoinit bool) (*github.Repository, error) {
62	// create random repo name that does not currently exist
63	var repoName string
64	for {
65		repoName = fmt.Sprintf("test-%d", rand.Int())
66		_, resp, err := client.Repositories.Get(context.Background(), owner, repoName)
67		if err != nil {
68			if resp.StatusCode == http.StatusNotFound {
69				// found a non-existent repo, perfect
70				break
71			}
72
73			return nil, err
74		}
75	}
76
77	// create the repository
78	repo, _, err := client.Repositories.Create(context.Background(), "", &github.Repository{Name: github.String(repoName), AutoInit: github.Bool(autoinit)})
79	if err != nil {
80		return nil, err
81	}
82
83	return repo, nil
84}
85