github.com/SAP/jenkins-library@v1.362.0/cmd/githubCommentIssue_test.go (about)

     1  //go:build unit
     2  // +build unit
     3  
     4  package cmd
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"net/http"
    10  	"testing"
    11  
    12  	"github.com/google/go-github/v45/github"
    13  	"github.com/stretchr/testify/assert"
    14  )
    15  
    16  type ghIssueCommentMock struct {
    17  	issueComment *github.IssueComment
    18  	issueID      int64
    19  	issueError   error
    20  	owner        string
    21  	repo         string
    22  	number       int
    23  }
    24  
    25  func (g *ghIssueCommentMock) CreateComment(ctx context.Context, owner string, repo string, number int, comment *github.IssueComment) (*github.IssueComment, *github.Response, error) {
    26  	g.issueComment = comment
    27  	g.owner = owner
    28  	g.repo = repo
    29  	g.number = number
    30  
    31  	issueComment := github.IssueComment{ID: &g.issueID, Body: comment.Body}
    32  
    33  	ghRes := github.Response{Response: &http.Response{Status: "200"}}
    34  	if g.issueError != nil {
    35  		ghRes.Status = "401"
    36  	}
    37  
    38  	return &issueComment, &ghRes, g.issueError
    39  }
    40  
    41  func TestRunGithubCommentIssue(t *testing.T) {
    42  	ctx := context.Background()
    43  	t.Parallel()
    44  
    45  	t.Run("Success", func(t *testing.T) {
    46  		// init
    47  		ghIssueCommentService := ghIssueCommentMock{
    48  			issueID: 1,
    49  		}
    50  		config := githubCommentIssueOptions{
    51  			Owner:      "TEST",
    52  			Repository: "test",
    53  			Body:       "This is my test body",
    54  			Number:     1,
    55  		}
    56  
    57  		// test
    58  		err := runGithubCommentIssue(ctx, &config, nil, &ghIssueCommentService)
    59  
    60  		// assert
    61  		assert.NoError(t, err)
    62  		assert.Equal(t, config.Owner, ghIssueCommentService.owner)
    63  		assert.Equal(t, config.Repository, ghIssueCommentService.repo)
    64  		assert.Equal(t, config.Body, ghIssueCommentService.issueComment.GetBody())
    65  		assert.Equal(t, config.Number, ghIssueCommentService.number)
    66  	})
    67  
    68  	t.Run("Error", func(t *testing.T) {
    69  		// init
    70  		ghIssueCommentService := ghIssueCommentMock{
    71  			issueError: fmt.Errorf("error creating comment"),
    72  		}
    73  		config := githubCommentIssueOptions{
    74  			Number: 1,
    75  		}
    76  
    77  		// test
    78  		err := runGithubCommentIssue(ctx, &config, nil, &ghIssueCommentService)
    79  
    80  		// assert
    81  		assert.EqualError(t, err, "Error occurred when creating comment on issue 1: error creating comment")
    82  	})
    83  }