1 # -*- coding: utf-8 -*-
3 # Copyright 2018 University of Bristol - High Performance Networks Research
7 # Contributors: Anderson Bravalheri, Dimitrios Gkounis, Abubakar Siddique
8 # Muqaddas, Navdeep Uniyal, Reza Nejabati and Dimitra Simeonidou
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
14 # http://www.apache.org/licenses/LICENSE-2.0
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
22 # For those usages not covered by the Apache License, Version 2.0 please
23 # contact with: <highperformance-networks@bristol.ac.uk>
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.
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.
37 from collections
import defaultdict
39 from io
import StringIO
41 from unittest
.mock
import MagicMock
, patch
43 logger
= logging
.getLogger()
46 class TestCaseWithLogging(unittest
.TestCase
):
47 """Attach a special handler to the root logger, capturing the logs in a
48 internal buffer (caplog property).
50 To retrieve the logs, do::
52 self.caplog.getvalue()
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
)
63 super(TestCaseWithLogging
, self
).tearDown()
64 self
.log_handler
.close()
65 self
.logger
.removeHandler(self
.log_handler
)
68 def mock_imports(modules
, preserve
=()):
69 """Given a list of modules, mock everything, unless listed in the preserve
73 if isinstance(modules
, str):
75 if isinstance(preserve
, str):
76 preserve
= (preserve
,)
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']
83 parts
= name
.split('.')
86 compound_name
.append(part
)
87 all_modules
.append('.'.join(compound_name
))
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
)
93 mocks
= {module
: MagicMock() for module
in all_modules
}
95 return patch
.dict('sys.modules', **mocks
)
98 def mock_dict(**kwargs
):
99 """Create a dict that always respond something.
102 **kwargs: certain items that should be set in the created object
104 response
= defaultdict(MagicMock
)
105 for k
, v
in kwargs
.items():
111 def mock_object(**kwargs
):
112 """Create an object that always respond something.
115 **kwargs: certain attributes that should be set in the created object
117 response
= MagicMock()
118 for k
, v
in kwargs
.items():
119 setattr(response
, k
, v
)