Passed
Push — master ( fdd80b...c492e3 )
by Olivier
03:48
created

_instantiate_node()   F

Complexity

Conditions 13

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 33
CRAP Score 15.1267

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 13
c 2
b 0
f 0
dl 0
loc 58
ccs 33
cts 43
cp 0.7674
crap 15.1267
rs 3.1873

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like _instantiate_node() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""
2
Instantiate a new node and its child nodes from a node type.
3
"""
4
5 1
import logging
6
7
8 1
from opcua import Node
9 1
from opcua import ua
10 1
from opcua.common import ua_utils
11 1
from opcua.common.copy_node import _rdesc_from_node, _read_and_copy_attrs
12
13
14 1
logger = logging.getLogger(__name__)
15
16
17 1
def instantiate(parent, node_type, nodeid=None, bname=None, dname=None, idx=0):
18
    """
19
    instantiate a node type under a parent node.
20
    nodeid and browse name of new node can be specified, or just namespace index
21
    If they exists children of the node type, such as components, variables and
22
    properties are also instantiated
23
    """
24 1
    rdesc = _rdesc_from_node(parent, node_type)
25 1
    rdesc.TypeDefinition = node_type.nodeid
26
27 1
    if nodeid is None:
28 1
        nodeid = ua.NodeId(namespaceidx=idx)  # will trigger automatic node generation in namespace idx
29 1
    if bname is None:
30
        bname = rdesc.BrowseName
31 1
    elif isinstance(bname, str):
32 1
        bname = ua.QualifiedName.from_string(bname)
33
34 1
    nodeids = _instantiate_node(parent.server, parent.nodeid, rdesc, nodeid, bname, dname=dname)
35 1
    return [Node(parent.server, nid) for nid in nodeids]
36
37
38 1
def _instantiate_node(server, parentid, rdesc, nodeid, bname, dname=None, recursive=True):
39
    """
40
    instantiate a node type under parent
41
    """
42 1
    node_type = Node(server, rdesc.NodeId)
43 1
    refs = node_type.get_referenced_nodes(refs=ua.ObjectIds.HasModellingRule)
44
45
    # skip optional elements
46 1
    if len(refs) == 1 and refs[0].nodeid == ua.NodeId(ua.ObjectIds.ModellingRule_Optional):
47
        return []
48
49 1
    addnode = ua.AddNodesItem()
50 1
    addnode.RequestedNewNodeId = nodeid
51 1
    addnode.BrowseName = bname
52 1
    addnode.ParentNodeId = parentid
53 1
    addnode.ReferenceTypeId = rdesc.ReferenceTypeId
54 1
    addnode.TypeDefinition = rdesc.TypeDefinition
55
56 1
    if rdesc.NodeClass in (ua.NodeClass.Object, ua.NodeClass.ObjectType):
57 1
        addnode.NodeClass = ua.NodeClass.Object
58 1
        _read_and_copy_attrs(node_type, ua.ObjectAttributes(), addnode)
59
60 1
    elif rdesc.NodeClass in (ua.NodeClass.Variable, ua.NodeClass.VariableType):
61 1
        addnode.NodeClass = ua.NodeClass.Variable
62 1
        _read_and_copy_attrs(node_type, ua.VariableAttributes(), addnode)
63
    elif rdesc.NodeClass in (ua.NodeClass.Method,):
64
        addnode.NodeClass = ua.NodeClass.Method
65
        _read_and_copy_attrs(node_type, ua.MethodAttributes(), addnode)
66
    elif rdesc.NodeClass in (ua.NodeClass.DataType,):
67
        addnode.NodeClass = ua.NodeClass.DataType
68
        _read_and_copy_attrs(node_type, ua.DataTypeAttributes(), addnode)
69
    else:
70
        logger.error("Instantiate: Node class not supported: %s", rdesc.NodeClass)
71
        raise RuntimeError("Instantiate: Node class not supported")
72
        return
73 1
    if dname is not None:
74 1
        addnode.NodeAttributes.DisplayName = dname
75
76 1
    res = server.add_nodes([addnode])[0]
77 1
    added_nodes = [res.AddedNodeId]
78
79 1
    if recursive:
80 1
        parents = ua_utils.get_node_supertypes(node_type, includeitself=True)
81 1
        node = Node(server, res.AddedNodeId)
82 1
        for parent in parents:
83 1
            descs = parent.get_children_descriptions(includesubtypes=False)
84 1
            for c_rdesc in descs:
85
                # skip items that already exists, prefer the 'lowest' one in object hierarchy
86 1
                if not ua_utils.is_child_present(node, c_rdesc.BrowseName):
87
                    # if root node being instantiated has a String NodeId, create the children with a String NodeId
88 1
                    if res.AddedNodeId.NodeIdType is ua.NodeIdType.String:
89 1
                        inst_nodeid = res.AddedNodeId.Identifier + "." + c_rdesc.BrowseName.Name
90 1
                        nodeids = _instantiate_node(server, res.AddedNodeId, c_rdesc, nodeid=ua.NodeId(identifier=inst_nodeid, namespaceidx=res.AddedNodeId.NamespaceIndex), bname=c_rdesc.BrowseName)
91
                    else:
92 1
                        nodeids = _instantiate_node(server, res.AddedNodeId, c_rdesc, nodeid=ua.NodeId(namespaceidx=res.AddedNodeId.NamespaceIndex), bname=c_rdesc.BrowseName)
93 1
                    added_nodes.extend(nodeids)
94
95 1
    return added_nodes
96
97
98