mirror of
https://github.com/SAP/jenkins-library.git
synced 2025-02-19 19:44:27 +02:00
Add tests
This commit is contained in:
parent
4302066327
commit
50153f42c7
@ -3,8 +3,12 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"mime"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/SAP/jenkins-library/pkg/log"
|
||||
"github.com/google/go-github/v28/github"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
@ -12,8 +16,11 @@ import (
|
||||
)
|
||||
|
||||
type githubRepoClient interface {
|
||||
GetLatestRelease(ctx context.Context, owner string, repo string) (*github.RepositoryRelease, *github.Response, error)
|
||||
CreateRelease(ctx context.Context, owner string, repo string, release *github.RepositoryRelease) (*github.RepositoryRelease, *github.Response, error)
|
||||
DeleteReleaseAsset(ctx context.Context, owner string, repo string, id int64) (*github.Response, error)
|
||||
GetLatestRelease(ctx context.Context, owner string, repo string) (*github.RepositoryRelease, *github.Response, error)
|
||||
ListReleaseAssets(ctx context.Context, owner string, repo string, id int64, opt *github.ListOptions) ([]*github.ReleaseAsset, *github.Response, error)
|
||||
UploadReleaseAsset(ctx context.Context, owner string, repo string, id int64, opt *github.UploadOptions, file *os.File) (*github.ReleaseAsset, *github.Response, error)
|
||||
}
|
||||
|
||||
type githubIssueClient interface {
|
||||
@ -21,14 +28,14 @@ type githubIssueClient interface {
|
||||
}
|
||||
|
||||
func githubPublishRelease(myGithubPublishReleaseOptions githubPublishReleaseOptions) error {
|
||||
ctx, client, err := piperGithub.NewClient(myGithubPublishReleaseOptions.GithubToken, myGithubPublishReleaseOptions.GithubAPIURL, myGithubPublishReleaseOptions.GithubAPIURL)
|
||||
ctx, client, err := piperGithub.NewClient(myGithubPublishReleaseOptions.GithubToken, myGithubPublishReleaseOptions.GithubAPIURL, myGithubPublishReleaseOptions.GithubUploadURL)
|
||||
if err != nil {
|
||||
return err
|
||||
log.Entry().WithError(err).Fatal("Failed to get GitHub client.")
|
||||
}
|
||||
|
||||
err = runGithubPublishRelease(ctx, &myGithubPublishReleaseOptions, client.Repositories, client.Issues)
|
||||
if err != nil {
|
||||
return err
|
||||
log.Entry().WithError(err).Fatal("Failed to publish GitHub release.")
|
||||
}
|
||||
|
||||
return nil
|
||||
@ -37,21 +44,28 @@ func githubPublishRelease(myGithubPublishReleaseOptions githubPublishReleaseOpti
|
||||
func runGithubPublishRelease(ctx context.Context, myGithubPublishReleaseOptions *githubPublishReleaseOptions, ghRepoClient githubRepoClient, ghIssueClient githubIssueClient) error {
|
||||
|
||||
var publishedAt github.Timestamp
|
||||
|
||||
lastRelease, resp, err := ghRepoClient.GetLatestRelease(ctx, myGithubPublishReleaseOptions.GithubOrg, myGithubPublishReleaseOptions.GithubRepo)
|
||||
if err != nil {
|
||||
if resp.StatusCode == 404 {
|
||||
//first release
|
||||
//no previous release found -> first release
|
||||
myGithubPublishReleaseOptions.AddDeltaToLastRelease = false
|
||||
publishedAt = lastRelease.GetPublishedAt()
|
||||
log.Entry().Debug("This is the first release.")
|
||||
} else {
|
||||
return errors.Wrap(err, "Error occured when retrieving latest GitHub releass")
|
||||
return errors.Wrap(err, "Error occured when retrieving latest GitHub release.")
|
||||
}
|
||||
}
|
||||
publishedAt = lastRelease.GetPublishedAt()
|
||||
log.Entry().Debugf("Previous GitHub release published: '%v'", publishedAt)
|
||||
|
||||
if myGithubPublishReleaseOptions.UpdateAsset {
|
||||
return uploadReleaseAsset(ctx, lastRelease.GetID(), myGithubPublishReleaseOptions, ghRepoClient)
|
||||
}
|
||||
|
||||
releaseBody := ""
|
||||
|
||||
if len(myGithubPublishReleaseOptions.ReleaseBodyHeader) > 0 {
|
||||
releaseBody += myGithubPublishReleaseOptions.ReleaseBodyHeader + "<br /\n>"
|
||||
releaseBody += myGithubPublishReleaseOptions.ReleaseBodyHeader + "\n"
|
||||
}
|
||||
|
||||
if myGithubPublishReleaseOptions.AddClosedIssues {
|
||||
@ -69,20 +83,22 @@ func runGithubPublishRelease(ctx context.Context, myGithubPublishReleaseOptions
|
||||
Body: &releaseBody,
|
||||
}
|
||||
|
||||
//create release
|
||||
createdRelease, _, err := ghRepoClient.CreateRelease(ctx, myGithubPublishReleaseOptions.GithubOrg, myGithubPublishReleaseOptions.GithubRepo, &release)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "creation of release '%v' failed", release.TagName)
|
||||
return errors.Wrapf(err, "Creation of release '%v' failed", *release.TagName)
|
||||
}
|
||||
log.Entry().Infof("Release %v created on %v/%v", *createdRelease.TagName, myGithubPublishReleaseOptions.GithubOrg, myGithubPublishReleaseOptions.GithubRepo)
|
||||
|
||||
// todo switch to logging
|
||||
fmt.Printf("Release %v created on %v/%v", *createdRelease.TagName, myGithubPublishReleaseOptions.GithubOrg, myGithubPublishReleaseOptions.GithubRepo)
|
||||
if len(myGithubPublishReleaseOptions.AssetPath) > 0 {
|
||||
return uploadReleaseAsset(ctx, createdRelease.GetID(), myGithubPublishReleaseOptions, ghRepoClient)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getClosedIssuesText(ctx context.Context, publishedAt github.Timestamp, myGithubPublishReleaseOptions *githubPublishReleaseOptions, ghIssueClient githubIssueClient) string {
|
||||
closedIssuesText := ""
|
||||
|
||||
options := github.IssueListByRepoOptions{
|
||||
State: "closed",
|
||||
Direction: "asc",
|
||||
@ -93,17 +109,19 @@ func getClosedIssuesText(ctx context.Context, publishedAt github.Timestamp, myGi
|
||||
}
|
||||
ghIssues, _, err := ghIssueClient.ListByRepo(ctx, myGithubPublishReleaseOptions.GithubOrg, myGithubPublishReleaseOptions.GithubRepo, &options)
|
||||
if err != nil {
|
||||
//log error
|
||||
log.Entry().WithError(err).Error("Failed to get GitHub issues.")
|
||||
}
|
||||
|
||||
prTexts := []string{"<br />**List of closed pull-requests since last release**"}
|
||||
issueTexts := []string{"<br />**List of closed issues since last release**"}
|
||||
prTexts := []string{"\n**List of closed pull-requests since last release**"}
|
||||
issueTexts := []string{"\n**List of closed issues since last release**"}
|
||||
|
||||
for _, issue := range ghIssues {
|
||||
if issue.IsPullRequest() && !isExcluded(issue, myGithubPublishReleaseOptions.ExcludeLabels) {
|
||||
prTexts = append(prTexts, fmt.Sprintf("[#%v](%v): %v", issue.GetNumber(), issue.GetHTMLURL(), issue.GetTitle()))
|
||||
log.Entry().Debugf("Added PR #%v to release", issue.GetNumber())
|
||||
} else if !issue.IsPullRequest() && !isExcluded(issue, myGithubPublishReleaseOptions.ExcludeLabels) {
|
||||
issueTexts = append(issueTexts, fmt.Sprintf("[#%v](%v): %v", issue.GetNumber(), issue.GetHTMLURL(), issue.GetTitle()))
|
||||
log.Entry().Debugf("Added Issue #%v to release", issue.GetNumber())
|
||||
}
|
||||
}
|
||||
|
||||
@ -121,9 +139,9 @@ func getReleaseDeltaText(myGithubPublishReleaseOptions *githubPublishReleaseOpti
|
||||
releaseDeltaText := ""
|
||||
|
||||
//add delta link to previous release
|
||||
releaseDeltaText += "<br />**Changes**<br />"
|
||||
releaseDeltaText += "\n**Changes**\n"
|
||||
releaseDeltaText += fmt.Sprintf(
|
||||
"[%v...%v](%v/%v/%v/compare/%v...%v) <br />",
|
||||
"[%v...%v](%v/%v/%v/compare/%v...%v)\n",
|
||||
lastRelease.GetTagName(),
|
||||
myGithubPublishReleaseOptions.Version,
|
||||
myGithubPublishReleaseOptions.GithubServerURL,
|
||||
@ -135,6 +153,56 @@ func getReleaseDeltaText(myGithubPublishReleaseOptions *githubPublishReleaseOpti
|
||||
return releaseDeltaText
|
||||
}
|
||||
|
||||
func uploadReleaseAsset(ctx context.Context, releaseID int64, myGithubPublishReleaseOptions *githubPublishReleaseOptions, ghRepoClient githubRepoClient) error {
|
||||
|
||||
assets, _, err := ghRepoClient.ListReleaseAssets(ctx, myGithubPublishReleaseOptions.GithubOrg, myGithubPublishReleaseOptions.GithubRepo, releaseID, &github.ListOptions{})
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to get list of release assets.")
|
||||
}
|
||||
var assetID int64
|
||||
for _, a := range assets {
|
||||
if a.GetName() == filepath.Base(myGithubPublishReleaseOptions.AssetPath) {
|
||||
assetID = a.GetID()
|
||||
break
|
||||
}
|
||||
}
|
||||
if assetID != 0 {
|
||||
//asset needs to be deleted first since API does not allow for replacement
|
||||
_, err := ghRepoClient.DeleteReleaseAsset(ctx, myGithubPublishReleaseOptions.GithubOrg, myGithubPublishReleaseOptions.GithubRepo, assetID)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to delete release asset.")
|
||||
}
|
||||
}
|
||||
|
||||
mediaType := mime.TypeByExtension(filepath.Ext(myGithubPublishReleaseOptions.AssetPath))
|
||||
if mediaType == "" {
|
||||
mediaType = "application/octet-stream"
|
||||
}
|
||||
log.Entry().Debugf("Using mediaType '%v'", mediaType)
|
||||
|
||||
name := filepath.Base(myGithubPublishReleaseOptions.AssetPath)
|
||||
log.Entry().Debugf("Using file name '%v'", name)
|
||||
|
||||
opts := github.UploadOptions{
|
||||
Name: name,
|
||||
MediaType: mediaType,
|
||||
}
|
||||
file, err := os.Open(myGithubPublishReleaseOptions.AssetPath)
|
||||
defer file.Close()
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "Failed to load release asset '%v'", myGithubPublishReleaseOptions.AssetPath)
|
||||
}
|
||||
|
||||
log.Entry().Info("Starting to upload release asset.")
|
||||
asset, _, err := ghRepoClient.UploadReleaseAsset(ctx, myGithubPublishReleaseOptions.GithubOrg, myGithubPublishReleaseOptions.GithubRepo, releaseID, &opts, file)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to upload release asset.")
|
||||
}
|
||||
log.Entry().Infof("Done uploading asset '%v'.", asset.GetURL())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isExcluded(issue *github.Issue, excludeLabels []string) bool {
|
||||
//issue.Labels[0].GetName()
|
||||
for _, ex := range excludeLabels {
|
||||
|
@ -4,6 +4,7 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/SAP/jenkins-library/pkg/config"
|
||||
"github.com/SAP/jenkins-library/pkg/log"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
@ -18,9 +19,10 @@ type githubPublishReleaseOptions struct {
|
||||
GithubRepo string `json:"githubRepo,omitempty"`
|
||||
GithubServerURL string `json:"githubServerUrl,omitempty"`
|
||||
GithubToken string `json:"githubToken,omitempty"`
|
||||
GithubUploadURL string `json:"githubUploadUrl,omitempty"`
|
||||
Labels []string `json:"labels,omitempty"`
|
||||
ReleaseBodyHeader string `json:"releaseBodyHeader,omitempty"`
|
||||
Update bool `json:"update,omitempty"`
|
||||
UpdateAsset bool `json:"updateAsset,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
}
|
||||
|
||||
@ -44,6 +46,8 @@ The result looks like
|
||||
|
||||
`,
|
||||
PreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
log.SetStepName("githubPublishRelease")
|
||||
log.SetVerbose(generalConfig.verbose)
|
||||
return PrepareConfig(cmd, &metadata, "githubPublishRelease", &myGithubPublishReleaseOptions, openPiperFile)
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
@ -66,9 +70,10 @@ func addGithubPublishReleaseFlags(cmd *cobra.Command) {
|
||||
cmd.Flags().StringVar(&myGithubPublishReleaseOptions.GithubRepo, "githubRepo", os.Getenv("PIPER_githubRepo"), "Set the GitHub repository.")
|
||||
cmd.Flags().StringVar(&myGithubPublishReleaseOptions.GithubServerURL, "githubServerUrl", "https://github.com", "GitHub server url for end-user access.")
|
||||
cmd.Flags().StringVar(&myGithubPublishReleaseOptions.GithubToken, "githubToken", os.Getenv("PIPER_githubToken"), "GitHub personal access token as per https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line")
|
||||
cmd.Flags().StringVar(&myGithubPublishReleaseOptions.GithubUploadURL, "githubUploadUrl", "https://uploads.github.com", "Set the GitHub API url.")
|
||||
cmd.Flags().StringSliceVar(&myGithubPublishReleaseOptions.Labels, "labels", []string{}, "Labels to include in issue search.")
|
||||
cmd.Flags().StringVar(&myGithubPublishReleaseOptions.ReleaseBodyHeader, "releaseBodyHeader", os.Getenv("PIPER_releaseBodyHeader"), "Content which will appear for the release.")
|
||||
cmd.Flags().BoolVar(&myGithubPublishReleaseOptions.Update, "update", false, "Specify if the release should be updated in case it already exists")
|
||||
cmd.Flags().BoolVar(&myGithubPublishReleaseOptions.UpdateAsset, "updateAsset", false, "Specify if a release asset should be updated only.")
|
||||
cmd.Flags().StringVar(&myGithubPublishReleaseOptions.Version, "version", os.Getenv("PIPER_version"), "Define the version number which will be written as tag as well as release name.")
|
||||
|
||||
cmd.MarkFlagRequired("githubApiUrl")
|
||||
@ -76,6 +81,7 @@ func addGithubPublishReleaseFlags(cmd *cobra.Command) {
|
||||
cmd.MarkFlagRequired("githubRepo")
|
||||
cmd.MarkFlagRequired("githubServerUrl")
|
||||
cmd.MarkFlagRequired("githubToken")
|
||||
cmd.MarkFlagRequired("githubUploadUrl")
|
||||
cmd.MarkFlagRequired("version")
|
||||
}
|
||||
|
||||
@ -145,6 +151,12 @@ func githubPublishReleaseMetadata() config.StepData {
|
||||
Type: "string",
|
||||
Mandatory: true,
|
||||
},
|
||||
{
|
||||
Name: "githubUploadUrl",
|
||||
Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
|
||||
Type: "string",
|
||||
Mandatory: true,
|
||||
},
|
||||
{
|
||||
Name: "labels",
|
||||
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
|
||||
@ -158,7 +170,7 @@ func githubPublishReleaseMetadata() config.StepData {
|
||||
Mandatory: false,
|
||||
},
|
||||
{
|
||||
Name: "update",
|
||||
Name: "updateAsset",
|
||||
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
|
||||
Type: "bool",
|
||||
Mandatory: false,
|
||||
|
@ -1,15 +1,359 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-github/v28/github"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestRunGithubPublishRelease(t *testing.T) {
|
||||
type ghRCMock struct {
|
||||
createErr error
|
||||
latestRelease *github.RepositoryRelease
|
||||
release *github.RepositoryRelease
|
||||
delErr error
|
||||
delID int64
|
||||
delOwner string
|
||||
delRepo string
|
||||
listErr error
|
||||
listID int64
|
||||
listOwner string
|
||||
listReleaseAssets []*github.ReleaseAsset
|
||||
listRepo string
|
||||
listOpts *github.ListOptions
|
||||
latestStatusCode int
|
||||
latestErr error
|
||||
uploadID int64
|
||||
uploadOpts *github.UploadOptions
|
||||
uploadOwner string
|
||||
uploadRepo string
|
||||
}
|
||||
|
||||
func (g *ghRCMock) CreateRelease(ctx context.Context, owner string, repo string, release *github.RepositoryRelease) (*github.RepositoryRelease, *github.Response, error) {
|
||||
g.release = release
|
||||
return release, nil, g.createErr
|
||||
}
|
||||
|
||||
func (g *ghRCMock) DeleteReleaseAsset(ctx context.Context, owner string, repo string, id int64) (*github.Response, error) {
|
||||
g.delOwner = owner
|
||||
g.delRepo = repo
|
||||
g.delID = id
|
||||
return nil, g.delErr
|
||||
}
|
||||
|
||||
func (g *ghRCMock) GetLatestRelease(ctx context.Context, owner string, repo string) (*github.RepositoryRelease, *github.Response, error) {
|
||||
hc := http.Response{StatusCode: 200}
|
||||
if g.latestStatusCode != 0 {
|
||||
hc.StatusCode = g.latestStatusCode
|
||||
}
|
||||
ghResp := github.Response{Response: &hc}
|
||||
return g.latestRelease, &ghResp, g.latestErr
|
||||
}
|
||||
|
||||
func (g *ghRCMock) ListReleaseAssets(ctx context.Context, owner string, repo string, id int64, opt *github.ListOptions) ([]*github.ReleaseAsset, *github.Response, error) {
|
||||
g.listID = id
|
||||
g.listOwner = owner
|
||||
g.listRepo = repo
|
||||
g.listOpts = opt
|
||||
return g.listReleaseAssets, nil, g.listErr
|
||||
}
|
||||
|
||||
func (g *ghRCMock) UploadReleaseAsset(ctx context.Context, owner string, repo string, id int64, opt *github.UploadOptions, file *os.File) (*github.ReleaseAsset, *github.Response, error) {
|
||||
g.uploadID = id
|
||||
g.uploadOwner = owner
|
||||
g.uploadRepo = repo
|
||||
g.uploadOpts = opt
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
type ghICMock struct {
|
||||
issues []*github.Issue
|
||||
lastPublished time.Time
|
||||
owner string
|
||||
repo string
|
||||
options *github.IssueListByRepoOptions
|
||||
}
|
||||
|
||||
func (g *ghICMock) ListByRepo(ctx context.Context, owner string, repo string, opt *github.IssueListByRepoOptions) ([]*github.Issue, *github.Response, error) {
|
||||
g.owner = owner
|
||||
g.repo = repo
|
||||
g.options = opt
|
||||
g.lastPublished = opt.Since
|
||||
return g.issues, nil, nil
|
||||
}
|
||||
|
||||
func TestRunGithubPublishRelease(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("Success - first release & no body", func(t *testing.T) {
|
||||
ghIssueClient := ghICMock{}
|
||||
ghRepoClient := ghRCMock{
|
||||
latestStatusCode: 404,
|
||||
latestErr: fmt.Errorf("not found"),
|
||||
}
|
||||
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
AddDeltaToLastRelease: true,
|
||||
Commitish: "master",
|
||||
GithubOrg: "TEST",
|
||||
GithubRepo: "test",
|
||||
GithubServerURL: "https://github.com",
|
||||
ReleaseBodyHeader: "Header",
|
||||
Version: "1.0",
|
||||
}
|
||||
err := runGithubPublishRelease(ctx, &myGithubPublishReleaseOptions, &ghRepoClient, &ghIssueClient)
|
||||
assert.NoError(t, err, "Error occured but none expected.")
|
||||
|
||||
assert.Equal(t, "Header\n", ghRepoClient.release.GetBody())
|
||||
})
|
||||
|
||||
t.Run("Success - subsequent releases & with body", func(t *testing.T) {
|
||||
lastTag := "1.0"
|
||||
lastPublishedAt := github.Timestamp{Time: time.Date(2019, 01, 01, 0, 0, 0, 0, time.UTC)}
|
||||
ghRepoClient := ghRCMock{
|
||||
createErr: nil,
|
||||
latestRelease: &github.RepositoryRelease{
|
||||
TagName: &lastTag,
|
||||
PublishedAt: &lastPublishedAt,
|
||||
},
|
||||
}
|
||||
prHTMLURL := "https://github.com/TEST/test/pull/1"
|
||||
prTitle := "Pull"
|
||||
prNo := 1
|
||||
|
||||
issHTMLURL := "https://github.com/TEST/test/issues/2"
|
||||
issTitle := "Issue"
|
||||
issNo := 2
|
||||
|
||||
ghIssueClient := ghICMock{
|
||||
issues: []*github.Issue{
|
||||
{Number: &prNo, Title: &prTitle, HTMLURL: &prHTMLURL, PullRequestLinks: &github.PullRequestLinks{URL: &prHTMLURL}},
|
||||
{Number: &issNo, Title: &issTitle, HTMLURL: &issHTMLURL},
|
||||
},
|
||||
}
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
AddClosedIssues: true,
|
||||
AddDeltaToLastRelease: true,
|
||||
Commitish: "master",
|
||||
GithubOrg: "TEST",
|
||||
GithubRepo: "test",
|
||||
GithubServerURL: "https://github.com",
|
||||
ReleaseBodyHeader: "Header",
|
||||
Version: "1.1",
|
||||
}
|
||||
err := runGithubPublishRelease(ctx, &myGithubPublishReleaseOptions, &ghRepoClient, &ghIssueClient)
|
||||
|
||||
assert.NoError(t, err, "Error occured but none expected.")
|
||||
|
||||
assert.Equal(t, "Header\n\n**List of closed pull-requests since last release**\n[#1](https://github.com/TEST/test/pull/1): Pull\n\n**List of closed issues since last release**\n[#2](https://github.com/TEST/test/issues/2): Issue\n\n**Changes**\n[1.0...1.1](https://github.com/TEST/test/compare/1.0...1.1)\n", ghRepoClient.release.GetBody())
|
||||
assert.Equal(t, "1.1", ghRepoClient.release.GetName())
|
||||
assert.Equal(t, "1.1", ghRepoClient.release.GetTagName())
|
||||
assert.Equal(t, "master", ghRepoClient.release.GetTargetCommitish())
|
||||
|
||||
assert.Equal(t, lastPublishedAt.Time, ghIssueClient.lastPublished)
|
||||
})
|
||||
|
||||
t.Run("Success - update asset", func(t *testing.T) {
|
||||
var releaseID int64 = 1
|
||||
ghIssueClient := ghICMock{}
|
||||
ghRepoClient := ghRCMock{
|
||||
latestRelease: &github.RepositoryRelease{
|
||||
ID: &releaseID,
|
||||
},
|
||||
}
|
||||
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
UpdateAsset: true,
|
||||
AssetPath: filepath.Join("testdata", t.Name()+"_test.txt"),
|
||||
}
|
||||
|
||||
err := runGithubPublishRelease(ctx, &myGithubPublishReleaseOptions, &ghRepoClient, &ghIssueClient)
|
||||
|
||||
assert.NoError(t, err, "Error occured but none expected.")
|
||||
|
||||
assert.Nil(t, ghRepoClient.release)
|
||||
|
||||
assert.Equal(t, releaseID, ghRepoClient.listID)
|
||||
assert.Equal(t, releaseID, ghRepoClient.uploadID)
|
||||
})
|
||||
|
||||
t.Run("Error - get release", func(t *testing.T) {
|
||||
ghIssueClient := ghICMock{}
|
||||
ghRepoClient := ghRCMock{
|
||||
latestErr: fmt.Errorf("Latest release error"),
|
||||
}
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{}
|
||||
err := runGithubPublishRelease(ctx, &myGithubPublishReleaseOptions, &ghRepoClient, &ghIssueClient)
|
||||
|
||||
assert.Equal(t, "Error occured when retrieving latest GitHub release.: Latest release error", fmt.Sprint(err))
|
||||
})
|
||||
|
||||
t.Run("Error - create release", func(t *testing.T) {
|
||||
ghIssueClient := ghICMock{}
|
||||
ghRepoClient := ghRCMock{
|
||||
createErr: fmt.Errorf("Create release error"),
|
||||
}
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
Version: "1.0",
|
||||
}
|
||||
err := runGithubPublishRelease(ctx, &myGithubPublishReleaseOptions, &ghRepoClient, &ghIssueClient)
|
||||
|
||||
assert.Equal(t, "Creation of release '1.0' failed: Create release error", fmt.Sprint(err))
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetClosedIssuesText(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
publishedAt := github.Timestamp{Time: time.Date(2019, 01, 01, 0, 0, 0, 0, time.UTC)}
|
||||
|
||||
t.Run("No issues", func(t *testing.T) {
|
||||
ghIssueClient := ghICMock{}
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
Version: "1.0",
|
||||
}
|
||||
|
||||
res := getClosedIssuesText(ctx, publishedAt, &myGithubPublishReleaseOptions, &ghIssueClient)
|
||||
|
||||
assert.Equal(t, "", res)
|
||||
})
|
||||
|
||||
t.Run("All issues", func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
publishedAt := github.Timestamp{Time: time.Date(2019, 01, 01, 0, 0, 0, 0, time.UTC)}
|
||||
|
||||
prHTMLURL := []string{"https://github.com/TEST/test/pull/1", "https://github.com/TEST/test/pull/2"}
|
||||
prTitle := []string{"Pull1", "Pull2"}
|
||||
prNo := []int{1, 2}
|
||||
|
||||
issHTMLURL := []string{"https://github.com/TEST/test/issues/3", "https://github.com/TEST/test/issues/4"}
|
||||
issTitle := []string{"Issue3", "Issue4"}
|
||||
issNo := []int{3, 4}
|
||||
|
||||
ghIssueClient := ghICMock{
|
||||
issues: []*github.Issue{
|
||||
{Number: &prNo[0], Title: &prTitle[0], HTMLURL: &prHTMLURL[0], PullRequestLinks: &github.PullRequestLinks{URL: &prHTMLURL[0]}},
|
||||
{Number: &prNo[1], Title: &prTitle[1], HTMLURL: &prHTMLURL[1], PullRequestLinks: &github.PullRequestLinks{URL: &prHTMLURL[1]}},
|
||||
{Number: &issNo[0], Title: &issTitle[0], HTMLURL: &issHTMLURL[0]},
|
||||
{Number: &issNo[1], Title: &issTitle[1], HTMLURL: &issHTMLURL[1]},
|
||||
},
|
||||
}
|
||||
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
GithubOrg: "TEST",
|
||||
GithubRepo: "test",
|
||||
}
|
||||
|
||||
res := getClosedIssuesText(ctx, publishedAt, &myGithubPublishReleaseOptions, &ghIssueClient)
|
||||
|
||||
assert.Equal(t, "\n**List of closed pull-requests since last release**\n[#1](https://github.com/TEST/test/pull/1): Pull1\n[#2](https://github.com/TEST/test/pull/2): Pull2\n\n**List of closed issues since last release**\n[#3](https://github.com/TEST/test/issues/3): Issue3\n[#4](https://github.com/TEST/test/issues/4): Issue4\n", res)
|
||||
assert.Equal(t, "TEST", ghIssueClient.owner, "Owner not properly passed")
|
||||
assert.Equal(t, "test", ghIssueClient.repo, "Repo not properly passed")
|
||||
assert.Equal(t, "closed", ghIssueClient.options.State, "Issue state not properly passed")
|
||||
assert.Equal(t, "asc", ghIssueClient.options.Direction, "Sort direction not properly passed")
|
||||
assert.Equal(t, publishedAt.Time, ghIssueClient.options.Since, "PublishedAt not properly passed")
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestGetReleaseDeltaText(t *testing.T) {
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
GithubOrg: "TEST",
|
||||
GithubRepo: "test",
|
||||
GithubServerURL: "https://github.com",
|
||||
Version: "1.1",
|
||||
}
|
||||
lastTag := "1.0"
|
||||
lastRelease := github.RepositoryRelease{
|
||||
TagName: &lastTag,
|
||||
}
|
||||
|
||||
res := getReleaseDeltaText(&myGithubPublishReleaseOptions, &lastRelease)
|
||||
|
||||
assert.Equal(t, "\n**Changes**\n[1.0...1.1](https://github.com/TEST/test/compare/1.0...1.1)\n", res)
|
||||
}
|
||||
|
||||
func TestUploadReleaseAsset(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("Success - existing asset", func(t *testing.T) {
|
||||
var releaseID int64 = 1
|
||||
assetName := "Success_-_existing_asset_test.txt"
|
||||
var assetID int64 = 11
|
||||
ghRepoClient := ghRCMock{
|
||||
latestRelease: &github.RepositoryRelease{
|
||||
ID: &releaseID,
|
||||
},
|
||||
listReleaseAssets: []*github.ReleaseAsset{
|
||||
{Name: &assetName, ID: &assetID},
|
||||
},
|
||||
}
|
||||
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
GithubOrg: "TEST",
|
||||
GithubRepo: "test",
|
||||
AssetPath: filepath.Join("testdata", t.Name()+"_test.txt"),
|
||||
}
|
||||
|
||||
err := uploadReleaseAsset(ctx, releaseID, &myGithubPublishReleaseOptions, &ghRepoClient)
|
||||
|
||||
assert.NoError(t, err, "Error occured but none expected.")
|
||||
|
||||
assert.Equal(t, "TEST", ghRepoClient.listOwner, "Owner not properly passed - list")
|
||||
assert.Equal(t, "test", ghRepoClient.listRepo, "Repo not properly passed - list")
|
||||
assert.Equal(t, releaseID, ghRepoClient.listID, "Relase ID not properly passed - list")
|
||||
|
||||
assert.Equal(t, "TEST", ghRepoClient.delOwner, "Owner not properly passed - del")
|
||||
assert.Equal(t, "test", ghRepoClient.delRepo, "Repo not properly passed - del")
|
||||
assert.Equal(t, assetID, ghRepoClient.delID, "Relase ID not properly passed - del")
|
||||
|
||||
assert.Equal(t, "TEST", ghRepoClient.uploadOwner, "Owner not properly passed - upload")
|
||||
assert.Equal(t, "test", ghRepoClient.uploadRepo, "Repo not properly passed - upload")
|
||||
assert.Equal(t, releaseID, ghRepoClient.uploadID, "Relase ID not properly passed - upload")
|
||||
assert.Equal(t, "text/plain; charset=utf-8", ghRepoClient.uploadOpts.MediaType, "Wrong MediaType passed - upload")
|
||||
})
|
||||
|
||||
t.Run("Success - no asset", func(t *testing.T) {
|
||||
var releaseID int64 = 1
|
||||
assetName := "notFound"
|
||||
var assetID int64 = 11
|
||||
ghRepoClient := ghRCMock{
|
||||
latestRelease: &github.RepositoryRelease{
|
||||
ID: &releaseID,
|
||||
},
|
||||
listReleaseAssets: []*github.ReleaseAsset{
|
||||
{Name: &assetName, ID: &assetID},
|
||||
},
|
||||
}
|
||||
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{
|
||||
GithubOrg: "TEST",
|
||||
GithubRepo: "test",
|
||||
AssetPath: filepath.Join("testdata", t.Name()+"_test.txt"),
|
||||
}
|
||||
|
||||
err := uploadReleaseAsset(ctx, releaseID, &myGithubPublishReleaseOptions, &ghRepoClient)
|
||||
|
||||
assert.NoError(t, err, "Error occured but none expected.")
|
||||
|
||||
assert.Equal(t, int64(0), ghRepoClient.delID, "Relase ID should not be populated")
|
||||
})
|
||||
|
||||
t.Run("Error - List Assets", func(t *testing.T) {
|
||||
var releaseID int64 = 1
|
||||
ghRepoClient := ghRCMock{
|
||||
listErr: fmt.Errorf("List Asset Error"),
|
||||
}
|
||||
myGithubPublishReleaseOptions := githubPublishReleaseOptions{}
|
||||
|
||||
err := uploadReleaseAsset(ctx, releaseID, &myGithubPublishReleaseOptions, &ghRepoClient)
|
||||
assert.Equal(t, "Failed to get list of release assets.: List Asset Error", fmt.Sprint(err), "Wrong error received")
|
||||
})
|
||||
}
|
||||
|
||||
func TestIsExcluded(t *testing.T) {
|
||||
|
1
cmd/testdata/TestRunGithubPublishRelease/Success_-_update_asset_test.txt
vendored
Normal file
1
cmd/testdata/TestRunGithubPublishRelease/Success_-_update_asset_test.txt
vendored
Normal file
@ -0,0 +1 @@
|
||||
TEST
|
1
cmd/testdata/TestUploadReleaseAsset/Success_-_existing_asset_test.txt
vendored
Normal file
1
cmd/testdata/TestUploadReleaseAsset/Success_-_existing_asset_test.txt
vendored
Normal file
@ -0,0 +1 @@
|
||||
TEST
|
1
cmd/testdata/TestUploadReleaseAsset/Success_-_no_asset_test.txt
vendored
Normal file
1
cmd/testdata/TestUploadReleaseAsset/Success_-_no_asset_test.txt
vendored
Normal file
@ -0,0 +1 @@
|
||||
TEST
|
@ -1,8 +1,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
//"os"
|
||||
|
||||
"github.com/SAP/jenkins-library/pkg/config"
|
||||
"github.com/SAP/jenkins-library/pkg/log"
|
||||
"github.com/spf13/cobra"
|
||||
|
@ -1,11 +1,11 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"os"
|
||||
"bytes"
|
||||
"io"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVersion(t *testing.T) {
|
||||
@ -17,7 +17,6 @@ func TestVersion(t *testing.T) {
|
||||
assert.Contains(t, result, "tag: \"<n/a>\"")
|
||||
})
|
||||
|
||||
|
||||
t.Run("versionAndTagSet", func(t *testing.T) {
|
||||
|
||||
result := runVersionCommand(t, "16bafe", "v1.2.3")
|
||||
@ -29,9 +28,9 @@ func TestVersion(t *testing.T) {
|
||||
func runVersionCommand(t *testing.T, commitID, tag string) string {
|
||||
|
||||
orig := os.Stdout
|
||||
defer func() {os.Stdout = orig}()
|
||||
defer func() { os.Stdout = orig }()
|
||||
|
||||
r,w,e := os.Pipe()
|
||||
r, w, e := os.Pipe()
|
||||
if e != nil {
|
||||
t.Error("Cannot setup pipes.")
|
||||
}
|
||||
@ -41,8 +40,12 @@ func runVersionCommand(t *testing.T, commitID, tag string) string {
|
||||
//
|
||||
// needs to be set in the free wild by the build process:
|
||||
// go build -ldflags "-X github.com/SAP/jenkins-library/cmd.GitCommit=${GIT_COMMIT} -X github.com/SAP/jenkins-library/cmd.GitTag=${GIT_TAG}"
|
||||
if len(commitID) > 0 { GitCommit = commitID; }
|
||||
if len(tag) > 0 { GitTag = tag }
|
||||
if len(commitID) > 0 {
|
||||
GitCommit = commitID
|
||||
}
|
||||
if len(tag) > 0 {
|
||||
GitTag = tag
|
||||
}
|
||||
defer func() { GitCommit = ""; GitTag = "" }()
|
||||
//
|
||||
//
|
||||
@ -58,4 +61,4 @@ func runVersionCommand(t *testing.T, commitID, tag string) string {
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, r)
|
||||
return buf.String()
|
||||
}
|
||||
}
|
||||
|
@ -101,6 +101,16 @@ spec:
|
||||
- STEPS
|
||||
type: string
|
||||
mandatory: true
|
||||
- name: githubUploadUrl
|
||||
description: Set the GitHub API url.
|
||||
scope:
|
||||
- GENERAL
|
||||
- PARAMETERS
|
||||
- STAGES
|
||||
- STEPS
|
||||
type: string
|
||||
default: https://uploads.github.com
|
||||
mandatory: true
|
||||
- name: labels
|
||||
description: 'Labels to include in issue search.'
|
||||
scope:
|
||||
@ -115,8 +125,8 @@ spec:
|
||||
- STAGES
|
||||
- STEPS
|
||||
type: string
|
||||
- name: update
|
||||
description: Specify if the release should be updated in case it already exists
|
||||
- name: updateAsset
|
||||
description: Specify if a release asset should be updated only.
|
||||
scope:
|
||||
- PARAMETERS
|
||||
- STAGES
|
||||
|
Loading…
x
Reference in New Issue
Block a user