
    Mh                     $   d Z ddlZddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlmZ ddlmZmZ ddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlm Z m!Z! ddl"m#Z# ddl$Z$ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. e$j/        r#e%e+e(e0                  e+e0         e+e.         f         Z1eZ2	 d.de3de4de%e
j
        e5f         fdZ6de7fdZ8 G d dej9                  Z: G d de:          Z; G d de;          Z<e$j=        ddde+e7         de'e'de*ed f         f         ge'd!         f         fd"            Z>e$j=        d#e'de*ed f         f         de'd!         fd$            Z>	 	 d/d#e+e'de*ed f         f                  de+e7         de*e'd!         e'e'de*ed f         f         ge'd!         f         f         fd%Z>de>_?         G d& d'ej@                  ZAd(ej9        d)e&de&fd*ZBd+e&ddfd,ZCeDd-k    r eC             dS dS )0a  Support classes for automated testing.

* `AsyncTestCase` and `AsyncHTTPTestCase`:  Subclasses of unittest.TestCase
  with additional support for testing asynchronous (`.IOLoop`-based) code.

* `ExpectLog`: Make test logs less spammy.

* `main()`: A simple test runner (wrapper around unittest.main()) with support
  for the tornado.autoreload module to rerun the tests when code changes.
    N)	Generator)gen)AsyncHTTPClientHTTPResponse)
HTTPServer)IOLoopTimeoutError)netutil)AsyncIOMainLoop)
Subprocess)app_log)raise_exc_infobasestring_type)Application)TupleAnyCallableTypeDictUnionOptional	Coroutine)TracebackTypeF	127.0.0.1
reuse_portaddressreturnc                     t          j        d|t          j        |           d         }|                                d         }||fS )aI  Binds a server socket to an available port on localhost.

    Returns a tuple (socket, port).

    .. versionchanged:: 4.4
       Always binds to ``127.0.0.1`` without resolving the name
       ``localhost``.

    .. versionchanged:: 6.2
       Added optional ``address`` argument to
       override the default "127.0.0.1".
    r   )familyr      )r
   bind_socketssocketAF_INETgetsockname)r   r   sockports       O/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/tornado/testing.pybind_unused_portr(   1   sP     	76>j  	D a D:    c                      t           j                            d          } |  	 t          |           S # t          $ r Y nw xY wdS )z}Get the global timeout setting for async tests.

    Returns a float, the timeout in seconds.

    .. versionadded:: 3.1
    ASYNC_TEST_TIMEOUTN   )osenvirongetfloat
ValueError)envs    r'   get_async_test_timeoutr3   G   sS     *..-
.
.C
	:: 	 	 	D	1s   2 
??c                   *    e Zd ZdZddeddf fdZd fdZd fdZdefd	Z	d
e
e         dededefdZddZ	 ddeej                 deej                 f fdZdeddfdZddededdfdZ	 	 ddeedef                  dee         defdZ xZS )AsyncTestCasea/  `~unittest.TestCase` subclass for testing `.IOLoop`-based
    asynchronous code.

    The unittest framework is synchronous, so the test must be
    complete by the time the test method returns. This means that
    asynchronous code cannot be used in quite the same way as usual
    and must be adapted to fit. To write your tests with coroutines,
    decorate your test methods with `tornado.testing.gen_test` instead
    of `tornado.gen.coroutine`.

    This class also provides the (deprecated) `stop()` and `wait()`
    methods for a more manual style of testing. The test method itself
    must call ``self.wait()``, and asynchronous callbacks should call
    ``self.stop()`` to signal completion.

    By default, a new `.IOLoop` is constructed for each test and is available
    as ``self.io_loop``.  If the code being tested requires a
    reused global `.IOLoop`, subclasses should override `get_new_ioloop` to return it,
    although this is deprecated as of Tornado 6.3.

    The `.IOLoop`'s ``start`` and ``stop`` methods should not be
    called directly.  Instead, use `self.stop <stop>` and `self.wait
    <wait>`.  Arguments passed to ``self.stop`` are returned from
    ``self.wait``.  It is possible to have multiple ``wait``/``stop``
    cycles in the same test.

    Example::

        # This test uses coroutine style.
        class MyTestCase(AsyncTestCase):
            @tornado.testing.gen_test
            def test_http_fetch(self):
                client = AsyncHTTPClient()
                response = yield client.fetch("http://www.tornadoweb.org")
                # Test contents of response
                self.assertIn("FriendFeed", response.body)

        # This test uses argument passing between self.stop and self.wait.
        class MyTestCase2(AsyncTestCase):
            def test_http_fetch(self):
                client = AsyncHTTPClient()
                client.fetch("http://www.tornadoweb.org/", self.stop)
                response = self.wait()
                # Test contents of response
                self.assertIn("FriendFeed", response.body)
    runTest
