...

Source file src/github.com/okta/okta-sdk-golang/v2/tests/unit/cache_test.go

Documentation: github.com/okta/okta-sdk-golang/v2/tests/unit

     1  /*
     2   * Copyright 2018 - Present Okta, Inc.
     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 unit
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io"
    23  	"io/ioutil"
    24  	"net/http"
    25  	"net/http/httptest"
    26  	"testing"
    27  
    28  	"github.com/jarcoal/httpmock"
    29  	"github.com/okta/okta-sdk-golang/v2/okta"
    30  	"github.com/okta/okta-sdk-golang/v2/okta/cache"
    31  	"github.com/okta/okta-sdk-golang/v2/okta/query"
    32  	"github.com/okta/okta-sdk-golang/v2/tests"
    33  
    34  	"github.com/stretchr/testify/assert"
    35  	"github.com/stretchr/testify/require"
    36  )
    37  
    38  func Test_cache_key_can_be_created_from_request_object(t *testing.T) {
    39  	var buff io.ReadWriter
    40  	request, _ := http.NewRequest("GET", "https://example.com/sample/cache-key/test+test@test."+
    41  		"com?with=a&query=string",
    42  		buff)
    43  
    44  	cacheKey := cache.CreateCacheKey(request)
    45  
    46  	assert.Equal(t, "https://example.com/sample/cache-key/test+test@test.com?with=a&query=string", cacheKey,
    47  		"The cache key was not created correctly.")
    48  }
    49  
    50  func Test_an_item_can_be_stored_in_cache(t *testing.T) {
    51  	var buff io.ReadWriter
    52  	url := "https://example.com/sample/cache-key/"
    53  	request, _ := http.NewRequest("GET", url, buff)
    54  
    55  	cacheKey := cache.CreateCacheKey(request)
    56  
    57  	myCache := cache.NewGoCache(30, 30)
    58  
    59  	found := myCache.Has(cacheKey)
    60  	assert.False(t, found, "item already existed in cache")
    61  
    62  	toCache := "test Item"
    63  	record := httptest.NewRecorder()
    64  	record.WriteString(toCache)
    65  	result := record.Result()
    66  
    67  	myCache.Set(cacheKey, result)
    68  
    69  	found = myCache.Has(cacheKey)
    70  	assert.True(t, found, "item does not exist in cache")
    71  
    72  	pulledFromCache := myCache.Get(cacheKey)
    73  
    74  	assert.NotEqual(t, result, pulledFromCache, "Item pulled from cache was not a copy")
    75  	cachedBody, _ := ioutil.ReadAll(pulledFromCache.Body)
    76  	assert.Equal(t, toCache, string(cachedBody), "Item pulled from cache was not correct")
    77  }
    78  
    79  func Test_an_item_can_be_deleted_from_cache(t *testing.T) {
    80  	var buff io.ReadWriter
    81  	url := "https://example.com/sample/cache-key/delete"
    82  	request, _ := http.NewRequest("GET", url, buff)
    83  
    84  	cacheKey := cache.CreateCacheKey(request)
    85  
    86  	myCache := cache.NewGoCache(30, 30)
    87  
    88  	record := httptest.NewRecorder()
    89  	record.WriteString("test Item")
    90  	result := record.Result()
    91  
    92  	myCache.Set(cacheKey, result)
    93  
    94  	found := myCache.Has(cacheKey)
    95  	assert.True(t, found, "item does not exist in cache")
    96  
    97  	myCache.Delete(cacheKey)
    98  
    99  	found = myCache.Has(cacheKey)
   100  	assert.False(t, found, "item was not deleted from cache")
   101  }
   102  
   103  func Test_cache_can_be_cleared(t *testing.T) {
   104  	var buff io.ReadWriter
   105  	url := "https://example.com/sample/cache-key/clear"
   106  	request, _ := http.NewRequest("GET", url, buff)
   107  
   108  	cacheKey := cache.CreateCacheKey(request)
   109  
   110  	myCache := cache.NewGoCache(30, 30)
   111  
   112  	record := httptest.NewRecorder()
   113  	record.WriteString("test Item")
   114  	result := record.Result()
   115  
   116  	myCache.Set(cacheKey, result)
   117  
   118  	found := myCache.Has(cacheKey)
   119  	assert.True(t, found, "item does not exist in cache")
   120  
   121  	myCache.Clear()
   122  
   123  	found = myCache.Has(cacheKey)
   124  	assert.False(t, found, "cache was not cleared")
   125  }
   126  
   127  // TestOAuthTokensAlwaysCached demonstrates oauth tokens are always cached even
   128  // when the client has request caching disabled.
   129  func TestOAuthTokensAlwaysCached(t *testing.T) {
   130  	httpmock.Activate()
   131  	defer httpmock.DeactivateAndReset()
   132  
   133  	ctx, client, err := tests.NewClient(context.TODO(),
   134  		okta.WithCache(false),
   135  		okta.WithOrgUrl("https://testing.oktapreview.com"),
   136  		okta.WithAuthorizationMode("PrivateKey"),
   137  		okta.WithClientId("abc"),
   138  		okta.WithPrivateKey(`
   139  -----BEGIN RSA PRIVATE KEY-----
   140  MIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf9Cnzj4p4WGeKLs1Pt8Qu
   141  KUpRKfFLfRYC9AIKjbJTWit+CqvjWYzvQwECAwEAAQJAIJLixBy2qpFoS4DSmoEm
   142  o3qGy0t6z09AIJtH+5OeRV1be+N4cDYJKffGzDa88vQENZiRm0GRq6a+HPGQMd2k
   143  TQIhAKMSvzIBnni7ot/OSie2TmJLY4SwTQAevXysE2RbFDYdAiEBCUEaRQnMnbp7
   144  9mxDXDf6AU0cN/RPBjb9qSHDcWZHGzUCIG2Es59z8ugGrDY+pxLQnwfotadxd+Uy
   145  v/Ow5T0q5gIJAiEAyS4RaI9YG8EWx/2w0T67ZUVAw8eOMB6BIUg0Xcu+3okCIBOs
   146  /5OiPgoTdSy7bcF9IGpSE8ZgGKzgYQVZeN97YE00
   147  -----END RSA PRIVATE KEY-----
   148  		`),
   149  		okta.WithScopes(([]string{"okta.apps.read"})))
   150  	require.NoError(t, err)
   151  
   152  	accessToken := okta.RequestAccessToken{
   153  		TokenType:   "Bearer",
   154  		ExpiresIn:   3600,
   155  		AccessToken: "xyz",
   156  		Scope:       "okta.apps.read",
   157  	}
   158  	httpmockTokenURLRegex := `=~^https://testing\.oktapreview\.com/oauth2/v1/token\?client_assertion=.*\z`
   159  	jsonResp, err := httpmock.NewJsonResponder(200, accessToken)
   160  	require.NoError(t, err)
   161  	httpmock.RegisterResponder("POST", httpmockTokenURLRegex, jsonResp)
   162  
   163  	adminConsole := []okta.Application{{
   164  		Id:     "abc123",
   165  		Name:   "saasure",
   166  		Label:  "Okta Admin Console",
   167  		Status: "ACTIVE",
   168  	}}
   169  	jsonResp, err = httpmock.NewJsonResponder(200, adminConsole)
   170  	require.NoError(t, err)
   171  	httpmockAdminConsoleRegex := `=~^https://testing\.oktapreview\.com/api/v1/apps?.*q\=Okta\+Admin\+Console.*\z`
   172  	httpmock.RegisterResponder("GET", httpmockAdminConsoleRegex, jsonResp)
   173  
   174  	dashboard := []okta.Application{{
   175  		Id:     "def456",
   176  		Name:   "okta_enduser",
   177  		Label:  "Okta Dashboard",
   178  		Status: "ACTIVE",
   179  	}}
   180  	jsonResp, err = httpmock.NewJsonResponder(200, dashboard)
   181  	require.NoError(t, err)
   182  	httpmockDashboardRegex := `=~^https://testing\.oktapreview\.com/api/v1/apps?.*q\=Okta\+Dashboard.*\z`
   183  	httpmock.RegisterResponder("GET", httpmockDashboardRegex, jsonResp)
   184  
   185  	_, _, err = client.Application.ListApplications(ctx, &query.Params{Limit: 1, Filter: "status eq ACTIVE", Q: "Okta Admin Console"})
   186  	require.NoError(t, err)
   187  	_, _, err = client.Application.ListApplications(ctx, &query.Params{Limit: 1, Filter: "status eq ACTIVE", Q: "Okta Admin Console"})
   188  	require.NoError(t, err)
   189  
   190  	_, _, err = client.Application.ListApplications(ctx, &query.Params{Limit: 1, Filter: "status eq ACTIVE", Q: "Okta Dashboard"})
   191  	require.NoError(t, err)
   192  	_, _, err = client.Application.ListApplications(ctx, &query.Params{Limit: 1, Filter: "status eq ACTIVE", Q: "Okta Dashboard"})
   193  	require.NoError(t, err)
   194  
   195  	info := httpmock.GetCallCountInfo()
   196  	totalCalls := httpmock.GetTotalCallCount()
   197  
   198  	assert.Equal(t, 5, totalCalls, fmt.Sprintf("there should only be 5 API calls in this test but there were %d calls", totalCalls))
   199  
   200  	// Tokens from requests should be cached.
   201  	require.True(t, info[fmt.Sprintf("POST %s", httpmockTokenURLRegex)] == 1, "tokens endpoint should only be called once")
   202  
   203  	// But all other requests should not be cached.
   204  	require.True(t, info[fmt.Sprintf("GET %s", httpmockAdminConsoleRegex)] == 2)
   205  	require.True(t, info[fmt.Sprintf("GET %s", httpmockDashboardRegex)] == 2)
   206  }
   207  

View as plain text