aboutsummaryrefslogtreecommitdiffstats
path: root/README.md
AgeCommit message (Expand)AuthorFilesLines
2020-09-09Add log level support for orchestratorRajamohan Raj1-0/+3
2020-06-25Update Go versionLarry Sachs1-10/+1
2019-05-08Update Readme to reflect the new golang versionKiran Kamineni1-7/+13
2019-03-28Fix document typo in readme.mdKiran Kamineni1-4/+3
2018-10-23Fix README referencesVictor Morales1-2/+2
2018-08-24Seed code for k8s multicloud pluginShashank Kumar Shankar1-0/+41
ef='#n134'>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 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
#   Copyright 2022 Orange, Deutsche Telekom AG
#
#   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.
import json
import oyaml as yaml
from collections import namedtuple
from pathlib import Path
from unittest import mock

import pytest

from onapsdk.exceptions import APIError, InvalidResponse, ResourceNotFound, StatusError
from onapsdk.sdc.service import Service
from onapsdk.sdnc import NetworkPreload, VfModulePreload
from onapsdk.so.instantiation import (
    NetworkInstantiation,
    ServiceInstantiation,
    SoService,
    SoServicePnf,
    SoServiceVfModule,
    SoServiceVnf,
    VfModuleInstantiation,
    VnfInstantiation,
    VnfOperation
)
from onapsdk.vid import Vid
from onapsdk.aai.business.owning_entity import OwningEntity


@mock.patch.object(ServiceInstantiation, "send_message_json")
def test_service_ala_carte_instantiation(mock_service_instantiation_send_message):
    mock_sdc_service = mock.MagicMock()
    mock_sdc_service.distributed = False
    with pytest.raises(StatusError):
        ServiceInstantiation.\
            instantiate_ala_carte(sdc_service=mock_sdc_service,
                                  cloud_region=mock.MagicMock(),
                                  tenant=mock.MagicMock(),
                                  customer=mock.MagicMock(),
                                  owning_entity=mock.MagicMock(),
                                  project=mock.MagicMock(),
                                  service_instance_name="test",
                                  service_subscription=mock.MagicMock())
    mock_sdc_service.distributed = True
    service_instance = ServiceInstantiation.\
            instantiate_ala_carte(sdc_service=mock_sdc_service,
                                  cloud_region=mock.MagicMock(),
                                  tenant=mock.MagicMock(),
                                  customer=mock.MagicMock(),
                                  owning_entity=mock.MagicMock(),
                                  project=mock.MagicMock(),
                                  service_instance_name="test",
                                  service_subscription=mock.MagicMock())
    assert service_instance.name == "test"

    service_instance = ServiceInstantiation.\
            instantiate_ala_carte(sdc_service=mock_sdc_service,
                                  cloud_region=mock.MagicMock(),
                                  tenant=mock.MagicMock(),
                                  customer=mock.MagicMock(),
                                  owning_entity=mock.MagicMock(),
                                  project=mock.MagicMock(),
                                  service_subscription=mock.MagicMock())
    assert service_instance.name.startswith("Python_ONAP_SDK_service_instance_")
    mock_service_instantiation_send_message.assert_called()
    method, _, url = mock_service_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{ServiceInstantiation.base_url}/onap/so/infra/"
                   f"serviceInstantiation/{ServiceInstantiation.api_version}/serviceInstances")


@mock.patch.object(ServiceInstantiation, "send_message_json")
def test_service_macro_instantiation(mock_service_instantiation_send_message):
    mock_sdc_service = mock.MagicMock()
    mock_sdc_service.distributed = False
    with pytest.raises(StatusError):
        ServiceInstantiation.\
            instantiate_macro(sdc_service=mock_sdc_service,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              customer=mock.MagicMock(),
                              owning_entity=mock.MagicMock(),
                              project=mock.MagicMock(),
                              line_of_business=mock.MagicMock(),
                              platform=mock.MagicMock(),
                              service_instance_name="test",
                              service_subscription=mock.MagicMock())
    mock_sdc_service.distributed = True
    service_instance = ServiceInstantiation.\
            instantiate_macro(sdc_service=mock_sdc_service,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              customer=mock.MagicMock(),
                              owning_entity=mock.MagicMock(),
                              project=mock.MagicMock(),
                              line_of_business=mock.MagicMock(),
                              platform=mock.MagicMock(),
                              service_instance_name="test",
                              service_subscription=mock.MagicMock())
    assert service_instance.name == "test"

    service_instance = ServiceInstantiation.\
            instantiate_macro(sdc_service=mock_sdc_service,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              customer=mock.MagicMock(),
                              owning_entity=mock.MagicMock(),
                              line_of_business=mock.MagicMock(),
                              platform=mock.MagicMock(),
                              project=mock.MagicMock(),
                              so_service=mock.MagicMock())
    assert service_instance.name.startswith("Python_ONAP_SDK_service_instance_")
    mock_service_instantiation_send_message.assert_called()
    method, _, url = mock_service_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{ServiceInstantiation.base_url}/onap/so/infra/"
                   f"serviceInstantiation/{ServiceInstantiation.api_version}/serviceInstances")

    so_service_mock = mock.MagicMock()
    so_service_mock.instance_name = "SoServiceInstanceName"
    service_instance = ServiceInstantiation.\
            instantiate_macro(sdc_service=mock_sdc_service,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              customer=mock.MagicMock(),
                              owning_entity=mock.MagicMock(),
                              line_of_business=mock.MagicMock(),
                              platform=mock.MagicMock(),
                              project=mock.MagicMock(),
                              so_service=so_service_mock)
    assert service_instance.name == "SoServiceInstanceName"
    mock_service_instantiation_send_message.assert_called()
    method, _, url = mock_service_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{ServiceInstantiation.base_url}/onap/so/infra/"
                   f"serviceInstantiation/{ServiceInstantiation.api_version}/serviceInstances")


