Best Python code snippet using Testify_python
test_result.py
Source:test_result.py  
...19import traceback20import six21from testify.utils import inspection22__testify = 123def plain_tb_formatter(etype, value, tb, length=None):24    # We want our formatters to return a string.25    return ''.join(traceback.format_exception(etype, value, tb, length))26class TestResult(object):27    debug = False28    def __init__(self, test_method, runner_id=None):29        super(TestResult, self).__init__()30        self.test_method = test_method31        self.test_method_name = test_method.__name__32        self.success = self.failure = self.error = self.interrupted = None33        self.run_time = self.start_time = self.end_time = None34        self.exception_infos = []35        self.complete = False36        self.previous_run = None37        self.runner_id = runner_id38    @property39    def exception_info(self):40        raise AttributeError(41            'The exception_info attribute has been replaced with the .exception_infos list. Please update your code.',42        )43    def start(self, previous_run=None):44        self.previous_run = previous_run45        self.start_time = datetime.datetime.now()46    def record(self, function):47        """Excerpted code for executing a block of code that might raise an48        exception, requiring us to update a result object.49        Return value is a boolean describing whether the block was successfully50        executed without exceptions.51        """52        try:53            function()54        except BaseException as exception:55            # some code may want to use an alternative exc_info for an exception56            # (for instance, in an event loop). You can signal an alternative57            # stack to use by adding a _testify_exc_tb attribute to the58            # exception object59            if hasattr(exception, '_testify_exc_tb'):60                exc_info = (type(exception), exception, exception._testify_exc_tb)61            else:62                exc_info = sys.exc_info()63            self.end_in_failure(exc_info)64            if self.debug:65                self._postmortem(exc_info)66            return False67        else:68            return True69    def _postmortem(self, exc_info):70        _, _, traceback = exc_info71        print("\nDEBUGGER")72        print(self.format_exception_info())73        try:74            detected_postmortem_tool = __import__('ipdb').post_mortem75        except ImportError:76            detected_postmortem_tool = __import__('pdb').post_mortem77        detected_postmortem_tool(traceback)78    def _complete(self):79        self.complete = True80        self.end_time = datetime.datetime.now()81        self.run_time = self.end_time - self.start_time82    def end_in_failure(self, exception_info):83        if not self.complete:84            self._complete()85        self.success = False86        if isinstance(exception_info[1], AssertionError):87            # test failure, kinda expect these vs. unknown errors88            self.failure = True89        elif isinstance(exception_info[1], KeyboardInterrupt):90            self.interrupted = True91        else:92            self.error = True93        self.exception_infos.append(exception_info)94    def end_in_success(self):95        if not self.complete:96            self._complete()97            self.success = True98    def __make_multi_error_message(self, formatter):99        result = []100        for exception_info in self.exception_infos:101            exctype, value, tb = exception_info102            part = formatter(exctype, value, tb)103            result.append(part)104        if len(result) == 1:105            return result[0]106        else:107            # Meant to match the python3 multiple-exception support:108            #   http://docs.python.org/3.1/reference/simple_stmts.html#the-raise-statement109            return '\nDuring handling of the above exception, another exception occurred:\n\n'.join(result)110    def format_exception_info(self, pretty=False):111        if not self.exception_infos:112            return None113        def is_relevant_tb_level(tb):114            if '__testify' in tb.tb_frame.f_globals:115                # nobody *wants* to read testify116                return False117            else:118                return True119        def count_relevant_tb_levels(tb):120            # count up to the *innermost* relevant frame121            length = 0122            relevant = 0123            while tb:124                length += 1125                if is_relevant_tb_level(tb):126                    relevant = length127                tb = tb.tb_next128            return relevant129        def formatter(exctype, value, tb):130            # Skip test runner traceback levels at the top.131            while tb and not is_relevant_tb_level(tb):132                tb = tb.tb_next133            if exctype is AssertionError:134                # Skip testify.assertions traceback levels at the bottom.135                length = count_relevant_tb_levels(tb)136                return plain_tb_formatter(exctype, value, tb, length)137            elif not tb:138                return "Exception: %r (%r)" % (exctype, value)139            else:140                return plain_tb_formatter(exctype, value, tb)141        return self.__make_multi_error_message(formatter)142    def format_exception_only(self):143        def formatter(exctype, value, tb):144            return ''.join(traceback.format_exception_only(exctype, value))145        return self.__make_multi_error_message(formatter)146    def to_dict(self):147        test_method_self_t = type(six.get_method_self(self.test_method))148        assert not isinstance(test_method_self_t, type(None))149        return {150            'previous_run': self.previous_run,151            'start_time': time.mktime(self.start_time.timetuple()) if self.start_time else None,152            'end_time': time.mktime(self.end_time.timetuple()) if self.end_time else None,153            'run_time': (154                self.run_time.seconds + float(self.run_time.microseconds) / 1000000...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
