github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/tenant/tenant_test.go (about)

     1  /*
     2   * Copyright 2020 The Compass Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package tenant_test
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"testing"
    23  
    24  	"github.com/kyma-incubator/compass/components/director/pkg/tenant"
    25  	"github.com/stretchr/testify/assert"
    26  	"github.com/stretchr/testify/require"
    27  )
    28  
    29  func TestLoadFromContext(t *testing.T) {
    30  	value := "foo"
    31  
    32  	testCases := []struct {
    33  		Name    string
    34  		Context context.Context
    35  
    36  		ExpectedResult     string
    37  		ExpectedErrMessage string
    38  	}{
    39  		{
    40  			Name:               "Success",
    41  			Context:            context.WithValue(context.TODO(), tenant.ContextKey, value),
    42  			ExpectedResult:     value,
    43  			ExpectedErrMessage: "",
    44  		},
    45  		{
    46  			Name:               "Error empty tenant value",
    47  			Context:            context.WithValue(context.TODO(), tenant.ContextKey, ""),
    48  			ExpectedResult:     "",
    49  			ExpectedErrMessage: "Tenant is required",
    50  		},
    51  		{
    52  			Name:               "Error missing tenant",
    53  			Context:            context.TODO(),
    54  			ExpectedResult:     "",
    55  			ExpectedErrMessage: "cannot read tenant from context",
    56  		},
    57  	}
    58  
    59  	for i, testCase := range testCases {
    60  		t.Run(fmt.Sprintf("%d: %s", i, testCase.Name), func(t *testing.T) {
    61  			// when
    62  			result, err := tenant.LoadFromContext(testCase.Context)
    63  
    64  			// then
    65  			if testCase.ExpectedErrMessage != "" {
    66  				require.Equal(t, testCase.ExpectedErrMessage, err.Error())
    67  				return
    68  			}
    69  
    70  			assert.Equal(t, testCase.ExpectedResult, result)
    71  		})
    72  	}
    73  }
    74  
    75  func TestSaveToLoadFromContext(t *testing.T) {
    76  	// given
    77  	value := "foo"
    78  
    79  	// when
    80  	result := tenant.SaveToContext(context.TODO(), value)
    81  
    82  	// then
    83  	assert.Equal(t, value, result.Value(tenant.ContextKey))
    84  }