Best Python code snippet using avocado_python
loader.py
Source:loader.py  
...502                               self.NOT_TEST_STR)503    def _make_existing_file_tests(self, test_path, make_broken,504                                  subtests_filter):505        return self._make_simple_or_broken_test(test_path, subtests_filter, make_broken)506    def _make_nonexisting_file_tests(self, test_path, make_broken,507                                     subtests_filter, test_name):  # pylint: disable=W0613508        return make_broken(NotATest, test_name, "File not found "509                           "('%s'; '%s')" % (test_name, test_path))510    @staticmethod511    def _make_test(klass, uid, description=None, subtests_filter=None,512                   **test_arguments):513        """514        Create test template515        :param klass: test class516        :param uid: test uid (by default used as id and name)517        :param description: Description appended to "uid" (for listing purpose)518        :param subtests_filter: optional filter of methods for avocado tests519        :param test_arguments: arguments to be passed to the klass(test_arguments)520        """521        if subtests_filter and not subtests_filter.search(uid):522            return []523        if description:524            uid = "%s: %s" % (uid, description)525        test_arguments["name"] = uid526        return [(klass, test_arguments)]527    def _make_tests(self, test_path, list_non_tests, subtests_filter=None):528        """529        Create test templates from given path530        :param test_path: File system path531        :param list_non_tests: include bad tests (NotATest, BrokenSymlink,...)532        :param subtests_filter: optional filter of methods for avocado tests533        """534        def ignore_broken(klass, uid, description=None):  # pylint: disable=W0613535            """ Always return empty list """536            return []537        if list_non_tests:  # return broken test with params538            make_broken = self._make_test539        else:  # return empty set instead540            make_broken = ignore_broken541        test_name = test_path542        if os.path.exists(test_path):543            if os.access(test_path, os.R_OK) is False:544                return make_broken(AccessDeniedPath, test_path, "Is not "545                                   "readable")546            return self._make_existing_file_tests(test_path, make_broken,547                                                  subtests_filter)548        else:549            if os.path.islink(test_path):550                try:551                    if not os.path.isfile(os.readlink(test_path)):552                        return make_broken(BrokenSymlink, test_path, "Is a "553                                           "broken symlink")554                except OSError:555                    return make_broken(AccessDeniedPath, test_path, "Is not "556                                       "accessible.")557            return self._make_nonexisting_file_tests(test_path, make_broken,558                                                     subtests_filter,559                                                     test_name)560class FileLoader(SimpleFileLoader):561    """562    Test loader class.563    """564    name = 'file'565    NOT_TEST_STR = ("Not an INSTRUMENTED (avocado.Test based), PyUNITTEST ("566                    "unittest.TestCase based) or SIMPLE (executable) test")567    @staticmethod568    def get_type_label_mapping():569        mapping = SimpleFileLoader.get_type_label_mapping()570        mapping.update(571            {test.SimpleTest: 'SIMPLE',572             test.Test: 'INSTRUMENTED',573             test.PythonUnittest: 'PyUNITTEST'})574        return mapping575    @staticmethod576    def get_decorator_mapping():577        mapping = SimpleFileLoader.get_decorator_mapping()578        mapping.update(579            {test.SimpleTest: output.TERM_SUPPORT.healthy_str,580             test.Test: output.TERM_SUPPORT.healthy_str,581             test.PythonUnittest: output.TERM_SUPPORT.healthy_str})582        return mapping583    @staticmethod584    def _is_matching_test_class(tst, test_class):585        if test_class is test.Test:586            # Instrumented tests are defined as string and loaded at the587            # execution time.588            return isinstance(tst, str)589        else:590            return not isinstance(tst, str) and issubclass(tst, test_class)591    def _find_python_unittests(self, test_path, disabled, subtests_filter):592        result = []593        class_methods = safeloader.find_python_unittests(test_path)594        for klass, methods in class_methods.items():595            if klass in disabled:596                continue597            if test_path.endswith(".py"):598                test_path = test_path[:-3]599            test_module_name = os.path.relpath(test_path)600            test_module_name = test_module_name.replace(os.path.sep, ".")601            candidates = [("%s.%s.%s" % (test_module_name, klass, method),602                           tags) for (method, tags, _) in methods]603            if subtests_filter:604                result += [_ for _ in candidates if subtests_filter.search(_)]605            else:606                result += candidates607        return result608    def _make_simple_test(self, test_path, subtests_filter):609        return self._make_test(test.SimpleTest, test_path,610                               subtests_filter=subtests_filter,611                               executable=test_path)612    def _make_simple_or_broken_test(self, test_path, subtests_filter, make_broken):613        if os.access(test_path, os.X_OK):614            # Module does not have an avocado test class inside but615            # it's executable, let's execute it.616            return self._make_simple_test(test_path, subtests_filter)617        else:618            # Module does not have an avocado test class inside, and619            # it's not executable. Not a Test.620            return make_broken(NotATest, test_path,621                               self.NOT_TEST_STR)622    def _make_python_file_tests(self, test_path, make_broken,623                                subtests_filter, test_name=None):624        if test_name is None:625            test_name = test_path626        try:627            # Avocado tests628            avocado_tests, disabled = safeloader.find_avocado_tests(test_path)629            if avocado_tests:630                test_factories = []631                for test_class, info in avocado_tests.items():632                    if isinstance(test_class, str):633                        for test_method, tags, _ in info:634                            name = test_name + \635                                ':%s.%s' % (test_class, test_method)636                            if (subtests_filter and637                                    not subtests_filter.search(name)):638                                continue639                            tst = (test_class, {'name': name,640                                                'modulePath': test_path,641                                                'methodName': test_method,642                                                'tags': tags})643                            test_factories.append(tst)644                return test_factories645            # Python unittests646            old_dir = os.getcwd()647            try:648                py_test_dir = os.path.abspath(os.path.dirname(test_path))649                py_test_name = os.path.basename(test_path)650                os.chdir(py_test_dir)651                python_unittests = self._find_python_unittests(py_test_name,652                                                               disabled,653                                                               subtests_filter)654            finally:655                os.chdir(old_dir)656            if python_unittests:657                return [(test.PythonUnittest, {"name": name,658                                               "test_dir": py_test_dir,659                                               "tags": tags})660                        for (name, tags) in python_unittests]661            else:662                # Module does not have an avocado test or pyunittest class inside,663                # but maybe it's a Python executable.664                return self._make_simple_or_broken_test(test_path,665                                                        subtests_filter,666                                                        make_broken)667        # Since a lot of things can happen here, the broad exception is668        # justified. The user will get it unadulterated anyway, and avocado669        # will not crash. Ugly python files can raise any exception670        except BaseException as details:  # pylint: disable=W0703671            if isinstance(details, KeyboardInterrupt):672                raise  # Don't ignore ctrl+c673            else:674                return self._make_simple_or_broken_test(test_path,675                                                        subtests_filter,676                                                        make_broken)677    def _make_existing_file_tests(self, test_path, make_broken,678                                  subtests_filter):679        if test_path.endswith('.py'):680            return self._make_python_file_tests(test_path, make_broken,681                                                subtests_filter)682        else:683            return self._make_simple_or_broken_test(test_path,684                                                    subtests_filter,685                                                    make_broken)686    def _make_nonexisting_file_tests(self, test_path, make_broken,687                                     subtests_filter, test_name):688        # Try to resolve test ID (keep compatibility)689        test_path = os.path.join(data_dir.get_test_dir(), test_name)690        if os.path.exists(test_path):691            return self._make_python_file_tests(test_path, make_broken,692                                                subtests_filter,693                                                test_name)694        else:695            if not subtests_filter and ':' in test_name:696                test_name, subtests_filter = test_name.split(':', 1)697                test_path = os.path.join(data_dir.get_test_dir(),698                                         test_name)699                if os.path.exists(test_path):700                    subtests_filter = re.compile(subtests_filter)...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!!
