aboutsummaryrefslogtreecommitdiffstats
path: root/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java
blob: fab7df5345c2bd7519eeff88de7702c105b4cfd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

/*
 * Copyright (C) 2018 Bell Canada. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.onap.so.heatbridge;

import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.onap.aai.domain.yang.L3InterfaceIpv6AddressList;
import org.onap.aai.domain.yang.LInterface;
import org.onap.aai.domain.yang.PInterface;
import org.onap.aai.domain.yang.Relationship;
import org.onap.aai.domain.yang.RelationshipList;
import org.onap.aai.domain.yang.SriovPf;
import org.onap.aai.domain.yang.VfModule;
import org.onap.aaiclient.client.aai.AAICommonObjectMapperProvider;
import org.onap.aaiclient.client.aai.AAIDSLQueryClient;
import org.onap.aaiclient.client.aai.AAIResourcesClient;
import org.onap.aaiclient.client.aai.AAISingleTransactionClient;
import org.onap.aaiclient.client.aai.entities.AAIResultWrapper;
import org.onap.aaiclient.client.aai.entities.Results;
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri;
import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory;
import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder;
import org.onap.aaiclient.client.graphinventory.entities.DSLQuery;
import org.onap.aaiclient.client.graphinventory.entities.Pathed;
import org.onap.aaiclient.client.graphinventory.exceptions.BulkProcessFailed;
import org.onap.so.cloud.resource.beans.NodeType;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.heatbridge.constants.HeatBridgeConstants;
import org.onap.so.heatbridge.helpers.AaiHelper;
import org.onap.so.heatbridge.openstack.api.OpenstackClient;
import org.onap.so.heatbridge.openstack.api.OpenstackClientException;
import org.openstack4j.model.compute.Flavor;
import org.openstack4j.model.compute.Image;
import org.openstack4j.model.compute.Server;
import org.openstack4j.model.compute.Server.Status;
import org.openstack4j.model.heat.Resource;
import org.openstack4j.model.network.IP;
import org.openstack4j.model.network.IPVersionType;
import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.NetworkType;
import org.openstack4j.model.network.Port;
import org.openstack4j.model.network.Subnet;
import org.openstack4j.openstack.heat.domain.HeatResource;
import org.openstack4j.openstack.heat.domain.HeatResource.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;


@RunWith(MockitoJUnitRunner.Silent.class)
public class HeatBridgeImplTest {

    private static final String CLOUD_OWNER = "CloudOwner";
    private static final String REGION_ID = "RegionOne";
    private static final String TENANT_ID = "7320ec4a5b9d4589ba7c4412ccfd290f";
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static Logger logger = LoggerFactory.getLogger(HeatBridgeImplTest.class);

    @Mock
    private OpenstackClient osClient;

    private CloudIdentity cloudIdentity = new CloudIdentity();

    @Mock
    private AAIResourcesClient resourcesClient;

    @Mock
    private AAISingleTransactionClient transaction;

    @Mock
    private AAIDSLQueryClient mockDSLClient;

    @Mock
    private Environment env;

    @Mock
    private Server server;

    @Mock
    private Server server2;

    @Mock
    private Image image;

    @Mock
    private AAIDSLQueryClient dSLQueryClient;

    @Mock
    private AAIResourcesClient aaiResourcesClient;

    @Spy
    @InjectMocks
    private HeatBridgeImpl heatbridge = new HeatBridgeImpl(resourcesClient, cloudIdentity, CLOUD_OWNER, REGION_ID,
            REGION_ID, TENANT_ID, NodeType.GREENFIELD);


    @Before
    public void setUp() throws HeatBridgeException, OpenstackClientException, BulkProcessFailed {
        when(resourcesClient.beginSingleTransaction()).thenReturn(transaction);
    }



    @Test
    public void testExtractStackResourceIdsByResourceType() throws HeatBridgeException {
        // Arrange
        List<Resource> expectedResourceList = (List<Resource>) extractTestStackResources();
        List<String> expectedServerIds =
                Arrays.asList("43c2159b-2c04-46ac-bda5-594110cae2d3", "7cff109a-b2b7-4933-97b4-ec44a8365568");

        // Act
        List<String> serverIds = heatbridge.extractStackResourceIdsByResourceType(expectedResourceList,
                HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE);

        // Assert
        assertEquals(expectedServerIds, serverIds);
    }


    @Test
    @Ignore
    public void testUpdateVserversToAai() throws HeatBridgeException, JsonProcessingException {
        AaiHelper helper = new AaiHelper();
        helper.setAAIResourcesClient(resourcesClient);
        heatbridge.setAAIHelper(helper);

        VfModule module = new VfModule();
        RelationshipList relationships = new RelationshipList();
        List<Relationship> listRelationships = relationships.getRelationship();
        Relationship vnfcRelationship = new Relationship();
        vnfcRelationship.setRelationshipLabel("org.onap.relationships.inventory.Uses");
        vnfcRelationship.setRelatedTo("vnfc");
        vnfcRelationship.setRelatedLink("/aai/v22/network/vnfcs/vnfc/test-server1-name");

        listRelationships.add(vnfcRelationship);

        module.setRelationshipList(relationships);
        AAIResultWrapper wrapper =
                new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(module));

        when(aaiResourcesClient.get(AAIUriFactory.createResourceUri(
                AAIFluentTypeBuilder.network().genericVnf("test-genericVnf-id").vfModule("test-vfModule-id"))))
                        .thenReturn(wrapper);

        // Arrange
        Server server1 = mock(Server.class);

        when(server1.getId()).thenReturn("test-server1-id");
        when(server1.getHypervisorHostname()).thenReturn("test-hypervisor");
        when(server1.getName()).thenReturn("test-server1-name");
        when(server1.getStatus()).thenReturn(Status.ACTIVE);
        when(server1.getLinks()).thenReturn(new ArrayList<>());

        Server server2 = mock(Server.class);
        when(server2.getId()).thenReturn("test-server2-id");
        when(server2.getHypervisorHostname()).thenReturn("");
        when(server2.getName()).thenReturn("test-server2-name");
        when(server2.getStatus()).thenReturn(Status.ACTIVE);
        when(server2.getLinks()).thenReturn(new ArrayList<>());

        List<Server> servers = Arrays.asList(server1, server2);

        Image image = mock(Image.class);
        when(server1.getImage()).thenReturn(image);
        when(server2.getImage()).thenReturn(image);
        when(image.getId()).thenReturn("test-image-id");

        Flavor flavor = mock(Flavor.class);
        when(server1.getFlavor()).thenReturn(flavor);
        when(server2.getFlavor()).thenReturn(flavor);
        when(flavor.getId()).thenReturn("test-flavor-id");


        // Act
        heatbridge.buildAddVserversToAaiAction("test-genericVnf-id", "test-vfModule-id", servers);

        // Assert
        ArgumentCaptor<AAIResourceUri> captor = ArgumentCaptor.forClass(AAIResourceUri.class);
        verify(transaction, times(2)).create(captor.capture(), any());

        List<AAIResourceUri> uris = captor.getAllValues();
        assertEquals(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
                .cloudRegion(CLOUD_OWNER, REGION_ID).tenant(TENANT_ID).vserver(server1.getId())), uris.get(0));
        assertEquals(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
                .cloudRegion(CLOUD_OWNER, REGION_ID).tenant(TENANT_ID).vserver(server2.getId())), uris.get(1));

    }

    @Test
    @Ignore
    public void testUpdateVserversToAaiNoHypervisorName() throws HeatBridgeException, JsonProcessingException {
        AaiHelper aaiHelper = new AaiHelper();
        VfModule module = new VfModule();
        RelationshipList relationships = new RelationshipList();
        List<Relationship> listRelationships = relationships.getRelationship();
        Relationship vnfcRelationship = new Relationship();
        vnfcRelationship.setRelationshipLabel("org.onap.relationships.inventory.Uses");
        vnfcRelationship.setRelatedTo("vnfc");
        vnfcRelationship.setRelatedLink("/aai/v22/network/vnfcs/vnfc/test-server1-name");

        listRelationships.add(vnfcRelationship);

        module.setRelationshipList(relationships);
        AAIResultWrapper wrapper =
                new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(module));
        when(aaiResourcesClient.get(AAIUriFactory.createResourceUri(
                AAIFluentTypeBuilder.network().genericVnf("test-genericVnf-id").vfModule("test-vfModule-id"))))
                        .thenReturn(wrapper);

        aaiHelper.setAAIResourcesClient(aaiResourcesClient);
        heatbridge.setAAIHelper(aaiHelper);

        // Arrange
        Server server1 = mock(Server.class);

        when(server1.getId()).thenReturn("test-server1-id");
        when(server1.getHypervisorHostname()).thenReturn("");
        when(server1.getName()).thenReturn("test-server1-name");
        when(server1.getStatus()).thenReturn(Status.ACTIVE);
        when(server1.getLinks()).thenReturn(new ArrayList<>());

        Server server2 = mock(Server.class);
        when(server2.getId()).thenReturn("test-server2-id");
        when(server2.getName()).thenReturn("test-server2-name");
        when(server2.getStatus()).thenReturn(Status.ACTIVE);
        when(server2.getLinks()).thenReturn(new ArrayList<>());

        List<Server> servers = Arrays.asList(server1, server2);

        Image image = mock(Image.class);
        when(server1.getImage()).thenReturn(image);
        when(server2.getImage()).thenReturn(image);
        when(image.getId()).thenReturn("test-image-id");

        Flavor flavor = mock(Flavor.class);
        when(server1.getFlavor()).thenReturn(flavor);
        when(server2.getFlavor()).thenReturn(flavor);
        when(flavor.getId()).thenReturn("test-flavor-id");

        // Act
        heatbridge.buildAddVserversToAaiAction("test-genericVnf-id", "test-vfModule-id", servers);

        // Assert
        ArgumentCaptor<AAIResourceUri> captor = ArgumentCaptor.forClass(AAIResourceUri.class);
        verify(transaction, times(2)).create(captor.capture(), any());

        List<AAIResourceUri> uris = captor.getAllValues();
        assertEquals(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
                .cloudRegion(CLOUD_OWNER, REGION_ID).tenant(TENANT_ID).vserver(server1.getId())), uris.get(0));
        assertEquals(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
                .cloudRegion(CLOUD_OWNER, REGION_ID).tenant(TENANT_ID).vserver(server2.getId())), uris.get(1));
    }

    @Test
    public void testCreateRelationships() throws HeatBridgeException, JsonProcessingException {
        AaiHelper aaiHelper = new AaiHelper();
        VfModule module = new VfModule();
        RelationshipList relationships = new RelationshipList();
        List<Relationship> listRelationships = relationships.getRelationship();
        Relationship vnfcRelationship = new Relationship();
        vnfcRelationship.setRelationshipLabel("org.onap.relationships.inventory.Uses");
        vnfcRelationship.setRelatedTo("vnfc");
        vnfcRelationship.setRelatedLink("/aai/v22/network/vnfcs/vnfc/test-server1-name");

        listRelationships.add(vnfcRelationship);

        module.setRelationshipList(relationships);
        AAIResultWrapper wrapper =
                new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(module));
        when(aaiResourcesClient.get(AAIUriFactory.createResourceUri(
                AAIFluentTypeBuilder.network().genericVnf("test-genericVnf-id").vfModule("test-vfModule-id"))))
                        .thenReturn(wrapper);

        aaiHelper.setAAIResourcesClient(aaiResourcesClient);
        // Arrange
        Server server1 = mock(Server.class);

        when(server1.getId()).thenReturn("test-server1-id");
        when(server1.getHypervisorHostname()).thenReturn("test-hypervisor");
        when(server1.getName()).thenReturn("test-server1-name");
        when(server1.getStatus()).thenReturn(Status.ACTIVE);
        when(server1.getLinks()).thenReturn(new ArrayList<>());

        // HypervisorHostname is not set
        Server server2 = mock(Server.class);
        when(server2.getId()).thenReturn("test-server1-id");
        when(server2.getName()).thenReturn("test-server1-name");
        when(server2.getStatus()).thenReturn(Status.ACTIVE);
        when(server2.getLinks()).thenReturn(new ArrayList<>());

        // HypervisorHostname is empty string
        Server server3 = mock(Server.class);
        when(server3.getId()).thenReturn("test-server1-id");
        when(server3.getHypervisorHostname()).thenReturn("");
        when(server3.getName()).thenReturn("test-server1-name");
        when(server3.getStatus()).thenReturn(Status.ACTIVE);
        when(server3.getLinks()).thenReturn(new ArrayList<>());

        org.onap.aai.domain.yang.RelationshipList relList = aaiHelper.getVserverRelationshipList(CLOUD_OWNER, REGION_ID,
                "test-genericVnf-id", "test-vfModule-id", server1);
        assertEquals(3, relList.getRelationship().size());

        org.onap.aai.domain.yang.RelationshipList relList2 = aaiHelper.getVserverRelationshipList(CLOUD_OWNER,
                REGION_ID, "test-genericVnf-id", "test-vfModule-id", server2);
        assertEquals(2, relList2.getRelationship().size());

        org.onap.aai.domain.yang.RelationshipList relList3 = aaiHelper.getVserverRelationshipList(CLOUD_OWNER,
                REGION_ID, "test-genericVnf-id", "test-vfModule-id", server3);
        assertEquals(2, relList3.getRelationship().size());
    }


    @Test
    public void testUpdateImagesToAai() throws HeatBridgeException {
        // Arrange
        Image image1 = mock(Image.class);
        when(image1.getId()).thenReturn("test-image1-id");
        when(image1.getName()).thenReturn("test-image1-name");
        when(image1.getLinks()).thenReturn(new ArrayList<>());

        Image image2 = mock(Image.class);
        when(image2.getId()).thenReturn("test-image2-id");
        when(image2.getName()).thenReturn("test-image2-name");
        when(image2.getLinks()).thenReturn(new ArrayList<>());

        List<Image> images = Arrays.asList(image1, image2);

        // Act #1
        heatbridge.buildAddImagesToAaiAction(images);

        // Assert #1
        verify(transaction, times(2)).create(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.Image.class));

        // Act #2
        heatbridge.buildAddImagesToAaiAction(images);

        // Assert #2
        verify(transaction, times(4)).create(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.Image.class));
    }

    @Test
    public void testUpdateFlavorsToAai() throws HeatBridgeException {
        // Arrange
        Flavor flavor1 = mock(Flavor.class);
        when(flavor1.getId()).thenReturn("test-flavor1-id");
        when(flavor1.getName()).thenReturn("test-flavor1-name");
        when(flavor1.getLinks()).thenReturn(new ArrayList<>());

        Flavor flavor2 = mock(Flavor.class);
        when(flavor2.getId()).thenReturn("test-flavor2-id");
        when(flavor2.getName()).thenReturn("test-flavor2-name");
        when(flavor2.getLinks()).thenReturn(new ArrayList<>());

        List<Flavor> flavors = Arrays.asList(flavor1, flavor2);

        // Act #1
        heatbridge.buildAddFlavorsToAaiAction(flavors);

        // Assert #1
        verify(transaction, times(2)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
    }

    @Test
    public void testUpdateVserverLInterfacesToAai()
            throws HeatBridgeException, JsonParseException, JsonMappingException, IOException {
        // Arrange
        List<Resource> stackResources = (List<Resource>) extractTestStackResources();
        Port port = mock(Port.class);
        when(port.getId()).thenReturn("test-port-id");
        when(port.getHostId()).thenReturn("pserverId");
        when(port.getName()).thenReturn("test-port-name");
        when(port.getvNicType()).thenReturn(HeatBridgeConstants.OS_SRIOV_PORT_TYPE);
        when(port.getMacAddress()).thenReturn("78:4f:43:68:e2:78");
        when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a");
        when(port.getDeviceId()).thenReturn("test-device-id");

        when(osClient.getServerById("test-device-id")).thenReturn(server);
        when(server.getHypervisorHostname()).thenReturn("test.server.name");
        String pfPciId = "0000:08:00.0";
        when(port.getProfile()).thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_PCI_SLOT_KEY, pfPciId,
                HeatBridgeConstants.OS_PF_PCI_SLOT_KEY, "testPfPciId"));

        IP ip = mock(IP.class);

        Set<IP> ipSet = new HashSet<>();
        ipSet.add(ip);
        when(ip.getIpAddress()).thenReturn("2606:ae00:2e60:100::226");
        when(ip.getSubnetId()).thenReturn("testSubnetId");
        when(port.getFixedIps()).thenAnswer(x -> ipSet);

        Subnet subnet = mock(Subnet.class);
        when(subnet.getCidr()).thenReturn("169.254.100.0/24");
        when(osClient.getSubnetById("testSubnetId")).thenReturn(subnet);

        Network network = mock(Network.class);
        when(network.getId()).thenReturn("test-network-id");
        when(network.getNetworkType()).thenReturn(NetworkType.VLAN);
        when(network.getProviderSegID()).thenReturn("2345");
        when(network.getProviderPhyNet()).thenReturn("ovsnet");

        when(osClient.getPortById("212a203a-9764-4f42-84ea-731536a8f13a")).thenReturn(port);
        when(osClient.getPortById("387e3904-8948-43d1-8635-b6c2042b54da")).thenReturn(port);
        when(osClient.getPortById("70a09dfd-f1c5-4bc8-bd8f-dc539b8d662a")).thenReturn(port);
        when(osClient.getPortById("12f88b4d-c8a4-4fbd-bcb4-7e36af02430b")).thenReturn(port);
        when(osClient.getPortById("c54b9f45-b413-4937-bbe4-3c8a5689cfc9")).thenReturn(port);
        when(osClient.getNetworkById(anyString())).thenReturn(network);

        SriovPf sriovPf = new SriovPf();
        sriovPf.setPfPciId(pfPciId);

        when(resourcesClient.exists(any(AAIResourceUri.class))).thenReturn(true);
        when(env.getProperty("mso.cloudOwner.included", "")).thenReturn("CloudOwner");
        doReturn(dSLQueryClient).when(heatbridge).getAAIDSLClient();
        List<Pathed> pathed = ((Results<Pathed>) MAPPER.readValue(getJson("pathed-sriov-pf.json"),
                new TypeReference<Results<Pathed>>() {})).getResult();
        when(dSLQueryClient.queryPathed(any(DSLQuery.class))).thenReturn(pathed);
        doReturn(false).when(heatbridge).sriovVfHasSriovPfRelationship(any());

        // Act
        heatbridge.buildAddVserverLInterfacesToAaiAction(stackResources, Arrays.asList("1", "2"), "CloudOwner");

        // Assert
        verify(transaction, times(20)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
        verify(osClient, times(5)).getPortById(anyString());
        verify(osClient, times(5)).getSubnetById("testSubnetId");
        verify(osClient, times(10)).getNetworkById(anyString());
        verify(transaction, times(5)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
    }

    @Test
    public void testUpdateNetworksToAai() throws HeatBridgeException {

        Subnet subnet1 = mock(Subnet.class);
        when(subnet1.getId()).thenReturn("test-subnet1-id");
        when(subnet1.getName()).thenReturn("test-subnet1-name");
        when(subnet1.isDHCPEnabled()).thenReturn(true);
        when(subnet1.getGateway()).thenReturn("test-subnet1-gateway");
        when(subnet1.getCidr()).thenReturn("test-subnet1-gateway");
        when(subnet1.getIpVersion()).thenReturn(IPVersionType.V4);

        Subnet subnet2 = mock(Subnet.class);
        when(subnet2.getId()).thenReturn("test-subnet2-id");
        when(subnet2.getName()).thenReturn("test-subnet2-name");
        when(subnet2.isDHCPEnabled()).thenReturn(true);
        when(subnet2.getGateway()).thenReturn("test-subnet1-gateway");
        when(subnet2.getCidr()).thenReturn("test-subnet1-gateway");
        when(subnet2.getIpVersion()).thenReturn(IPVersionType.V6);

        when(osClient.getSubnetById(subnet1.getId())).thenReturn(subnet1);
        when(osClient.getSubnetById(subnet2.getId())).thenReturn(subnet2);

        List<String> subnetIds = Arrays.asList(subnet1.getId(), subnet2.getId());

        // Arrange
        Network network1 = mock(Network.class);
        when(network1.getId()).thenReturn("test-network1-id");
        when(network1.isShared()).thenReturn(true);
        when(network1.isRouterExternal()).thenReturn(true);
        when(network1.isAdminStateUp()).thenReturn(true);
        when(network1.getProviderPhyNet()).thenReturn("sriov-network1");
        when(network1.getName()).thenReturn("network1");
        when(network1.getSubnets()).thenReturn(subnetIds);

        Network network2 = mock(Network.class);
        when(network2.getId()).thenReturn("test-network2-id");
        when(network2.isShared()).thenReturn(true);
        when(network2.isRouterExternal()).thenReturn(true);
        when(network2.isAdminStateUp()).thenReturn(true);
        when(network2.getProviderPhyNet()).thenReturn("sriov-network2");
        when(network2.getName()).thenReturn("network2");
        when(network2.getSubnets()).thenReturn(subnetIds);

        String vnfId = "some-uuiid-of-the-vnf";
        String vfModuleId = "some-uuiid-of-the-vf-module";

        Subnet subnet = mock(Subnet.class);

        List<Network> networks = Arrays.asList(network1, network2);

        // Act #1
        heatbridge.buildAddNetworksToAaiAction(vnfId, vfModuleId, networks);

        // Assert #1
        verify(transaction, times(2)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));

        // Act #2
        heatbridge.buildAddNetworksToAaiAction(vnfId, vfModuleId, networks);

        // Assert #2
        verify(transaction, times(4)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));

    }

    @Test
    public void testUpdateLInterfaceVlan() throws HeatBridgeException {
        // Arrange
        List<Resource> stackResources = (List<Resource>) extractTestStackResources();
        Port port = mock(Port.class);
        when(port.getId()).thenReturn("test-port-id");
        when(port.getName()).thenReturn("test-port-name");
        when(port.getvNicType()).thenReturn(HeatBridgeConstants.OS_SRIOV_PORT_TYPE);
        when(port.getMacAddress()).thenReturn("78:4f:43:68:e2:78");
        when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a");
        when(port.getDeviceId()).thenReturn("test-device-id");

        LInterface lIf = new LInterface();
        lIf.setInterfaceId("test-port-id");
        lIf.setInterfaceType("SRIOV");
        lIf.setInterfaceName("name");

        String pfPciId = "0000:08:00.0";
        when(port.getProfile()).thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_PCI_SLOT_KEY, pfPciId,
                HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY, "physical_network_id"));

        IP ip = mock(IP.class);

        Set<IP> ipSet = new HashSet<>();
        ipSet.add(ip);
        when(ip.getIpAddress()).thenReturn("2606:ae00:2e60:100::226");
        when(ip.getSubnetId()).thenReturn("testSubnetId");
        when(port.getFixedIps()).thenAnswer(x -> ipSet);

        Subnet subnet = mock(Subnet.class);
        when(subnet.getCidr()).thenReturn("169.254.100.0/24");
        when(osClient.getSubnetById("testSubnetId")).thenReturn(subnet);

        Network network = mock(Network.class);
        when(network.getId()).thenReturn("test-network-id");
        when(network.getNetworkType()).thenReturn(NetworkType.VLAN);
        when(network.getProviderSegID()).thenReturn("2345");
        when(network.getProviderPhyNet()).thenReturn("ovsnet");
        doNothing().when(heatbridge).processOVS(any(), any(), any());

        when(osClient.getNetworkById(anyString())).thenReturn(network);

        SriovPf sriovPf = new SriovPf();
        sriovPf.setPfPciId(pfPciId);
        PInterface pIf = mock(PInterface.class);
        when(pIf.getInterfaceName()).thenReturn("test-port-id");
        when(resourcesClient.get(eq(PInterface.class), any(AAIResourceUri.class))).thenReturn(Optional.of(pIf));

        // Act
        heatbridge.createVlanAndSriovVF(port, lIf, "hostname");

        // Assert
        verify(transaction, times(2)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
        verify(osClient, times(1)).getNetworkById(anyString());
        verify(heatbridge, times(0)).processOVS(any(), any(), any());
    }

    @Test
    public void testUpdateLInterfaceIps()
            throws HeatBridgeException, JsonParseException, JsonMappingException, IOException {

        Port port = mock(Port.class);
        when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a");
        when(port.getDeviceId()).thenReturn("test-device-id");

        IP ip = mock(IP.class);

        Set<IP> ipSet = new HashSet<>();
        ipSet.add(ip);
        when(ip.getIpAddress()).thenReturn("2606:ae00:2e60:100::226");
        when(ip.getSubnetId()).thenReturn("testSubnetId");
        when(port.getFixedIps()).thenAnswer(x -> ipSet);

        Subnet subnet = mock(Subnet.class);
        when(subnet.getCidr()).thenReturn("169.254.100.0/24");
        when(osClient.getSubnetById("testSubnetId")).thenReturn(subnet);

        LInterface lIf = new LInterface();
        lIf.setInterfaceName("test-port-name");

        // Act
        heatbridge.updateLInterfaceIps(port, lIf);

        L3InterfaceIpv6AddressList ipv6 = new L3InterfaceIpv6AddressList();
        ipv6.setIsFloating(false);
        ipv6.setL3InterfaceIpv6Address("2606:ae00:2e60:100::226");
        ipv6.setNeutronNetworkId(port.getNetworkId());
        ipv6.setNeutronSubnetId(ip.getSubnetId());
        ipv6.setL3InterfaceIpv6PrefixLength(Long.parseLong("24"));

        ArgumentCaptor<Optional> argument = ArgumentCaptor.forClass(Optional.class);

        // Assert
        verify(transaction).createIfNotExists(
                eq(AAIUriFactory.createResourceUri(
                        AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion("CloudOwner", "RegionOne")
                                .tenant("7320ec4a5b9d4589ba7c4412ccfd290f").vserver("test-device-id")
                                .lInterface("test-port-name").l3InterfaceIpv6AddressList("2606:ae00:2e60:100::226"))),
                argument.capture());

        assertTrue(argument.getValue().isPresent());

        assertThat((L3InterfaceIpv6AddressList) argument.getValue().get(), sameBeanAs(ipv6));
    }

    @Test
    public void testUpdateVserverLInterfacesToAai_skipVlans()
            throws HeatBridgeException, JsonParseException, JsonMappingException, IOException {
        // Arrange
        List<Resource> stackResources = (List<Resource>) extractTestStackResources();
        Port port = mock(Port.class);
        when(port.getId()).thenReturn("test-port-id");
        when(port.getName()).thenReturn("test-port-name");
        when(port.getvNicType()).thenReturn(HeatBridgeConstants.OS_SRIOV_PORT_TYPE);
        when(port.getMacAddress()).thenReturn("78:4f:43:68:e2:78");
        when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a");
        when(port.getDeviceId()).thenReturn("test-device-id");
        String pfPciId = "0000:08:00.0";
        when(port.getProfile()).thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_PCI_SLOT_KEY, pfPciId,
                HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY, "physical_network_id"));

        Network network = mock(Network.class);
        when(network.getId()).thenReturn("test-network-id");
        when(network.getNetworkType()).thenReturn(NetworkType.VLAN);
        when(network.getProviderSegID()).thenReturn("2345");

        when(osClient.getPortById("212a203a-9764-4f42-84ea-731536a8f13a")).thenReturn(port);
        when(osClient.getPortById("387e3904-8948-43d1-8635-b6c2042b54da")).thenReturn(port);
        when(osClient.getPortById("70a09dfd-f1c5-4bc8-bd8f-dc539b8d662a")).thenReturn(port);
        when(osClient.getPortById("12f88b4d-c8a4-4fbd-bcb4-7e36af02430b")).thenReturn(port);
        when(osClient.getPortById("c54b9f45-b413-4937-bbe4-3c8a5689cfc9")).thenReturn(port);
        when(osClient.getNetworkById(anyString())).thenReturn(network);

        PInterface pIf = mock(PInterface.class);
        when(pIf.getInterfaceName()).thenReturn("test-port-id");
        doNothing().when(heatbridge).updateSriovPfToSriovVF(any(), any());

        // Act
        heatbridge.buildAddVserverLInterfacesToAaiAction(stackResources, Arrays.asList("1", "2"), "CloudOwner");

        // Assert
        verify(transaction, times(5)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
        verify(osClient, times(5)).getPortById(anyString());
        verify(osClient, times(5)).getNetworkById(anyString());
    }

    @Test
    public void testBuildAddVserverLInterfacesToAaiAction_PortProfileNull()
            throws HeatBridgeException, JsonParseException, JsonMappingException, IOException {
        // Arrange
        List<Resource> stackResources = (List<Resource>) extractTestStackResources();
        Port port = mock(Port.class);
        when(port.getId()).thenReturn("test-port-id");
        when(port.getName()).thenReturn("test-port-name");
        when(port.getvNicType()).thenReturn(HeatBridgeConstants.OS_SRIOV_PORT_TYPE);
        when(port.getMacAddress()).thenReturn("78:4f:43:68:e2:78");
        when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a");
        when(port.getDeviceId()).thenReturn("test-device-id");
        String pfPciId = "0000:08:00.0";

        Network network = mock(Network.class);
        when(network.getId()).thenReturn("test-network-id");
        when(network.getNetworkType()).thenReturn(NetworkType.VLAN);
        when(network.getProviderSegID()).thenReturn("2345");

        when(osClient.getPortById("212a203a-9764-4f42-84ea-731536a8f13a")).thenReturn(port);
        when(osClient.getPortById("387e3904-8948-43d1-8635-b6c2042b54da")).thenReturn(port);
        when(osClient.getPortById("70a09dfd-f1c5-4bc8-bd8f-dc539b8d662a")).thenReturn(port);
        when(osClient.getPortById("12f88b4d-c8a4-4fbd-bcb4-7e36af02430b")).thenReturn(port);
        when(osClient.getPortById("c54b9f45-b413-4937-bbe4-3c8a5689cfc9")).thenReturn(port);
        when(osClient.getNetworkById(anyString())).thenReturn(network);

        PInterface pIf = mock(PInterface.class);
        when(pIf.getInterfaceName()).thenReturn("test-port-id");
        doNothing().when(heatbridge).updateSriovPfToSriovVF(any(), any());

        // Act
        heatbridge.buildAddVserverLInterfacesToAaiAction(stackResources, Arrays.asList("1", "2"), "CloudOwner");

        // Assert
        ArgumentCaptor<Optional> argument = ArgumentCaptor.forClass(Optional.class);
        verify(transaction, times(5)).createIfNotExists(any(AAIResourceUri.class), argument.capture());
        assertEquals(false, ((LInterface) argument.getValue().get()).isL2Multicasting());
        verify(osClient, times(5)).getPortById(anyString());
        verify(osClient, times(5)).getNetworkById(anyString());
    }

    @Test
    public void testBuildAddVserverLInterfacesToAaiAction_DeviceIdNull()
            throws HeatBridgeException, JsonParseException, JsonMappingException, IOException {
        // Arrange
        List<Resource> stackResources = (List<Resource>) extractTestStackResources();
        Port port = mock(Port.class);
        when(port.getId()).thenReturn("test-port-id");
        when(port.getName()).thenReturn("test-port-name");
        when(port.getvNicType()).thenReturn(HeatBridgeConstants.OS_SRIOV_PORT_TYPE);
        when(port.getMacAddress()).thenReturn("78:4f:43:68:e2:78");
        when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a");
        when(port.getDeviceId()).thenReturn(null);
        String pfPciId = "0000:08:00.0";

        Network network = mock(Network.class);
        when(network.getId()).thenReturn("test-network-id");
        when(network.getNetworkType()).thenReturn(NetworkType.VLAN);
        when(network.getProviderSegID()).thenReturn("2345");

        when(osClient.getPortById("212a203a-9764-4f42-84ea-731536a8f13a")).thenReturn(port);
        when(osClient.getPortById("387e3904-8948-43d1-8635-b6c2042b54da")).thenReturn(port);
        when(osClient.getPortById("70a09dfd-f1c5-4bc8-bd8f-dc539b8d662a")).thenReturn(port);
        when(osClient.getPortById("12f88b4d-c8a4-4fbd-bcb4-7e36af02430b")).thenReturn(port);
        when(osClient.getPortById("c54b9f45-b413-4937-bbe4-3c8a5689cfc9")).thenReturn(port);
        when(osClient.getNetworkById(anyString())).thenReturn(network);

        PInterface pIf = mock(PInterface.class);
        when(pIf.getInterfaceName()).thenReturn("test-port-id");
        doNothing().when(heatbridge).updateSriovPfToSriovVF(any(), any());

        // Act
        heatbridge.buildAddVserverLInterfacesToAaiAction(stackResources, Arrays.asList("1", "2"), "CloudOwner");

        // Assert
        verify(transaction, times(0)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
        verify(osClient, times(5)).getPortById(anyString());
        verify(osClient, times(5)).getNetworkById(anyString());
    }

    @Test
    public void testExtractOpenstackImagesFromServers() throws HeatBridgeException {
        // Arrange
        List<Server> serverList = new ArrayList<>();
        serverList.add(server);
        serverList.add(server2);
        when(server.getImage()).thenReturn(null);
        when(server.getImage()).thenReturn(image);
        when(image.getId()).thenReturn("imageId");
        // Act

        List<Image> images = heatbridge.extractOpenstackImagesFromServers(serverList);


        // Assert
        assertEquals(1, images.size());
    }

    private List<? extends Resource> extractTestStackResources() {
        List<HeatResource> stackResources = null;
        try {
            stackResources = MAPPER.readValue(readTestResourceFile("stack-resources.json"), Resources.class).getList();
            assertNotNull(stackResources);
            assertFalse(stackResources.isEmpty());
        } catch (IOException e) {
            Assert.fail("Failed to extract test stack resources.");
        }
        return stackResources;
    }


    private String readTestResourceFile(String filePath) {
        String content = null;
        String pathname = Objects.requireNonNull(getClass().getClassLoader().getResource(filePath)).getFile();
        File file = new File(pathname);
        try {
            content = Objects.requireNonNull(FileUtils.readFileToString(file, Charset.defaultCharset()));
        } catch (IOException e) {
            Assert.fail(String.format("Failed to read test resource file (%s)", filePath));
        }
        return content;
    }

    private String getJson(String filename) throws IOException {
        return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/" + filename)));
    }


}