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

     1  package cmd
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/pkg/errors"
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  type mockGcpPublishEventUtilsBundle struct {
    11  	config *gcpPublishEventOptions
    12  }
    13  
    14  func (g *mockGcpPublishEventUtilsBundle) GetConfig() *gcpPublishEventOptions {
    15  	return g.config
    16  }
    17  
    18  func (g *mockGcpPublishEventUtilsBundle) GetOIDCTokenByValidation(roleID string) (string, error) {
    19  	return "testOIDCtoken123", nil
    20  }
    21  
    22  func (g *mockGcpPublishEventUtilsBundle) GetFederatedToken(projectNumber, pool, provider, token string) (string, error) {
    23  	return "testFederatedToken123", nil
    24  }
    25  
    26  func (g *mockGcpPublishEventUtilsBundle) Publish(projectNumber string, topic string, token string, key string, data []byte) error {
    27  	if topic == "goodTestCase" {
    28  		return nil
    29  	} else if topic == "badTestCase" {
    30  		return errors.New("failed to send request")
    31  	}
    32  	return nil
    33  }
    34  
    35  func TestRunGcpPublishEvent(t *testing.T) {
    36  	t.Parallel()
    37  
    38  	t.Run("happy path", func(t *testing.T) {
    39  		t.Parallel()
    40  		// init
    41  		mock := &mockGcpPublishEventUtilsBundle{
    42  			config: &gcpPublishEventOptions{
    43  				EventType:   "PipelineRunStarted",
    44  				EventSource: "unittest",
    45  				Topic:       "goodTestCase",
    46  			}}
    47  
    48  		// test
    49  		err := runGcpPublishEvent(mock)
    50  
    51  		// assert
    52  		assert.NoError(t, err)
    53  	})
    54  
    55  	t.Run("error path", func(t *testing.T) {
    56  		t.Parallel()
    57  		// init
    58  		mock := &mockGcpPublishEventUtilsBundle{
    59  			config: &gcpPublishEventOptions{
    60  				EventType:   "PipelineRunStarted",
    61  				EventSource: "unittest",
    62  				Topic:       "badTestCase",
    63  			}}
    64  
    65  		// test
    66  		err := runGcpPublishEvent(mock)
    67  
    68  		// assert
    69  		assert.EqualError(t, err, "failed to publish event: failed to send request")
    70  	})
    71  }