
    g;1                        d 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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 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 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 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 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" ddlm#Z# ddlm$Z$ erd Z!d  Z% G d! d"e          Z&ej'        (                    d#$          ej'        )                    ed%&          ej'        )                    eoe d'&           G d( d)e&                                              Z*ej'        )                    ed*&           G d+ d,e*                      Z+ G d- d.e&          Z,dS )/a>	  Notes about unicode handling in psutil
======================================.

Starting from version 5.3.0 psutil adds unicode support, see:
https://github.com/giampaolo/psutil/issues/1040
The notes below apply to *any* API returning a string such as
process exe(), cwd() or username():

* all strings are encoded by using the OS filesystem encoding
  (sys.getfilesystemencoding()) which varies depending on the platform
  (e.g. "UTF-8" on macOS, "mbcs" on Win)
* no API call is supposed to crash with UnicodeDecodeError
* instead, in case of badly encoded data returned by the OS, the
  following error handlers are used to replace the corrupted characters in
  the string:
    * Python 3: sys.getfilesystemencodeerrors() (PY 3.6+) or
      "surrogatescape" on POSIX and "replace" on Windows
    * Python 2: "replace"
* on Python 2 all APIs return bytes (str type), never unicode
* on Python 2, you can go back to unicode by doing:

    >>> unicode(p.exe(), sys.getdefaultencoding(), errors="replace")

For a detailed explanation of how psutil handles unicode see #1040.

Tests
=====

List of APIs returning or dealing with a string:
('not tested' means they are not tested to deal with non-ASCII strings):

* Process.cmdline()
* Process.cwd()
* Process.environ()
* Process.exe()
* Process.memory_maps()
* Process.name()
* Process.net_connections('unix')
* Process.open_files()
* Process.username()             (not tested)

* disk_io_counters()             (not tested)
* disk_partitions()              (not tested)
* disk_usage(str)
* net_connections('unix')
* net_if_addrs()                 (not tested)
* net_if_stats()                 (not tested)
* net_io_counters()              (not tested)
* sensors_fans()                 (not tested)
* sensors_temperatures()         (not tested)
* users()                        (not tested)

* WindowsService.binpath()       (not tested)
* WindowsService.description()   (not tested)
* WindowsService.display_name()  (not tested)
* WindowsService.name()          (not tested)
* WindowsService.status()        (not tested)
* WindowsService.username()      (not tested)

In here we create a unicode path with a funky non-ASCII name and (where
possible) make psutil return it back (e.g. on name(), exe(), open_files(),
etc.) and make sure that:

* psutil never crashes with UnicodeDecodeError
* the returned path matches
    N)closing)BSD)POSIX)WINDOWS)PY3)super)APPVEYOR)ASCII_FS)
