Your IP : 216.73.216.213


Current Path : /opt/alt/python37/lib/python3.7/site-packages/logilab/common/__pycache__/
Upload File :
Current File : //opt/alt/python37/lib/python3.7/site-packages/logilab/common/__pycache__/testlib.cpython-37.pyc

B

�d{T���@sDdZddlmZdZddlZddlZddlmZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlmZddlmZddlmZddlmZdd	lmZdd
lmZmZmZmZddlmZddl Z!e"e!dd��syddl#Z dd
l#m$Z$Wn"e%k
�re%de&��YnXnddl Z dd
l m$Z$ddl'm(Z(ddl)m*Z*m+Z+ddl,m-Z-m.Z.ddl/m0Z0dddddgZ1dZ2ed�e�Z3dZ4dd�Z5dd�Z6dd �Z7e2d!d"d#fd$d�Z8d%d&�Z9Gd'd(�d(e j:�Z;Gd)d*�d*e<�Z=dd+l,m>Z>e>e j?�d,d-��Z@e>e j?�d.d/��ZAe j?Z?Gd0d1�d1eB�ZCGd2d3�d3eD�ZEe jFZGGd4d5�d5e$�ZHd6d7�ZIGd8d9�d9eD�ZJGd:d;�d;eK�ZLd<d=�ZMGd>d?�d?e jN�ZNed@�eNjO�eN_OddlPZPGdAdB�dBe j?�ZQGdCdD�dDePjR�ZRGdEdF�dFeN�ZSdaTGdGdH�dH�ZUGdIdJ�dJejV�ZWGdKdL�dL�ZXdMdN�ZYdOdP�ZZGdQdR�dR�Z[dSdT�Z\dUdV�Z]dWdX�Z^dS)Ya�Run tests.

This will find all modules whose name match a given prefix in the test
directory, and run them. Various command line options provide
additional facilities.

Command line options:

 -v  verbose -- run tests in verbose mode with output to stdout
 -q  quiet   -- don't print anything except if a test fails
 -t  testdir -- directory where the tests will be found
 -x  exclude -- add a test to exclude
 -p  profile -- profiled execution
 -d  dbc     -- enable design-by-contract
 -m  match   -- only run test matching the tag pattern which follow

If no non-option arguments are present, prefixes used are 'test',
'regrtest', 'smoketest' and 'unittest'.

�)�print_functionzrestructuredtext enN)�rmtree)�
itemgetter)�	dropwhile)�isgeneratorfunction)�string_types)�builtins�range�configparser�input)�
deprecated�__package__)�SkipTestz.You have to install python-unittest2 to use %s)�wraps)�Debugger�colorize_source)�cached�
classproperty)�	textutils�main�
unittest_main�
find_testsZrun_test�spawn)�testZregrtestZ	smoketest�unittest�funcZ
validationz*[lgc 0.63] use inspect.isgeneratorfunction�cs0t��r�fdd�}|St���fdd��}|S)z�A decorator ensuring no temporary file left when the function return
    Work only for temporary file create with the tempfile modulec?sZt��}tjdd�}|t_zx�||�D]
}|Vq(WWdzt|dd�Wd|t_XXdS)Nz	temp-lgc-)�prefixT)�
ignore_errors)�tempfile�
gettempdir�mkdtemp�tempdirr)�args�kwargs�
old_tmpdir�
new_tmpdir�x)�callable��G/opt/alt/python37/lib/python3.7/site-packages/logilab/common/testlib.py�proxycszwith_tempdir.<locals>.proxycsFt��}tjdd�}|t_z
�||�Szt|dd�Wd|t_XXdS)Nz	temp-lgc-)rT)r)rr r!r"r)r#�kargsr%r&)r(r)r*r+qs
)rr)r(r+r))r(r*�with_tempdir_s

r-cst���fdd��}|S)zJA decorator moving the enclosed function inside the tempfile.tempfdir
    c	s0t��}t�tj�z
�||�St�|�XdS)N)�os�getcwd�chdirrr")r#r,Zold_cwd)r(r)r*r+�s

zin_tempdir.<locals>.proxy)r)r(r+r))r(r*�
in_tempdir�s	r1cCstt|��}|j|_|S)zRA decorator run the enclosed function inside a tmpdir removed after execution
    )r-r1�__name__)r(r+r)r)r*�within_tempdir�sr3z.pyr)TcCs|g}xjt�|�D]\}|r"|�|�rxH|D]@}|�|�r(|rV|�|�rV|dt|��}||kr(|�|�q(WqW|��|S)z7
    Return a list of all applicable test modules.
    N)r.�listdir�endswith�
startswith�len�append�sort)Ztestdir�prefixes�suffixZexcludesZ
remove_suffix�tests�namerr)r)r*r�s

c	Cs|j}|j|j}t|�dkr,|d��n�x�d}td�td�dd�t|�D���td�t�yrtd�}|�	��
�d	kr�t�PnLyt|�}|||d}Wn&tt
fk
r�td
|f�Yn
X|��Wq.ttfk
r�t�PYq.Xq.WdS)zDstarts an interactive shell so that the user can inspect errors
    rrzChoose a test to debug:�
cSs g|]\}\}}d||f�qS)z	%s : %sr))�.0�i�_�descrr)r)r*�
<listcomp>�sz*start_interactive_mode.<locals>.<listcomp>zType 'exit' (or ^D) to quitzEnter a test name: �exitzERROR: invalid test number %rN)�	debuggers�error_descrs�fail_descrsr7�start�print�join�	enumerater�strip�lower�int�
ValueError�
IndexError�EOFError�KeyboardInterrupt)�resultrEZdescrsZ	testindexZtodebugZdebuggerr)r)r*�start_interactive_mode�s2rTcszeZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Z�fd
d�Z�fdd�Z	dd�Z
�fdd�Zdd�Zdd�Z
�ZS)�SkipAwareTestResultFNcsXtt|��|||�g|_g|_g|_g|_||_||_||_	||_
t|_|dk|_
dS)Nr)�superrU�__init__�skippedrErGrF�	exitfirst�pdbmode�cvg�colorizer�pdbclass�verbose)�self�streamZdescriptions�	verbosityrYrZr[r\)�	__class__r)r*rW�szSkipAwareTestResult.__init__cCst|d|���S)Nz	%s_descrs)�getattrrM)r_�flavourr)r)r*�
descrs_for�szSkipAwareTestResult.descrs_forcCs>|�|��t|j�|f�|jr:|j�|�t��d��dS)N�)rer8r7rErZr]�sys�exc_info)r_Z
test_descrrdr)r)r*�_create_pdb�szSkipAwareTestResult._create_pdbc#sBt�t��t�tj����fdd�}xt||�D]
}|Vq0WdS)z;only consider non-testlib frames when formatting  tracebackcst�|d���fkS)Nr)�osp�abspath)�fi)�lgc_testlib�std_testlibr)r*�<lambda>��z8SkipAwareTestResult._iter_valid_frames.<locals>.<lambda>N)rjrk�__file__rr)r_�frames�invalid�	frameinfor))rmrnr*�_iter_valid_frames�s

z&SkipAwareTestResult._iter_valid_framescCs�|\}}}dg}t�|�}|j}t|�|��}�x8|D�].\}	\}
}}}
}}t�|�}|dkrdd}n
d�|�}|r�t�	|d�}t
|�}|�d|||
f�|�d|���|j
r6|�dt|
�|jf�|�d�|�d	d
�dd��xft|
j���D]T\}}|�d
||f�|dkr�x0tt|����D]\}}|�d||f��q.Wq�W|�d�|�d�q6W|�d�t�||���d�|�S)z�Converts a sys.exc_info()-style tuple of values into a string.

        This method is overridden here because we want to colorize
        lines if --color is passed, and display local variables if
        --verbose is passed
        z!Traceback (most recent call last)Nz<no source available>�Zmagentaz  File "%s", line %s, in %sz    %sz%r == %rz    z local variables �B�-z
    %s: %rr_z      self.%s: %rzF    ------------------------------------------------------------------r>)�inspect�getinnerframesr\rKrurjrkrJrZ
colorize_ansirr8rLr^�dir�
__module__�center�sorted�f_locals�items�vars�	traceback�format_exception_only)r_�errr�exctype�exc�tb�outputrrr\�index�frame�filename�lineno�funcname�ctxZctxindex�sourceZvarname�valuer)r)r*�_exc_info_to_string�s8





z'SkipAwareTestResult._exc_info_to_stringcsf|\}}}t|t�r.|tks t�|�||�n4|jr:d|_|�|�}tt|��	||�|�
|d�dS)zerr ->  (exc_type, exc, tcbk)T�errorN)�
isinstancer�AssertionError�addSkiprY�
shouldStop�getDescriptionrVrU�addErrorri)r_rr��exc_typer�rArB)rbr)r*r�s


zSkipAwareTestResult.addErrorcs8|jrd|_|�|�}tt|��||�|�|d�dS)NT�fail)rYr�r�rVrU�
addFailureri)r_rr�rB)rbr)r*r�"s

zSkipAwareTestResult.addFailurecCs:|j�||f�|jr$|j�d�n|jr6|j�d�dS)N�SKIPPED�S)rXr8ZshowAllr`�writelnZdots�write)r_r�reasonr)r)r*r�)s
zSkipAwareTestResult.addSkipcstt|���|��dS)N)rVrU�printErrors�printSkippedList)r_)rbr)r*r�0szSkipAwareTestResult.printErrorscCsTxN|jD]D\}}|�|�}|j�|j�|j�dd|f�|j�d|�qWdS)Nz%s: %sr�z	%s)rXr�r`r��
separator1)r_rr�rBr)r)r*r�4s