methodNamer   Nc                     t                                          |           d| _        d| _        d | _        d | _        d | _        d | _        d S )NF)super__init___AsyncTestCase__stopped_AsyncTestCase__running_AsyncTestCase__failure_AsyncTestCase__stop_args_AsyncTestCase__timeout_test_generator)selfr7   	__class__s     r'   r:   zAsyncTestCase.__init__   sO    $$$  $r)   c                    t           j        }d|cxk    rdk     sn d|cxk    rdk    rAn n>t          | t          j                               t          j        ddt          d           t                                                       t          |           j
        t          j
        urt          j        d	t                     | 
                                | _        t          j        | j        j                   d S )
N)   
   r   )rD   rE   	   )rD      r   )rD   rG   r    ignorezThere is no current event loopztornado\..*)messagecategorymodulezget_new_ioloop is deprecated)sysversion_infosetup_with_context_managerwarningscatch_warningsfilterwarningsDeprecationWarningr9   setUptypeget_new_ioloopr5   warnio_loopasyncioset_event_loopasyncio_loop)rA   py_verrB   s     r'   rS   zAsyncTestCase.setUp   s    !&----:----:3U3U3U3U:3U3U3U3U3U 'tX-D-F-FGGG#8+%	    	::$M,HHHM8:LMMM**,,t|899999r)   c                 ^   | j         j        }t          j        |          d D             D ]}|                                 rS| j                             fd          \  }}|rJ |D ],}	 |                                 # t          j        $ r Y )w xY wt          j	                     t          j
        d            t          | j         t                    s| j                             d           t                                                       |                                  d S )Nc                 :    g | ]}|                                 |S  )done).0ts     r'   
<listcomp>z*AsyncTestCase.tearDown.<locals>.<listcomp>   s%    222q2222r)   c                  ,    t          j                   S N)rX   wait)taskss   r'   <lambda>z(AsyncTestCase.tearDown.<locals>.<lambda>   s    ',u:M:M r)   T)all_fds)rW   rZ   rX   	all_taskscancelrun_syncresultCancelledErrorr   uninitializerY   
isinstance_NON_OWNED_IOLOOPScloser9   tearDown_AsyncTestCase__rethrow)rA   rZ   ra   r_   pendingfrf   rB   s         @r'   rr   zAsyncTestCase.tearDown   sR   
 |0!,// 32E222 	 	AHHJJJJ  	 L112M2M2M2MNNMD'  HHJJJJ-   D 	!!!t$$$$,(:;; 	-
 Lt,,,
 	s   3BBBc                 "    t          d          S )a  Returns the `.IOLoop` to use for this test.

        By default, a new `.IOLoop` is created for each test.
        Subclasses may override this method to return
        `.IOLoop.current()` if it is not appropriate to use a new
        `.IOLoop` in each tests (for example, if there are global
        singletons using the default `.IOLoop`) or if a per-test event
        loop is being provided by another system (such as
        ``pytest-asyncio``).

        .. deprecated:: 6.3
           This method will be removed in Tornado 7.0.
        F)make_current)r   rA   s    r'   rU   zAsyncTestCase.get_new_ioloop   s     5))))r)   typvaluetbc                     | j         |||f| _         nt          j        d|||f           |                                  dS )Nz%multiple unhandled exceptions in test)exc_infoT)r=   r   errorstoprA   ry   rz   r{   s       r'   _handle_exceptionzAsyncTestCase._handle_exception   sU     >!!5"-DNNM73rBR    			tr)   c                 R    | j         | j         }d | _         t          |           d S d S rd   )r=   r   )rA   failures     r'   	__rethrowzAsyncTestCase.__rethrow   s4    >%nG!DN7##### &%r)   rl   c                 r    t                                          |          }|                                  |S rd   )r9   runrs   )rA   rl   retrB   s      r'   r   zAsyncTestCase.run   s1     ggkk&!!
 	
