Use apfId in publish service
[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         apfId := "apfId"
49         aefId := "aefId"
50         newApiId := "api_id_app-management"
51         serviceRegisterMock := serviceMocks.ServiceRegister{}
52         serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId"})
53         helmManagerMock := helmMocks.HelmManager{}
54         helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
55         serviceUnderTest, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
56
57         // Check no services published
58         result := testutil.NewRequest().Get("/aefId/service-apis/"+newApiId).Go(t, requestHandler)
59
60         assert.Equal(t, http.StatusNotFound, result.Code())
61
62         domainName := "domain"
63         var protocol publishapi.Protocol = "HTTP_1_1"
64         description := "Description,namespace,repoName,chartName,releaseName"
65         newServiceDescription := getServiceAPIDescription(aefId, domainName, description, protocol)
66
67         // Publish a service
68         result = testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
69
70         assert.Equal(t, http.StatusCreated, result.Code())
71         var resultService publishapi.ServiceAPIDescription
72         err := result.UnmarshalBodyToObject(&resultService)
73         assert.NoError(t, err, "error unmarshaling response")
74         assert.Equal(t, *resultService.ApiId, newApiId)
75         assert.Equal(t, "http://example.com/"+apfId+"/service-apis/"+*resultService.ApiId, result.Recorder.Header().Get(echo.HeaderLocation))
76         newServiceDescription.ApiId = &newApiId
77         wantedAPILIst := []publishapi.ServiceAPIDescription{newServiceDescription}
78         assert.True(t, serviceUnderTest.AreAPIsRegistered(&wantedAPILIst))
79         assert.True(t, serviceUnderTest.IsAPIRegistered("aefId", "app-management"))
80         serviceRegisterMock.AssertCalled(t, "GetAefsForPublisher", apfId)
81         helmManagerMock.AssertCalled(t, "InstallHelmChart", "namespace", "repoName", "chartName", "releaseName")
82         assert.ElementsMatch(t, []string{aefId}, serviceUnderTest.getAllAefIds())
83
84         // Check that service is published
85         result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
86
87         assert.Equal(t, http.StatusOK, result.Code())
88         err = result.UnmarshalBodyToObject(&resultService)
89         assert.NoError(t, err, "error unmarshaling response")
90         assert.Equal(t, *resultService.ApiId, newApiId)
91
92         // Delete a service
93         helmManagerMock.On("UninstallHelmChart", mock.Anything, mock.Anything).Return(nil)
94         result = testutil.NewRequest().Delete("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
95
96         assert.Equal(t, http.StatusNoContent, result.Code())
97         helmManagerMock.AssertCalled(t, "UninstallHelmChart", "namespace", "chartName")
98         assert.Empty(t, serviceUnderTest.getAllAefIds())
99
100         // Check no services published
101         result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
102
103         assert.Equal(t, http.StatusNotFound, result.Code())
104 }
105
106 func TestPostUnpublishedServiceWithUnregisteredFunction(t *testing.T) {
107         apfId := "apfId"
108         aefId := "aefId"
109         serviceRegisterMock := serviceMocks.ServiceRegister{}
110         serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{"otherAefId"})
111         _, requestHandler := getEcho(&serviceRegisterMock, nil)
112
113         domainName := "domain"
114         var protocol publishapi.Protocol = "HTTP_1_1"
115         description := "Description"
116         newServiceDescription := getServiceAPIDescription(aefId, domainName, description, protocol)
117
118         // Publish a service
119         result := testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
120
121         assert.Equal(t, http.StatusNotFound, result.Code())
122         var resultError common29122.ProblemDetails
123         err := result.UnmarshalBodyToObject(&resultError)
124         assert.NoError(t, err, "error unmarshaling response")
125         errMsg := "Function not registered, aefId"
126         assert.Equal(t, &errMsg, resultError.Cause)
127         notFound := http.StatusNotFound
128         assert.Equal(t, &notFound, resultError.Status)
129 }
130
131 func getEcho(serviceRegister providermanagement.ServiceRegister, helmManager helmmanagement.HelmManager) (*PublishService, *echo.Echo) {
132         swagger, err := publishapi.GetSwagger()
133         if err != nil {
134                 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
135                 os.Exit(1)
136         }
137
138         swagger.Servers = nil
139
140         ps := NewPublishService(serviceRegister, helmManager)
141
142         e := echo.New()
143         e.Use(echomiddleware.Logger())
144         e.Use(middleware.OapiRequestValidator(swagger))
145
146         publishapi.RegisterHandlers(e, ps)
147         return ps, e
148 }
149
150 func getServiceAPIDescription(aefId, domainName, description string, protocol publishapi.Protocol) publishapi.ServiceAPIDescription {
151         return publishapi.ServiceAPIDescription{
152                 AefProfiles: &[]publishapi.AefProfile{
153                         {
154                                 AefId:      aefId,
155                                 DomainName: &domainName,
156                                 Protocol:   &protocol,
157                                 Versions: []publishapi.Version{
158                                         {
159                                                 ApiVersion: "v1",
160                                                 Resources: &[]publishapi.Resource{
161                                                         {
162                                                                 CommType: "REQUEST_RESPONSE",
163                                                                 Operations: &[]publishapi.Operation{
164                                                                         "POST",
165                                                                 },
166                                                                 ResourceName: "app",
167                                                                 Uri:          "app",
168                                                         },
169                                                 },
170                                         },
171                                 },
172                         },
173                 },
174                 ApiName:     "app-management",
175                 Description: &description,
176         }
177 }