o ,]M@sddlmZmZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z mZmZmZmZddlmZmZmZerHddlZddZdd ZGd d d eZGd d d eZGdddeZGdddejZeedZddZ ddZ!ddZ"ddZ#e$ejdsejj%ej_&d$ddZ'e$ejdse ejde'Gddde(Z)Gd d!d!e)Z*d$d"d#Z+e$ejd#se ejd#e+dSdS)%)print_functionabsolute_importN)dedent) bind_methodPY26PY3PY2PY27) check_outputSTDOUTCalledProcessErrorcCs|dr |dd}t|S)z, Removes any leading and dedents.  N) startswithr)coder3/usr/lib/python3/dist-packages/future/tests/base.py reformat_codes  rcs^|dddtD}ddtD}ddtD}||ks*Jddd}d d }||||ks>Jd tfd d|D}tt||}tfd d|D}tt||} tfdd|D} tt|| } g} ttD]-} | |vr| || q|| |vr| | | q|| |vr| | | q|| | q|d | S)a Returns the code block with any ``__future__`` import lines sorted, and then any ``future`` import lines sorted, then any ``builtins`` import lines sorted. This only sorts the lines within the expected blocks. See test_order_future_lines() for an example. r cSg|] \}}|dr|qS)from __future__ import r.0ilinerrr *  z&order_future_lines..cSs(g|]\}}|ds|dr|qS)z from futurez from pastrrrrrr-s  cSr)z from builtinsrrrrrr1rzIinternal usage error: dedent the code before calling order_future_lines()cSst|dkr t|SdS)Nr)lenmaxnumbersrrrmymax7sz!order_future_lines..mymaxcSst|dkr t|StdS)Nrinf)rminfloatrrrrmymin:sz!order_future_lines..myminz2the __future__ and future imports are out of ordercg|]}|qSrrrrlinesrrrCcr&rrr'r(rrrFr*cr&rrr'r(rrrIr*) split enumeratelstripsorteddictziprangerappendjoin)ruufuture_line_numbersfuture_line_numbersbuiltins_line_numbersr!r%uulsorted_uufuture_linesflsorted_future_linesblsorted_builtins_lines new_linesrrr(rorder_future_liness4  r>c@s"eZdZdZdddZddZdS)VerboseCalledProcessErrorz Like CalledProcessError, but it displays more information (message and script output) for diagnosing test failures etc. NcCs||_||_||_||_dSN)msg returncodecmdoutput)selfrArBrCrDrrr__init__`s z"VerboseCalledProcessError.__init__cCsd|j|j|j|jfS)Nz>Command '%s' failed with exit status %d Message: %s Output: %s)rCrBrArD)rErrr__str__fsz!VerboseCalledProcessError.__str__r@)__name__ __module__ __qualname____doc__rFrGrrrrr?[s  r?c@ eZdZdS) FuturizeErrorNrHrIrJrrrrrMjrMc@rL)PasteurizeErrorNrNrrrrrPmrOrPc@seZdZdZddZ  dddZdd d Zd d Z   dd dZddZ dddZ dddZ   dddZ de jfddZdS) CodeHandlerzt Handy mixin for test classes for writing / reading / futurizing / running .py files in the test suite. cCsltd|_td|_tjg|_ttj j |_ t d}|r-dt tj|i|_dSdt i|_dS)zi The outputs from the various futurize stages should have the following headers: z from __future__ import absolute_import from __future__ import division from __future__ import print_function a4 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * PYTHONPATHN)rheaders1headers2sys executable interpreterstempfilemkdtempospathseptempdirgetenvgetcwdpathsepenv)rEpypathrrrsetUpvs   zCodeHandler.setUprFTc CsP|rt|}|||j||||d|}|r&|jD]} |j| d} q|S)a Converts the code block using ``futurize`` and returns the resulting code. Passing stages=[1] or stages=[2] passes the flag ``--stage1`` or ``stage2`` to ``futurize``. Passing both stages runs ``futurize`` with both stages by default. If from3 is False, runs ``futurize``, converting from Python 2 to both 2 and 3. If from3 is True, runs ``pasteurize`` to convert from Python 3 to both 2 and 3. Optionally reformats the code block first using the reformat() function. If run is True, runs the resulting code under all Python interpreters in self.interpreters. )stages all_importsfrom3 conservative) interpreter)r_write_test_script_futurize_test_script_read_test_scriptrW_run_test_script) rErrfrgrhreformatrunrirDrj_rrrconverts  zCodeHandler.convertcCsp|r ||}||}t|trt|ts|d}t|tr*t|ts*|d}|t||dS)a Compares whether the code blocks are equal. If not, raises an exception so the test fails. Ignores any trailing whitespace like blank lines. If ignore_imports is True, passes the code blocks into the strip_future_imports method. If one code block is a unicode string and the other a byte-string, it assumes the byte-string is encoded as utf-8. utf-8N)strip_future_imports isinstancebytesdecode assertEqualr>rstrip)rErDexpectedignore_importsrrrcompares    zCodeHandler.comparecCs`g}|dD]#}|ds*|ds*|ds*d|vs*d|vs*|ds*||qd|S)a Strips any of these import lines: from __future__ import from future from future. from builtins or any line containing: install_hooks() or: install_aliases() Limitation: doesn't handle imports split across multiple lines like this: from __future__ import (absolute_import, division, print_function, unicode_literals) r rz from future zfrom builtins zinstall_hooks()zinstall_aliases()z from future.)r+rr2r3)rErrDrrrrrts   z CodeHandler.strip_future_importsc Cs`|j||||||d} |rd|vr|jn|j} nd} t|} | | vr$d} |j| | | |ddS)a< Convenience method that calls convert() and compare(). Reformats the code blocks automatically using the reformat_code() function. If all_imports is passed, we add the appropriate import headers for the stage(s) selected to the ``expected`` code-block, so they needn't appear repeatedly in the test code. If ignore_imports is True, ignores the presence of any lines beginning: from __future__ import ... from future import ... for the purpose of the comparison. )rfrgrhrprire)r{N)rrrTrSrr|) rEbeforerzrfrgr{rhrprirDheaders reformattedrrr convert_checks   zCodeHandler.convert_checkcKs|j||fi|dS)ze Convenience method to ensure the code is unchanged by the futurize process. N)r)rErkwargsrrr unchangedszCodeHandler.unchangedmytestscript.pycCs^t|tr |d}tj|j|ddd}|t|WddS1s(wYdS)z Dedents the given code (a multiline string) and writes it out to a file in a temporary folder like /tmp/tmpUDCn7x/mytestscript.py. rswtencodingN)rurvrwioopenr]writer)rErfilenamefrrrrk!s  "zCodeHandler._write_test_scriptcCsDtj|j|ddd }|}Wd|S1swY|S)Nrtrsr)rrr]read)rErr newsourcerrrrm,s   zCodeHandler._read_test_scriptc CsDg}t|}|r |d|rd}n'd}|dgkr|dn|dgkr*|dn|ddgks2J|r9|d|j|}tj|g|d |g} z t| t|jd } W| Sty} zAt |} d d | d |j|d| f} Wdn1s}wYd|vrt nt }t| dsd| _|| | j| j| jdd} ~ ww)Nz --all-importsz pasteurize.pyz futurize.pyrz--stage1rez--stage2z--conservativez-w)stderrra8Error running the command %s %s Contents of file %s: %s env=%s ---- %s ----futurizerDrD)listr2r]rUrVr r rar rr3rrMrPhasattrrDrBrC)rErrfrgrhriparamsscriptfn call_argsrDerrA ErrorClassrrrrl1sF          z!CodeHandler._futurize_test_scriptc Cs|j|}z t||g|jtd}W|StyY}z;t|}dd||gd|j|d|f}Wdn1s=wYt|dsJd|_ t ||j |j |j dd}~ww)N)rarrrrrrDr) r]r rar r rr3rrrDr?rBrC)rErrjrrDrrrArrrrn`s*     zCodeHandler._run_test_scriptN)rdFFTTF)T)rdFTFTF)r)rrdFFF)rHrIrJrKrcrrr|rtrrrkrmrlrUrVrnrrrrrQqs,+ " #   /rQz#this test is known to fail on Py2.6cCts|St|Sr@)runittestexpectedFailurefuncrrrexpectedFailurePY3 rcCrr@)rrrrrrrexpectedFailurePY26rrcCrr@)r rrrrrrexpectedFailurePY27rrcCrr@)rrrrrrrexpectedFailurePY2rrassertRaisesRegexcCsTt|ttfr|s Jdt|}||s(|pd}d||j|f}||dS)z=Fail the test unless the text matches the regular expression.z!expected_regex must not be empty.zRegex didn't matchz%s: %r not found in %rN)rustrunicoderecompilesearchpatternfailureException)rEtextexpected_regexrArrr assertRegexs    rc@s*eZdZ  dddZddZddZdS) _AssertRaisesBaseContextNcCsl||_||_|durz|j|_Wntyt||_Ynwd|_t|ttfr.t |}||_ d|_ dSr@) rz test_caserHobj_nameAttributeErrorrrurvrrrrA)rErzr callable_objrrrrrFs    z!_AssertRaisesBaseContext.__init__cCs|j|j|}|j|r@)r_formatMessagerAr)rE standardMsgrArrr _raiseFailures z&_AssertRaisesBaseContext._raiseFailurecCsR|dur |dd|_|S|||i|WddS1s"wYdS)z If callable_obj is None, assertRaises/Warns is being used as a context manager, so check for a 'msg' kwarg and return self. If callable_obj is not None, call it passing args and kwargs. NrA)poprA)rEnamerargsrrrrhandles "z_AssertRaisesBaseContext.handle)NN)rHrIrJrFrrrrrrrs   rc@s eZdZdZddZddZdS)_AssertWarnsContextzBA context manager used to implement TestCase.assertWarns* methods.cCsNtjD] }t|ddri|_qtjdd|_|j|_t d|j |S)N__warningregistry__T)recordalways) rUmodulesvaluesgetattrrwarningscatch_warningswarnings_manager __enter__ simplefilterrz)rEvrrrrs  z_AssertWarnsContext.__enter__cCs|j||||durdSz|jj}Wnty"t|j}Ynwd}|jD]-}|j}t||js4q(|dur:|}|j durH|j t|sHq(||_ |j |_ |j |_ dS|durg|d|j jt||jrv|d||jdS|d|dS)Nz"{}" does not match "{}"z{} not triggered by {}z{} not triggered)r__exit__rzrHrrrmessagerurrwarningrlinenorformatrr)rEexc_type exc_valuetbexc_namefirst_matchingmwrrrrs@        z_AssertWarnsContext.__exit__N)rHrIrJrKrrrrrrrs rcOst|||}|d|||S)aFail unless a warning of class warnClass is triggered by callable_obj when invoked with arguments args and keyword arguments kwargs. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception. If called with callable_obj omitted or None, will return a context object used like this:: with self.assertWarns(SomeWarning): do_something() An optional keyword argument 'msg' can be provided when assertWarns is used as a context object. The context manager keeps a reference to the first matching warning as the 'warning' attribute; similarly, the 'filename' and 'lineno' attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:: with self.assertWarns(SomeWarning) as cm: do_something() the_warning = cm.warning self.assertEqual(the_warning.some_attribute, 147) assertWarns)rr)rEexpected_warningrrrcontextrrrrs rr@), __future__rrrZrXrrUrrrtextwrapr future.utilsrrrrr future.moves.subprocessr r r unittest2rr>r?rMrPTestCaserQskipIfskip26rrrrrassertRaisesRegexprrobjectrrrrrrrsJ  @     " 1