def test_service_instance_aai_service_instance():
    customer_mock = mock.MagicMock()
    service_instantiation = ServiceInstantiation(name="test",
                                                request_id="test_request_id",
                                                instance_id="test_instance_id",
                                                sdc_service=mock.MagicMock(),
                                                cloud_region=mock.MagicMock(),
                                                tenant=mock.MagicMock(),
                                                customer=customer_mock,
                                                owning_entity=mock.MagicMock(),
                                                project=mock.MagicMock())
    status_mock = mock.PropertyMock(return_value=ServiceInstantiation.StatusEnum.IN_PROGRESS)
    type(service_instantiation).status = status_mock
    with pytest.raises(StatusError):
        service_instantiation.aai_service_instance

    status_mock.return_value = return_value=ServiceInstantiation.StatusEnum.COMPLETED
    assert service_instantiation.aai_service_instance is not None

    customer_mock.get_service_subscription_by_service_type.side_effect = APIError
    with pytest.raises(APIError) as err:
        service_instantiation.aai_service_instance
    assert err.type == APIError


@mock.patch.object(VnfInstantiation, "send_message_json")
def test_vnf_instantiation(mock_vnf_instantiation_send_message):
    aai_service_instance_mock = mock.MagicMock()
    aai_service_instance_mock.instance_id = "test_instance_id"
    vnf_instantiation = VnfInstantiation.\
        instantiate_ala_carte(aai_service_instance=aai_service_instance_mock,
                              vnf_object=mock.MagicMock(),
                              line_of_business="test_lob",
                              platform="test_platform",
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              sdc_service=mock.MagicMock())
    assert vnf_instantiation.name.startswith("Python_ONAP_SDK_vnf_instance_")
    mock_vnf_instantiation_send_message.assert_called_once()
    method, _, url = mock_vnf_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{VnfInstantiation.base_url}/onap/so/infra/serviceInstantiation/"
                   f"{VnfInstantiation.api_version}/serviceInstances/"
                   f"{aai_service_instance_mock.instance_id}/vnfs")

    vnf_instantiation = VnfInstantiation.\
        instantiate_ala_carte(aai_service_instance=aai_service_instance_mock,
                              vnf_object=mock.MagicMock(),
                              line_of_business="test_lob",
                              platform="test_platform",
                              vnf_instance_name="test",
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              sdc_service=mock.MagicMock())
    assert vnf_instantiation.name == "test"


@mock.patch.object(VnfInstantiation, "send_message_json")
def test_vnf_instantiation_with_cr_and_tenant(mock_vnf_instantiation_send_message):
    aai_service_instance_mock = mock.MagicMock()
    aai_service_instance_mock.instance_id = "test_instance_id"
    vnf_instantiation = VnfInstantiation.\
        instantiate_ala_carte(aai_service_instance=aai_service_instance_mock,
                              vnf_object=mock.MagicMock(),
                              line_of_business="test_lob",
                              platform="test_platform",
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              sdc_service=mock.MagicMock())
    assert vnf_instantiation.name.startswith("Python_ONAP_SDK_vnf_instance_")
    mock_vnf_instantiation_send_message.assert_called_once()
    method, _, url = mock_vnf_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{VnfInstantiation.base_url}/onap/so/infra/serviceInstantiation/"
                   f"{VnfInstantiation.api_version}/serviceInstances/"
                   f"{aai_service_instance_mock.instance_id}/vnfs")

    vnf_instantiation = VnfInstantiation.\
        instantiate_ala_carte(aai_service_instance=aai_service_instance_mock,
                              vnf_object=mock.MagicMock(),
                              line_of_business="test_lob",
                              platform="test_platform",
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              vnf_instance_name="test",
                              sdc_service=mock.MagicMock())
    assert vnf_instantiation.name == "test"


