Passed
Pull Request — master (#957)
by Rogerio
02:39
created

TestController.test_debug_on()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
"""Test kytos.core.controller module."""
2
import asyncio
3
import json
4
import logging
5
import warnings
6
from copy import copy
7
from unittest import TestCase
8
from unittest.mock import Mock, patch
9
10
from kytos.core import Controller
11
from kytos.core.config import KytosConfig
12
13
14
class TestController(TestCase):
15
    """Controller tests."""
16
17
    def setUp(self):
18
        """Instantiate a controller."""
19
20
        self.loop = asyncio.new_event_loop()
21
        asyncio.set_event_loop(None)
22
23
        self.options = KytosConfig().options['daemon']
24
        self.controller = Controller(self.options, loop=self.loop)
25
        self.controller.log = Mock()
26
27
    def test_configuration_endpoint(self):
28
        """Should return the attribute options as json."""
29
        serializable_options = vars(self.options)
30
        expected = json.dumps(serializable_options)
31
        actual = self.controller.configuration_endpoint()
32
        self.assertEqual(expected, actual)
33
34
    @staticmethod
35
    @patch('kytos.core.controller.LogManager')
36
    @patch('kytos.core.logs.Path')
37
    def test_websocket_log_usage(path, log_manager):
38
        """Assert that the web socket log is used."""
39
        loop = asyncio.new_event_loop()
40
        asyncio.set_event_loop(None)
41
42
        # Save original state
43
        handlers_bak = copy(logging.root.handlers)
44
45
        # Minimum to instantiate Controller
46
        options = Mock(napps='')
47
        path.return_value.exists.return_value = False
48
        controller = Controller(options, loop=loop)
49
50
        # The test
51
        controller.enable_logs()
52
        log_manager.enable_websocket.assert_called_once()
53
54
        # Restore original state
55
        logging.root.handlers = handlers_bak
56
57
    def test_unload_napp_listener(self):
58
        """Call NApp shutdown listener on unload."""
59
        username, napp_name = 'test', 'napp'
60
        listener = self._add_napp(username, napp_name)
61
62
        listener.assert_not_called()
63
        self.controller.unload_napp(username, napp_name)
64
        listener.assert_called()
65
66
    def test_unload_napp_other_listener(self):
67
        """Should not call other NApps' shutdown listener on unload."""
68
        username, napp_name = 'test', 'napp1'
69
        self._add_napp(username, napp_name)
70
        other_listener = self._add_napp('test', 'napp2')
71
72
        self.controller.unload_napp(username, napp_name)
73
        other_listener.assert_not_called()
74
75
    def _add_napp(self, username, napp_name):
76
        """Add a mocked NApp to the controller."""
77
        napp_id = f'{username}/{napp_name}'
78
        event_name = f'kytos/core.shutdown.{napp_id}'
79
        listener = Mock()
80
        self.controller.events_listeners[event_name] = [listener]
81
        napp = Mock(_listeners={})
82
        self.controller.napps[(username, napp_name)] = napp
83
        return listener
84
85
    def test_deprecation_warning(self):
86
        """Deprecated method should suggest @rest decorator."""
87
        with warnings.catch_warnings(record=True) as wrngs:
88
            warnings.simplefilter("always")  # trigger all warnings
89
            self.controller.register_rest_endpoint('x', lambda x: x, ['GET'])
90
            self.assertEqual(1, len(wrngs))
91
            warning = wrngs[0]
92
            self.assertEqual(warning.category, DeprecationWarning)
93
            self.assertIn('@rest', str(warning.message))
94
95
    def test_loggers(self):
96
        """Test that all controller loggers are under kytos
97
        hierachy logger"""
98
        loggers = self.controller.loggers()
99
        for logger in loggers:
100
            self.assertTrue(logger.name.startswith("kytos"))
101
102
    def test_debug_on(self):
103
        """Test the enable debug feature."""
104
        # Enable debug for kytos.core
105
        self.controller.debug("kytos.core", 1)
106
        self._test_debug_result()
107
108
    def test_debug_on_defaults(self):
109
        """Test the enable debug feature. Test the default parameter"""
110
        # Enable debug for kytos.core
111
        self.controller.debug("kytos.core")
112
        self._test_debug_result()
113
114
    def _test_debug_result(self):
115
        """Verify if the loggers have level debug."""
116
        loggers = self.controller.loggers()
117
        for logger in loggers:
118
            # Check if all kytos.core loggers are in DEBUG mode.
119
            # All the rest must remain the same.
120
            if logger.name.startswith("kytos.core"):
121
                self.assertTrue(logger.getEffectiveLevel(), logging.DEBUG)
122
            else:
123
                self.assertTrue(logger.getEffectiveLevel(), logging.CRITICAL)
124
125
    def test_debug_off(self):
126
        """Test the disable debug feature"""
127
        # Fist we enable the debug
128
        self.controller.debug("kytos.core", 1)
129
        # ... then we disable the debug for the test
130
        self.controller.debug("kytos.core", 0)
131
        loggers = self.controller.loggers()
132
        for logger in loggers:
133
            self.assertTrue(logger.getEffectiveLevel(), logging.CRITICAL)
134