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
|
# *****************************************************************************
#
# 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.
#
# See NOTICE file for details.
#
# *****************************************************************************
import multiprocessing as mp
import inspect
import os
import sys
import traceback
import queue
import unittest
import common
_modules = {} # type: ignore[var-annotated]
def _import(filename):
import importlib.util
module_name = os.path.basename(filename)[:-3]
dirname = os.path.dirname(filename)
if filename in _modules:
return _modules[filename]
spec = importlib.util.spec_from_file_location(
module_name, filename, submodule_search_locations=[dirname])
origin = importlib.util.module_from_spec(spec)
sys.modules[module_name] = origin
spec.loader.exec_module(origin)
_modules[filename] = origin
return origin
def _execute(inQueue, outQueue):
while True:
datum = inQueue.get()
if datum is None:
break
ex = None
ret = None
(func_name, func_file, args, kwargs) = datum
try:
module = _import(func_file)
func = getattr(module, func_name)
ret = func(*args, **kwargs)
except Exception as ex1:
traceback.print_exc()
ex = ex1
# This may fail if we get a Java exception so timeout is used
outQueue.put([ret, ex])
class Client(object):
def __init__(self):
self.start()
def start(self):
ctx = mp.get_context("spawn")
self.inQueue = ctx.Queue()
self.outQueue = ctx.Queue()
self.process = ctx.Process(target=_execute, args=(self.inQueue, self.outQueue), daemon=True)
self.process.start()
self.timeout = 20
def execute(self, function, *args, **kwargs):
self.inQueue.put([function.__name__, os.path.abspath(
inspect.getfile(function)), args, kwargs])
try:
(ret, ex) = self.outQueue.get(True, self.timeout)
except queue.Empty:
raise AssertionError("function {func} FAILED with args: {args} and kwargs: {kwargs}"
.format(func=function, args=args, kwargs=kwargs))
if ex is not None:
raise ex
return ret
def restart(self):
self.stop()
self.start()
def stop(self):
self.inQueue.put(None)
self.process.join()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.stop()
return False
def TestCase(cls=None, **kwargs):
""" Decorator that makes tests run in a subprocess """
if cls:
return _prepare(cls)
def modify(cls):
return _prepare(cls, **kwargs)
return modify
def _hook(filename, clsname, funcname, *args):
module = _import(filename)
cls = getattr(module, clsname)
inst = '_instance_%s' % cls.__name__
if not inst in module.__dict__:
setattr(module, inst, cls())
inst = getattr(module, inst)
getattr(inst, funcname)(*args)
def _prepare(orig, individual=False):
clsname = orig.__name__
filename = os.path.abspath(inspect.getfile(orig))
class ProxyClass(orig):
def __init__(self, *args):
orig.__init__(self, *args)
@classmethod
def tearDownClass(cls):
ProxyClass._client.execute(
_hook, filename, clsname, '_tearDownClass')
ProxyClass._client.stop()
@classmethod
def setUpClass(cls):
ProxyClass._client = Client()
ProxyClass._client.execute(_hook, filename, clsname, '_setUpClass')
def setUp(self):
if common.fast:
raise unittest.SkipTest("fast")
if individual:
ProxyClass._client.restart()
ProxyClass._client.execute(_hook, filename, clsname, '_setUp')
if hasattr(self, "setUpLocals"):
ProxyClass._client.execute(
_hook, filename, clsname, '_set', self.setUpLocals())
def _set(self, dic):
for k, v in dic.items():
setattr(self, k, v)
def tearDown(self):
ProxyClass._client.execute(_hook, filename, clsname, '_tearDown')
class ProxyMethod(object):
def __init__(self, name):
self.name = name
self.__name__ = name
self.__qualname__ = "%s.%s" % (clsname, name)
def __call__(self):
ProxyClass._client.execute(_hook, filename, clsname, self.name)
for k, v in orig.__dict__.items():
if k.startswith("test"):
test = ProxyMethod("_" + k)
test.__name__ = k
type.__setattr__(ProxyClass, k, test)
type.__setattr__(ProxyClass, "_" + k, v)
type.__setattr__(ProxyClass, "_setUp", orig.setUp)
type.__setattr__(ProxyClass, "_setUpClass", orig.setUpClass)
type.__setattr__(ProxyClass, "_tearDown", orig.tearDown)
type.__setattr__(ProxyClass, "_tearDownClass", orig.tearDownClass)
return ProxyClass
|