@mock.patch.object(VnfInstantiation, "send_message_json")
@mock.patch.object(OwningEntity, "get_by_owning_entity_id")
def test_vnf_instantiation_macro(mock_owning_entity_get, mock_vnf_instantiation_send_message):
    aai_service_instance_mock = mock.MagicMock()
    aai_service_instance_mock.instance_id = "test_instance_id"

    relation_1 = mock.MagicMock()
    relation_1.related_to = "owning-entity"
    relation_1.relationship_data = [{"relationship-value": "test"}]
    relation_2 = mock.MagicMock()
    relation_2.related_to = "project"
    relation_2.relationship_data = [{"relationship-value": "test"}]

    aai_service_instance_mock.relationships = (item for item in [relation_1, relation_2])

    vnf_instantiation = VnfInstantiation.\
        instantiate_macro(aai_service_instance=aai_service_instance_mock,
                          vnf_object=mock.MagicMock(),
                          line_of_business="test_lob",
                          platform="test_platform",
                          cloud_region=mock.MagicMock(),
                          tenant=mock.MagicMock(),
                          sdc_service=mock.MagicMock())
    assert vnf_instantiation.name.startswith("Python_ONAP_SDK_vnf_instance_")
    mock_vnf_instantiation_send_message.assert_called_once()
    method, _, url = mock_vnf_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{VnfInstantiation.base_url}/onap/so/infra/serviceInstantiation/"
                   f"{VnfInstantiation.api_version}/serviceInstances/"
                   f"{aai_service_instance_mock.instance_id}/vnfs")

    vnf_instantiation = VnfInstantiation. \
        instantiate_macro(aai_service_instance=aai_service_instance_mock,
                          vnf_object=mock.MagicMock(),
                          line_of_business="test_lob",
                          platform="test_platform",
                          vnf_instance_name="test",
                          cloud_region=mock.MagicMock(),
                          tenant=mock.MagicMock(),
                          sdc_service=mock.MagicMock())
    assert vnf_instantiation.name == "test"

    vnf_instantiation = VnfInstantiation. \
        instantiate_macro(aai_service_instance=aai_service_instance_mock,
                          vnf_object=mock.MagicMock(),
                          line_of_business="test_lob",
                          platform="test_platform",
                          cloud_region=mock.MagicMock(),
                          tenant=mock.MagicMock(),
                          sdc_service=mock.MagicMock(),
                          so_vnf=mock.MagicMock())
    assert vnf_instantiation.name.startswith("Python_ONAP_SDK_service_instance_")

    so_vnf_mock = mock.MagicMock()
    so_vnf_mock.instance_name = "SoVnfInstanceName"
    vnf_instantiation = VnfInstantiation. \
        instantiate_macro(aai_service_instance=aai_service_instance_mock,
                          vnf_object=mock.MagicMock(),
                          line_of_business="test_lob",
                          platform="test_platform",
                          cloud_region=mock.MagicMock(),
                          tenant=mock.MagicMock(),
                          sdc_service=mock.MagicMock(),
                          so_vnf=so_vnf_mock)
    assert vnf_instantiation.name == "SoVnfInstanceName"


@mock.patch.object(VnfInstantiation, "send_message_json")
@mock.patch.object(OwningEntity, "get_by_owning_entity_id")
def test_vnf_macro_so_action(mock_owning_entity_get, mock_vnf_instantiation_send_message):

    mock_sdc_service = mock.MagicMock()
    with pytest.raises(StatusError):
        VnfInstantiation.\
            so_action(vnf_instance=mock.MagicMock(),
                      operation_type=mock.MagicMock(),
                      aai_service_instance=mock.MagicMock(),
                      line_of_business=mock.MagicMock(),
                      platform=mock.MagicMock(),
                      sdc_service=mock_sdc_service,
                      so_service=mock.MagicMock())

    relation_1 = mock.MagicMock()
    relation_1.related_to = "owning-entity"
    relation_1.relationship_data = [{"relationship-value": "test"}]
    relation_2 = mock.MagicMock()
    relation_2.related_to = "project"
    relation_2.relationship_data = [{"relationship-value": "test"}]

    mock_aai_service_instance = mock.MagicMock()
    mock_aai_service_instance.instance_id = mock.MagicMock()
    mock_aai_service_instance.relationships = (item for item in [relation_1, relation_2])
    mock_aai_service_instance.service_subscription = mock.MagicMock()
    mock_vnf_instance = mock.MagicMock()
    mock_vnf_instance.vnf_name = "test_name_update"
    mock_vnf_instance.vnf_id = "1234"

    vnf_instance_update = VnfInstantiation.\
        so_action(vnf_instance=mock_vnf_instance,
                  operation_type=VnfOperation.UPDATE,
                  aai_service_instance=mock_aai_service_instance,
                  line_of_business=mock.MagicMock(),
                  platform=mock.MagicMock(),
                  sdc_service=mock_sdc_service,
                  so_service=mock.MagicMock())
    assert vnf_instance_update.name == "test_name_update"
    mock_vnf_instantiation_send_message.assert_called()
    method, _, url = mock_vnf_instantiation_send_message.call_args[0]
    assert method == "PUT"
    assert url == (f"{ServiceInstantiation.base_url}/onap/so/infra/"
                   f"serviceInstantiation/{ServiceInstantiation.api_version}/serviceInstances/"
                   f"{mock_aai_service_instance.instance_id}/vnfs/{mock_vnf_instance.vnf_id}")

    mock_vnf_instance = mock.MagicMock()
    mock_vnf_instance.vnf_name = "test_name_healthcheck"

    vnf_instance_healthcheck = VnfInstantiation. \
        so_action(vnf_instance=mock_vnf_instance,
                  operation_type=VnfOperation.HEALTHCHECK,
                  aai_service_instance=mock_aai_service_instance,
                  line_of_business=mock.MagicMock(),
                  platform=mock.MagicMock(),
                  sdc_service=mock_sdc_service,
                  so_service=mock.MagicMock())
    assert vnf_instance_healthcheck.name == "test_name_healthcheck"
    mock_vnf_instantiation_send_message.assert_called()
    method, _, url = mock_vnf_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{ServiceInstantiation.base_url}/onap/so/infra/"
                   f"serviceInstantiation/{ServiceInstantiation.api_version}/serviceInstances/"
                   f"{mock_aai_service_instance.instance_id}/vnfs/{mock_vnf_instance.vnf_id}/healthcheck")


