github.com/abdfnx/gh-api@v0.0.0-20210414084727-f5432eec23b8/pkg/cmd/run/download/http_test.go (about) 1 package download 2 3 import ( 4 "net/http" 5 "os" 6 "path/filepath" 7 "sort" 8 "strings" 9 "testing" 10 11 "github.com/abdfnx/gh-api/internal/ghrepo" 12 "github.com/abdfnx/gh-api/pkg/httpmock" 13 "github.com/stretchr/testify/assert" 14 "github.com/stretchr/testify/require" 15 ) 16 17 func Test_List(t *testing.T) { 18 reg := &httpmock.Registry{} 19 defer reg.Verify(t) 20 21 reg.Register( 22 httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/123/artifacts"), 23 httpmock.StringResponse(`{ 24 "total_count": 2, 25 "artifacts": [ 26 {"name": "artifact-1"}, 27 {"name": "artifact-2"} 28 ] 29 }`)) 30 31 api := &apiPlatform{ 32 client: &http.Client{Transport: reg}, 33 repo: ghrepo.New("OWNER", "REPO"), 34 } 35 artifacts, err := api.List("123") 36 require.NoError(t, err) 37 38 require.Equal(t, 2, len(artifacts)) 39 assert.Equal(t, "artifact-1", artifacts[0].Name) 40 assert.Equal(t, "artifact-2", artifacts[1].Name) 41 } 42 43 func Test_List_perRepository(t *testing.T) { 44 reg := &httpmock.Registry{} 45 defer reg.Verify(t) 46 47 reg.Register( 48 httpmock.REST("GET", "repos/OWNER/REPO/actions/artifacts"), 49 httpmock.StringResponse(`{}`)) 50 51 api := &apiPlatform{ 52 client: &http.Client{Transport: reg}, 53 repo: ghrepo.New("OWNER", "REPO"), 54 } 55 _, err := api.List("") 56 require.NoError(t, err) 57 } 58 59 func Test_Download(t *testing.T) { 60 tmpDir := t.TempDir() 61 destDir := filepath.Join(tmpDir, "artifact") 62 63 reg := &httpmock.Registry{} 64 defer reg.Verify(t) 65 66 reg.Register( 67 httpmock.REST("GET", "repos/OWNER/REPO/actions/artifacts/12345/zip"), 68 httpmock.FileResponse("./fixtures/myproject.zip")) 69 70 api := &apiPlatform{ 71 client: &http.Client{Transport: reg}, 72 } 73 err := api.Download("https://api.github.com/repos/OWNER/REPO/actions/artifacts/12345/zip", destDir) 74 require.NoError(t, err) 75 76 var paths []string 77 parentPrefix := tmpDir + string(filepath.Separator) 78 err = filepath.Walk(tmpDir, func(p string, info os.FileInfo, err error) error { 79 if err != nil { 80 return err 81 } 82 if p == tmpDir { 83 return nil 84 } 85 entry := strings.TrimPrefix(p, parentPrefix) 86 if info.IsDir() { 87 entry += "/" 88 } else if info.Mode()&0111 != 0 { 89 entry += "(X)" 90 } 91 paths = append(paths, entry) 92 return nil 93 }) 94 require.NoError(t, err) 95 96 sort.Strings(paths) 97 assert.Equal(t, []string{ 98 "artifact/", 99 filepath.Join("artifact", "bin") + "/", 100 filepath.Join("artifact", "bin", "myexe"), 101 filepath.Join("artifact", "readme.md"), 102 filepath.Join("artifact", "src") + "/", 103 filepath.Join("artifact", "src", "main.go"), 104 filepath.Join("artifact", "src", "util.go"), 105 }, paths) 106 }