Best Python code snippet using unittest-xml-reporting_python
test.py
Source:test.py  
1import functools2import itertools3from types import GeneratorType4from ..exception_handling import handling_exceptions5from ..exceptions import SkipTest, InvalidTest6from .fixtures.parameters import bound_parametrizations_context7from .runnable_test import RunnableTest8from .runnable_test_factory import RunnableTestFactory9from .requirements import get_requirements10from .tagging import get_tags11from .fixtures.utils import nofixtures12class TestTestFactory(RunnableTestFactory):13    def __init__(self, testclass):14        super(TestTestFactory, self).__init__(testclass)15        self.testclass = testclass16    def get_class_name(self):17        return self.testclass.__name__18    def _generate_tests(self, fixture_store):19        if is_abstract_base_class(self.testclass):20            return21        for test_method_name in dir(self.testclass):22            if not test_method_name.startswith("test"):23                continue24            for fixture_variation in self._iter_parametrization_variations(test_method_name, fixture_store):25                case = self.testclass(26                    test_method_name,27                    fixture_store=fixture_store,28                    fixture_namespace=fixture_store.get_current_namespace(),29                    variation=fixture_variation,30                )31                if self.testclass.__slash_skipped__:32                    case.run = functools.partial(SkipTest.throw, self.testclass.__slash_skipped_reason__)33                yield case  # pylint: disable=protected-access34    def _iter_parametrization_variations(self, test_method_name, fixture_store):35        return fixture_store.iter_parametrization_variations(methods=itertools.chain(36            zip(itertools.repeat('before'), self._get_all_before_methods()),37            zip(itertools.repeat('after'), self._get_all_after_methods()),38            [getattr(self.testclass, test_method_name)],39        ))40    def _get_all_before_methods(self):41        return self._iter_inherited_methods('before')42    def _get_all_after_methods(self):43        return self._iter_inherited_methods('after')44    def _iter_inherited_methods(self, name):45        for cls in self.testclass.__mro__:46            if hasattr(cls, name):47                yield getattr(cls, name)48    def get_unmet_requirements(self):49        raise NotImplementedError() # pragma: no cover50class Test(RunnableTest):51    """52    This is a base class for implementing unittest-style test classes.53    """54    def __init__(self, test_method_name, fixture_store, fixture_namespace, variation):55        super(Test, self).__init__(fixture_store, fixture_namespace, variation)56        self._test_method_name = test_method_name57    def get_test_function(self):58        return getattr(self, self._test_method_name)59    def get_tags(self):60        test_tags = (get_tags(type(self))61                     + get_tags(getattr(type(self), self._test_method_name))62                     + self.get_variation().tags)63        if nofixtures.is_marked(self.get_test_function()):64            return test_tags65        return test_tags + self._get_fixture_tags()66    __slash_skipped__ = False67    __slash_skipped_reason__ = None68    __slash_needed_contexts__ = None69    @classmethod70    def skip_all(cls, reason=None):71        cls.__slash_skipped__ = True72        cls.__slash_skipped_reason__ = reason73    def get_required_fixture_objects(self):74        method = self.get_test_function()75        return self._fixture_store.get_required_fixture_objects(method, namespace=self._fixture_namespace)76    def get_address_in_factory(self):77        returned = ''78        if self._test_method_name is not None:79            returned += ".{}".format(self._test_method_name)80        return returned81    def _get_call_string(self, kwargs):82        if not kwargs:83            return ""84        return "({})".format(", ".join("{}={!r}".format(k, v) for k, v in kwargs.items()))85    def get_requirements(self):86        test_requirements = get_requirements(type(self)) + get_requirements(self.get_test_function())87        if nofixtures.is_marked(self.get_test_function()):88            return test_requirements89        return list(set(test_requirements + self._get_fixtures_requirements()))90    def run(self):  # pylint: disable=E020291        """92        .. warning:: Not to be overriden93        """94        method = self.get_test_function()95        with bound_parametrizations_context(self._variation, self._fixture_store, self._fixture_namespace):96            _call_with_fixtures = functools.partial(self._fixture_store.call_with_fixtures, namespace=self._fixture_namespace)97            _call_with_fixtures(self.before)98            try:99                with handling_exceptions():100                    result = _call_with_fixtures(method, trigger_test_start=True)101                    if isinstance(result, GeneratorType):102                        raise InvalidTest('{} is a generator. Running generators is not supported'.format(method))103            finally:104                with handling_exceptions():105                    _call_with_fixtures(self.after, trigger_test_end=True)106    def before(self):107        """108        Gets called before each separate case generated from this test class109        """110        pass111    def after(self):112        """113        Gets called after each separate case from this test class executed, assuming :meth:`.before` was successful.114        """115        pass116    def _format_kwargs(self, kwargs):117        return ", ".join("{}={!r}".format(x, y) for x, y in kwargs.items())118def abstract_test_class(cls):119    """120    Marks a class as **abstract**, thus meaning it is not to be run121    directly, but rather via a subclass.122    """123    assert issubclass(cls, Test), "abstract_test_class only operates on slash.Test subclasses"124    cls.__slash_abstract__ = True125    return cls126def is_abstract_base_class(cls):127    """128    Checks if a given class is abstract.129    .. seealso:: :func:`abstract_test_class`130    """131    return bool(cls.__dict__.get("__slash_abstract__", False))132def is_valid_test_name(name):...abstract_testcase.py
Source:abstract_testcase.py  
...28    @property29    def test_method_obj(self):30        return getattr(self, self._testMethodName)31    @property32    def real_test_method_name(self):33        return self._testMethodName34    @property35    def test_method_settings(self):36        return Test.get_test_marker(self.test_method_obj)37    @property38    def _test_method_name(self):39        return "{}_{}".format(self._testMethodName, self._serial_number)40    def set_testcase_runtime_datas(self, args=[], kwargs={}):41        self.__testcase_runtime_datas["args"] = args42        self.__testcase_runtime_datas["kwargs"] = kwargs43    def get_testcase_runtime_datas(self):44        return self.__testcase_runtime_datas45    def shortDescription(self):46        name = Test.get_test_marker(self.test_method_obj, key=Test.DESCRIPTION, default_value=None)47        return name or None48    def id(self):49        return "{}.{}".format(strclass(self.__class__), self._test_method_name)50    def __eq__(self, other):51        if type(self) is not type(other):52            return NotImplemented...unittest_retry_wrapper.py
Source:unittest_retry_wrapper.py  
1# https://stackoverflow.com/questions/7152428/can-python-unittest-automatically-reattempt-a-failed-testcase-suite2import unittest3class MyTest(unittest.TestCase):4    ###5    ### Insert test methods here6    ###7    # Wrapping each test method so that a retry would take place.8    def run(self, result=None):9        self.original_method_name = self._test_method_name10        self._test_method_name = "_test_retry_wrapper"11        super(MyTest, self).run(result)12        self._test_method_name = self.original_method_name13    def _test_retry_wrapper(self):14        test_method = getattr(self, self.original_method_name)15        retries_left = settings.test_retry_count16        while True:17            try:18                test_method()19                break20            except:21                if retries_left == 0:22                    raise23                else:24                    retries_left = retries_left - 125def main():26    print('hello')27    x = MyTest()28    return29if __name__ == '__main__':...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!!
