Skip to content

Commit

Permalink
Merge pull request #12 from QualiSystems/feature/borismod_context2
Browse files Browse the repository at this point in the history
add ErrorHandlingContext class
  • Loading branch information
borismod committed Jul 21, 2016
2 parents 4d871e7 + 9041e89 commit 2e3f769
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
44 changes: 44 additions & 0 deletions cloudshell/core/context/error_handling_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import traceback

from cloudshell.core.context.context_service import ContextBasedService


class ErrorHandlingContext(ContextBasedService):
def __init__(self, context, logger):
"""
Initializes an instance of ErrorHandlingContext
Allows proper logging on exception
:param context: ResourceCommandContext
:param logger: Logger
:type logger: Logger
"""
self.context = context
self.logger = logger

def get_objects(self):
"""
Returns context instance. Should not be called explicitly
:return: ErrorHandlingContext
:rtype ErrorHandlingContext
"""
return self

def context_started(self):
"""
Called upon block start. Should not be called explicitly
:return: ErrorHandlingContext
:rtype ErrorHandlingContext
"""
return self

def context_ended(self, exc_type, exc_value, exc_traceback):
"""
Called upon block end. Should not be called explicitly
In case of exception during the block execution logs the error with debug severity
and allows the same exception to be thrown
:return: ErrorHandlingContext
:rtype ErrorHandlingContext
"""
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
self.logger.error('Error occurred: ' + ''.join(lines))
return False
19 changes: 19 additions & 0 deletions tests/core/context/test_error_handling_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from unittest import TestCase

from mock import Mock, MagicMock

from cloudshell.core.context.error_handling_context import ErrorHandlingContext


class TestLoggingSession(TestCase):

def test_log_written_when_exception_occurs(self):
context = Mock()
logger = Mock()
logger.error = MagicMock()
try:
with ErrorHandlingContext(context=context, logger=logger):
raise ValueError('some value error occurred')
except ValueError:
self.assertTrue(logger.error.called)

0 comments on commit 2e3f769

Please sign in to comment.