z$SkipAwareTestResult.printSkippedListcCs�x�t|�|�|�D]|\\}}\}}|j�|j�|j�d||f�|j�|j�|j�|�|j�d�t|j���|j�d�t|j���qWdS)Nz%s: %sz	no stdoutz	no stderr)�ziprer`r�r�Z
separator2r}r7)r_rd�errorsrArBrr�r)r)r*�printErrorList<s"z"SkipAwareTestResult.printErrorList)FFNF)r2r|�__qualname__rWrerirur�r�r�r�r�r�r��
__classcell__r)r))rbr*rU�s%
rUc@seZdZdZdZdZdZdS)�_DebugResultzCUsed by the TestSuite to hold previous class when running in debug.NF)r2r|r��__doc__Z_previousTestClass�_moduleSetUpFailedr�r)r)r)r*r�Gsr�)�monkeypatchc
Cs�|�|�}|dkrdS|jr dSytj|}Wntk
rBdSXt|d�rht�dt�t	|d|j
�t|dd�}|dk	r�y
|�WnDtk
r�}z&t
|t�r��d|}|�|||�Wdd}~XYnXdS)N�teardown_modulez<Please rename teardown_module() to tearDownModule() instead.�tearDownModuleztearDownModule (%s))�_get_previous_moduler�rg�modules�KeyError�hasattr�warnings�warn�DeprecationWarning�setattrr�rc�	Exceptionr�r��_addClassOrModuleLevelException)r_rS�previousModule�moduler��e�	errorNamer)r)r*�_handleModuleTearDownNs,



r�c	
Cs�|�|�}|jj}||krdS|�|�d|_ytj|}Wntk
rPdSXt|d�rvt	�
dt�t|d|j
�t|dd�}|dk	r�y
|�WnJtk
r�}z,t|t�r��d|_d|}|�|||�Wdd}~XYnXdS)NF�setup_modulez6Please rename setup_module() to setUpModule() instead.�setUpModuleTzsetUpModule (%s))r�rbr|r�r�rgr�r�r�r�r�r�r�r�rcr�r�r�r�)	r_rrSr�Z
currentModuler�r�r�r�r)r)r*�_handleModuleFixtureis0




r�c@seZdZdZdS)�keywordsz5Keyword args (**kwargs) support for generative tests.N)r2r|r�r�r)r)r)r*r��sr�c@seZdZdZdd�ZdS)�starargsz0Variable arguments (*args) for generative tests.cGst�||�S)N)�tuple�__new__)�clsr#r)r)r*r��szstarargs.__new__N)r2r|r�r�r�r)r)r)r*r��sr�c@seZdZdZdS)�InnerTestSkippedzraised when a test is skippedN)r2r|r�r�r)r)r)r*r��sr�cCs�g}d}i}d}x�|D]�}t|t�rJ|}|r4td��|dO}|t|�7}qt|t�rr|}|d@rhtd��|dO}q|d@s�|d@r�td��q|�|�qW||fS)Nr)rzfound starargs after keywords !rf�z got multiple keywords parametersz%found parameters after kwargs or args)r�r��	TypeError�listr�r8)�paramsr#�varargsr$�flags�paramr)r)r*�parse_generative_args�s(




r�c@seZdZdd�ZdS)�	InnerTestcGst�||�}||_|S)N)r�r�r=)r�r=�data�instancer)r)r*r��szInnerTest.__new__N)r2r|r�r�r)r)r)r*r��sr�cs0eZdZdZ�fdd�Zdd�Zdd�Z�ZS)�Tagsz(A set of tag able validate an expressioncs\|�dd�|_|r"td|����t|�dkrDt|dt�sD|d}tt|�j	|f|�dS)N�inheritTz4%s are an invalid keyword argument for this functionrr)
�popr�r��keysr7r�rrVr�rW)r_�tagsr$)rbr)r*rW�sz
Tags.__init__cCs||kS)Nr))r_�keyr)r)r*�__getitem__�szTags.__getitem__cCst|i|�S)N)�eval)r_�expr)r)r*�match�sz
Tags.match)r2r|r�r�rWr�r�r�r)r))rbr*r��s	r�cs�fdd�}|S)Ncst�d�jtd��||�S)NzPlease use %s instead.rf)r�r�r2r�)r#r$)�
original_funcr)r*�deprecated_func�sz#_deprecate.<locals>.deprecated_funcr))r�r�r))r�r*�
_deprecate�sr�csreZdZdZdZeZe�ZdY�fdd�	Z	e
edd���Ze
dd	��Zd
d�Z�fdd
�Zdd�Zdd�ZdZdd�Zd[dd�Zd\dd�Zd]dd�Zdd�Zeejj�Zeejj�Zeejj�Z eejj!�Z"eejj#�Z$d^dd�Z%e&d�d_d d!��Z'e&d"�d`d#d$��Z(e(Z)e)Z*Z+e&d%�dad&d'��Z,e&d(�dbd)d*��Z-e&d+�dcd-d.��Z.e.Z/e&d/�ddd1d2��Z0e&d/�ded3d4��Z1dfd5d6�Z2e&d/�d7d8��Z3dgd:d;�Z4e&d+�dhd=d>��Z5e5Z6e&d/�did@dA��Z7e7Z8e&d/�djdCdD��Z9e9Z:e&d/�dEdF��Z;e;Z<dkdGdH�Z=e&dI�dldJdK��Z>e&dL�dmdMdN��Z?e&dO�dndQdR��Z@do�fdSdT�	ZAeAZBeCjDdUk�rNejjEZFnejjFZEeCjDdVk�rjdWdX�ZG�ZHS)p�TestCasez;A unittest.TestCase extension with some additional methods.N�runTestcs0tt|��|�tj|_|j|_d|_d|_	dS)N)
rVr�rWrgrh�_TestCase__exc_info�_testMethodNameZ_TestCase__testMethodName�_current_test_descr�	_options_)r_Z
methodName)rbr)r*rW�s
zTestCase.__init__cCs$t|j�}t�t�t�|j��d�S)zphelper attribute holding the standard test's data directory

        NOTE: this is a logilab's standard
        r�)�
