2 # -*- coding: utf-8 -*-
12 from time
import sleep
15 __author__
= "Alfonso Tierno, alfonso.tiernosepulveda@telefonica.com"
16 __date__
= "$2018-03-01$"
18 version_date
= "Oct 2018"
22 print("Usage: ", sys
.argv
[0], "[options]")
23 print(" Performs system tests over running NBI. It can be used for real OSM test using option '--test-osm'")
24 print(" If this is the case env variables 'OSMNBITEST_VIM_NAME' must be suplied to create a VIM if not exist "
25 "where deployment is done")
27 print(" -h|--help: shows this help")
28 print(" --insecure: Allows non trusted https NBI server")
29 print(" --list: list available tests")
30 print(" --manual-check: Deployment tests stop after deployed to allow manual inspection. Only make sense with "
32 print(" -p|--password PASSWORD: NBI access password. 'admin' by default")
33 print(" ---project PROJECT: NBI access project. 'admin' by default")
34 print(" --test TEST[,...]: Execute only a test or a comma separated list of tests")
35 print(" --params key=val: params to the previous test. key can be vnfd-files, nsd-file, ns-name, ns-config")
36 print(" --test-osm: If missing this test is intended for NBI only, no other OSM components are expected. Use "
37 "this flag to test the system. LCM and RO components are expected to be up and running")
38 print(" --timeout TIMEOUT: General NBI timeout, by default {}s".format(timeout
))
39 print(" --timeout-deploy TIMEOUT: Timeout used for getting NS deployed, by default {}s".format(timeout_deploy
))
40 print(" --timeout-configure TIMEOUT: Timeout used for getting NS deployed and configured,"
41 " by default {}s".format(timeout_configure
))
42 print(" -u|--user USERNAME: NBI access username. 'admin' by default")
43 print(" --url URL: complete NBI server URL. 'https//localhost:9999/osm' by default")
44 print(" -v|--verbose print debug information, can be used several times")
45 print(" --no-verbose remove verbosity")
46 print(" --version: prints current version")
47 print("ENV variables used for real deployment tests with option osm-test.")
48 print(" export OSMNBITEST_VIM_NAME=vim-name")
49 print(" export OSMNBITEST_VIM_URL=vim-url")
50 print(" export OSMNBITEST_VIM_TYPE=vim-type")
51 print(" export OSMNBITEST_VIM_TENANT=vim-tenant")
52 print(" export OSMNBITEST_VIM_USER=vim-user")
53 print(" export OSMNBITEST_VIM_PASSWORD=vim-password")
54 print(" export OSMNBITEST_VIM_CONFIG=\"vim-config\"")
55 print(" export OSMNBITEST_NS_NAME=\"vim-config\"")
59 r_header_json
= {"Content-type": "application/json"}
61 "Content-type": "application/json",
62 "Accept": "application/json",
64 r_header_yaml
= {"Content-type": "application/yaml"}
66 "Content-type": "application/yaml",
67 "Accept": "application/yaml",
69 r_header_text
= {"Content-type": "text/plain"}
70 r_header_octect
= {"Content-type": "application/octet-stream"}
72 "Accept": "text/plain",
74 r_header_zip
= {"Content-type": "application/zip"}
76 "Accept": "application/zip",
79 "Accept": "application/yaml", "Content-type": "application/zip"
83 # test ones authorized
84 test_authorized_list
= (
85 ("AU1", "Invalid vnfd id", "GET", "/vnfpkgm/v1/vnf_packages/non-existing-id",
86 headers_json
, None, 404, r_header_json
, "json"),
87 ("AU2", "Invalid nsd id", "GET", "/nsd/v1/ns_descriptors/non-existing-id",
88 headers_yaml
, None, 404, r_header_yaml
, "yaml"),
89 ("AU3", "Invalid nsd id", "DELETE", "/nsd/v1/ns_descriptors_content/non-existing-id",
90 headers_yaml
, None, 404, r_header_yaml
, "yaml"),
92 timeout
= 120 # general timeout
93 timeout_deploy
= 60*10 # timeout for NS deploying without charms
94 timeout_configure
= 60*20 # timeout for NS deploying and configuring
97 class TestException(Exception):
102 def __init__(self
, url_base
, header_base
=None, verify
=False, user
="admin", password
="admin", project
="admin"):
103 self
.url_base
= url_base
104 if header_base
is None:
105 self
.header_base
= {}
107 self
.header_base
= header_base
.copy()
108 self
.s
= requests
.session()
109 self
.s
.headers
= self
.header_base
113 self
.password
= password
114 self
.project
= project
116 # contains ID of tests obtained from Location response header. "" key contains last obtained id
118 self
.old_test_description
= ""
120 def set_header(self
, header
):
121 self
.s
.headers
.update(header
)
123 def unset_header(self
, key
):
124 if key
in self
.s
.headers
:
125 del self
.s
.headers
[key
]
127 def test(self
, name
, description
, method
, url
, headers
, payload
, expected_codes
, expected_headers
,
128 expected_payload
, store_file
=None):
130 Performs an http request and check http code response. Exit if different than allowed. It get the returned id
131 that can be used by following test in the URL with {name} where name is the name of the test
132 :param name: short name of the test
133 :param description: description of the test
134 :param method: HTTP method: GET,PUT,POST,DELETE,...
135 :param url: complete URL or relative URL
136 :param headers: request headers to add to the base headers
137 :param payload: Can be a dict, transformed to json, a text or a file if starts with '@'
138 :param expected_codes: expected response codes, can be int, int tuple or int range
139 :param expected_headers: expected response headers, dict with key values
140 :param expected_payload: expected payload, 0 if empty, 'yaml', 'json', 'text', 'zip', 'octet-stream'
141 :param store_file: filename to store content
142 :return: requests response
147 self
.s
= requests
.session()
151 elif not url
.startswith("http"):
152 url
= self
.url_base
+ url
154 var_start
= url
.find("<") + 1
156 var_end
= url
.find(">", var_start
)
159 var_name
= url
[var_start
:var_end
]
160 if var_name
in self
.test_ids
:
161 url
= url
[:var_start
-1] + self
.test_ids
[var_name
] + url
[var_end
+1:]
162 var_start
+= len(self
.test_ids
[var_name
])
163 var_start
= url
.find("<", var_start
) + 1
165 if isinstance(payload
, str):
166 if payload
.startswith("@"):
168 file_name
= payload
[1:]
169 if payload
.startswith("@b"):
171 file_name
= payload
[2:]
172 with
open(file_name
, mode
) as f
:
174 elif isinstance(payload
, dict):
175 payload
= json
.dumps(payload
)
177 test_description
= "Test {} {} {} {}".format(name
, description
, method
, url
)
178 if self
.old_test_description
!= test_description
:
179 self
.old_test_description
= test_description
180 logger
.warning(test_description
)
182 if expected_payload
in ("zip", "octet-string") or store_file
:
184 r
= getattr(self
.s
, method
.lower())(url
, data
=payload
, headers
=headers
, verify
=self
.verify
, stream
=stream
)
185 if expected_payload
in ("zip", "octet-string") or store_file
:
186 logger
.debug("RX {}".format(r
.status_code
))
188 logger
.debug("RX {}: {}".format(r
.status_code
, r
.text
))
192 if isinstance(expected_codes
, int):
193 expected_codes
= (expected_codes
,)
194 if r
.status_code
not in expected_codes
:
196 "Got status {}. Expected {}. {}".format(r
.status_code
, expected_codes
, r
.text
))
199 for header_key
, header_val
in expected_headers
.items():
200 if header_key
.lower() not in r
.headers
:
201 raise TestException("Header {} not present".format(header_key
))
202 if header_val
and header_val
.lower() not in r
.headers
[header_key
]:
203 raise TestException("Header {} does not contain {} but {}".format(header_key
, header_val
,
204 r
.headers
[header_key
]))
206 if expected_payload
is not None:
207 if expected_payload
== 0 and len(r
.content
) > 0:
208 raise TestException("Expected empty payload")
209 elif expected_payload
== "json":
212 except Exception as e
:
213 raise TestException("Expected json response payload, but got Exception {}".format(e
))
214 elif expected_payload
== "yaml":
216 yaml
.safe_load(r
.text
)
217 except Exception as e
:
218 raise TestException("Expected yaml response payload, but got Exception {}".format(e
))
219 elif expected_payload
in ("zip", "octet-string"):
220 if len(r
.content
) == 0:
221 raise TestException("Expected some response payload, but got empty")
223 # tar = tarfile.open(None, 'r:gz', fileobj=r.raw)
224 # for tarinfo in tar:
225 # tarname = tarinfo.name
227 # except Exception as e:
228 # raise TestException("Expected zip response payload, but got Exception {}".format(e))
229 elif expected_payload
== "text":
230 if len(r
.content
) == 0:
231 raise TestException("Expected some response payload, but got empty")
234 with
open(store_file
, 'wb') as fd
:
235 for chunk
in r
.iter_content(chunk_size
=128):
238 location
= r
.headers
.get("Location")
240 _id
= location
[location
.rfind("/") + 1:]
242 self
.test_ids
[name
] = str(_id
)
243 self
.test_ids
[""] = str(_id
) # last id
245 except TestException
as e
:
249 r_status_code
= r
.status_code
251 logger
.error("{} \nRX code{}: {}".format(e
, r_status_code
, r_text
))
254 logger
.error("Cannot open file {}".format(e
))
257 def get_autorization(self
): # user=None, password=None, project=None):
258 if self
.token
: # and self.user == user and self.password == password and self.project == project:
261 # self.password = password
262 # self.project = project
263 r
= self
.test("TOKEN", "Obtain token", "POST", "/admin/v1/tokens", headers_json
,
264 {"username": self
.user
, "password": self
.password
, "project_id": self
.project
},
265 (200, 201), r_header_json
, "json")
267 self
.token
= response
["id"]
268 self
.set_header({"Authorization": "Bearer {}".format(self
.token
)})
270 def remove_authorization(self
):
272 self
.test("TOKEN_DEL", "Delete token", "DELETE", "/admin/v1/tokens/{}".format(self
.token
), headers_json
,
273 None, (200, 201, 204), None, None)
275 self
.unset_header("Authorization")
277 def get_create_vim(self
, test_osm
):
280 self
.get_autorization()
282 vim_name
= os
.environ
.get("OSMNBITEST_VIM_NAME")
285 "Needed to define OSMNBITEST_VIM_XXX variables to create a real VIM for deployment")
289 r
= self
.test("_VIMGET1", "Get VIM ID", "GET", "/admin/v1/vim_accounts?name={}".format(vim_name
), headers_json
,
290 None, 200, r_header_json
, "json")
293 return vims
[0]["_id"]
296 # check needed environ parameters:
297 if not os
.environ
.get("OSMNBITEST_VIM_URL") or not os
.environ
.get("OSMNBITEST_VIM_TENANT"):
298 raise TestException("Env OSMNBITEST_VIM_URL and OSMNBITEST_VIM_TENANT are needed for create a real VIM"
299 " to deploy on whit the --test-osm option")
300 vim_data
= "{{schema_version: '1.0', name: '{}', vim_type: {}, vim_url: '{}', vim_tenant_name: '{}', "\
301 "vim_user: {}, vim_password: {}".format(vim_name
,
302 os
.environ
.get("OSMNBITEST_VIM_TYPE", "openstack"),
303 os
.environ
.get("OSMNBITEST_VIM_URL"),
304 os
.environ
.get("OSMNBITEST_VIM_TENANT"),
305 os
.environ
.get("OSMNBITEST_VIM_USER"),
306 os
.environ
.get("OSMNBITEST_VIM_PASSWORD"))
307 if os
.environ
.get("OSMNBITEST_VIM_CONFIG"):
308 vim_data
+= " ,config: {}".format(os
.environ
.get("OSMNBITEST_VIM_CONFIG"))
311 vim_data
= "{schema_version: '1.0', name: fakeVim, vim_type: openstack, vim_url: 'http://10.11.12.13/fake'"\
312 ", vim_tenant_name: 'vimtenant', vim_user: vimuser, vim_password: vimpassword}"
313 r
= self
.test("_VIMGET2", "Create VIM", "POST", "/admin/v1/vim_accounts", headers_yaml
, vim_data
,
314 (201), {"Location": "/admin/v1/vim_accounts/", "Content-Type": "application/yaml"}, "yaml")
315 location
= r
.headers
.get("Location")
316 return location
[location
.rfind("/") + 1:]
319 class TestNonAuthorized
:
320 description
= "test invalid URLs. methods and no authorization"
323 def run(engine
, test_osm
, manual_check
, test_params
=None):
324 engine
.remove_authorization()
325 test_not_authorized_list
= (
326 ("NA1", "Invalid token", "GET", "/admin/v1/users", headers_json
, None, 401, r_header_json
, "json"),
327 ("NA2", "Invalid URL", "POST", "/admin/v1/nonexist", headers_yaml
, None, 405, r_header_yaml
, "yaml"),
328 ("NA3", "Invalid version", "DELETE", "/admin/v2/users", headers_yaml
, None, 405, r_header_yaml
, "yaml"),
330 for t
in test_not_authorized_list
:
334 class TestUsersProjects
:
335 description
= "test project and user creation"
338 def run(engine
, test_osm
, manual_check
, test_params
=None):
339 engine
.get_autorization()
340 engine
.test("PU1", "Create project non admin", "POST", "/admin/v1/projects", headers_json
, {"name": "P1"},
341 (201, 204), {"Location": "/admin/v1/projects/", "Content-Type": "application/json"}, "json")
342 engine
.test("PU2", "Create project admin", "POST", "/admin/v1/projects", headers_json
,
343 {"name": "Padmin", "admin": True}, (201, 204),
344 {"Location": "/admin/v1/projects/", "Content-Type": "application/json"}, "json")
345 engine
.test("PU3", "Create project bad format", "POST", "/admin/v1/projects", headers_json
, {"name": 1}, 422,
346 r_header_json
, "json")
347 engine
.test("PU4", "Create user with bad project", "POST", "/admin/v1/users", headers_json
,
348 {"username": "U1", "projects": ["P1", "P2", "Padmin"], "password": "pw1"}, 409,
349 r_header_json
, "json")
350 engine
.test("PU5", "Create user with bad project and force", "POST", "/admin/v1/users?FORCE=True", headers_json
,
351 {"username": "U1", "projects": ["P1", "P2", "Padmin"], "password": "pw1"}, 201,
352 {"Location": "/admin/v1/users/", "Content-Type": "application/json"}, "json")
353 engine
.test("PU6", "Create user 2", "POST", "/admin/v1/users", headers_json
,
354 {"username": "U2", "projects": ["P1"], "password": "pw2"}, 201,
355 {"Location": "/admin/v1/users/", "Content-Type": "application/json"}, "json")
357 engine
.test("PU7", "Edit user U1, delete P2 project", "PATCH", "/admin/v1/users/U1", headers_json
,
358 {"projects": {"$'P2'": None}}, 204, None, None)
359 res
= engine
.test("PU1", "Check user U1, contains the right projects", "GET", "/admin/v1/users/U1",
360 headers_json
, None, 200, None, json
)
363 expected_projects
= ["P1", "Padmin"]
364 if u1
["projects"] != expected_projects
:
365 raise TestException("User content projects '{}' different than expected '{}'. Edition has not done"
366 " properly".format(u1
["projects"], expected_projects
))
368 engine
.test("PU8", "Edit user U1, set Padmin as default project", "PUT", "/admin/v1/users/U1", headers_json
,
369 {"projects": {"$'Padmin'": None, "$+[0]": "Padmin"}}, 204, None, None)
370 res
= engine
.test("PU1", "Check user U1, contains the right projects", "GET", "/admin/v1/users/U1",
371 headers_json
, None, 200, None, json
)
374 expected_projects
= ["Padmin", "P1"]
375 if u1
["projects"] != expected_projects
:
376 raise TestException("User content projects '{}' different than expected '{}'. Edition has not done"
377 " properly".format(u1
["projects"], expected_projects
))
379 engine
.test("PU9", "Edit user U1, change password", "PATCH", "/admin/v1/users/U1", headers_json
,
380 {"password": "pw1_new"}, 204, None, None)
382 engine
.test("PU10", "Change to project P1 non existing", "POST", "/admin/v1/tokens/", headers_json
,
383 {"project_id": "P1"}, 401, r_header_json
, "json")
385 res
= engine
.test("PU1", "Change to user U1 project P1", "POST", "/admin/v1/tokens", headers_json
,
386 {"username": "U1", "password": "pw1_new", "project_id": "P1"}, (200, 201),
387 r_header_json
, "json")
388 response
= res
.json()
389 engine
.set_header({"Authorization": "Bearer {}".format(response
["id"])})
391 engine
.test("PU11", "Edit user projects non admin", "PUT", "/admin/v1/users/U1", headers_json
,
392 {"projects": {"$'P1'": None}}, 401, r_header_json
, "json")
393 engine
.test("PU12", "Add new project non admin", "POST", "/admin/v1/projects", headers_json
,
394 {"name": "P2"}, 401, r_header_json
, "json")
395 engine
.test("PU13", "Add new user non admin", "POST", "/admin/v1/users", headers_json
,
396 {"username": "U3", "projects": ["P1"], "password": "pw3"}, 401,
397 r_header_json
, "json")
399 res
= engine
.test("PU14", "Change to user U1 project Padmin", "POST", "/admin/v1/tokens", headers_json
,
400 {"project_id": "Padmin"}, (200, 201), r_header_json
, "json")
401 response
= res
.json()
402 engine
.set_header({"Authorization": "Bearer {}".format(response
["id"])})
404 engine
.test("PU15", "Add new project admin", "POST", "/admin/v1/projects", headers_json
, {"name": "P2"},
405 (201, 204), {"Location": "/admin/v1/projects/", "Content-Type": "application/json"}, "json")
406 engine
.test("PU16", "Add new user U3 admin", "POST", "/admin/v1/users",
407 headers_json
, {"username": "U3", "projects": ["P2"], "password": "pw3"}, (201, 204),
408 {"Location": "/admin/v1/users/", "Content-Type": "application/json"}, "json")
409 engine
.test("PU17", "Edit user projects admin", "PUT", "/admin/v1/users/U3", headers_json
,
410 {"projects": ["P2"]}, 204, None, None)
412 engine
.test("PU18", "Delete project P2 conflict", "DELETE", "/admin/v1/projects/P2", headers_json
, None, 409,
413 r_header_json
, "json")
414 engine
.test("PU19", "Delete project P2 forcing", "DELETE", "/admin/v1/projects/P2?FORCE=True", headers_json
,
415 None, 204, None, None)
417 engine
.test("PU20", "Delete user U1. Conflict deleting own user", "DELETE", "/admin/v1/users/U1", headers_json
,
418 None, 409, r_header_json
, "json")
419 engine
.test("PU21", "Delete user U2", "DELETE", "/admin/v1/users/U2", headers_json
, None, 204, None, None)
420 engine
.test("PU22", "Delete user U3", "DELETE", "/admin/v1/users/U3", headers_json
, None, 204, None, None)
422 engine
.remove_authorization() # To force get authorization
423 engine
.get_autorization()
424 engine
.test("PU23", "Delete user U1", "DELETE", "/admin/v1/users/U1", headers_json
, None, 204, None, None)
425 engine
.test("PU24", "Delete project P1", "DELETE", "/admin/v1/projects/P1", headers_json
, None, 204, None, None)
426 engine
.test("PU25", "Delete project Padmin", "DELETE", "/admin/v1/projects/Padmin", headers_json
, None, 204,
431 description
= "Creates/edit/delete fake VIMs and SDN controllers"
435 "schema_version": "1.0",
436 "schema_type": "No idea",
438 "description": "Descriptor name",
439 "vim_type": "openstack",
440 "vim_url": "http://localhost:/vim",
441 "vim_tenant_name": "vimTenant",
443 "vim_password": "password",
444 "config": {"config_param": 1}
448 "description": "sdn-description",
449 "dpid": "50:50:52:54:00:94:21:21",
450 "ip": "192.168.15.17",
452 "type": "opendaylight",
457 self
.port_mapping
= [
458 {"compute_node": "compute node 1",
459 "ports": [{"pci": "0000:81:00.0", "switch_port": "port-2/1", "switch_mac": "52:54:00:94:21:21"},
460 {"pci": "0000:81:00.1", "switch_port": "port-2/2", "switch_mac": "52:54:00:94:21:22"}
462 {"compute_node": "compute node 2",
463 "ports": [{"pci": "0000:81:00.0", "switch_port": "port-2/3", "switch_mac": "52:54:00:94:21:23"},
464 {"pci": "0000:81:00.1", "switch_port": "port-2/4", "switch_mac": "52:54:00:94:21:24"}
468 def run(self
, engine
, test_osm
, manual_check
, test_params
=None):
470 vim_bad
= self
.vim
.copy()
473 engine
.get_autorization()
474 engine
.test("FVIM1", "Create VIM", "POST", "/admin/v1/vim_accounts", headers_json
, self
.vim
, (201, 204),
475 {"Location": "/admin/v1/vim_accounts/", "Content-Type": "application/json"}, "json")
476 engine
.test("FVIM2", "Create VIM without name, bad schema", "POST", "/admin/v1/vim_accounts", headers_json
,
477 vim_bad
, 422, None, headers_json
)
478 engine
.test("FVIM3", "Create VIM name repeated", "POST", "/admin/v1/vim_accounts", headers_json
, self
.vim
,
479 409, None, headers_json
)
480 engine
.test("FVIM4", "Show VIMs", "GET", "/admin/v1/vim_accounts", headers_yaml
, None, 200, r_header_yaml
,
482 engine
.test("FVIM5", "Show VIM", "GET", "/admin/v1/vim_accounts/<FVIM1>", headers_yaml
, None, 200,
483 r_header_yaml
, "yaml")
486 engine
.test("FVIM6", "Delete VIM", "DELETE", "/admin/v1/vim_accounts/<FVIM1>?FORCE=True", headers_yaml
,
488 engine
.test("FVIM7", "Check VIM is deleted", "GET", "/admin/v1/vim_accounts/<FVIM1>", headers_yaml
, None,
489 404, r_header_yaml
, "yaml")
491 # delete and wait until is really deleted
492 engine
.test("FVIM6", "Delete VIM", "DELETE", "/admin/v1/vim_accounts/<FVIM1>", headers_yaml
, None, 202,
496 r
= engine
.test("FVIM7", "Check VIM is deleted", "GET", "/admin/v1/vim_accounts/<FVIM1>", headers_yaml
,
497 None, None, r_header_yaml
, "yaml")
498 if r
.status_code
== 404:
500 elif r
.status_code
== 200:
504 raise TestException("Vim created at 'FVIM1' is not delete after {} seconds".format(timeout
))
507 class TestVIMSDN(TestFakeVim
):
508 description
= "Creates VIM with SDN editing SDN controllers and port_mapping"
511 TestFakeVim
.__init
__(self
)
513 def run(self
, engine
, test_osm
, manual_check
, test_params
=None):
514 engine
.get_autorization()
516 engine
.test("VIMSDN1", "Create SDN", "POST", "/admin/v1/sdns", headers_json
, self
.sdn
, (201, 204),
517 {"Location": "/admin/v1/sdns/", "Content-Type": "application/json"}, "json")
520 engine
.test("VIMSDN2", "Edit SDN", "PATCH", "/admin/v1/sdns/<VIMSDN1>", headers_json
, {"name": "new_sdn_name"},
524 self
.vim
["config"]["sdn-controller"] = engine
.test_ids
["VIMSDN1"]
525 self
.vim
["config"]["sdn-port-mapping"] = self
.port_mapping
526 engine
.test("VIMSDN3", "Create VIM", "POST", "/admin/v1/vim_accounts", headers_json
, self
.vim
, (200, 204, 201),
527 {"Location": "/admin/v1/vim_accounts/", "Content-Type": "application/json"}, "json"),
529 self
.port_mapping
[0]["compute_node"] = "compute node XX"
530 engine
.test("VIMSDN4", "Edit VIM change port-mapping", "PUT", "/admin/v1/vim_accounts/<VIMSDN3>", headers_json
,
531 {"config": {"sdn-port-mapping": self
.port_mapping
}}, 204, None, None)
532 engine
.test("VIMSDN5", "Edit VIM remove port-mapping", "PUT", "/admin/v1/vim_accounts/<VIMSDN3>", headers_json
,
533 {"config": {"sdn-port-mapping": None}}, 204, None, None)
537 engine
.test("VIMSDN6", "Delete VIM remove port-mapping", "DELETE",
538 "/admin/v1/vim_accounts/<VIMSDN3>?FORCE=True", headers_json
, None, 202, None, 0)
539 engine
.test("VIMSDN7", "Delete SDNC", "DELETE", "/admin/v1/sdns/<VIMSDN1>?FORCE=True", headers_json
, None,
542 engine
.test("VIMSDN8", "Check VIM is deleted", "GET", "/admin/v1/vim_accounts/<VIMSDN3>", headers_yaml
,
543 None, 404, r_header_yaml
, "yaml")
544 engine
.test("VIMSDN9", "Check SDN is deleted", "GET", "/admin/v1/sdns/<VIMSDN1>", headers_yaml
, None,
545 404, r_header_yaml
, "yaml")
547 # delete and wait until is really deleted
548 engine
.test("VIMSDN6", "Delete VIM remove port-mapping", "DELETE", "/admin/v1/vim_accounts/<VIMSDN3>",
549 headers_json
, None, (202, 201, 204), None, 0)
550 engine
.test("VIMSDN7", "Delete SDN", "DELETE", "/admin/v1/sdns/<VIMSDN1>", headers_json
, None,
551 (202, 201, 204), None, 0)
554 r
= engine
.test("VIMSDN8", "Check VIM is deleted", "GET", "/admin/v1/vim_accounts/<VIMSDN3>",
555 headers_yaml
, None, None, r_header_yaml
, "yaml")
556 if r
.status_code
== 404:
558 elif r
.status_code
== 200:
562 raise TestException("Vim created at 'VIMSDN3' is not delete after {} seconds".format(timeout
))
564 r
= engine
.test("VIMSDN9", "Check SDNC is deleted", "GET", "/admin/v1/sdns/<VIMSDN1>",
565 headers_yaml
, None, None, r_header_yaml
, "yaml")
566 if r
.status_code
== 404:
568 elif r
.status_code
== 200:
572 raise TestException("SDNC created at 'VIMSDN1' is not delete after {} seconds".format(timeout
))
576 description
= "Base class for downloading descriptors from ETSI, onboard and deploy in real VIM"
587 self
.descriptor_url
= "https://osm-download.etsi.org/ftp/osm-3.0-three/2nd-hackfest/packages/"
588 self
.vnfd_filenames
= ("cirros_vnf.tar.gz",)
589 self
.nsd_filename
= "cirros_2vnf_ns.tar.gz"
590 self
.uses_configuration
= False
596 self
.passed_tests
= 0
599 def create_descriptors(self
, engine
):
600 temp_dir
= os
.path
.dirname(os
.path
.abspath(__file__
)) + "/temp/"
601 if not os
.path
.exists(temp_dir
):
602 os
.makedirs(temp_dir
)
603 for vnfd_filename
in self
.vnfd_filenames
:
604 if "/" in vnfd_filename
:
605 vnfd_filename_path
= vnfd_filename
606 if not os
.path
.exists(vnfd_filename_path
):
607 raise TestException("File '{}' does not exist".format(vnfd_filename_path
))
609 vnfd_filename_path
= temp_dir
+ vnfd_filename
610 if not os
.path
.exists(vnfd_filename_path
):
611 with
open(vnfd_filename_path
, "wb") as file:
612 response
= requests
.get(self
.descriptor_url
+ vnfd_filename
)
613 if response
.status_code
>= 300:
614 raise TestException("Error downloading descriptor from '{}': {}".format(
615 self
.descriptor_url
+ vnfd_filename
, response
.status_code
))
616 file.write(response
.content
)
617 if vnfd_filename_path
.endswith(".yaml"):
618 headers
= headers_yaml
620 headers
= headers_zip_yaml
621 if self
.step
% 2 == 0:
622 # vnfd CREATE AND UPLOAD in one step:
623 test_name
= "DEPLOY{}".format(self
.step
)
624 engine
.test(test_name
, "Onboard VNFD in one step", "POST",
625 "/vnfpkgm/v1/vnf_packages_content", headers
, "@b" + vnfd_filename_path
, 201,
626 {"Location": "/vnfpkgm/v1/vnf_packages_content/", "Content-Type": "application/yaml"}, yaml
)
627 self
.vnfds_test
.append(test_name
)
628 self
.vnfds_id
.append(engine
.test_ids
[test_name
])
631 # vnfd CREATE AND UPLOAD ZIP
632 test_name
= "DEPLOY{}".format(self
.step
)
633 engine
.test(test_name
, "Onboard VNFD step 1", "POST", "/vnfpkgm/v1/vnf_packages",
634 headers_json
, None, 201,
635 {"Location": "/vnfpkgm/v1/vnf_packages/", "Content-Type": "application/json"}, "json")
636 self
.vnfds_test
.append(test_name
)
637 self
.vnfds_id
.append(engine
.test_ids
[test_name
])
639 # location = r.headers["Location"]
640 # vnfd_id = location[location.rfind("/")+1:]
641 engine
.test("DEPLOY{}".format(self
.step
), "Onboard VNFD step 2 as ZIP", "PUT",
642 "/vnfpkgm/v1/vnf_packages/<>/package_content",
643 headers
, "@b" + vnfd_filename_path
, 204, None, 0)
646 if "/" in self
.nsd_filename
:
647 nsd_filename_path
= self
.nsd_filename
648 if not os
.path
.exists(nsd_filename_path
):
649 raise TestException("File '{}' does not exist".format(nsd_filename_path
))
651 nsd_filename_path
= temp_dir
+ self
.nsd_filename
652 if not os
.path
.exists(nsd_filename_path
):
653 with
open(nsd_filename_path
, "wb") as file:
654 response
= requests
.get(self
.descriptor_url
+ self
.nsd_filename
)
655 if response
.status_code
>= 300:
656 raise TestException("Error downloading descriptor from '{}': {}".format(
657 self
.descriptor_url
+ self
.nsd_filename
, response
.status_code
))
658 file.write(response
.content
)
659 if nsd_filename_path
.endswith(".yaml"):
660 headers
= headers_yaml
662 headers
= headers_zip_yaml
664 self
.nsd_test
= "DEPLOY" + str(self
.step
)
665 if self
.step
% 2 == 0:
666 # nsd CREATE AND UPLOAD in one step:
667 engine
.test("DEPLOY{}".format(self
.step
), "Onboard NSD in one step", "POST",
668 "/nsd/v1/ns_descriptors_content", headers
, "@b" + nsd_filename_path
, 201,
669 {"Location": "/nsd/v1/ns_descriptors_content/", "Content-Type": "application/yaml"}, yaml
)
672 # nsd CREATE AND UPLOAD ZIP
673 engine
.test("DEPLOY{}".format(self
.step
), "Onboard NSD step 1", "POST", "/nsd/v1/ns_descriptors",
674 headers_json
, None, 201,
675 {"Location": "/nsd/v1/ns_descriptors/", "Content-Type": "application/json"}, "json")
677 # location = r.headers["Location"]
678 # vnfd_id = location[location.rfind("/")+1:]
679 engine
.test("DEPLOY{}".format(self
.step
), "Onboard NSD step 2 as ZIP", "PUT",
680 "/nsd/v1/ns_descriptors/<>/nsd_content",
681 headers
, "@b" + nsd_filename_path
, 204, None, 0)
683 self
.nsd_id
= engine
.test_ids
[self
.nsd_test
]
685 def delete_descriptors(self
, engine
):
687 engine
.test("DEPLOY{}".format(self
.step
), "Delete NSSD SOL005", "DELETE",
688 "/nsd/v1/ns_descriptors/<{}>".format(self
.nsd_test
),
689 headers_yaml
, None, 204, None, 0)
691 for vnfd_test
in self
.vnfds_test
:
692 engine
.test("DEPLOY{}".format(self
.step
), "Delete VNFD SOL005", "DELETE",
693 "/vnfpkgm/v1/vnf_packages/<{}>".format(vnfd_test
), headers_yaml
, None, 204, None, 0)
696 def instantiate(self
, engine
, ns_data
):
697 ns_data_text
= yaml
.safe_dump(ns_data
, default_flow_style
=True, width
=256)
698 # create NS Two steps
699 r
= engine
.test("DEPLOY{}".format(self
.step
), "Create NS step 1", "POST", "/nslcm/v1/ns_instances",
700 headers_yaml
, ns_data_text
, 201,
701 {"Location": "nslcm/v1/ns_instances/", "Content-Type": "application/yaml"}, "yaml")
702 self
.ns_test
= "DEPLOY{}".format(self
.step
)
703 self
.ns_id
= engine
.test_ids
[self
.ns_test
]
704 engine
.test_ids
[self
.ns_test
]
706 r
= engine
.test("DEPLOY{}".format(self
.step
), "Instantiate NS step 2", "POST",
707 "/nslcm/v1/ns_instances/<{}>/instantiate".format(self
.ns_test
), headers_yaml
, ns_data_text
,
708 201, {"Location": "nslcm/v1/ns_lcm_op_occs/", "Content-Type": "application/yaml"}, "yaml")
709 nslcmop_test
= "DEPLOY{}".format(self
.step
)
713 # Wait until status is Ok
714 wait
= timeout_configure
if self
.uses_configuration
else timeout_deploy
716 r
= engine
.test("DEPLOY{}".format(self
.step
), "Wait until NS is deployed and configured", "GET",
717 "/nslcm/v1/ns_lcm_op_occs/<{}>".format(nslcmop_test
), headers_json
, None,
718 200, r_header_json
, "json")
720 if "COMPLETED" in nslcmop
["operationState"]:
722 elif "FAILED" in nslcmop
["operationState"]:
723 raise TestException("NS instantiate has failed: {}".format(nslcmop
["detailed-status"]))
727 raise TestException("NS instantiate is not done after {} seconds".format(timeout_deploy
))
730 def _wait_nslcmop_ready(self
, engine
, nslcmop_test
, timeout_deploy
, expected_fail
=False):
733 r
= engine
.test("DEPLOY{}".format(self
.step
), "Wait to ns lcm operation complete", "GET",
734 "/nslcm/v1/ns_lcm_op_occs/<{}>".format(nslcmop_test
), headers_json
, None,
735 200, r_header_json
, "json")
737 if "COMPLETED" in nslcmop
["operationState"]:
739 raise TestException("NS terminate has success, expecting failing: {}".format(
740 nslcmop
["detailed-status"]))
742 elif "FAILED" in nslcmop
["operationState"]:
743 if not expected_fail
:
744 raise TestException("NS terminate has failed: {}".format(nslcmop
["detailed-status"]))
749 raise TestException("NS instantiate is not terminate after {} seconds".format(timeout
))
751 def terminate(self
, engine
):
754 r
= engine
.test("DEPLOY{}".format(self
.step
), "Terminate NS", "POST",
755 "/nslcm/v1/ns_instances/<{}>/terminate".format(self
.ns_test
), headers_yaml
, None,
756 201, {"Location": "nslcm/v1/ns_lcm_op_occs/", "Content-Type": "application/yaml"}, "yaml")
757 nslcmop2_test
= "DEPLOY{}".format(self
.step
)
759 # Wait until status is Ok
760 self
._wait
_nslcmop
_ready
(engine
, nslcmop2_test
, timeout_deploy
)
762 r
= engine
.test("DEPLOY{}".format(self
.step
), "Delete NS", "DELETE",
763 "/nslcm/v1/ns_instances/<{}>".format(self
.ns_test
), headers_yaml
, None,
767 r
= engine
.test("DEPLOY{}".format(self
.step
), "Delete NS with FORCE", "DELETE",
768 "/nslcm/v1/ns_instances/<{}>?FORCE=True".format(self
.ns_test
), headers_yaml
, None,
772 # check all it is deleted
773 r
= engine
.test("DEPLOY{}".format(self
.step
), "Check NS is deleted", "GET",
774 "/nslcm/v1/ns_instances/<{}>".format(self
.ns_test
), headers_yaml
, None,
777 r
= engine
.test("DEPLOY{}".format(self
.step
), "Check NSLCMOPs are deleted", "GET",
778 "/nslcm/v1/ns_lcm_op_occs?nsInstanceId=<{}>".format(self
.ns_test
), headers_json
, None,
781 if not isinstance(nslcmops
, list) or nslcmops
:
782 raise TestException("NS {} deleted but with ns_lcm_op_occ active: {}".format(self
.ns_test
, nslcmops
))
784 def test_ns(self
, engine
, test_osm
, commands
=None, users
=None, passwds
=None, keys
=None, timeout
=0):
787 r
= engine
.test("TEST_NS{}".format(n
), "GET VNFR_IDs", "GET",
788 "/nslcm/v1/ns_instances/{}".format(self
.ns_id
), headers_json
, None,
789 200, r_header_json
, "json")
793 vnfr_list
= ns_data
['constituent-vnfr-ref']
796 for vnfr_id
in vnfr_list
:
797 self
.total_tests
+= 1
798 r
= engine
.test("TEST_NS{}".format(n
), "GET IP_ADDRESS OF VNFR", "GET",
799 "/nslcm/v1/vnfrs/{}".format(vnfr_id
), headers_json
, None,
800 200, r_header_json
, "json")
804 if vnfr_data
.get("ip-address"):
805 name
= "TEST_NS{}".format(n
)
806 description
= "Run tests in VNFR with IP {}".format(vnfr_data
['ip-address'])
808 test_description
= "Test {} {}".format(name
, description
)
809 logger
.warning(test_description
)
810 vnf_index
= str(vnfr_data
["member-vnf-index-ref"])
811 while timeout
>= time
:
812 result
, message
= self
.do_checks([vnfr_data
["ip-address"]],
813 vnf_index
=vnfr_data
["member-vnf-index-ref"],
814 commands
=commands
.get(vnf_index
), user
=users
.get(vnf_index
),
815 passwd
=passwds
.get(vnf_index
), key
=keys
.get(vnf_index
))
817 logger
.warning(message
)
823 logger
.critical(message
)
827 logger
.critical(message
)
829 logger
.critical("VNFR {} has not mgmt address. Check failed".format(vnfr_id
))
831 def do_checks(self
, ip
, vnf_index
, commands
=[], user
=None, passwd
=None, key
=None):
834 from pssh
.clients
import ParallelSSHClient
835 from pssh
.utils
import load_private_key
836 from ssh2
import exceptions
as ssh2Exception
837 except ImportError as e
:
838 logger
.critical("package <pssh> or/and <urllib3> is not installed. Please add it with 'pip3 install "
839 "parallel-ssh' and/or 'pip3 install urllib3': {}".format(e
))
840 urllib3
.disable_warnings(urllib3
.exceptions
.InsecureRequestWarning
)
842 p_host
= os
.environ
.get("PROXY_HOST")
843 p_user
= os
.environ
.get("PROXY_USER")
844 p_password
= os
.environ
.get("PROXY_PASSWD")
847 pkey
= load_private_key(key
)
851 client
= ParallelSSHClient(ip
, user
=user
, password
=passwd
, pkey
=pkey
, proxy_host
=p_host
,
852 proxy_user
=p_user
, proxy_password
=p_password
, timeout
=10, num_retries
=0)
854 output
= client
.run_command(cmd
)
856 if output
[ip
[0]].exit_code
:
857 return -1, " VNFR {} could not be checked: {}".format(ip
[0], output
[ip
[0]].stderr
)
859 self
.passed_tests
+= 1
860 return 1, " Test successful"
861 except (ssh2Exception
.ChannelFailure
, ssh2Exception
.SocketDisconnectError
, ssh2Exception
.SocketTimeout
,
862 ssh2Exception
.SocketRecvError
) as e
:
863 return 0, "Timeout accessing the VNFR {}: {}".format(ip
[0], str(e
))
864 except Exception as e
:
865 return -1, "ERROR checking the VNFR {}: {}".format(ip
[0], str(e
))
867 def aditional_operations(self
, engine
, test_osm
, manual_check
):
870 def run(self
, engine
, test_osm
, manual_check
, test_params
=None):
871 engine
.get_autorization()
872 nsname
= os
.environ
.get("OSMNBITEST_NS_NAME", "OSMNBITEST")
874 if "vnfd-files" in test_params
:
875 self
.vnfd_filenames
= test_params
["vnfd-files"].split(",")
876 if "nsd-file" in test_params
:
877 self
.nsd_filename
= test_params
["nsd-file"]
878 if test_params
.get("ns-name"):
879 nsname
= test_params
["ns-name"]
880 self
.create_descriptors(engine
)
882 # create real VIM if not exist
883 self
.vim_id
= engine
.get_create_vim(test_osm
)
884 ns_data
= {"nsDescription": "default description", "nsName": nsname
, "nsdId": self
.nsd_id
,
885 "vimAccountId": self
.vim_id
}
886 if test_params
and test_params
.get("ns-config"):
887 if isinstance(test_params
["ns-config"], str):
888 ns_data
.update(yaml
.load(test_params
["ns-config"]))
890 ns_data
.update(test_params
["ns-config"])
891 self
.instantiate(engine
, ns_data
)
894 input('NS has been deployed. Perform manual check and press enter to resume')
896 self
.test_ns(engine
, test_osm
, self
.cmds
, self
.uss
, self
.pss
, self
.keys
, self
.timeout
)
897 self
.aditional_operations(engine
, test_osm
, manual_check
)
898 self
.terminate(engine
)
899 self
.delete_descriptors(engine
)
902 def print_results(self
):
903 print("\n\n\n--------------------------------------------")
904 print("TEST RESULTS:\n PASSED TESTS: {} - TOTAL TESTS: {}".format(self
.total_tests
, self
.passed_tests
))
905 print("--------------------------------------------")
908 class TestDeployHackfestCirros(TestDeploy
):
909 description
= "Load and deploy Hackfest cirros_2vnf_ns example"
913 self
.vnfd_filenames
= ("cirros_vnf.tar.gz",)
914 self
.nsd_filename
= "cirros_2vnf_ns.tar.gz"
915 self
.cmds
= {'1': ['ls -lrt', ], '2': ['ls -lrt', ]}
916 self
.uss
= {'1': "cirros", '2': "cirros"}
917 self
.pss
= {'1': "cubswin:)", '2': "cubswin:)"}
920 class TestDeployHackfest1(TestDeploy
):
921 description
= "Load and deploy Hackfest_1_vnfd example"
925 self
.vnfd_filenames
= ("hackfest_1_vnfd.tar.gz",)
926 self
.nsd_filename
= "hackfest_1_nsd.tar.gz"
927 # self.cmds = {'1': ['ls -lrt', ], '2': ['ls -lrt', ]}
928 # self.uss = {'1': "cirros", '2': "cirros"}
929 # self.pss = {'1': "cubswin:)", '2': "cubswin:)"}
932 class TestDeployHackfestCirrosScaling(TestDeploy
):
933 description
= "Load and deploy Hackfest cirros_2vnf_ns example with scaling modifications"
937 self
.vnfd_filenames
= ("cirros_vnf.tar.gz",)
938 self
.nsd_filename
= "cirros_2vnf_ns.tar.gz"
940 def create_descriptors(self
, engine
):
941 super().create_descriptors(engine
)
942 # Modify VNFD to add scaling and count=2
945 "$id: 'cirros_vnfd-VM'":
947 scaling-group-descriptor:
948 - name: "scale_cirros"
949 max-instance-count: 2
951 - vdu-id-ref: cirros_vnfd-VM
954 engine
.test("DEPLOY{}".format(self
.step
), "Edit VNFD ", "PATCH",
955 "/vnfpkgm/v1/vnf_packages/{}".format(self
.vnfds_id
[0]),
956 headers_yaml
, payload
, 204, None, None)
959 def aditional_operations(self
, engine
, test_osm
, manual_check
):
962 # 2 perform scale out twice
963 payload
= '{scaleType: SCALE_VNF, scaleVnfData: {scaleVnfType: SCALE_OUT, scaleByStepData: ' \
964 '{scaling-group-descriptor: scale_cirros, member-vnf-index: "1"}}}'
965 for i
in range(0, 2):
966 engine
.test("DEPLOY{}".format(self
.step
), "Execute scale action over NS", "POST",
967 "/nslcm/v1/ns_instances/<{}>/scale".format(self
.ns_test
), headers_yaml
, payload
,
968 201, {"Location": "nslcm/v1/ns_lcm_op_occs/", "Content-Type": "application/yaml"}, "yaml")
969 nslcmop2_scale_out
= "DEPLOY{}".format(self
.step
)
970 self
._wait
_nslcmop
_ready
(engine
, nslcmop2_scale_out
, timeout_deploy
)
972 input('NS scale out done. Check that two more vdus are there')
973 # TODO check automatic
976 payload
= '{scaleType: SCALE_VNF, scaleVnfData: {scaleVnfType: SCALE_IN, scaleByStepData: ' \
977 '{scaling-group-descriptor: scale_cirros, member-vnf-index: "1"}}}'
978 for i
in range(0, 2):
979 engine
.test("DEPLOY{}".format(self
.step
), "Execute scale IN action over NS", "POST",
980 "/nslcm/v1/ns_instances/<{}>/scale".format(self
.ns_test
), headers_yaml
, payload
,
981 201, {"Location": "nslcm/v1/ns_lcm_op_occs/", "Content-Type": "application/yaml"}, "yaml")
982 nslcmop2_scale_in
= "DEPLOY{}".format(self
.step
)
983 self
._wait
_nslcmop
_ready
(engine
, nslcmop2_scale_in
, timeout_deploy
)
985 input('NS scale in done. Check that two less vdus are there')
986 # TODO check automatic
988 # perform scale in that must fail as reached limit
989 engine
.test("DEPLOY{}".format(self
.step
), "Execute scale IN out of limit action over NS", "POST",
990 "/nslcm/v1/ns_instances/<{}>/scale".format(self
.ns_test
), headers_yaml
, payload
,
991 201, {"Location": "nslcm/v1/ns_lcm_op_occs/", "Content-Type": "application/yaml"}, "yaml")
992 nslcmop2_scale_in
= "DEPLOY{}".format(self
.step
)
993 self
._wait
_nslcmop
_ready
(engine
, nslcmop2_scale_in
, timeout_deploy
, expected_fail
=True)
996 class TestDeployIpMac(TestDeploy
):
997 description
= "Load and deploy descriptor examples setting mac, ip address at descriptor and instantiate params"
1001 self
.vnfd_filenames
= ("vnfd_2vdu_set_ip_mac2.yaml", "vnfd_2vdu_set_ip_mac.yaml")
1002 self
.nsd_filename
= "scenario_2vdu_set_ip_mac.yaml"
1003 self
.descriptor_url
= \
1004 "https://osm.etsi.org/gitweb/?p=osm/RO.git;a=blob_plain;f=test/RO_tests/v3_2vdu_set_ip_mac/"
1005 self
.cmds
= {'1': ['ls -lrt', ], '2': ['ls -lrt', ]}
1006 self
.uss
= {'1': "osm", '2': "osm"}
1007 self
.pss
= {'1': "osm4u", '2': "osm4u"}
1010 def run(self
, engine
, test_osm
, manual_check
, test_params
=None):
1011 # super().run(engine, test_osm, manual_check, test_params)
1012 # run again setting IPs with instantiate parameters
1013 instantiation_params
= {
1016 "member-vnf-index": "1",
1019 "name": "internal_vld1", # net_internal
1021 "ip-version": "ipv4",
1022 "subnet-address": "10.9.8.0/24",
1023 "dhcp-params": {"count": 100, "start-address": "10.9.8.100"}
1025 "internal-connection-point": [
1028 "ip-address": "10.9.8.2",
1032 "ip-address": "10.9.8.3",
1043 # "name": "iface11",
1044 # "floating-ip-required": True,
1048 "mac-address": "52:33:44:55:66:13"
1057 "ip-address": "10.31.31.22",
1058 "mac-address": "52:33:44:55:66:21"
1067 super().run(engine
, test_osm
, manual_check
, test_params
={"ns-config": instantiation_params
})
1070 class TestDeployHackfest4(TestDeploy
):
1071 description
= "Load and deploy Hackfest 4 example."
1075 self
.vnfd_filenames
= ("hackfest_4_vnfd.tar.gz",)
1076 self
.nsd_filename
= "hackfest_4_nsd.tar.gz"
1077 self
.uses_configuration
= True
1078 self
.cmds
= {'1': ['ls -lrt', ], '2': ['ls -lrt', ]}
1079 self
.uss
= {'1': "ubuntu", '2': "ubuntu"}
1080 self
.pss
= {'1': "osm4u", '2': "osm4u"}
1082 def create_descriptors(self
, engine
):
1083 super().create_descriptors(engine
)
1084 # Modify VNFD to add scaling
1086 scaling-group-descriptor:
1087 - name: "scale_dataVM"
1088 max-instance-count: 10
1090 - name: "auto_cpu_util_above_threshold"
1091 scaling-type: "automatic"
1095 - name: "cpu_util_above_threshold"
1096 scale-in-threshold: 15
1097 scale-in-relational-operation: "LE"
1098 scale-out-threshold: 60
1099 scale-out-relational-operation: "GE"
1100 vnf-monitoring-param-ref: "all_aaa_cpu_util"
1102 - vdu-id-ref: dataVM
1104 scaling-config-action:
1105 - trigger: post-scale-out
1106 vnf-config-primitive-name-ref: touch
1107 - trigger: pre-scale-in
1108 vnf-config-primitive-name-ref: touch
1115 default-value: '/home/ubuntu/touched'
1117 engine
.test("DEPLOY{}".format(self
.step
), "Edit VNFD ", "PATCH",
1118 "/vnfpkgm/v1/vnf_packages/<{}>".format(self
.vnfds_test
[0]), headers_yaml
, payload
, 204, None, None)
1122 class TestDeployHackfest3Charmed(TestDeploy
):
1123 description
= "Load and deploy Hackfest 3charmed_ns example. Modifies it for adding scaling and performs " \
1124 "primitive actions and scaling"
1128 self
.vnfd_filenames
= ("hackfest_3charmed_vnfd.tar.gz",)
1129 self
.nsd_filename
= "hackfest_3charmed_nsd.tar.gz"
1130 self
.uses_configuration
= True
1131 self
.cmds
= {'1': [''], '2': ['ls -lrt /home/ubuntu/first-touch', ]}
1132 self
.uss
= {'1': "ubuntu", '2': "ubuntu"}
1133 self
.pss
= {'1': "osm4u", '2': "osm4u"}
1135 # def create_descriptors(self, engine):
1136 # super().create_descriptors(engine)
1137 # # Modify VNFD to add scaling
1139 # scaling-group-descriptor:
1140 # - name: "scale_dataVM"
1141 # max-instance-count: 10
1143 # - name: "auto_cpu_util_above_threshold"
1144 # scaling-type: "automatic"
1148 # - name: "cpu_util_above_threshold"
1149 # scale-in-threshold: 15
1150 # scale-in-relational-operation: "LE"
1151 # scale-out-threshold: 60
1152 # scale-out-relational-operation: "GE"
1153 # vnf-monitoring-param-ref: "all_aaa_cpu_util"
1155 # - vdu-id-ref: dataVM
1157 # scaling-config-action:
1158 # - trigger: post-scale-out
1159 # vnf-config-primitive-name-ref: touch
1160 # - trigger: pre-scale-in
1161 # vnf-config-primitive-name-ref: touch
1162 # vnf-configuration:
1168 # default-value: '/home/ubuntu/touched'
1170 # engine.test("DEPLOY{}".format(self.step), "Edit VNFD ", "PATCH",
1171 # "/vnfpkgm/v1/vnf_packages/<{}>".format(self.vnfds_test[0]),
1172 # headers_yaml, payload, 200,
1173 # r_header_yaml, yaml)
1174 # self.vnfds_test.append("DEPLOY" + str(self.step))
1177 def aditional_operations(self
, engine
, test_osm
, manual_check
):
1181 payload
= '{member_vnf_index: "2", primitive: touch, primitive_params: { filename: /home/ubuntu/OSMTESTNBI }}'
1182 engine
.test("DEPLOY{}".format(self
.step
), "Executer service primitive over NS", "POST",
1183 "/nslcm/v1/ns_instances/<{}>/action".format(self
.ns_test
), headers_yaml
, payload
,
1184 201, {"Location": "nslcm/v1/ns_lcm_op_occs/", "Content-Type": "application/yaml"}, "yaml")
1185 nslcmop2_action
= "DEPLOY{}".format(self
.step
)
1187 # Wait until status is Ok
1188 self
._wait
_nslcmop
_ready
(engine
, nslcmop2_action
, timeout_deploy
)
1190 input('NS service primitive has been executed. Check that file /home/ubuntu/OSMTESTNBI is present at '
1193 cmds
= {'1': [''], '2': ['ls -lrt /home/ubuntu/OSMTESTNBI', ]}
1194 uss
= {'1': "ubuntu", '2': "ubuntu"}
1195 pss
= {'1': "osm4u", '2': "osm4u"}
1196 self
.test_ns(engine
, test_osm
, cmds
, uss
, pss
, self
.keys
, self
.timeout
)
1198 # # 2 perform scale out
1199 # payload = '{scaleType: SCALE_VNF, scaleVnfData: {scaleVnfType: SCALE_OUT, scaleByStepData: ' \
1200 # '{scaling-group-descriptor: scale_dataVM, member-vnf-index: "1"}}}'
1201 # engine.test("DEPLOY{}".format(self.step), "Execute scale action over NS", "POST",
1202 # "/nslcm/v1/ns_instances/<{}>/scale".format(self.ns_test), headers_yaml, payload,
1203 # 201, {"Location": "nslcm/v1/ns_lcm_op_occs/", "Content-Type": "application/yaml"}, "yaml")
1204 # nslcmop2_scale_out = "DEPLOY{}".format(self.step)
1205 # self._wait_nslcmop_ready(engine, nslcmop2_scale_out, timeout_deploy)
1207 # input('NS scale out done. Check that file /home/ubuntu/touched is present and new VM is created')
1208 # # TODO check automatic
1210 # # 2 perform scale in
1211 # payload = '{scaleType: SCALE_VNF, scaleVnfData: {scaleVnfType: SCALE_IN, scaleByStepData: ' \
1212 # '{scaling-group-descriptor: scale_dataVM, member-vnf-index: "1"}}}'
1213 # engine.test("DEPLOY{}".format(self.step), "Execute scale action over NS", "POST",
1214 # "/nslcm/v1/ns_instances/<{}>/scale".format(self.ns_test), headers_yaml, payload,
1215 # 201, {"Location": "nslcm/v1/ns_lcm_op_occs/", "Content-Type": "application/yaml"}, "yaml")
1216 # nslcmop2_scale_in = "DEPLOY{}".format(self.step)
1217 # self._wait_nslcmop_ready(engine, nslcmop2_scale_in, timeout_deploy)
1219 # input('NS scale in done. Check that file /home/ubuntu/touched is updated and new VM is deleted')
1220 # # TODO check automatic
1223 class TestDescriptors
:
1224 description
= "Test VNFD, NSD, PDU descriptors CRUD and dependencies"
1228 self
.vnfd_filename
= "hackfest_3charmed_vnfd.tar.gz"
1229 self
.nsd_filename
= "hackfest_3charmed_nsd.tar.gz"
1230 self
.descriptor_url
= "https://osm-download.etsi.org/ftp/osm-3.0-three/2nd-hackfest/packages/"
1234 def run(self
, engine
, test_osm
, manual_check
, test_params
=None):
1235 engine
.get_autorization()
1236 temp_dir
= os
.path
.dirname(os
.path
.abspath(__file__
)) + "/temp/"
1237 if not os
.path
.exists(temp_dir
):
1238 os
.makedirs(temp_dir
)
1241 for filename
in (self
.vnfd_filename
, self
.nsd_filename
):
1242 filename_path
= temp_dir
+ filename
1243 if not os
.path
.exists(filename_path
):
1244 with
open(filename_path
, "wb") as file:
1245 response
= requests
.get(self
.descriptor_url
+ filename
)
1246 if response
.status_code
>= 300:
1247 raise TestException("Error downloading descriptor from '{}': {}".format(
1248 self
.descriptor_url
+ filename
, response
.status_code
))
1249 file.write(response
.content
)
1251 vnfd_filename_path
= temp_dir
+ self
.vnfd_filename
1252 nsd_filename_path
= temp_dir
+ self
.nsd_filename
1254 # vnfd CREATE AND UPLOAD in one step:
1255 test_name
= "DESCRIPTOR{}".format(self
.step
)
1256 engine
.test(test_name
, "Onboard VNFD in one step", "POST",
1257 "/vnfpkgm/v1/vnf_packages_content", headers_zip_yaml
, "@b" + vnfd_filename_path
, 201,
1258 {"Location": "/vnfpkgm/v1/vnf_packages_content/", "Content-Type": "application/yaml"}, "yaml")
1259 self
.vnfd_id
= engine
.test_ids
[test_name
]
1262 # get vnfd descriptor
1263 engine
.test("DESCRIPTOR" + str(self
.step
), "Get VNFD descriptor", "GET",
1264 "/vnfpkgm/v1/vnf_packages/{}".format(self
.vnfd_id
), headers_yaml
, None, 200, r_header_yaml
, "yaml")
1267 # get vnfd file descriptor
1268 engine
.test("DESCRIPTOR" + str(self
.step
), "Get VNFD file descriptor", "GET",
1269 "/vnfpkgm/v1/vnf_packages/{}/vnfd".format(self
.vnfd_id
), headers_text
, None, 200,
1270 r_header_text
, "text", temp_dir
+"vnfd-yaml")
1272 # TODO compare files: diff vnfd-yaml hackfest_3charmed_vnfd/hackfest_3charmed_vnfd.yaml
1274 # get vnfd zip file package
1275 engine
.test("DESCRIPTOR" + str(self
.step
), "Get VNFD zip package", "GET",
1276 "/vnfpkgm/v1/vnf_packages/{}/package_content".format(self
.vnfd_id
), headers_zip
, None, 200,
1277 r_header_zip
, "zip", temp_dir
+"vnfd-zip")
1279 # TODO compare files: diff vnfd-zip hackfest_3charmed_vnfd.tar.gz
1282 engine
.test("DESCRIPTOR" + str(self
.step
), "Get VNFD artifact package", "GET",
1283 "/vnfpkgm/v1/vnf_packages/{}/artifacts/icons/osm.png".format(self
.vnfd_id
), headers_zip
, None, 200,
1284 r_header_octect
, "octet-string", temp_dir
+"vnfd-icon")
1286 # TODO compare files: diff vnfd-icon hackfest_3charmed_vnfd/icons/osm.png
1288 # nsd CREATE AND UPLOAD in one step:
1289 test_name
= "DESCRIPTOR{}".format(self
.step
)
1290 engine
.test(test_name
, "Onboard NSD in one step", "POST",
1291 "/nsd/v1/ns_descriptors_content", headers_zip_yaml
, "@b" + nsd_filename_path
, 201,
1292 {"Location": "/nsd/v1/ns_descriptors_content/", "Content-Type": "application/yaml"}, "yaml")
1293 self
.nsd_id
= engine
.test_ids
[test_name
]
1296 # get nsd descriptor
1297 engine
.test("DESCRIPTOR" + str(self
.step
), "Get NSD descriptor", "GET",
1298 "/nsd/v1/ns_descriptors/{}".format(self
.nsd_id
), headers_yaml
, None, 200, r_header_yaml
, "yaml")
1301 # get nsd file descriptor
1302 engine
.test("DESCRIPTOR" + str(self
.step
), "Get NSD file descriptor", "GET",
1303 "/nsd/v1/ns_descriptors/{}/nsd".format(self
.nsd_id
), headers_text
, None, 200,
1304 r_header_text
, "text", temp_dir
+"nsd-yaml")
1306 # TODO compare files: diff nsd-yaml hackfest_3charmed_nsd/hackfest_3charmed_nsd.yaml
1308 # get nsd zip file package
1309 engine
.test("DESCRIPTOR" + str(self
.step
), "Get NSD zip package", "GET",
1310 "/nsd/v1/ns_descriptors/{}/nsd_content".format(self
.nsd_id
), headers_zip
, None, 200,
1311 r_header_zip
, "zip", temp_dir
+"nsd-zip")
1313 # TODO compare files: diff nsd-zip hackfest_3charmed_nsd.tar.gz
1316 engine
.test("DESCRIPTOR" + str(self
.step
), "Get NSD artifact package", "GET",
1317 "/nsd/v1/ns_descriptors/{}/artifacts/icons/osm.png".format(self
.nsd_id
), headers_zip
, None, 200,
1318 r_header_octect
, "octet-string", temp_dir
+"nsd-icon")
1320 # TODO compare files: diff nsd-icon hackfest_3charmed_nsd/icons/osm.png
1323 test_rest
.test("DESCRIPTOR" + str(self
.step
), "Delete VNFD conflict", "DELETE",
1324 "/vnfpkgm/v1/vnf_packages/{}".format(self
.vnfd_id
), headers_yaml
, None, 409, None, None)
1327 test_rest
.test("DESCRIPTOR" + str(self
.step
), "Delete VNFD force", "DELETE",
1328 "/vnfpkgm/v1/vnf_packages/{}?FORCE=TRUE".format(self
.vnfd_id
), headers_yaml
, None, 204, None, 0)
1332 test_rest
.test("DESCRIPTOR" + str(self
.step
), "Delete NSD", "DELETE",
1333 "/nsd/v1/ns_descriptors/{}".format(self
.nsd_id
), headers_yaml
, None, 204, None, 0)
1337 if __name__
== "__main__":
1341 # Disable warnings from self-signed certificates.
1342 requests
.packages
.urllib3
.disable_warnings()
1344 logging
.basicConfig(format
="%(levelname)s %(message)s", level
=logging
.ERROR
)
1345 logger
= logging
.getLogger('NBI')
1346 # load parameters and configuration
1347 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hvu:p:",
1348 ["url=", "user=", "password=", "help", "version", "verbose", "no-verbose",
1349 "project=", "insecure", "timeout", "timeout-deploy", "timeout-configure",
1350 "test=", "list", "test-osm", "manual-check", "params="])
1351 url
= "https://localhost:9999/osm"
1352 user
= password
= project
= "admin"
1354 manual_check
= False
1358 "NonAuthorized": TestNonAuthorized
,
1359 "FakeVIM": TestFakeVim
,
1360 "TestUsersProjects": TestUsersProjects
,
1361 "VIM-SDN": TestVIMSDN
,
1362 "Deploy-Custom": TestDeploy
,
1363 "Deploy-Hackfest-Cirros": TestDeployHackfestCirros
,
1364 "Deploy-Hackfest-Cirros-Scaling": TestDeployHackfestCirrosScaling
,
1365 "Deploy-Hackfest-3Charmed": TestDeployHackfest3Charmed
,
1366 "Deploy-Hackfest-4": TestDeployHackfest4
,
1367 "Deploy-CirrosMacIp": TestDeployIpMac
,
1368 "TestDescriptors": TestDescriptors
,
1369 "TestDeployHackfest1": TestDeployHackfest1
,
1370 # "Deploy-MultiVIM": TestDeployMultiVIM,
1376 # print("parameter:", o, a)
1377 if o
== "--version":
1378 print("test version " + __version__
+ ' ' + version_date
)
1381 for test
, test_class
in test_classes
.items():
1382 print("{:20} {}".format(test
+ ":", test_class
.description
))
1384 elif o
in ("-v", "--verbose"):
1386 elif o
== "no-verbose":
1388 elif o
in ("-h", "--help"):
1391 elif o
== "--test-osm":
1393 elif o
== "--manual-check":
1397 elif o
in ("-u", "--user"):
1399 elif o
in ("-p", "--password"):
1401 elif o
== "--project":
1404 # print("asdfadf", o, a, a.split(","))
1405 for _test
in a
.split(","):
1406 if _test
not in test_classes
:
1407 print("Invalid test name '{}'. Use option '--list' to show available tests".format(_test
),
1410 test_to_do
.append(_test
)
1411 elif o
== "--params":
1412 param_key
, _
, param_value
= a
.partition("=")
1413 text_index
= len(test_to_do
)
1414 if text_index
not in test_params
:
1415 test_params
[text_index
] = {}
1416 test_params
[text_index
][param_key
] = param_value
1417 elif o
== "--insecure":
1419 elif o
== "--timeout":
1421 elif o
== "--timeout-deploy":
1422 timeout_deploy
= int(a
)
1423 elif o
== "--timeout-configure":
1424 timeout_configure
= int(a
)
1426 assert False, "Unhandled option"
1428 logger
.setLevel(logging
.WARNING
)
1430 logger
.setLevel(logging
.DEBUG
)
1432 logger
.setLevel(logging
.ERROR
)
1434 test_rest
= TestRest(url
, user
=user
, password
=password
, project
=project
)
1435 # print("tests to do:", test_to_do)
1438 for test
in test_to_do
:
1440 test_class
= test_classes
[test
]
1441 test_class().run(test_rest
, test_osm
, manual_check
, test_params
.get(text_index
))
1443 for test
, test_class
in test_classes
.items():
1444 test_class().run(test_rest
, test_osm
, manual_check
, test_params
.get(0))
1450 except TestException
as e
:
1451 logger
.error(test
+ "Test {} Exception: {}".format(test
, str(e
)))
1453 except getopt
.GetoptError
as e
:
1455 print(e
, file=sys
.stderr
)
1457 except Exception as e
:
1458 logger
.critical(test
+ " Exception: " + str(e
), exc_info
=True)