Best Python code snippet using green
test_loader.py
Source:test_loader.py  
...302                def test_two(self):303                    pass304            """))305        fh.close()306        suite = loader.loadFromModuleFilename(filename)307        self.assertEqual(suite.countTestCases(), 1)308        self.assertRaises(unittest.case.SkipTest,309                getattr(suite._tests[0], suite._tests[0]._testMethodName))310class TestDiscover(unittest.TestCase):311    def test_bad_input(self):312        """313        discover() raises ImportError when passed a non-directory314        """315        tmpdir = tempfile.mkdtemp()316        self.addCleanup(shutil.rmtree, tmpdir)317        self.assertRaises(ImportError, loader.discover,318                os.path.join(tmpdir, 'garbage_in'))319        filename = os.path.join(tmpdir, 'some_file.py')320        fh = open(filename, 'w')...loader.py
Source:loader.py  
...32        test_case_names.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))33        if not test_case_names and hasattr(testCaseClass, "runTest"):34            test_case_names = ["runTest"]35        return flattenTestSuite(map(testCaseClass, test_case_names))36    def loadFromModuleFilename(self, filename):37        dotted_module, parent_dir = findDottedModuleAndParentDir(filename)38        # Adding the parent path of the module to the start of sys.path is39        # the closest we can get to an absolute import in Python that I can40        # find.41        sys.path.insert(0, parent_dir)42        try:43            __import__(dotted_module)44            loaded_module = sys.modules[dotted_module]45            debug("Imported {}".format(dotted_module), 2)46        except unittest.case.SkipTest as e:47            # TODO: #25 - Right now this mimics the behavior in unittest.  Lets48            # refactor it and simplify it after we make sure it works.49            # This is a cause of the traceback mangling I observed.50            reason = str(e)51            @unittest.case.skip(reason)52            def testSkipped(self):53                pass  # pragma: no cover54            TestClass = type(55                str("ModuleSkipped"), (unittest.case.TestCase,), {filename: testSkipped}56            )57            return self.suiteClass((TestClass(filename),))58        except:59            # TODO: #25 - Right now this mimics the behavior in unittest.  Lets60            # refactor it and simplify it after we make sure it works.61            # This is a cause of the traceback mangling I observed.62            message = ("Failed to import {} computed from filename {}\n{}").format(63                dotted_module, filename, traceback.format_exc()64            )65            def testFailure(self):66                raise ImportError(message)67            TestClass = type(68                str("ModuleImportFailure"),69                (unittest.case.TestCase,),70                {filename: testFailure},71            )72            return self.suiteClass((TestClass(filename),))73        finally:74            # This gets called before return statements in except clauses75            # actually return. Yay!76            sys.path.pop(0)77        # --- Find the tests inside the loaded module ---78        return self.loadTestsFromModule(loaded_module)79    if sys.version_info >= (3, 5):  # pragma: no cover80        def loadTestsFromModule(self, module, pattern=None):81            tests = super(GreenTestLoader, self).loadTestsFromModule(82                module, pattern=pattern83            )84            return flattenTestSuite(tests, module)85    else:  # pragma: no cover86        def loadTestsFromModule(self, module):87            tests = super(GreenTestLoader, self).loadTestsFromModule(module)88            return flattenTestSuite(tests, module)89    def loadTestsFromName(self, name, module=None):90        tests = super(GreenTestLoader, self).loadTestsFromName(name, module)91        return flattenTestSuite(tests, module)92    def discover(self, current_path, file_pattern="test*.py", top_level_dir=None):93        """94        I take a path to a directory and discover all the tests inside files95        matching file_pattern.96        If path is not a readable directory, I raise an ImportError.97        If I don't find anything, I return None.  Otherwise I return a98        GreenTestSuite99        """100        current_abspath = os.path.abspath(current_path)101        if not os.path.isdir(current_abspath):102            raise ImportError("'{}' is not a directory".format(str(current_path)))103        suite = GreenTestSuite()104        try:105            for file_or_dir_name in sorted(os.listdir(current_abspath)):106                path = os.path.join(current_abspath, file_or_dir_name)107                # Recurse into directories, attempting to skip virtual environments108                bin_activate = os.path.join(path, "bin", "activate")109                if os.path.isdir(path) and not os.path.isfile(bin_activate):110                    # Don't follow symlinks111                    if os.path.islink(path):112                        continue113                    # Don't recurse into directories that couldn't be a package name114                    if not python_dir_pattern.match(file_or_dir_name):115                        continue116                    subdir_suite = self.discover(117                        path,118                        file_pattern=file_pattern,119                        top_level_dir=top_level_dir or current_path,120                    )121                    if subdir_suite:122                        suite.addTest(subdir_suite)123                elif os.path.isfile(path):124                    # Skip irrelevant files125                    if not python_file_pattern.match(file_or_dir_name):126                        continue127                    if not fnmatch(file_or_dir_name, file_pattern):128                        continue129                    # Try loading the file as a module130                    module_suite = self.loadFromModuleFilename(path)131                    if module_suite:132                        suite.addTest(module_suite)133        except OSError:134            debug("WARNING: Test discovery failed at path {}".format(current_path))135        return flattenTestSuite(suite) if suite.countTestCases() else None136    def loadTargets(self, targets, file_pattern="test*.py"):137        # If a string was passed in, put it into a list.138        if type(targets) != list:139            targets = [targets]140        # Make sure there are no duplicate entries, preserving order141        target_dict = OrderedDict()142        for target in targets:143            target_dict[target] = True144        targets = target_dict.keys()...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!!