@mock.patch.object(NetworkInstantiation, "send_message_json")
@mock.patch.object(NetworkPreload, "send_message_json")
def test_network_instantiation(mock_network_preload, mock_network_instantiation_send_message):
    aai_service_instance_mock = mock.MagicMock()
    aai_service_instance_mock.instance_id = "test_instance_id"
    vnf_instantiation = NetworkInstantiation.\
        instantiate_ala_carte(aai_service_instance=aai_service_instance_mock,
                              network_object=mock.MagicMock(),
                              line_of_business="test_lob",
                              platform="test_platform",
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock())
    mock_network_preload.assert_called_once()
    assert vnf_instantiation.name.startswith("Python_ONAP_SDK_network_instance_")
    mock_network_instantiation_send_message.assert_called_once()
    method, _, url = mock_network_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{NetworkInstantiation.base_url}/onap/so/infra/serviceInstantiation/"
                   f"{NetworkInstantiation.api_version}/serviceInstances/"
                   f"{aai_service_instance_mock.instance_id}/networks")

    network_instantiation = NetworkInstantiation.\
        instantiate_ala_carte(aai_service_instance=aai_service_instance_mock,
                              network_object=mock.MagicMock(),
                              line_of_business="test_lob",
                              platform="test_platform",
                              network_instance_name="test",
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock())
    assert mock_network_preload.call_count == 2
    assert network_instantiation.name == "test"


@mock.patch.object(NetworkInstantiation, "send_message_json")
@mock.patch.object(NetworkPreload, "send_message_json")
def test_network_instantiation_with_cr_and_tenant(mock_network_preload, mock_network_instantiation_send_message):
    aai_service_instance_mock = mock.MagicMock()
    aai_service_instance_mock.instance_id = "test_instance_id"
    vnf_instantiation = NetworkInstantiation.\
        instantiate_ala_carte(aai_service_instance=aai_service_instance_mock,
                              network_object=mock.MagicMock(),
                              line_of_business=mock.MagicMock(),
                              platform=mock.MagicMock(),
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock())
    mock_network_preload.assert_called_once()
    assert vnf_instantiation.name.startswith("Python_ONAP_SDK_network_instance_")
    mock_network_instantiation_send_message.assert_called_once()
    method, _, url = mock_network_instantiation_send_message.call_args[0]
    assert method == "POST"
    assert url == (f"{NetworkInstantiation.base_url}/onap/so/infra/serviceInstantiation/"
                   f"{NetworkInstantiation.api_version}/serviceInstances/"
                   f"{aai_service_instance_mock.instance_id}/networks")

    network_instantiation = NetworkInstantiation.\
        instantiate_ala_carte(aai_service_instance=aai_service_instance_mock,
                              network_object=mock.MagicMock(),
                              line_of_business="test_lob",
                              platform="test_platform",
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              network_instance_name="test")
    assert mock_network_preload.call_count == 2
    assert network_instantiation.name == "test"

