PATH: //proc/self/root/proc/thread-self/root/opt/alt/python311/lib64/python3.11/test
FILE_BARU
CREATE
FOLDER_BARU
MKDIR
UPLOAD_FILE
GO
[ .. KEMBALI ]
π Sine-1000Hz-300ms.aif
β
X
π __init__.py
β
X
π __main__.py
β
X
π __pycache__/
X
π _test_atexit.py
β
X
π _test_eintr.py
β
X
π _test_embed_set_config.py
β
X
π _test_embed_structseq.py
β
X
π _test_multiprocessing.py
β
X
π _test_venv_multiprocessing.py
β
X
π archiver_tests.py
β
X
π audiodata/
X
π audiotest.au
β
X
π audiotests.py
β
X
π audit-tests.py
β
X
π autotest.py
β
X
π bisect_cmd.py
β
X
π certdata/
X
π cjkencodings/
X
π clinic.test.c
β
X
π cmath_testcases.txt
β
X
π configdata/
X
π crashers/
X
π curses_tests.py
β
X
π data/
X
π datetimetester.py
β
X
π decimaltestdata/
X
π dis_module.py
β
X
π dtracedata/
X
π empty.vbs
β
X
π encoded_modules/
X
π exception_hierarchy.txt
β
X
π floating_points.txt
β
X
π fork_wait.py
β
X
π formatfloat_testcases.txt
β
X
π ieee754.txt
β
X
π imghdrdata/
X
π imp_dummy.py
β
X
π leakers/
X
π libregrtest/
X
π list_tests.py
β
X
π lock_tests.py
β
X
π mailcap.txt
β
X
π mapping_tests.py
β
X
π math_testcases.txt
β
X
π memory_watchdog.py
β
X
π mime.types
β
X
π mock_socket.py
β
X
π mp_fork_bomb.py
β
X
π mp_preload.py
β
X
π multibytecodec_support.py
β
X
π pickletester.py
β
X
π profilee.py
β
X
π pstats.pck
β
X
π pyclbr_input.py
β
X
π pythoninfo.py
β
X
π randv2_32.pck
β
X
π randv2_64.pck
β
X
π randv3.pck
β
X
π re_tests.py
β
X
π recursion.tar
β
X
π regrtest.py
β
X
π regrtestdata/
X
π relimport.py
β
X
π reperf.py
β
X
π seq_tests.py
β
X
π signalinterproctester.py
β
X
π sndhdrdata/
X
π ssl_servers.py
β
X
π ssltests.py
β
X
π string_tests.py
β
X
π subprocessdata/
X
π support/
X
π test___all__.py
β
X
π test__locale.py
β
X
π test__opcode.py
β
X
π test__osx_support.py
β
X
π test__xxsubinterpreters.py
β
X
π test_abc.py
β
X
π test_abstract_numbers.py
β
X
π test_aifc.py
β
X
π test_argparse.py
β
X
π test_array.py
β
X
π test_asdl_parser.py
β
X
π test_ast.py
β
X
π test_asyncgen.py
β
X
π test_asynchat.py
β
X
π test_asyncio/
X
π test_asyncore.py
β
X
π test_atexit.py
β
X
π test_audioop.py
β
X
π test_audit.py
β
X
π test_augassign.py
β
X
π test_base64.py
β
X
π test_baseexception.py
β
X
π test_bdb.py
β
X
π test_bigaddrspace.py
β
X
π test_bigmem.py
β
X
π test_binascii.py
β
X
π test_binop.py
β
X
π test_bisect.py
β
X
π test_bool.py
β
X
π test_buffer.py
β
X
π test_bufio.py
β
X
π test_builtin.py
β
X
π test_bytes.py
β
X
π test_bz2.py
β
X
π test_c_locale_coercion.py
β
X
π test_calendar.py
β
X
π test_call.py
β
X
π test_capi/
X
π test_cgi.py
β
X
π test_cgitb.py
β
X
π test_charmapcodec.py
β
X
π test_check_c_globals.py
β
X
π test_class.py
β
X
π test_clinic.py
β
X
π test_cmath.py
β
X
π test_cmd.py
β
X
π test_cmd_line.py
β
X
π test_cmd_line_script.py
β
X
π test_code.py
β
X
π test_code_module.py
β
X
π test_codeccallbacks.py
β
X
π test_codecencodings_cn.py
β
X
π test_codecencodings_hk.py
β
X
π test_codecencodings_iso2022.py
β
X
π test_codecencodings_jp.py
β
X
π test_codecencodings_kr.py
β
X
π test_codecencodings_tw.py
β
X
π test_codecmaps_cn.py
β
X
π test_codecmaps_hk.py
β
X
π test_codecmaps_jp.py
β
X
π test_codecmaps_kr.py
β
X
π test_codecmaps_tw.py
β
X
π test_codecs.py
β
X
π test_codeop.py
β
X
π test_collections.py
β
X
π test_colorsys.py
β
X
π test_compare.py
β
X
π test_compile.py
β
X
π test_compileall.py
β
X
π test_complex.py
β
X
π test_concurrent_futures/
X
π test_configparser.py
β
X
π test_contains.py
β
X
π test_context.py
β
X
π test_contextlib.py
β
X
π test_contextlib_async.py
β
X
π test_copy.py
β
X
π test_copyreg.py
β
X
π test_coroutines.py
β
X
π test_cppext/
X
π test_cprofile.py
β
X
π test_crashers.py
β
X
π test_crypt.py
β
X
π test_csv.py
β
X
π test_ctypes.py
β
X
π test_curses.py
β
X
π test_dataclasses/
X
π test_datetime.py
β
X
π test_dbm.py
β
X
π test_dbm_dumb.py
β
X
π test_dbm_gnu.py
β
X
π test_dbm_ndbm.py
β
X
π test_decimal.py
β
X
π test_decorators.py
β
X
π test_defaultdict.py
β
X
π test_deque.py
β
X
π test_descr.py
β
X
π test_descrtut.py
β
X
π test_devpoll.py
β
X
π test_dict.py
β
X
π test_dict_version.py
β
X
π test_dictcomps.py
β
X
π test_dictviews.py
β
X
π test_difflib.py
β
X
π test_difflib_expect.html
β
X
π test_dis.py
β
X
π test_distutils.py
β
X
π test_doctest/
X
π test_docxmlrpc.py
β
X
π test_dtrace.py
β
X
π test_dynamic.py
β
X
π test_dynamicclassattribute.py
β
X
π test_eintr.py
β
X
π test_email/
X
π test_embed.py
β
X
π test_ensurepip.py
β
X
π test_enum.py
β
X
π test_enumerate.py
β
X
π test_eof.py
β
X
π test_epoll.py
β
X
π test_errno.py
β
X
π test_except_star.py
β
X
π test_exception_group.py
β
X
π test_exception_hierarchy.py
β
X
π test_exception_variations.py
β
X
π test_exceptions.py
β
X
π test_extcall.py
β
X
π test_faulthandler.py
β
X
π test_fcntl.py
β
X
π test_file.py
β
X
π test_file_eintr.py
β
X
π test_filecmp.py
β
X
π test_fileinput.py
β
X
π test_fileio.py
β
X
π test_fileutils.py
β
X
π test_finalization.py
β
X
π test_float.py
β
X
π test_flufl.py
β
X
π test_fnmatch.py
β
X
π test_fork1.py
β
X
π test_format.py
β
X
π test_fractions.py
β
X
π test_frame.py
β
X
π test_frozen.py
β
X
π test_fstring.py
β
X
π test_ftplib.py
β
X
π test_funcattrs.py
β
X
π test_functools.py
β
X
π test_future_stmt/
X
π test_gc.py
β
X
π test_gdb/
X
π test_generator_stop.py
β
X
π test_generators.py
β
X
π test_genericalias.py
β
X
π test_genericclass.py
β
X
π test_genericpath.py
β
X
π test_genexps.py
β
X
π test_getopt.py
β
X
π test_getpass.py
β
X
π test_getpath.py
β
X
π test_gettext.py
β
X
π test_glob.py
β
X
π test_global.py
β
X
π test_grammar.py
β
X
π test_graphlib.py
β
X
π test_grp.py
β
X
π test_gzip.py
β
X
π test_hash.py
β
X
π test_hashlib.py
β
X
π test_heapq.py
β
X
π test_hmac.py
β
X
π test_html.py
β
X
π test_htmlparser.py
β
X
π test_http_cookiejar.py
β
X
π test_http_cookies.py
β
X
π test_httplib.py
β
X
π test_httpservers.py
β
X
π test_idle.py
β
X
π test_imaplib.py
β
X
π test_imghdr.py
β
X
π test_imp.py
β
X
π test_import/
X
π test_importlib/
X
π test_index.py
β
X
π test_inspect/
X
π test_int.py
β
X
π test_int_literal.py
β
X
π test_interpreters.py
β
X
π test_io.py
β
X
π test_ioctl.py
β
X
π test_ipaddress.py
β
X
π test_isinstance.py
β
X
π test_iter.py
β
X
π test_iterlen.py
β
X
π test_itertools.py
β
X
π test_json/
X
π test_keyword.py
β
X
π test_keywordonlyarg.py
β
X
π test_kqueue.py
β
X
π test_largefile.py
β
X
π test_launcher.py
β
X
π test_lib2to3.py
β
X
π test_linecache.py
β
X
π test_list.py
β
X
π test_listcomps.py
β
X
π test_lltrace.py
β
X
π test_locale.py
β
X
π test_logging.py
β
X
π test_long.py
β
X
π test_longexp.py
β
X
π test_lzma.py
β
X
π test_mailbox.py
β
X
π test_mailcap.py
β
X
π test_marshal.py
β
X
π test_math.py
β
X
π test_memoryio.py
β
X
π test_memoryview.py
β
X
π test_metaclass.py
β
X
π test_mimetypes.py
β
X
π test_minidom.py
β
X
π test_mmap.py
β
X
π test_module/
X
π test_modulefinder.py
β
X
π test_msilib.py
β
X
π test_multibytecodec.py
β
X
π test_multiprocessing_fork/
X
π test_multiprocessing_forkserver/
X
π test_multiprocessing_main_handling.py
β
X
π test_multiprocessing_spawn/
X
π test_named_expressions.py
β
X
π test_netrc.py
β
X
π test_nis.py
β
X
π test_nntplib.py
β
X
π test_ntpath.py
β
X
π test_numeric_tower.py
β
X
π test_opcache.py
β
X
π test_opcodes.py
β
X
π test_openpty.py
β
X
π test_operator.py
β
X
π test_optparse.py
β
X
π test_ordered_dict.py
β
X
π test_os.py
β
X
π test_ossaudiodev.py
β
X
π test_osx_env.py
β
X
π test_pathlib.py
β
X
π test_patma.py
β
X
π test_pdb.py
β
X
π test_peepholer.py
β
X
π test_peg_generator/
X
π test_pep646_syntax.py
β
X
π test_pickle.py
β
X
π test_picklebuffer.py
β
X
π test_pickletools.py
β
X
π test_pipes.py
β
X
π test_pkg.py
β
X
π test_pkgutil.py
β
X
π test_platform.py
β
X
π test_plistlib.py
β
X
π test_poll.py
β
X
π test_popen.py
β
X
π test_poplib.py
β
X
π test_positional_only_arg.py
β
X
π test_posix.py
β
X
π test_posixpath.py
β
X
π test_pow.py
β
X
π test_pprint.py
β
X
π test_print.py
β
X
π test_profile.py
β
X
π test_property.py
β
X
π test_pstats.py
β
X
π test_pty.py
β
X
π test_pulldom.py
β
X
π test_pwd.py
β
X
π test_py_compile.py
β
X
π test_pyclbr.py
β
X
π test_pydoc/
X
π test_pyexpat.py
β
X
π test_queue.py
β
X
π test_quopri.py
β
X
π test_raise.py
β
X
π test_random.py
β
X
π test_range.py
β
X
π test_re.py
β
X
π test_readline.py
β
X
π test_regrtest.py
β
X
π test_repl.py
β
X
π test_reprlib.py
β
X
π test_resource.py
β
X
π test_richcmp.py
β
X
π test_rlcompleter.py
β
X
π test_robotparser.py
β
X
π test_runpy.py
β
X
π test_sax.py
β
X
π test_sched.py
β
X
π test_scope.py
β
X
π test_script_helper.py
β
X
π test_secrets.py
β
X
π test_select.py
β
X
π test_selectors.py
β
X
π test_set.py
β
X
π test_setcomps.py
β
X
π test_shelve.py
β
X
π test_shlex.py
β
X
π test_shutil.py
β
X
π test_signal.py
β
X
π test_site.py
β
X
π test_slice.py
β
X
π test_smtpd.py
β
X
π test_smtplib.py
β
X
π test_smtpnet.py
β
X
π test_sndhdr.py
β
X
π test_socket.py
β
X
π test_socketserver.py
β
X
π test_sort.py
β
X
π test_source_encoding.py
β
X
π test_spwd.py
β
X
π test_sqlite3/
X
π test_ssl.py
β
X
π test_stable_abi_ctypes.py
β
X
π test_startfile.py
β
X
π test_stat.py
β
X
π test_statistics.py
β
X
π test_strftime.py
β
X
π test_string.py
β
X
π test_string_literals.py
β
X
π test_stringprep.py
β
X
π test_strptime.py
β
X
π test_strtod.py
β
X
π test_struct.py
β
X
π test_structseq.py
β
X
π test_subclassinit.py
β
X
π test_subprocess.py
β
X
π test_sunau.py
β
X
π test_sundry.py
β
X
π test_super.py
β
X
π test_support.py
β
X
π test_symtable.py
β
X
π test_syntax.py
β
X
π test_sys.py
β
X
π test_sys_setprofile.py
β
X
π test_sys_settrace.py
β
X
π test_sysconfig.py
β
X
π test_syslog.py
β
X
π test_tabnanny.py
β
X
π test_tarfile.py
β
X
π test_tcl.py
β
X
π test_telnetlib.py
β
X
π test_tempfile.py
β
X
π test_termios.py
β
X
π test_textwrap.py
β
X
π test_thread.py
β
X
π test_threadedtempfile.py
β
X
π test_threading.py
β
X
π test_threading_local.py
β
X
π test_threadsignals.py
β
X
π test_time.py
β
X
π test_timeit.py
β
X
π test_timeout.py
β
X
π test_tix.py
β
X
π test_tk.py
β
X
π test_tokenize.py
β
X
π test_tomllib/
X
π test_tools/
X
π test_trace.py
β
X
π test_traceback.py
β
X
π test_tracemalloc.py
β
X
π test_ttk_guionly.py
β
X
π test_ttk_textonly.py
β
X
π test_tty.py
β
X
π test_tuple.py
β
X
π test_turtle.py
β
X
π test_type_annotations.py
β
X
π test_type_cache.py
β
X
π test_type_comments.py
β
X
π test_typechecks.py
β
X
π test_types.py
β
X
π test_typing.py
β
X
π test_ucn.py
β
X
π test_unary.py
β
X
π test_unicode.py
β
X
π test_unicode_file.py
β
X
π test_unicode_file_functions.py
β
X
π test_unicode_identifiers.py
β
X
π test_unicodedata.py
β
X
π test_unittest.py
β
X
π test_univnewlines.py
β
X
π test_unpack.py
β
X
π test_unpack_ex.py
β
X
π test_unparse.py
β
X
π test_urllib.py
β
X
π test_urllib2.py
β
X
π test_urllib2_localnet.py
β
X
π test_urllib2net.py
β
X
π test_urllib_response.py
β
X
π test_urllibnet.py
β
X
π test_urlparse.py
β
X
π test_userdict.py
β
X
π test_userlist.py
β
X
π test_userstring.py
β
X
π test_utf8_mode.py
β
X
π test_utf8source.py
β
X
π test_uu.py
β
X
π test_uuid.py
β
X
π test_venv.py
β
X
π test_wait3.py
β
X
π test_wait4.py
β
X
π test_warnings/
X
π test_wave.py
β
X
π test_weakref.py
β
X
π test_weakset.py
β
X
π test_webbrowser.py
β
X
π test_winconsoleio.py
β
X
π test_winreg.py
β
X
π test_winsound.py
β
X
π test_with.py
β
X
π test_wsgiref.py
β
X
π test_xdrlib.py
β
X
π test_xml_dom_minicompat.py
β
X
π test_xml_etree.py
β
X
π test_xml_etree_c.py
β
X
π test_xmlrpc.py
β
X
π test_xmlrpc_net.py
β
X
π test_xxlimited.py
β
X
π test_xxtestfuzz.py
β
X
π test_yield_from.py
β
X
π test_zipapp.py
β
X
π test_zipfile.py
β
X
π test_zipfile64.py
β
X
π test_zipimport.py
β
X
π test_zipimport_support.py
β
X
π test_zlib.py
β
X
π test_zoneinfo/
X
π testcodec.py
β
X
π testtar.tar
β
X
π testtar.tar.xz
β
X
π tf_inherit_check.py
β
X
π time_hashlib.py
β
X
π tokenizedata/
X
π tracedmodules/
X
π typinganndata/
X
π win_console_handler.py
β
X
π xmltestdata/
X
π xmltests.py
β
X
π zip_cp437_header.zip
β
X
π zipdir.zip
β
X
π zipdir_backslash.zip
β
X
π ziptestdata/
X
SAVING...
BERHASIL DIUBAH!
EDITING: test_unparse.py
"""Tests for the unparse.py script in the Tools/parser directory.""" import unittest import test.support import pathlib import random import tokenize import ast def read_pyfile(filename): """Read and return the contents of a Python source file (as a string), taking into account the file encoding.""" with tokenize.open(filename) as stream: return stream.read() for_else = """\ def f(): for x in range(10): break else: y = 2 z = 3 """ while_else = """\ def g(): while True: break else: y = 2 z = 3 """ relative_import = """\ from . import fred from .. import barney from .australia import shrimp as prawns """ nonlocal_ex = """\ def f(): x = 1 def g(): nonlocal x x = 2 y = 7 def h(): nonlocal x, y """ # also acts as test for 'except ... as ...' raise_from = """\ try: 1 / 0 except ZeroDivisionError as e: raise ArithmeticError from e """ class_decorator = """\ @f1(arg) @f2 class Foo: pass """ elif1 = """\ if cond1: suite1 elif cond2: suite2 else: suite3 """ elif2 = """\ if cond1: suite1 elif cond2: suite2 """ try_except_finally = """\ try: suite1 except ex1: suite2 except ex2: suite3 else: suite4 finally: suite5 """ try_except_star_finally = """\ try: suite1 except* ex1: suite2 except* ex2: suite3 else: suite4 finally: suite5 """ with_simple = """\ with f(): suite1 """ with_as = """\ with f() as x: suite1 """ with_two_items = """\ with f() as x, g() as y: suite1 """ docstring_prefixes = ( "", "class foo:\n ", "def foo():\n ", "async def foo():\n ", ) class ASTTestCase(unittest.TestCase): def assertASTEqual(self, ast1, ast2): # Ensure the comparisons start at an AST node self.assertIsInstance(ast1, ast.AST) self.assertIsInstance(ast2, ast.AST) # An AST comparison routine modeled after ast.dump(), but # instead of string building, it traverses the two trees # in lock-step. def traverse_compare(a, b, missing=object()): if type(a) is not type(b): self.fail(f"{type(a)!r} is not {type(b)!r}") if isinstance(a, ast.AST): for field in a._fields: value1 = getattr(a, field, missing) value2 = getattr(b, field, missing) # Singletons are equal by definition, so further # testing can be skipped. if value1 is not value2: traverse_compare(value1, value2) elif isinstance(a, list): try: for node1, node2 in zip(a, b, strict=True): traverse_compare(node1, node2) except ValueError: # Attempt a "pretty" error ala assertSequenceEqual() len1 = len(a) len2 = len(b) if len1 > len2: what = "First" diff = len1 - len2 else: what = "Second" diff = len2 - len1 msg = f"{what} list contains {diff} additional elements." raise self.failureException(msg) from None elif a != b: self.fail(f"{a!r} != {b!r}") traverse_compare(ast1, ast2) def check_ast_roundtrip(self, code1, **kwargs): with self.subTest(code1=code1, ast_parse_kwargs=kwargs): ast1 = ast.parse(code1, **kwargs) code2 = ast.unparse(ast1) ast2 = ast.parse(code2, **kwargs) self.assertASTEqual(ast1, ast2) def check_invalid(self, node, raises=ValueError): with self.subTest(node=node): self.assertRaises(raises, ast.unparse, node) def get_source(self, code1, code2=None): code2 = code2 or code1 code1 = ast.unparse(ast.parse(code1)) return code1, code2 def check_src_roundtrip(self, code1, code2=None): code1, code2 = self.get_source(code1, code2) with self.subTest(code1=code1, code2=code2): self.assertEqual(code2, code1) def check_src_dont_roundtrip(self, code1, code2=None): code1, code2 = self.get_source(code1, code2) with self.subTest(code1=code1, code2=code2): self.assertNotEqual(code2, code1) class UnparseTestCase(ASTTestCase): # Tests for specific bugs found in earlier versions of unparse def test_fstrings(self): self.check_ast_roundtrip("f'a'") self.check_ast_roundtrip("f'{{}}'") self.check_ast_roundtrip("f'{{5}}'") self.check_ast_roundtrip("f'{{5}}5'") self.check_ast_roundtrip("f'X{{}}X'") self.check_ast_roundtrip("f'{a}'") self.check_ast_roundtrip("f'{ {1:2}}'") self.check_ast_roundtrip("f'a{a}a'") self.check_ast_roundtrip("f'a{a}{a}a'") self.check_ast_roundtrip("f'a{a}a{a}a'") self.check_ast_roundtrip("f'{a!r}x{a!s}12{{}}{a!a}'") self.check_ast_roundtrip("f'{a:10}'") self.check_ast_roundtrip("f'{a:100_000{10}}'") self.check_ast_roundtrip("f'{a!r:10}'") self.check_ast_roundtrip("f'{a:a{b}10}'") self.check_ast_roundtrip( "f'a{b}{c!s}{d!r}{e!a}{f:a}{g:a{b}}{h!s:a}" "{j!s:{a}b}{k!s:a{b}c}{l!a:{b}c{d}}{x+y=}'" ) def test_fstrings_special_chars(self): # See issue 25180 self.check_ast_roundtrip(r"""f'{f"{0}"*3}'""") self.check_ast_roundtrip(r"""f'{f"{y}"*3}'""") self.check_ast_roundtrip("""f''""") self.check_ast_roundtrip('''f"""'end' "quote\\""""''') def test_fstrings_complicated(self): # See issue 28002 self.check_ast_roundtrip("""f'''{"'"}'''""") self.check_ast_roundtrip('''f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-\'\'\'''') self.check_ast_roundtrip('''f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-'single quote\\'\'\'\'''') self.check_ast_roundtrip('f"""{\'\'\'\n\'\'\'}"""') self.check_ast_roundtrip('f"""{g(\'\'\'\n\'\'\')}"""') self.check_ast_roundtrip('''f"a\\r\\nb"''') self.check_ast_roundtrip('''f"\\u2028{'x'}"''') def test_strings(self): self.check_ast_roundtrip("u'foo'") self.check_ast_roundtrip("r'foo'") self.check_ast_roundtrip("b'foo'") def test_del_statement(self): self.check_ast_roundtrip("del x, y, z") def test_shifts(self): self.check_ast_roundtrip("45 << 2") self.check_ast_roundtrip("13 >> 7") def test_for_else(self): self.check_ast_roundtrip(for_else) def test_while_else(self): self.check_ast_roundtrip(while_else) def test_unary_parens(self): self.check_ast_roundtrip("(-1)**7") self.check_ast_roundtrip("(-1.)**8") self.check_ast_roundtrip("(-1j)**6") self.check_ast_roundtrip("not True or False") self.check_ast_roundtrip("True or not False") def test_integer_parens(self): self.check_ast_roundtrip("3 .__abs__()") def test_huge_float(self): self.check_ast_roundtrip("1e1000") self.check_ast_roundtrip("-1e1000") self.check_ast_roundtrip("1e1000j") self.check_ast_roundtrip("-1e1000j") def test_nan(self): self.assertASTEqual( ast.parse(ast.unparse(ast.Constant(value=float('nan')))), ast.parse('1e1000 - 1e1000') ) def test_min_int(self): self.check_ast_roundtrip(str(-(2 ** 31))) self.check_ast_roundtrip(str(-(2 ** 63))) def test_imaginary_literals(self): self.check_ast_roundtrip("7j") self.check_ast_roundtrip("-7j") self.check_ast_roundtrip("0j") self.check_ast_roundtrip("-0j") def test_lambda_parentheses(self): self.check_ast_roundtrip("(lambda: int)()") def test_chained_comparisons(self): self.check_ast_roundtrip("1 < 4 <= 5") self.check_ast_roundtrip("a is b is c is not d") def test_function_arguments(self): self.check_ast_roundtrip("def f(): pass") self.check_ast_roundtrip("def f(a): pass") self.check_ast_roundtrip("def f(b = 2): pass") self.check_ast_roundtrip("def f(a, b): pass") self.check_ast_roundtrip("def f(a, b = 2): pass") self.check_ast_roundtrip("def f(a = 5, b = 2): pass") self.check_ast_roundtrip("def f(*, a = 1, b = 2): pass") self.check_ast_roundtrip("def f(*, a = 1, b): pass") self.check_ast_roundtrip("def f(*, a, b = 2): pass") self.check_ast_roundtrip("def f(a, b = None, *, c, **kwds): pass") self.check_ast_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass") self.check_ast_roundtrip("def f(*args, **kwargs): pass") def test_relative_import(self): self.check_ast_roundtrip(relative_import) def test_nonlocal(self): self.check_ast_roundtrip(nonlocal_ex) def test_raise_from(self): self.check_ast_roundtrip(raise_from) def test_bytes(self): self.check_ast_roundtrip("b'123'") def test_annotations(self): self.check_ast_roundtrip("def f(a : int): pass") self.check_ast_roundtrip("def f(a: int = 5): pass") self.check_ast_roundtrip("def f(*args: [int]): pass") self.check_ast_roundtrip("def f(**kwargs: dict): pass") self.check_ast_roundtrip("def f() -> None: pass") def test_set_literal(self): self.check_ast_roundtrip("{'a', 'b', 'c'}") def test_empty_set(self): self.assertASTEqual( ast.parse(ast.unparse(ast.Set(elts=[]))), ast.parse('{*()}') ) def test_set_comprehension(self): self.check_ast_roundtrip("{x for x in range(5)}") def test_dict_comprehension(self): self.check_ast_roundtrip("{x: x*x for x in range(10)}") def test_class_decorators(self): self.check_ast_roundtrip(class_decorator) def test_class_definition(self): self.check_ast_roundtrip("class A(metaclass=type, *[], **{}): pass") def test_elifs(self): self.check_ast_roundtrip(elif1) self.check_ast_roundtrip(elif2) def test_try_except_finally(self): self.check_ast_roundtrip(try_except_finally) def test_try_except_star_finally(self): self.check_ast_roundtrip(try_except_star_finally) def test_starred_assignment(self): self.check_ast_roundtrip("a, *b, c = seq") self.check_ast_roundtrip("a, (*b, c) = seq") self.check_ast_roundtrip("a, *b[0], c = seq") self.check_ast_roundtrip("a, *(b, c) = seq") def test_with_simple(self): self.check_ast_roundtrip(with_simple) def test_with_as(self): self.check_ast_roundtrip(with_as) def test_with_two_items(self): self.check_ast_roundtrip(with_two_items) def test_dict_unpacking_in_dict(self): # See issue 26489 self.check_ast_roundtrip(r"""{**{'y': 2}, 'x': 1}""") self.check_ast_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""") def test_slices(self): self.check_ast_roundtrip("a[i]") self.check_ast_roundtrip("a[i,]") self.check_ast_roundtrip("a[i, j]") # The AST for these next two both look like `a[(*a,)]` self.check_ast_roundtrip("a[(*a,)]") self.check_ast_roundtrip("a[*a]") self.check_ast_roundtrip("a[b, *a]") self.check_ast_roundtrip("a[*a, c]") self.check_ast_roundtrip("a[b, *a, c]") self.check_ast_roundtrip("a[*a, *a]") self.check_ast_roundtrip("a[b, *a, *a]") self.check_ast_roundtrip("a[*a, b, *a]") self.check_ast_roundtrip("a[*a, *a, b]") self.check_ast_roundtrip("a[b, *a, *a, c]") self.check_ast_roundtrip("a[(a:=b)]") self.check_ast_roundtrip("a[(a:=b,c)]") self.check_ast_roundtrip("a[()]") self.check_ast_roundtrip("a[i:j]") self.check_ast_roundtrip("a[:j]") self.check_ast_roundtrip("a[i:]") self.check_ast_roundtrip("a[i:j:k]") self.check_ast_roundtrip("a[:j:k]") self.check_ast_roundtrip("a[i::k]") self.check_ast_roundtrip("a[i:j,]") self.check_ast_roundtrip("a[i:j, k]") def test_invalid_raise(self): self.check_invalid(ast.Raise(exc=None, cause=ast.Name(id="X"))) def test_invalid_fstring_value(self): self.check_invalid( ast.JoinedStr( values=[ ast.Name(id="test"), ast.Constant(value="test") ] ) ) def test_invalid_fstring_backslash(self): self.check_invalid(ast.FormattedValue(value=ast.Constant(value="\\\\"))) def test_invalid_yield_from(self): self.check_invalid(ast.YieldFrom(value=None)) def test_import_from_level_none(self): tree = ast.ImportFrom(module='mod', names=[ast.alias(name='x')]) self.assertEqual(ast.unparse(tree), "from mod import x") tree = ast.ImportFrom(module='mod', names=[ast.alias(name='x')], level=None) self.assertEqual(ast.unparse(tree), "from mod import x") def test_docstrings(self): docstrings = ( 'this ends with double quote"', 'this includes a """triple quote"""', '\r', '\\r', '\t', '\\t', '\n', '\\n', '\r\\r\t\\t\n\\n', '""">>> content = \"\"\"blabla\"\"\" <<<"""', r'foo\n\x00', "' \\'\\'\\'\"\"\" \"\"\\'\\' \\'", 'πβπ©Έ½ΓΌΓ©Ε^\\\\X\\\\BB\N{LONG RIGHTWARDS SQUIGGLE ARROW}' ) for docstring in docstrings: # check as Module docstrings for easy testing self.check_ast_roundtrip(f"'''{docstring}'''") def test_constant_tuples(self): self.check_src_roundtrip(ast.Constant(value=(1,), kind=None), "(1,)") self.check_src_roundtrip( ast.Constant(value=(1, 2, 3), kind=None), "(1, 2, 3)" ) def test_function_type(self): for function_type in ( "() -> int", "(int, int) -> int", "(Callable[complex], More[Complex(call.to_typevar())]) -> None" ): self.check_ast_roundtrip(function_type, mode="func_type") def test_type_comments(self): for statement in ( "a = 5 # type:", "a = 5 # type: int", "a = 5 # type: int and more", "def x(): # type: () -> None\n\tpass", "def x(y): # type: (int) -> None and more\n\tpass", "async def x(): # type: () -> None\n\tpass", "async def x(y): # type: (int) -> None and more\n\tpass", "for x in y: # type: int\n\tpass", "async for x in y: # type: int\n\tpass", "with x(): # type: int\n\tpass", "async with x(): # type: int\n\tpass" ): self.check_ast_roundtrip(statement, type_comments=True) def test_type_ignore(self): for statement in ( "a = 5 # type: ignore", "a = 5 # type: ignore and more", "def x(): # type: ignore\n\tpass", "def x(y): # type: ignore and more\n\tpass", "async def x(): # type: ignore\n\tpass", "async def x(y): # type: ignore and more\n\tpass", "for x in y: # type: ignore\n\tpass", "async for x in y: # type: ignore\n\tpass", "with x(): # type: ignore\n\tpass", "async with x(): # type: ignore\n\tpass" ): self.check_ast_roundtrip(statement, type_comments=True) class CosmeticTestCase(ASTTestCase): """Test if there are cosmetic issues caused by unnecessary additions""" def test_simple_expressions_parens(self): self.check_src_roundtrip("(a := b)") self.check_src_roundtrip("await x") self.check_src_roundtrip("x if x else y") self.check_src_roundtrip("lambda x: x") self.check_src_roundtrip("1 + 1") self.check_src_roundtrip("1 + 2 / 3") self.check_src_roundtrip("(1 + 2) / 3") self.check_src_roundtrip("(1 + 2) * 3 + 4 * (5 + 2)") self.check_src_roundtrip("(1 + 2) * 3 + 4 * (5 + 2) ** 2") self.check_src_roundtrip("~x") self.check_src_roundtrip("x and y") self.check_src_roundtrip("x and y and z") self.check_src_roundtrip("x and (y and x)") self.check_src_roundtrip("(x and y) and z") self.check_src_roundtrip("(x ** y) ** z ** q") self.check_src_roundtrip("x >> y") self.check_src_roundtrip("x << y") self.check_src_roundtrip("x >> y and x >> z") self.check_src_roundtrip("x + y - z * q ^ t ** k") self.check_src_roundtrip("P * V if P and V else n * R * T") self.check_src_roundtrip("lambda P, V, n: P * V == n * R * T") self.check_src_roundtrip("flag & (other | foo)") self.check_src_roundtrip("not x == y") self.check_src_roundtrip("x == (not y)") self.check_src_roundtrip("yield x") self.check_src_roundtrip("yield from x") self.check_src_roundtrip("call((yield x))") self.check_src_roundtrip("return x + (yield x)") def test_class_bases_and_keywords(self): self.check_src_roundtrip("class X:\n pass") self.check_src_roundtrip("class X(A):\n pass") self.check_src_roundtrip("class X(A, B, C, D):\n pass") self.check_src_roundtrip("class X(x=y):\n pass") self.check_src_roundtrip("class X(metaclass=z):\n pass") self.check_src_roundtrip("class X(x=y, z=d):\n pass") self.check_src_roundtrip("class X(A, x=y):\n pass") self.check_src_roundtrip("class X(A, **kw):\n pass") self.check_src_roundtrip("class X(*args):\n pass") self.check_src_roundtrip("class X(*args, **kwargs):\n pass") def test_fstrings(self): self.check_src_roundtrip('''f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-\'\'\'''') self.check_src_roundtrip('''f"\\u2028{'x'}"''') self.check_src_roundtrip(r"f'{x}\n'") self.check_src_roundtrip('''f''\'{"""\n"""}\\n''\'''') self.check_src_roundtrip('''f''\'{f"""{x}\n"""}\\n''\'''') def test_docstrings(self): docstrings = ( '"""simple doc string"""', '''"""A more complex one with some newlines"""''', '''"""Foo bar baz empty newline"""''', '"""With some \t"""', '"""Foo "bar" baz """', '"""\\r"""', '""""""', '"""\'\'\'"""', '"""\'\'\'\'\'\'"""', '"""πβπ©Έ½ΓΌΓ©Ε^\\\\X\\\\BBβΏ"""', '"""end in single \'quote\'"""', "'''end in double \"quote\"'''", '"""almost end in double "quote"."""', ) for prefix in docstring_prefixes: for docstring in docstrings: self.check_src_roundtrip(f"{prefix}{docstring}") def test_docstrings_negative_cases(self): # Test some cases that involve strings in the children of the # first node but aren't docstrings to make sure we don't have # False positives. docstrings_negative = ( 'a = """false"""', '"""false""" + """unless its optimized"""', '1 + 1\n"""false"""', 'f"""no, top level but f-fstring"""' ) for prefix in docstring_prefixes: for negative in docstrings_negative: # this cases should be result with single quote # rather then triple quoted docstring src = f"{prefix}{negative}" self.check_ast_roundtrip(src) self.check_src_dont_roundtrip(src) def test_unary_op_factor(self): for prefix in ("+", "-", "~"): self.check_src_roundtrip(f"{prefix}1") for prefix in ("not",): self.check_src_roundtrip(f"{prefix} 1") def test_slices(self): self.check_src_roundtrip("a[()]") self.check_src_roundtrip("a[1]") self.check_src_roundtrip("a[1, 2]") # Note that `a[*a]`, `a[*a,]`, and `a[(*a,)]` all evaluate to the same # thing at runtime and have the same AST, but only `a[*a,]` passes # this test, because that's what `ast.unparse` produces. self.check_src_roundtrip("a[*a,]") self.check_src_roundtrip("a[1, *a]") self.check_src_roundtrip("a[*a, 2]") self.check_src_roundtrip("a[1, *a, 2]") self.check_src_roundtrip("a[*a, *a]") self.check_src_roundtrip("a[1, *a, *a]") self.check_src_roundtrip("a[*a, 1, *a]") self.check_src_roundtrip("a[*a, *a, 1]") self.check_src_roundtrip("a[1, *a, *a, 2]") self.check_src_roundtrip("a[1:2, *a]") self.check_src_roundtrip("a[*a, 1:2]") def test_lambda_parameters(self): self.check_src_roundtrip("lambda: something") self.check_src_roundtrip("four = lambda: 2 + 2") self.check_src_roundtrip("lambda x: x * 2") self.check_src_roundtrip("square = lambda n: n ** 2") self.check_src_roundtrip("lambda x, y: x + y") self.check_src_roundtrip("add = lambda x, y: x + y") self.check_src_roundtrip("lambda x, y, /, z, q, *, u: None") self.check_src_roundtrip("lambda x, *y, **z: None") def test_star_expr_assign_target(self): for source_type, source in [ ("single assignment", "{target} = foo"), ("multiple assignment", "{target} = {target} = bar"), ("for loop", "for {target} in foo:\n pass"), ("async for loop", "async for {target} in foo:\n pass") ]: for target in [ "a", "a,", "a, b", "a, *b, c", "a, (b, c), d", "a, (b, c, d), *e", "a, (b, *c, d), e", "a, (b, *c, (d, e), f), g", "[a]", "[a, b]", "[a, *b, c]", "[a, [b, c], d]", "[a, [b, c, d], *e]", "[a, [b, *c, d], e]", "[a, [b, *c, [d, e], f], g]", "a, [b, c], d", "[a, b, (c, d), (e, f)]", "a, b, [*c], d, e" ]: with self.subTest(source_type=source_type, target=target): self.check_src_roundtrip(source.format(target=target)) def test_star_expr_assign_target_multiple(self): self.check_src_roundtrip("() = []") self.check_src_roundtrip("[] = ()") self.check_src_roundtrip("() = [a] = c, = [d] = e, f = () = g = h") self.check_src_roundtrip("a = b = c = d") self.check_src_roundtrip("a, b = c, d = e, f = g") self.check_src_roundtrip("[a, b] = [c, d] = [e, f] = g") self.check_src_roundtrip("a, b = [c, d] = e, f = g") def test_multiquote_joined_string(self): self.check_ast_roundtrip("f\"'''{1}\\\"\\\"\\\"\" ") self.check_ast_roundtrip("""f"'''{1}""\\"" """) self.check_ast_roundtrip("""f'""\"{1}''' """) self.check_ast_roundtrip("""f'""\"{1}""\\"' """) class DirectoryTestCase(ASTTestCase): """Test roundtrip behaviour on all files in Lib and Lib/test.""" lib_dir = pathlib.Path(__file__).parent / ".." test_directories = (lib_dir, lib_dir / "test") run_always_files = {"test_grammar.py", "test_syntax.py", "test_compile.py", "test_ast.py", "test_asdl_parser.py", "test_fstring.py", "test_patma.py"} _files_to_test = None @classmethod def files_to_test(cls): if cls._files_to_test is not None: return cls._files_to_test items = [ item.resolve() for directory in cls.test_directories for item in directory.glob("*.py") if not item.name.startswith("bad") ] # Test limited subset of files unless the 'cpu' resource is specified. if not test.support.is_resource_enabled("cpu"): tests_to_run_always = {item for item in items if item.name in cls.run_always_files} items = set(random.sample(items, 10)) # Make sure that at least tests that heavily use grammar features are # always considered in order to reduce the chance of missing something. items = list(items | tests_to_run_always) # bpo-31174: Store the names sample to always test the same files. # It prevents false alarms when hunting reference leaks. cls._files_to_test = items return items def test_files(self): for item in self.files_to_test(): if test.support.verbose: print(f"Testing {item.absolute()}") with self.subTest(filename=item): source = read_pyfile(item) self.check_ast_roundtrip(source) if __name__ == "__main__": unittest.main()
SIMPAN PERUBAHAN