Best Python code snippet using tempest_python
check_uuid.py
Source:check_uuid.py  
...114        return line.strip().startswith('@')115    @staticmethod116    def _is_def(line):117        return line.strip().startswith('def ')118    def _add_uuid_to_test(self, patcher, test_node, source_path):119        with open(source_path) as src:120            src_lines = src.read().split('\n')121        lineno = test_node.lineno122        insert_position = lineno123        while True:124            if (self._is_def(src_lines[lineno - 1]) or125                    (self._is_decorator(src_lines[lineno - 1]) and126                        (DECORATOR_TEMPLATE.split('(')[0] <=127                            src_lines[lineno - 1].strip().split('(')[0]))):128                insert_position = lineno129                break130            lineno += 1131        patcher.add_patch(132            source_path,133            ' ' * test_node.col_offset + DECORATOR_TEMPLATE % uuid.uuid4(),134            insert_position135        )136    @staticmethod137    def _is_test_case(module, node):138        if (node.__class__ is ast.ClassDef and139                hasattr(module, node.name) and140                inspect.isclass(getattr(module, node.name))):141            return issubclass(getattr(module, node.name), unittest.TestCase)142    @staticmethod143    def _is_test_method(node):144        return (node.__class__ is ast.FunctionDef145                and node.name.startswith('test_'))146    @staticmethod147    def _next_node(body, node):148        if body.index(node) < len(body):149            return body[body.index(node) + 1]150    @staticmethod151    def _import_name(node):152        if type(node) == ast.Import:153            return node.names[0].name154        elif type(node) == ast.ImportFrom:155            return '%s.%s' % (node.module, node.names[0].name)156    def _add_import_for_test_uuid(self, patcher, src_parsed, source_path):157        with open(source_path) as f:158            src_lines = f.read().split('\n')159        line_no = 0160        tempest_imports = [node for node in src_parsed.body161                           if self._import_name(node) and162                           'tempest.' in self._import_name(node)]163        if not tempest_imports:164            import_snippet = '\n'.join(('', IMPORT_LINE, ''))165        else:166            for node in tempest_imports:167                if self._import_name(node) < DECORATOR_IMPORT:168                    continue169                else:170                    line_no = node.lineno171                    import_snippet = IMPORT_LINE172                    break173            else:174                line_no = tempest_imports[-1].lineno175                while True:176                    if (not src_lines[line_no - 1] or177                            getattr(self._next_node(src_parsed.body,178                                                    tempest_imports[-1]),179                                    'lineno') == line_no or180                            line_no == len(src_lines)):181                        break182                    line_no += 1183                import_snippet = '\n'.join((IMPORT_LINE, ''))184        patcher.add_patch(source_path, import_snippet, line_no)185    def get_tests(self):186        """Get test methods with sources from base package with metadata"""187        tests = {}188        for module_name in self._modules_search():189            tests[module_name] = {}190            module = importlib.import_module(module_name)191            source_path = '.'.join(192                (os.path.splitext(module.__file__)[0], 'py')193            )194            with open(source_path, 'r') as f:195                source = f.read()196            tests[module_name]['source_path'] = source_path197            tests[module_name]['tests'] = {}198            source_parsed = ast.parse(source)199            tests[module_name]['ast'] = source_parsed200            tests[module_name]['import_valid'] = (201                hasattr(module, DECORATOR_MODULE) and202                inspect.ismodule(getattr(module, DECORATOR_MODULE))203            )204            test_cases = (node for node in source_parsed.body205                          if self._is_test_case(module, node))206            for node in test_cases:207                for subnode in filter(self._is_test_method, node.body):208                        test_name = '%s.%s' % (node.name, subnode.name)209                        tests[module_name]['tests'][test_name] = subnode210        return tests211    @staticmethod212    def _filter_tests(function, tests):213        """Filter tests with condition 'function(test_node) == True'"""214        result = {}215        for module_name in tests:216            for test_name in tests[module_name]['tests']:217                if function(module_name, test_name, tests):218                    if module_name not in result:219                        result[module_name] = {220                            'ast': tests[module_name]['ast'],221                            'source_path': tests[module_name]['source_path'],222                            'import_valid': tests[module_name]['import_valid'],223                            'tests': {}224                        }225                    result[module_name]['tests'][test_name] = \226                        tests[module_name]['tests'][test_name]227        return result228    def find_untagged(self, tests):229        """Filter all tests without uuid in metadata"""230        def check_uuid_in_meta(module_name, test_name, tests):231            idempotent_id = self._get_idempotent_id(232                tests[module_name]['tests'][test_name])233            return not idempotent_id234        return self._filter_tests(check_uuid_in_meta, tests)235    def report_collisions(self, tests):236        """Reports collisions if there are any. Returns true if237        collisions exist.238        """239        uuids = {}240        def report(module_name, test_name, tests):241            test_uuid = self._get_idempotent_id(242                tests[module_name]['tests'][test_name])243            if not test_uuid:244                return245            if test_uuid in uuids:246                error_str = "%s:%s\n uuid %s collision: %s<->%s\n%s:%s" % (247                    tests[module_name]['source_path'],248                    tests[module_name]['tests'][test_name].lineno,249                    test_uuid,250                    test_name,251                    uuids[test_uuid]['test_name'],252                    uuids[test_uuid]['source_path'],253                    uuids[test_uuid]['test_node'].lineno,254                )255                print(error_str)256                print("cannot automatically resolve the collision, please "257                      "manually remove the duplicate value on the new test.")258                return True259            else:260                uuids[test_uuid] = {261                    'module': module_name,262                    'test_name': test_name,263                    'test_node': tests[module_name]['tests'][test_name],264                    'source_path': tests[module_name]['source_path']265                }266        return bool(self._filter_tests(report, tests))267    def report_untagged(self, tests):268        """Reports untagged tests if there are any. Returns true if269        untagged tests exist.270        """271        def report(module_name, test_name, tests):272            error_str = "%s:%s\nmissing @test.idempotent_id('...')\n%s\n" % (273                tests[module_name]['source_path'],274                tests[module_name]['tests'][test_name].lineno,275                test_name276            )277            print(error_str)278            return True279        return bool(self._filter_tests(report, tests))280    def fix_tests(self, tests):281        """Add uuids to all tests specified in tests and282        fix it in source files283        """284        patcher = SourcePatcher()285        for module_name in tests:286            add_import_once = True287            for test_name in tests[module_name]['tests']:288                if not tests[module_name]['import_valid'] and add_import_once:289                    self._add_import_for_test_uuid(290                        patcher,291                        tests[module_name]['ast'],292                        tests[module_name]['source_path']293                    )294                    add_import_once = False295                self._add_uuid_to_test(296                    patcher, tests[module_name]['tests'][test_name],297                    tests[module_name]['source_path'])298        patcher.apply_patches()299def run():300    parser = argparse.ArgumentParser()301    parser.add_argument('--package', action='store', dest='package',302                        default='tempest', type=str,303                        help='Package with tests')304    parser.add_argument('--fix', action='store_true', dest='fix_tests',305                        help='Attempt to fix tests without UUIDs')306    args = parser.parse_args()307    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))308    pkg = importlib.import_module(args.package)309    checker = TestChecker(pkg)...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!!
