'L idZddlmZddlmZddlmZddlmZddlm Z ddlm Z ddl m Z dd l m Z dd l m Z dd lZdd lmZdd lZdd lmZdd lZddlmZdd lZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl"m#Z#ddl$m%Z%ddl$m&Z&ddl$m'Z'ddl$m(Z(ddl$m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/dd l.m0Z0dd!l1m2Z2dd"l3m4Z4dd#l5m6Z6erejneZ8n ejnZ8d$Z9d%Z:ejvd&Z<e4d'Z=e4e>e?e@ej"fZAdEd(ZBGd)d*ejZDGd+d,eDZEGd-d.ejZGdFd/ZHdGd0ZIed1ej2ZKGd3d4eeKZLGd5d'e8ZMeGd6d7ZNe/dHd8ZOdId9ZPe(d:;dJd<ZQGd=d>ZRGd?d@ejZTGdAdBe8ZUGdCdDejZWy )Kz!Access and control log capturing.) annotations) Generator)Mapping)Set)contextmanager) nullcontext)datetime) timedelta)timezoneN)StringIO) LogRecord)Path) TracebackType)final)Generic)Literal) TYPE_CHECKING)TypeVar)nodes)TerminalWriter)CaptureManager) _strtobool)Config)create_terminal_writer)hookimpl) UsageError)Parser)check_ispytest)fixture)FixtureRequest)Session)StashKey)TerminalReporterz<%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)sz%H:%M:%Sz \x1b\[[\d;]+mLogCaptureHandlerc.tjd|S)N)_ANSI_ESCAPE_SEQsub)texts U/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/_pytest/logging.py_remove_ansi_escape_sequencesr+9s   D ))c&eZdZdZddfd ZxZS)DatetimeFormatterzA logging formatter which formats record with :func:`datetime.datetime.strftime` formatter instead of :func:`time.strftime` in case of microseconds in format string. c&|rd|vr{|j|j}tt|j|j }t |ddt|jdz|d}|j|St|-||S)Nz%f)secondsri) microsecondtzinfo) convertercreatedr r tm_gmtofftm_zoner intmsecsstrftimesuper formatTime)selfrecorddatefmtcttzdt __class__s r*r<zDatetimeFormatter.formatTimeCs} tw/B)BLL92::FB2a7FLL44G0HQSTB;;w' 'w!&'22r,N)r>r r? str | Nonereturnstr)__name__ __module__ __qualname____doc__r< __classcell__rCs@r*r.r.=s 3 3r,r.c,eZdZUdZej dhej ddhejdhejdhejdhejdheje iZ ded<ej d Zd fd Zdd Zdfd ZxZS)ColoredLevelFormatterzfA logging formatter which colorizes the %(levelname)..s part of the log format passed to __init__.redboldyellowgreenpurplezMapping[int, AbstractSet[str]]LOGLEVEL_COLOROPTSz$%\(levelname\)([+-.]?\d*(?:\.\d+)?s)ct||i|||_|jj|_i|_|jjD]\}}|j|g|yrD) r;__init___terminalwriter_style_fmt _original_fmt_level_to_fmt_mappingrUitemsadd_color_level)r=terminalwriterargskwargslevel color_optsrCs r*rWzColoredLevelFormatter.__init___so $)&)-![[--57"!%!8!8!>!>!@ 5 E: D  4 4 5r,c|jJ|jj|j}|sy|j}|dt j |iz}|Dcic]}|d}}|j j|fi|}|jj||j|j|<ycc}w)aAdd or update color opts for a log level. :param level: Log level to apply a style to, e.g. ``logging.INFO``. :param color_opts: ANSI escape sequence color options. Capitalized colors indicates background color, i.e. ``'green', 'Yellow', 'bold'`` will give bold green text on yellow background. .. warning:: This is an experimental API. N levelnameT) rZLEVELNAME_FMT_REGEXsearchgrouplogging getLevelNamerXmarkupr(r\) r=rbrclevelname_fmt_match levelname_fmtformatted_levelnamename color_kwargscolorized_formatted_levelnames r*r^z%ColoredLevelFormatter.add_color_levelhsyy$$$"66==diiH" +113 +{GfmtrCs r*ruzColoredLevelFormatter.formats@((,,V^^T=O=OP w~f%%r,)r_rrFNone)rbr8rcrGrFrwr>logging.LogRecordrFrG)rHrIrJrKriCRITICALERRORWARNINGWARNINFODEBUGNOTSETsetrU__annotations__recompilerfrWr^rurLrMs@r*rOrOPs& 5' v( xj wi z:6%"**%LM5 <&&r,rOc>eZdZdZdfd ZeddZddZxZS)PercentStyleMultilinezA logging style with special support for multiline messages. If the message of a record consists of multiple lines, this style formats the message as if each line were logged separately. cPt|||j||_yrD)r;rW_get_auto_indent _auto_indent)r=rv auto_indentrCs r*rWzPercentStyleMultiline.__init__s#  11+>r,c|yt|tr|ryyt|tr t|St|tr t|Sy#t$rYnwxYw t |ry y#t$rYywxYw)aDetermine the current auto indentation setting. Specify auto indent behavior (on/off/fixed) by passing in extra={"auto_indent": [value]} to the call to logging.log() or using a --log-auto-indent [value] command line or the log_auto_indent [value] config option. Default behavior is auto-indent off. Using the string "True" or "on" or the boolean True as the value turns auto indent on, using the string "False" or "off" or the boolean False or the int 0 turns it off, and specifying a positive integer fixes the indentation position to the value specified. Any other values for the option are invalid, and will silently be converted to the default. :param None|bool|int|str auto_indent_option: User specified option for indentation from command line, config or extra kwarg. Accepts int, bool or str. str option accepts the same range of values as boolean config options, as well as positive integers represented in str form. :returns: Indentation value, which can be -1 (automatically determine indentation) or 0 (auto-indent turned off) or >0 (explicitly set indentation position). r) isinstanceboolr8rG ValueErrorr)auto_indent_options r*rz&PercentStyleMultiline._get_auto_indents@  % *D 1! *C 0)* * *C 0 -..   012   s$ A AA A.. A:9A:cd|jvrt|dr|j|j}n |j}|r}|jj }|j i|jd|diz}|dkrt|j|d}n|}||d<dd|zzj|S|j |jzS)N rmessager ) rhasattrrrr splitlinesrZ__dict__r+findjoin)r=r>rlines formatted indentations r*ruzPercentStyleMultiline.formats 6>> !v}-"33F4F4FG "// 113 II(P6??(PIuQx(PP ?"? "J"O"Oa#K #.K$as[0066u==yy6??**r,)rvrGrint | str | bool | NonerFrw)rrrFr8rx) rHrIrJrKrW staticmethodrrurLrMs@r*rrs' ?33j+r,rcf|D],}|j|}||j|}|s*|cSyrD) getoptiongetini)confignamesrorets r*get_option_inirs<t$ ;--%C J r,cjdd4fd }|ddddd|d d td |d dtd jdddd|dddd |dddd |dddd |dddd |dd d!d!d"gd#$|d%d&dd' |d(d)dd |d*d+dd |d,d-dd. j d/d0gd1d23y)5z%Add options to control log capturing.riNc`j|||d|zj|fd|i|y)NzDefault value for defaulttypehelpdest)addini addoption)optionrrrrarhparsers r*add_option_iniz(pytest_addoption..add_option_inis= '3G&3P   4T4V4r,z --log-level log_levelLEVELzLevel of messages to catch/display. Not set by default, so it depends on the root/parent log handler's effective level, where it is "WARNING" by default.)rrmetavarrz --log-format log_formatz%Log format used by the logging module)rrrz--log-date-formatlog_date_formatz*Log date format used by the logging modulelog_cliFrzAEnable log display during test run (also known as "live logging")r--log-cli-level log_cli_levelzCLI logging levelz--log-cli-formatlog_cli_formatz--log-cli-date-formatlog_cli_date_formatz --log-filelog_filez.Path to a file when logging will be written toz--log-file-mode log_file_modewazLog file open mode)rrchoicesrz--log-file-levellog_file_levelzLog file logging levelz--log-file-formatlog_file_formatz--log-file-date-formatlog_file_date_formatz--log-auto-indentlog_auto_indentzfAuto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.z --log-disableappendlogger_disablez7Disable a logger by name. Can be passed multiple times.)actionrrr)NN)getgroupDEFAULT_LOG_FORMATDEFAULT_LOG_DATE_FORMATrr)rrrhs` @r*pytest_addoptionrsj OOI &E5   B  " 4   ' 9   MM  P  DW  4   " 9    =   c !   %    4   # 9    u   OO  F r, _HandlerType)boundc>eZdZdZdZdddZd dZ d dZy) catching_logszCContext manager that prepares the whole logging machinery properly.)handlerrb orig_levelNc ||_||_yrD)rrb)r=rrbs r*rWzcatching_logs.__init__[s  r,crtj}|j%|jj |j|j |j|j@|j|_|j t|j |j|jSrD)ri getLoggerrbrsetLevel addHandlerrmin)r= root_loggers r* __enter__zcatching_logs.__enter___s'') :: ! LL ! !$** -t||, :: !)//DO  T__djj!A B||r,ctj}|j|j|j|j |j yrD)rirrbrr removeHandlerr)r=exc_typeexc_valexc_tbrs r*__exit__zcatching_logs.__exit__is@ '') :: !   1!!$,,/r,rD)rrrb int | NonerFrw)rFr)rztype[BaseException] | NonerzBaseException | NonerzTracebackType | NonerFrw)rHrIrJrK __slots__rWrrr,r*rrVs?M2I 0, 0& 0% 0  0r,rcHeZdZdZdfd Zdfd ZddZddZddZxZ S) r$z;A logging handler that stores log records and the log text.cBt|tg|_y)zCreate a new log handler.N)r;rWr records)r=rCs r*rWzLogCaptureHandler.__init__xs $02 r,cZ|jj|t| |y)z;Keep the log records in a list in addition to the log text.N)rrr;emit)r=r>rCs r*rzLogCaptureHandler.emit}s! F#  Vr,c0g|_t|_yrD)rr streamr=s r*resetzLogCaptureHandler.resets j r,cV|jjt|_yrD)rclearr rrs r*rzLogCaptureHandler.clears j r,c&tjryrD)riraiseExceptionsr=r>s r* handleErrorzLogCaptureHandler.handleErrors  " "  #r,rFrwr>ryrFrw) rHrIrJrKrWrrrrrLrMs@r*r$r$usE3  !!r,ceZdZdZddddZddZeddZ ddZeddZ edd Z edd Z edd Z dd Z dd ZdddZedddZeddZy)LogCaptureFixturez-Provides access and control of log capturing.F _ispytestcRt|||_d|_i|_d|_yrD)r_item_initial_handler_level_initial_logger_levels_initial_disabled_logging_level)r=itemrs r*rWzLogCaptureFixture.__init__s)y! 26#=?#;?,r,c\|j%|jj|j|jj D]+\}}t j |}|j|-|j't j|jd|_yy)zFinalize the fixture. This restores the log levels and the disabled logging levels changed by :meth:`set_level`. N) rrrrr]rirrdisable)r= logger_namerbloggers r* _finalizezLogCaptureFixture._finalizes  & & 2 LL ! !$"="= >"&"="="C"C"E # K&&{3F OOE " #  / / ; OOD@@ A37D 0 B\\JALLN3JJJs.Ac\|jDcgc]}|jc}Scc}w)aA list of format-interpolated log messages. Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list are all interpolated. Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with levels, timestamps, etc, making exact comparisons more reliable. Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments to the logging functions) is not included, as this is added by the formatter in the handler. .. versionadded:: 3.7 )rrrs r*messageszLogCaptureFixture.messagess"")- 51 555s)c8|jjy)z8Reset the list of log records and the captured log text.N)rrrs r*rzLogCaptureFixture.clears r,cl|jj}t|trt j |}t|t s%t jtj|S|j|s2t|dz tj}t j||S)aPEnable the desired logging level if the global level was disabled via ``logging.disabled``. Only enables logging levels greater than or equal to the requested ``level``. Does nothing if the desired ``level`` wasn't disabled. :param level: The logger level caplog should capture. All logging is enabled if a non-standard logging level string is supplied. Valid level strings are in :data:`logging._nameToLevel`. :param logger_obj: The logger object to check. :return: The original disabled logging level. ) managerrrrGrirjr8r isEnabledFormax)r=rb logger_objoriginal_disable_level disable_levels r*_force_enable_loggingz'LogCaptureFixture._force_enable_loggings"'1&8&8&@&@ eS !((/E%% OOGNN +&% ((/  GNN;M OOM *%%r,Ncltj|}|jj||j|j ||j |jj|_|jj ||j||}|j||_ yy)aSet the threshold level of a logger for the duration of a test. Logging messages which are less severe than this level will not be captured. .. versionchanged:: 3.4 The levels of the loggers changed by this function will be restored to their initial values at the end of the test. Will enable the requested logging level if it was disabled via :func:`logging.disable`. :param level: The level. :param logger: The logger to update. If not given, the root logger. N) rirr setdefaultrbrrrrr)r=rbrrinitial_disabled_logging_levels r* set_levelzLogCaptureFixture.set_levels&&v.  ##..vz7G7GHE"  & & .*.,,*<*C@8 44 B8 B  BMM$$KK66$ & &,: &  &DR244. / /r,rc#bKt|jd}||jyw)aAccess and control log capturing. Captured logs are available through the following properties/methods:: * caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output string TrN)rnoder)requestresults r*caplogr4Ss)w||t y)zCreate a new plugin to capture log messages. The formatter can be safely shared across all handlers so create a single one for the entire test session here. rrrrrrrrUTF-8modeencodingrr)r?rterminalreporterNcapturemanagerrr)loggers_to_disable) _config_create_formatterr formatterr<rr$caplog_handler setFormatterreport_handlerrosdevnullpathdirnameabspathisdirmakedirsr _FileHandlerlog_file_handlerr.r_log_cli_enabledr? get_plugin_LiveLoggingStreamHandlerlog_cli_handler_LiveLoggingNullHandler_disable_loggersrr) r=rr directoryrrlog_file_formatterterminal_reportercapture_managerlog_cli_formatters r*rWzLoggingPlugin.__init__sq  // 6< 0 6#4 5 6#4 5  36;G/1 ((8/1 ((88 $k "&*5C rzz !(ABI77==+ I&+FODK , 4--! )1BLQ- *,= / %9  **+=>7 O[   " & 4 4 ? ?@R S $0 00$22==>NOO**;_M  $;#> , ,N  "t||'A'A'Ca'G*+DLL   ' 4//t7I7I J t44D''eS9' : : :$%++446<<>''eS9' : : : :sM"E"D8AD,C,;D,D8# E,=D))D,,D5 1D88E=Ec#K|jjdi}||jt<|j |d5ddddy#1swYyxYww)Nsetup)r^rrrr)r=remptys r*pytest_runtest_setupz"LoggingPlugin.pytest_runtest_setupDsU %%g.46). %&   tW -     sAAA AAAc#K|jjd|j|d5ddddy#1swYyxYww)Ncall)r^rrr=rs r*pytest_runtest_callz!LoggingPlugin.pytest_runtest_callMsA %%f-   tV ,     s.A > A AA c#,K|jjd |j|d5dddd|jt=|jt =y#1swY,xYw#|jt=|jt =wxYww)Nteardown)r^rrrrrrs r*pytest_runtest_teardownz%LoggingPlugin.pytest_runtest_teardownTs %%j1 /""44   -. -.    -. -.s1BA-A!A-#B!A*&A--$BBc:|jjdy)Nfinishrrs r*pytest_runtest_logfinishz&LoggingPlugin.pytest_runtest_logfinish_s %%h/r,c#8K|jjdt|j|j5t|j|j 5dcdddcdddS#1swYnxYw dddy#1swYyxYww)N sessionfinishrrrs r*pytest_sessionfinishz"LoggingPlugin.pytest_sessionfinishcs %%o6 4//t7I7I J t44D|j r2|jjd|j zddd|_t|-|dddy#1swYyxYw)NrT)rrz live log -)seprQ) rdglobal_and_fixture_disabledrrrwriterrrsectionr;r)r=r> ctx_managerrCs r*rz_LiveLoggingStreamHandler.emits##  < < >   !-- !!$'-1*551115D.KK%%d+++  ##K$**$<#D#Q+/( GL  ! ! !s CDD cyrDrrs r*rz%_LiveLoggingStreamHandler.handleErrorrr,)rcr#rdzCaptureManager | NonerFrwr)r rErFrwr) rHrIrJrKrrrWrrrrrLrMs@r*r]r]zsJ $F # ++ +/ +  ++/!& r,r]c(eZdZdZddZddZddZy) r_z5A logging handler used when live logging is disabled.cyrDrrs r*rz_LiveLoggingNullHandler.reset r,cyrDrrs r*rz _LiveLoggingNullHandler.set_whenrr,cyrDrrs r*rz#_LiveLoggingNullHandler.handleErrorrr,Nr)r rGrFrwr)rHrIrJrKrrrrr,r*r_r_s?   r,r_)r)rGrFrG)rrrrG)rrrFrw)r2r rFzGenerator[LogCaptureFixture])rrr9rGrFrr)XrK __future__rcollections.abcrrr AbstractSet contextlibrrr r r ior rir rRpathlibrrtypesrtypingrrrrr_pytestr _pytest._ior_pytest.capturer_pytest.configrrrrr_pytest.config.argparsingr_pytest.deprecatedr_pytest.fixturesrr _pytest.mainr! _pytest.stashr"_pytest.terminalr# StreamHandlerlogging_StreamHandlerrrrr'rdictrGlistrr+ Formatterr.rO PercentStylerrrHandlerrrr$rr4r<rBrA FileHandlerrYr] NullHandlerr_rr,r*rs'"%#.%"    &*%!1#%,-$+ "-#11(;#11S$2::./2X124AXd3W->->(?#?@AC*3))3&9&-9&xV+G00V+raH~W__= 0GL)0>-<|/|/|/~     0 $KKn&n&b 7&& 8 58 v  g11  r,