github.com/google/go-github/v66@v66.0.0/test/integration/github_test.go (about)

     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  //go:build integration
     7  // +build integration
     8  
     9  package integration
    10  
    11  import (
    12  	"context"
    13  	"fmt"
    14  	"math/rand"
    15  	"net/http"
    16  	"os"
    17  
    18  	"github.com/google/go-github/v66/github"
    19  )
    20  
    21  var (
    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  
    29  func 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  		client = github.NewClient(nil).WithAuthToken(token)
    36  		auth = true
    37  	}
    38  }
    39  
    40  func checkAuth(name string) bool {
    41  	if !auth {
    42  		fmt.Printf("No auth - skipping portions of %v\n", name)
    43  	}
    44  	return auth
    45  }
    46  
    47  func createRandomTestRepository(owner string, autoinit bool) (*github.Repository, error) {
    48  	// determine the owner to use if one wasn't specified
    49  	if owner == "" {
    50  		owner = os.Getenv("GITHUB_OWNER")
    51  		if owner == "" {
    52  			me, _, err := client.Users.Get(context.Background(), "")
    53  			if err != nil {
    54  				return nil, err
    55  			}
    56  			owner = *me.Login
    57  		}
    58  	}
    59  
    60  	// create random repo name that does not currently exist
    61  	var repoName string
    62  	for {
    63  		repoName = fmt.Sprintf("test-%d", rand.Int())
    64  		_, resp, err := client.Repositories.Get(context.Background(), owner, repoName)
    65  		if err != nil {
    66  			if resp.StatusCode == http.StatusNotFound {
    67  				// found a non-existent repo, perfect
    68  				break
    69  			}
    70  
    71  			return nil, err
    72  		}
    73  	}
    74  
    75  	// create the repository
    76  	repo, _, err := client.Repositories.Create(
    77  		context.Background(),
    78  		owner,
    79  		&github.Repository{
    80  			Name:     github.String(repoName),
    81  			AutoInit: github.Bool(autoinit),
    82  		},
    83  	)
    84  	if err != nil {
    85  		return nil, err
    86  	}
    87  
    88  	return repo, nil
    89  }