Fix tests
[nonrtric/plt/sme.git] / capifcore / internal / publishservice / publishservice_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: Nordix Foundation
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 publishservice
22
23 import (
24         "fmt"
25         "net/http"
26         "os"
27         "testing"
28
29         "oransc.org/nonrtric/capifcore/internal/common29122"
30         "oransc.org/nonrtric/capifcore/internal/providermanagement"
31
32         "github.com/labstack/echo/v4"
33
34         publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
35
36         "oransc.org/nonrtric/capifcore/internal/helmmanagement"
37         helmMocks "oransc.org/nonrtric/capifcore/internal/helmmanagement/mocks"
38         serviceMocks "oransc.org/nonrtric/capifcore/internal/providermanagement/mocks"
39
40         "github.com/deepmap/oapi-codegen/pkg/middleware"
41         "github.com/deepmap/oapi-codegen/pkg/testutil"
42         echomiddleware "github.com/labstack/echo/v4/middleware"
43         "github.com/stretchr/testify/assert"
44         "github.com/stretchr/testify/mock"
45 )
46
47 func TestPublishUnpublishService(t *testing.T) {
48         aefId := "aefId"
49         newApiId := "api_id_app-management"
50         serviceRegisterMock := serviceMocks.ServiceRegister{}
51         serviceRegisterMock.On("IsFunctionRegistered", aefId).Return(true)
52         helmManagerMock := helmMocks.HelmManager{}
53         helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
54         serviceUnderTest, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
55
56         // Check no services published
57         result := testutil.NewRequest().Get("/aefId/service-apis/"+newApiId).Go(t, requestHandler)
58
59         assert.Equal(t, http.StatusNotFound, result.Code())
60
61         domainName := "domain"
62         var protocol publishapi.Protocol = "HTTP_1_1"
63         description := "Description,namespace,repoName,chartName,releaseName"
64         newServiceDescription := getServiceAPIDescription(aefId, domainName, description, protocol)
65
66         // Publish a service
67         result = testutil.NewRequest().Post("/aefId/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
68
69         assert.Equal(t, http.StatusCreated, result.Code())
70         var resultService publishapi.ServiceAPIDescription
71         err := result.UnmarshalBodyToObject(&resultService)
72         assert.NoError(t, err, "error unmarshaling response")
73         assert.Equal(t, *resultService.ApiId, newApiId)
74         assert.Equal(t, "http://example.com/"+aefId+"/service-apis/"+*resultService.ApiId, result.Recorder.Header().Get(echo.HeaderLocation))
75         newServiceDescription.ApiId = &newApiId
76         wantedAPILIst := []publishapi.ServiceAPIDescription{newServiceDescription}
77         assert.True(t, serviceUnderTest.AreAPIsRegistered(&wantedAPILIst))
78         assert.True(t, serviceUnderTest.IsAPIRegistered("aefId", "app-management"))
79         serviceRegisterMock.AssertCalled(t, "IsFunctionRegistered", aefId)
80         helmManagerMock.AssertCalled(t, "InstallHelmChart", "namespace", "repoName", "chartName", "releaseName")
81         assert.ElementsMatch(t, wantedAPILIst, *serviceUnderTest.GetAPIs())
82
83         // Check that service is published
84         result = testutil.NewRequest().Get("/aefId/service-apis/"+newApiId).Go(t, requestHandler)
85
86         assert.Equal(t, http.StatusOK, result.Code())
87         err = result.UnmarshalBodyToObject(&resultService)
88         assert.NoError(t, err, "error unmarshaling response")
89         assert.Equal(t, *resultService.ApiId, newApiId)
90
91         // Delete a service
92         helmManagerMock.On("UninstallHelmChart", mock.Anything, mock.Anything).Return(nil)
93         result = testutil.NewRequest().Delete("/aefId/service-apis/"+newApiId).Go(t, requestHandler)
94
95         assert.Equal(t, http.StatusNoContent, result.Code())
96         helmManagerMock.AssertCalled(t, "UninstallHelmChart", "namespace", "chartName")
97         assert.Empty(t, *serviceUnderTest.GetAPIs())
98
99         // Check no services published
100         result = testutil.NewRequest().Get("/aefId/service-apis/"+newApiId).Go(t, requestHandler)
101
102         assert.Equal(t, http.StatusNotFound, result.Code())
103 }
104
105 func TestPostUnpublishedServiceWithUnregisteredFunction(t *testing.T) {
106         aefId := "aefId"
107         serviceRegisterMock := serviceMocks.ServiceRegister{}
108         serviceRegisterMock.On("IsFunctionRegistered", aefId).Return(false)
109         _, requestHandler := getEcho(&serviceRegisterMock, nil)
110
111         domainName := "domain"
112         var protocol publishapi.Protocol = "HTTP_1_1"
113         description := "Description"
114         newServiceDescription := getServiceAPIDescription(aefId, domainName, description, protocol)
115
116         // Publish a service
117         result := testutil.NewRequest().Post("/aefId/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
118
119         assert.Equal(t, http.StatusNotFound, result.Code())
120         var resultError common29122.ProblemDetails
121         err := result.UnmarshalBodyToObject(&resultError)
122         assert.NoError(t, err, "error unmarshaling response")
123         errMsg := "Function not registered, aefId"
124         assert.Equal(t, &errMsg, resultError.Cause)
125         notFound := http.StatusNotFound
126         assert.Equal(t, &notFound, resultError.Status)
127 }
128
129 func getEcho(serviceRegister providermanagement.ServiceRegister, helmManager helmmanagement.HelmManager) (*PublishService, *echo.Echo) {
130         swagger, err := publishapi.GetSwagger()
131         if err != nil {
132                 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
133                 os.Exit(1)
134         }
135
136         swagger.Servers = nil
137
138         ps := NewPublishService(serviceRegister, helmManager)
139
140         e := echo.New()
141         e.Use(echomiddleware.Logger())
142         e.Use(middleware.OapiRequestValidator(swagger))
143
144         publishapi.RegisterHandlers(e, ps)
145         return ps, e
146 }
147
148 func getServiceAPIDescription(aefId, domainName, description string, protocol publishapi.Protocol) publishapi.ServiceAPIDescription {
149         return publishapi.ServiceAPIDescription{
150                 AefProfiles: &[]publishapi.AefProfile{
151                         {
152                                 AefId:      aefId,
153                                 DomainName: &domainName,
154                                 Protocol:   &protocol,
155                                 Versions: []publishapi.Version{
156                                         {
157                                                 ApiVersion: "v1",
158                                                 Resources: &[]publishapi.Resource{
159                                                         {
160                                                                 CommType: "REQUEST_RESPONSE",
161                                                                 Operations: &[]publishapi.Operation{
162                                                                         "POST",
163                                                                 },
164                                                                 ResourceName: "app",
165                                                                 Uri:          "app",
166                                                         },
167                                                 },
168                                         },
169                                 },
170                         },
171                 },
172                 ApiName:     "app-management",
173                 Description: &description,
174         }
175 }