aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_sdc2_pnf.py
blob: 07834a5e739886f586da030383276a3e06268bf9 (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
import json
from collections import namedtuple
from random import choice, randint
from sys import maxsize
from tempfile import NamedTemporaryFile
from unittest.mock import MagicMock, patch, PropertyMock
from uuid import uuid4

from pytest import raises

from onapsdk.exceptions import ResourceNotFound
from onapsdk.sdc2.sdc_resource import LifecycleState, LifecycleOperation
from onapsdk.sdc2.pnf import Pnf, ResoureTypeEnum


def test_pnf_resource_type():
    assert Pnf.resource_type() == ResoureTypeEnum.PNF


def test_pnf_create_payload_template():
    assert Pnf.create_payload_template() == "sdc2_create_pnf.json.j2"


def test_copy_pnf():
    pnf1 = Pnf(name="test_pnf1")
    pnf2 = Pnf(name="test_pnf2")
    assert pnf1.name == "test_pnf1"
    assert pnf2.name == "test_pnf2"
    assert pnf1 != pnf2
    pnf2._copy_object(pnf1)
    assert pnf1.name == "test_pnf1"
    assert pnf2.name == "test_pnf1"
    assert pnf1 == pnf2


@patch("onapsdk.sdc2.pnf.Pnf._get_active_rough")
@patch("onapsdk.sdc2.pnf.Pnf._get_archived_rough")
def test_get_all_rough(mock_get_archived, mock_get_active):
    Pnf._get_all_rough()
    mock_get_archived.assert_called_once()
    mock_get_active.assert_called_once()


@patch("onapsdk.sdc2.pnf.Pnf._get_all_rough")
@patch("onapsdk.sdc2.pnf.Pnf.get_by_name_and_version")
def test_get_by_name(mock_get_by_name_and_version, mock_get_all_rough):
    mock_get_all_rough.return_value = []
    with raises(ResourceNotFound):
        Pnf.get_by_name("test_1")

    mock_get_all_rough.return_value = [
        {
            "name": "not_test_1",
            "version": "1.0"
        }
    ]
    with raises(ResourceNotFound):
        Pnf.get_by_name("test_1")

    mock_get_all_rough.return_value = [
        {
            "name": "not_test_1",
            "version": "1.0"
        },
        {
            "name": "test_1",
            "version": "1.0"
        }
    ]
    Pnf.get_by_name("test_1")
    mock_get_by_name_and_version.assert_called_once_with("test_1", "1.0")

    mock_get_by_name_and_version.reset_mock()
    mock_get_all_rough.return_value = [
        {
            "name": "not_test_1",
            "version": "1.0"
        },
        {
            "name": "test_1",
            "version": "1.0"
        },
        {
            "name": "test_1",
            "version": "2.0"
        }
    ]
    Pnf.get_by_name("test_1")
    mock_get_by_name_and_version.assert_called_once_with("test_1", "2.0")


@patch("onapsdk.sdc2.pnf.Pnf.send_message")
def test_delete(mock_send_message_json):
    pnf = Pnf(name="test_pnf", unique_id="test_pnf_unique_id")
    pnf.delete()
    mock_send_message_json.assert_called_once()
    method, log, url = mock_send_message_json.mock_calls[0].args
    assert method == "DELETE"
    assert "test_pnf" in log
    assert url.endswith("test_pnf_unique_id")


@patch("onapsdk.sdc2.pnf.Pnf.send_message")
def test_archive(mock_send_message_json):
    pnf = Pnf(name="test_pnf", unique_id="test_pnf_unique_id")
    pnf.archive()
    mock_send_message_json.assert_called_once()
    method, log, url = mock_send_message_json.mock_calls[0].args
    assert method == "POST"
    assert "test_pnf" in log
    assert url.endswith("test_pnf_unique_id/archive")


@patch("onapsdk.sdc2.pnf.Pnf._get_all_rough")
@patch("onapsdk.sdc2.pnf.Pnf.get_by_name_and_version")
def test_get_all(mock_get_by_name_and_version, mock_get_all_rough):
    mock_get_all_rough.return_value = []
    Pnf.get_all()
    mock_get_by_name_and_version.assert_not_called()

    mock_get_all_rough.return_value = [
        {
            "name": "test_pnf_1",
            "version": "1.0"
        }
    ]
    list(Pnf.get_all())
    mock_get_by_name_and_version.assert_called_once_with("test_pnf_1", "1.0")

    mock_get_by_name_and_version.reset_mock()
    mock_get_all_rough.return_value = (
        {
            "name": f"test_pnf_{idx}",
            "version": f"{idx}.0"
        } for idx in range(100)
    )
    list(Pnf.get_all())
    assert len(mock_get_by_name_and_version.mock_calls) == 100


@patch("onapsdk.sdc2.pnf.Pnf.send_message_json")
def test_get_active_rough(mock_send_message_json):
    mock_send_message_json.return_value = {"resources": []}
    assert(len(list(Pnf._get_active_rough()))) == 0

    mock_send_message_json.return_value = {"resources": [
        {
            "resourceType": "VF"
        },
        {
            "resourceType": "PNF"
        },
        {
            "resourceType": "VL"
        }
    ]}
    assert(len(list(Pnf._get_active_rough()))) == 1


@patch("onapsdk.sdc2.pnf.Pnf.send_message_json")
def test_get_archive_rough(mock_send_message_json):
    mock_send_message_json.return_value = {"resources": []}
    assert(len(list(Pnf._get_archived_rough()))) == 0

    mock_send_message_json.return_value = {"resources": [
        {
            "resourceType": "VF"
        },
        {
            "resourceType": "PNF"
        },
        {
            "resourceType": "VL"
        }
    ]}
    assert(len(list(Pnf._get_archived_rough()))) == 1


def test_get_by_name_and_version_endpoint():
    for i in range(1000):
        assert Pnf.get_by_name_and_version_endpoint(
            name=f"pnf_{i}",
            version=f"v{i}.0").endswith(
                f"catalog/resources/resourceName/pnf_{i}/resourceVersion/v{i}.0")


def test_add_deployment_artifact_endpoint():
    for _ in range(10**3):
        object_id: str = str(uuid4())
        assert Pnf.add_deployment_artifact_endpoint(
            object_id=object_id
        ) == f"sdc2/rest/v1/catalog/resources/{object_id}/artifacts"


def test_update():
    pnf = Pnf(
        name=str(uuid4()),
        unique_id=str(uuid4()),
        uuid=str(uuid4()),
        invariant_uuid=str(uuid4()),
        version=str(uuid4()),
        last_update_date=randint(0, maxsize),
        lifecycle_state=choice(list(LifecycleState)),
        last_updater_user_id=str(uuid4()),
        all_versions=[str(uuid4()) for _ in range(10**3)]
    )
    update_dict = {
        "uniqueId": str(uuid4()),
        "uuid": str(uuid4()),
        "invariantUUID": str(uuid4()),
        "version": str(uuid4()),
        "lastUpdateDate": randint(0, maxsize),
        "lifecycleState": choice(list(LifecycleState)),
        "lastUpdaterUserId": str(uuid4()),
        "allVersions": [str(uuid4()) for _ in range(10**3)]
    }
    pnf.update(update_dict)
    assert pnf.unique_id == update_dict["uniqueId"]
    assert pnf.uuid == update_dict["uuid"]
    assert pnf.invariant_uuid == update_dict["invariantUUID"]
    assert pnf.version == update_dict["version"]
    assert pnf.last_update_date == update_dict["lastUpdateDate"]
    assert pnf.lifecycle_state == update_dict["lifecycleState"]
    assert pnf.last_updater_user_id == update_dict["lastUpdaterUserId"]
    assert pnf.all_versions == update_dict["allVersions"]


@patch("onapsdk.sdc2.pnf.Pnf.send_message_json")
@patch("onapsdk.sdc2.pnf.Pnf.update")
def test_lifecycle_operation(mock_update, mock_send_message_json):
    for lifecycle_operation in LifecycleOperation:
        mock_send_message_json.reset_mock()
        mock_update.reset_mock()
        return_dict = {
            "uniqueId": str(uuid4()),
            "uuid": str(uuid4()),
            "invariantUUID": str(uuid4()),
            "version": str(uuid4()),
            "lastUpdateDate": randint(0, maxsize),
            "lifecycleState": choice(list(LifecycleState)),
            "lastUpdaterUserId": str(uuid4()),
            "allVersions": [str(uuid4()) for _ in range(10**3)]
        }
        mock_send_message_json.return_value = return_dict
        pnf_unique_id = str(uuid4())
        pnf = Pnf(
            name=str(uuid4()),
            unique_id=pnf_unique_id
        )
        pnf.lifecycle_operation(lifecycle_operation)
        mock_send_message_json.assert_called_once()
        method, log, url = mock_send_message_json.mock_calls[0].args
        data = mock_send_message_json.mock_calls[0].kwargs["data"]
        assert method == "POST"
        assert log.startswith(f"Request lifecycle operation {lifecycle_operation}")
        assert url.endswith(f"sdc2/rest/v1/catalog/resources/{pnf_unique_id}/lifecycleState/{lifecycle_operation}")
        assert json.loads(data)["userRemarks"] == str(lifecycle_operation).lower()
        mock_update.assert_called_once_with(return_dict)


@patch("onapsdk.sdc2.pnf.Pnf.send_message_json")
@patch("onapsdk.sdc2.pnf.Pnf.get_by_name_and_version_endpoint")
def test_get_by_name_and_version(mock_get_endpoint, mock_send_message_json):
    for name, version in [(str(uuid4()), str(uuid4())) for _ in range(10**2)]:
        mock_send_message_json.reset_mock()
        mock_send_message_json.return_value = {
            "uniqueId": str(uuid4()),
            "uuid": str(uuid4()),
            "invariantUUID": str(uuid4()),
            "version": str(uuid4()),
            "lastUpdateDate": randint(0, maxsize),
            "lifecycleState": choice(list(LifecycleState)),
            "lastUpdaterUserId": str(uuid4()),
            "allVersions": [str(uuid4()) for _ in range(10**2)],
            "archived": choice([True, False]),
            "creationDate": randint(0, maxsize),
            "componentType": str(uuid4()),
            "description": str(uuid4()),
            "icon": str(uuid4()),
            "name": str(uuid4()),
            "systemName": str(uuid4()),
            "tags": [str(uuid4()) for _ in range(10**2)],
        }
        mock_get_endpoint.reset_mock()
        mock_get_endpoint.return_value = f"{name}/{version}"
        Pnf.get_by_name_and_version(name, version)
        mock_send_message_json.assert_called_once()
        method, log, _ = mock_send_message_json.mock_calls[0].args
        assert method == "GET"
        assert log == "Get Pnf by name and version"
        mock_get_endpoint.assert_called_once_with(name, version)


@patch("onapsdk.sdc2.pnf.Pnf.send_message_json")
def test_add_deployment_artifact(mock_send_message_json):
    with NamedTemporaryFile() as temp_file:
        temp_file.write(b"Hello world!")
        temp_file.seek(0)

        pnf = Pnf(name=str(uuid4()), unique_id=str(uuid4()))
        pnf.add_deployment_artifact(
            str(uuid4()),
            str(uuid4()),
            str(uuid4()),
            temp_file.name
        )
        mock_send_message_json.assert_called_once()


@patch("onapsdk.sdc2.pnf.Pnf.send_message_json")
@patch("onapsdk.sdc2.sdc_resource.ComponentInstance.create_from_api_response")
def test_add_deployment_artifact(mock_create_component_instance, mock_send_message_json):
    pnf = Pnf(name=str(uuid4()), unique_id=str(uuid4()))
    mock_send_message_json.return_value = []
    assert len(list(pnf.component_instances)) == 0
    mock_send_message_json.assert_called_once_with(
        "GET",
        "Get Pnf component instances",
        f"{pnf.base_back_url}/sdc2/rest/v1/catalog/resources/{pnf.unique_id}/componentInstances"
    )

    mock_send_message_json.return_value = [{}]
    assert len(list(pnf.component_instances)) == 1
    mock_create_component_instance.assert_called_once_with({}, pnf)


@patch("onapsdk.sdc2.pnf.Pnf.component_instances", new_callable=PropertyMock)
def test_get_component_by_name(mock_component_instances):
    ComponentInstance = namedtuple("ComponentInstance", ["component_name"])

    pnf = Pnf(name="test_component_instances")
    mock_component_instances.return_value = []
    assert pnf.get_component_by_name("test_name") is None

    mock_component_instances.return_value = [ComponentInstance(component_name="test_name")]
    assert pnf.get_component_by_name("test_name") is not None
    assert pnf.get_component_by_name("test_name").component_name == "test_name"

    mock_component_instances.return_value = [ComponentInstance(component_name=f"test_name_{i}") for i in range(10**2)]
    assert pnf.get_component_by_name("test_name") is None

    random_name = f"test_name_{choice(range(10**2))}"
    assert pnf.get_component_by_name(random_name) is not None
    assert pnf.get_component_by_name(random_name).component_name == random_name


@patch("onapsdk.sdc2.pnf.Pnf.send_message_json")
@patch("onapsdk.sdc2.pnf.Pnf.get_create_payload")
@patch("onapsdk.sdc2.pnf.Pnf.create_from_api_response")
def test_create(mock_create_from_api_response, mock_get_create_payload, mock_send_message_json):
    mock_get_create_payload.return_value = "test_payload"
    Pnf.create(name="test_pnf")
    mock_send_message_json.assert_called_once_with(
        "POST",
        "Create PNF test_pnf",
        Pnf.CREATE_ENDPOINT,
        data="test_payload"
    )


@patch("onapsdk.sdc2.sdc_resource.ResourceCategory.get_by_name")
def test_get_create_payload(mock_resource_category_get_by_name):
    mock_vsp = MagicMock(csar_uuid="test_vsp_csar_uuid")
    mock_vendor = MagicMock()
    mock_vendor.name = "test_vendor_name"
    resource_category_mock = MagicMock()
    resource_category_mock.name = "test_category"
    resource_category_mock.unique_id = "category_unique_id"
    resource_subcategory_mock = MagicMock()
    resource_subcategory_mock.name = "test_subcategory"
    resource_subcategory_mock.unique_id = "subcategory_unique_id"
    resource_category_mock.get_subcategory.return_value = resource_subcategory_mock
    mock_resource_category_get_by_name.return_value = resource_category_mock

    create_payload = json.loads(Pnf.get_create_payload(
        name="test_pnf",
        vsp=mock_vsp,
        vendor=mock_vendor
    ))
    assert create_payload["name"] == "test_pnf"
    assert create_payload["contactId"] == "cs0008"
    assert create_payload["componentType"] == "RESOURCE"
    assert create_payload["csarUUID"] == "test_vsp_csar_uuid"
    assert create_payload["csarVersion"] == "1.0"
    assert create_payload["categories"][0]["name"] == "test_category"
    assert create_payload["categories"][0]["uniqueId"] == "category_unique_id"
    assert create_payload["categories"][0]["subcategories"][0]["name"] == "test_subcategory"
    assert create_payload["categories"][0]["subcategories"][0]["uniqueId"] == "subcategory_unique_id"
    assert create_payload["resourceType"] == "PNF"
    assert create_payload["description"] == "ONAP SDK Resource"
    assert create_payload["vendorName"] == "test_vendor_name"
    assert create_payload["vendorRelease"] == "1.0"

    create_payload = json.loads(Pnf.get_create_payload(
        name="test_pnf",
        vsp=mock_vsp,
        vendor=mock_vendor,
        description="test description"
    ))
    assert create_payload["name"] == "test_pnf"
    assert create_payload["contactId"] == "cs0008"
    assert create_payload["componentType"] == "RESOURCE"
    assert create_payload["csarUUID"] == "test_vsp_csar_uuid"
    assert create_payload["csarVersion"] == "1.0"
    assert create_payload["categories"][0]["name"] == "test_category"
    assert create_payload["categories"][0]["uniqueId"] == "category_unique_id"
    assert create_payload["categories"][0]["subcategories"][0]["name"] == "test_subcategory"
    assert create_payload["categories"][0]["subcategories"][0]["uniqueId"] == "subcategory_unique_id"
    assert create_payload["resourceType"] == "PNF"
    assert create_payload["description"] == "test description"
    assert create_payload["vendorName"] == "test_vendor_name"
    assert create_payload["vendorRelease"] == "1.0"