__import__r|rjrJ�dirnamerkrq)r��modr)r)r*�datadir�s
zTestCase.datadircGstj|jf|��S)z&joins the object's datadir and `fname`)rjrJr�)r��fnamer)r)r*�datapath�szTestCase.datapathcCs
||_dS)z�sets the current test's description.
        This can be useful for generative tests because it allows to specify
        a description per yield
        N)r�)r_rBr)r)r*�set_description�szTestCase.set_descriptioncs|jdk	r|jStt|���S)z`override default unittest shortDescription to handle correctly
        generative tests
        N)r�rVr��shortDescription)r_)rbr)r*r��s
zTestCase.shortDescriptionc
Os�y|||�Wn�ttfk
r(�Ynptjk
r~}z8t|d�rV|�|t|��nt�dt	d�|�
|�dSd}~XYn|�||���dSdS)Nr�z4TestResult has no addSkip method, skips not reportedrfFT)
rR�
SystemExitrrr�r��strr�r��RuntimeWarning�
addSuccessr�r�)r_rSrr#r$r�r)r)r*�	quiet_runs

zTestCase.quiet_runcCst||j�S)zreturn the test method)rcr�)r_r)r)r*�_get_test_methodszTestCase._get_test_methodcCst|j||�S)z>return the option value or default if the option is not define)rcr�)r_�option�defaultr)r)r*�optvalszTestCase.optvalc	Cs�ddlm}|dkr|��}|j|_||_|��}t|jdd�sLt|dd�r�z*t|jdd�pft|dd�}|�||�Wd|�	|�XdS|r�||�s�dS|�
|��z|�||j�s�dSt
|�}|r�|�|||�n|�||�}|dk}	|�||j�s�dS|�s�|	�r�t|d��r�|j�r�yHt|d	�}
z.d
�|jj|jj|jf�}|
�|tj�Wd|
��XWn4tk
�r�tdt�t��|�t j!d��YnX|�"|�Wd|�	|�XdS)
z�rewrite TestCase.__call__ to support generative tests
        This is mostly a copy/paste from unittest.py (i.e same
        variable names, same logic, except for the generative tests part)
        r)�FILE_RESTARTNZ__unittest_skip__FZ__unittest_skip_why__rvrY�a�.z&Error while saving succeeded test into)�file)#Zlogilab.common.pytestr��defaultTestResultr]r�r�rcrbZ_addSkipZstopTestZ	startTestr�ZsetUpr�_proceed_generative�_proceedZtearDownr�rY�openrJr|r2r�r�r.�linesep�closer�rIrjr/rg�
__stderr__r�)r_rS�runcondition�optionsr�Z
testMethodZskip_whyZ
generative�status�successZrestartfilerBr)r)r*�__call__sZ




zTestCase.__call__c
Cs�|jd8_d}y�x�|�D]�}|rD||dd�sDt|t�r||�sDqt|ttf�sX|f}|d}t|dd��\}}|jd7_|�||||�}	|	dkr�|�|�d}nd}|jrPqWWn |�	||�
��d}YnX|S)NrTF)Z
skipgeneratorr)ZtestsRunr�r�r�r�r�r�r�r�r�r�)
r_rS�testfuncrrr�rr#r$rr)r)r*r�Ys2



zTestCase._proceed_generativer)c
Cs�|pi}y|||�Wn�|jk
r<|�||���dStk
rP�Ynrtk
r|}z|�||�dSd}~XYnFtk
r�}z|�||�dSd}~XYn|�||���dSdS)z�proceed the actual test
        returns 0 on success, 1 on failure, 2 on error

        Note: addSuccess can't be called here because we have to wait
        for tearDown to be successfully executed to declare the test as
        successful
        rNrrf)�failureExceptionr�r�rRr�r�rr�)r_rSrr#r$r�r)r)r*r�{s$zTestCase._proceedcCst�S)z.return a new instance of the defaultTestResult)rU)r_r)r)r*r��szTestCase.defaultTestResultcCs|pd}t|��dS)z6mark a generative test as skipped for the <msg> reasonztest was skippedN)r�)r_�msgr)r)r*�	innerSkip�szTestCase.innerSkipz#Please use assertDictEqual instead.c		Cs�t|�}g}xf|��D]Z\}}y.|||krD|�d||||f�||=Wqtk
rn|�d|�YqXqW|r�|�d|�|r�|�|�n.|r�|dk	r�d|}nd}|�|d�|��dS)a
compares two dicts

        If the two dict differ, the first difference is shown in the error
        message
        :param dict1: a Python Dictionary
        :param dict2: a Python Dictionary
        :param msg: custom message (String) in case of failure
        z%r != %r for key %rzmissing %r keyzdict2 is lacking %rNz%s
rvr>)�dictr�r8r�rr�rJ)	r_Zdict1Zdict2r�context�msgsr�r��baser)r)r*�assertDictEquals�s&



zTestCase.assertDictEqualsz$Please use assertCountEqual instead.c	Cs�t|�t|�}}|�t|�t|�|�t|�t|�kr�|dkr�ddg}i}i}x |D]}|�|d�d||<qVWx |D]}|�|d�d||<qxWx8|��D],\}}||}||kr�|�d|||f�q�W|�|�dS)z�compares two iterable and shows difference between both

        :param got: the unordered Iterable that we found
        :param expected: the expected unordered Iterable
        :param msg: custom message (String) in case of failure
        Nz7Iterable have the same elements but not the same numberz	<element>	<expected>i	<got>rrz		%s	%s	%s)r�ZassertSetEqual�setr7�get�	iteritemsr8r�)	r_�got�expectedrZ	got_countZexpected_count�element�count�other_countr)r)r*�assertUnorderedIterableEquals�s"

z&TestCase.assertUnorderedIterableEqualsz"Please use assertSetEqual instead.cCs�t|t�rt|t�s0t�dtd�|�|||�Si}|||d<|||d<t|���r�|dkrxd�dd�|�	�D��}|�
|�dS)	a#compares two sets and shows difference between both

        Don't use it for iterables other than sets.

        :param got: the Set that we found
        :param expected: the second Set to be compared to the first one
        :param msg: custom message (String) in case of failure
        zdthe assertSetEquals function if now intended for set only.use assertUnorderedIterableEquals instead.rf�missingZ
unexpectedNr>css2|]*\}}|rd|d�dd�|D��fVqdS)z%s:
	%sz
	css|]}t|�VqdS)N)r�)r?r�r)r)r*�	<genexpr>�sz5TestCase.assertSetEquals.<locals>.<genexpr>.<genexpr>N)rJ)r?r��valuesr)r)r*r�sz+TestCase.assertSetEquals.<locals>.<genexpr>)r�rr�r�r�r�anyZ
itervaluesrJrr�)r_rrrr�r)r)r*�assertSetEquals�s
zTestCase.assertSetEqualsz#Please use assertListEqual instead.c	Cs�|dd�}x�t|�D]�\}}yJ|d|kr`ddlm}||�||�|�d|d||f�|d=Wqtk
r�|dkr�d|t|�|f}|�|�YqXqW|r�|dkr�d|}|�|�dS)acompares two lists

        If the two list differ, the first difference is shown in the error
        message

        :param list_1: a Python List
        :param list_2: a second Python List
        :param msg: custom message (String) in case of failure
        Nr)�pprintz%r != %r for index %dz9list_1 has only %d elements, not %s (at least %r missing)zlist_2 is lacking %r)rKrr�rPr7)r_Zlist_1Zlist_2rZ_l1r@r�rr)r)r*�assertListEquals�s$
