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