Best Python code snippet using localstack_python
test_unparse.py
Source:test_unparse.py  
...102"""103class ASTTestCase(unittest.TestCase):104    def assertASTEqual(self, ast1, ast2):105        self.assertEqual(ast.dump(ast1), ast.dump(ast2))106    def check_roundtrip(self, code1, filename="internal"):107        ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST)108        unparse_buffer = io.StringIO()109        unparse.Unparser(ast1, unparse_buffer)110        code2 = unparse_buffer.getvalue()111        ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST)112        self.assertASTEqual(ast1, ast2)113class UnparseTestCase(ASTTestCase):114    # Tests for specific bugs found in earlier versions of unparse115    def test_fstrings(self):116        # See issue 25180117        self.check_roundtrip(r"""f'{f"{0}"*3}'""")118        self.check_roundtrip(r"""f'{f"{y}"*3}'""")119    def test_del_statement(self):120        self.check_roundtrip("del x, y, z")121    def test_shifts(self):122        self.check_roundtrip("45 << 2")123        self.check_roundtrip("13 >> 7")124    def test_for_else(self):125        self.check_roundtrip(for_else)126    def test_while_else(self):127        self.check_roundtrip(while_else)128    def test_unary_parens(self):129        self.check_roundtrip("(-1)**7")130        self.check_roundtrip("(-1.)**8")131        self.check_roundtrip("(-1j)**6")132        self.check_roundtrip("not True or False")133        self.check_roundtrip("True or not False")134    def test_integer_parens(self):135        self.check_roundtrip("3 .__abs__()")136    def test_huge_float(self):137        self.check_roundtrip("1e1000")138        self.check_roundtrip("-1e1000")139        self.check_roundtrip("1e1000j")140        self.check_roundtrip("-1e1000j")141    def test_min_int(self):142        self.check_roundtrip(str(-2**31))143        self.check_roundtrip(str(-2**63))144    def test_imaginary_literals(self):145        self.check_roundtrip("7j")146        self.check_roundtrip("-7j")147        self.check_roundtrip("0j")148        self.check_roundtrip("-0j")149    def test_lambda_parentheses(self):150        self.check_roundtrip("(lambda: int)()")151    def test_chained_comparisons(self):152        self.check_roundtrip("1 < 4 <= 5")153        self.check_roundtrip("a is b is c is not d")154    def test_function_arguments(self):155        self.check_roundtrip("def f(): pass")156        self.check_roundtrip("def f(a): pass")157        self.check_roundtrip("def f(b = 2): pass")158        self.check_roundtrip("def f(a, b): pass")159        self.check_roundtrip("def f(a, b = 2): pass")160        self.check_roundtrip("def f(a = 5, b = 2): pass")161        self.check_roundtrip("def f(*, a = 1, b = 2): pass")162        self.check_roundtrip("def f(*, a = 1, b): pass")163        self.check_roundtrip("def f(*, a, b = 2): pass")164        self.check_roundtrip("def f(a, b = None, *, c, **kwds): pass")165        self.check_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass")166        self.check_roundtrip("def f(*args, **kwargs): pass")167    def test_relative_import(self):168        self.check_roundtrip(relative_import)169    def test_nonlocal(self):170        self.check_roundtrip(nonlocal_ex)171    def test_raise_from(self):172        self.check_roundtrip(raise_from)173    def test_bytes(self):174        self.check_roundtrip("b'123'")175    def test_annotations(self):176        self.check_roundtrip("def f(a : int): pass")177        self.check_roundtrip("def f(a: int = 5): pass")178        self.check_roundtrip("def f(*args: [int]): pass")179        self.check_roundtrip("def f(**kwargs: dict): pass")180        self.check_roundtrip("def f() -> None: pass")181    def test_set_literal(self):182        self.check_roundtrip("{'a', 'b', 'c'}")183    def test_set_comprehension(self):184        self.check_roundtrip("{x for x in range(5)}")185    def test_dict_comprehension(self):186        self.check_roundtrip("{x: x*x for x in range(10)}")187    def test_class_decorators(self):188        self.check_roundtrip(class_decorator)189    def test_class_definition(self):190        self.check_roundtrip("class A(metaclass=type, *[], **{}): pass")191    def test_elifs(self):192        self.check_roundtrip(elif1)193        self.check_roundtrip(elif2)194    def test_try_except_finally(self):195        self.check_roundtrip(try_except_finally)196    def test_starred_assignment(self):197        self.check_roundtrip("a, *b, c = seq")198        self.check_roundtrip("a, (*b, c) = seq")199        self.check_roundtrip("a, *b[0], c = seq")200        self.check_roundtrip("a, *(b, c) = seq")201    def test_with_simple(self):202        self.check_roundtrip(with_simple)203    def test_with_as(self):204        self.check_roundtrip(with_as)205    def test_with_two_items(self):206        self.check_roundtrip(with_two_items)207    def test_dict_unpacking_in_dict(self):208        # See issue 26489209        self.check_roundtrip(r"""{**{'y': 2}, 'x': 1}""")210        self.check_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""")211class DirectoryTestCase(ASTTestCase):212    """Test roundtrip behaviour on all files in Lib and Lib/test."""213    NAMES = None214    # test directories, relative to the root of the distribution215    test_directories = 'Lib', os.path.join('Lib', 'test')216    @classmethod217    def get_names(cls):218        if cls.NAMES is not None:219            return cls.NAMES220        names = []221        for d in cls.test_directories:222            test_dir = os.path.join(basepath, d)223            for n in os.listdir(test_dir):224                if n.endswith('.py') and not n.startswith('bad'):225                    names.append(os.path.join(test_dir, n))226        # Test limited subset of files unless the 'cpu' resource is specified.227        if not test.support.is_resource_enabled("cpu"):228            names = random.sample(names, 10)229        # bpo-31174: Store the names sample to always test the same files.230        # It prevents false alarms when hunting reference leaks.231        cls.NAMES = names232        return names233    def test_files(self):234        # get names of files to test235        names = self.get_names()236        for filename in names:237            if test.support.verbose:238                print('Testing %s' % filename)239            # Some f-strings are not correctly round-tripped by240            #  Tools/parser/unparse.py.  See issue 28002 for details.241            #  We need to skip files that contain such f-strings.242            if os.path.basename(filename) in ('test_fstring.py', ):243                if test.support.verbose:244                    print(f'Skipping {filename}: see issue 28002')245                continue246            with self.subTest(filename=filename):247                source = read_pyfile(filename)248                self.check_roundtrip(source)249if __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!!
