o
    bi\<                     @   s^   d dl mZ d dlZd dlZd dlZddlmZmZmZm	Z	m
Z
 ddlmZ G dd dZdS )    )contextmanagerN   )ParserElementParseExceptionKeyword__diag__
__compat__)core_builtin_exprsc                   @   s   e Zd ZdZG dd dZG dd dejZe						dd	dd
de	de
je de
je dede	de
je	 de
je	 de
je	ef dede	fddZdS )pyparsing_testzB
    namespace class for classes useful in writing unit tests
    c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )z&pyparsing_test.reset_pyparsing_contexta?  
        Context manager to be used when writing unit tests that modify pyparsing config values:
        - packrat parsing
        - bounded recursion parsing
        - default whitespace characters
        - default keyword characters
        - literal string auto-conversion class
        - ``__diag__`` settings

        Example:

        .. testcode::

            ppt = pyparsing.pyparsing_test

            class MyTestClass(ppt.TestParseResultsAsserts):
                def test_literal(self):
                    with ppt.reset_pyparsing_context():
                        # test that literals used to construct
                        # a grammar are automatically suppressed
                        ParserElement.inline_literals_using(Suppress)

                        term = Word(alphas) | Word(nums)
                        group = Group('(' + term[...] + ')')

                        # assert that the '()' characters
                        # are not included in the parsed tokens
                        self.assertParseAndCheckList(
                            group,
                            "(abc 123 def)",
                            ['abc', '123', 'def']
                        )

                    # after exiting context manager, literals
                    # are converted to Literal expressions again
        c                 C   s
   i | _ d S N)_save_contextself r   K/home/kim/smarthome/.venv/lib/python3.10/site-packages/pyparsing/testing.py__init__>   s   
z/pyparsing_test.reset_pyparsing_context.__init__c                 C   s   t j| jd< tj| jd< t j| jd< t j| jd< t j| jd< t jr)t jj	| jd< nd | jd< t j
| jd< t j| jd< d	d
 tjD | jd< dtji| jd< | S )Ndefault_whitespacedefault_keyword_charsliteral_string_classverbose_stacktracepackrat_enabledpackrat_cache_sizepackrat_parserecursion_enabledc                 S   s   i | ]}|t t|qS r   )getattrr   ).0namer   r   r   
<dictcomp>W   s    z?pyparsing_test.reset_pyparsing_context.save.<locals>.<dictcomp>r   collect_all_And_tokensr   )r   DEFAULT_WHITE_CHARSr   r   DEFAULT_KEYWORD_CHARSZ_literalStringClassr   _packratEnabledZpackrat_cachesize_parse_left_recursion_enabledr   Z
_all_namesr   r   r   r   r   r   saveA   s&   


z+pyparsing_test.reset_pyparsing_context.savec                 C   s   t j| jd krt | jd  | jd t _| jd t_t | jd  | jd  D ]\}}|r4t	j
nt	j| q+dt _| jd rKt | jd  n| jd	 t _| jd
 t _tD ]}|d qY| jd t_| S )Nr   r   r   r   r   Fr   r   r   r   r   )r   r   r   Zset_default_whitespace_charsr   r   r    Zinline_literals_usingitemsr   enabledisabler!   Zenable_packratr#   r$   r	   Z	set_debugr   r   )r   r   valueexprr   r   r   restorea   s0   