r)   methodc                      |            }t          |t                    st          j        |          rt	          d          |t          d|z            dS )ax  Run the given test method, raising an error if it returns non-None.

        Failure to decorate asynchronous test methods with ``@gen_test`` can lead to tests
        incorrectly passing.

        Remove this override when Python 3.10 support is dropped. This check (in the form of a
        DeprecationWarning) became a part of the standard library in 3.11.

        Note that ``_callTestMethod`` is not documented as a public interface. However, it is
        present in all supported versions of Python (3.8+), and if it goes away in the future that's
        OK because we can just remove this override as noted above.
        zVGenerator and coroutine test methods should be decorated with tornado.testing.gen_testNz)Return value from test method ignored: %r)ro   r   inspectiscoroutine	TypeErrorr1   )rA   r   rl   s      r'   _callTestMethodzAsyncTestCase._callTestMethod   sp     fi(( 	SG,?,G,G 	S;   H6QRRR  r)   _argkwargsc                     ||rJ |p|| _         | j        r | j                                         d| _        d| _        dS )aI  Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
        to return.

        Keyword arguments or a single positional argument passed to `stop()` are
        saved and will be returned by `wait()`.

        .. deprecated:: 5.1

           `stop` and `wait` are deprecated; use ``@gen_test`` instead.
        NFT)r>   r<   rW   r   r;   )rA   r   r   s      r'   r   zAsyncTestCase.stop  sM     |6|||!>T> 	#L"DNr)   	condition.timeoutc                     t                       j        srAd fd} j                             j                                        z   |           _        	 d _         j                                          j        |
 |            rn5 j        & j        	                     j                   d _         j        sJ d _         
                                  j        }d _        |S )a  Runs the `.IOLoop` until stop is called or timeout has passed.

        In the event of a timeout, an exception will be thrown. The
        default timeout is 5 seconds; it may be overridden with a
        ``timeout`` keyword argument or globally with the
        ``ASYNC_TEST_TIMEOUT`` environment variable.

        If ``condition`` is not ``None``, the `.IOLoop` will be restarted
        after `stop()` until ``condition()`` returns ``True``.

        .. versionchanged:: 3.1
           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.

        .. deprecated:: 5.1

           `stop` and `wait` are deprecated; use ``@gen_test`` instead.
        Nr   c                      	                       dz            # t          $ r t          j                     _        Y nw xY w                                  d S )Nz*Async operation timed out after %s seconds)failureException	ExceptionrL   r}   r=   r   )rA   r   s   r'   timeout_funcz(AsyncTestCase.wait.<locals>.timeout_funcC  sg    8"33H7R   % 8 8 8),8IIKKKKKs    "A A TFr   N)r3   r;   rW   add_timeouttimer?   r<   startr=   remove_timeoutrs   r>   )rA   r   r   r   rl   s   ` `  r'   re   zAsyncTestCase.wait'  s!   , ?,..G~ 	&               "&!9!9L%%'''1<" "!%""$$$>-1Biikk1B	
 ~)++DN;;;!%~!r)   )r6   r   rd   NN)__name__
