a ze@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZmZmZmZmZmZmZmZe jZgdZdZefddZedfd d ZGd d d ejZd dZedkre dS)N)support)make_pkg make_script make_zip_pkgmake_zip_scriptassert_python_okassert_python_failure spawn_python kill_python)Ztest1Ztest2Ztest3a# Script may be run with optimisation enabled, so don't rely on assert # statements being executed def assertEqual(lhs, rhs): if lhs != rhs: raise AssertionError('%r != %r' % (lhs, rhs)) def assertIdentical(lhs, rhs): if lhs is not rhs: raise AssertionError('%r is not %r' % (lhs, rhs)) # Check basic code execution result = ['Top level assignment'] def f(): result.append('Lower level reference') f() assertEqual(result, ['Top level assignment', 'Lower level reference']) # Check population of magic variables assertEqual(__name__, '__main__') from importlib.machinery import BuiltinImporter _loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__) print('__loader__==%a' % _loader) print('__file__==%a' % __file__) print('__cached__==%a' % __cached__) print('__package__==%r' % __package__) # Check PEP 451 details import os.path if __package__ is not None: print('__main__ was located through the import system') assertIdentical(__spec__.loader, __loader__) expected_spec_name = os.path.splitext(os.path.basename(__file__))[0] if __package__: expected_spec_name = __package__ + "." + expected_spec_name assertEqual(__spec__.name, expected_spec_name) assertEqual(__spec__.parent, __package__) assertIdentical(__spec__.submodule_search_locations, None) assertEqual(__spec__.origin, __file__) if __spec__.cached is not None: assertEqual(__spec__.cached, __cached__) # Check the sys module import sys assertIdentical(globals(), sys.modules[__name__].__dict__) if __spec__ is not None: # XXX: We're not currently making __main__ available under its real name pass # assertIdentical(globals(), sys.modules[__spec__.name].__dict__) from test import test_cmd_line_script example_args_list = test_cmd_line_script.example_args assertEqual(sys.argv[1:], example_args_list) print('sys.argv[0]==%a' % sys.argv[0]) print('sys.path[0]==%a' % sys.path[0]) # Check the working directory import os print('cwd==%a' % os.getcwd()) cCst|||}t|SN)r importlibinvalidate_caches) script_dirscript_basenamesource to_returnrM/opt/bitninja-python-dojo/embedded/lib/python3.9/test/test_cmd_line_script.py_make_test_scriptNs rcCst||||||}t|Sr )rr r )Zzip_dirZ zip_basenameZpkg_namerrdepthrrrr_make_test_zip_pkgSs  rc@seZdZdlddZddddZddddZd d Zd d Zej dmddZ dnddZ doddZ ddZ ddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9Zd:d;Z dd?Z"d@dAZ#dBdCZ$dDdEZ%dFdGZ&ej dHdIZ'dJdKZ(dLdMZ)dNdOZ*dPdQZ+dRdSZ,dTdUZ-dVdWZ.dXdYZ/dZd[Z0d\d]Z1d^d_Z2d`daZ3dbdcZ4dddeZ5dfdgZ6dhdiZ7djdkZ8dS)p CmdLineTestNc Cs tdkr td|tt|||dd|} d|} d|} d|} d|}| durdt} d | }tdkrtd t| t| t| t||| d ||| d ||| d ||| d |||d |||d |dS) NrzOutput from test script %r:rz__loader__==%az __file__==%az__package__==%rzsys.argv[0]==%azsys.path[0]==%azcwd==%azExpected output:utf-8)verboseprintrepr assertEqualosgetcwdassertInencode)self script_nameZ exit_codedata expected_fileexpected_argv0expected_path0expected_packageexpected_loader expected_cwdZprinted_loaderZ printed_fileZprinted_packageZ printed_argv0Z printed_path0Z printed_cwdrrr _check_output[s0   zCmdLineTest._check_outputcwdc Osdt|tr|g}gt||t} t| d|d| \} } } ||| | | |||||| dS)NF __isolatedZ__cwd) isinstancestrrZ!optim_args_from_interpreter_flags example_argsrr+)r"script_exec_argsr%r&r'r(r)r-cmd_line_switchesenv_varsrun_argsrcouterrrrr _check_scriptxs$   zCmdLineTest._check_scriptc Ost|tr|f}nt|}||}t|d|d|\}}} tdkrltd|tt| td|||d| dS)NFr.rzOutput from test script zExpected output: %rr) r0r1tuplerrrrr r!) r"r3Z expected_msgr-r4r5r6r7r8r9rrr_check_import_errors    zCmdLineTest._check_import_errorcCs2tdd\}}}ttjjd}|||dS)N-czprint(__loader__)r)rrr machineryBuiltinImporterr!r )r"r7r8r9expectedrrrtest_dash_c_loaderszCmdLineTest.test_dash_c_loadercCsVt}z"|jd|jWt|}n t|}0ttjj d}| ||dS)Nsprint(__loader__) r) r stdinwriteflushr rr r>r?r!r )r"pr8r@rrrtest_stdin_loaders  zCmdLineTest.test_stdin_loaderFccs~|rtdtjd}|j}ntdtjd}|j}z8|d}|dkrDqN|q0|VWt|| nt|| 0dS)Nz-i)stderrs>>> ) r subprocessPIPErGSTDOUTstdoutreadreadliner close)r"separate_stderrrErGr$rrrinteractive_pythons   zCmdLineTest.interactive_pythoncCsZ||<}|jd|j|d|jWdn1sL0YdS)Ns print('foo') sfoo)rQrBrCrDrrLrNstrip)r"rPrErrrcheck_repl_stdout_flushs   z#CmdLineTest.check_repl_stdout_flushcCs||f}|jd|j|r,|jn|j}|d||d||d|Wdn1sv0YdS)Ns1/0 s Traceback sFile ""sZeroDivisionError)rQrBrCrDrGrLr rN)r"rPrErGrrrcheck_repl_stderr_flushs   z#CmdLineTest.check_repl_stderr_flushcCs |dSr rSr"rrrtest_repl_stdout_flushsz"CmdLineTest.test_repl_stdout_flushcCs|ddSNTrUrVrrr&test_repl_stdout_flush_separate_stderrsz2CmdLineTest.test_repl_stdout_flush_separate_stderrcCs |dSr rTrVrrrtest_repl_stderr_flushsz"CmdLineTest.test_repl_stderr_flushcCs|ddSrXrZrVrrr&test_repl_stderr_flush_separate_stderrsz2CmdLineTest.test_repl_stderr_flush_separate_stderrc CsRt6}t|d}|j||||dtjj|dWdn1sD0YdS)Nscript)r*rtemp_dirrr:r r>SourceFileLoaderr"rr#rrrtest_basic_scripts   zCmdLineTest.test_basic_scriptc CsntR}|tj||t|d}tj|}|||||dt j j Wdn1s`0YdS)Nr]) rZtemp_cwd assertTruerpathisabsrbasenamer:r r>r`)r"rr#Z relative_namerrrtest_script_abspaths    zCmdLineTest.test_script_abspathc CsptT}t|d}tj|ddt|t|}|||||dt j j Wdn1sb0YdS)Nr]Tdoraise rr_r py_compilecompilerremovemake_legacy_pycr:r r>SourcelessFileLoaderr"rr#pyc_filerrrtest_script_compileds    z CmdLineTest.test_script_compiledc CsNt2}t|d}|||||dtjjWdn1s@0YdS)N__main__r^rarrrtest_directorys    zCmdLineTest.test_directoryc CsptT}t|d}tj|ddt|t|}|||||dt j j Wdn1sb0YdS)NrsTrhrtrjrprrrtest_directory_compileds     z#CmdLineTest.test_directory_compiledcCs@t$}d|}|||Wdn1s20YdS)N"can't find '__main__' module in %r)rr_r<)r"rmsgrrrtest_directory_errors z CmdLineTest.test_directory_errorc Cs\t@}t|d}t|d|\}}|||||dtjWdn1sN0YdS)Nrstest_ziprt)rr_rrr: zipimport zipimporter)r"rr#zip_namerun_namerrr test_zipfile s   zCmdLineTest.test_zipfilec CsptT}t|d}tj|dtjjd}t|d|\}}|||||dt j Wdn1sb0YdSNrsT)riinvalidation_moderzrt) rr_rrkrlPycInvalidationMode TIMESTAMPrr:r{r|r"rr# compiled_namer}r~rrrtest_zipfile_compiled_timestamps  z+CmdLineTest.test_zipfile_compiled_timestampc CsptT}t|d}tj|dtjjd}t|d|\}}|||||dt j Wdn1sb0YdSr) rr_rrkrlr CHECKED_HASHrr:r{r|rrrr"test_zipfile_compiled_checked_hashs  z.CmdLineTest.test_zipfile_compiled_checked_hashc CsptT}t|d}tj|dtjjd}t|d|\}}|||||dt j Wdn1sb0YdSr) rr_rrkrlrUNCHECKED_HASHrr:r{r|rrrr$test_zipfile_compiled_unchecked_hash's  z0CmdLineTest.test_zipfile_compiled_unchecked_hashcCsZt>}t|d}t|d|\}}d|}|||Wdn1sL0YdS)NZnot_mainrzrw)rr_rrr<)r"rr#r}r~rxrrrtest_zipfile_error1s   zCmdLineTest.test_zipfile_errorc CsltP}tj|d}t|t|d}|jddg|||dtj j |dWdn1s^0YdS)Ntest_pkgr]-mtest_pkg.scriptr, rr_rrdjoinrrr:r r>r`r"rpkg_dirr#rrrtest_module_in_package8s  z"CmdLineTest.test_module_in_packagec Cs^tB}t|ddd\}}|jddg|||dtj||dWdn1sP0YdS)Nrzrr]rrZ PYTHONPATHr-rr_rr:r{r|r"rr}r~rrr!test_module_in_package_in_zipfileBs  z-CmdLineTest.test_module_in_package_in_zipfilec CsbtF}t|ddddd\}}|jddg|||dtj||d Wdn1sT0YdS) Nrzrr])rrztest_pkg.test_pkg.scriptztest_pkg.test_pkgrrrrrr$test_module_in_subpackage_in_zipfileIs z0CmdLineTest.test_module_in_subpackage_in_zipfilec CsltP}tj|d}t|t|d}|jddg|||dtj j |dWdn1s^0YdS)Nrrsrr,rrrrr test_packageQs   zCmdLineTest.test_packagec Cstr}tj|d}t|t|d}tj|dd}t |t |}|j ddg|||dt j j|dWdn1s0YdS)NrrsTrhrr,)rr_rrdrrrrkrlrmrnr:r r>ro)r"rrr#rrqrrrtest_package_compiled[s     z!CmdLineTest.test_package_compiledcCsZt>}tj|d}t|d}|jddg||dWdn1sL0YdS)Nrz7'test_pkg' is a package and cannot be directly executedrr,rr_rrdrrr<)r"rrrxrrrtest_package_errorhs  zCmdLineTest.test_package_errorcCsptT}tj|d}t|tj|d}t|d}|jddg||dWdn1sb0YdS)Nrrsz^Cannot use package as __main__ module; 'test_pkg' is a package and cannot be directly executedrr,r)r"rrZmain_dirrxrrrtest_package_recursionps z"CmdLineTest.test_package_recursionc Cst}tj|dtj|d}t|dt|d}tddgt Rddi\}}}t d krlt t |d d}| |d ||||||||dtjjWdn1s0YWdn1s0YdS) Nrdrz1import sys; print('init_argv0==%r' % sys.argv[0])r]rrr/Frzinit_argv0==%rr)rr_ change_cwdrrdrrrrr2rrrr r!r+r r>r`)r"rrr#r7r8r9r@rrrtest_issue8202{s     zCmdLineTest.test_issue8202c Cst}tj|dtdd\}|dtdddd\}}}tdkrVtt|d d }| | d |Wdn1s0YWdn1s0YWdn1s0YdS) Nrr=wr$z2import sys; print("sys.path[0]==%r" % sys.path[0])F)r/rzsys.path[0]==%rrtr) rr_ropenrCrrrrr r!)r"rfr7r8r9r@rrr"test_issue8202_dash_c_file_ignoreds     z.CmdLineTest.test_issue8202_dash_c_file_ignoredc Cst}t|d}tj|d~tddT}|dtddgtRddi\}}}|||||||dt j j Wdn1s0YWdn1s0YWdn1s0YdS) Notherrrrr$r/Frt) rr_rrrrCrr2r+r r>r`)r"rr#rr7r8r9rrr"test_issue8202_dash_m_file_ignoreds      z.CmdLineTest.test_issue8202_dash_m_file_ignoredc Cst}tj|d}t|dddF}|d|dtdD]}|dqD|dWdn1sr0Ytj|d t |\}}}Wdn1s0Y| d || d |Wdn1s0YdS) Nz issue20884.pyr )newlinez#coding: iso-8859-1 z""" zQxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx r) rr_rrdrrrCrangerrr)r"rr#r_r7r8r9rrrtest_issue20884s     (, zCmdLineTest.test_issue20884c gs|t`}tj|d4tj|d}t|g|R|VWdn1sP0YWdn1sn0YdS)Nrr)rr_rrrdrr)r"argsrrrrrsetup_test_pkgs   zCmdLineTest.setup_test_pkgcGs@tdg|Rddi\}}}tdkr0tt|||d|S)Nrr/Fr)rrrrr)r"rr7r8r9rrrcheck_dash_m_failures   z CmdLineTest.check_dash_m_failurecCsV|:}t|dd}|jdgtR}|d|Wdn1sH0YdS)Nrz+if __name__ == '__main__': raise ValueErrorztest_pkg.others ValueError)rrrr2r )r"rr#r9rrrtest_dash_m_error_code_is_ones  z)CmdLineTest.test_dash_m_error_code_is_onec Cstd}|D]f\}}||Dtd|\}}}||d||||d|Wdq1sd0YqdS)N))builtinssNo code object available)z builtins.xs=Error while finding module specification.*ModuleNotFoundError)z builtins.x.ys]Error while finding module specification.*ModuleNotFoundError.*No module named.*not a package)zos.pathsloader.*cannot handle)r s=No module named.*is a package and cannot be directly executed)zimportlib.nonexistentsNo module named)z .unittests#Relative module names not supportedrr Traceback)subTestrr assertRegex assertNotIn)r"ZtestsnameZregexr7rr9rrrtest_dash_m_errorss    zCmdLineTest.test_dash_m_errorsc Cst}tj|drtdtddWdn1sB0Y|d}||d|d||d|Wdn1s0YWdn1s0YdS)Nrrztest_pkg/__init__.pycwbsGError while finding module specification.*ImportError.*bad magic numbers is a packager) rr_rrmkdirrrrrr"rr9rrrtest_dash_m_bad_pycs      zCmdLineTest.test_dash_m_bad_pycc Cst|}tj|dPtddWdn1s80Y|d}|d|Wdn1sl0YWdn1s0YdS)Nrz asyncio.pyrs>Try using 'asyncio' instead of 'asyncio.py' as the module name)rr_rrrr rrrr*test_hint_when_triying_to_import_a_py_files    z6CmdLineTest.test_hint_when_triying_to_import_a_py_filec Csttttf}|D]}|j}d|}||n||D}|d}| | d|| d|| d|Wdn1s0YWdq1s0YqdS)Nz%raise {0}('Exception in __init__.py')rasciisException in __init__.pyr) ImportErrorAttributeError TypeError ValueError__name__formatrrrr r!)r" exceptions exceptioninitrr9rrrtest_dash_m_init_tracebacks     z&CmdLineTest.test_dash_m_init_tracebackcCsj|N}d}t|d||d}|d||d||d|Wdn1s\0YdS)Nz1raise ImportError('Exception in __main__ module')rsrs ImportErrorsException in __main__ moduler)rrrr )r"rmainr9rrrtest_dash_m_main_tracebacks     z&CmdLineTest.test_dash_m_main_tracebackcCstd}t}t|d|}t|\}}}|dd}|t |d| |d d| |d d | |d  d Wdn1s0YdS) Nz| try: raise ValueError except: raise NameError from None r]rrrZ Tracebackrz File  NameError) textwrapdedentrr_rrdecodesplitrlenrc startswithr"r]rr#exitcoderLrGtextrrrtest_pep_409_verbiages   z!CmdLineTest.test_pep_409_verbiagecCstjrtjdvrttj}ntjr,tj}n |dd}tt ||}| tj |t |\}}}| t||dd||f| d|dS)N)win32darwinzneed support.TESTFN_NONASCIIzprint(ascii(__file__)) rzstdout=%r stderr=%rr)rZTESTFN_UNDECODABLEsysplatformrfsdecodeZTESTFN_NONASCIIZskipTestrrZ addCleanupunlinkrrrrstripr)r"rrr#r7rLrGrrrtest_non_ascii*s"   zCmdLineTest.test_non_asciicCsjtd}tD}t|d|}t|\}}}|d}||dWdn1s\0YdS)Nz import sys error = None try: raise ValueError('some text') except ValueError as err: error = err if error: sys.exit(error) r]rz some text) rrrr_rrrrrrrrr)test_issue20500_exit_with_exception_valueAs    z5CmdLineTest.test_issue20500_exit_with_exception_valuecCsld}tL}t|d|}t|\}}}tt|d}|d|Wdn1s^0YdS)Nz 1 + 1 = 2 r]r 1 + 1 = 2 ^) rr_rrio TextIOWrapperBytesIOrMr rrrr*test_syntaxerror_unindented_caret_positionSs   z6CmdLineTest.test_syntaxerror_unindented_caret_positioncCstd}t}t|d|}t|\}}}tt|d }| d|d}t|d|}t|\}}}tt|d }| d|| d|Wdn1s0YdS)Nz; if True: 1 + 1 = 2 r]rrzif True: 1 + 1 = 2  ) rrrr_rrrrrrMr rrrrr(test_syntaxerror_indented_caret_position\s      z4CmdLineTest.test_syntaxerror_indented_caret_positioncCsfd}tF}t|d|}t|\}}}||ddgdWdn1sX0YdS)Nzfoo = f"""{} foo""" r])s foo""" ^s3SyntaxError: f-string: empty expression not allowedrr_rrr splitlinesr"r]rr#rrLrGrrr#test_syntaxerror_multi_line_fstringss  z/CmdLineTest.test_syntaxerror_multi_line_fstringcCshd}tH}t|d|}td|\}}}||ddgdWdn1sZ0YdS)Nzfoo = """\q""" r]z-Werrorr)s foo = """\q"""rs'SyntaxError: invalid escape sequence \qrrrrr3test_syntaxerror_invalid_escape_sequence_multi_lines   z?CmdLineTest.test_syntaxerror_invalid_escape_sequence_multi_linec Cstd}d|_t}t}t|d|}td||d}t| }| |d|| ||td||d}t| }| ||td||d}t| }| |||Wdn1s0YWdn1s0YdS)Nc import sys for entry in sys.path: print(entry) rsz-Esr,rz-I) rrmaxDiffrr_rr r rrrr) r"r]work_dirrr#rEZ out_by_nameZ out_by_dirZout_by_dir_isolatedrrr-test_consistent_sys_path_for_direct_executions    z9CmdLineTest.test_consistent_sys_path_for_direct_executionc Cstd}d|_t}tj|d}t|t |d|}t dd|d}t | }||d||||t dd|d}t | }|||tdd|d\}} } | } |d | d Wdn1s0YdS) NrZ script_pkgrsz-smzscript_pkg.__main__r,rz-ImzNo module named script_pkg)rrrrr_rrdrrrr r rrrrrr ) r"r]rrr#rEZ out_by_moduleZout_by_packagerrLrGZtraceback_linesrrr-test_consistent_sys_path_for_module_executions$        z9CmdLineTest.test_consistent_sys_path_for_module_executioncCsTd}|tj|t|dtjtjd}|\}}|d|| |j ddS)Nznonexistingscript.pyT)rrLrGz: can't open file r) Z assertFalserrdexistsr rIrJ communicater ZassertNotEqual returncode)r"r]procr8r9rrrtest_nonexisting_scripts  z#CmdLineTest.test_nonexisting_script)N)F)F)F)9r __module__ __qualname__r+r:r<rArF contextlibcontextmanagerrQrSrTrWrYr[r\rbrgrrrurvryrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrZsr                      %rcCs tdSr )r reap_childrenrrrrtearDownModulesrrs)!rr Zimportlib.machineryr{ZunittestrrZos.pathrkrIrrtestrZtest.support.script_helperrrrrrrr r rr2Z test_sourcerrZTestCaserrrrrrrrs8 (5