github.com/kubri/kubri@v0.5.1-0.20240317001612-bda2aaef967e/target/github/github_test.go (about)

     1  package github_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"path"
     8  	"testing"
     9  	"time"
    10  
    11  	gh "github.com/google/go-github/github"
    12  	"golang.org/x/oauth2"
    13  
    14  	"github.com/kubri/kubri/internal/test"
    15  	"github.com/kubri/kubri/target/github"
    16  )
    17  
    18  func TestGithub(t *testing.T) {
    19  	token, ok := os.LookupEnv("GITHUB_TOKEN")
    20  	if !ok {
    21  		t.Skip("Missing environment variable: GITHUB_TOKEN")
    22  	}
    23  
    24  	ctx := context.Background()
    25  	ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
    26  	client := gh.NewClient(oauth2.NewClient(ctx, ts))
    27  	user, _, err := client.Users.Get(ctx, "")
    28  	if err != nil {
    29  		t.Fatal(err)
    30  	}
    31  	owner := user.GetLogin()
    32  
    33  	tests := []struct {
    34  		name   string
    35  		branch string
    36  	}{
    37  		{"DefaultBranch", ""},
    38  		{"WithBranch", "foo"},
    39  	}
    40  
    41  	for _, tc := range tests {
    42  		t.Run(tc.name, func(t *testing.T) {
    43  			repo := fmt.Sprintf("test_%d", time.Now().UnixNano())
    44  
    45  			r, _, err := client.Repositories.Create(ctx, "", &gh.Repository{Name: &repo})
    46  			if err != nil {
    47  				t.Fatal(err)
    48  			}
    49  			t.Cleanup(func() {
    50  				_, err := client.Repositories.Delete(ctx, owner, repo)
    51  				if err != nil {
    52  					t.Fatal(err)
    53  				}
    54  			})
    55  
    56  			tgt, err := github.New(github.Config{Owner: user.GetLogin(), Repo: repo, Branch: tc.branch})
    57  			if err != nil {
    58  				t.Fatal(err)
    59  			}
    60  
    61  			branch := tc.branch
    62  			if branch == "" {
    63  				branch = r.GetDefaultBranch()
    64  			}
    65  
    66  			test.Target(t, tgt, func(asset string) string {
    67  				return "https://raw.githubusercontent.com/" + path.Join(owner, repo, branch, asset)
    68  			}, test.WithDelay(time.Second))
    69  
    70  			t.Run("Error", func(t *testing.T) {
    71  				_, err = github.New(github.Config{Owner: "owner", Repo: "repo", Branch: tc.branch})
    72  				if err == nil {
    73  					t.Fatal("should fail for invalid repo")
    74  				}
    75  			})
    76  		})
    77  	}
    78  }