__module____qualname____doc__strr:   rS   rr   r   rU   r   r   r   boolr   rs   r   unittest
TestResultr   r   r   r   r   r0   re   __classcell__rB   s   @r'   r5   r5   W   s       - -^	$ 	$3 	$t 	$ 	$ 	$ 	$ 	$ 	$: : : : : :$* * * * * *X* * * * * 
	?
+4
:G
	
 
 
 
$ $ $ $ 7;	 	x23		(%	&	 	 	 	 	 	Sh S4 S S S S0  s t    ( 48#'5 5HS$Y/05 %5 
	5 5 5 5 5 5 5 5r)   r5   c            	            e Zd ZdZd fdZdefdZdefdZde	fdZ
	 dd	ed
ededefdZdeeef         fdZdefdZdefdZd	edefdZd fdZ xZS )AsyncHTTPTestCasear  A test case that starts up an HTTP server.

    Subclasses must override `get_app()`, which returns the
    `tornado.web.Application` (or other `.HTTPServer` callback) to be tested.
    Tests will typically use the provided ``self.http_client`` to fetch
    URLs from this server.

    Example, assuming the "Hello, world" example from the user guide is in
    ``hello.py``::

        import hello

        class TestHelloApp(AsyncHTTPTestCase):
            def get_app(self):
                return hello.make_app()

            def test_homepage(self):
                response = self.fetch('/')
                self.assertEqual(response.code, 200)
                self.assertEqual(response.body, 'Hello, world')

    That call to ``self.fetch()`` is equivalent to ::

        self.http_client.fetch(self.get_url('/'), self.stop)
        response = self.wait()

    which illustrates how AsyncTestCase can turn an asynchronous operation,
    like ``http_client.fetch()``, into a synchronous operation. If you need
    to do other asynchronous operations in tests, you'll probably need to use
    ``stop()`` and ``wait()`` yourself.
    r   Nc                 D   t                                                       t                      \  }}|| _        |                                 | _        |                                 | _        |                                 | _	        | j	        
                    |g           d S rd   )r9   rS   r(   _AsyncHTTPTestCase__portget_http_clienthttp_clientget_app_appget_http_serverhttp_serveradd_sockets)rA   r%   r&   rB   s      r'   rS   zAsyncHTTPTestCase.setUp  s    %''
d//11LLNN	//11$$dV,,,,,r)   c                     t                      S rd   )r   rx   s    r'   r   z!AsyncHTTPTestCase.get_http_client  s       r)   c                 J    t          | j        fi |                                 S rd   )r   r   get_httpserver_optionsrx   s    r'   r   z!AsyncHTTPTestCase.get_http_server  s&    $)EEt'B'B'D'DEEEr)   c                     t                      )zzShould be overridden by subclasses to return a
        `tornado.web.Application` or other `.HTTPServer` callback.
        )NotImplementedErrorrx   s    r'   r   zAsyncHTTPTestCase.get_app  s     "###r)   Fpathraise_errorr   c                      |                                                     d          r|n                     |           j                             fdt                                S )aE  Convenience method to synchronously fetch a URL.

        The given path will be appended to the local server's host and
        port.  Any additional keyword arguments will be passed directly to
        `.AsyncHTTPClient.fetch` (and so could be used to pass
        ``method="POST"``, ``body="..."``, etc).

        If the path begins with http:// or https://, it will be treated as a
        full URL and will be fetched as-is.

        If ``raise_error`` is ``True``, a `tornado.httpclient.HTTPError` will
        be raised if the response code is not 200. This is the same behavior
        as the ``raise_error`` argument to `.AsyncHTTPClient.fetch`, but
        the default is ``False`` here (it's ``True`` in `.AsyncHTTPClient`)
        because tests often need to deal with non-200 response codes.

        .. versionchanged:: 5.0
           Added support for absolute URLs.

        .. versionchanged:: 5.1

           Added the ``raise_error`` argument.

        .. deprecated:: 5.1

           This method currently turns any exception into an
           `.HTTPResponse` with status code 599. In Tornado 6.0,
           errors other than `tornado.httpclient.HTTPError` will be
           passed through, and ``raise_error=False`` will only
           suppress errors that would be raised due to non-200
           response codes.

        )zhttp://zhttps://c                  .     j         j        fdi S )Nr   )r   fetch)r   r   rA   urls   r'   rg   z)AsyncHTTPTestCase.fetch.<locals>.<lambda>  s%    *D$*3RRKR6RR r)   r   )lower
