Passed
Pull Request — master (#171)
by Italo Valcy
03:12
created

build.tests.helpers   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 140
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 74
dl 0
loc 140
rs 10
c 0
b 0
f 0

5 Functions

Rating   Name   Duplication   Size   Complexity  
A get_link_mocked() 0 37 1
A id_to_interface_mock() 0 7 1
A get_uni_mocked() 0 28 1
A get_mocked_requests() 0 10 1
A get_controller_mock() 0 6 1

3 Methods

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