UTI: Export results
[csit.git] / resources / libraries / python / model / util.py
1 # Copyright (c) 2021 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Module hosting few utility functions useful when dealing with modelled data.
15
16 This is for storing varied utility functions, which are too short and diverse
17 to be put into more descriptive modules.
18 """
19
20
21 from robot.libraries.BuiltIn import BuiltIn
22
23
24 def descend(parent_node, key, default_factory=None):
25     """Return a sub-node, create and insert it when it does not exist.
26
27     Without this function:
28         child_node = parent_node.get(key, dict())
29         parent_node[key] = child_node
30
31     With this function:
32         child_node = descend(parent_node, key)
33
34     New code is shorter and avoids the need to type key and parent_node twice.
35
36     :param parent_node: Reference to inner node of a larger structure
37         we want to descend from.
38     :param key: Key of the maybe existing child node.
39     :param default_factory: If the key does not exist, call this
40         to create a new value to be inserted under the key.
41         None means dict. The other popular option is list.
42     :type parent_node: dict
43     :type key: str
44     :type default_factory: Optional[Callable[[], object]]
45     :returns: The reference to (maybe just created) child node.
46     :rtype: object
47     """
48     if key not in parent_node:
49         factory = dict if default_factory is None else default_factory
50         parent_node[key] = factory()
51     return parent_node[key]
52
53
54 def get_export_data():
55     """Return raw_data member of export_json library instance.
56
57     This assumes the data has been initialized already.
58     Return None if Robot is not running.
59
60     :returns: Current library instance's raw data field.
61     :rtype: Optional[dict]
62     :raises AttributeError: If library is not imported yet.
63     """
64     instance = BuiltIn().get_library_instance(
65         u"resources.libraries.python.model.export_json"
66     )
67     if instance is None:
68         return None
69     return instance.raw_data