startswithget_urlrW   rk   r3   )rA   r   r   r   r   s   ` ``@r'   r   zAsyncHTTPTestCase.fetch  s}    H ::<<""#:;; 	%CC,,t$$C|$$RRRRRRR*,, % 
 
 	
r)   c                     i S )zgMay be overridden by subclasses to return additional
        keyword arguments for the server.
        r^   rx   s    r'   r   z(AsyncHTTPTestCase.get_httpserver_options  s	     	r)   c                     | j         S )zZReturns the port used by the server.

        A new port is chosen for each test.
        )r   rx   s    r'   get_http_portzAsyncHTTPTestCase.get_http_port  s    
 {r)   c                     dS )Nhttpr^   rx   s    r'   get_protocolzAsyncHTTPTestCase.get_protocol  s    vr)   c                 \    |                                   d|                                  | S )z>Returns an absolute url for the given path on the test server.z://127.0.0.1:)r   r   )rA   r   s     r'   r   zAsyncHTTPTestCase.get_url  s3    ##%%PPD4F4F4H4HP$PPPr)   c                    | j                                          | j                            | j         j        t                                 | j                                         | ` | `t                      
                                 d S )Nr   )r   r   rW   rk   close_all_connectionsr3   r   rq   r   r9   rr   )rA   rB   s    r'   rr   zAsyncHTTPTestCase.tearDown  s    2<R<T<T 	 	
 	
 	
 	   Ir)   r   )F)r   r   r   r   rS   r   r   r   r   r   r   r   r   r   r   r   r   r   intr   r   r   rr   r   r   s   @r'   r   r   _  s|        @- - - - - -! ! ! ! !F F F F F$ $ $ $ $ .3+
 +
+
&*+
>A+
	+
 +
 +
 +
ZS#X    s    c    QC QC Q Q Q Q         r)   r   c                       e Zd ZdZdefdZdeeef         fdZ	deeef         fdZ
edeeef         fd            ZdefdZdS )	AsyncHTTPSTestCasezjA test case that starts an HTTPS server.

    Interface is generally the same as `AsyncHTTPTestCase`.
    r   c                 @    t          dt          d                    S )NTF)validate_cert)force_instancedefaults)r   dictrx   s    r'   r   z"AsyncHTTPSTestCase.get_http_client  s!    dTPU=V=V=VWWWWr)   c                 F    t          |                                           S )N)ssl_options)r   get_ssl_optionsrx   s    r'   r   z)AsyncHTTPSTestCase.get_httpserver_options  s     4 4 6 67777r)   c                 4    t                                           S )zMay be overridden by subclasses to select SSL options.

        By default includes a self-signed testing certificate.
        )r   default_ssl_optionsrx   s    r'   r   z"AsyncHTTPSTestCase.get_ssl_options  s    
 "55777r)   c                      t           j                            t                    } t	          t           j                            | dd          t           j                            | dd                    S )Ntestztest.crtztest.key)certfilekeyfile)r-   r   dirname__file__r   join)
module_dirs    r'   r   z&AsyncHTTPSTestCase.default_ssl_options  sX     W__X..
W\\*fjAAGLLVZ@@
 
 
 	
r)   c                     dS )Nhttpsr^   rx   s    r'   r   zAsyncHTTPSTestCase.get_protocol  s    wr)   N)r   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   r^   r)   r'   r   r     s         
X X X X X8S#X 8 8 8 88c3h 8 8 8 8 

c3h 

 

 

 \

c      r)   r   r   r   .r   .Nc                     d S rd   r^   r   s    r'   gen_testr     s	     	Dr)   funcc                     d S rd   r^   )r   s    r'   r   r     s    Dr)   c                     t                      dt          dt          t          df         f         dt          d         ffd}|  ||           S |S )a1  Testing equivalent of ``@gen.coroutine``, to be applied to test methods.

    ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not
    already running.  ``@gen_test`` should be applied to test methods
    on subclasses of `AsyncTestCase`.

    Example::

        class MyTest(AsyncHTTPTestCase):
            @gen_test
            def test_something(self):
                response = yield self.http_client.fetch(self.get_url('/'))

    By default, ``@gen_test`` times out after 5 seconds. The timeout may be
    overridden globally with the ``ASYNC_TEST_TIMEOUT`` environment variable,
    or for each test with the ``timeout`` keyword argument::

        class MyTest(AsyncHTTPTestCase):
            @gen_test(timeout=10)
            def test_something_slow(self):
                response = yield self.http_client.fetch(self.get_url('/'))

    Note that ``@gen_test`` is incompatible with `AsyncTestCase.stop`,
    `AsyncTestCase.wait`, and `AsyncHTTPTestCase.fetch`. Use ``yield
    self.http_client.fetch(self.get_url())`` as shown above instead.

    .. versionadded:: 3.1
       The ``timeout`` argument and ``ASYNC_TEST_TIMEOUT`` environment
       variable.

    .. versionchanged:: 4.0
       The wrapper now passes along ``*args, **kwargs`` so it can be used
       on functions with arguments.

    Nru   .r   r   r   c                      t          j                    fd            }t          j                   r|nt	          j        |          t          j                  fd            }|S )Nc                      | g|R i |}t          |t                    st          j        |          r|| _        nd | _        |S rd   )ro   r   r   r   r@   )rA   argsr   rl   ru   s       r'   pre_coroutinez-gen_test.<locals>.wrap.<locals>.pre_coroutineH  s`     Qt-d---f--F&),, ,0CF0K0K ,'-$$'+$Mr)   c                     	 | j                             t          j        | g|R i |          S # t          $ r=}| j        0t          | j        dd          r| j                            |            d }~ww xY w)Nr   
