mfa_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package mfa
  14. import (
  15. "context"
  16. "testing"
  17. "github.com/stretchr/testify/assert"
  18. v1 "k8s.io/api/core/v1"
  19. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "sigs.k8s.io/controller-runtime/pkg/client"
  22. clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
  23. )
  24. func TestGenerate(t *testing.T) {
  25. type args struct {
  26. jsonSpec *apiextensions.JSON
  27. client client.Client
  28. }
  29. tests := []struct {
  30. name string
  31. g *Generator
  32. args args
  33. want map[string][]byte
  34. wantErr bool
  35. }{
  36. {
  37. name: "no json spec should result in error",
  38. args: args{
  39. jsonSpec: nil,
  40. },
  41. wantErr: true,
  42. },
  43. {
  44. name: "invalid json spec should result in error",
  45. args: args{
  46. jsonSpec: &apiextensions.JSON{
  47. Raw: []byte(`no json`),
  48. },
  49. },
  50. wantErr: true,
  51. },
  52. {
  53. name: "spec with secret should result in valid token",
  54. args: args{
  55. jsonSpec: &apiextensions.JSON{
  56. // time is used to pin the numbers, otherwise, they would keep changing.
  57. Raw: []byte(`{"spec": {"secret": {"name": "secret", "key": "secret"}, "when": "1998-05-05T05:05:05Z"}}`),
  58. },
  59. client: clientfake.NewClientBuilder().WithObjects(&v1.Secret{
  60. ObjectMeta: metav1.ObjectMeta{
  61. Name: "secret",
  62. Namespace: "namespace",
  63. },
  64. Data: map[string][]byte{
  65. "secret": []byte("foo"),
  66. },
  67. }).Build(),
  68. },
  69. want: map[string][]byte{
  70. "token": []byte(`674024`),
  71. "timeLeft": []byte(`25`),
  72. },
  73. wantErr: false,
  74. },
  75. }
  76. for _, tt := range tests {
  77. t.Run(tt.name, func(t *testing.T) {
  78. g := &Generator{}
  79. got, _, err := g.Generate(context.Background(), tt.args.jsonSpec, tt.args.client, "namespace")
  80. if (err != nil) != tt.wantErr {
  81. t.Errorf("Generator.Generate() error = %v, wantErr %v", err, tt.wantErr)
  82. return
  83. }
  84. assert.Equal(t, tt.want, got)
  85. })
  86. }
  87. }