e6a4d0e60e6435c381a61c5dde5a5fad15c845ca
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / cmpv2controller / logger / certificate_request_logger_test.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (C) 2020 Nokia. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package logger
22
23 import (
24         "bytes"
25
26         "io/ioutil"
27         "log"
28         "os"
29         "strings"
30         "testing"
31         "time"
32
33         cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
34         "github.com/stretchr/testify/assert"
35         metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
36
37         x509utils "onap.org/oom-certservice/k8s-external-provider/src/x509"
38         "onap.org/oom-certservice/k8s-external-provider/src/leveledlogger"
39 )
40
41 var checkedLogMessages = [7]string{"Property 'duration'", "Property 'usages'", "Property 'ipAddresses'",
42         "Property 'isCA'", "Property 'subject.streetAddress'", "Property 'subject.postalCodes'",
43         "Property 'subject.serialNumber'"}
44
45 var supportedProperties = [7]string{"Property 'organization'", "Property 'organization unit'", "Property 'country'",
46         "Property 'state'", "Property 'location'", "Property 'dns names'"}
47
48 const RESULT_LOG = "testdata/test_result.log"
49
50 func TestMain(m *testing.M) {
51         leveledlogger.SetConfigFileName("testdata/test_logger_config.json")
52         os.Exit(m.Run())
53 }
54
55 func TestLogShouldNotProvideInformationAboutSkippedPropertiesIfNotExistInCSR(t *testing.T) {
56         //given
57         logger := leveledlogger.GetLoggerWithName("test")
58         request := getCertificateRequestWithoutSkippedProperties()
59
60         csr, err := x509utils.DecodeCSR(request.Spec.Request)
61         if err != nil {
62                 assert.FailNow(t, "Could not parse Certificate Sign Request")
63         }
64
65         //when
66         LogCertRequestProperties(logger, request, csr)
67         logsArray := convertLogFileToStringArray(RESULT_LOG)
68
69         //then
70         for _, logMsg := range checkedLogMessages {
71                 assert.False(t, logsContainExpectedMessage(logsArray, logMsg), "Logs contain: "+logMsg+", but should not")
72         }
73         removeTemporaryFile(RESULT_LOG)
74 }
75
76 func TestLogShouldProvideInformationAboutSkippedPropertiesIfExistInCSR(t *testing.T) {
77         //given
78         logger := leveledlogger.GetLoggerWithName("test")
79         request := getCertificateRequestWithSkippedProperties()
80
81         csr, err := x509utils.DecodeCSR(request.Spec.Request)
82         if err != nil {
83                 assert.FailNow(t, "Could not parse Certificate Sign Request")
84         }
85
86         //when
87         LogCertRequestProperties(logger, request, csr)
88         logsArray := convertLogFileToStringArray(RESULT_LOG)
89
90         //then
91         for _, logMsg := range checkedLogMessages {
92                 assert.True(t, logsContainExpectedMessage(logsArray, logMsg), "Logs not contain: "+logMsg)
93         }
94         removeTemporaryFile(RESULT_LOG)
95 }
96
97 func TestLogShouldListSupportedProperties(t *testing.T) {
98         //given
99         logger := leveledlogger.GetLoggerWithName("test")
100         request := getCertificateRequestWithoutSkippedProperties()
101
102         csr, err := x509utils.DecodeCSR(request.Spec.Request)
103         if err != nil {
104                 assert.FailNow(t, "Could not parse Certificate Sign Request")
105         }
106
107         //when
108         LogCertRequestProperties(logger, request, csr)
109         logsArray := convertLogFileToStringArray(RESULT_LOG)
110
111         //then
112         for _, logMsg := range supportedProperties {
113                 assert.True(t, logsContainExpectedMessage(logsArray, logMsg), "Logs not contain: "+logMsg)
114         }
115         removeTemporaryFile(RESULT_LOG)
116 }
117
118 func getCertificateRequestWithoutSkippedProperties() *cmapi.CertificateRequest {
119         request := new(cmapi.CertificateRequest)
120         request.Spec.Request = []byte(csrWithoutSkippedProperties)
121         return request
122 }
123
124 func getCertificateRequestWithSkippedProperties() *cmapi.CertificateRequest {
125         request := new(cmapi.CertificateRequest)
126         request.Spec.Request = []byte(csrWithSkippedProperties)
127         request.Spec.Duration = &metav1.Duration{Duration: time.Hour}
128         request.Spec.IsCA = true
129         request.Spec.Usages = cmapi.DefaultKeyUsages()
130         return request
131 }
132
133 func convertBufferToStringArray(buffer *bytes.Buffer) []string {
134         return strings.Split(buffer.String(), "\n")
135 }
136
137 func convertLogFileToStringArray(filename string) []string {
138         buffer := bytes.NewBuffer(make([]byte, 0))
139         buffer.Write(readFile(filename))
140         return convertBufferToStringArray(buffer)
141 }
142
143 func readFile(filename string) []byte {
144         certRequest, err := ioutil.ReadFile(filename)
145         if err != nil {
146                 log.Fatal(err)
147         }
148         return certRequest
149 }
150
151 func removeTemporaryFile(fileName string) {
152         if _, err := os.Stat(fileName); err == nil {
153                 e := os.Remove(fileName)
154                 if e != nil {
155                         log.Fatal(e)
156                 }
157         }
158 }
159
160 func logsContainExpectedMessage(array []string, expectedMsg string) bool {
161         for _, logMsg := range array {
162                 if strings.Contains(logMsg, expectedMsg) {
163                         return true
164                 }
165         }
166         return false
167 }