cr_runningT)rW   rk   	functoolspartialr	   r@   getattrthrow)rA   r   r   ecoror   s       r'   post_coroutinez.gen_test.<locals>.wrap.<locals>.post_coroutineX  s    |,,%dDB4BBB6BBG -         '3(,9 93 (..q111
 s   /3 
A:8A55A:)r   wrapsr   iscoroutinefunctionr   	coroutine)ru   r   r   r   r   s   `  @r'   wrapzgen_test.<locals>.wrap?  s     
			 	 	 	 
		 &q)) 	0 DD=//D				 	 	 	 	 
		. r)   )r3   r   r   r   )r   r   r   s    ` r'   r   r     s{    T (**1eI{$:;;< 1)AT 1 1 1 1 1 1f 
 tDzz r)   c                       e Zd ZdZ	 	 ddeej        ef         dede	de
e         ddf
d	Zd
ej        de	fdZddZddde
e         de
e         ddfdZdS )	ExpectLoga  Context manager to capture and suppress expected log output.

    Useful to make tests of error conditions less noisy, while still
    leaving unexpected log entries visible.  *Not thread safe.*

    The attribute ``logged_stack`` is set to ``True`` if any exception
    stack trace was logged.

    Usage::

        with ExpectLog('tornado.application', "Uncaught exception"):
            error_response = self.fetch("/some_page")

    .. versionchanged:: 4.3
       Added the ``logged_stack`` attribute.
    TNloggerregexrequiredlevelr   c                     t          |t                    rt          j        |          }|| _        t          j        |          | _        || _        d| _	        d| _
        d| _        || _        d| _        dS )a  Constructs an ExpectLog context manager.

        :param logger: Logger object (or name of logger) to watch.  Pass an
            empty string to watch the root logger.
        :param regex: Regular expression to match.  Any log entries on the
            specified logger that match this regex will be suppressed.
        :param required: If true, an exception will be raised if the end of the
            ``with`` statement is reached without matching any log entries.
        :param level: A constant from the ``logging`` module indicating the
            expected log level. If this parameter is provided, only log messages
            at this level will be considered to match. Additionally, the
            supplied ``logger`` will have its level adjusted if necessary (for
            the duration of the ``ExpectLog`` to enable the expected message.

        .. versionchanged:: 6.1
           Added the ``level`` parameter.

        .. deprecated:: 6.3
           In Tornado 7.0, only ``WARNING`` and higher logging levels will be
           matched by default. To match ``INFO`` and lower levels, the ``level``
           argument must be used. This is changing to minimize differences
           between ``tornado.testing.main`` (which enables ``INFO`` logs by
           default) and most other test runners (including those in IDEs)
           which have ``INFO`` logs disabled by default.
        r   FN)ro   r   logging	getLoggerr   recompiler   r   matcheddeprecated_level_matchedlogged_stackr   
