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
|
# -*- coding: ascii -*-
u"""
:Copyright:
Copyright 2014 - 2019
Andr\xe9 Malo or his licensors, as applicable
:License:
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================
Test Utilities
================
Test utilities.
"""
__author__ = u"Andr\xe9 Malo"
__docformat__ = "restructuredtext en"
import contextlib as _contextlib
import functools as _ft
import sys as _sys
import types as _types
from pytest import skip
try:
from unittest import mock # pylint: disable = unused-import
except ImportError:
import mock # noqa
try:
reload
except NameError:
# pylint: disable = redefined-builtin
try:
from importlib import reload
except ImportError:
from imp import reload
unset = object()
class Bunch(object):
""" Bunch object - represent all init kwargs as attributes """
def __init__(self, **kw):
""" Initialization """
self.__dict__.update(kw)
@_contextlib.contextmanager
def patched_import(what, how=unset):
"""
Context manager to mock an import statement temporarily
:Parameters:
`what` : ``str``
Name of the module to mock
`how` : any
How should it be replaced? If omitted or `unset`, a new MagicMock
instance is created. The result is yielded as context.
"""
_is_exc = lambda obj: isinstance(obj, BaseException) or (
isinstance(obj, (type, _types.ClassType))
and issubclass(obj, BaseException)
)
class FinderLoader(object):
""" Finder / Loader for meta path """
def __init__(self, fullname, module):
self.module = module
self.name = fullname
extra = '%s.' % fullname
for key in list(_sys.modules.keys()):
if key.startswith(extra):
del _sys.modules[key]
if fullname in _sys.modules:
del _sys.modules[fullname]
def find_module(self, fullname, path=None):
""" Find the module """
# pylint: disable = unused-argument
if fullname == self.name:
return self
return None
def load_module(self, fullname):
""" Load the module """
if _is_exc(self.module):
raise self.module
_sys.modules[fullname] = self.module
return self.module
realmodules = _sys.modules
try:
_sys.modules = dict(realmodules)
obj = FinderLoader(what, mock.MagicMock() if how is unset else how)
realpath = _sys.meta_path
try:
_sys.meta_path = [obj] + _sys.meta_path
old, parts = unset, what.rsplit('.', 1)
if len(parts) == 2:
parent, base = parts[0], parts[1]
if parent in _sys.modules:
parent = _sys.modules[parent]
if hasattr(parent, base):
old = getattr(parent, base)
setattr(parent, base, obj.module)
try:
yield obj.module
finally:
if old is not unset:
setattr(parent, base, old)
finally:
_sys.meta_path = realpath
finally:
_sys.modules = realmodules
def uni(value):
"""
Create unicode from raw string with unicode escapes
:Parameters:
`value` : ``str``
String, which encodes to ascii and decodes as unicode_escape
:Return: The decoded string
:Rtype: ``unicode``
"""
return value.encode('ascii').decode('unicode_escape')
class badstr(object): # pylint: disable = invalid-name
""" bad string """
def __str__(self):
raise RuntimeError("yo")
badstr = badstr()
class badbytes(object): # pylint: disable = invalid-name
""" bad bytes """
def __bytes__(self):
raise RuntimeError("yoyo")
if str is bytes:
__str__ = __bytes__
badbytes = badbytes()
class badbool(object): # pylint: disable = invalid-name
""" bad bool """
def __bool__(self):
raise RuntimeError("yoyo")
if str is bytes:
__nonzero__ = __bool__
badbool = badbool()
class baditer(object): # pylint: disable = invalid-name
""" bad iter """
def __init__(self, *what):
self._what = iter(what)
def __iter__(self):
return self
def __next__(self):
for item in self._what:
if isinstance(item, Exception):
raise item
return item
next = __next__
|