github.com/jaylevin/jenkins-library@v1.230.4/cmd/transportRequestReqIDFromGit_test.go (about)

     1  package cmd
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"github.com/stretchr/testify/assert"
     7  	"strings"
     8  	"testing"
     9  )
    10  
    11  type transportRequestUtilsMock struct {
    12  	err  error
    13  	trID string
    14  	cdID string
    15  }
    16  
    17  func (m *transportRequestUtilsMock) FindIDInRange(label, from, to string) (string, error) {
    18  	if m.err != nil {
    19  		return "", m.err
    20  	}
    21  	if strings.HasPrefix(label, "TransportRequest") {
    22  		return m.trID, nil
    23  	}
    24  	if strings.HasPrefix(label, "ChangeDocument") {
    25  		return m.cdID, nil
    26  	}
    27  
    28  	return "invalid", fmt.Errorf("invalid label passed: %s", label)
    29  }
    30  
    31  func TestTrGitGetTransportRequestID(t *testing.T) {
    32  	t.Parallel()
    33  
    34  	t.Run("good", func(t *testing.T) {
    35  		t.Parallel()
    36  
    37  		t.Run("getTransportRequestID", func(t *testing.T) {
    38  			configMock := newTrIDConfigMock()
    39  
    40  			id, err := getTransportRequestID(configMock.config, &transportRequestUtilsMock{trID: "43218765"})
    41  
    42  			if assert.NoError(t, err) {
    43  				assert.Equal(t, id, "43218765")
    44  			}
    45  		})
    46  		t.Run("runTransportRequestDocIDFromGit", func(t *testing.T) {
    47  			configMock := newTrIDConfigMock()
    48  			cpe := &transportRequestReqIDFromGitCommonPipelineEnvironment{}
    49  
    50  			err := runTransportRequestReqIDFromGit(configMock.config, nil, &transportRequestUtilsMock{trID: "43218765"}, cpe)
    51  
    52  			if assert.NoError(t, err) {
    53  				assert.Equal(t, cpe.custom.transportRequestID, "43218765")
    54  			}
    55  		})
    56  	})
    57  	t.Run("bad", func(t *testing.T) {
    58  		t.Parallel()
    59  
    60  		t.Run("runTransportRequestDocIDFromGit", func(t *testing.T) {
    61  			configMock := newTrIDConfigMock()
    62  			cpe := &transportRequestReqIDFromGitCommonPipelineEnvironment{}
    63  
    64  			err := runTransportRequestReqIDFromGit(configMock.config, nil, &transportRequestUtilsMock{err: errors.New("fail")}, cpe)
    65  
    66  			assert.EqualError(t, err, "fail")
    67  		})
    68  
    69  	})
    70  }
    71  
    72  type trIDConfigMock struct {
    73  	config *transportRequestReqIDFromGitOptions
    74  }
    75  
    76  func newTrIDConfigMock() *trIDConfigMock {
    77  	return &trIDConfigMock{
    78  		config: &transportRequestReqIDFromGitOptions{
    79  			GitFrom:               "origin/master",
    80  			GitTo:                 "HEAD",
    81  			TransportRequestLabel: "TransportRequest",
    82  		},
    83  	}
    84  }