blob: f5b7b0cfee07a424479ed7d5ade63a9bec9adcd6 [file] [log] [blame]
Martin Cosyns0efdc872021-09-27 16:24:30 +00001# Copyright 2020-present Open Networking Foundation
2# Original copyright 2020-present ADTRAN, Inc.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14from grpc_robot.grpc_robot import _package_version_get
15
16
17class Collections(object):
18 """
19 Tools for collections (list, dict) related functionality.
20 """
21
22 try:
23 ROBOT_LIBRARY_VERSION = _package_version_get('grpc_robot')
24 except NameError:
25 ROBOT_LIBRARY_VERSION = 'unknown'
26
27 @staticmethod
28 def dict_get_key_by_value(input_dict, search_value):
29 """
30 Gets the first key from _input_dict_ which has the value of _search_value_.
31
32 If _search_value_ is not found in _input_dict_, an empty string is returned.
33
34 *Parameters*:
35 - _input_dict_: <dictionary> to be browsed.
36 - _search_value_: <string>, value to be searched for.
37
38 *Return*: key of dictionary if search value is in input_dict else empty string
39 """
40 return_key = ''
41 for key, val in input_dict.items():
42 if val == search_value:
43 return_key = key
44 break
45
46 return return_key
47
48 @staticmethod
49 def dict_get_value(values_dict, key, strict=False):
50 """
51 Returns the value for given _key_ in _values_dict_.
52
53 If _strict_ is set to False (default) it will return given _key_ if its is not in the dictionary.
54 If set to True, an AssertionError is raised.
55
56 *Parameters*:
57 - _key_: <string>, key to be searched in dictionary.
58 - _values_dict_: <dictionary> in which the key is searched.
59 - _strict_: Optional: <boolean> switch to indicate if an exception shall be raised if key is not in values_dict.
60 Default: False
61
62 *Return*:
63 - if key is in values_dict: Value from _values_dict_ for _key_.
64 - else: _key_.
65 - raises AssertionError in case _key_ is not in _values_dict_ and _strict_ is True.
66 """
67 try:
68 return_value = values_dict[key]
69 except KeyError:
70 if strict:
71 raise AssertionError('Error: Value not found for key: %s' % key)
72 else:
73 return_value = key
74
75 return return_value
76
77 @staticmethod
78 def list_get_dict_by_value(input_list, key_name, value, match='first'):
79 """
80 Retrieves a dictionary from a list of dictionaries where _key_name_ has the _value, if _match_ is
81 "first". Else it returns all matching dictionaries.
82
83 *Parameters*:
84 - _input_list_: <list> ; List of dictionaries.
85 - _key_name_: <dictionary> or <list> ; Name of the key to be searched for.
86 - _value_: <string> or <number> ; Any value of key _key_name_ to be searched for.
87
88 *Example*:
89 | ${dict1} | Create Dictionary | key_key=master1 | key1=value11 | key2=value12 | |
90 | ${dict2} | Create Dictionary | key_key=master2 | key1=value21 | key2=value22 | |
91 | ${dict3} | Create Dictionary | key_key=master3 | key1=value31 | key2=value32 | |
92 | ${dict4} | Create Dictionary | key_key=master4 | key5=value41 | key6=value42 | |
93 | ${the_list} | Create List | ${dict1} | ${dict2} | ${dict3} | ${dict4} |
94 | ${result} | List Get Dict By Value | ${the_list} | key_key | master4 | |
95
96 Variable ${result} has following structure:
97 | ${result} = {
98 | 'key_key': 'master4',
99 | 'key5': 'value41',
100 | 'key6': 'value42'
101 | }
102 """
103 try:
104 if match == 'first':
105 return input_list[next(index for (index, d) in enumerate(input_list) if d[key_name] == value)]
106 else:
107 return [d for d in input_list if d[key_name] == value]
108 except (KeyError, TypeError, StopIteration):
109 raise KeyError('list does not contain a dictionary with key:value "%s:%s"' % (key_name, value))
110
111 @staticmethod
112 def to_camel_case(snake_str, first_uppercase=False):
113 components = snake_str.split('_')
114 # We capitalize the first letter of each component except the first one
115 # with the 'title' method and join them together.
116 return (components[0] if not first_uppercase else components[0].title()) + ''.join(x.title() for x in components[1:])