summaryrefslogtreecommitdiff
path: root/tests/unittests/test_reporting.py
blob: f4011a79a26d754405639e3cfde22a96adec74b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# Copyright 2015 Canonical Ltd.
# This file is part of cloud-init.  See LICENCE file for license information.
#
# vi: ts=4 expandtab

from cloudinit import reporting

from .helpers import (mock, TestCase)


def _fake_registry():
    return mock.Mock(registered_items={'a': mock.MagicMock(),
                                       'b': mock.MagicMock()})


class TestReportStartEvent(TestCase):

    @mock.patch('cloudinit.reporting.instantiated_handler_registry',
                new_callable=_fake_registry)
    def test_report_start_event_passes_something_with_as_string_to_handlers(
            self, instantiated_handler_registry):
        event_name, event_description = 'my_test_event', 'my description'
        reporting.report_start_event(event_name, event_description)
        expected_string_representation = ': '.join(
            ['start', event_name, event_description])
        for _, handler in (
                instantiated_handler_registry.registered_items.items()):
            self.assertEqual(1, handler.publish_event.call_count)
            event = handler.publish_event.call_args[0][0]
            self.assertEqual(expected_string_representation, event.as_string())


class TestReportFinishEvent(TestCase):

    def _report_finish_event(self, successful=None):
        event_name, event_description = 'my_test_event', 'my description'
        reporting.report_finish_event(
            event_name, event_description, successful=successful)
        return event_name, event_description

    def assertHandlersPassedObjectWithAsString(
            self, handlers, expected_as_string):
        for _, handler in handlers.items():
            self.assertEqual(1, handler.publish_event.call_count)
            event = handler.publish_event.call_args[0][0]
            self.assertEqual(expected_as_string, event.as_string())

    @mock.patch('cloudinit.reporting.instantiated_handler_registry',
                new_callable=_fake_registry)
    def test_report_finish_event_passes_something_with_as_string_to_handlers(
            self, instantiated_handler_registry):
        event_name, event_description = self._report_finish_event()
        expected_string_representation = ': '.join(
            ['finish', event_name, event_description])
        self.assertHandlersPassedObjectWithAsString(
            instantiated_handler_registry.registered_items,
            expected_string_representation)

    @mock.patch('cloudinit.reporting.instantiated_handler_registry',
                new_callable=_fake_registry)
    def test_reporting_successful_finish_has_sensible_string_repr(
            self, instantiated_handler_registry):
        event_name, event_description = self._report_finish_event(
            successful=True)
        expected_string_representation = ': '.join(
            ['finish', event_name, 'success', event_description])
        self.assertHandlersPassedObjectWithAsString(
            instantiated_handler_registry.registered_items,
            expected_string_representation)

    @mock.patch('cloudinit.reporting.instantiated_handler_registry',
                new_callable=_fake_registry)
    def test_reporting_unsuccessful_finish_has_sensible_string_repr(
            self, instantiated_handler_registry):
        event_name, event_description = self._report_finish_event(
            successful=False)
        expected_string_representation = ': '.join(
            ['finish', event_name, 'fail', event_description])
        self.assertHandlersPassedObjectWithAsString(
            instantiated_handler_registry.registered_items,
            expected_string_representation)


class TestReportingEvent(TestCase):

    def test_as_string(self):
        event_type, name, description = 'test_type', 'test_name', 'test_desc'
        event = reporting.ReportingEvent(event_type, name, description)
        expected_string_representation = ': '.join(
            [event_type, name, description])
        self.assertEqual(expected_string_representation, event.as_string())


class TestReportingHandler(TestCase):

    def test_no_default_publish_event_implementation(self):
        self.assertRaises(NotImplementedError,
                          reporting.ReportingHandler().publish_event, None)


class TestLogHandler(TestCase):

    @mock.patch.object(reporting.logging, 'getLogger')
    def test_appropriate_logger_used(self, getLogger):
        event_type, event_name = 'test_type', 'test_name'
        event = reporting.ReportingEvent(event_type, event_name, 'description')
        reporting.LogHandler().publish_event(event)
        self.assertEqual(
            [mock.call(
                'cloudinit.reporting.{0}.{1}'.format(event_type, event_name))],
            getLogger.call_args_list)

    @mock.patch.object(reporting.logging, 'getLogger')
    def test_single_log_message_at_info_published(self, getLogger):
        event = reporting.ReportingEvent('type', 'name', 'description')
        reporting.LogHandler().publish_event(event)
        self.assertEqual(1, getLogger.return_value.info.call_count)

    @mock.patch.object(reporting.logging, 'getLogger')
    def test_log_message_uses_event_as_string(self, getLogger):
        event = reporting.ReportingEvent('type', 'name', 'description')
        reporting.LogHandler().publish_event(event)
        self.assertIn(event.as_string(),
                      getLogger.return_value.info.call_args[0][0])


class TestDefaultRegisteredHandler(TestCase):

    def test_log_handler_registered_by_default(self):
        registered_items = (
            reporting.instantiated_handler_registry.registered_items)
        for _, item in registered_items.items():
            if isinstance(item, reporting.LogHandler):
                break
        else:
            self.fail('No reporting LogHandler registered by default.')


class TestReportingConfiguration(TestCase):

    @mock.patch.object(reporting, 'instantiated_handler_registry')
    def test_empty_configuration_doesnt_add_handlers(
            self, instantiated_handler_registry):
        reporting.add_configuration({})
        self.assertEqual(
            0, instantiated_handler_registry.register_item.call_count)

    @mock.patch.object(
        reporting, 'instantiated_handler_registry', reporting.DictRegistry())
    @mock.patch.object(reporting, 'available_handlers')
    def test_looks_up_handler_by_type_and_adds_it(self, available_handlers):
        handler_type_name = 'test_handler'
        handler_cls = mock.Mock()
        available_handlers.registered_items = {handler_type_name: handler_cls}
        handler_name = 'my_test_handler'
        reporting.add_configuration(
            {handler_name: {'type': handler_type_name}})
        self.assertEqual(
            {handler_name: handler_cls.return_value},
            reporting.instantiated_handler_registry.registered_items)

    @mock.patch.object(
        reporting, 'instantiated_handler_registry', reporting.DictRegistry())
    @mock.patch.object(reporting, 'available_handlers')
    def test_uses_non_type_parts_of_config_dict_as_kwargs(
            self, available_handlers):
        handler_type_name = 'test_handler'
        handler_cls = mock.Mock()
        available_handlers.registered_items = {handler_type_name: handler_cls}
        extra_kwargs = {'foo': 'bar', 'bar': 'baz'}
        handler_config = extra_kwargs.copy()
        handler_config.update({'type': handler_type_name})
        handler_name = 'my_test_handler'
        reporting.add_configuration({handler_name: handler_config})
        self.assertEqual(
            handler_cls.return_value,
            reporting.instantiated_handler_registry.registered_items[
                handler_name])
        self.assertEqual([mock.call(**extra_kwargs)],
                         handler_cls.call_args_list)

    @mock.patch.object(
        reporting, 'instantiated_handler_registry', reporting.DictRegistry())
    @mock.patch.object(reporting, 'available_handlers')
    def test_handler_config_not_modified(self, available_handlers):
        handler_type_name = 'test_handler'
        handler_cls = mock.Mock()
        available_handlers.registered_items = {handler_type_name: handler_cls}
        handler_config = {'type': handler_type_name, 'foo': 'bar'}
        expected_handler_config = handler_config.copy()
        reporting.add_configuration({'my_test_handler': handler_config})
        self.assertEqual(expected_handler_config, handler_config)