github.com/prebid/prebid-server/v2@v2.18.0/hooks/repo_test.go (about)

     1  package hooks
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"testing"
     7  
     8  	"github.com/prebid/prebid-server/v2/hooks/hookstage"
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestNewHookRepository(t *testing.T) {
    14  	id := "foobar"
    15  	testCases := map[string]struct {
    16  		isFound      bool
    17  		providedHook interface{}
    18  		expectedHook interface{}
    19  		expectedErr  error
    20  		getHookFn    func(HookRepository) (interface{}, bool)
    21  	}{
    22  		"Added hook returns": {
    23  			isFound:      true,
    24  			providedHook: hook{},
    25  			expectedHook: hook{},
    26  			expectedErr:  nil,
    27  			getHookFn: func(repo HookRepository) (interface{}, bool) {
    28  				return repo.GetEntrypointHook(id)
    29  			},
    30  		},
    31  		"Not found hook": {
    32  			isFound:      false,
    33  			providedHook: hook{},
    34  			expectedHook: nil,
    35  			expectedErr:  nil,
    36  			getHookFn: func(repo HookRepository) (interface{}, bool) {
    37  				return repo.GetRawAuctionHook(id) // ask for not implemented hook
    38  			},
    39  		},
    40  		"Fails to add type that does not implement any hook interface": {
    41  			providedHook: struct{}{},
    42  			expectedErr:  fmt.Errorf(`hook "%s" does not implement any supported hook interface`, id),
    43  		},
    44  	}
    45  
    46  	for name, test := range testCases {
    47  		t.Run(name, func(t *testing.T) {
    48  			repo, err := NewHookRepository(map[string]interface{}{id: test.providedHook})
    49  			assert.Equal(t, test.expectedErr, err)
    50  			if test.expectedErr == nil {
    51  				hook, found := test.getHookFn(repo)
    52  				assert.Equal(t, test.isFound, found)
    53  				assert.Equal(t, test.expectedHook, hook)
    54  			}
    55  		})
    56  	}
    57  }
    58  
    59  func TestAddHook_FailsToAddHookOfSameTypeAndIdTwice(t *testing.T) {
    60  	id := "foobar"
    61  	hook := hook{}
    62  	repo := hookRepository{}
    63  	expectedErr := fmt.Errorf(`hook of type "%T" with id "%s" already registered`, new(hookstage.Entrypoint), id)
    64  
    65  	err := repo.add(id, hook)
    66  	require.NoError(t, err, "failed to add hook")
    67  
    68  	err = repo.add(id, hook)
    69  	assert.Equal(t, expectedErr, err)
    70  }
    71  
    72  type hook struct{}
    73  
    74  func (h hook) HandleEntrypointHook(ctx context.Context, context hookstage.ModuleInvocationContext, payload hookstage.EntrypointPayload) (hookstage.HookResult[hookstage.EntrypointPayload], error) {
    75  	return hookstage.HookResult[hookstage.EntrypointPayload]{}, nil
    76  }