mfa_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 mfa
  13. import (
  14. "context"
  15. "testing"
  16. "github.com/stretchr/testify/assert"
  17. v1 "k8s.io/api/core/v1"
  18. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "sigs.k8s.io/controller-runtime/pkg/client"
  21. clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
  22. )
  23. func TestGenerate(t *testing.T) {
  24. type args struct {
  25. jsonSpec *apiextensions.JSON
  26. client client.Client
  27. }
  28. tests := []struct {
  29. name string
  30. g *Generator
  31. args args
  32. want map[string][]byte
  33. wantErr bool
  34. }{
  35. {
  36. name: "no json spec should result in error",
  37. args: args{
  38. jsonSpec: nil,
  39. },
  40. wantErr: true,
  41. },
  42. {
  43. name: "invalid json spec should result in error",
  44. args: args{
  45. jsonSpec: &apiextensions.JSON{
  46. Raw: []byte(`no json`),
  47. },
  48. },
  49. wantErr: true,
  50. },
  51. {
  52. name: "spec with secret should result in valid token",
  53. args: args{
  54. jsonSpec: &apiextensions.JSON{
  55. // time is used to pin the numbers, otherwise, they would keep changing.
  56. Raw: []byte(`{"spec": {"secret": {"name": "secret", "key": "secret"}, "when": "1998-05-05T05:05:05Z"}}`),
  57. },
  58. client: clientfake.NewClientBuilder().WithObjects(&v1.Secret{
  59. ObjectMeta: metav1.ObjectMeta{
  60. Name: "secret",
  61. Namespace: "namespace",
  62. },
  63. Data: map[string][]byte{
  64. "secret": []byte("foo"),
  65. },
  66. }).Build(),
  67. },
  68. want: map[string][]byte{
  69. "token": []byte(`674024`),
  70. "timeLeft": []byte(`25`),
  71. },
  72. wantErr: false,
  73. },
  74. }
  75. for _, tt := range tests {
  76. t.Run(tt.name, func(t *testing.T) {
  77. g := &Generator{}
  78. got, _, err := g.Generate(context.Background(), tt.args.jsonSpec, tt.args.client, "namespace")
  79. if (err != nil) != tt.wantErr {
  80. t.Errorf("Generator.Generate() error = %v, wantErr %v", err, tt.wantErr)
  81. return
  82. }
  83. assert.Equal(t, tt.want, got)
  84. })
  85. }
  86. }