CI_TESTING)HAS_ENVIRON)HAS_MEMORY_MAPS)HAS_NET_CONNECTIONS_UNIX)INVALID_UNICODE_SUFFIX)PYPYTESTFN_PREFIX)UNICODE_SUFFIX)PsutilTestCase)bind_unix_socket)chdir)copyload_shared_lib)create_py_exe)
get_testfn)pytest)
safe_mkdirsafe_rmpath)skip_on_access_denied)spawn_testproc)	terminatec                 n    ddl m} 	  ||           S # t          $ r t          j                     Y d S w xY w)Nr   r   )psutil.testsr   WindowsError	traceback	print_exc)pathrms     U/var/www/html/ai-engine/env/lib/python3.11/site-packages/psutil/tests/test_unicode.pyr   r   q   s[     	322222	"2d88O 	" 	" 	"!!!!!!	"s   
 44c                    d}t          |           }	 t          |           t          |           t          |g          }t	          j        ||dz              t          |dz              	 |t          |           t          |           dS # t          t          f$ r$ Y |t          |           t          |           dS w xY w# |t          |           t          |           w xY w)z`Return True if both the fs and the subprocess module can
    deal with a unicode file name.
    Nsuffix)cmdz-2TF)	r   r   r   r   shutilcopyfiler    UnicodeEncodeErrorIOError)r+   sproctestfns      r(   try_unicoder3      s    Ev&&&FFfF8,,,...FTM""" eF (    eF
 eFs$   AB C!C CC "C*c                   <     e Zd ZdZe fd            Z fdZ xZS )BaseUnicodeTestNc                    t                                                       d| _        d | _        | j        Mt          | j                  s	d| _        d S t          | j                  | _        t          | j                   d S d S )NFTr*   )r   
setUpClass
skip_tests
funky_namefunky_suffixr3   r   r   )cls	__class__s    r(   r7   zBaseUnicodeTest.setUpClass   s    's/00 .!%!+33C!D!D!Dcn----- ('    c                 ~    t                                                       | j        rt          j        d          d S )Nzcan't handle unicode str)r   setUpr8   r   skip)selfr<   s    r(   r?   zBaseUnicodeTest.setUp   s9    ? 	:+8999	: 	:r=   )__name__
__module____qualname__r:   classmethodr7   r?   __classcell__)r<   s   @r(   r5   r5      s`        L	. 	. 	. 	. [	.: : : : : : : : :r=   r5   serial)namezASCII fsreasonztoo much trouble on PYPY2c                   \   e Zd ZdZeZd Zd Zd Zd Z	d Z
ej                            eoed          d	             Zej                            e d
          d             Zej                            e d
          ej                            e d           e            d                                     Zd Zej                            e d          ej                            e d          ej                            ed          d                                     ZdS )
TestFSAPIsz1Test FS APIs with a funky, valid, UTF8 path name.c                     t          | j        t                    rdnd}t          j                    5  t          j        d           | j        t          j        |          v cd d d            S # 1 swxY w Y   d S )N.ignore)
isinstancer9   strwarningscatch_warningssimplefilteroslistdir)rA   heres     r(   expect_exact_path_matchz"TestFSAPIs.expect_exact_path_match   s     !#66@ssD$&& 	7 	7!(+++?bj&6&66	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7s   /A..A25A2c                    | j         ddg}|                     |          }t          j        |j                  }|                                }t          |t                    sJ |                                 rGt          j
                            |          t          j
                            | j                   k    sJ d S d S Nz-cz2import time; [time.sleep(0.1) for x in range(100)])r9   r   psutilProcesspidexerP   rQ   rX   rU   r&   normcase)rA   r,   subppr^   s        r(   test_proc_exezTestFSAPIs.test_proc_exe   s    O@

 ""3''N48$$eegg#s#####'')) 	N7##C((BG,<,<T_,M,MMMMM	N 	NMMr=   c                 H   | j         ddg}|                     |          }t          j        |j                                                  }t          |t                    sJ |                                 r*|t          j
                            | j                   k    sJ d S d S rZ   )r9   r   r[   r\   r]   rH   rP   rQ   rX   rU   r&   basename)rA   r,   r`   rH   s       r(   test_proc_namezTestFSAPIs.test_proc_name   s    O@

 ""3''~dh'',,..$$$$$$'')) 	=27++DO<<<<<<	= 	=<<r=   c                    | j         ddg}|                     |          }t          j        |j                  }|                                }|D ]}t          |t                    sJ |                                 r||k    sJ d S d S rZ   )	r9   r   r[   r\   r]   cmdlinerP   rQ   rX   )rA   r,   r`   ra   rg   parts         r(   test_proc_cmdlinezTestFSAPIs.test_proc_cmdline   s    O@

 ""3''N48$$))++ 	) 	)DdC(((((('')) 	"c>>>>	" 	"!>r=   c                    | j         dz   }|                     t          |           t          |           t	          |          5  t          j                    }|                                }d d d            n# 1 swxY w Y   t          |                                t                    sJ | 
                                r||k    sJ d S d S N2)r9   
addCleanupr   r   r   r[   r\   cwdrP   rQ   rX   )rA   dnamera   rn   s       r(   test_proc_cwdzTestFSAPIs.test_proc_cwd   s    #%U+++55\\ 	 	  A%%''C	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 !%%''3''''''')) 	 %<<<<	  	 <s   (A88A<?A<zfails on PYPY + WINDOWSrI   c                 d   t          j                    }t          |                                          }t	          | j        d          5  t          |                                          }d d d            n# 1 swxY w Y   ||z
                                  j        }t          |t                    sJ t          r|st          j        d          |                                 rGt          j                            |          t          j                            | j                  k    sJ d S d S )Nrbzopen_files on BSD is broken)r[   r\   set
open_filesopenr9   popr&   rP   rQ   r   r   r@   rX   rU   r_   )rA   ra   startnewr&   s        r(   test_proc_open_fileszTestFSAPIs.test_proc_open_files   sH   NALLNN##$/4(( 	& 	&allnn%%C	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&e  ""'$$$$$$ 	=t 	=+;<<<'')) 	O7##D))RW-=-=do-N-NNNNN	O 	ONNs   
"A88A<?A<z
POSIX onlyc                    |                      | j                  }	 t          |          }n*# t          $ r t          r t          j        d          w xY wt          |          5  t          j	                    
                    d          d         }t          |j        t                    sJ |j        |k    sJ 	 d d d            d S # 1 swxY w Y   d S )Nr*   not supportedunixr   )r   r:   r   r/   r   r   r@   r   r[   r\   net_connectionsrP   laddrrQ   )rA   rH   sockconns       r(   test_proc_net_connectionsz$TestFSAPIs.test_proc_net_connections  s"   d&788	3#D))DD! 	3 	3 	3 3k/222		3
 T]] 	& 	&>##33F;;A>Ddj#.....:%%%%%	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&s   - 'A&AC

CCzcan't list UNIX socketsc                    d }|                      | j                  }	 t          |          }n*# t          $ r t          r t          j        d          w xY wt          |          5  t          j	        d          } ||          }t          |j        t                    sJ |j        |k    sJ 	 d d d            d S # 1 swxY w Y   d S )Nc                     | D ]B}t           j                            |j                                      t
                    r|c S Ct          d          )Nzconnection not found)rU   r&   rd   r~   
startswithr   
ValueError)consr   s     r(   	find_sockz2TestFSAPIs.test_net_connections.<locals>.find_sock  sV        7##DJ//::=II  KKK 3444r=   r*   r{   r|   )kind)r   r:   r   r/   r   r   r@   r   r[   r}   rP   r~   rQ   )rA   r   rH   r   r   r   s         r(   test_net_connectionszTestFSAPIs.test_net_connections  s3   	5 	5 	5 d&788	3#D))DD! 	3 	3 	3 3k/222		3
 T]] 	& 	&)v666D9T??Ddj#.....:%%%%%		& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&s   0 'A)A
CCCc                     | j         dz   }|                     t          |           t          |           t	          j        |           d S rk   )r9   rm   r   r   r[   
disk_usage)rA   ro   s     r(   test_disk_usagezTestFSAPIs.test_disk_usage/  sG    #%U+++5%     r=   r{   z&ctypes does not support unicode on PY2zunstable on PYPYc                 <   t          | j                  5 }d fdt          j                                                    D             }d |D             } |          |v sJ |D ]}t          |t                    sJ 	 d d d            d S # 1 swxY w Y   d S )Nr*   c                 z    t           j                            t           j                            |                     S )N)rU   r&   realpathr_   )ra   s    r(   normpathz-TestFSAPIs.test_memory_maps.<locals>.normpath?  s(    w''(8(8(;(;<<<r=   c                 0    g | ]} |j                   S  )r&   ).0xr   s     r(   
<listcomp>z/TestFSAPIs.test_memory_maps.<locals>.<listcomp>B  s2       %&    r=   c                 $    g | ]}t           |v |S r   r   )r   r   s     r(   r   z/TestFSAPIs.test_memory_maps.<locals>.<listcomp>F  s"    BBBa}/A/A/A/A/Ar=   )r   r:   r[   r\   memory_mapsrP   rQ   )rA   
funky_pathlibpathsr&   r   s       @r(   test_memory_mapszTestFSAPIs.test_memory_maps5  s#    !(9::: 	-j= = =   *0.*:*:*F*F*H*H  H CB8BBBH8J''83333  - -!$,,,,,,-	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-s   A,BBBN)rB   rC   rD   __doc__r   r:   rX   rb   re   ri   rp   r   markskipifr   r   ry   r   r   r   r   r   r   r   r   r   r   r=   r(   rL   rL      s        <;!L7 7 7N N N
= 
= 
=" " "	  	  	  [(1JKKO O LKO [E	,77& & 87& [E	,77[$$-F    & &   87
&*! ! ! [O+ODD[@    [%788- - 98  ED
- - -r=   rL   zunreliable on CIc                       e Zd ZdZeZd ZdS )TestFSAPIsWithInvalidPathz-Test FS APIs with a funky, invalid path name.c                     dS )NTr   )rA   s    r(   rX   z1TestFSAPIsWithInvalidPath.expect_exact_path_matchR  s    tr=   N)rB   rC   rD   r   r   r:   rX   r   r=   r(   r   r   L  s.        77)L    r=   r   c                       e Zd ZdZerendZej        	                    e
 d          ej        	                    eoed          d                         ZdS )TestNonFSAPISz&Unicode tests for non fs-related APIs.   èr{   rI   zsegfaults on PYPY + WINDOWSc                    t           j                                        }| j        |d<   |                     |          }t          j        |j                  }|                                }|                                D ]3\  }}t          |t                    sJ t          |t                    sJ 4|d         | j        k    sJ d S )N	FUNNY_ARG)env)rU   environcopyr:   r   r[   r\   r]   itemsrP   rQ   )rA   r   r1   ra   kvs         r(   test_proc_environzTestNonFSAPIS.test_proc_environa  s     joo,K###,,N59%%iikkIIKK 	& 	&DAqa%%%%%a%%%%%%;4#4444444r=   N)rB   rC   rD   r   r   r   r:   r   r   r   r   r   r   r   r   r=   r(   r   r   \  s        00%(2>>dL[K@@[(1NOO5 5 PO A@5 5 5r=   r   )-r   rU   r-   r$   rR   
contextlibr   r[   r   r   r   psutil._compatr   r   r"   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r3   r5   r   xdist_groupr   rL   r   r   r   r=   r(   <module>r      s  A AF 
			                                                  ! ! ! ! ! ! ! ! ! ! ! ! # # # # # # $ $ $ $ $ $ ( ( ( ( ( ( 1 1 1 1 1 1 / / / / / /       & & & & & & ' ' ' ' ' ' ' ' ' ' ' ' ) ) ) ) ) )       , , , , , , & & & & & & # # # # # #       # # # # # # $ $ $ $ $ $ . . . . . . ' ' ' ' ' ' " " " " " "  "" " "&  6: : : : :n : : :* h''HZ00D$W-HIIR- R- R- R- R- R- R- JI 10 ('R-j J'9::    
   ;:5 5 5 5 5O 5 5 5 5 5r=   