z.pyparsing_test.reset_pyparsing_context.restorec                 C   s   t |  }|j| j |S r   )typer   update)r   retr   r   r   copy   s   
z+pyparsing_test.reset_pyparsing_context.copyc                 C   s   |   S r   )r%   r   r   r   r   	__enter__   s   z0pyparsing_test.reset_pyparsing_context.__enter__c                 G   s   |    d S r   )r+   )r   argsr   r   r   __exit__   s   z/pyparsing_test.reset_pyparsing_context.__exit__N)
__name__
__module____qualname____doc__r   r%   r+   r/   r0   r2   r   r   r   r   reset_pyparsing_context   s    % %r7   c                   @   sT   e Zd ZdZ	dddZ	dddZ	ddd	Z	dd
dZee	ddfddZ
dS )z&pyparsing_test.TestParseResultsAssertszk
        A mixin class to add parse results assertion methods to normal unittest.TestCase classes.
        Nc                 C   s@   |dur| j || |d |dur| j || |d dS dS )z
            Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,
            and compare any defined results names with an optional ``expected_dict``.
            Nmsg)ZassertEqualas_listas_dict)r   resultexpected_listexpected_dictr9   r   r   r   assertParseResultsEquals   s
   z?pyparsing_test.TestParseResultsAsserts.assertParseResultsEqualsTc                 C   @   |j |dd}|rt|  nt|  | j|||d dS )z
            Convenience wrapper assert to test a parser element and input string, and assert that
            the resulting :meth:`ParseResults.as_list` is equal to the ``expected_list``.
            TZ	parse_all)r=   r9   Nparse_stringprintdumpr:   r?   )r   r*   test_stringr=   r9   verboser<   r   r   r   assertParseAndCheckList   
   z>pyparsing_test.TestParseResultsAsserts.assertParseAndCheckListc                 C   r@   )z
            Convenience wrapper assert to test a parser element and input string, and assert that
            the resulting :meth:`ParseResults.as_dict` is equal to the ``expected_dict``.
            TrA   )r>   r9   NrB   )r   r*   rF   r>   r9   rG   r<   r   r   r   assertParseAndCheckDict   rI   z>pyparsing_test.TestParseResultsAsserts.assertParseAndCheckDictc              	   C   s<  |\}}|du r| j ||dur|ndd dS dd t||D }|D ]k\}}}	tdd |	D d}
tdd |	D d}|dura| j||
pF|d	 t|trQ|W d   n1 s[w   Y  q#td
d |	D d}tdd |	D d}||fdkr| j||||
p|d q#td| q#| j ||dur|ndd dS )a2  
            Unit test assertion to evaluate output of
            :meth:`~ParserElement.run_tests`.

            If a list of list-dict tuples is given as the
            ``expected_parse_results`` argument, then these are zipped
            with the report tuples returned by ``run_tests()``
            and evaluated using :meth:`assertParseResultsEquals`.
            Finally, asserts that the overall
            `:meth:~ParserElement.run_tests` success value is ``True``.

            :param run_tests_report: the return value from :meth:`ParserElement.run_tests`
            :type run_tests_report: tuple[bool, list[tuple[str, ParseResults | Exception]]]
            :param expected_parse_results: (optional)
            :type expected_parse_results: list[tuple[str | list | dict | Exception, ...]]
            Nzfailed runTestsr8   c                 S   s   g | ]\}}g ||R qS r   r   )r   Zrptexpectedr   r   r   
<listcomp>   s    zOpyparsing_test.TestParseResultsAsserts.assertRunTestResults.<locals>.<listcomp>c                 s       | ]
}t |tr|V  qd S r   )
isinstancestrr   expr   r   r   	<genexpr>       zNpyparsing_test.TestParseResultsAsserts.assertRunTestResults.<locals>.<genexpr>c                 s   s(    | ]}t |trt|tr|V  qd S r   )rN   r,   
issubclass	ExceptionrP   r   r   r   rR      s    
)expected_exceptionr9   c                 s   rM   r   )rN   listrP   r   r   r   rR      rS   c                 s   rM   r   )rN   dictrP   r   r   r   rR      rS   NN)r=   r>   r9   zno validation for )Z
assertTruezipnextassertRaisesrN   rU   r?   rD   )r   Zrun_tests_reportZexpected_parse_resultsr9   Zrun_test_successZrun_test_resultsZmergedrF   r<   rK   Zfail_msgrV   r=   r>   r   r   r   assertRunTestResults   sV   

z;pyparsing_test.TestParseResultsAsserts.assertRunTestResultsc                 c   s    |d ur-t |trt|}| j|||d}|V  W d    d S 1 s&w   Y  d S | j||d}|V  W d    d S 1 sCw   Y  d S )Nr8   )rN   rO   reescapeassertRaisesRegexr\   )r   exc_typeZexpected_msgr9   ctxr   r   r   assertRaisesParseException  s   

