Create wrapper to sys.exc_info

try:
     ...
 except SomeException:
     with tobiko.exc_info():
         # It will reraise original exception at the end of this block
         ...

Change-Id: Icad6bdd7261dd9b972b5b33110041876ca488070
This commit is contained in:
Federico Ressi 2019-06-26 16:24:02 +02:00
parent 87bb3fc2be
commit ae4accef4e
4 changed files with 55 additions and 1 deletions

View File

@ -26,6 +26,7 @@ fail = _asserts.fail
TobikoException = _exception.TobikoException
check_valid_type = _exception.check_valid_type
exc_info = _exception.exc_info
is_fixture = _fixture.is_fixture
get_fixture = _fixture.get_fixture

View File

@ -13,6 +13,15 @@
# under the License.
from __future__ import absolute_import
import collections
import sys
from oslo_log import log
import six
LOG = log.getLogger(__name__)
class TobikoException(Exception):
"""Base Tobiko Exception.
@ -72,3 +81,27 @@ def check_valid_type(obj, *valid_types):
obj, types_str)
raise TypeError(message)
return obj
class ExceptionInfo(collections.namedtuple('ExceptionInfo',
['type', 'value', 'traceback'])):
reraise_on_exit = True
def __enter__(self):
return self
def __exit__(self, _type, _value, _traceback):
if self.reraise_on_exit:
LOG.exception("Exception occurred while handling %s(%s) "
"exception.", _type, _value)
self.reraise()
def reraise(self):
six.reraise(*self)
def exc_info(reraise=True):
info = ExceptionInfo(*sys.exc_info())
info.reraise_on_exit = reraise
return info

View File

@ -82,7 +82,7 @@ class AnsibleManager(object):
'username': credentials.username,
'project_name': credentials.project_name,
'password': credentials.project_name.password,
'image': CONF.tobiko.nova.image,
'image': CONF.tobiko.glance.cirros_image,
'flavor': CONF.tobiko.nova.flavor}
self.variable_manager.extra_vars = extra_vars

View File

@ -13,6 +13,8 @@
# under the License.
from __future__ import absolute_import
import sys
import tobiko
from tobiko.tests import unit
@ -102,3 +104,21 @@ class TestCheckValidType(unit.TobikoUnitTest):
).format(repr(obj), tyes_str)
self.assertEqual(message, str(ex))
class TestExcInfo(unit.TobikoUnitTest):
def test_exc_info(self):
try:
raise RuntimeError('some error')
except RuntimeError:
exc_info = tobiko.exc_info()
exc_type, exc_value, traceback = sys.exc_info()
self.assertEqual((exc_type, exc_value, traceback), exc_info)
self.assertIs(RuntimeError, exc_info.type)
self.assertIs(exc_value, exc_info.value)
self.assertIs(traceback, exc_info.traceback)
reraised = self.assertRaises(RuntimeError, exc_info.reraise)
self.assertIs(exc_value, reraised)