orig_level)rA   r   r   r   r   s        r'   r:   zExpectLog.__init__  so    @ fo.. 	/&v..FZ&&
 ()%!
r)   recordc           	         |j         rd| _        |                                }| j                            |          r| j        %|j        t          j        k     r| xj	        dz  c_	        | j        L|j        | j        k    r<t          j        d|dt          j        | j                  d|j        d           dS | xj        dz  c_        dS dS )NTr    zGot expected log message z at unexpected level (z vs )F)r}   r  
getMessager   matchr   levelnor  WARNINGr  r   warninggetLevelName	levelnamer  )rA   r	  rI   s      r'   filterzExpectLog.filter  s    ? 	% $D##%%:G$$ 	z!fnw&F&F --2--z%&.DJ*F*Fww 4TZ @ @ @ @&BRBRBRT   tLLALL5tr)   c                     | j         R| j         | j                                        k     r0| j        j         | _        | j                            | j                    | j                            |            | S rd   )r   r   getEffectiveLevelr  setLevel	addFilterrx   s    r'   	__enter__zExpectLog.__enter__  sc    :!dj4;3P3P3R3R&R&R"k/DOK  ,,,d###r)   ry   zOptional[Type[BaseException]]rz   r{   c                 6   | j         | j                            | j                    | j                            |            |s| j        r| j        st          d          |s3| j        r.| j        | j        k    r t          j	        dt                     d S d S d S d S )Nz did not get expected log messagez9ExpectLog matched at INFO or below without level argument)r  r   r  removeFilterr   r  r   r  rO   rV   rR   r   s       r'   __exit__zExpectLog.__exit__  s     ?&K  111  &&& 	@t} 	@T\ 	@>???		 .$,>>MK"    	 	 	 	 ?>r)   )TN)r   r   )r   r   r   r   r   r  Loggerr   r   r   r   r   r:   	LogRecordr  r  BaseExceptionr   r  r^   r)   r'   r   r     s         * #* *gno56* * 	*
 }* 
* * * *XW. 4    ,   , & ]#	
 
     r)   r   testcasecmc                 h    |                                 }|                     |j        ddd           |S )a[  Use a context manager to setUp a test case.

    Example::

        def setUp(self):
            setup_with_context_manager(self, warnings.catch_warnings())
            warnings.filterwarnings("ignore", category=DeprecationWarning)
            # The catch_warnings context manager will be deactivated
            # automatically in tearDown.

    N)r  
addCleanupr  )r  r   vals      r'   rN   rN     s2     ,,..CT4666Jr)   r   c                  4   ddl m}m}m}  |dt          dd            |dt                      |d	t                      |d
t                      |dt                      |dt                     t
          j        d         g |t
          j                  z   }|j        s)t          j        t          j	        t          j
                   |j        d| d<   |j        d| d<   |j        d| d