""zApyparsing_test.TestParseResultsAsserts.assertRaisesParseException)NNN)NTrY   )r3   r4   r5   r6   r?   rH   rJ   r]   r   r   rc   r   r   r   r   TestParseResultsAsserts   s    



Ird   NT| )indentbase_1s
start_lineend_lineexpand_tabseol_markmark_spacesmark_controlrg   rh   returnc                   s  |r|   } ttrd   |durZtt|}|dkr=dd ttddtdd	D }	d
|	d< t|	}
d nt	|tfddt
tdddg D }
| |
} |durz|dkrz|dkrttddd}
| |
} n| d|} |du rd}|du rt|  }t|t|  }ttd||}|dkr|  t|| d| }ndd | dt|| d| D }|sdS tt|tdd |D } dd   }|dkr||rdnd ddd tt|d dD  d }nd}|rdnd| ddd t| d  D  d }d}||r"dnd || d    d }|| | d fd dt||| d!D  d S )"u^  
        Helpful method for debugging a parser - prints a string with line and column numbers.
        (Line and column numbers are 1-based by default - if debugging a parse action,
        pass base_1=False, to correspond to the loc value passed to the parse action.)

        :param s: string to be printed with line and column numbers
        :param start_line: starting line number in s to print (default=1)
        :param end_line: ending line number in s to print (default=len(s))
        :param expand_tabs: expand tabs to spaces, to match the pyparsing default
        :param eol_mark: string to mark the end of lines, helps visualize trailing spaces
        :param mark_spaces: special character to display in place of spaces
        :param mark_control: convert non-printing control characters to a placeholding
                             character; valid values:

                             - ``"unicode"`` - replaces control chars with Unicode symbols, such as "␍" and "␊"
                             - any single character string - replace control characters with given string
                             - ``None`` (default) - string is displayed as-is


        :param indent: string to indent with line and column numbers; if an int
                       is passed, converted to ``" " * indent``
        :param base_1: whether to label string using base 1; if False, string will be
                       labeled based at 0

        :returns: input string with leading line numbers and column number headers

        .. versionchanged:: 3.2.0
           New ``indent`` and ``base_1`` arguments.
         Nunicodec                 S   s   i | ]\}}||qS r   r   )r   cur   r   r   r   G  s    
z4pyparsing_test.with_line_numbers.<locals>.<dictcomp>r   !   i $  i3$  i!$     rf   c                    s   i | ]}| qS r   r   )r   rs   )ord_mark_controlr   r   r   P  s        i	$  i#$  )	   rx   c                 S   s   g | ]}|d  qS )   ␊r   r   liner   r   r   rL   c  s    z4pyparsing_test.with_line_numbers.<locals>.<listcomp>rz   c                 s   s    | ]}t |V  qd S r   )lenr{   r   r   r   rR   k  s    z3pyparsing_test.with_line_numbers.<locals>.<genexpr>r   c   c                 s   s$    | ]}d  |d d  V  qdS )zc                                                                                                   r   d   Nr   r   ir   r   r   rR   r  s
    
r   
c                 s   s"    | ]}d |d d  V  qdS )z	         r   
   Nr   r   r   r   r   rR   ~  s     r   Z
12345678900c                 3   s2    | ]\}} | d d|   V  qdS )d:Nr   )r   r   r|   )rm   rg   lineno_widthr   r   rR     s
    
)start)
expandtabsrN   inttypingcastrO   rZ   range	maketransordrW   	translatereplacer}   
splitlinesminmaxsplitjoin	enumerate)ri   rj   rk   rl   rm   rn   ro   rg   rh   Ztranstable_mapZtblZs_linesZmax_line_lenZleadZheader0Zheader1digitsZheader2r   )rm   rg   r   rw   r   with_line_numbers  s   *

 



$z pyparsing_test.with_line_numbers)NNTre   NN)r3   r4   r5   r6   r7   unittestZTestCaserd   staticmethodrO   r   Optionalr   boolUnionr   r   r   r   r   r
      sH    y 		
r
   )
contextlibr   r^   r   r   corer   r   r   r   r   rf   r	   r
   r   r   r   r   <module>   s   