@mock.patch.object(Vid, "send_message")
@mock.patch.object(VnfInstantiation, "send_message_json")
@mock.patch("onapsdk.so.instantiation.SdcService")
def test_vnf_instantiation_get_by_vnf_instance_name(mock_sdc_service, mock_send_message_json, mock_send):
    mock_sdc_service.return_value.vnfs = []
    mock_send_message_json.return_value = {}
    with pytest.raises(InvalidResponse):
        VnfInstantiation.get_by_vnf_instance_name("test_vnf_instance_name")
    mock_send_message_json.return_value = {
        "requestList": [
            {
                "request": {
                    "requestScope": "not_vnf"
                }
            }
        ]
    }
    with pytest.raises(InvalidResponse):
        VnfInstantiation.get_by_vnf_instance_name("test_vnf_instance_name")
    mock_send_message_json.return_value = {
        "requestList": [
            {
                "request": {
                    "requestScope": "vnf",
                    "requestType": "updateInstance"
                }
            }
        ]
    }
    with pytest.raises(InvalidResponse):
        VnfInstantiation.get_by_vnf_instance_name("test_vnf_instance_name")
    mock_send_message_json.return_value = {
        "requestList": [
            {
                "request": {
                    "requestScope": "vnf",
                    "requestType": "createInstance"
                }
            }
        ]
    }
    with pytest.raises(ResourceNotFound):
        VnfInstantiation.get_by_vnf_instance_name("test_vnf_instance_name")
    mock_send_message_json.return_value = {
        "requestList": [
            {
                "request": {
                    "requestScope": "vnf",
                    "requestType": "createInstance",
                    "requestDetails": {
                        "relatedInstanceList": [
                            {
                                "relatedInstance": {
                                    "modelInfo": {
                                        "modelType": "service",
                                        "modelName": "test_service"
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        ]
    }
    with pytest.raises(ResourceNotFound):
        VnfInstantiation.get_by_vnf_instance_name("test_vnf_instance_name")
    mock_vnf = mock.MagicMock()
    mock_vnf.name = "test_vnf_name"
    mock_sdc_service.return_value.vnfs = [mock_vnf]
    mock_send_message_json.return_value = {
        "requestList": [
            {
                "request": {
                    "requestScope": "vnf",
                    "requestType": "createInstance",
                    "requestDetails": {
                        "modelInfo": {
                            "modelCustomizationName": "test_fail_vnf_name"
                        },
                        "relatedInstanceList": [
                            {
                                "relatedInstance": {
                                    "modelInfo": {
                                        "modelType": "service",
                                        "modelName": "test_service",
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        ]
    }
    with pytest.raises(ResourceNotFound):
        VnfInstantiation.get_by_vnf_instance_name("test_vnf_instance_name")
    mock_sdc_service.return_value.vnfs = [mock_vnf]
    mock_send_message_json.return_value = {
        "requestList": [
            {
                "request": {
                    "requestScope": "vnf",
                    "requestType": "createInstance",
                    "requestDetails": {
                        "modelInfo": {
                            "modelCustomizationName": "test_vnf_name"
                        },
                        "relatedInstanceList": [
                            {
                                "relatedInstance": {
                                    "modelInfo": {
                                        "modelType": "service",
                                        "modelName": "test_service"
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        ]
    }
    assert VnfInstantiation.get_by_vnf_instance_name("test_vnf_instance_name") is not None


@mock.patch.object(VfModuleInstantiation, "send_message_json")
@mock.patch.object(VfModulePreload, "upload_vf_module_preload")
def test_vf_module_instantiation(mock_vf_module_preload, mock_send_message_json):
    mock_service_instance = mock.MagicMock()
    mock_service_instance.instance_id = "1234"
    mock_vnf_instance = mock.MagicMock()
    mock_vnf_instance.service_instance = mock_service_instance
    mock_vnf_instance.vnf_id = "4321"
    instantiation = VfModuleInstantiation.\
        instantiate_ala_carte(vf_module=mock.MagicMock(),
                              vnf_instance=mock_vnf_instance,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock())
    assert instantiation.name.startswith("Python_ONAP_SDK_vf_module_instance_")
    mock_send_message_json.assert_called_once()
    method, _, url = mock_send_message_json.call_args[0]
    assert method == "POST"
    assert url == (f"{VfModuleInstantiation.base_url}/onap/so/infra/serviceInstantiation/"
                   f"{VfModuleInstantiation.api_version}/serviceInstances/1234/vnfs/"
                   f"4321/vfModules")

    instantiation = VfModuleInstantiation.\
        instantiate_ala_carte(vf_module=mock.MagicMock(),
                              vnf_instance=mock_vnf_instance,
                              vf_module_instance_name="test",
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock())
    assert instantiation.name == "test"


@mock.patch.object(VfModuleInstantiation, "send_message_json")
@mock.patch.object(VfModulePreload, "upload_vf_module_preload")
def test_vf_module_instantiation_with_cr_and_tenant(mock_vf_module_preload, mock_send_message_json):
    mock_service_instance = mock.MagicMock()
    mock_service_instance.instance_id = "1234"
    mock_vnf_instance = mock.MagicMock()
    mock_vnf_instance.service_instance = mock_service_instance
    mock_vnf_instance.vnf_id = "4321"
    instantiation = VfModuleInstantiation.\
        instantiate_ala_carte(vf_module=mock.MagicMock(),
                              vnf_instance=mock_vnf_instance,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock())
    assert instantiation.name.startswith("Python_ONAP_SDK_vf_module_instance_")
    mock_send_message_json.assert_called_once()
    method, _, url = mock_send_message_json.call_args[0]
    assert method == "POST"
    assert url == (f"{VfModuleInstantiation.base_url}/onap/so/infra/serviceInstantiation/"
                   f"{VfModuleInstantiation.api_version}/serviceInstances/1234/vnfs/"
                   f"4321/vfModules")

    instantiation = VfModuleInstantiation.\
        instantiate_ala_carte(vf_module=mock.MagicMock(),
                              vnf_instance=mock_vnf_instance,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              vf_module_instance_name="test")
    assert instantiation.name == "test"


def test_instantiation_wait_for_finish():
    with mock.patch.object(ServiceInstantiation, "finished", new_callable=mock.PropertyMock) as mock_finished:
        with mock.patch.object(ServiceInstantiation, "completed", new_callable=mock.PropertyMock) as mock_completed:
            instantiation = ServiceInstantiation(
                name="test",
                request_id="test",
                instance_id="test",
                sdc_service=mock.MagicMock(),
                cloud_region=mock.MagicMock(),
                tenant=mock.MagicMock(),
                customer=mock.MagicMock(),
                owning_entity=mock.MagicMock(),
                project=mock.MagicMock()
            )
            instantiation.WAIT_FOR_SLEEP_TIME = 0
            mock_finished.side_effect = [False, False, True]
            mock_completed.return_value = True
            rv = namedtuple("Value", ["return_value"])
            instantiation._wait_for_finish(rv)
            assert rv.return_value

@mock.patch.object(ServiceInstantiation, "send_message_json")
def test_service_instantiation_multicloud(mock_send_message_json):

    mock_sdc_service = mock.MagicMock()
    mock_sdc_service.distributed = True
    _ = ServiceInstantiation.\
            instantiate_ala_carte(sdc_service=mock_sdc_service,
                                  cloud_region=mock.MagicMock(),
                                  tenant=mock.MagicMock(),
                                  customer=mock.MagicMock(),
                                  owning_entity=mock.MagicMock(),
                                  project=mock.MagicMock(),
                                  service_subscription=mock.MagicMock())
    _, kwargs = mock_send_message_json.call_args
    data = json.loads(kwargs["data"])
    assert data["requestDetails"]["requestParameters"]["userParams"] == []
    mock_send_message_json.reset_mock()

    _ = ServiceInstantiation.\
            instantiate_ala_carte(sdc_service=mock_sdc_service,
                                  cloud_region=mock.MagicMock(),
                                  tenant=mock.MagicMock(),
                                  customer=mock.MagicMock(),
                                  owning_entity=mock.MagicMock(),
                                  project=mock.MagicMock(),
                                  enable_multicloud=True,
                                  service_subscription=mock.MagicMock())
    _, kwargs = mock_send_message_json.call_args
    data = json.loads(kwargs["data"])
    assert data["requestDetails"]["requestParameters"]["userParams"] == [{"name": "orchestrator", "value": "multicloud"}]
    mock_send_message_json.reset_mock()

    _ = ServiceInstantiation.\
            instantiate_macro(sdc_service=mock_sdc_service,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              customer=mock.MagicMock(),
                              owning_entity=mock.MagicMock(),
                              project=mock.MagicMock(),
                              line_of_business=mock.MagicMock(),
                              platform=mock.MagicMock(),
                              service_instance_name="test",
                              service_subscription=mock.MagicMock())
    _, kwargs = mock_send_message_json.call_args
    data = json.loads(kwargs["data"])
    assert not any(filter(lambda x: x == {"name": "orchestrator", "value": "multicloud"}, data["requestDetails"]["requestParameters"]["userParams"]))
    mock_send_message_json.reset_mock()

    _ = ServiceInstantiation.\
            instantiate_macro(sdc_service=mock_sdc_service,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              customer=mock.MagicMock(),
                              owning_entity=mock.MagicMock(),
                              project=mock.MagicMock(),
                              line_of_business=mock.MagicMock(),
                              platform=mock.MagicMock(),
                              service_instance_name="test",
                              enable_multicloud=True,
                              service_subscription=mock.MagicMock())
    _, kwargs = mock_send_message_json.call_args
    data = json.loads(kwargs["data"])
    assert any(filter(lambda x: x == {"name": "orchestrator", "value": "multicloud"}, data["requestDetails"]["requestParameters"]["userParams"]))


@mock.patch.object(ServiceInstantiation, "send_message_json")
def test_service_instantiation_so_service(mock_send_message_json):
    mock_sdc_service = mock.MagicMock()
    mock_sdc_service.distributed = True

    so_service = SoService(
        subscription_service_type="test_so_service",
        vnfs=[
            SoServiceVnf(
                model_name="test_so_service_vnf_model_name_1",
                instance_name="test_so_service_vnf_instance_name_1",
                parameters={
                    "param_1": "param_1_value",
                    "param_2": "param_2_value"
                }
            ),
            SoServiceVnf(
                model_name="test_so_service_vnf_model_name_2",
                instance_name="test_so_service_vnf_instance_name_2",
                vf_modules=[
                    SoServiceVfModule(
                        model_name="test_so_service_vf_module_model_name_1",
                        instance_name="test_so_service_vf_module_instance_name_1",
                        parameters={
                            "vf_module_param_1": "vf_module_param_1_value",
                            "vf_module_param_2": "vf_module_param_2_value"
                        }
                    ),
                    SoServiceVfModule(
                        model_name="test_so_service_vf_module_model_name_2",
                        instance_name="test_so_service_vf_module_instance_name_2",
                        parameters={
                            "vf_module_param_1": "vf_module_param_1_value",
                            "vf_module_param_2": "vf_module_param_2_value"
                        }
                    ),
                ]
            )
        ],
        pnfs=[
            SoServicePnf(
                model_name="test_so_service_pnf_model_name_1",
                instance_name="test_so_service_pnf_instance_name_1"
            ),
            SoServicePnf(
                model_name="test_so_service_pnf_model_name_2",
                instance_name="test_so_service_pnf_instance_name_2"
            )
        ]
    )

    _ = ServiceInstantiation.\
            instantiate_macro(sdc_service=mock_sdc_service,
                              cloud_region=mock.MagicMock(),
                              tenant=mock.MagicMock(),
                              customer=mock.MagicMock(),
                              owning_entity=mock.MagicMock(),
                              project=mock.MagicMock(),
                              line_of_business=mock.MagicMock(),
                              platform=mock.MagicMock(),
                              service_instance_name="test",
                              so_service=so_service)
    _, kwargs = mock_send_message_json.call_args
    data = json.loads(kwargs["data"])
    assert data["requestDetails"]["requestParameters"]["subscriptionServiceType"] == "test_so_service"
    assert len(data["requestDetails"]["requestParameters"]["userParams"][1]["service"]["resources"]["vnfs"]) == 2
    assert len(data["requestDetails"]["requestParameters"]["userParams"][1]["service"]["resources"]["pnfs"]) == 2
    vnf_1_data = data["requestDetails"]["requestParameters"]["userParams"][1]["service"]["resources"]["vnfs"][0]
    vnf_2_data = data["requestDetails"]["requestParameters"]["userParams"][1]["service"]["resources"]["vnfs"][1]
    pnf_1_data = data["requestDetails"]["requestParameters"]["userParams"][1]["service"]["resources"]["pnfs"][0]
    pnf_2_data = data["requestDetails"]["requestParameters"]["userParams"][1]["service"]["resources"]["pnfs"][1]

    assert vnf_1_data["instanceName"] == "test_so_service_vnf_instance_name_1"
    assert len(vnf_1_data["instanceParams"][0]) == 2
    assert vnf_1_data["instanceParams"][0]["param_1"] == "param_1_value"
    assert vnf_1_data["instanceParams"][0]["param_2"] == "param_2_value"
    assert len(vnf_1_data["vfModules"]) == 0

    assert vnf_2_data["instanceName"] == "test_so_service_vnf_instance_name_2"
    assert len(vnf_2_data["instanceParams"][0]) == 0
    assert len(vnf_2_data["vfModules"]) == 2
    vf_module_1_data = vnf_2_data["vfModules"][0]
    vf_module_2_data = vnf_2_data["vfModules"][1]

    assert vf_module_1_data["instanceName"] == "test_so_service_vf_module_instance_name_1"
    assert len(vf_module_1_data["instanceParams"][0]) == 2
    assert vf_module_1_data["instanceParams"][0]["vf_module_param_1"] == "vf_module_param_1_value"
    assert vf_module_1_data["instanceParams"][0]["vf_module_param_2"] == "vf_module_param_2_value"

    assert vf_module_2_data["instanceName"] == "test_so_service_vf_module_instance_name_2"
    assert len(vf_module_2_data["instanceParams"][0]) == 2
    assert vf_module_2_data["instanceParams"][0]["vf_module_param_1"] == "vf_module_param_1_value"
    assert vf_module_2_data["instanceParams"][0]["vf_module_param_2"] == "vf_module_param_2_value"

    assert pnf_1_data["instanceName"] == "test_so_service_pnf_instance_name_1"

    assert pnf_2_data["instanceName"] == "test_so_service_pnf_instance_name_2"


def test_so_service_load_from_yaml():

    so_service_yaml = """
    subscription_service_type: myservice
    vnfs:
        - model_name: myvfmodel
          instance_name: myfirstvnf
          parameters:
              param1: value1
          processing_priority: 1
          vf_modules:
              - instance_name: mysecondvfm
                model_name: base
                processing_priority: 2
                parameters:
                    param-vfm1: value-vfm1
              - instance_name: myfirstvfm
                model_name: base
                processing_priority: 1
                parameters:
                    param-vfm1: value-vfm1
        - model_name: myvfmodel
          instance_name: mysecondvnf
          parameters:
              param1: value1
          processing_priority: 2
          vf_modules:
              - instance_name: myfirstvfm
                model_name: base
                processing_priority: 1
                parameters:
                    param-vfm1: value-vfm1
              - instance_name: mysecondvfm
                model_name: base
                processing_priority: 2
                parameters:
                    param-vfm1: value-vfm1
    pnfs:
        - model_name: mypnfmodel
          instance_name: myfirstpnf
    """
    so_service = SoService.load(yaml.safe_load(so_service_yaml))
    assert so_service.subscription_service_type == "myservice"
    assert not so_service.instance_name
    assert len(so_service.vnfs) == 2
    assert len(so_service.pnfs) == 1

    so_service_vnf_1 = so_service.vnfs[0]
    so_service_vnf_2 = so_service.vnfs[1]
    so_service_pnf = so_service.pnfs[0]

    assert so_service_vnf_1.model_name == "myvfmodel"
    assert so_service_vnf_1.instance_name == "myfirstvnf"
    assert so_service_vnf_1.processing_priority == 1
    assert len(so_service_vnf_1.parameters) == 1
    assert so_service_vnf_1.parameters["param1"] == "value1"
    assert len(so_service_vnf_1.vf_modules) == 2

    so_service_vnf_1_vf_module_1 = so_service_vnf_1.vf_modules[0]
    so_service_vnf_1_vf_module_2 = so_service_vnf_1.vf_modules[1]

    assert so_service_vnf_1_vf_module_1.model_name == "base"
    assert so_service_vnf_1_vf_module_1.instance_name == "mysecondvfm"
    assert so_service_vnf_1_vf_module_1.processing_priority == 2
    assert len(so_service_vnf_1_vf_module_1.parameters) == 1
    assert so_service_vnf_1_vf_module_1.parameters["param-vfm1"] == "value-vfm1"
    assert so_service_vnf_1_vf_module_2.model_name == "base"
    assert so_service_vnf_1_vf_module_2.instance_name == "myfirstvfm"
    assert so_service_vnf_1_vf_module_2.processing_priority == 1
    assert len(so_service_vnf_1_vf_module_2.parameters) == 1
    assert so_service_vnf_1_vf_module_2.parameters["param-vfm1"] == "value-vfm1"

    assert so_service_vnf_2.model_name == "myvfmodel"
    assert so_service_vnf_2.instance_name == "mysecondvnf"
    assert so_service_vnf_2.processing_priority == 2
    assert len(so_service_vnf_2.parameters) == 1
    assert so_service_vnf_2.parameters["param1"] == "value1"
    assert len(so_service_vnf_2.vf_modules) == 2

    so_service_vnf_1_vf_module_1 = so_service_vnf_2.vf_modules[0]
    so_service_vnf_1_vf_module_2 = so_service_vnf_2.vf_modules[1]

    assert so_service_vnf_1_vf_module_1.model_name == "base"
    assert so_service_vnf_1_vf_module_1.instance_name == "myfirstvfm"
    assert so_service_vnf_1_vf_module_1.processing_priority == 1
    assert len(so_service_vnf_1_vf_module_1.parameters) == 1
    assert so_service_vnf_1_vf_module_1.parameters["param-vfm1"] == "value-vfm1"
    assert so_service_vnf_1_vf_module_2.model_name == "base"
    assert so_service_vnf_1_vf_module_2.instance_name == "mysecondvfm"
    assert so_service_vnf_1_vf_module_2.processing_priority == 2
    assert len(so_service_vnf_1_vf_module_2.parameters) == 1
    assert so_service_vnf_1_vf_module_2.parameters["param-vfm1"] == "value-vfm1"

    assert so_service_pnf.model_name == "mypnfmodel"
    assert so_service_pnf.instance_name == "myfirstpnf"


def test_so_service_load_from_file():
    with Path(Path(__file__).parent, "data/test_so_service_data.yaml").open() as yaml_template:
        so_service_data = yaml.safe_load(yaml_template)
    service = Service(next(iter(so_service_data.keys())))
    so_service = SoService.load(so_service_data[service.name])
    assert so_service.subscription_service_type == "myservice"
    assert not so_service.instance_name
    assert len(so_service.vnfs) == 2

    so_service_vnf_1 = so_service.vnfs[0]
    so_service_vnf_2 = so_service.vnfs[1]

    assert so_service_vnf_1.model_name == "myvfmodel"
    assert so_service_vnf_1.instance_name == "myfirstvnf"
    assert so_service_vnf_1.processing_priority == 1
    assert len(so_service_vnf_1.parameters) == 1
    assert so_service_vnf_1.parameters["param1"] == "value1"
    assert len(so_service_vnf_1.vf_modules) == 2

    so_service_vnf_1_vf_module_1 = so_service_vnf_1.vf_modules[0]
    so_service_vnf_1_vf_module_2 = so_service_vnf_1.vf_modules[1]

    assert so_service_vnf_1_vf_module_1.model_name == "base"
    assert so_service_vnf_1_vf_module_1.instance_name == "mysecondvfm"
    assert so_service_vnf_1_vf_module_1.processing_priority == 2
    assert len(so_service_vnf_1_vf_module_1.parameters) == 1
    assert so_service_vnf_1_vf_module_1.parameters["param-vfm1"] == "value-vfm1"
    assert so_service_vnf_1_vf_module_2.model_name == "base"
    assert so_service_vnf_1_vf_module_2.instance_name == "myfirstvfm"
    assert so_service_vnf_1_vf_module_2.processing_priority == 1
    assert len(so_service_vnf_1_vf_module_2.parameters) == 1
    assert so_service_vnf_1_vf_module_2.parameters["param-vfm1"] == "value-vfm1"

    assert so_service_vnf_2.model_name == "myvfmodel"
    assert so_service_vnf_2.instance_name == "mysecondvnf"
    assert so_service_vnf_2.processing_priority == 2
    assert len(so_service_vnf_2.parameters) == 1
    assert so_service_vnf_2.parameters["param1"] == "value1"
    assert len(so_service_vnf_2.vf_modules) == 2

    so_service_vnf_1_vf_module_1 = so_service_vnf_2.vf_modules[0]
    so_service_vnf_1_vf_module_2 = so_service_vnf_2.vf_modules[1]

    assert so_service_vnf_1_vf_module_1.model_name == "base"
    assert so_service_vnf_1_vf_module_1.instance_name == "myfirstvfm"
    assert so_service_vnf_1_vf_module_1.processing_priority == 1
    assert len(so_service_vnf_1_vf_module_1.parameters) == 1
    assert so_service_vnf_1_vf_module_1.parameters["param-vfm1"] == "value-vfm1"
    assert so_service_vnf_1_vf_module_2.model_name == "base"
    assert so_service_vnf_1_vf_module_2.instance_name == "mysecondvfm"
    assert so_service_vnf_1_vf_module_2.processing_priority == 2
    assert len(so_service_vnf_1_vf_module_2.parameters) == 1
    assert so_service_vnf_1_vf_module_2.parameters["param-vfm1"] == "value-vfm1"


def test_so_service_vnf_load_from_yaml():

    so_vnf_yaml = """
    model_name: myvnfmodel
    instance_name: mynewvnf
    parameters:
        param1: value1
    vf_modules:
        - instance_name: myfirstvfm
          model_name: base
          processing_priority: 1
          parameters:
              param-vfm1: value-vfm1
        - instance_name: mysecondvfm
          model_name: second_base
          processing_priority: 2
          parameters:
              param-vfm2: value-vfm2
              param-vfm3: value-vfm3
    """

    so_vnf = SoServiceVnf.load(yaml.safe_load(so_vnf_yaml))
    assert so_vnf.model_name == "myvnfmodel"
    assert so_vnf.instance_name == "mynewvnf"

    assert len(so_vnf.parameters) == 1
    assert so_vnf.parameters["param1"] == "value1"

    assert len(so_vnf.vf_modules) == 2
    so_vnf_vf_module_1 = so_vnf.vf_modules[0]
    so_vnf_vf_module_2 = so_vnf.vf_modules[1]

    assert so_vnf_vf_module_1.model_name == "base"
    assert so_vnf_vf_module_1.instance_name == "myfirstvfm"
    assert so_vnf_vf_module_1.processing_priority == 1
    assert len(so_vnf_vf_module_1.parameters) == 1
    assert so_vnf_vf_module_1.parameters["param-vfm1"] == "value-vfm1"

    assert so_vnf_vf_module_2.model_name == "second_base"
    assert so_vnf_vf_module_2.instance_name == "mysecondvfm"
    assert so_vnf_vf_module_2.processing_priority == 2
    assert len(so_vnf_vf_module_2.parameters) == 2
    assert so_vnf_vf_module_2.parameters["param-vfm2"] == "value-vfm2"
    assert so_vnf_vf_module_2.parameters["param-vfm3"] == "value-vfm3"