zTestCase.assertListEqualsz6Non-standard. Please use assertMultiLineEqual instead.FcCsB|��}|��}|r0dd�|D�}dd�|D�}|�|||�dS)a-compare two strings and assert that the text lines of the strings
        are equal.

        :param string1: a String
        :param string2: a String
        :param msg: custom message (String) in case of failure
        :param striplines: Boolean to trigger line stripping before comparing
        cSsg|]}|���qSr))rL)r?�lr)r)r*rC)sz.TestCase.assertLinesEquals.<locals>.<listcomp>cSsg|]}|���qSr))rL)r?rr)r)r*rC*sN)�
splitlinesZassertListEqual)r_Zstring1Zstring2r�
striplines�lines1�lines2r)r)r*�assertLinesEqualss
zTestCase.assertLinesEqualsz<Non-standard: please copy test method to your TestCase classrfc
Cs�yddlm}|�|||�Wn�tk
r�ddlm}m}|�}y|�|�Wn~|k
r�}z`|dkr�|�d�xt|�	��D]}	|�
�}
q�Wd|�	�dd}d||
|f}|�|�Wdd}~XYnXYnXdS)	z�asserts the XML stream is well-formed (no DTD conformance check)

        :param context: number of context lines in standard message
                        (show all data if negative).
                        Only available with element tree
        r)�parse)�make_parser�SAXParseExceptionNrvr�^z#XML stream not well formed: %s
%s%s)�xml.etree.ElementTreer%�_assertETXMLWellFormed�ImportErrorZxml.saxr&r'�seekr	Z
getLineNumber�readliner�)r_r`rrr%r&r'�parser�exrA�line�pointerr)r)r*�assertXMLWellFormed.s 
zTestCase.assertXMLWellFormedcCsDyddlm}Wn tk
r0ddlm}YnX|�|||�dS)z�asserts the XML string is well-formed (no DTD conformance check)

        :param context: number of context lines in standard message
                        (show all data if negative).
                        Only available with element tree
        r)�
fromstringN)r)r3r+Zelementtree.ElementTreer*)r_Z
xml_stringrrr3r)r)r*�assertXMLStringWellFormedGs
z"TestCase.assertXMLStringWellFormedcCs�ddlm}yddlm}Wntk
r4|}YnXy||�W�n�||fk
�r�}�z\|dk�r�t|d�r�|�d�|��}n
|�d�}t	|�}	g}
|j
dk	�r�|dkr�d}|	}n t|j
|d�}t|j
||	�}t	d|�}
d	|
}x.t
||j
�D]}|
�||||df�q�W|
�||j
||j
df�|
�d
dd|
d|j�x8t
|j
d|d�D] }|
�||||df��qrWd
�|
�}d||f}|�|�Wdd}~XYnXdS)a~internal function used by /assertXML(String)?WellFormed/ functions

        :param data: xml_data
        :param parse: appropriate parser function for this data
        :param msg: error message
        :param context: number of context lines in standard message
                        (show all data if negative).
                        Only available with element tree
        r)�
ExpatError)�
ParseErrorN�	readlinesTrz%iz %%%ii: %%sz%s^
� rfrvz!XML stream not well formed: %s
%s)�xml.parsers.expatr5r)r6r+r�r,r7r r7r��max�minr	r8�offsetrJr�)r_r�r%rrr5r6r/�linesZnb_linesZ
context_linesrH�endZline_number_lengthZline_patternZline_noZrich_contextr)r)r*r*Us@






  
zTestCase._assertETXMLWellFormedc	Cs�|�|j|d�t|j�s(t|�dkr^t|�dkrL|�d|t|j�f�|�|j|d�t|�stt|�dk�rt|�dkr�|�d|t|�f�t|�t|d�kr�|�d|t|d�dt|d�dkt|�f�x0tt|d��D]}|�|||d|�q�W|j	�s$t|�dk�rXt|�dk�rF|�d	||j	f�|�|j	|d�|j
�snt|�d
k�r�t|�d
k�r�|�d||j
f�|�|j
|d
�dS)
zvcompare an ElementTree Element to a tuple formatted as follow:
        (tagname, [attrib[, children[, text[, tail]]]])rrz(tuple %s has no attributes (%s expected)rfz&tuple %s has no children (%i expected)z(tuple %s has %i children%s (%i expected))rv�s�z(tuple %s has no text value (%r expected)r�z(tuple %s has no tail value (%r expected)N)�assertTextEquals�tagr7Zattribr�r
ZassertDictEqualr	�assertXMLEqualsTuple�text�tail)r_r�tupr�r)r)r*rC�s4
 zTestCase.assertXMLEqualsTuple�Texts differcsl�pd�tj||�fdd�d�}g}xB|D]:}|�|�|�d�s*|�d�d|g|t|���q*WdS)N)r8�	cs|�kS)Nr))r')�junkr)r*ro�rpz$TestCase._difftext.<locals>.<lambda>)Zcharjunkr8r>z%s
)�difflibZndiffr8r6r�rJr�)r_r"r#rI�
msg_prefixrS�readr0r))rIr*�	_difftext�s


