Step 2: Move test folder to root
[integration/test.git] / csit / libraries / AAAJsonUtils.py
1 """
2 AAAJSonUtils library for looking up relevant information in a json record
3
4 This library can be used to take a chunk of json results and mine out
5 needed information for testing.
6 Author: Carmen Kelling - HP Enterprise
7 """
8
9 import json
10 import jsonpath
11
12
13 def countnodes(args):
14     """ Count the number of nodes in a chunk of JSON.
15
16         Because json blobs come in multiple forms, use node, subnode or
17         category to assist in defining what to count.
18
19     Args:
20         :param jsonblob: a smattering of JSON data to work through
21         :param node: a node to look for such as users, groups, domains
22         :param subnode: a sub-item to look for, such as domainid
23         :param category: from a simple json record, a field to look for
24
25     Returns:
26         :returns ctr: the correct number of records have in the json
27     """
28     ctr = 0
29
30     try:
31         jsonobj = json.loads(args['jsonblob'])
32     except KeyError:
33         print "countnodes: json blob to parse not found"
34         raise
35
36     if 'subnode' in args:
37         ctr = len(jsonobj)
38     elif 'category' in args:
39         category_ = args['category'].encode('ascii', 'ignore')
40         ctr = len(jsonobj[category_])
41     else:
42         # working with a single record, short-cut and return count of 1
43         return 1
44     return ctr
45
46
47 def fieldcount(pobject, field):
48     """ Helper-func - use countnodes to count the occurences of field in pobject
49
50         example
51         count the occurences of domainid in this single record...
52
53         [ {
54               "description": "default odl sdn domain",
55               "domainid": 1,
56               "enabled": "true",
57               "name": "MasterTest Domain"
58           } ]
59
60     Args:
61         :param pobject: JSON code to work through
62         :param field: an element to search for and count
63
64     Returns:
65         :returns number_nodes: the correct number of fields you counted
66         in the json
67     """
68     number_nodes = countnodes({'jsonblob': pobject, 'field': field})
69     return number_nodes
70
71
72 def subnodecount(pobject, subnode):
73     """ Helper-func - use countnodes to count subnode in pobject
74
75         example
76         count the occurences of domainid in this json.
77         this chunk lacks nested dictionary keywords (users, domains, roles)...
78
79         {
80               "description": "odl master domain",
81               "domainid": 1,
82               "enabled": "true",
83               "name": "Master Test Domain"
84         }
85         {
86               "description": "sdn user domain",
87               "domainid": 2,
88               "enabled": "true",
89               "name": "User Domain"
90         }
91         ...
92
93     Args:
94         :param pobject: JSON code to work through
95         :param subnode: a subnode, such as domainid, to search for and count
96
97     Returns:
98         :returns number_nodes: the correct number of fields you counted
99         in the json
100     """
101     number_nodes = countnodes({'jsonblob': pobject, 'subnode': subnode})
102     return number_nodes
103
104
105 def nodecount(pobject, category, node):
106     """ Helper-func - use countnodes function to count node of a category type
107
108         example
109         count the domainid in these properly formatted json blobs...
110
111         "domains: [
112             {
113               "description": "odl master domain",
114               "domainid": 1,
115               "enabled": "true",
116               "name": "Master Test Domain"
117             }
118             {
119               "description": "sdn user domain",
120               "domainid": 2,
121               "enabled": "true",
122               "name": "User Domain"
123             }
124             ...
125         ]
126         "users": [
127             ...
128         ]
129
130     Args:
131         :param pobject: JSON code to work through
132         :param node: a node, such as domainid, to search for in a properly
133         formatted json object, and count
134
135     Returns:
136         :returns number_nodes: the correct number of fields you counted
137         in the json
138     """
139     number_nodes = \
140         countnodes({'jsonblob': pobject, 'category': category, 'node': node})
141     return number_nodes
142
143
144 def get_id_by_name(args):
145     """ Get an ID by the Name field.
146
147         Go through the json given, and pull out all ids that are identified
148         by the corresponding name argument.
149
150     Args:
151         :param jsonblob: a smattering of JSON code to work through
152         :param name: a name to look up in the database of json
153         :param head: will be one of roles, users, domains
154         :param typeval: literal value of either user, role or domain
155         :param size: a count on the number of records to search
156
157     Returns:
158         :returns nodelist: return the first id that has same corresponding name
159     """
160     try:
161         jsonobj = json.loads(args['jsonblob'])
162     except KeyError:
163         print "get_id_by_name: json blob not specified:"
164         raise
165
166     try:
167         name = args['name']
168     except KeyError:
169         print "get_id_by_name: name [usr, domain, role] not specified in args"
170         raise
171
172     if 'head' in args:
173         blobkey = args['head']
174     else:
175         # use an empty key when the arg is not specified.  deals with simpler
176         # form
177         blobkey = ''
178
179     try:
180         datatype = args['typeval']
181     except KeyError:
182         print "get_id_by_name: need a type arg to process correct name for id"
183         raise
184
185     try:
186         ncount = args['size']
187     except KeyError:
188         raise
189
190     nodelist = []
191
192     # Loop through the records looking for the specified name.  When found,
193     # return the corresponding attribute value
194     if ncount > 0:
195         for i in range(ncount):
196             # build up some 'lookup' keys, call jsonpath with that key
197             bkey1 = '$.' + blobkey + '[' + str(i) + '].name'
198             typename = datatype + 'id'
199             bkey2 = '$.' + blobkey + '[' + str(i) + '].' + typename
200
201             # find records with same name
202             name_record = jsonpath.jsonpath(jsonobj, bkey1)
203             # find corresponding node info, for that name
204             node_record = jsonpath.jsonpath(jsonobj, bkey2)
205
206             # build up an alternative set of keys.  This lets you deal with
207             # other format of json
208             bkey3 = '$.' + blobkey + '.name'
209             typename2 = datatype + 'id'
210             bkey4 = '$.' + blobkey + '.' + typename2
211
212             # find records with same name
213             altname_record = jsonpath.jsonpath(jsonobj, bkey3)
214             # find corresponding record node info, for that name
215             altnode_record = jsonpath.jsonpath(jsonobj, bkey4)
216             try:
217                 if name in list(name_record):
218                     nodelist.append(node_record.pop())
219             except:
220                 try:
221                     if name in list(altname_record):
222                         nodelist.append(altnode_record.pop())
223                 except:
224                     raise
225
226     try:
227         return nodelist.pop()
228     except LookupError:
229         raise
230
231
232 def get_attribute_by_id(args):
233     """ Get an attribute by the id field.
234
235         Each json record in the json blob has a unique ID, return
236         the corresponding attribute field from that record.  Could be
237         description, name, email, password, or any field in available
238         in that record.
239
240     Args:
241         :param jsonblob: a smattering of JSON code to work through
242         :param id: the ID to look up in the database of json
243         :param head: will be one of roles, users, domains
244         :param typeval: literal value of either user, role or domain
245         :param size: a count on the number of records to search
246
247     Returns:
248         :returns name_record: the name attribute value that corresponds
249         to the provided id
250     """
251     try:
252         jsonobj = json.loads(args['jsonblob'])
253     except KeyError:
254         print "get_attribute_by_id: json blob not specified:"
255         raise
256
257     try:
258         nodeid = args['id']
259     except KeyError:
260         print "get_attribute_by_id: id to look for not specified in parameters"
261         raise
262
263     if 'attr' in args:
264         attr = args['attr']
265     else:
266         # If caller does not specify a record attribute to return, then
267         # simply default to giving the description of the id you are
268         # searching on
269         attr = 'description'
270
271     if 'head' in args:
272         # will be one of roles, users, domains, or empty to process more
273         # specific grouping of json data
274         blobkey = args['head']
275     else:
276         # use an empty key when the arg is not specified, allows us to
277         # process chunk of JSON without the outer layer defining roles,
278         # users, domains. (simpler format)
279         blobkey = ''
280
281     try:
282         datatype = args['typeval']
283     except KeyError:
284         print "get_attribute_by_id: need type arg to process name for id"
285         raise
286
287     try:
288         size = args['size']
289     except KeyError:
290         print "get_attribute_by_id: specify number of records we need"
291         raise
292
293     # Loop through the records looking for the nodeid, when found, return
294     # the corresponding attribute value
295
296     ncount = size
297     if ncount > 0:
298         for i in range(ncount):
299             bkey1 = '$.' + blobkey + '[' + str(i) + '].' + attr
300             bkey2 = '$.' + blobkey + '[' + str(i) + '].' + datatype + 'id'
301
302             bkey3 = '$.' + blobkey + '.' + attr
303             bkey4 = '$.' + blobkey + '.' + datatype + 'id'
304
305             name_record = jsonpath.jsonpath(jsonobj, bkey1)
306             node_record = jsonpath.jsonpath(jsonobj, bkey2)
307             altname_record = jsonpath.jsonpath(jsonobj, bkey3)
308             altnode_record = jsonpath.jsonpath(jsonobj, bkey4)
309
310             if type(node_record) is list:
311                 if nodeid in list(node_record):
312                     return name_record.pop()
313             else:
314                 try:
315                     node_record
316                 except:
317                     print "not in list"
318                 else:
319                     return name_record
320
321             if type(altnode_record) is list:
322                 if nodeid in list(altnode_record):
323                     return altname_record.pop()
324                 else:
325                     try:
326                         altnode_record
327                     except:
328                         print "not in list"
329                     else:
330                         return altname_record
331
332
333 def get_role_id_by_rolename(pobject, rolename, number_nodes):
334     """ Helper-func - use get_id_by_name to obtain role-ids for a role-name
335
336         sample record...
337         "roles": [ {
338               "description": "a role for admins",
339               "name": "admin",
340               "roleid": 1
341           }
342           {
343               ...
344           } ]
345
346     Args:
347         :param pobject: JSON blob to work through
348         :param rolename: the name element to search for
349         :param number_nodes: number of records to process
350
351     Returns:
352         :returns roleid:  a list of one or more roleid's that match
353         the rolename given
354     """
355     roleid = get_id_by_name({'jsonblob': pobject,
356                              'name': rolename,
357                              'head': 'roles',
358                              'size': number_nodes,
359                              'typeval': 'role'})
360     try:
361         roleid
362     except:
363         raise
364     else:
365         return roleid
366
367
368 def get_role_name_by_roleid(pobject, roleid, number_nodes):
369     """ Helper-func - use get_attribute_by_id to get role-name for a role-id
370
371         sample record...
372         "roles": [ {
373               "description": "a role for admins",
374               "name": "admin",
375               "roleid": 1
376           }
377           {
378               ...
379           } ]
380
381     Args:
382         :param pobject: JSON blob to work through
383         :param roleid: the identifier element to search for
384         :param number_nodes: number of records to process
385
386     Returns:
387         :returns rolename:  the role name that corresponds to the record
388         identified by the role-id
389     """
390     rolename = get_attribute_by_id({'jsonblob': pobject,
391                                     'head': 'roles',
392                                     'id': roleid,
393                                     'attr': 'name',
394                                     'size': number_nodes,
395                                     'typeval': 'role'})
396     try:
397         rolename
398     except:
399         raise
400     else:
401         return rolename
402
403
404 def get_role_description_by_roleid(pobject, roleid, number_nodes):
405     """ Helper-func - get role-description for a role-id
406
407         sample record...
408         "roles": [ {
409               "description": "a role for admins",
410               "name": "admin",
411               "roleid": 1
412           }
413           {
414               ...
415           } ]
416
417     Args:
418         :param pobject: JSON blob to work through
419         :param roleid: the identifier element to search for
420         :param number_nodes: number of records to process
421
422     Returns:
423         :returns roledesc:  the role description that corresponds to the record
424         identified by the role-id
425     """
426     roledesc = get_attribute_by_id({'jsonblob': pobject,
427                                     'head': 'roles',
428                                     'id': roleid,
429                                     'attr': 'description',
430                                     'size': number_nodes,
431                                     'typeval': 'role'})
432     try:
433         roledesc
434     except:
435         raise
436     else:
437         return roledesc
438
439
440 def get_domain_id_by_domainname(pobject, domainname, number_nodes):
441     """ Helper-func - get all domain-ids corresponding to domain-name
442
443         sample record...
444         "domains": [ {
445               "description": "default odl sdn domain",
446               "domainid": 1,
447               "enabled": true,
448               "name": "admin"
449           }
450           {
451               ...
452           } ]
453
454     Args:
455         :param pobject: JSON blob to work through
456         :param domainname: the name element to search for
457         :param number_nodes: number of records to process
458
459     Returns:
460         :returns domainid:  a list of one or more domain-id's that match
461         the domain-name given
462     """
463     domainid = get_id_by_name({'jsonblob': pobject,
464                                'name': domainname,
465                                'size': number_nodes,
466                                'typeval': 'domain'})
467
468     try:
469         domainid
470     except:
471         raise
472     else:
473         return domainid
474
475
476 def get_domain_name_by_domainid(pobject, domainid, number_nodes):
477     """ Helper-func - get domain-name for a particular domainid
478
479         sample record...
480         "domains": [ {
481               "description": "default odl sdn domain",
482               "domainid": 1,
483               "enabled": true,
484               "name": "admin"
485           }
486           {
487               ...
488           } ]
489
490     Args:
491         :param pobject: JSON blob to work through
492         :param domainid: the identifier element to search for
493         :param number_nodes: number of records to process
494
495     Returns:
496         :returns domainname:  the domain name that corresponds to the record
497         identified by the domainid
498     """
499     domainname = get_attribute_by_id({'jsonblob': pobject,
500                                       'head': 'domains',
501                                       'id': domainid,
502                                       'attr': 'name',
503                                       'size': number_nodes,
504                                       'typeval': 'domain'})
505     try:
506         domainname
507     except:
508         raise
509     else:
510         return domainname
511
512
513 def get_domain_description_by_domainid(pobject, domainid, number_nodes):
514     """ Helper-func - get the domaind descripton for a particular domainid
515
516         sample record...
517         "domains": [ {
518               "description": "default odl sdn domain",
519               "domainid": 1,
520               "enabled": true,
521               "name": "admin"
522           }
523           {
524               ...
525           } ]
526
527     Args:
528         :param pobject: JSON blob to work through
529         :param domainid: the identifier element to search for
530         :param number_nodes: number of records to process
531
532     Returns:
533         :returns domainname:  the domain description field that corresponds
534         to the record identified by the domainid
535     """
536     domaindesc = get_attribute_by_id({'jsonblob': pobject,
537                                       'head': 'domains',
538                                       'id': domainid,
539                                       'attr': 'description',
540                                       'size': number_nodes,
541                                       'typeval': 'domain'})
542     try:
543         domaindesc
544     except:
545         raise
546     else:
547         return domaindesc
548
549
550 def get_domain_state_by_domainid(pobject, domainid, number_nodes):
551     """ Helper-func - get domain state field  for a particular domainid
552
553         sample record...
554         "domains": [ {
555               "description": "default odl sdn domain",
556               "domainid": 1,
557               "enabled": true,
558               "name": "admin"
559           }
560           {
561               ...
562           } ]
563
564     Args:
565         :param pobject: JSON blob to work through
566         :param domainid: the identifier element to search for
567         :param number_nodes: number of records to process
568
569     Returns:
570         :returns domainstate:  the domain state (enabled) field that
571         corresponds to the record identified by the domainid
572     """
573     domainstate = get_attribute_by_id({'jsonblob': pobject,
574                                        'head': 'domains',
575                                        'id': domainid,
576                                        'attr': 'enabled',
577                                        'size': number_nodes,
578                                        'typeval': 'domain'})
579     try:
580         domainstate
581     except:
582         raise
583     else:
584         return domainstate
585
586
587 def get_user_id_by_username(pobject, username, number_nodes):
588     """ Helper-func - get user-ids corresponding to username
589
590         sample record...
591         "users": [ {
592               "description": "admin user",
593               "email": "admin@anydomain.com",
594               "enabled": true,
595               "userid": 1,
596               "name": "admin",
597               "password": "**********",
598               "userid": 1
599           }
600           {
601               ...
602           } ]
603
604     Args:
605         :param pobject: JSON blob to work through
606         :param username: the name element to search for
607         :param number_nodes: number of records to process
608
609     Returns:
610         :returns userid:  a list of one or more user-id's that match
611         the username given
612     """
613     userid = get_id_by_name({'jsonblob': pobject,
614                              'name': username,
615                              'head': 'users',
616                              'size': number_nodes,
617                              'typeval': 'user'})
618     try:
619         userid
620     except:
621         raise
622     else:
623         return userid
624
625
626 def get_user_password_by_userid(pobject, userid, number_nodes):
627     """ Helper-func - get user password field for a particular userid
628
629         sample record...
630         "users": [ {
631               "description": "admin user",
632               "email": "admin@anydomain.com",
633               "enabled": true,
634               "userid": 1,
635               "name": "admin",
636               "password": "**********",
637               "userid": 1
638           }
639           {
640               ...
641           } ]
642
643     Args:
644         :param pobject: JSON blob to work through
645         :param userid: the identifier element to search for
646         :param number_nodes: number of records to process
647
648     Returns:
649         :returns userpassword:  the raw password field that corresponds to
650          the record identified by the userid
651     """
652     userpassword = get_attribute_by_id({'jsonblob': pobject,
653                                         'head': 'users',
654                                         'id': userid,
655                                         'attr': 'password',
656                                         'size': number_nodes,
657                                         'typeval': 'user'})
658     try:
659         userpassword
660     except:
661         raise
662     else:
663         return userpassword
664
665
666 def get_user_name_by_userid(pobject, userid, number_nodes):
667     """ Helper-func - get the username field for a particular userid
668
669         sample record...
670         "users": [ {
671               "description": "admin user",
672               "email": "admin@anydomain.com",
673               "enabled": true,
674               "userid": 1,
675               "name": "admin",
676               "password": "**********",
677               "userid": 1
678           }
679           {
680               ...
681           } ]
682
683     Args:
684         :param pobject: JSON blob to work through
685         :param userid: the identifier element to search for
686         :param number_nodes: number of records to process
687
688     Returns:
689         :returns username:  the name field that corresponds to the record
690         identified by the userid
691     """
692     username = get_attribute_by_id({'jsonblob': pobject,
693                                     'head': 'users',
694                                     'id': userid,
695                                     'attr': 'name',
696                                     'size': number_nodes,
697                                     'typeval': 'user'})
698     try:
699         username
700     except:
701         raise
702     else:
703         return username
704
705
706 def get_user_state_by_userid(pobject, userid, number_nodes):
707     """ Helper-func - get user state field for a particular userid
708
709         sample record...
710         "users": [ {
711               "description": "admin user",
712               "email": "admin@anydomain.com",
713               "enabled": true,
714               "userid": 1,
715               "name": "admin",
716               "password": "**********",
717               "userid": 1
718           }
719           {
720               ...
721           } ]
722
723     Args:
724         :param pobject: JSON blob to work through
725         :param userid: the identifier element to search for
726         :param number_nodes: number of records to process
727
728     Returns:
729         :returns userstate:  the enabled field that corresponds to the record
730         identified by the userid
731     """
732     userstate = get_attribute_by_id({'jsonblob': pobject,
733                                      'head': 'users',
734                                      'id': userid,
735                                      'attr': 'enabled',
736                                      'size': number_nodes,
737                                      'typeval': 'user'})
738     try:
739         userstate
740     except:
741         raise
742     else:
743         return userstate
744
745
746 def get_user_email_by_userid(pobject, userid, number_nodes):
747     """ Helper-func - get user email field for a particular userid
748
749         sample record...
750         "users": [ {
751               "description": "admin user",
752               "email": "admin@anydomain.com",
753               "enabled": true,
754               "userid": 1,
755               "name": "admin",
756               "password": "**********",
757               "userid": 1
758           }
759           {
760               ...
761           } ]
762
763     Args:
764         :param pobject: JSON blob to work through
765         :param userid: the identifier element to search for
766         :param number_nodes: number of records to process
767
768     Returns:
769         :returns useremail:  the email field that corresponds to the record
770         identified by the userid
771     """
772     useremail = get_attribute_by_id({'jsonblob': pobject,
773                                      'head': 'users',
774                                      'id': userid,
775                                      'attr': 'email',
776                                      'size': number_nodes,
777                                      'typeval': 'user'})
778     try:
779         useremail
780     except:
781         raise
782     else:
783         return useremail
784
785
786 def get_user_description_by_userid(pobject, userid, number_nodes):
787     """ Helper-func - get user description field for a particular userid
788
789         sample record...
790         "users": [ {
791               "description": "admin user",
792               "email": "admin@anydomain.com",
793               "enabled": true,
794               "userid": 1,
795               "name": "admin",
796               "password": "**********",
797               "userid": 1
798           }
799           {
800               ...
801           } ]
802
803     Args:
804         :param pobject: JSON blob to work through
805         :param userid: the identifier element to search for
806         :param number_nodes: number of records to process
807
808     Returns:
809         :returns userdesc:  the description field that corresponds to the
810         record identified by the userid
811     """
812     userdesc = get_attribute_by_id({'jsonblob': pobject,
813                                     'head': 'users',
814                                     'id': userid,
815                                     'attr': 'description',
816                                     'size': number_nodes,
817                                     'typeval': 'user'})
818     try:
819         userdesc
820     except:
821         raise
822     else:
823         return userdesc