<   |j        d| d<   |j        d| d<   t           dk    rBt#          |          dk    r/t%          dt
          j                   t          j        d           t#          |          dk    rt+          j        dd|d|  dS t+          j        dd|d|  dS )a  A simple test runner.

    This test runner is essentially equivalent to `unittest.main` from
    the standard library, but adds support for Tornado-style option
    parsing and log formatting. It is *not* necessary to use this
    `main` function to run tests using `AsyncTestCase`; these tests
    are self-contained and can run with any test runner.

    The easiest way to run a test is via the command line::

        python -m tornado.testing tornado.test.web_test

    See the standard library ``unittest`` module for ways in which
    tests can be specified.

    Projects with many tests may wish to define a test script like
    ``tornado/test/runtests.py``.  This script should define a method
    ``all()`` which returns a test suite and then call
    `tornado.testing.main()`.  Note that even when a test script is
    used, the ``all()`` test suite may be overridden by naming a
    single test on the command line::

        # Runs all tests
        python -m tornado.test.runtests
        # Runs one test
        python -m tornado.test.runtests tornado.test.web_test

    Additional keyword arguments passed through to ``unittest.main()``.
    For example, use ``tornado.testing.main(verbosity=2)``
    to show many test details as they are run.
    See http://docs.python.org/library/unittest.html#unittest.main
    for full argument list.

    .. versionchanged:: 5.0

       This function produces no output of its own; only that produced
       by the `unittest` module (previously it would add a PASS or FAIL
       log message).
    r   )defineoptionsparse_command_lineexception_on_interruptTzIf true (default), ctrl-c raises a KeyboardInterrupt exception.  This prints a stack trace but cannot interrupt certain operations.  If false, the process is more reliably killed, but does not print a stack trace.)rT   defaulthelpverbose)rT   quietfailfastcatchbufferN   	verbosity
catchbreak__main__r    zNo tests specified)file)rK   argvall)defaultTestr5  r^   )tornado.optionsr%  r&  r'  r   rL   r5  r(  signalSIGINTSIG_DFLr+  r,  r-  r.  r/  r   lenprintstderrexitr   main)r   r%  r&  r'  r5  s        r'   r@  r@    s   P DCCCCCCCCC
F 8
 
 
 
 F94    
F7
F:D!!!!
F7
F8$HQK=--ch777D) 5fmV^444"{} {#!z} #|~!x:#d))q.."4444 4yy1}}7T7777777=%d==f=====r)   r3  )Fr   r   )Er   rX   collections.abcr   r   r   r  r-   r  r9  r"   rL   r   rO   tornador   tornado.httpclientr   r   tornado.httpserverr   tornado.ioloopr   r	   r
   tornado.platform.asyncior   tornado.processr   tornado.logr   tornado.utilr   r   tornado.webr   typingr   r   r   r   r   r   r   r   typesr   TYPE_CHECKINGr  _ExcInfoTuplerp   r   r   r   r(   r0   r3   TestCaser5   r   r   overloadr   __test__Filterr   rN   r@  r   r^   r)   r'   <module>rS     s  	 	  % % % % % %       				 				   



         < < < < < < < < ) ) ) ) ) ) / / / / / / / /       4 4 4 4 4 4 & & & & & &       8 8 8 8 8 8 8 8 # # # # # #  O O O O O O O O O O O O O O O O O O O O      	 m$%x'>@WWM
 %  .9 '*
6=#   ,     E E E E EH% E E EP@ @ @ @ @ @ @ @F! ! ! ! !* ! ! !H "&	 	 		xU9k#9::;<hy>QQR	 	 	 	 	8Cy+'=!>>? 	HYDW 	 	 	 	
 DH#h h
8Cy+'=!>>?
@he_h YhsE)["899:;Xi=PPQSh h h hZ  n n n n n n n nd):      "Y>3 Y>4 Y> Y> Y> Y>x zDFFFFF r)   