build.tests.helpers.get_controller_mock()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 0
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
"""Module to help to create tests."""
2 1
from unittest.mock import Mock
3
4 1
from kytos.core import Controller
5 1
from kytos.core.common import EntityStatus
6 1
from kytos.core.config import KytosConfig
7 1
from kytos.core.interface import TAG, TAGRange, UNI, Interface
8 1
from kytos.core.link import Link
9 1
from kytos.core.switch import Switch
10 1
from kytos.lib.helpers import get_interface_mock, get_switch_mock
11
12
13 1
def get_controller_mock():
14
    """Return a controller mock."""
15 1
    options = KytosConfig().options["daemon"]
16 1
    controller = Controller(options)
17 1
    controller.log = Mock()
18 1
    return controller
19
20
21 1
def id_to_interface_mock(interface_id):
22
    """Create mocked interface/switch from id."""
23 1
    switch_id = ":".join(interface_id.split(":")[:-1])
24 1
    port_id = int(interface_id.split(":")[-1])
25 1
    switch = get_switch_mock(switch_id, 0x04)
26 1
    switch.id = switch_id
27 1
    interface = get_interface_mock(port_id, port_id, switch)
28 1
    return interface
29
30
31 1
def get_link_mocked(**kwargs):
32
    """Return a link mocked.
33
34
    Args:
35
        link_dict: Python dict returned after call link.as_dict()
36
    """
37 1
    switch_a = kwargs.get("switch_a", Switch("00:00:00:00:00:01"))
38 1
    switch_b = kwargs.get("switch_b", Switch("00:00:00:00:00:02"))
39
40 1
    endpoint_a = Interface(
41
        kwargs.get("endpoint_a_name", "eth0"),
42
        kwargs.get("endpoint_a_port", 1),
43
        switch_a,
44
    )
45 1
    endpoint_b = Interface(
46
        kwargs.get("endpoint_b_name", "eth1"),
47
        kwargs.get("endpoint_b_port", 2),
48
        switch_b,
49
    )
50 1
    link = Mock(spec=Link, endpoint_a=endpoint_a, endpoint_b=endpoint_b)
51 1
    link.make_tags_available.return_value = True, True
52 1
    link.endpoint_a.link = link
53 1
    link.endpoint_b.link = link
54 1
    link.as_dict.return_value = kwargs.get(
55
        "link_dict", {"id": kwargs.get("link_id", 1)}
56
    )
57
58 1
    link.status = kwargs.get("status", EntityStatus.DOWN)
59
60 1
    metadata = kwargs.get("metadata", {})
61
62 1
    def side_effect(key):
63
        """Mock Link get metadata."""
64 1
        return Mock(value=metadata.get(key))
65
66 1
    link.get_metadata = Mock(side_effect=side_effect)
67 1
    link.metadata = metadata
68
69 1
    return link
70
71
72 1
def get_mocked_requests(_):
73
    """Mock requests.get."""
74
    return MockResponse(
75
        {
76
            "links": {
77
                "abc": {"active": False, "enabled": True},
78
                "def": {"active": True, "enabled": True},
79
            }
80
        },
81
        200,
82
    )
83
84
85 1
def get_uni_mocked(**kwargs):
86
    """Create an uni mocked.
87
88
    Args:
89
        interface_name(str): Interface name. Defaults to "eth1".
90
        interface_port(int): Interface pror. Defaults to 1.
91
        tag_type(str): Type of a tag. Defaults to 'vlan'.
92
        tag_value(int): Value of a tag. Defaults to 81
93
        is_valid(bool): Value returned by is_valid method.
94
                        Defaults to False.
95
    """
96 1
    interface_name = kwargs.get("interface_name", "eth1")
97 1
    interface_port = kwargs.get("interface_port", 1)
98 1
    tag_type = kwargs.get("tag_type", 'vlan')
99 1
    tag_value = kwargs.get("tag_value", 81)
100 1
    is_valid = kwargs.get("is_valid", False)
101 1
    switch = Mock(spec=Switch)
102 1
    switch.id = kwargs.get("switch_id", "custom_switch_id")
103 1
    switch.dpid = kwargs.get("switch_dpid", "custom_switch_dpid")
104 1
    interface = Interface(interface_name, interface_port, switch)
105 1
    if isinstance(tag_value, list):
106 1
        tag = TAGRange(tag_type, tag_value)
107
    else:
108 1
        tag = TAG(tag_type, tag_value)
109 1
    uni = Mock(spec=UNI, interface=interface, user_tag=tag)
110 1
    uni.is_valid.return_value = is_valid
111 1
    uni.as_dict.return_value = {
112
        "interface_id": f"switch_mock:{interface_port}",
113
        "tag": tag.as_dict(),
114
    }
115 1
    return uni
116
117
118 1
class MockResponse:
119
    """
120
    Mock a httpx response object.
121
122
    Just define a function and add the patch decorator to the test.
123
    Example:
124
    def mocked_requests_get(*args, **kwargs):
125
        return MockResponse({}, 200)
126
    @patch('httpx.get', side_effect=mocked_requests_get)
127
128
    """
129
130 1
    def __init__(self, json_data, status_code):
131
        """Create mock response object with parameters.
132
133
        Args:
134
            json_data: JSON response content
135
            status_code: HTTP status code.
136
        """
137
        self.json_data = json_data
138
        self.status_code = status_code
139
140 1
    def json(self):
141
        """Return the response json data."""
142
        return self.json_data
143
144 1
    def __str__(self):
145
        return self.__class__.__name__
146