24246586add4fecb3da34ac03d18d3c9cd5ce4c1
[nonrtric/plt/sme.git] / servicemanager / internal / discoverservice / discoverservice_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2024: OpenInfra Foundation Europe
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 discoverservice
22
23 import (
24         "fmt"
25         "net/http"
26         "os"
27         "reflect"
28         "sort"
29         "strings"
30         "testing"
31
32         echo "github.com/labstack/echo/v4"
33         log "github.com/sirupsen/logrus"
34
35         "oransc.org/nonrtric/servicemanager/internal/common29122"
36         "oransc.org/nonrtric/servicemanager/internal/discoverserviceapi"
37         "oransc.org/nonrtric/servicemanager/internal/invokermanagement"
38         "oransc.org/nonrtric/servicemanager/internal/invokermanagementapi"
39
40         publishapi "oransc.org/nonrtric/servicemanager/internal/publishserviceapi"
41
42         "github.com/deepmap/oapi-codegen/pkg/middleware"
43         "github.com/deepmap/oapi-codegen/pkg/testutil"
44         echomiddleware "github.com/labstack/echo/v4/middleware"
45         "github.com/stretchr/testify/assert"
46
47         "oransc.org/nonrtric/servicemanager/internal/envreader"
48         "oransc.org/nonrtric/servicemanager/internal/kongclear"
49         "oransc.org/nonrtric/servicemanager/internal/providermanagement"
50
51         provapi "oransc.org/nonrtric/servicemanager/internal/providermanagementapi"
52         "oransc.org/nonrtric/servicemanager/internal/publishservice"
53 )
54
55 var requestHandler *echo.Echo
56
57 func TestMain(m *testing.M) {
58         err := setupTest()
59         if err != nil {
60                 return
61         }
62
63         ret := m.Run()
64         if ret == 0 {
65                 teardown()
66         }
67         os.Exit(ret)
68 }
69
70 func setupTest() error {
71         myEnv, myPorts, err := envreader.ReadDotEnv()
72         if err != nil {
73                 log.Fatal("error loading environment file on setupTest")
74                 return err
75         }
76
77         requestHandler, err = getEcho(myEnv, myPorts)
78         if err != nil {
79                 log.Fatal("getEcho fatal error on setupTest")
80                 return err
81         }
82         err = teardown()
83         if err != nil {
84                 log.Fatal("getEcho fatal error on teardown")
85                 return err
86         }
87
88         return err
89 }
90
91 func getProvider() provapi.APIProviderEnrolmentDetails {
92         var (
93                 domainInfo  = "Kong"
94                 funcInfoAPF = "rApp Kong as APF"
95                 funcInfoAEF = "rApp Kong as AEF"
96         )
97
98         testFuncs := []provapi.APIProviderFunctionDetails{
99                 {
100                         ApiProvFuncInfo: &funcInfoAPF,
101                         ApiProvFuncRole: provapi.ApiProviderFuncRoleAPF,
102                         RegInfo: provapi.RegistrationInformation{
103                                 ApiProvPubKey: "APF-PublicKey",
104                         },
105                 },
106                 {
107                         ApiProvFuncInfo: &funcInfoAEF,
108                         ApiProvFuncRole: provapi.ApiProviderFuncRoleAEF,
109                         RegInfo: provapi.RegistrationInformation{
110                                 ApiProvPubKey: "AEF-PublicKey",
111                         },
112                 },
113         }
114         return provapi.APIProviderEnrolmentDetails{
115                 RegSec:         "sec",
116                 ApiProvDomInfo: &domainInfo,
117                 ApiProvFuncs:   &testFuncs,
118         }
119 }
120
121 func teardown() error {
122         log.Trace("entering teardown")
123
124         t := new(testing.T) // Create a new testing.T instance for teardown
125
126         // Delete the invoker
127         invokerInfo := "invoker a"
128         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
129
130         result := testutil.NewRequest().Delete("/api-invoker-management/v1/onboardedInvokers/"+invokerId).Go(t, requestHandler)
131         assert.Equal(t, http.StatusNoContent, result.Code())
132
133         // Delete the original published service
134         apfId := "APF_id_rApp_Kong_as_APF"
135         apiName := "apiName"
136         apiId := "api_id_" + apiName
137
138         result = testutil.NewRequest().Delete("/published-apis/v1/"+apfId+"/service-apis/"+apiId).Go(t, requestHandler)
139         assert.Equal(t, http.StatusNoContent, result.Code())
140
141         // Delete the first published service
142         apfId = "APF_id_rApp_Kong_as_APF"
143         apiName = "apiName1"
144         apiId = "api_id_" + apiName
145
146         result = testutil.NewRequest().Delete("/published-apis/v1/"+apfId+"/service-apis/"+apiId).Go(t, requestHandler)
147         assert.Equal(t, http.StatusNoContent, result.Code())
148
149         // Delete the second published service
150         apiName = "apiName2"
151         apiId = "api_id_" + apiName
152
153         result = testutil.NewRequest().Delete("/published-apis/v1/"+apfId+"/service-apis/"+apiId).Go(t, requestHandler)
154         assert.Equal(t, http.StatusNoContent, result.Code())
155
156         // Delete the provider
157         domainID := "domain_id_Kong"
158         result = testutil.NewRequest().Delete("/api-provider-management/v1/registrations/"+domainID).Go(t, requestHandler)
159         assert.Equal(t, http.StatusNoContent, result.Code())
160
161         myEnv, myPorts, err := envreader.ReadDotEnv()
162         if err != nil {
163                 log.Fatal("error loading environment file")
164                 return err
165         }
166
167         err = kongclear.KongClear(myEnv, myPorts)
168         if err != nil {
169                 log.Fatal("error clearing Kong on teardown")
170         }
171         return err
172 }
173
174 func TestRegisterValidProvider(t *testing.T) {
175         teardown()
176         newProvider := getProvider()
177
178         // Register a valid provider
179         result := testutil.NewRequest().Post("/api-provider-management/v1/registrations").WithJsonBody(newProvider).Go(t, requestHandler)
180         assert.Equal(t, http.StatusCreated, result.Code())
181
182         var resultProvider provapi.APIProviderEnrolmentDetails
183         err := result.UnmarshalBodyToObject(&resultProvider)
184         assert.NoError(t, err, "error unmarshaling response")
185 }
186
187 func TestPublishUnpublishService(t *testing.T) {
188         apfId := "APF_id_rApp_Kong_as_APF"
189         apiName := "apiName1"
190         apiId := "api_id_" + apiName
191
192         myEnv, myPorts, err := envreader.ReadDotEnv()
193         assert.Nil(t, err, "error reading env file")
194
195         testServiceIpv4 := common29122.Ipv4Addr(myEnv["TEST_SERVICE_IPV4"])
196         testServicePort := common29122.Port(myPorts["TEST_SERVICE_PORT"])
197
198         assert.NotEmpty(t, testServiceIpv4, "TEST_SERVICE_IPV4 is required in .env file for unit testing")
199         assert.NotZero(t, testServicePort, "TEST_SERVICE_PORT is required in .env file for unit testing")
200
201         // Check no services published
202         result := testutil.NewRequest().Get("/published-apis/v1/"+apfId+"/service-apis").Go(t, requestHandler)
203         assert.Equal(t, http.StatusOK, result.Code())
204
205         // Parse JSON from the response body
206         var resultServices []publishapi.ServiceAPIDescription
207         err = result.UnmarshalJsonToObject(&resultServices)
208         assert.NoError(t, err, "error unmarshaling response")
209
210         // Check if the parsed array is empty
211         assert.Zero(t, len(resultServices))
212         assert.True (t, len(resultServices) == 0)
213
214         aefId := "AEF_id_rApp_Kong_as_AEF"
215         namespace := "namespace"
216         repoName := "repoName"
217         chartName := "chartName"
218         releaseName := "releaseName"
219         description := fmt.Sprintf("Description,%s,%s,%s,%s", namespace, repoName, chartName, releaseName)
220
221         apiCategory := "apiCategory"
222         apiVersion := "v1"
223         var protocolHTTP11 = publishapi.ProtocolHTTP11
224         var dataFormatJSON = publishapi.DataFormatJSON
225
226         newServiceDescription := getServiceAPIDescription(aefId, apiName, apiCategory, apiVersion, &protocolHTTP11, &dataFormatJSON, description, testServiceIpv4, testServicePort, publishapi.CommunicationTypeREQUESTRESPONSE)
227
228         // Publish a service for provider
229         result = testutil.NewRequest().Post("/published-apis/v1/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
230         assert.Equal(t, http.StatusCreated, result.Code())
231
232         if result.Code() != http.StatusCreated {
233                 log.Fatalf("failed to publish the service with HTTP result code %d", result.Code())
234         }
235
236         var resultService publishapi.ServiceAPIDescription
237         err = result.UnmarshalJsonToObject(&resultService)
238         assert.NoError(t, err, "error unmarshaling response")
239         assert.Equal(t, apiId, *resultService.ApiId)
240
241         assert.Equal(t, "http://example.com/published-apis/v1/"+apfId+"/service-apis/"+*resultService.ApiId, result.Recorder.Header().Get(echo.HeaderLocation))
242
243         // Check that the service is published for the provider
244         result = testutil.NewRequest().Get("/published-apis/v1/"+apfId+"/service-apis/"+apiId).Go(t, requestHandler)
245         assert.Equal(t, http.StatusOK, result.Code())
246
247         err = result.UnmarshalJsonToObject(&resultService)
248         assert.NoError(t, err, "error unmarshaling response")
249         assert.Equal(t, apiId, *resultService.ApiId)
250
251         aefProfile := (*resultService.AefProfiles)[0]
252         interfaceDescription := (*aefProfile.InterfaceDescriptions)[0]
253
254         resultServiceIpv4 := *interfaceDescription.Ipv4Addr
255         resultServicePort := *interfaceDescription.Port
256
257         kongIPv4 := common29122.Ipv4Addr(myEnv["KONG_IPV4"])
258         kongDataPlanePort := common29122.Port(myPorts["KONG_DATA_PLANE_PORT"])
259
260         assert.NotEmpty(t, kongIPv4, "KONG_IPV4 is required in .env file for unit testing")
261         assert.NotZero(t, kongDataPlanePort, "KONG_DATA_PLANE_PORT is required in .env file for unit testing")
262
263         assert.Equal(t, kongIPv4, resultServiceIpv4)
264         assert.Equal(t, kongDataPlanePort, resultServicePort)
265
266         // Check one service published
267         result = testutil.NewRequest().Get("/published-apis/v1/"+apfId+"/service-apis").Go(t, requestHandler)
268         assert.Equal(t, http.StatusOK, result.Code())
269
270         // Parse JSON from the response body
271         err = result.UnmarshalJsonToObject(&resultServices)
272         assert.NoError(t, err, "error unmarshaling response")
273
274         // Check if the parsed array has one item
275         assert.True (t, len(resultServices) == 1)
276
277         // Publish a second service for provider
278         apiName2 := "apiName2"
279         apiId2 := "api_id_" + apiName2
280         apiVersion = "v2"
281         apiCategory = ""
282         protocolHTTP1 := publishapi.ProtocolHTTP2
283         var dataFormatOther publishapi.DataFormat = "OTHER"
284
285         newServiceDescription2 := getServiceAPIDescription(aefId, apiName2, apiCategory, apiVersion, &protocolHTTP1, &dataFormatOther, description, testServiceIpv4, testServicePort, publishapi.CommunicationTypeSUBSCRIBENOTIFY)
286
287         result = testutil.NewRequest().Post("/published-apis/v1/"+apfId+"/service-apis").WithJsonBody(newServiceDescription2).Go(t, requestHandler)
288         assert.Equal(t, http.StatusCreated, result.Code())
289
290         if result.Code() != http.StatusCreated {
291                 log.Fatalf("failed to publish the service with HTTP result code %d", result.Code())
292                 return
293         }
294
295         err = result.UnmarshalJsonToObject(&resultService)
296         assert.NoError(t, err, "error unmarshaling response")
297         assert.Equal(t, apiId2, *resultService.ApiId)
298
299         // Check no services published
300         result = testutil.NewRequest().Get("/published-apis/v1/"+apfId+"/service-apis").Go(t, requestHandler)
301         assert.Equal(t, http.StatusOK, result.Code())
302
303         // Parse JSON from the response body
304         err = result.UnmarshalJsonToObject(&resultServices)
305         assert.NoError(t, err, "error unmarshaling response")
306
307         // Check if the parsed array has two items
308         assert.True (t, len(resultServices) == 2)
309 }
310
311 func TestOnboardInvoker(t *testing.T) {
312         invokerInfo := "invoker a"
313         newInvoker := getInvoker(invokerInfo)
314
315         // Onboard a valid invoker
316         result := testutil.NewRequest().Post("/api-invoker-management/v1/onboardedInvokers").WithJsonBody(newInvoker).Go(t, requestHandler)
317         assert.Equal(t, http.StatusCreated, result.Code())
318
319         var resultInvoker invokermanagementapi.APIInvokerEnrolmentDetails
320
321         err := result.UnmarshalBodyToObject(&resultInvoker)
322         assert.NoError(t, err, "error unmarshaling response")
323
324         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
325
326         assert.Equal(t, invokerId, *resultInvoker.ApiInvokerId)
327         assert.Equal(t, newInvoker.NotificationDestination, resultInvoker.NotificationDestination)
328         assert.Equal(t, newInvoker.OnboardingInformation.ApiInvokerPublicKey, resultInvoker.OnboardingInformation.ApiInvokerPublicKey)
329         assert.Equal(t, "http://example.com/api-invoker-management/v1/onboardedInvokers/"+*resultInvoker.ApiInvokerId, result.Recorder.Header().Get(echo.HeaderLocation))
330 }
331
332 func TestGetAllServiceAPIs(t *testing.T) {
333         invokerInfo := "invoker a"
334         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
335         apiName1 := "apiName1"
336         apiName2 := "apiName2"
337
338         // Get all APIs, without any filter
339         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId).Go(t, requestHandler)
340         assert.Equal(t, http.StatusOK, result.Code())
341
342         var resultDiscovery discoverserviceapi.DiscoveredAPIs
343         err := result.UnmarshalBodyToObject(&resultDiscovery)
344         assert.NoError(t, err, "error unmarshaling response")
345
346         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
347         if resultDiscovery.ServiceAPIDescriptions != nil {
348                 assert.Equal(t, 2, len(*resultDiscovery.ServiceAPIDescriptions), "incorrect count of ServiceAPIDescriptions")
349                 if len(*resultDiscovery.ServiceAPIDescriptions) == 2 {
350                         // The order of the results is inconsistent.
351                         resultApiName1 := (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName
352                         resultApiName2 := (*resultDiscovery.ServiceAPIDescriptions)[1].ApiName
353                         resultApiNames := []string{resultApiName1, resultApiName2}
354                         sort.Strings(resultApiNames)
355                         expectedApiNames := []string{apiName1, apiName2}
356                         sort.Strings(expectedApiNames)
357                         assert.True(t, reflect.DeepEqual(resultApiNames, expectedApiNames))
358                 }
359
360         }
361 }
362
363 func TestGetAllServiceAPIsWhenMissingProvider(t *testing.T) {
364         invokerId := "unregistered"
365
366         // Get all APIs, without any filter
367         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId).Go(t, requestHandler)
368         assert.Equal(t, http.StatusNotFound, result.Code())
369
370         var problemDetails common29122.ProblemDetails
371         err := result.UnmarshalBodyToObject(&problemDetails)
372         assert.NoError(t, err, "error unmarshaling response")
373
374         notFound := http.StatusNotFound
375         assert.Equal(t, &notFound, problemDetails.Status)
376         assert.Contains(t, *problemDetails.Cause, invokerId)
377         assert.Contains(t, *problemDetails.Cause, "not registered")
378 }
379
380 func TestFilterApiName(t *testing.T) {
381         apiName := "apiName1"
382         invokerInfo := "invoker a"
383         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
384
385         // Get APIs with filter
386         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId+"&api-name="+apiName).Go(t, requestHandler)
387         assert.Equal(t, http.StatusOK, result.Code())
388
389         var resultDiscovery discoverserviceapi.DiscoveredAPIs
390         err := result.UnmarshalBodyToObject(&resultDiscovery)
391         assert.NoError(t, err, "error unmarshaling response")
392
393         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
394         if resultDiscovery.ServiceAPIDescriptions != nil {
395                 assert.Equal(t, 1, len(*resultDiscovery.ServiceAPIDescriptions))
396                 if len(*resultDiscovery.ServiceAPIDescriptions) == 1 {
397                         assert.Equal(t, apiName, (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName)
398                 }
399         }
400 }
401
402 func TestFilterAefId(t *testing.T) {
403         apiName1 := "apiName1"
404         apiName2 := "apiName2"
405         invokerInfo := "invoker a"
406         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
407
408         aefId := "AEF_id_rApp_Kong_as_AEF"
409
410         // Get APIs with filter
411         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId+"&aef-id="+aefId).Go(t, requestHandler)
412         assert.Equal(t, http.StatusOK, result.Code())
413
414         var resultDiscovery discoverserviceapi.DiscoveredAPIs
415         err := result.UnmarshalBodyToObject(&resultDiscovery)
416         assert.NoError(t, err, "error unmarshaling response")
417
418         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
419         if resultDiscovery.ServiceAPIDescriptions != nil {
420                 assert.Equal(t, 2, len(*resultDiscovery.ServiceAPIDescriptions), "incorrect count of ServiceAPIDescriptions")
421                 if len(*resultDiscovery.ServiceAPIDescriptions) == 2 {
422                         // The order of the results is inconsistent.
423                         resultApiName1 := (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName
424                         resultApiName2 := (*resultDiscovery.ServiceAPIDescriptions)[1].ApiName
425                         resultApiNames := []string{resultApiName1, resultApiName2}
426                         sort.Strings(resultApiNames)
427                         expectedApiNames := []string{apiName1, apiName2}
428                         sort.Strings(expectedApiNames)
429                         assert.True(t, reflect.DeepEqual(resultApiNames, expectedApiNames))
430                 }
431         }
432 }
433
434 func TestFilterVersion(t *testing.T) {
435         apiName := "apiName1"
436         invokerInfo := "invoker a"
437         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
438         apiVersion := "v1"
439
440         // Get APIs with filter
441         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId+"&api-version="+apiVersion).Go(t, requestHandler)
442         assert.Equal(t, http.StatusOK, result.Code())
443
444         var resultDiscovery discoverserviceapi.DiscoveredAPIs
445         err := result.UnmarshalBodyToObject(&resultDiscovery)
446
447         assert.NoError(t, err, "error unmarshaling response")
448
449         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
450         if resultDiscovery.ServiceAPIDescriptions != nil {
451                 assert.Equal(t, 1, len(*resultDiscovery.ServiceAPIDescriptions))
452                 if len(*resultDiscovery.ServiceAPIDescriptions) == 1 {
453                         assert.Equal(t, apiName, (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName)
454                 }
455         }
456 }
457
458 func TestFilterCommType(t *testing.T) {
459         apiName := "apiName1"
460         invokerInfo := "invoker a"
461         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
462
463         commType := publishapi.CommunicationTypeREQUESTRESPONSE
464
465         // Get APIs with filter
466         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId+"&comm-type="+string(commType)).Go(t, requestHandler)
467         assert.Equal(t, http.StatusOK, result.Code())
468
469         var resultDiscovery discoverserviceapi.DiscoveredAPIs
470         err := result.UnmarshalBodyToObject(&resultDiscovery)
471         assert.NoError(t, err, "error unmarshaling response")
472
473         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
474         if resultDiscovery.ServiceAPIDescriptions != nil {
475                 assert.Equal(t, 1, len(*resultDiscovery.ServiceAPIDescriptions))
476                 if len(*resultDiscovery.ServiceAPIDescriptions) == 1 {
477                         assert.Equal(t, apiName, (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName)
478                 }
479         }
480 }
481
482 func TestFilterVersionAndCommType(t *testing.T) {
483         apiName := "apiName1"
484         invokerInfo := "invoker a"
485         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
486
487         apiVersion := "v1"
488         commType := publishapi.CommunicationTypeREQUESTRESPONSE
489
490         // Get APIs with filter
491         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId+"&api-version="+apiVersion+"&comm-type="+string(commType)).Go(t, requestHandler)
492         assert.Equal(t, http.StatusOK, result.Code())
493
494         var resultDiscovery discoverserviceapi.DiscoveredAPIs
495         err := result.UnmarshalBodyToObject(&resultDiscovery)
496         assert.NoError(t, err, "error unmarshaling response")
497
498         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
499         if resultDiscovery.ServiceAPIDescriptions != nil {
500                 assert.Equal(t, 1, len(*resultDiscovery.ServiceAPIDescriptions))
501                 if len(*resultDiscovery.ServiceAPIDescriptions) == 1 {
502                         assert.Equal(t, apiName, (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName)
503                 }
504         }
505 }
506
507 func TestFilterAPICategory(t *testing.T) {
508         apiName := "apiName1"
509         invokerInfo := "invoker a"
510         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
511
512         apiCategory := "apiCategory"
513
514         // Get APIs with filter
515         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId+"&api-cat="+apiCategory).Go(t, requestHandler)
516         assert.Equal(t, http.StatusOK, result.Code())
517
518         var resultDiscovery discoverserviceapi.DiscoveredAPIs
519         err := result.UnmarshalBodyToObject(&resultDiscovery)
520         assert.NoError(t, err, "error unmarshaling response")
521
522         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
523         if resultDiscovery.ServiceAPIDescriptions != nil {
524                 assert.Equal(t, 1, len(*resultDiscovery.ServiceAPIDescriptions))
525                 if len(*resultDiscovery.ServiceAPIDescriptions) == 1 {
526                         assert.Equal(t, apiName, (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName)
527                 }
528         }
529 }
530
531 func TestFilterProtocol(t *testing.T) {
532         apiName := "apiName1"
533         invokerInfo := "invoker a"
534         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
535
536         var protocolHTTP11 = publishapi.ProtocolHTTP11
537
538         // Get APIs with filter
539         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId+"&protocol="+string(protocolHTTP11)).Go(t, requestHandler)
540         assert.Equal(t, http.StatusOK, result.Code())
541
542         var resultDiscovery discoverserviceapi.DiscoveredAPIs
543         err := result.UnmarshalBodyToObject(&resultDiscovery)
544         assert.NoError(t, err, "error unmarshaling response")
545
546         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
547
548         if resultDiscovery.ServiceAPIDescriptions != nil {
549                 assert.Equal(t, 1, len(*resultDiscovery.ServiceAPIDescriptions))
550                 if len(*resultDiscovery.ServiceAPIDescriptions) == 1 {
551                         assert.Equal(t, apiName, (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName)
552                 }
553         }
554 }
555
556 func TestFilterDataFormat(t *testing.T) {
557         apiName := "apiName1"
558         invokerInfo := "invoker a"
559         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
560
561         var dataFormatJSON = publishapi.DataFormatJSON
562
563         // Get APIs with filter
564         result := testutil.NewRequest().Get("/service-apis/v1/allServiceAPIs?api-invoker-id="+invokerId+"&data-format="+string(dataFormatJSON)).Go(t, requestHandler)
565         assert.Equal(t, http.StatusOK, result.Code())
566
567         var resultDiscovery discoverserviceapi.DiscoveredAPIs
568         err := result.UnmarshalBodyToObject(&resultDiscovery)
569
570         assert.NoError(t, err, "error unmarshaling response")
571
572         assert.NotNil(t, resultDiscovery.ServiceAPIDescriptions, "error reading ServiceAPIDescriptions")
573         if resultDiscovery.ServiceAPIDescriptions != nil {
574                 assert.Equal(t, 1, len(*resultDiscovery.ServiceAPIDescriptions))
575                 if len(*resultDiscovery.ServiceAPIDescriptions) == 1 {
576                         assert.Equal(t, apiName, (*resultDiscovery.ServiceAPIDescriptions)[0].ApiName)
577                 }
578         }
579         teardown()
580 }
581
582 func getEcho(myEnv map[string]string, myPorts map[string]int) (*echo.Echo, error) {
583         capifProtocol := myEnv["CAPIF_PROTOCOL"]
584         capifIPv4 := common29122.Ipv4Addr(myEnv["CAPIF_IPV4"])
585         capifPort := common29122.Port(myPorts["CAPIF_PORT"])
586         kongDomain := myEnv["KONG_DOMAIN"]
587         kongProtocol := myEnv["KONG_PROTOCOL"]
588         kongIPv4 := common29122.Ipv4Addr(myEnv["KONG_IPV4"])
589         kongDataPlanePort := common29122.Port(myPorts["KONG_DATA_PLANE_PORT"])
590         kongControlPlanePort := common29122.Port(myPorts["KONG_CONTROL_PLANE_PORT"])
591
592         e := echo.New()
593
594         // Register ProviderManagement
595         providerManagerSwagger, err := provapi.GetSwagger()
596         if err != nil {
597                 log.Fatalf("error loading ProviderManagement swagger spec\n: %s", err)
598                 return nil, err
599         }
600         providerManagerSwagger.Servers = nil
601         providerManager := providermanagement.NewProviderManager(capifProtocol, capifIPv4, capifPort)
602
603         var group *echo.Group
604
605         group = e.Group("/api-provider-management/v1")
606         group.Use(middleware.OapiRequestValidator(providerManagerSwagger))
607         provapi.RegisterHandlersWithBaseURL(e, providerManager, "/api-provider-management/v1")
608
609         // Register PublishService
610         publishServiceSwagger, err := publishapi.GetSwagger()
611         if err != nil {
612                 fmt.Fprintf(os.Stderr, "Error loading PublishService swagger spec\n: %s", err)
613                 return nil, err
614         }
615
616         publishServiceSwagger.Servers = nil
617
618         ps := publishservice.NewPublishService(kongDomain, kongProtocol, kongIPv4, kongDataPlanePort, kongControlPlanePort, capifProtocol, capifIPv4, capifPort)
619
620         group = e.Group("/published-apis/v1")
621         group.Use(echomiddleware.Logger())
622         group.Use(middleware.OapiRequestValidator(publishServiceSwagger))
623         publishapi.RegisterHandlersWithBaseURL(e, ps, "/published-apis/v1")
624
625         // Register InvokerService
626         invokerServiceSwagger, err := invokermanagementapi.GetSwagger()
627         if err != nil {
628                 fmt.Fprintf(os.Stderr, "Error loading InvokerManagement swagger spec\n: %s", err)
629                 return nil, err
630         }
631
632         invokerServiceSwagger.Servers = nil
633
634         im := invokermanagement.NewInvokerManager(capifProtocol, capifIPv4, capifPort)
635
636         group = e.Group("/api-invoker-management/v1")
637         group.Use(echomiddleware.Logger())
638         group.Use(middleware.OapiRequestValidator(invokerServiceSwagger))
639         invokermanagementapi.RegisterHandlersWithBaseURL(e, im, "api-invoker-management/v1")
640
641         // Register DiscoveryService
642         discoverySeviceSwagger, err := discoverserviceapi.GetSwagger()
643         if err != nil {
644                 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
645                 os.Exit(1)
646         }
647
648         discoverySeviceSwagger.Servers = nil
649
650         ds := NewDiscoverService(capifProtocol, capifIPv4, capifPort)
651
652         group = e.Group("/service-apis/v1")
653         group.Use(echomiddleware.Logger())
654         group.Use(middleware.OapiRequestValidator(discoverySeviceSwagger))
655         discoverserviceapi.RegisterHandlersWithBaseURL(e, ds, "service-apis/v1")
656
657         return e, err
658 }
659
660 func getServiceAPIDescription(aefId string, apiName string, apiCategory string, apiVersion string, protocol *publishapi.Protocol, dataFormat *publishapi.DataFormat, description string, testServiceIpv4 common29122.Ipv4Addr, testServicePort common29122.Port, commType publishapi.CommunicationType) publishapi.ServiceAPIDescription {
661         domainName := "Kong"
662         otherDomainName := "otherDomain"
663
664         var otherProtocol publishapi.Protocol = "HTTP_2"
665
666         categoryPointer := &apiCategory
667         if apiCategory == "" {
668                 categoryPointer = nil
669         }
670
671         var DataFormatOther publishapi.DataFormat = "OTHER"
672
673         return publishapi.ServiceAPIDescription{
674                 AefProfiles: &[]publishapi.AefProfile{
675                         {
676                                 AefId: aefId,
677                                 InterfaceDescriptions: &[]publishapi.InterfaceDescription{
678                                         {
679                                                 Ipv4Addr: &testServiceIpv4,
680                                                 Port:     &testServicePort,
681                                                 SecurityMethods: &[]publishapi.SecurityMethod{
682                                                         "PKI",
683                                                 },
684                                         },
685                                 },
686                                 DomainName: &domainName,
687                                 Protocol:   protocol,
688                                 DataFormat: dataFormat,
689                                 Versions: []publishapi.Version{
690                                         {
691                                                 ApiVersion: apiVersion,
692                                                 Resources: &[]publishapi.Resource{
693                                                         {
694                                                                 CommType: commType,
695                                                                 Operations: &[]publishapi.Operation{
696                                                                         "GET",
697                                                                 },
698                                                                 ResourceName: "helloworld",
699                                                                 Uri:          "/helloworld",
700                                                         },
701                                                 },
702                                         },
703                                 },
704                         },
705                         {
706                                 AefId:      aefId, // "otherAefId"
707                                 DomainName: &otherDomainName,
708                                 Protocol:   &otherProtocol,
709                                 DataFormat: &DataFormatOther,
710                                 Versions: []publishapi.Version{
711                                         {
712                                                 ApiVersion: "v3",
713                                                 Resources: &[]publishapi.Resource{
714                                                         {
715                                                                 ResourceName: "app",
716                                                                 CommType:     publishapi.CommunicationTypeSUBSCRIBENOTIFY,
717                                                                 Uri:          "uri",
718                                                                 Operations: &[]publishapi.Operation{
719                                                                         "POST",
720                                                                 },
721                                                         },
722                                                 },
723                                         },
724                                 },
725                         },
726                 },
727                 ApiName:            apiName,
728                 Description:        &description,
729                 ServiceAPICategory: categoryPointer,
730         }
731 }
732
733 func getInvoker(invokerInfo string) invokermanagementapi.APIInvokerEnrolmentDetails {
734         newInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
735                 ApiInvokerInformation:   &invokerInfo,
736                 NotificationDestination: "http://golang.cafe/",
737                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
738                         ApiInvokerPublicKey: "key",
739                 },
740                 ApiList: nil,
741         }
742         return newInvoker
743 }