token_fetcher_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package auth
  13. import (
  14. "context"
  15. "testing"
  16. "github.com/stretchr/testify/assert"
  17. authv1 "k8s.io/api/authentication/v1"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. k8sv1 "k8s.io/client-go/kubernetes/typed/core/v1"
  20. )
  21. func TestTokenFetcher(t *testing.T) {
  22. tf := &authTokenFetcher{
  23. ServiceAccount: "foobar",
  24. Namespace: "example",
  25. k8sClient: &mockK8sV1{},
  26. }
  27. token, err := tf.FetchToken(context.Background())
  28. assert.Nil(t, err)
  29. assert.Equal(t, []byte("FAKETOKEN"), token)
  30. }
  31. // Mock K8s client for creating tokens.
  32. type mockK8sV1 struct {
  33. k8sv1.CoreV1Interface
  34. }
  35. func (m *mockK8sV1) ServiceAccounts(namespace string) k8sv1.ServiceAccountInterface {
  36. return &mockK8sV1SA{v1mock: m}
  37. }
  38. // Mock the K8s service account client.
  39. type mockK8sV1SA struct {
  40. k8sv1.ServiceAccountInterface
  41. v1mock *mockK8sV1
  42. }
  43. func (ma *mockK8sV1SA) CreateToken(
  44. ctx context.Context,
  45. serviceAccountName string,
  46. tokenRequest *authv1.TokenRequest,
  47. opts metav1.CreateOptions,
  48. ) (*authv1.TokenRequest, error) {
  49. return &authv1.TokenRequest{
  50. Status: authv1.TokenRequestStatus{
  51. Token: "FAKETOKEN",
  52. },
  53. }, nil
  54. }