blob: 787fbced9e3ff7c2cec363cd5ad37060bac6ee1c [file] [log] [blame]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001# -*- coding: utf-8 -*-
2##
3# Copyright 2018 University of Bristol - High Performance Networks Research
4# Group
5# All Rights Reserved.
6#
7# Contributors: Anderson Bravalheri, Dimitrios Gkounis, Abubakar Siddique
8# Muqaddas, Navdeep Uniyal, Reza Nejabati and Dimitra Simeonidou
9#
10# Licensed under the Apache License, Version 2.0 (the "License"); you may
11# not use this file except in compliance with the License. You may obtain
12# a copy of the License at
13#
14# http://www.apache.org/licenses/LICENSE-2.0
15#
16# Unless required by applicable law or agreed to in writing, software
17# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
19# License for the specific language governing permissions and limitations
20# under the License.
21#
22# For those usages not covered by the Apache License, Version 2.0 please
23# contact with: <highperformance-networks@bristol.ac.uk>
24#
25# Neither the name of the University of Bristol nor the names of its
26# contributors may be used to endorse or promote products derived from
27# this software without specific prior written permission.
28#
29# This work has been performed in the context of DCMS UK 5G Testbeds
30# & Trials Programme and in the framework of the Metro-Haul project -
31# funded by the European Commission under Grant number 761727 through the
32# Horizon 2020 and 5G-PPP programmes.
33##
34
35import logging
36import unittest
37from collections import defaultdict
38
39from six import StringIO
40
41from mock import MagicMock, patch
42
43logger = logging.getLogger()
44
45
46class TestCaseWithLogging(unittest.TestCase):
47 """Attach a special handler to the root logger, capturing the logs in a
48 internal buffer (caplog property).
49
50 To retrieve the logs, do::
51
52 self.caplog.getvalue()
53 """
54 def setUp(self):
55 super(TestCaseWithLogging, self).setUp()
56 self.logger = logging.getLogger()
57 self.caplog = StringIO()
58 self.log_handler = logging.StreamHandler(self.caplog)
59 self.logger.addHandler(self.log_handler)
60 self.logger.setLevel(logging.NOTSET)
61
62 def tearDown(self):
63 super(TestCaseWithLogging, self).tearDown()
64 self.log_handler.close()
65 self.logger.removeHandler(self.log_handler)
66
67
68def mock_imports(modules, preserve=()):
69 """Given a list of modules, mock everything, unless listed in the preserve
70 argument.
71 """
72 # Ensure iterable
73 if isinstance(modules, str):
74 modules = (modules,)
75 if isinstance(preserve, str):
76 preserve = (preserve,)
77
78 # First expand the list, since children modules needs their parent also
79 # mocked most of the time.
80 # Example: ['Crypto.PublicKey'] => ['Crypto', 'Crypto.PublicKey']
81 all_modules = []
82 for name in modules:
83 parts = name.split('.')
84 compound_name = []
85 for part in parts:
86 compound_name.append(part)
87 all_modules.append('.'.join(compound_name))
88
89 all_modules = set(m for m in all_modules if m not in preserve)
90 for module in all_modules:
91 logger.info('Mocking module `%s`', module)
92
93 mocks = {module: MagicMock() for module in all_modules}
94
95 return patch.dict('sys.modules', **mocks)
96
97
98def mock_dict(**kwargs):
99 """Create a dict that always respond something.
100
101 Arguments:
102 **kwargs: certain items that should be set in the created object
103 """
104 response = defaultdict(MagicMock)
105 for k, v in kwargs.items():
106 response[k] = v
107
108 return response
109
110
111def mock_object(**kwargs):
112 """Create an object that always respond something.
113
114 Arguments:
115 **kwargs: certain attributes that should be set in the created object
116 """
117 response = MagicMock()
118 for k, v in kwargs.items():
119 setattr(response, k, v)
120
121 return response