zTestCase._difftext�Text differc	Cs�g}t|t�s |�dt|��t|t�s<|�dt|��|rP|�d�|��|���d�}|���d�}|r�dd�|D�}dd�|D�}|�||||�dS)	aKcompare two multiline strings (using difflib and splitlines())

        :param text1: a Python BaseString
        :param text2: a second Python Basestring
        :param junk: List of Caracters
        :param msg_prefix: String (message prefix)
        :param striplines: Boolean to trigger line stripping before comparing
        ztext1 is not a string (%s)ztext2 is not a string (%s)r>TcSsg|]}|���qSr))rL)r?r0r)r)r*rC�sz-TestCase.assertTextEquals.<locals>.<listcomp>cSsg|]}|���qSr))rL)r?r0r)r)r*rC�sN)	r�rr8�typer�rJrLr rM)	r_Ztext1Ztext2rIrKr!rr"r#r)r)r*rA�s

zTestCase.assertTextEquals�
Stream differcCs<||krdS|�d�|�d�|�|��|��||�dS)z3compare two streams (using difflib and readlines())Nr)r,rMr7)r_Zstream1Zstream2rIrKr)r)r*�assertStreamEquals�s

zTestCase.assertStreamEquals�r8rHcCs&|jt|�t|�|d||fd�dS)z compares two files using difflibzFiles differs
-:%s
+:%s
)rKN)�assertStreamEqualr�)r_Zfname1Zfname2rIr)r)r*�assertFileEquals�szTestCase.assertFileEqualsc
st���std���t���s,td����fdd�t���D�}|jtd�d��fdd�t���D�}|jtd�d�t|�t|�}}d}d\}}	}
}�xd�yDt|�\}}	}
}d	}t|�\}
}}}d}|�	||
kd
|�|
�f�i}t
|	�}t
|�}|||d<|||d<t
|
�}t
|�}|||d
<|||d<dd�|��D�}|�r�|�ddt�
�|�t�
�|
�f�|�d�
|��x|
|fD]}|���q�Wx:t|
�D].\}}|�t�
�||�t�
�|
||���q�WWq�tk
�rPYq�Xq�WdS)z compares two files using difflibz%s doesn't existscs.g|]&\}}}|t��d��d�||f�qS)N�/)r7�lstrip)r?�ipath�idirs�ifiles)�path_ar)r*rC�sz,TestCase.assertDirEquals.<locals>.<listcomp>r)r�cs.g|]&\}}}|t��d��d�||f�qS)NrU)r7rV)r?rWrXrY)�path_br)r*rC�sT)NNNFz,unexpected %s in %s while looking %s from %szunexpected directorieszmissing directorieszunexpected filesz
missing filescSs g|]\}}|rd||f�qS)z%s: %sr))r?r=r�r)r)r*rCsz%s and %s differ :r>N)rj�existsr�r.�walkr9r�iter�next�
assertTruerr��insertrJr�rKrT�
StopIteration)r_rZr[Zall_aZall_bZiter_aZiter_bZpartial_iterZipath_aZidirs_aZifiles_aZdata_aZdatas_aZipath_bZidirs_bZifiles_bZdatas_br�Zsdirs_aZsdirs_bZsfiles_aZsfiles_br�filesr��pathr))rZr[r*�assertDirEquals�sV



zTestCase.assertDirEqualscCsj|rtjdtdd�|dkr<|r&d}nd}|||t|�f}|rT|�|j|k|�n|�t||�|�dS)aAcheck if an object is an instance of a class

        :param obj: the Python Object to be checked
        :param klass: the target class
        :param msg: a String for a custom message
        :param strict: if True, check that the class of <obj> is <klass>;
                       else check with 'isinstance'
        z1[API] Non-standard. Strict parameter has vanishedrf)�
stacklevelNz%r is not of class %s but of %sz%%r is not an instance of %s but of %s)r�r�r�rOr`rbr�)r_�obj�klassr�strictr)r)r*�assertIsInstance)s	
zTestCase.assertIsInstancez Please use assertIsNone instead.cCs&|dkrd|f}|�|dk|�dS)zKassert obj is None

        :param obj: Python Object to be tested
        Nz"reference to %r when None expected)r`)r_rgrr)r)r*�
assertNone@s
zTestCase.assertNonez#Please use assertIsNotNone instead.cCs |dkrd}|�|dk	|�dS)zassert obj is not NoneNzunexpected reference to None)r`)r_rgrr)r)r*�
assertNotNoneJszTestCase.assertNotNonez3Non-standard. Please use assertAlmostEqual instead.��h㈵��>cCsD|dkrd||f}|r&|t�|�}|�t�||�|k|�dS)adcompares if two floats have a distance smaller than expected
        precision.

        :param obj: a Float
        :param other: another Float to be comparted to <obj>
        :param prec: a Float describing the precision
        :param relative: boolean switching to relative/absolute precision
        :param msg: a String for a custom message
        Nz%r != %r)�math�fabsr`)r_rg�otherZprecZrelativerr)r)r*�assertFloatAlmostEqualsQs
z TestCase.assertFloatAlmostEqualsc	
s�|dkr&tt|�j}|||f|�|�Sy|||�Wn4|k
rh}zGdd�d�}||�Sd}~XYn*Xt|d�r||j}nt|�}|�d|��dS)a�override default failUnlessRaises method to return the raised
        exception instance.

        Fail unless an exception of class excClass is thrown
        by callableObj when invoked with arguments args and keyword
        arguments kwargs. If a different type of exception is
        thrown, it will not be caught, and the test case will be
        deemed to have suffered an error, exactly as for an
        unexpected exception.

        CAUTION! There are subtle differences between Logilab and unittest2
        - exc is not returned in standard version
        - context capabilities in standard version
        - try/except/else construction (minor)

        :param excClass: the Exception to be raised
        :param callableObj: a callable Object which should raise <excClass>
        :param args: a List of arguments for <callableObj>
        :param kwargs: a List of keyword arguments  for <callableObj>
        Nc@seZdZdd�Zdd�ZdS)z1TestCase.failUnlessRaises.<locals>.ProxyExceptioncSs
||_dS)N)�_obj)r_rgr)r)r*rW�sz:TestCase.failUnlessRaises.<locals>.ProxyException.__init__cSsd}t�|td�|j�|�S)Nz�This exception was retrieved with the old testlib way `exc = self.assertRaises(Exc, callable)`, please use the context manager instead'rf)r�r�r�rr�__getattribute__)r_�attrZwarn_msgr)r)r*�__getattr__�sz=TestCase.failUnlessRaises.<locals>.ProxyException.__getattr__N)r2r|r�rWrur)r)r)r*�ProxyExceptionsrvr2z
%s not raised)rVr��assertRaisesr�r2r�r)	r_ZexcClassZcallableObjr#r$Z_assertr�rvZexcName)rbr)r*�failUnlessRaisescs	
zTestCase.failUnlessRaises)r@rf)rf�cOs|jd|f|�|�dS)N)�assertNotEqual)r_r�r#r$r)r)r*�assertIsNotNone�szTestCase.assertIsNotNone)r�)N)NNN)N)r)N)N)NN)N)N)N)NF)Nrf)Nrf)Nrf)NrG)NrNF)NrP)rR)NF)N)N)rmFN)N)Ir2r|r�r�ZmaxDiffrr]r�r�rWrrr��classmethodr�r�r�r�r�r�rr�r�r�r�rr��skipTest�skipZassertEqualZassertEqualsrzZassertNotEqualsZassertAlmostEqualZassertAlmostEqualsZassertNotAlmostEqualZassertNotAlmostEqualsr	rrrZassertUnorderedIterableEqualZassertUnordIterEqualsZassertUnordIterEqualrrr$ZassertLineEqualr2r4r*rCrMrAZassertTextEqualrQrSrTZassertFileEqualreZassertDirEqualrjrkrlrqrxrwrg�version_infoZassertCountEqual�assertItemsEqualr{r�r)r))rbr*r��s�

>
"


2$

>
	-
r�z4assertItemsEqual is deprecated, use assertCountEqualc@seZdZdd�ZdS)�SkippedSuitecCs|�d�dS)z$just there to trigger test executionz(doctest module has no DocTestSuite classN)Zskipped_test)r_r)r)r*r�szSkippedSuite.testN)r2r|r�rr)r)r)r*r��sr�c@seZdZdd�Zdd�ZdS)�
DocTestFindercOs&|�dd�|_tjj|f|�|�dS)NrXr))r�rX�doctestr�rW)r_r#r$r)r)r*rW�szDocTestFinder.__init__cCs,t|dd�|jkrdStj�||||||�S)zroverride default _get_test method to be able to skip tests
        according to skipped attribute's value
        r2rvN)rcrXr�r��	_get_test)r_rgr=r��globsZsource_linesr)r)r*r��szDocTestFinder._get_testN)r2r|r�rWr�r)r)r)r*r��sr�c@s*eZdZdZdZddd�ZeZdd�ZdS)	�DocTestztrigger module doctest
    I don't know how to make unittest.main consider the DocTestSuite instance
    without this hack
    r)Nc	Csxy*t|jd�}tj|j|d�}tjtj_Wnt	k
rDt
�}YnXtj�
�}z
|�|�Stj��tj�|�XdS)N)rX)Ztest_finder)r�rXr�ZDocTestSuiter�rgrhZDocTestCaser��AttributeErrorr�r�__dict__�copy�run�clear�update)r_rSrr�finderZsuiteZold_builtinsr)r)r*r�s


zDocTest.__call__cCsdS)z$just there to trigger test executionNr))r_r)r)r*r�szDocTest.test)NNN)r2r|r�r�rXrr�rr)r)r)r*r��s

r�c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�MockSMTPzfake smtplib.SMTPcCs||_||_g|_adS)N)�host�port�reveived�MAILBOX)r_r�r�r)r)r*rW�szMockSMTP.__init__cCsdS)zignore debug levelNr))r_Z
debuglevelr)r)r*�set_debuglevel�szMockSMTP.set_debuglevelcCs|j�|||f�dS)zpush sent mail in the mailboxN)r�r8)r_ZfromaddrZtoaddres�bodyr)r)r*�sendmail�szMockSMTP.sendmailcCsdS)zignore quitNr))r_r)r)r*�quit�sz
MockSMTP.quitN)r2r|r�r�rWr�r�r�r)r)r)r*r��s
r�c@s eZdZdZdd�Zdd�ZdS)�MockConfigParserzfake ConfigParser.ConfigParsercCsTtj�|�xB|��D]6\}}|�|�x"|��D]\}}|�|||�q2WqWdS)N)r
�ConfigParserrWr�add_sectionr)r_r�section�pairsr�r�r)r)r*rW�s

zMockConfigParser.__init__cCs
t��dS)N)�NotImplementedError)r_rAr)r)r*r��szMockConfigParser.writeN)r2r|r�r�rWr�r)r)r)r*r��sr�c@sReZdZdZdd�Zdd�Zddd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�ZdS)�MockConnectionz@fake DB-API 2.0 connexion AND cursor (i.e. cursor() return self)cCsg|_g|_||_dS)N)�received�states�results)r_r�r)r)r*rW�szMockConnection.__init__cCs|S)zMock cursor methodr))r_r)r)r*�cursor�szMockConnection.cursorNcCs|j�||f�dS)zMock execute methodN)r�r8)r_�queryr#r)r)r*�execute�szMockConnection.executecCs
|jdS)zMock fetchone methodr)r�)r_r)r)r*�fetchoneszMockConnection.fetchonecCs|jS)zMock fetchall method)r�)r_r)r)r*�fetchallszMockConnection.fetchallcCs|j�dt|j�f�dS)zMock commiy method�commitN)r�r8r7r�)r_r)r)r*r�szMockConnection.commitcCs|j�dt|j�f�dS)zMock rollback method�rollbackN)r�r8r7r�)r_r)r)r*r�szMockConnection.rollbackcCsdS)zMock close methodNr))r_r)r)r*r�szMockConnection.close)N)r2r|r�r�rWr�r�r�r�r�r�r�r)r)r)r*r��s
r�cKstdd|��S)z�creates an object using params to set attributes
    >>> option = mock_object(verbose=False, index=range(5))
    >>> option.verbose
    False
    >>> option.index
    [0, 1, 2, 3, 4]
    ZMockr))rO)r�r)r)r*�mock_objectsr�cCs�t�t�}}xP|D]H}t�||�}t�|�}|dkrB|�|�q|�t�|��|�|�qWx |D]}t�|�sft�|�qfWx|D]}t	|d��
�q�WdS)a�Creates directories and files found in <path>.

    :param paths: list of relative paths to files or directories
    :param chroot: the root directory in which paths will be created

    >>> from os.path import isdir, isfile
    >>> isdir('/tmp/a')
    False
    >>> create_files(['a/b/foo.py', 'a/b/c/', 'a/b/c/d/e.py'], '/tmp')
    >>> isdir('/tmp/a')
    True
    >>> isdir('/tmp/a/b/c')
    True
    >>> isfile('/tmp/a/b/c/d/e.py')
    True
    >>> isfile('/tmp/a/b/foo.py')
    True
    rv�wN)rrjrJ�basename�addr��isdirr.�makedirsr�r�)�paths�chroot�dirsrcrdr��dirpath�filepathr)r)r*�create_filess




r�c@seZdZdd�ZdS)�
AttrObjectcKs|j�|�dS)N)r�r�)r_r$r)r)r*rWDszAttrObject.__init__N)r2r|r�rWr)r)r)r*r�Csr�cs��fdd�}|S)z#descriptor adding tag to a functioncst|d�rt�t���|_|S)Nr�)r�r�r�r�)r)r#r$r)r*�descIsztag.<locals>.descr))r#r$r�r))r#r$r*rBGsrBcs�fdd�}|S)zY Compare version of python interpreter to the given one. Skip the test
    if older.
    csz��d�}ytdd�|D��}Wn tk
r@td���YnXtjdd���|krr��fdd�}|j|_|S|SdS)Nr�cSsg|]}t|��qSr))rN)r?�vr)r)r*rCVszBrequire_version.<locals>.check_require_version.<locals>.<listcomp>z0%s is not a correct version : should be X.Y[.Z].r@cs&|�d�d�dd��D��f�dS)Nz:Need at least %s version of python. Current version is %s.r�cSsg|]}t|��qSr))r�)r?rr)r)r*rC\szQrequire_version.<locals>.check_require_version.<locals>.new_f.<locals>.<listcomp>)r}rJ)r_r#r$)�current�versionr)r*�new_f[sz=require_version.<locals>.check_require_version.<locals>.new_f)�splitr�rOrgrr2)�fZversion_elements�comparer�)r�)r�r*�check_require_versionSs
z.require_version.<locals>.check_require_versionr))r�r�r))r�r*�require_versionOsr�cs�fdd�}|S)z@ Check if the given module is loaded. Skip the test if not.
    cs:yt��|Stk
r4�fdd�}|j|_|SXdS)Ncs|�d��dS)Nz%s can not be imported.)r})r_r#r$)r�r)r*r�ksz;require_module.<locals>.check_require_module.<locals>.new_f)r�r+r2)r�r�)r�r)r*�check_require_modulefsz,require_module.<locals>.check_require_moduler))r�r�r))r�r*�require_modulecs	r�)_r��
__future__r�
__docformat__rgr.�os.pathrdrj�rer�ryrJrrnr��shutilr�operatorr�	itertoolsrrZsixrZ	six.movesrr	r
rZlogilab.common.deprecationrrZunittest_legacyrcZ	unittest2rr+r2�	functoolsrZlogilab.common.debuggerrrZlogilab.common.decoratorsrrZlogilab.commonr�__all__ZDEFAULT_PREFIXESZis_generatorZ
__unittestr-r1r3rrTZ_TextTestResultrU�objectr�r�Z	TestSuiter�r�r
r�r�r�rrr�r�r�rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rBr�r�r)r)r)r*�<module>&s�!%xL

%