applied-ai-018 commited on
Commit
35c2f47
·
verified ·
1 Parent(s): 6db9ec4

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step40/zero/15.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step40/zero/15.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step40/zero/15.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step40/zero/19.input_layernorm.weight/exp_avg.pt +3 -0
  5. venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/INSTALLER +1 -0
  6. venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/License.txt +154 -0
  7. venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/METADATA +36 -0
  8. venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/RECORD +39 -0
  9. venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/WHEEL +5 -0
  10. venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/top_level.txt +1 -0
  11. venv/lib/python3.10/site-packages/psutil/tests/__init__.py +2043 -0
  12. venv/lib/python3.10/site-packages/psutil/tests/__main__.py +12 -0
  13. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/__main__.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/runner.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_aix.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_bsd.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_connections.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_contracts.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_linux.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_memleaks.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_misc.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_osx.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_posix.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_process.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_process_all.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_sunos.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_system.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_testutils.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_unicode.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_windows.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/psutil/tests/runner.py +385 -0
  33. venv/lib/python3.10/site-packages/psutil/tests/test_connections.py +576 -0
  34. venv/lib/python3.10/site-packages/psutil/tests/test_contracts.py +349 -0
  35. venv/lib/python3.10/site-packages/psutil/tests/test_linux.py +2350 -0
  36. venv/lib/python3.10/site-packages/psutil/tests/test_memleaks.py +496 -0
  37. venv/lib/python3.10/site-packages/psutil/tests/test_misc.py +1014 -0
  38. venv/lib/python3.10/site-packages/psutil/tests/test_osx.py +210 -0
  39. venv/lib/python3.10/site-packages/psutil/tests/test_process.py +1636 -0
  40. venv/lib/python3.10/site-packages/psutil/tests/test_process_all.py +464 -0
  41. venv/lib/python3.10/site-packages/psutil/tests/test_sunos.py +45 -0
  42. venv/lib/python3.10/site-packages/psutil/tests/test_system.py +967 -0
  43. venv/lib/python3.10/site-packages/psutil/tests/test_testutils.py +453 -0
  44. venv/lib/python3.10/site-packages/psutil/tests/test_unicode.py +365 -0
  45. venv/lib/python3.10/site-packages/psutil/tests/test_windows.py +967 -0
  46. venv/lib/python3.10/site-packages/rouge_score/__init__.py +15 -0
  47. venv/lib/python3.10/site-packages/rouge_score/__pycache__/__init__.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/rouge_score/__pycache__/create_pyrouge_files.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/rouge_score/__pycache__/io.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/rouge_score/__pycache__/io_test.cpython-310.pyc +0 -0
ckpts/universal/global_step40/zero/15.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3d5058354eda46e385890d076df06604a2d4a42e1be597e5ba620617dd41b62
3
+ size 33555612
ckpts/universal/global_step40/zero/15.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:103ab82d90c70dacc6343ee31f5ad4072264cac023117fa1e17e32bd67cb2c30
3
+ size 33555627
ckpts/universal/global_step40/zero/15.mlp.dense_h_to_4h_swiglu.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61d74b76d6bd6939bd7a6a2192b8fa989a3523dea812c9b9ce33bde1ddb51f0b
3
+ size 33555533
ckpts/universal/global_step40/zero/19.input_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:611dc2c411224a41201e4b5e94406191d6c2bd1aee83573814f89896a4b020c6
3
+ size 9372
venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/License.txt ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE AGREEMENT FOR NVIDIA SOFTWARE DEVELOPMENT KITS
2
+
3
+ This license agreement, including exhibits attached ("Agreement”) is a legal agreement between you and NVIDIA Corporation ("NVIDIA") and governs your use of a NVIDIA software development kit (“SDK”).
4
+
5
+ Each SDK has its own set of software and materials, but here is a description of the types of items that may be included in a SDK: source code, header files, APIs, data sets and assets (examples include images, textures, models, scenes, videos, native API input/output files), binary software, sample code, libraries, utility programs, programming code and documentation.
6
+
7
+ This Agreement can be accepted only by an adult of legal age of majority in the country in which the SDK is used.
8
+
9
+ If you are entering into this Agreement on behalf of a company or other legal entity, you represent that you have the legal authority to bind the entity to this Agreement, in which case “you” will mean the entity you represent.
10
+
11
+ If you don’t have the required age or authority to accept this Agreement, or if you don’t accept all the terms and conditions of this Agreement, do not download, install or use the SDK.
12
+
13
+ You agree to use the SDK only for purposes that are permitted by (a) this Agreement, and (b) any applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions.
14
+
15
+ 1. License.
16
+
17
+ 1.1 Grant
18
+
19
+ Subject to the terms of this Agreement, NVIDIA hereby grants you a non-exclusive, non-transferable license, without the right to sublicense (except as expressly provided in this Agreement) to:
20
+
21
+ (i) Install and use the SDK,
22
+
23
+ (ii) Modify and create derivative works of sample source code delivered in the SDK, and
24
+
25
+ (iii) Distribute those portions of the SDK that are identified in this Agreement as distributable, as incorporated in object code format into a software application that meets the distribution requirements indicated in this Agreement.
26
+
27
+ 1.2 Distribution Requirements
28
+
29
+ These are the distribution requirements for you to exercise the distribution grant:
30
+
31
+ (i) Your application must have material additional functionality, beyond the included portions of the SDK.
32
+
33
+ (ii) The distributable portions of the SDK shall only be accessed by your application.
34
+
35
+ (iii) The following notice shall be included in modifications and derivative works of sample source code distributed: “This software contains source code provided by NVIDIA Corporation.”
36
+
37
+ (iv) Unless a developer tool is identified in this Agreement as distributable, it is delivered for your internal use only.
38
+
39
+ (v) The terms under which you distribute your application must be consistent with the terms of this Agreement, including (without limitation) terms relating to the license grant and license restrictions and protection of NVIDIA’s intellectual property rights. Additionally, you agree that you will protect the privacy, security and legal rights of your application users.
40
+
41
+ (vi) You agree to notify NVIDIA in writing of any known or suspected distribution or use of the SDK not in compliance with the requirements of this Agreement, and to enforce the terms of your agreements with respect to distributed SDK.
42
+
43
+ 1.3 Authorized Users
44
+
45
+ You may allow employees and contractors of your entity or of your subsidiary(ies) to access and use the SDK from your secure network to perform work on your behalf.
46
+
47
+ If you are an academic institution you may allow users enrolled or employed by the academic institution to access and use the SDK from your secure network.
48
+
49
+ You are responsible for the compliance with the terms of this Agreement by your authorized users. If you become aware that your authorized users didn’t follow the terms of this Agreement, you agree to take reasonable steps to resolve the non-compliance and prevent new occurrences.
50
+
51
+ 1.4 Pre-Release SDK
52
+ The SDK versions identified as alpha, beta, preview or otherwise as pre-release, may not be fully functional, may contain errors or design flaws, and may have reduced or different security, privacy, accessibility, availability, and reliability standards relative to commercial versions of NVIDIA software and materials. Use of a pre-release SDK may result in unexpected results, loss of data, project delays or other unpredictable damage or loss.
53
+ You may use a pre-release SDK at your own risk, understanding that pre-release SDKs are not intended for use in production or business-critical systems.
54
+ NVIDIA may choose not to make available a commercial version of any pre-release SDK. NVIDIA may also choose to abandon development and terminate the availability of a pre-release SDK at any time without liability.
55
+ 1.5 Updates
56
+
57
+ NVIDIA may, at its option, make available patches, workarounds or other updates to this SDK. Unless the updates are provided with their separate governing terms, they are deemed part of the SDK licensed to you as provided in this Agreement.
58
+
59
+ You agree that the form and content of the SDK that NVIDIA provides may change without prior notice to you. While NVIDIA generally maintains compatibility between versions, NVIDIA may in some cases make changes that introduce incompatibilities in future versions of the SDK.
60
+
61
+ 1.6 Third Party Licenses
62
+
63
+ The SDK may come bundled with, or otherwise include or be distributed with, third party software licensed by a NVIDIA supplier and/or open source software provided under an open source license. Use of third party software is subject to the third-party license terms, or in the absence of third party terms, the terms of this Agreement. Copyright to third party software is held by the copyright holders indicated in the third-party software or license.
64
+
65
+ 1.7 Reservation of Rights
66
+
67
+ NVIDIA reserves all rights, title and interest in and to the SDK not expressly granted to you under this Agreement.
68
+
69
+ 2. Limitations.
70
+
71
+ The following license limitations apply to your use of the SDK:
72
+
73
+ 2.1 You may not reverse engineer, decompile or disassemble, or remove copyright or other proprietary notices from any portion of the SDK or copies of the SDK.
74
+
75
+ 2.2 Except as expressly provided in this Agreement, you may not copy, sell, rent, sublicense, transfer, distribute, modify, or create derivative works of any portion of the SDK.
76
+
77
+ 2.3 Unless you have an agreement with NVIDIA for this purpose, you may not indicate that an application created with the SDK is sponsored or endorsed by NVIDIA.
78
+
79
+ 2.4 You may not bypass, disable, or circumvent any encryption, security, digital rights management or authentication mechanism in the SDK.
80
+
81
+ 2.5 You may not use the SDK in any manner that would cause it to become subject to an open source software license. As examples, licenses that require as a condition of use, modification, and/or distribution that the SDK be (i) disclosed or distributed in source code form; (ii) licensed for the purpose of making derivative works; or (iii) redistributable at no charge.
82
+
83
+ 2.6 Unless you have an agreement with NVIDIA for this purpose, you may not use the SDK with any system or application where the use or failure of the system or application can reasonably be expected to threaten or result in personal injury, death, or catastrophic loss. Examples include use in avionics, navigation, military, medical, life support or other life critical applications. NVIDIA does not design, test or manufacture the SDK for these critical uses and NVIDIA shall not be liable to you or any third party, in whole or in part, for any claims or damages arising from such uses.
84
+
85
+ 2.7 You agree to defend, indemnify and hold harmless NVIDIA and its affiliates, and their respective employees, contractors, agents, officers and directors, from and against any and all claims, damages, obligations, losses, liabilities, costs or debt, fines, restitutions and expenses (including but not limited to attorney’s fees and costs incident to establishing the right of indemnification) arising out of or related to your use of the SDK outside of the scope of this Agreement, or not in compliance with its terms.
86
+
87
+ 3. Ownership.
88
+
89
+ 3.1 NVIDIA or its licensors hold all rights, title and interest in and to the SDK and its modifications and derivative works, including their respective intellectual property rights, subject to your rights under Section 3.2. This SDK may include software and materials from NVIDIA’s licensors, and these licensors are intended third party beneficiaries that may enforce this Agreement with respect to their intellectual property rights.
90
+
91
+ 3.2 You hold all rights, title and interest in and to your applications and your derivative works of the sample source code delivered in the SDK, including their respective intellectual property rights, subject to NVIDIA’s rights under section 3.1.
92
+
93
+ 3.3 You may, but don’t have to, provide to NVIDIA suggestions, feature requests or other feedback regarding the SDK, including possible enhancements or modifications to the SDK. For any feedback that you voluntarily provide, you hereby grant NVIDIA and its affiliates a perpetual, non-exclusive, worldwide, irrevocable license to use, reproduce, modify, license, sublicense (through multiple tiers of sublicensees), and distribute (through multiple tiers of distributors) it without the payment of any royalties or fees to you. NVIDIA will use feedback at its choice. NVIDIA is constantly looking for ways to improve its products, so you may send feedback to NVIDIA through the developer portal at https://developer.nvidia.com.
94
+
95
+ 4. No Warranties.
96
+
97
+ THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF DEALING OR COURSE OF TRADE.
98
+
99
+ 5. Limitations of Liability.
100
+
101
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS LIMIT.
102
+
103
+ These exclusions and limitations of liability shall apply regardless if NVIDIA or its affiliates have been advised of the possibility of such damages, and regardless of whether a remedy fails its essential purpose. These exclusions and limitations of liability form an essential basis of the bargain between the parties, and, absent any of these exclusions or limitations of liability, the provisions of this Agreement, including, without limitation, the economic terms, would be substantially different.
104
+
105
+ 6. Termination.
106
+
107
+ 6.1 This Agreement will continue to apply until terminated by either you or NVIDIA as described below.
108
+
109
+ 6.2 If you want to terminate this Agreement, you may do so by stopping to use the SDK.
110
+
111
+ 6.3 NVIDIA may, at any time, terminate this Agreement if: (i) you fail to comply with any term of this Agreement and the non-compliance is not fixed within thirty (30) days following notice from NVIDIA (or immediately if you violate NVIDIA’s intellectual property rights); (ii) you commence or participate in any legal proceeding against NVIDIA with respect to the SDK; or (iii) NVIDIA decides to no longer provide the SDK in a country or, in NVIDIA’s sole discretion, the continued use of it is no longer commercially viable.
112
+
113
+ 6.4 Upon any termination of this Agreement, you agree to promptly discontinue use of the SDK and destroy all copies in your possession or control. Your prior distributions in accordance with this Agreement are not affected by the termination of this Agreement. Upon written request, you will certify in writing that you have complied with your commitments under this section. Upon any termination of this Agreement all provisions survive except for the licenses granted to you.
114
+
115
+ 7. General.
116
+
117
+ If you wish to assign this Agreement or your rights and obligations, including by merger, consolidation, dissolution or operation of law, contact NVIDIA to ask for permission. Any attempted assignment not approved by NVIDIA in writing shall be void and of no effect. NVIDIA may assign, delegate or transfer this Agreement and its rights and obligations, and if to a non-affiliate you will be notified.
118
+
119
+ You agree to cooperate with NVIDIA and provide reasonably requested information to verify your compliance with this Agreement.
120
+
121
+ This Agreement will be governed in all respects by the laws of the United States and of the State of Delaware as those laws are applied to contracts entered into and performed entirely within Delaware by Delaware residents, without regard to the conflicts of laws principles. The United Nations Convention on Contracts for the International Sale of Goods is specifically disclaimed. You agree to all terms of this Agreement in the English language.
122
+
123
+ The state or federal courts residing in Santa Clara County, California shall have exclusive jurisdiction over any dispute or claim arising out of this Agreement. Notwithstanding this, you agree that NVIDIA shall still be allowed to apply for injunctive remedies or an equivalent type of urgent legal relief in any jurisdiction.
124
+
125
+ If any court of competent jurisdiction determines that any provision of this Agreement is illegal, invalid or unenforceable, such provision will be construed as limited to the extent necessary to be consistent with and fully enforceable under the law and the remaining provisions will remain in full force and effect. Unless otherwise specified, remedies are cumulative.
126
+
127
+ Each party acknowledges and agrees that the other is an independent contractor in the performance of this Agreement.
128
+
129
+ The SDK has been developed entirely at private expense and is “commercial items” consisting of “commercial computer software” and “commercial computer software documentation” provided with RESTRICTED RIGHTS. Use, duplication or disclosure by the U.S. Government or a U.S. Government subcontractor is subject to the restrictions in this Agreement pursuant to DFARS 227.7202-3(a) or as set forth in subparagraphs (b)(1) and (2) of the Commercial Computer Software - Restricted Rights clause at FAR 52.227-19, as applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas Expressway, Santa Clara, CA 95051.
130
+
131
+ The SDK is subject to United States export laws and regulations. You agree that you will not ship, transfer or export the SDK into any country, or use the SDK in any manner, prohibited by the United States Bureau of Industry and Security or economic sanctions regulations administered by the U.S. Department of Treasury’s Office of Foreign Assets Control (OFAC), or any applicable export laws, restrictions or regulations. These laws include restrictions on destinations, end users and end use. By accepting this Agreement, you confirm that you are not a resident or citizen of any country currently embargoed by the U.S. and that you are not otherwise prohibited from receiving the SDK.
132
+
133
+ Any notice delivered by NVIDIA to you under this Agreement will be delivered via mail, email or fax. You agree that any notices that NVIDIA sends you electronically will satisfy any legal communication requirements. Please direct your legal notices or other correspondence to NVIDIA Corporation, 2788 San Tomas Expressway, Santa Clara, California 95051, United States of America, Attention: Legal Department.
134
+
135
+ This Agreement and any exhibits incorporated into this Agreement constitute the entire agreement of the parties with respect to the subject matter of this Agreement and supersede all prior negotiations or documentation exchanged between the parties relating to this SDK license. Any additional and/or conflicting terms on documents issued by you are null, void, and invalid. Any amendment or waiver under this Agreement shall be in writing and signed by representatives of both parties.
136
+
137
+ (v. January 28, 2020)
138
+
139
+
140
+ cuDNN SUPPLEMENT TO SOFTWARE LICENSE AGREEMENT FOR NVIDIA SOFTWARE DEVELOPMENT KITS
141
+
142
+ The terms in this supplement govern your use of the NVIDIA cuDNN SDK under the terms of your license agreement (“Agreement”) as modified by this supplement. Capitalized terms used but not defined below have the meaning assigned to them in the Agreement.
143
+
144
+ This supplement is an exhibit to the Agreement and is incorporated as an integral part of the Agreement. In the event of conflict between the terms in this supplement and the terms in the Agreement, the terms in this supplement govern.
145
+
146
+ 4.1 License Scope. The SDK is licensed for you to develop applications only for use in systems with NVIDIA GPUs.
147
+
148
+ 2. Distribution. The following portions of the SDK are distributable under the Agreement: the runtime files .so and .h, cudnn64_7.dll, and cudnn.lib.
149
+
150
+ In addition to the rights above, for parties that are developing software intended solely for use on Jetson development kits or Jetson modules and running Linux for Tegra software the following shall apply: the SDK may be distributed in its entirety, as provided by NVIDIA and without separation of its components, for you and/or your licensees to create software development kits for use only on the Jetson platform and running Linux for Tegra software.
151
+
152
+ 3. Licensing. If the distribution terms in this Agreement are not suitable for your organization, or for any questions regarding this Agreement, please contact NVIDIA at [email protected].
153
+ (v. January 28, 2020)
154
+
venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/METADATA ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: nvidia-cudnn-cu12
3
+ Version: 8.9.2.26
4
+ Summary: cuDNN runtime libraries
5
+ Home-page: https://developer.nvidia.com/cuda-zone
6
+ Author: Nvidia CUDA Installer Team
7
+ Author-email: [email protected]
8
+ License: NVIDIA Proprietary Software
9
+ Keywords: cuda,nvidia,runtime,machine learning,deep learning
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: Other/Proprietary License
15
+ Classifier: Natural Language :: English
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.5
18
+ Classifier: Programming Language :: Python :: 3.6
19
+ Classifier: Programming Language :: Python :: 3.7
20
+ Classifier: Programming Language :: Python :: 3.8
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3 :: Only
25
+ Classifier: Topic :: Scientific/Engineering
26
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
27
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
28
+ Classifier: Topic :: Software Development
29
+ Classifier: Topic :: Software Development :: Libraries
30
+ Classifier: Operating System :: Microsoft :: Windows
31
+ Classifier: Operating System :: POSIX :: Linux
32
+ Requires-Python: >=3
33
+ License-File: License.txt
34
+ Requires-Dist: nvidia-cublas-cu12
35
+
36
+ cuDNN runtime libraries containing primitives for deep neural networks.
venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/RECORD ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ nvidia/__pycache__/__init__.cpython-310.pyc,,
3
+ nvidia/cudnn/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ nvidia/cudnn/__pycache__/__init__.cpython-310.pyc,,
5
+ nvidia/cudnn/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ nvidia/cudnn/include/__pycache__/__init__.cpython-310.pyc,,
7
+ nvidia/cudnn/include/cudnn.h,sha256=tq-l2UFypIfK4cMhF38556O6nfSRRFPRmChaXFTtCXY,2968
8
+ nvidia/cudnn/include/cudnn_adv_infer.h,sha256=bQkFH6xmvorYhPutqYf43_nHKMNNfc7EmUSa3LjtuHU,29027
9
+ nvidia/cudnn/include/cudnn_adv_infer_v8.h,sha256=bQkFH6xmvorYhPutqYf43_nHKMNNfc7EmUSa3LjtuHU,29027
10
+ nvidia/cudnn/include/cudnn_adv_train.h,sha256=ckG1OvQWW2CHiVIWBkt52XpvWHuW2V7RjTc-jRzcqxw,27700
11
+ nvidia/cudnn/include/cudnn_adv_train_v8.h,sha256=ckG1OvQWW2CHiVIWBkt52XpvWHuW2V7RjTc-jRzcqxw,27700
12
+ nvidia/cudnn/include/cudnn_backend.h,sha256=boGGTGpV4u8iYOQNEoNOZZhO0yZtJg4PxtQfiszkZy4,25332
13
+ nvidia/cudnn/include/cudnn_backend_v8.h,sha256=boGGTGpV4u8iYOQNEoNOZZhO0yZtJg4PxtQfiszkZy4,25332
14
+ nvidia/cudnn/include/cudnn_cnn_infer.h,sha256=rff5rMGK9i7Kqh974MrT14FBXIK06yxtd0eMTdDDyxs,29083
15
+ nvidia/cudnn/include/cudnn_cnn_infer_v8.h,sha256=rff5rMGK9i7Kqh974MrT14FBXIK06yxtd0eMTdDDyxs,29083
16
+ nvidia/cudnn/include/cudnn_cnn_train.h,sha256=6Ofk5encwLyqofNRookwneGIOvTzVouFOIFT9E5GNz4,10217
17
+ nvidia/cudnn/include/cudnn_cnn_train_v8.h,sha256=6Ofk5encwLyqofNRookwneGIOvTzVouFOIFT9E5GNz4,10217
18
+ nvidia/cudnn/include/cudnn_ops_infer.h,sha256=YhgGSMuwmPVE6Bn_5BauDmg73-5CQLgBXGnRP24R9SE,49631
19
+ nvidia/cudnn/include/cudnn_ops_infer_v8.h,sha256=YhgGSMuwmPVE6Bn_5BauDmg73-5CQLgBXGnRP24R9SE,49631
20
+ nvidia/cudnn/include/cudnn_ops_train.h,sha256=fp2ghY0c73LAqBfEjWu-TcFMIwm9WfedreRBKP8qOjw,25733
21
+ nvidia/cudnn/include/cudnn_ops_train_v8.h,sha256=fp2ghY0c73LAqBfEjWu-TcFMIwm9WfedreRBKP8qOjw,25733
22
+ nvidia/cudnn/include/cudnn_v8.h,sha256=tq-l2UFypIfK4cMhF38556O6nfSRRFPRmChaXFTtCXY,2968
23
+ nvidia/cudnn/include/cudnn_version.h,sha256=Q8IGmDi7U0HcXT9ch56ZIEtqYGoQaUgRfE9IPeAXKHk,4019
24
+ nvidia/cudnn/include/cudnn_version_v8.h,sha256=Q8IGmDi7U0HcXT9ch56ZIEtqYGoQaUgRfE9IPeAXKHk,4019
25
+ nvidia/cudnn/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
+ nvidia/cudnn/lib/__pycache__/__init__.cpython-310.pyc,,
27
+ nvidia/cudnn/lib/libcudnn.so.8,sha256=zoqo90nmnP9egwWElfxVldHmqmP_JvJ_dFUhtuM07M4,150200
28
+ nvidia/cudnn/lib/libcudnn_adv_infer.so.8,sha256=UMAvlhd106yiZ2NpFWQ12WS1YVcZ-LRLSc1z7cISF_M,125141304
29
+ nvidia/cudnn/lib/libcudnn_adv_train.so.8,sha256=LIGAoSMreb2YIPPTvucq5dMNrd1G2zCSKnb6E6x-b98,116248176
30
+ nvidia/cudnn/lib/libcudnn_cnn_infer.so.8,sha256=fbihfSwhpvRoTZmgc8p5HGYA27v8Ree3hq2OQtDPEYs,647553136
31
+ nvidia/cudnn/lib/libcudnn_cnn_train.so.8,sha256=wHaPPuMZ4hfpYbqhtAhKfVKQDwiBwDZMNxMIux9YoiY,132457288
32
+ nvidia/cudnn/lib/libcudnn_ops_infer.so.8,sha256=5SC-cNarIuWsVlBJvbexWCSDcDtkHEQKfCHpLhJxXq4,90621456
33
+ nvidia/cudnn/lib/libcudnn_ops_train.so.8,sha256=yJ2chx0PHRs9EDcjSmbrsJ-ZDj1TJMUCXUWDXX2C1GI,70922856
34
+ nvidia_cudnn_cu12-8.9.2.26.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
35
+ nvidia_cudnn_cu12-8.9.2.26.dist-info/License.txt,sha256=Sc95vbNXNLUv5iAwE7O9dZ-B6ZjNMqosZcUduaiMYdI,18174
36
+ nvidia_cudnn_cu12-8.9.2.26.dist-info/METADATA,sha256=ANghqAslBQAo827_kxW66xQqlAqzsPv-pSjxESPV-Zg,1570
37
+ nvidia_cudnn_cu12-8.9.2.26.dist-info/RECORD,,
38
+ nvidia_cudnn_cu12-8.9.2.26.dist-info/WHEEL,sha256=-kQi_VMfvRQozZJT7HUPMfY-5vLo0LVTmAylNJ3Ft98,106
39
+ nvidia_cudnn_cu12-8.9.2.26.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7
venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-manylinux1_x86_64
5
+
venv/lib/python3.10/site-packages/nvidia_cudnn_cu12-8.9.2.26.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ nvidia
venv/lib/python3.10/site-packages/psutil/tests/__init__.py ADDED
@@ -0,0 +1,2043 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Test utilities."""
8
+
9
+ from __future__ import print_function
10
+
11
+ import atexit
12
+ import contextlib
13
+ import ctypes
14
+ import errno
15
+ import functools
16
+ import gc
17
+ import inspect
18
+ import os
19
+ import platform
20
+ import random
21
+ import re
22
+ import select
23
+ import shlex
24
+ import shutil
25
+ import signal
26
+ import socket
27
+ import stat
28
+ import subprocess
29
+ import sys
30
+ import tempfile
31
+ import textwrap
32
+ import threading
33
+ import time
34
+ import unittest
35
+ import warnings
36
+ from socket import AF_INET
37
+ from socket import AF_INET6
38
+ from socket import SOCK_STREAM
39
+
40
+ import psutil
41
+ from psutil import AIX
42
+ from psutil import LINUX
43
+ from psutil import MACOS
44
+ from psutil import NETBSD
45
+ from psutil import OPENBSD
46
+ from psutil import POSIX
47
+ from psutil import SUNOS
48
+ from psutil import WINDOWS
49
+ from psutil._common import bytes2human
50
+ from psutil._common import debug
51
+ from psutil._common import memoize
52
+ from psutil._common import print_color
53
+ from psutil._common import supports_ipv6
54
+ from psutil._compat import PY3
55
+ from psutil._compat import FileExistsError
56
+ from psutil._compat import FileNotFoundError
57
+ from psutil._compat import range
58
+ from psutil._compat import super
59
+ from psutil._compat import u
60
+ from psutil._compat import unicode
61
+ from psutil._compat import which
62
+
63
+
64
+ try:
65
+ from unittest import mock # py3
66
+ except ImportError:
67
+ with warnings.catch_warnings():
68
+ warnings.simplefilter("ignore")
69
+ import mock # NOQA - requires "pip install mock"
70
+
71
+ if PY3:
72
+ import enum
73
+ else:
74
+ enum = None
75
+
76
+ if POSIX:
77
+ from psutil._psposix import wait_pid
78
+
79
+
80
+ # fmt: off
81
+ __all__ = [
82
+ # constants
83
+ 'APPVEYOR', 'DEVNULL', 'GLOBAL_TIMEOUT', 'TOLERANCE_SYS_MEM', 'NO_RETRIES',
84
+ 'PYPY', 'PYTHON_EXE', 'PYTHON_EXE_ENV', 'ROOT_DIR', 'SCRIPTS_DIR',
85
+ 'TESTFN_PREFIX', 'UNICODE_SUFFIX', 'INVALID_UNICODE_SUFFIX',
86
+ 'CI_TESTING', 'VALID_PROC_STATUSES', 'TOLERANCE_DISK_USAGE', 'IS_64BIT',
87
+ "HAS_CPU_AFFINITY", "HAS_CPU_FREQ", "HAS_ENVIRON", "HAS_PROC_IO_COUNTERS",
88
+ "HAS_IONICE", "HAS_MEMORY_MAPS", "HAS_PROC_CPU_NUM", "HAS_RLIMIT",
89
+ "HAS_SENSORS_BATTERY", "HAS_BATTERY", "HAS_SENSORS_FANS",
90
+ "HAS_SENSORS_TEMPERATURES", "MACOS_11PLUS",
91
+ "MACOS_12PLUS", "COVERAGE",
92
+ # subprocesses
93
+ 'pyrun', 'terminate', 'reap_children', 'spawn_testproc', 'spawn_zombie',
94
+ 'spawn_children_pair',
95
+ # threads
96
+ 'ThreadTask',
97
+ # test utils
98
+ 'unittest', 'skip_on_access_denied', 'skip_on_not_implemented',
99
+ 'retry_on_failure', 'TestMemoryLeak', 'PsutilTestCase',
100
+ 'process_namespace', 'system_namespace', 'print_sysinfo',
101
+ 'is_win_secure_system_proc',
102
+ # fs utils
103
+ 'chdir', 'safe_rmpath', 'create_py_exe', 'create_c_exe', 'get_testfn',
104
+ # os
105
+ 'get_winver', 'kernel_version',
106
+ # sync primitives
107
+ 'call_until', 'wait_for_pid', 'wait_for_file',
108
+ # network
109
+ 'check_net_address', 'filter_proc_connections',
110
+ 'get_free_port', 'bind_socket', 'bind_unix_socket', 'tcp_socketpair',
111
+ 'unix_socketpair', 'create_sockets',
112
+ # compat
113
+ 'reload_module', 'import_module_by_path',
114
+ # others
115
+ 'warn', 'copyload_shared_lib', 'is_namedtuple',
116
+ ]
117
+ # fmt: on
118
+
119
+
120
+ # ===================================================================
121
+ # --- constants
122
+ # ===================================================================
123
+
124
+ # --- platforms
125
+
126
+ PYPY = '__pypy__' in sys.builtin_module_names
127
+ # whether we're running this test suite on a Continuous Integration service
128
+ APPVEYOR = 'APPVEYOR' in os.environ
129
+ GITHUB_ACTIONS = 'GITHUB_ACTIONS' in os.environ or 'CIBUILDWHEEL' in os.environ
130
+ CI_TESTING = APPVEYOR or GITHUB_ACTIONS
131
+ COVERAGE = 'COVERAGE_RUN' in os.environ
132
+ # are we a 64 bit process?
133
+ IS_64BIT = sys.maxsize > 2**32
134
+
135
+
136
+ @memoize
137
+ def macos_version():
138
+ version_str = platform.mac_ver()[0]
139
+ version = tuple(map(int, version_str.split(".")[:2]))
140
+ if version == (10, 16):
141
+ # When built against an older macOS SDK, Python will report
142
+ # macOS 10.16 instead of the real version.
143
+ version_str = subprocess.check_output(
144
+ [
145
+ sys.executable,
146
+ "-sS",
147
+ "-c",
148
+ "import platform; print(platform.mac_ver()[0])",
149
+ ],
150
+ env={"SYSTEM_VERSION_COMPAT": "0"},
151
+ universal_newlines=True,
152
+ )
153
+ version = tuple(map(int, version_str.split(".")[:2]))
154
+ return version
155
+
156
+
157
+ if MACOS:
158
+ MACOS_11PLUS = macos_version() > (10, 15)
159
+ MACOS_12PLUS = macos_version() >= (12, 0)
160
+ else:
161
+ MACOS_11PLUS = False
162
+ MACOS_12PLUS = False
163
+
164
+
165
+ # --- configurable defaults
166
+
167
+ # how many times retry_on_failure() decorator will retry
168
+ NO_RETRIES = 10
169
+ # bytes tolerance for system-wide related tests
170
+ TOLERANCE_SYS_MEM = 5 * 1024 * 1024 # 5MB
171
+ TOLERANCE_DISK_USAGE = 10 * 1024 * 1024 # 10MB
172
+ # the timeout used in functions which have to wait
173
+ GLOBAL_TIMEOUT = 5
174
+ # be more tolerant if we're on CI in order to avoid false positives
175
+ if CI_TESTING:
176
+ NO_RETRIES *= 3
177
+ GLOBAL_TIMEOUT *= 3
178
+ TOLERANCE_SYS_MEM *= 4
179
+ TOLERANCE_DISK_USAGE *= 3
180
+
181
+ # --- file names
182
+
183
+ # Disambiguate TESTFN for parallel testing.
184
+ if os.name == 'java':
185
+ # Jython disallows @ in module names
186
+ TESTFN_PREFIX = '$psutil-%s-' % os.getpid()
187
+ else:
188
+ TESTFN_PREFIX = '@psutil-%s-' % os.getpid()
189
+ UNICODE_SUFFIX = u("-ƒőő")
190
+ # An invalid unicode string.
191
+ if PY3:
192
+ INVALID_UNICODE_SUFFIX = b"f\xc0\x80".decode('utf8', 'surrogateescape')
193
+ else:
194
+ INVALID_UNICODE_SUFFIX = "f\xc0\x80"
195
+ ASCII_FS = sys.getfilesystemencoding().lower() in ('ascii', 'us-ascii')
196
+
197
+ # --- paths
198
+
199
+ ROOT_DIR = os.path.realpath(
200
+ os.path.join(os.path.dirname(__file__), '..', '..')
201
+ )
202
+ SCRIPTS_DIR = os.environ.get(
203
+ "PSUTIL_SCRIPTS_DIR", os.path.join(ROOT_DIR, 'scripts')
204
+ )
205
+ HERE = os.path.realpath(os.path.dirname(__file__))
206
+
207
+ # --- support
208
+
209
+ HAS_CONNECTIONS_UNIX = POSIX and not SUNOS
210
+ HAS_CPU_AFFINITY = hasattr(psutil.Process, "cpu_affinity")
211
+ HAS_CPU_FREQ = hasattr(psutil, "cpu_freq")
212
+ HAS_GETLOADAVG = hasattr(psutil, "getloadavg")
213
+ HAS_ENVIRON = hasattr(psutil.Process, "environ")
214
+ HAS_IONICE = hasattr(psutil.Process, "ionice")
215
+ HAS_MEMORY_MAPS = hasattr(psutil.Process, "memory_maps")
216
+ HAS_NET_IO_COUNTERS = hasattr(psutil, "net_io_counters")
217
+ HAS_PROC_CPU_NUM = hasattr(psutil.Process, "cpu_num")
218
+ HAS_PROC_IO_COUNTERS = hasattr(psutil.Process, "io_counters")
219
+ HAS_RLIMIT = hasattr(psutil.Process, "rlimit")
220
+ HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery")
221
+ try:
222
+ HAS_BATTERY = HAS_SENSORS_BATTERY and bool(psutil.sensors_battery())
223
+ except Exception: # noqa: BLE001
224
+ HAS_BATTERY = False
225
+ HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans")
226
+ HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures")
227
+ HAS_THREADS = hasattr(psutil.Process, "threads")
228
+ SKIP_SYSCONS = (MACOS or AIX) and os.getuid() != 0
229
+
230
+ # --- misc
231
+
232
+
233
+ def _get_py_exe():
234
+ def attempt(exe):
235
+ try:
236
+ subprocess.check_call(
237
+ [exe, "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
238
+ )
239
+ except subprocess.CalledProcessError:
240
+ return None
241
+ else:
242
+ return exe
243
+
244
+ env = os.environ.copy()
245
+
246
+ # On Windows, starting with python 3.7, virtual environments use a
247
+ # venv launcher startup process. This does not play well when
248
+ # counting spawned processes, or when relying on the PID of the
249
+ # spawned process to do some checks, e.g. connections check per PID.
250
+ # Let's use the base python in this case.
251
+ base = getattr(sys, "_base_executable", None)
252
+ if WINDOWS and sys.version_info >= (3, 7) and base is not None:
253
+ # We need to set __PYVENV_LAUNCHER__ to sys.executable for the
254
+ # base python executable to know about the environment.
255
+ env["__PYVENV_LAUNCHER__"] = sys.executable
256
+ return base, env
257
+ elif GITHUB_ACTIONS:
258
+ return sys.executable, env
259
+ elif MACOS:
260
+ exe = (
261
+ attempt(sys.executable)
262
+ or attempt(os.path.realpath(sys.executable))
263
+ or attempt(which("python%s.%s" % sys.version_info[:2]))
264
+ or attempt(psutil.Process().exe())
265
+ )
266
+ if not exe:
267
+ raise ValueError("can't find python exe real abspath")
268
+ return exe, env
269
+ else:
270
+ exe = os.path.realpath(sys.executable)
271
+ assert os.path.exists(exe), exe
272
+ return exe, env
273
+
274
+
275
+ PYTHON_EXE, PYTHON_EXE_ENV = _get_py_exe()
276
+ DEVNULL = open(os.devnull, 'r+')
277
+ atexit.register(DEVNULL.close)
278
+
279
+ VALID_PROC_STATUSES = [
280
+ getattr(psutil, x) for x in dir(psutil) if x.startswith('STATUS_')
281
+ ]
282
+ AF_UNIX = getattr(socket, "AF_UNIX", object())
283
+
284
+ _subprocesses_started = set()
285
+ _pids_started = set()
286
+
287
+
288
+ # ===================================================================
289
+ # --- threads
290
+ # ===================================================================
291
+
292
+
293
+ class ThreadTask(threading.Thread):
294
+ """A thread task which does nothing expect staying alive."""
295
+
296
+ def __init__(self):
297
+ super().__init__()
298
+ self._running = False
299
+ self._interval = 0.001
300
+ self._flag = threading.Event()
301
+
302
+ def __repr__(self):
303
+ name = self.__class__.__name__
304
+ return '<%s running=%s at %#x>' % (name, self._running, id(self))
305
+
306
+ def __enter__(self):
307
+ self.start()
308
+ return self
309
+
310
+ def __exit__(self, *args, **kwargs):
311
+ self.stop()
312
+
313
+ def start(self):
314
+ """Start thread and keep it running until an explicit
315
+ stop() request. Polls for shutdown every 'timeout' seconds.
316
+ """
317
+ if self._running:
318
+ raise ValueError("already started")
319
+ threading.Thread.start(self)
320
+ self._flag.wait()
321
+
322
+ def run(self):
323
+ self._running = True
324
+ self._flag.set()
325
+ while self._running:
326
+ time.sleep(self._interval)
327
+
328
+ def stop(self):
329
+ """Stop thread execution and and waits until it is stopped."""
330
+ if not self._running:
331
+ raise ValueError("already stopped")
332
+ self._running = False
333
+ self.join()
334
+
335
+
336
+ # ===================================================================
337
+ # --- subprocesses
338
+ # ===================================================================
339
+
340
+
341
+ def _reap_children_on_err(fun):
342
+ @functools.wraps(fun)
343
+ def wrapper(*args, **kwargs):
344
+ try:
345
+ return fun(*args, **kwargs)
346
+ except Exception:
347
+ reap_children()
348
+ raise
349
+
350
+ return wrapper
351
+
352
+
353
+ @_reap_children_on_err
354
+ def spawn_testproc(cmd=None, **kwds):
355
+ """Create a python subprocess which does nothing for some secs and
356
+ return it as a subprocess.Popen instance.
357
+ If "cmd" is specified that is used instead of python.
358
+ By default stdin and stdout are redirected to /dev/null.
359
+ It also attempts to make sure the process is in a reasonably
360
+ initialized state.
361
+ The process is registered for cleanup on reap_children().
362
+ """
363
+ kwds.setdefault("stdin", DEVNULL)
364
+ kwds.setdefault("stdout", DEVNULL)
365
+ kwds.setdefault("cwd", os.getcwd())
366
+ kwds.setdefault("env", PYTHON_EXE_ENV)
367
+ if WINDOWS:
368
+ # Prevents the subprocess to open error dialogs. This will also
369
+ # cause stderr to be suppressed, which is suboptimal in order
370
+ # to debug broken tests.
371
+ CREATE_NO_WINDOW = 0x8000000
372
+ kwds.setdefault("creationflags", CREATE_NO_WINDOW)
373
+ if cmd is None:
374
+ testfn = get_testfn(dir=os.getcwd())
375
+ try:
376
+ safe_rmpath(testfn)
377
+ pyline = (
378
+ "import time;"
379
+ + "open(r'%s', 'w').close();" % testfn
380
+ + "[time.sleep(0.1) for x in range(100)];" # 10 secs
381
+ )
382
+ cmd = [PYTHON_EXE, "-c", pyline]
383
+ sproc = subprocess.Popen(cmd, **kwds)
384
+ _subprocesses_started.add(sproc)
385
+ wait_for_file(testfn, delete=True, empty=True)
386
+ finally:
387
+ safe_rmpath(testfn)
388
+ else:
389
+ sproc = subprocess.Popen(cmd, **kwds)
390
+ _subprocesses_started.add(sproc)
391
+ wait_for_pid(sproc.pid)
392
+ return sproc
393
+
394
+
395
+ @_reap_children_on_err
396
+ def spawn_children_pair():
397
+ """Create a subprocess which creates another one as in:
398
+ A (us) -> B (child) -> C (grandchild).
399
+ Return a (child, grandchild) tuple.
400
+ The 2 processes are fully initialized and will live for 60 secs
401
+ and are registered for cleanup on reap_children().
402
+ """
403
+ tfile = None
404
+ testfn = get_testfn(dir=os.getcwd())
405
+ try:
406
+ s = textwrap.dedent("""\
407
+ import subprocess, os, sys, time
408
+ s = "import os, time;"
409
+ s += "f = open('%s', 'w');"
410
+ s += "f.write(str(os.getpid()));"
411
+ s += "f.close();"
412
+ s += "time.sleep(60);"
413
+ p = subprocess.Popen([r'%s', '-c', s])
414
+ p.wait()
415
+ """ % (os.path.basename(testfn), PYTHON_EXE))
416
+ # On Windows if we create a subprocess with CREATE_NO_WINDOW flag
417
+ # set (which is the default) a "conhost.exe" extra process will be
418
+ # spawned as a child. We don't want that.
419
+ if WINDOWS:
420
+ subp, tfile = pyrun(s, creationflags=0)
421
+ else:
422
+ subp, tfile = pyrun(s)
423
+ child = psutil.Process(subp.pid)
424
+ grandchild_pid = int(wait_for_file(testfn, delete=True, empty=False))
425
+ _pids_started.add(grandchild_pid)
426
+ grandchild = psutil.Process(grandchild_pid)
427
+ return (child, grandchild)
428
+ finally:
429
+ safe_rmpath(testfn)
430
+ if tfile is not None:
431
+ safe_rmpath(tfile)
432
+
433
+
434
+ def spawn_zombie():
435
+ """Create a zombie process and return a (parent, zombie) process tuple.
436
+ In order to kill the zombie parent must be terminate()d first, then
437
+ zombie must be wait()ed on.
438
+ """
439
+ assert psutil.POSIX
440
+ unix_file = get_testfn()
441
+ src = textwrap.dedent("""\
442
+ import os, sys, time, socket, contextlib
443
+ child_pid = os.fork()
444
+ if child_pid > 0:
445
+ time.sleep(3000)
446
+ else:
447
+ # this is the zombie process
448
+ s = socket.socket(socket.AF_UNIX)
449
+ with contextlib.closing(s):
450
+ s.connect('%s')
451
+ if sys.version_info < (3, ):
452
+ pid = str(os.getpid())
453
+ else:
454
+ pid = bytes(str(os.getpid()), 'ascii')
455
+ s.sendall(pid)
456
+ """ % unix_file)
457
+ tfile = None
458
+ sock = bind_unix_socket(unix_file)
459
+ try:
460
+ sock.settimeout(GLOBAL_TIMEOUT)
461
+ parent, tfile = pyrun(src)
462
+ conn, _ = sock.accept()
463
+ try:
464
+ select.select([conn.fileno()], [], [], GLOBAL_TIMEOUT)
465
+ zpid = int(conn.recv(1024))
466
+ _pids_started.add(zpid)
467
+ zombie = psutil.Process(zpid)
468
+ call_until(zombie.status, "ret == psutil.STATUS_ZOMBIE")
469
+ return (parent, zombie)
470
+ finally:
471
+ conn.close()
472
+ finally:
473
+ sock.close()
474
+ safe_rmpath(unix_file)
475
+ if tfile is not None:
476
+ safe_rmpath(tfile)
477
+
478
+
479
+ @_reap_children_on_err
480
+ def pyrun(src, **kwds):
481
+ """Run python 'src' code string in a separate interpreter.
482
+ Returns a subprocess.Popen instance and the test file where the source
483
+ code was written.
484
+ """
485
+ kwds.setdefault("stdout", None)
486
+ kwds.setdefault("stderr", None)
487
+ srcfile = get_testfn()
488
+ try:
489
+ with open(srcfile, "w") as f:
490
+ f.write(src)
491
+ subp = spawn_testproc([PYTHON_EXE, f.name], **kwds)
492
+ wait_for_pid(subp.pid)
493
+ return (subp, srcfile)
494
+ except Exception:
495
+ safe_rmpath(srcfile)
496
+ raise
497
+
498
+
499
+ @_reap_children_on_err
500
+ def sh(cmd, **kwds):
501
+ """Run cmd in a subprocess and return its output.
502
+ raises RuntimeError on error.
503
+ """
504
+ # Prevents subprocess to open error dialogs in case of error.
505
+ flags = 0x8000000 if WINDOWS else 0
506
+ kwds.setdefault("stdout", subprocess.PIPE)
507
+ kwds.setdefault("stderr", subprocess.PIPE)
508
+ kwds.setdefault("universal_newlines", True)
509
+ kwds.setdefault("creationflags", flags)
510
+ if isinstance(cmd, str):
511
+ cmd = shlex.split(cmd)
512
+ p = subprocess.Popen(cmd, **kwds)
513
+ _subprocesses_started.add(p)
514
+ if PY3:
515
+ stdout, stderr = p.communicate(timeout=GLOBAL_TIMEOUT)
516
+ else:
517
+ stdout, stderr = p.communicate()
518
+ if p.returncode != 0:
519
+ raise RuntimeError(stderr)
520
+ if stderr:
521
+ warn(stderr)
522
+ if stdout.endswith('\n'):
523
+ stdout = stdout[:-1]
524
+ return stdout
525
+
526
+
527
+ def terminate(proc_or_pid, sig=signal.SIGTERM, wait_timeout=GLOBAL_TIMEOUT):
528
+ """Terminate a process and wait() for it.
529
+ Process can be a PID or an instance of psutil.Process(),
530
+ subprocess.Popen() or psutil.Popen().
531
+ If it's a subprocess.Popen() or psutil.Popen() instance also closes
532
+ its stdin / stdout / stderr fds.
533
+ PID is wait()ed even if the process is already gone (kills zombies).
534
+ Does nothing if the process does not exist.
535
+ Return process exit status.
536
+ """
537
+
538
+ def wait(proc, timeout):
539
+ if isinstance(proc, subprocess.Popen) and not PY3:
540
+ proc.wait()
541
+ else:
542
+ proc.wait(timeout)
543
+ if WINDOWS and isinstance(proc, subprocess.Popen):
544
+ # Otherwise PID may still hang around.
545
+ try:
546
+ return psutil.Process(proc.pid).wait(timeout)
547
+ except psutil.NoSuchProcess:
548
+ pass
549
+
550
+ def sendsig(proc, sig):
551
+ # XXX: otherwise the build hangs for some reason.
552
+ if MACOS and GITHUB_ACTIONS:
553
+ sig = signal.SIGKILL
554
+ # If the process received SIGSTOP, SIGCONT is necessary first,
555
+ # otherwise SIGTERM won't work.
556
+ if POSIX and sig != signal.SIGKILL:
557
+ proc.send_signal(signal.SIGCONT)
558
+ proc.send_signal(sig)
559
+
560
+ def term_subprocess_proc(proc, timeout):
561
+ try:
562
+ sendsig(proc, sig)
563
+ except OSError as err:
564
+ if WINDOWS and err.winerror == 6: # "invalid handle"
565
+ pass
566
+ elif err.errno != errno.ESRCH:
567
+ raise
568
+ return wait(proc, timeout)
569
+
570
+ def term_psutil_proc(proc, timeout):
571
+ try:
572
+ sendsig(proc, sig)
573
+ except psutil.NoSuchProcess:
574
+ pass
575
+ return wait(proc, timeout)
576
+
577
+ def term_pid(pid, timeout):
578
+ try:
579
+ proc = psutil.Process(pid)
580
+ except psutil.NoSuchProcess:
581
+ # Needed to kill zombies.
582
+ if POSIX:
583
+ return wait_pid(pid, timeout)
584
+ else:
585
+ return term_psutil_proc(proc, timeout)
586
+
587
+ def flush_popen(proc):
588
+ if proc.stdout:
589
+ proc.stdout.close()
590
+ if proc.stderr:
591
+ proc.stderr.close()
592
+ # Flushing a BufferedWriter may raise an error.
593
+ if proc.stdin:
594
+ proc.stdin.close()
595
+
596
+ p = proc_or_pid
597
+ try:
598
+ if isinstance(p, int):
599
+ return term_pid(p, wait_timeout)
600
+ elif isinstance(p, (psutil.Process, psutil.Popen)):
601
+ return term_psutil_proc(p, wait_timeout)
602
+ elif isinstance(p, subprocess.Popen):
603
+ return term_subprocess_proc(p, wait_timeout)
604
+ else:
605
+ raise TypeError("wrong type %r" % p)
606
+ finally:
607
+ if isinstance(p, (subprocess.Popen, psutil.Popen)):
608
+ flush_popen(p)
609
+ pid = p if isinstance(p, int) else p.pid
610
+ assert not psutil.pid_exists(pid), pid
611
+
612
+
613
+ def reap_children(recursive=False):
614
+ """Terminate and wait() any subprocess started by this test suite
615
+ and any children currently running, ensuring that no processes stick
616
+ around to hog resources.
617
+ If recursive is True it also tries to terminate and wait()
618
+ all grandchildren started by this process.
619
+ """
620
+ # Get the children here before terminating them, as in case of
621
+ # recursive=True we don't want to lose the intermediate reference
622
+ # pointing to the grandchildren.
623
+ children = psutil.Process().children(recursive=recursive)
624
+
625
+ # Terminate subprocess.Popen.
626
+ while _subprocesses_started:
627
+ subp = _subprocesses_started.pop()
628
+ terminate(subp)
629
+
630
+ # Collect started pids.
631
+ while _pids_started:
632
+ pid = _pids_started.pop()
633
+ terminate(pid)
634
+
635
+ # Terminate children.
636
+ if children:
637
+ for p in children:
638
+ terminate(p, wait_timeout=None)
639
+ _, alive = psutil.wait_procs(children, timeout=GLOBAL_TIMEOUT)
640
+ for p in alive:
641
+ warn("couldn't terminate process %r; attempting kill()" % p)
642
+ terminate(p, sig=signal.SIGKILL)
643
+
644
+
645
+ # ===================================================================
646
+ # --- OS
647
+ # ===================================================================
648
+
649
+
650
+ def kernel_version():
651
+ """Return a tuple such as (2, 6, 36)."""
652
+ if not POSIX:
653
+ raise NotImplementedError("not POSIX")
654
+ s = ""
655
+ uname = os.uname()[2]
656
+ for c in uname:
657
+ if c.isdigit() or c == '.':
658
+ s += c
659
+ else:
660
+ break
661
+ if not s:
662
+ raise ValueError("can't parse %r" % uname)
663
+ minor = 0
664
+ micro = 0
665
+ nums = s.split('.')
666
+ major = int(nums[0])
667
+ if len(nums) >= 2:
668
+ minor = int(nums[1])
669
+ if len(nums) >= 3:
670
+ micro = int(nums[2])
671
+ return (major, minor, micro)
672
+
673
+
674
+ def get_winver():
675
+ if not WINDOWS:
676
+ raise NotImplementedError("not WINDOWS")
677
+ wv = sys.getwindowsversion()
678
+ if hasattr(wv, 'service_pack_major'): # python >= 2.7
679
+ sp = wv.service_pack_major or 0
680
+ else:
681
+ r = re.search(r"\s\d$", wv[4])
682
+ sp = int(r.group(0)) if r else 0
683
+ return (wv[0], wv[1], sp)
684
+
685
+
686
+ # ===================================================================
687
+ # --- sync primitives
688
+ # ===================================================================
689
+
690
+
691
+ class retry:
692
+ """A retry decorator."""
693
+
694
+ def __init__(
695
+ self,
696
+ exception=Exception,
697
+ timeout=None,
698
+ retries=None,
699
+ interval=0.001,
700
+ logfun=None,
701
+ ):
702
+ if timeout and retries:
703
+ raise ValueError("timeout and retries args are mutually exclusive")
704
+ self.exception = exception
705
+ self.timeout = timeout
706
+ self.retries = retries
707
+ self.interval = interval
708
+ self.logfun = logfun
709
+
710
+ def __iter__(self):
711
+ if self.timeout:
712
+ stop_at = time.time() + self.timeout
713
+ while time.time() < stop_at:
714
+ yield
715
+ elif self.retries:
716
+ for _ in range(self.retries):
717
+ yield
718
+ else:
719
+ while True:
720
+ yield
721
+
722
+ def sleep(self):
723
+ if self.interval is not None:
724
+ time.sleep(self.interval)
725
+
726
+ def __call__(self, fun):
727
+ @functools.wraps(fun)
728
+ def wrapper(*args, **kwargs):
729
+ exc = None
730
+ for _ in self:
731
+ try:
732
+ return fun(*args, **kwargs)
733
+ except self.exception as _: # NOQA
734
+ exc = _
735
+ if self.logfun is not None:
736
+ self.logfun(exc)
737
+ self.sleep()
738
+ continue
739
+ if PY3:
740
+ raise exc
741
+ else:
742
+ raise
743
+
744
+ # This way the user of the decorated function can change config
745
+ # parameters.
746
+ wrapper.decorator = self
747
+ return wrapper
748
+
749
+
750
+ @retry(
751
+ exception=psutil.NoSuchProcess,
752
+ logfun=None,
753
+ timeout=GLOBAL_TIMEOUT,
754
+ interval=0.001,
755
+ )
756
+ def wait_for_pid(pid):
757
+ """Wait for pid to show up in the process list then return.
758
+ Used in the test suite to give time the sub process to initialize.
759
+ """
760
+ if pid not in psutil.pids():
761
+ raise psutil.NoSuchProcess(pid)
762
+ psutil.Process(pid)
763
+
764
+
765
+ @retry(
766
+ exception=(FileNotFoundError, AssertionError),
767
+ logfun=None,
768
+ timeout=GLOBAL_TIMEOUT,
769
+ interval=0.001,
770
+ )
771
+ def wait_for_file(fname, delete=True, empty=False):
772
+ """Wait for a file to be written on disk with some content."""
773
+ with open(fname, "rb") as f:
774
+ data = f.read()
775
+ if not empty:
776
+ assert data
777
+ if delete:
778
+ safe_rmpath(fname)
779
+ return data
780
+
781
+
782
+ @retry(
783
+ exception=AssertionError,
784
+ logfun=None,
785
+ timeout=GLOBAL_TIMEOUT,
786
+ interval=0.001,
787
+ )
788
+ def call_until(fun, expr):
789
+ """Keep calling function for timeout secs and exit if eval()
790
+ expression is True.
791
+ """
792
+ ret = fun()
793
+ assert eval(expr) # noqa
794
+ return ret
795
+
796
+
797
+ # ===================================================================
798
+ # --- fs
799
+ # ===================================================================
800
+
801
+
802
+ def safe_rmpath(path):
803
+ """Convenience function for removing temporary test files or dirs."""
804
+
805
+ def retry_fun(fun):
806
+ # On Windows it could happen that the file or directory has
807
+ # open handles or references preventing the delete operation
808
+ # to succeed immediately, so we retry for a while. See:
809
+ # https://bugs.python.org/issue33240
810
+ stop_at = time.time() + GLOBAL_TIMEOUT
811
+ while time.time() < stop_at:
812
+ try:
813
+ return fun()
814
+ except FileNotFoundError:
815
+ pass
816
+ except WindowsError as _:
817
+ err = _
818
+ warn("ignoring %s" % (str(err)))
819
+ time.sleep(0.01)
820
+ raise err
821
+
822
+ try:
823
+ st = os.stat(path)
824
+ if stat.S_ISDIR(st.st_mode):
825
+ fun = functools.partial(shutil.rmtree, path)
826
+ else:
827
+ fun = functools.partial(os.remove, path)
828
+ if POSIX:
829
+ fun()
830
+ else:
831
+ retry_fun(fun)
832
+ except FileNotFoundError:
833
+ pass
834
+
835
+
836
+ def safe_mkdir(dir):
837
+ """Convenience function for creating a directory."""
838
+ try:
839
+ os.mkdir(dir)
840
+ except FileExistsError:
841
+ pass
842
+
843
+
844
+ @contextlib.contextmanager
845
+ def chdir(dirname):
846
+ """Context manager which temporarily changes the current directory."""
847
+ curdir = os.getcwd()
848
+ try:
849
+ os.chdir(dirname)
850
+ yield
851
+ finally:
852
+ os.chdir(curdir)
853
+
854
+
855
+ def create_py_exe(path):
856
+ """Create a Python executable file in the given location."""
857
+ assert not os.path.exists(path), path
858
+ atexit.register(safe_rmpath, path)
859
+ shutil.copyfile(PYTHON_EXE, path)
860
+ if POSIX:
861
+ st = os.stat(path)
862
+ os.chmod(path, st.st_mode | stat.S_IEXEC)
863
+ return path
864
+
865
+
866
+ def create_c_exe(path, c_code=None):
867
+ """Create a compiled C executable in the given location."""
868
+ assert not os.path.exists(path), path
869
+ if not which("gcc"):
870
+ raise unittest.SkipTest("gcc is not installed")
871
+ if c_code is None:
872
+ c_code = textwrap.dedent("""
873
+ #include <unistd.h>
874
+ int main() {
875
+ pause();
876
+ return 1;
877
+ }
878
+ """)
879
+ else:
880
+ assert isinstance(c_code, str), c_code
881
+
882
+ atexit.register(safe_rmpath, path)
883
+ with open(get_testfn(suffix='.c'), "w") as f:
884
+ f.write(c_code)
885
+ try:
886
+ subprocess.check_call(["gcc", f.name, "-o", path])
887
+ finally:
888
+ safe_rmpath(f.name)
889
+ return path
890
+
891
+
892
+ def get_testfn(suffix="", dir=None):
893
+ """Return an absolute pathname of a file or dir that did not
894
+ exist at the time this call is made. Also schedule it for safe
895
+ deletion at interpreter exit. It's technically racy but probably
896
+ not really due to the time variant.
897
+ """
898
+ while True:
899
+ name = tempfile.mktemp(prefix=TESTFN_PREFIX, suffix=suffix, dir=dir)
900
+ if not os.path.exists(name): # also include dirs
901
+ path = os.path.realpath(name) # needed for OSX
902
+ atexit.register(safe_rmpath, path)
903
+ return path
904
+
905
+
906
+ # ===================================================================
907
+ # --- testing
908
+ # ===================================================================
909
+
910
+
911
+ class TestCase(unittest.TestCase):
912
+
913
+ # Print a full path representation of the single unit tests
914
+ # being run.
915
+ def __str__(self):
916
+ fqmod = self.__class__.__module__
917
+ if not fqmod.startswith('psutil.'):
918
+ fqmod = 'psutil.tests.' + fqmod
919
+ return "%s.%s.%s" % (
920
+ fqmod,
921
+ self.__class__.__name__,
922
+ self._testMethodName,
923
+ )
924
+
925
+ # assertRaisesRegexp renamed to assertRaisesRegex in 3.3;
926
+ # add support for the new name.
927
+ if not hasattr(unittest.TestCase, 'assertRaisesRegex'):
928
+ assertRaisesRegex = unittest.TestCase.assertRaisesRegexp # noqa
929
+
930
+ # ...otherwise multiprocessing.Pool complains
931
+ if not PY3:
932
+
933
+ def runTest(self):
934
+ pass
935
+
936
+ @contextlib.contextmanager
937
+ def subTest(self, *args, **kw):
938
+ # fake it for python 2.7
939
+ yield
940
+
941
+
942
+ # monkey patch default unittest.TestCase
943
+ unittest.TestCase = TestCase
944
+
945
+
946
+ class PsutilTestCase(TestCase):
947
+ """Test class providing auto-cleanup wrappers on top of process
948
+ test utilities.
949
+ """
950
+
951
+ def get_testfn(self, suffix="", dir=None):
952
+ fname = get_testfn(suffix=suffix, dir=dir)
953
+ self.addCleanup(safe_rmpath, fname)
954
+ return fname
955
+
956
+ def spawn_testproc(self, *args, **kwds):
957
+ sproc = spawn_testproc(*args, **kwds)
958
+ self.addCleanup(terminate, sproc)
959
+ return sproc
960
+
961
+ def spawn_children_pair(self):
962
+ child1, child2 = spawn_children_pair()
963
+ self.addCleanup(terminate, child2)
964
+ self.addCleanup(terminate, child1) # executed first
965
+ return (child1, child2)
966
+
967
+ def spawn_zombie(self):
968
+ parent, zombie = spawn_zombie()
969
+ self.addCleanup(terminate, zombie)
970
+ self.addCleanup(terminate, parent) # executed first
971
+ return (parent, zombie)
972
+
973
+ def pyrun(self, *args, **kwds):
974
+ sproc, srcfile = pyrun(*args, **kwds)
975
+ self.addCleanup(safe_rmpath, srcfile)
976
+ self.addCleanup(terminate, sproc) # executed first
977
+ return sproc
978
+
979
+ def _check_proc_exc(self, proc, exc):
980
+ self.assertIsInstance(exc, psutil.Error)
981
+ self.assertEqual(exc.pid, proc.pid)
982
+ self.assertEqual(exc.name, proc._name)
983
+ if exc.name:
984
+ self.assertNotEqual(exc.name, "")
985
+ if isinstance(exc, psutil.ZombieProcess):
986
+ self.assertEqual(exc.ppid, proc._ppid)
987
+ if exc.ppid is not None:
988
+ self.assertGreaterEqual(exc.ppid, 0)
989
+ str(exc)
990
+ repr(exc)
991
+
992
+ def assertPidGone(self, pid):
993
+ with self.assertRaises(psutil.NoSuchProcess) as cm:
994
+ try:
995
+ psutil.Process(pid)
996
+ except psutil.ZombieProcess:
997
+ raise AssertionError("wasn't supposed to raise ZombieProcess")
998
+ self.assertEqual(cm.exception.pid, pid)
999
+ self.assertEqual(cm.exception.name, None)
1000
+ assert not psutil.pid_exists(pid), pid
1001
+ self.assertNotIn(pid, psutil.pids())
1002
+ self.assertNotIn(pid, [x.pid for x in psutil.process_iter()])
1003
+
1004
+ def assertProcessGone(self, proc):
1005
+ self.assertPidGone(proc.pid)
1006
+ ns = process_namespace(proc)
1007
+ for fun, name in ns.iter(ns.all, clear_cache=True):
1008
+ with self.subTest(proc=proc, name=name):
1009
+ try:
1010
+ ret = fun()
1011
+ except psutil.ZombieProcess:
1012
+ raise
1013
+ except psutil.NoSuchProcess as exc:
1014
+ self._check_proc_exc(proc, exc)
1015
+ else:
1016
+ msg = "Process.%s() didn't raise NSP and returned %r" % (
1017
+ name,
1018
+ ret,
1019
+ )
1020
+ raise AssertionError(msg)
1021
+ proc.wait(timeout=0) # assert not raise TimeoutExpired
1022
+
1023
+ def assertProcessZombie(self, proc):
1024
+ # A zombie process should always be instantiable.
1025
+ clone = psutil.Process(proc.pid)
1026
+ # Cloned zombie on Open/NetBSD has null creation time, see:
1027
+ # https://github.com/giampaolo/psutil/issues/2287
1028
+ self.assertEqual(proc, clone)
1029
+ if not (OPENBSD or NETBSD):
1030
+ self.assertEqual(hash(proc), hash(clone))
1031
+ # Its status always be querable.
1032
+ self.assertEqual(proc.status(), psutil.STATUS_ZOMBIE)
1033
+ # It should be considered 'running'.
1034
+ assert proc.is_running()
1035
+ assert psutil.pid_exists(proc.pid)
1036
+ # as_dict() shouldn't crash.
1037
+ proc.as_dict()
1038
+ # It should show up in pids() and process_iter().
1039
+ self.assertIn(proc.pid, psutil.pids())
1040
+ self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
1041
+ psutil._pmap = {}
1042
+ self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
1043
+ # Call all methods.
1044
+ ns = process_namespace(proc)
1045
+ for fun, name in ns.iter(ns.all, clear_cache=True):
1046
+ with self.subTest(proc=proc, name=name):
1047
+ try:
1048
+ fun()
1049
+ except (psutil.ZombieProcess, psutil.AccessDenied) as exc:
1050
+ self._check_proc_exc(proc, exc)
1051
+ if LINUX:
1052
+ # https://github.com/giampaolo/psutil/pull/2288
1053
+ with self.assertRaises(psutil.ZombieProcess) as cm:
1054
+ proc.cmdline()
1055
+ self._check_proc_exc(proc, cm.exception)
1056
+ with self.assertRaises(psutil.ZombieProcess) as cm:
1057
+ proc.exe()
1058
+ self._check_proc_exc(proc, cm.exception)
1059
+ with self.assertRaises(psutil.ZombieProcess) as cm:
1060
+ proc.memory_maps()
1061
+ self._check_proc_exc(proc, cm.exception)
1062
+ # Zombie cannot be signaled or terminated.
1063
+ proc.suspend()
1064
+ proc.resume()
1065
+ proc.terminate()
1066
+ proc.kill()
1067
+ assert proc.is_running()
1068
+ assert psutil.pid_exists(proc.pid)
1069
+ self.assertIn(proc.pid, psutil.pids())
1070
+ self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
1071
+ psutil._pmap = {}
1072
+ self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
1073
+
1074
+ # Its parent should 'see' it (edit: not true on BSD and MACOS).
1075
+ # descendants = [x.pid for x in psutil.Process().children(
1076
+ # recursive=True)]
1077
+ # self.assertIn(proc.pid, descendants)
1078
+
1079
+ # __eq__ can't be relied upon because creation time may not be
1080
+ # querable.
1081
+ # self.assertEqual(proc, psutil.Process(proc.pid))
1082
+
1083
+ # XXX should we also assume ppid() to be usable? Note: this
1084
+ # would be an important use case as the only way to get
1085
+ # rid of a zombie is to kill its parent.
1086
+ # self.assertEqual(proc.ppid(), os.getpid())
1087
+
1088
+
1089
+ @unittest.skipIf(PYPY, "unreliable on PYPY")
1090
+ class TestMemoryLeak(PsutilTestCase):
1091
+ """Test framework class for detecting function memory leaks,
1092
+ typically functions implemented in C which forgot to free() memory
1093
+ from the heap. It does so by checking whether the process memory
1094
+ usage increased before and after calling the function many times.
1095
+
1096
+ Note that this is hard (probably impossible) to do reliably, due
1097
+ to how the OS handles memory, the GC and so on (memory can even
1098
+ decrease!). In order to avoid false positives, in case of failure
1099
+ (mem > 0) we retry the test for up to 5 times, increasing call
1100
+ repetitions each time. If the memory keeps increasing then it's a
1101
+ failure.
1102
+
1103
+ If available (Linux, OSX, Windows), USS memory is used for comparison,
1104
+ since it's supposed to be more precise, see:
1105
+ https://gmpy.dev/blog/2016/real-process-memory-and-environ-in-python
1106
+ If not, RSS memory is used. mallinfo() on Linux and _heapwalk() on
1107
+ Windows may give even more precision, but at the moment are not
1108
+ implemented.
1109
+
1110
+ PyPy appears to be completely unstable for this framework, probably
1111
+ because of its JIT, so tests on PYPY are skipped.
1112
+
1113
+ Usage:
1114
+
1115
+ class TestLeaks(psutil.tests.TestMemoryLeak):
1116
+
1117
+ def test_fun(self):
1118
+ self.execute(some_function)
1119
+ """
1120
+
1121
+ # Configurable class attrs.
1122
+ times = 200
1123
+ warmup_times = 10
1124
+ tolerance = 0 # memory
1125
+ retries = 10 if CI_TESTING else 5
1126
+ verbose = True
1127
+ _thisproc = psutil.Process()
1128
+ _psutil_debug_orig = bool(os.getenv('PSUTIL_DEBUG'))
1129
+
1130
+ @classmethod
1131
+ def setUpClass(cls):
1132
+ psutil._set_debug(False) # avoid spamming to stderr
1133
+
1134
+ @classmethod
1135
+ def tearDownClass(cls):
1136
+ psutil._set_debug(cls._psutil_debug_orig)
1137
+
1138
+ def _get_mem(self):
1139
+ # USS is the closest thing we have to "real" memory usage and it
1140
+ # should be less likely to produce false positives.
1141
+ mem = self._thisproc.memory_full_info()
1142
+ return getattr(mem, "uss", mem.rss)
1143
+
1144
+ def _get_num_fds(self):
1145
+ if POSIX:
1146
+ return self._thisproc.num_fds()
1147
+ else:
1148
+ return self._thisproc.num_handles()
1149
+
1150
+ def _log(self, msg):
1151
+ if self.verbose:
1152
+ print_color(msg, color="yellow", file=sys.stderr)
1153
+
1154
+ def _check_fds(self, fun):
1155
+ """Makes sure num_fds() (POSIX) or num_handles() (Windows) does
1156
+ not increase after calling a function. Used to discover forgotten
1157
+ close(2) and CloseHandle syscalls.
1158
+ """
1159
+ before = self._get_num_fds()
1160
+ self.call(fun)
1161
+ after = self._get_num_fds()
1162
+ diff = after - before
1163
+ if diff < 0:
1164
+ raise self.fail(
1165
+ "negative diff %r (gc probably collected a "
1166
+ "resource from a previous test)" % diff
1167
+ )
1168
+ if diff > 0:
1169
+ type_ = "fd" if POSIX else "handle"
1170
+ if diff > 1:
1171
+ type_ += "s"
1172
+ msg = "%s unclosed %s after calling %r" % (diff, type_, fun)
1173
+ raise self.fail(msg)
1174
+
1175
+ def _call_ntimes(self, fun, times):
1176
+ """Get 2 distinct memory samples, before and after having
1177
+ called fun repeatedly, and return the memory difference.
1178
+ """
1179
+ gc.collect(generation=1)
1180
+ mem1 = self._get_mem()
1181
+ for x in range(times):
1182
+ ret = self.call(fun)
1183
+ del x, ret
1184
+ gc.collect(generation=1)
1185
+ mem2 = self._get_mem()
1186
+ self.assertEqual(gc.garbage, [])
1187
+ diff = mem2 - mem1 # can also be negative
1188
+ return diff
1189
+
1190
+ def _check_mem(self, fun, times, retries, tolerance):
1191
+ messages = []
1192
+ prev_mem = 0
1193
+ increase = times
1194
+ for idx in range(1, retries + 1):
1195
+ mem = self._call_ntimes(fun, times)
1196
+ msg = "Run #%s: extra-mem=%s, per-call=%s, calls=%s" % (
1197
+ idx,
1198
+ bytes2human(mem),
1199
+ bytes2human(mem / times),
1200
+ times,
1201
+ )
1202
+ messages.append(msg)
1203
+ success = mem <= tolerance or mem <= prev_mem
1204
+ if success:
1205
+ if idx > 1:
1206
+ self._log(msg)
1207
+ return
1208
+ else:
1209
+ if idx == 1:
1210
+ print() # NOQA
1211
+ self._log(msg)
1212
+ times += increase
1213
+ prev_mem = mem
1214
+ raise self.fail(". ".join(messages))
1215
+
1216
+ # ---
1217
+
1218
+ def call(self, fun):
1219
+ return fun()
1220
+
1221
+ def execute(
1222
+ self, fun, times=None, warmup_times=None, retries=None, tolerance=None
1223
+ ):
1224
+ """Test a callable."""
1225
+ times = times if times is not None else self.times
1226
+ warmup_times = (
1227
+ warmup_times if warmup_times is not None else self.warmup_times
1228
+ )
1229
+ retries = retries if retries is not None else self.retries
1230
+ tolerance = tolerance if tolerance is not None else self.tolerance
1231
+ try:
1232
+ assert times >= 1, "times must be >= 1"
1233
+ assert warmup_times >= 0, "warmup_times must be >= 0"
1234
+ assert retries >= 0, "retries must be >= 0"
1235
+ assert tolerance >= 0, "tolerance must be >= 0"
1236
+ except AssertionError as err:
1237
+ raise ValueError(str(err))
1238
+
1239
+ self._call_ntimes(fun, warmup_times) # warm up
1240
+ self._check_fds(fun)
1241
+ self._check_mem(fun, times=times, retries=retries, tolerance=tolerance)
1242
+
1243
+ def execute_w_exc(self, exc, fun, **kwargs):
1244
+ """Convenience method to test a callable while making sure it
1245
+ raises an exception on every call.
1246
+ """
1247
+
1248
+ def call():
1249
+ self.assertRaises(exc, fun)
1250
+
1251
+ self.execute(call, **kwargs)
1252
+
1253
+
1254
+ def print_sysinfo():
1255
+ import collections
1256
+ import datetime
1257
+ import getpass
1258
+ import locale
1259
+ import pprint
1260
+
1261
+ try:
1262
+ import pip
1263
+ except ImportError:
1264
+ pip = None
1265
+ try:
1266
+ import wheel
1267
+ except ImportError:
1268
+ wheel = None
1269
+
1270
+ info = collections.OrderedDict()
1271
+
1272
+ # OS
1273
+ if psutil.LINUX and which('lsb_release'):
1274
+ info['OS'] = sh('lsb_release -d -s')
1275
+ elif psutil.OSX:
1276
+ info['OS'] = 'Darwin %s' % platform.mac_ver()[0]
1277
+ elif psutil.WINDOWS:
1278
+ info['OS'] = "Windows " + ' '.join(map(str, platform.win32_ver()))
1279
+ if hasattr(platform, 'win32_edition'):
1280
+ info['OS'] += ", " + platform.win32_edition()
1281
+ else:
1282
+ info['OS'] = "%s %s" % (platform.system(), platform.version())
1283
+ info['arch'] = ', '.join(
1284
+ list(platform.architecture()) + [platform.machine()]
1285
+ )
1286
+ if psutil.POSIX:
1287
+ info['kernel'] = platform.uname()[2]
1288
+
1289
+ # python
1290
+ info['python'] = ', '.join([
1291
+ platform.python_implementation(),
1292
+ platform.python_version(),
1293
+ platform.python_compiler(),
1294
+ ])
1295
+ info['pip'] = getattr(pip, '__version__', 'not installed')
1296
+ if wheel is not None:
1297
+ info['pip'] += " (wheel=%s)" % wheel.__version__
1298
+
1299
+ # UNIX
1300
+ if psutil.POSIX:
1301
+ if which('gcc'):
1302
+ out = sh(['gcc', '--version'])
1303
+ info['gcc'] = str(out).split('\n')[0]
1304
+ else:
1305
+ info['gcc'] = 'not installed'
1306
+ s = platform.libc_ver()[1]
1307
+ if s:
1308
+ info['glibc'] = s
1309
+
1310
+ # system
1311
+ info['fs-encoding'] = sys.getfilesystemencoding()
1312
+ lang = locale.getlocale()
1313
+ info['lang'] = '%s, %s' % (lang[0], lang[1])
1314
+ info['boot-time'] = datetime.datetime.fromtimestamp(
1315
+ psutil.boot_time()
1316
+ ).strftime("%Y-%m-%d %H:%M:%S")
1317
+ info['time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1318
+ info['user'] = getpass.getuser()
1319
+ info['home'] = os.path.expanduser("~")
1320
+ info['cwd'] = os.getcwd()
1321
+ info['pyexe'] = PYTHON_EXE
1322
+ info['hostname'] = platform.node()
1323
+ info['PID'] = os.getpid()
1324
+
1325
+ # metrics
1326
+ info['cpus'] = psutil.cpu_count()
1327
+ info['loadavg'] = "%.1f%%, %.1f%%, %.1f%%" % (
1328
+ tuple([x / psutil.cpu_count() * 100 for x in psutil.getloadavg()])
1329
+ )
1330
+ mem = psutil.virtual_memory()
1331
+ info['memory'] = "%s%%, used=%s, total=%s" % (
1332
+ int(mem.percent),
1333
+ bytes2human(mem.used),
1334
+ bytes2human(mem.total),
1335
+ )
1336
+ swap = psutil.swap_memory()
1337
+ info['swap'] = "%s%%, used=%s, total=%s" % (
1338
+ int(swap.percent),
1339
+ bytes2human(swap.used),
1340
+ bytes2human(swap.total),
1341
+ )
1342
+ info['pids'] = len(psutil.pids())
1343
+ pinfo = psutil.Process().as_dict()
1344
+ pinfo.pop('memory_maps', None)
1345
+ info['proc'] = pprint.pformat(pinfo)
1346
+
1347
+ print("=" * 70, file=sys.stderr) # NOQA
1348
+ for k, v in info.items():
1349
+ print("%-17s %s" % (k + ':', v), file=sys.stderr) # NOQA
1350
+ print("=" * 70, file=sys.stderr) # NOQA
1351
+ sys.stdout.flush()
1352
+
1353
+ if WINDOWS:
1354
+ os.system("tasklist")
1355
+ elif which("ps"):
1356
+ os.system("ps aux")
1357
+ print("=" * 70, file=sys.stderr) # NOQA
1358
+ sys.stdout.flush()
1359
+
1360
+
1361
+ def is_win_secure_system_proc(pid):
1362
+ # see: https://github.com/giampaolo/psutil/issues/2338
1363
+ @memoize
1364
+ def get_procs():
1365
+ ret = {}
1366
+ out = sh("tasklist.exe /NH /FO csv")
1367
+ for line in out.splitlines()[1:]:
1368
+ bits = [x.replace('"', "") for x in line.split(",")]
1369
+ name, pid = bits[0], int(bits[1])
1370
+ ret[pid] = name
1371
+ return ret
1372
+
1373
+ try:
1374
+ return get_procs()[pid] == "Secure System"
1375
+ except KeyError:
1376
+ return False
1377
+
1378
+
1379
+ def _get_eligible_cpu():
1380
+ p = psutil.Process()
1381
+ if hasattr(p, "cpu_num"):
1382
+ return p.cpu_num()
1383
+ elif hasattr(p, "cpu_affinity"):
1384
+ return random.choice(p.cpu_affinity())
1385
+ return 0
1386
+
1387
+
1388
+ class process_namespace:
1389
+ """A container that lists all Process class method names + some
1390
+ reasonable parameters to be called with. Utility methods (parent(),
1391
+ children(), ...) are excluded.
1392
+
1393
+ >>> ns = process_namespace(psutil.Process())
1394
+ >>> for fun, name in ns.iter(ns.getters):
1395
+ ... fun()
1396
+ """
1397
+
1398
+ utils = [('cpu_percent', (), {}), ('memory_percent', (), {})]
1399
+
1400
+ ignored = [
1401
+ ('as_dict', (), {}),
1402
+ ('children', (), {'recursive': True}),
1403
+ ('is_running', (), {}),
1404
+ ('memory_info_ex', (), {}),
1405
+ ('oneshot', (), {}),
1406
+ ('parent', (), {}),
1407
+ ('parents', (), {}),
1408
+ ('pid', (), {}),
1409
+ ('wait', (0,), {}),
1410
+ ]
1411
+
1412
+ getters = [
1413
+ ('cmdline', (), {}),
1414
+ ('connections', (), {'kind': 'all'}),
1415
+ ('cpu_times', (), {}),
1416
+ ('create_time', (), {}),
1417
+ ('cwd', (), {}),
1418
+ ('exe', (), {}),
1419
+ ('memory_full_info', (), {}),
1420
+ ('memory_info', (), {}),
1421
+ ('name', (), {}),
1422
+ ('nice', (), {}),
1423
+ ('num_ctx_switches', (), {}),
1424
+ ('num_threads', (), {}),
1425
+ ('open_files', (), {}),
1426
+ ('ppid', (), {}),
1427
+ ('status', (), {}),
1428
+ ('threads', (), {}),
1429
+ ('username', (), {}),
1430
+ ]
1431
+ if POSIX:
1432
+ getters += [('uids', (), {})]
1433
+ getters += [('gids', (), {})]
1434
+ getters += [('terminal', (), {})]
1435
+ getters += [('num_fds', (), {})]
1436
+ if HAS_PROC_IO_COUNTERS:
1437
+ getters += [('io_counters', (), {})]
1438
+ if HAS_IONICE:
1439
+ getters += [('ionice', (), {})]
1440
+ if HAS_RLIMIT:
1441
+ getters += [('rlimit', (psutil.RLIMIT_NOFILE,), {})]
1442
+ if HAS_CPU_AFFINITY:
1443
+ getters += [('cpu_affinity', (), {})]
1444
+ if HAS_PROC_CPU_NUM:
1445
+ getters += [('cpu_num', (), {})]
1446
+ if HAS_ENVIRON:
1447
+ getters += [('environ', (), {})]
1448
+ if WINDOWS:
1449
+ getters += [('num_handles', (), {})]
1450
+ if HAS_MEMORY_MAPS:
1451
+ getters += [('memory_maps', (), {'grouped': False})]
1452
+
1453
+ setters = []
1454
+ if POSIX:
1455
+ setters += [('nice', (0,), {})]
1456
+ else:
1457
+ setters += [('nice', (psutil.NORMAL_PRIORITY_CLASS,), {})]
1458
+ if HAS_RLIMIT:
1459
+ setters += [('rlimit', (psutil.RLIMIT_NOFILE, (1024, 4096)), {})]
1460
+ if HAS_IONICE:
1461
+ if LINUX:
1462
+ setters += [('ionice', (psutil.IOPRIO_CLASS_NONE, 0), {})]
1463
+ else:
1464
+ setters += [('ionice', (psutil.IOPRIO_NORMAL,), {})]
1465
+ if HAS_CPU_AFFINITY:
1466
+ setters += [('cpu_affinity', ([_get_eligible_cpu()],), {})]
1467
+
1468
+ killers = [
1469
+ ('send_signal', (signal.SIGTERM,), {}),
1470
+ ('suspend', (), {}),
1471
+ ('resume', (), {}),
1472
+ ('terminate', (), {}),
1473
+ ('kill', (), {}),
1474
+ ]
1475
+ if WINDOWS:
1476
+ killers += [('send_signal', (signal.CTRL_C_EVENT,), {})]
1477
+ killers += [('send_signal', (signal.CTRL_BREAK_EVENT,), {})]
1478
+
1479
+ all = utils + getters + setters + killers
1480
+
1481
+ def __init__(self, proc):
1482
+ self._proc = proc
1483
+
1484
+ def iter(self, ls, clear_cache=True):
1485
+ """Given a list of tuples yields a set of (fun, fun_name) tuples
1486
+ in random order.
1487
+ """
1488
+ ls = list(ls)
1489
+ random.shuffle(ls)
1490
+ for fun_name, args, kwds in ls:
1491
+ if clear_cache:
1492
+ self.clear_cache()
1493
+ fun = getattr(self._proc, fun_name)
1494
+ fun = functools.partial(fun, *args, **kwds)
1495
+ yield (fun, fun_name)
1496
+
1497
+ def clear_cache(self):
1498
+ """Clear the cache of a Process instance."""
1499
+ self._proc._init(self._proc.pid, _ignore_nsp=True)
1500
+
1501
+ @classmethod
1502
+ def test_class_coverage(cls, test_class, ls):
1503
+ """Given a TestCase instance and a list of tuples checks that
1504
+ the class defines the required test method names.
1505
+ """
1506
+ for fun_name, _, _ in ls:
1507
+ meth_name = 'test_' + fun_name
1508
+ if not hasattr(test_class, meth_name):
1509
+ msg = "%r class should define a '%s' method" % (
1510
+ test_class.__class__.__name__,
1511
+ meth_name,
1512
+ )
1513
+ raise AttributeError(msg)
1514
+
1515
+ @classmethod
1516
+ def test(cls):
1517
+ this = set([x[0] for x in cls.all])
1518
+ ignored = set([x[0] for x in cls.ignored])
1519
+ klass = set([x for x in dir(psutil.Process) if x[0] != '_'])
1520
+ leftout = (this | ignored) ^ klass
1521
+ if leftout:
1522
+ raise ValueError("uncovered Process class names: %r" % leftout)
1523
+
1524
+
1525
+ class system_namespace:
1526
+ """A container that lists all the module-level, system-related APIs.
1527
+ Utilities such as cpu_percent() are excluded. Usage:
1528
+
1529
+ >>> ns = system_namespace
1530
+ >>> for fun, name in ns.iter(ns.getters):
1531
+ ... fun()
1532
+ """
1533
+
1534
+ getters = [
1535
+ ('boot_time', (), {}),
1536
+ ('cpu_count', (), {'logical': False}),
1537
+ ('cpu_count', (), {'logical': True}),
1538
+ ('cpu_stats', (), {}),
1539
+ ('cpu_times', (), {'percpu': False}),
1540
+ ('cpu_times', (), {'percpu': True}),
1541
+ ('disk_io_counters', (), {'perdisk': True}),
1542
+ ('disk_partitions', (), {'all': True}),
1543
+ ('disk_usage', (os.getcwd(),), {}),
1544
+ ('net_connections', (), {'kind': 'all'}),
1545
+ ('net_if_addrs', (), {}),
1546
+ ('net_if_stats', (), {}),
1547
+ ('net_io_counters', (), {'pernic': True}),
1548
+ ('pid_exists', (os.getpid(),), {}),
1549
+ ('pids', (), {}),
1550
+ ('swap_memory', (), {}),
1551
+ ('users', (), {}),
1552
+ ('virtual_memory', (), {}),
1553
+ ]
1554
+ if HAS_CPU_FREQ:
1555
+ getters += [('cpu_freq', (), {'percpu': True})]
1556
+ if HAS_GETLOADAVG:
1557
+ getters += [('getloadavg', (), {})]
1558
+ if HAS_SENSORS_TEMPERATURES:
1559
+ getters += [('sensors_temperatures', (), {})]
1560
+ if HAS_SENSORS_FANS:
1561
+ getters += [('sensors_fans', (), {})]
1562
+ if HAS_SENSORS_BATTERY:
1563
+ getters += [('sensors_battery', (), {})]
1564
+ if WINDOWS:
1565
+ getters += [('win_service_iter', (), {})]
1566
+ getters += [('win_service_get', ('alg',), {})]
1567
+
1568
+ ignored = [
1569
+ ('process_iter', (), {}),
1570
+ ('wait_procs', ([psutil.Process()],), {}),
1571
+ ('cpu_percent', (), {}),
1572
+ ('cpu_times_percent', (), {}),
1573
+ ]
1574
+
1575
+ all = getters
1576
+
1577
+ @staticmethod
1578
+ def iter(ls):
1579
+ """Given a list of tuples yields a set of (fun, fun_name) tuples
1580
+ in random order.
1581
+ """
1582
+ ls = list(ls)
1583
+ random.shuffle(ls)
1584
+ for fun_name, args, kwds in ls:
1585
+ fun = getattr(psutil, fun_name)
1586
+ fun = functools.partial(fun, *args, **kwds)
1587
+ yield (fun, fun_name)
1588
+
1589
+ test_class_coverage = process_namespace.test_class_coverage
1590
+
1591
+
1592
+ def serialrun(klass):
1593
+ """A decorator to mark a TestCase class. When running parallel tests,
1594
+ class' unit tests will be run serially (1 process).
1595
+ """
1596
+ # assert issubclass(klass, unittest.TestCase), klass
1597
+ assert inspect.isclass(klass), klass
1598
+ klass._serialrun = True
1599
+ return klass
1600
+
1601
+
1602
+ def retry_on_failure(retries=NO_RETRIES):
1603
+ """Decorator which runs a test function and retries N times before
1604
+ actually failing.
1605
+ """
1606
+
1607
+ def logfun(exc):
1608
+ print("%r, retrying" % exc, file=sys.stderr) # NOQA
1609
+
1610
+ return retry(
1611
+ exception=AssertionError, timeout=None, retries=retries, logfun=logfun
1612
+ )
1613
+
1614
+
1615
+ def skip_on_access_denied(only_if=None):
1616
+ """Decorator to Ignore AccessDenied exceptions."""
1617
+
1618
+ def decorator(fun):
1619
+ @functools.wraps(fun)
1620
+ def wrapper(*args, **kwargs):
1621
+ try:
1622
+ return fun(*args, **kwargs)
1623
+ except psutil.AccessDenied:
1624
+ if only_if is not None:
1625
+ if not only_if:
1626
+ raise
1627
+ raise unittest.SkipTest("raises AccessDenied")
1628
+
1629
+ return wrapper
1630
+
1631
+ return decorator
1632
+
1633
+
1634
+ def skip_on_not_implemented(only_if=None):
1635
+ """Decorator to Ignore NotImplementedError exceptions."""
1636
+
1637
+ def decorator(fun):
1638
+ @functools.wraps(fun)
1639
+ def wrapper(*args, **kwargs):
1640
+ try:
1641
+ return fun(*args, **kwargs)
1642
+ except NotImplementedError:
1643
+ if only_if is not None:
1644
+ if not only_if:
1645
+ raise
1646
+ msg = (
1647
+ "%r was skipped because it raised NotImplementedError"
1648
+ % fun.__name__
1649
+ )
1650
+ raise unittest.SkipTest(msg)
1651
+
1652
+ return wrapper
1653
+
1654
+ return decorator
1655
+
1656
+
1657
+ # ===================================================================
1658
+ # --- network
1659
+ # ===================================================================
1660
+
1661
+
1662
+ # XXX: no longer used
1663
+ def get_free_port(host='127.0.0.1'):
1664
+ """Return an unused TCP port. Subject to race conditions."""
1665
+ with contextlib.closing(socket.socket()) as sock:
1666
+ sock.bind((host, 0))
1667
+ return sock.getsockname()[1]
1668
+
1669
+
1670
+ def bind_socket(family=AF_INET, type=SOCK_STREAM, addr=None):
1671
+ """Binds a generic socket."""
1672
+ if addr is None and family in (AF_INET, AF_INET6):
1673
+ addr = ("", 0)
1674
+ sock = socket.socket(family, type)
1675
+ try:
1676
+ if os.name not in ('nt', 'cygwin'):
1677
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1678
+ sock.bind(addr)
1679
+ if type == socket.SOCK_STREAM:
1680
+ sock.listen(5)
1681
+ return sock
1682
+ except Exception:
1683
+ sock.close()
1684
+ raise
1685
+
1686
+
1687
+ def bind_unix_socket(name, type=socket.SOCK_STREAM):
1688
+ """Bind a UNIX socket."""
1689
+ assert psutil.POSIX
1690
+ assert not os.path.exists(name), name
1691
+ sock = socket.socket(socket.AF_UNIX, type)
1692
+ try:
1693
+ sock.bind(name)
1694
+ if type == socket.SOCK_STREAM:
1695
+ sock.listen(5)
1696
+ except Exception:
1697
+ sock.close()
1698
+ raise
1699
+ return sock
1700
+
1701
+
1702
+ def tcp_socketpair(family, addr=("", 0)):
1703
+ """Build a pair of TCP sockets connected to each other.
1704
+ Return a (server, client) tuple.
1705
+ """
1706
+ with contextlib.closing(socket.socket(family, SOCK_STREAM)) as ll:
1707
+ ll.bind(addr)
1708
+ ll.listen(5)
1709
+ addr = ll.getsockname()
1710
+ c = socket.socket(family, SOCK_STREAM)
1711
+ try:
1712
+ c.connect(addr)
1713
+ caddr = c.getsockname()
1714
+ while True:
1715
+ a, addr = ll.accept()
1716
+ # check that we've got the correct client
1717
+ if addr == caddr:
1718
+ return (a, c)
1719
+ a.close()
1720
+ except OSError:
1721
+ c.close()
1722
+ raise
1723
+
1724
+
1725
+ def unix_socketpair(name):
1726
+ """Build a pair of UNIX sockets connected to each other through
1727
+ the same UNIX file name.
1728
+ Return a (server, client) tuple.
1729
+ """
1730
+ assert psutil.POSIX
1731
+ server = client = None
1732
+ try:
1733
+ server = bind_unix_socket(name, type=socket.SOCK_STREAM)
1734
+ server.setblocking(0)
1735
+ client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1736
+ client.setblocking(0)
1737
+ client.connect(name)
1738
+ # new = server.accept()
1739
+ except Exception:
1740
+ if server is not None:
1741
+ server.close()
1742
+ if client is not None:
1743
+ client.close()
1744
+ raise
1745
+ return (server, client)
1746
+
1747
+
1748
+ @contextlib.contextmanager
1749
+ def create_sockets():
1750
+ """Open as many socket families / types as possible."""
1751
+ socks = []
1752
+ fname1 = fname2 = None
1753
+ try:
1754
+ socks.append(bind_socket(socket.AF_INET, socket.SOCK_STREAM))
1755
+ socks.append(bind_socket(socket.AF_INET, socket.SOCK_DGRAM))
1756
+ if supports_ipv6():
1757
+ socks.append(bind_socket(socket.AF_INET6, socket.SOCK_STREAM))
1758
+ socks.append(bind_socket(socket.AF_INET6, socket.SOCK_DGRAM))
1759
+ if POSIX and HAS_CONNECTIONS_UNIX:
1760
+ fname1 = get_testfn()
1761
+ fname2 = get_testfn()
1762
+ s1, s2 = unix_socketpair(fname1)
1763
+ s3 = bind_unix_socket(fname2, type=socket.SOCK_DGRAM)
1764
+ for s in (s1, s2, s3):
1765
+ socks.append(s)
1766
+ yield socks
1767
+ finally:
1768
+ for s in socks:
1769
+ s.close()
1770
+ for fname in (fname1, fname2):
1771
+ if fname is not None:
1772
+ safe_rmpath(fname)
1773
+
1774
+
1775
+ def check_net_address(addr, family):
1776
+ """Check a net address validity. Supported families are IPv4,
1777
+ IPv6 and MAC addresses.
1778
+ """
1779
+ import ipaddress # python >= 3.3 / requires "pip install ipaddress"
1780
+
1781
+ if enum and PY3 and not PYPY:
1782
+ assert isinstance(family, enum.IntEnum), family
1783
+ if family == socket.AF_INET:
1784
+ octs = [int(x) for x in addr.split('.')]
1785
+ assert len(octs) == 4, addr
1786
+ for num in octs:
1787
+ assert 0 <= num <= 255, addr
1788
+ if not PY3:
1789
+ addr = unicode(addr)
1790
+ ipaddress.IPv4Address(addr)
1791
+ elif family == socket.AF_INET6:
1792
+ assert isinstance(addr, str), addr
1793
+ if not PY3:
1794
+ addr = unicode(addr)
1795
+ ipaddress.IPv6Address(addr)
1796
+ elif family == psutil.AF_LINK:
1797
+ assert re.match(r'([a-fA-F0-9]{2}[:|\-]?){6}', addr) is not None, addr
1798
+ else:
1799
+ raise ValueError("unknown family %r" % family)
1800
+
1801
+
1802
+ def check_connection_ntuple(conn):
1803
+ """Check validity of a connection namedtuple."""
1804
+
1805
+ def check_ntuple(conn):
1806
+ has_pid = len(conn) == 7
1807
+ assert len(conn) in (6, 7), len(conn)
1808
+ assert conn[0] == conn.fd, conn.fd
1809
+ assert conn[1] == conn.family, conn.family
1810
+ assert conn[2] == conn.type, conn.type
1811
+ assert conn[3] == conn.laddr, conn.laddr
1812
+ assert conn[4] == conn.raddr, conn.raddr
1813
+ assert conn[5] == conn.status, conn.status
1814
+ if has_pid:
1815
+ assert conn[6] == conn.pid, conn.pid
1816
+
1817
+ def check_family(conn):
1818
+ assert conn.family in (AF_INET, AF_INET6, AF_UNIX), conn.family
1819
+ if enum is not None:
1820
+ assert isinstance(conn.family, enum.IntEnum), conn
1821
+ else:
1822
+ assert isinstance(conn.family, int), conn
1823
+ if conn.family == AF_INET:
1824
+ # actually try to bind the local socket; ignore IPv6
1825
+ # sockets as their address might be represented as
1826
+ # an IPv4-mapped-address (e.g. "::127.0.0.1")
1827
+ # and that's rejected by bind()
1828
+ s = socket.socket(conn.family, conn.type)
1829
+ with contextlib.closing(s):
1830
+ try:
1831
+ s.bind((conn.laddr[0], 0))
1832
+ except socket.error as err:
1833
+ if err.errno != errno.EADDRNOTAVAIL:
1834
+ raise
1835
+ elif conn.family == AF_UNIX:
1836
+ assert conn.status == psutil.CONN_NONE, conn.status
1837
+
1838
+ def check_type(conn):
1839
+ # SOCK_SEQPACKET may happen in case of AF_UNIX socks
1840
+ SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object())
1841
+ assert conn.type in (
1842
+ socket.SOCK_STREAM,
1843
+ socket.SOCK_DGRAM,
1844
+ SOCK_SEQPACKET,
1845
+ ), conn.type
1846
+ if enum is not None:
1847
+ assert isinstance(conn.type, enum.IntEnum), conn
1848
+ else:
1849
+ assert isinstance(conn.type, int), conn
1850
+ if conn.type == socket.SOCK_DGRAM:
1851
+ assert conn.status == psutil.CONN_NONE, conn.status
1852
+
1853
+ def check_addrs(conn):
1854
+ # check IP address and port sanity
1855
+ for addr in (conn.laddr, conn.raddr):
1856
+ if conn.family in (AF_INET, AF_INET6):
1857
+ assert isinstance(addr, tuple), type(addr)
1858
+ if not addr:
1859
+ continue
1860
+ assert isinstance(addr.port, int), type(addr.port)
1861
+ assert 0 <= addr.port <= 65535, addr.port
1862
+ check_net_address(addr.ip, conn.family)
1863
+ elif conn.family == AF_UNIX:
1864
+ assert isinstance(addr, str), type(addr)
1865
+
1866
+ def check_status(conn):
1867
+ assert isinstance(conn.status, str), conn.status
1868
+ valids = [
1869
+ getattr(psutil, x) for x in dir(psutil) if x.startswith('CONN_')
1870
+ ]
1871
+ assert conn.status in valids, conn.status
1872
+ if conn.family in (AF_INET, AF_INET6) and conn.type == SOCK_STREAM:
1873
+ assert conn.status != psutil.CONN_NONE, conn.status
1874
+ else:
1875
+ assert conn.status == psutil.CONN_NONE, conn.status
1876
+
1877
+ check_ntuple(conn)
1878
+ check_family(conn)
1879
+ check_type(conn)
1880
+ check_addrs(conn)
1881
+ check_status(conn)
1882
+
1883
+
1884
+ def filter_proc_connections(cons):
1885
+ """Our process may start with some open UNIX sockets which are not
1886
+ initialized by us, invalidating unit tests.
1887
+ """
1888
+ new = []
1889
+ for conn in cons:
1890
+ if POSIX and conn.family == socket.AF_UNIX:
1891
+ if MACOS and "/syslog" in conn.raddr:
1892
+ debug("skipping %s" % str(conn))
1893
+ continue
1894
+ new.append(conn)
1895
+ return new
1896
+
1897
+
1898
+ # ===================================================================
1899
+ # --- compatibility
1900
+ # ===================================================================
1901
+
1902
+
1903
+ def reload_module(module):
1904
+ """Backport of importlib.reload of Python 3.3+."""
1905
+ try:
1906
+ import importlib
1907
+
1908
+ if not hasattr(importlib, 'reload'): # python <=3.3
1909
+ raise ImportError
1910
+ except ImportError:
1911
+ import imp
1912
+
1913
+ return imp.reload(module)
1914
+ else:
1915
+ return importlib.reload(module)
1916
+
1917
+
1918
+ def import_module_by_path(path):
1919
+ name = os.path.splitext(os.path.basename(path))[0]
1920
+ if sys.version_info[0] < 3:
1921
+ import imp
1922
+
1923
+ return imp.load_source(name, path)
1924
+ else:
1925
+ import importlib.util
1926
+
1927
+ spec = importlib.util.spec_from_file_location(name, path)
1928
+ mod = importlib.util.module_from_spec(spec)
1929
+ spec.loader.exec_module(mod)
1930
+ return mod
1931
+
1932
+
1933
+ # ===================================================================
1934
+ # --- others
1935
+ # ===================================================================
1936
+
1937
+
1938
+ def warn(msg):
1939
+ """Raise a warning msg."""
1940
+ warnings.warn(msg, UserWarning, stacklevel=2)
1941
+
1942
+
1943
+ def is_namedtuple(x):
1944
+ """Check if object is an instance of namedtuple."""
1945
+ t = type(x)
1946
+ b = t.__bases__
1947
+ if len(b) != 1 or b[0] != tuple:
1948
+ return False
1949
+ f = getattr(t, '_fields', None)
1950
+ if not isinstance(f, tuple):
1951
+ return False
1952
+ return all(isinstance(n, str) for n in f)
1953
+
1954
+
1955
+ if POSIX:
1956
+
1957
+ @contextlib.contextmanager
1958
+ def copyload_shared_lib(suffix=""):
1959
+ """Ctx manager which picks up a random shared CO lib used
1960
+ by this process, copies it in another location and loads it
1961
+ in memory via ctypes. Return the new absolutized path.
1962
+ """
1963
+ exe = 'pypy' if PYPY else 'python'
1964
+ ext = ".so"
1965
+ dst = get_testfn(suffix=suffix + ext)
1966
+ libs = [
1967
+ x.path
1968
+ for x in psutil.Process().memory_maps()
1969
+ if os.path.splitext(x.path)[1] == ext and exe in x.path.lower()
1970
+ ]
1971
+ src = random.choice(libs)
1972
+ shutil.copyfile(src, dst)
1973
+ try:
1974
+ ctypes.CDLL(dst)
1975
+ yield dst
1976
+ finally:
1977
+ safe_rmpath(dst)
1978
+
1979
+ else:
1980
+
1981
+ @contextlib.contextmanager
1982
+ def copyload_shared_lib(suffix=""):
1983
+ """Ctx manager which picks up a random shared DLL lib used
1984
+ by this process, copies it in another location and loads it
1985
+ in memory via ctypes.
1986
+ Return the new absolutized, normcased path.
1987
+ """
1988
+ from ctypes import WinError
1989
+ from ctypes import wintypes
1990
+
1991
+ ext = ".dll"
1992
+ dst = get_testfn(suffix=suffix + ext)
1993
+ libs = [
1994
+ x.path
1995
+ for x in psutil.Process().memory_maps()
1996
+ if x.path.lower().endswith(ext)
1997
+ and 'python' in os.path.basename(x.path).lower()
1998
+ and 'wow64' not in x.path.lower()
1999
+ ]
2000
+ if PYPY and not libs:
2001
+ libs = [
2002
+ x.path
2003
+ for x in psutil.Process().memory_maps()
2004
+ if 'pypy' in os.path.basename(x.path).lower()
2005
+ ]
2006
+ src = random.choice(libs)
2007
+ shutil.copyfile(src, dst)
2008
+ cfile = None
2009
+ try:
2010
+ cfile = ctypes.WinDLL(dst)
2011
+ yield dst
2012
+ finally:
2013
+ # Work around OverflowError:
2014
+ # - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
2015
+ # job/o53330pbnri9bcw7
2016
+ # - http://bugs.python.org/issue30286
2017
+ # - http://stackoverflow.com/questions/23522055
2018
+ if cfile is not None:
2019
+ FreeLibrary = ctypes.windll.kernel32.FreeLibrary
2020
+ FreeLibrary.argtypes = [wintypes.HMODULE]
2021
+ ret = FreeLibrary(cfile._handle)
2022
+ if ret == 0:
2023
+ WinError()
2024
+ safe_rmpath(dst)
2025
+
2026
+
2027
+ # ===================================================================
2028
+ # --- Exit funs (first is executed last)
2029
+ # ===================================================================
2030
+
2031
+
2032
+ # this is executed first
2033
+ @atexit.register
2034
+ def cleanup_test_procs():
2035
+ reap_children(recursive=True)
2036
+
2037
+
2038
+ # atexit module does not execute exit functions in case of SIGTERM, which
2039
+ # gets sent to test subprocesses, which is a problem if they import this
2040
+ # module. With this it will. See:
2041
+ # https://gmpy.dev/blog/2016/how-to-always-execute-exit-functions-in-python
2042
+ if POSIX:
2043
+ signal.signal(signal.SIGTERM, lambda sig, _: sys.exit(sig))
venv/lib/python3.10/site-packages/psutil/tests/__main__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Run unit tests. This is invoked by:
6
+ $ python -m psutil.tests.
7
+ """
8
+
9
+ from .runner import main
10
+
11
+
12
+ main()
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (53.2 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (302 Bytes). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/runner.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_aix.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_bsd.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_connections.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_contracts.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_linux.cpython-310.pyc ADDED
Binary file (73.9 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_memleaks.cpython-310.pyc ADDED
Binary file (22.4 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_misc.cpython-310.pyc ADDED
Binary file (29.8 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_osx.cpython-310.pyc ADDED
Binary file (6.59 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_posix.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_process.cpython-310.pyc ADDED
Binary file (49.2 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_process_all.cpython-310.pyc ADDED
Binary file (14.1 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_sunos.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_system.cpython-310.pyc ADDED
Binary file (28.7 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_testutils.cpython-310.pyc ADDED
Binary file (17.3 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_unicode.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/__pycache__/test_windows.cpython-310.pyc ADDED
Binary file (30.7 kB). View file
 
venv/lib/python3.10/site-packages/psutil/tests/runner.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Unit test runner, providing new features on top of unittest module:
8
+ - colourized output
9
+ - parallel run (UNIX only)
10
+ - print failures/tracebacks on CTRL+C
11
+ - re-run failed tests only (make test-failed).
12
+
13
+ Invocation examples:
14
+ - make test
15
+ - make test-failed
16
+
17
+ Parallel:
18
+ - make test-parallel
19
+ - make test-process ARGS=--parallel
20
+ """
21
+
22
+ from __future__ import print_function
23
+
24
+ import atexit
25
+ import optparse
26
+ import os
27
+ import sys
28
+ import textwrap
29
+ import time
30
+ import unittest
31
+
32
+
33
+ try:
34
+ import ctypes
35
+ except ImportError:
36
+ ctypes = None
37
+
38
+ try:
39
+ import concurrencytest # pip install concurrencytest
40
+ except ImportError:
41
+ concurrencytest = None
42
+
43
+ import psutil
44
+ from psutil._common import hilite
45
+ from psutil._common import print_color
46
+ from psutil._common import term_supports_colors
47
+ from psutil._compat import super
48
+ from psutil.tests import CI_TESTING
49
+ from psutil.tests import import_module_by_path
50
+ from psutil.tests import print_sysinfo
51
+ from psutil.tests import reap_children
52
+ from psutil.tests import safe_rmpath
53
+
54
+
55
+ VERBOSITY = 2
56
+ FAILED_TESTS_FNAME = '.failed-tests.txt'
57
+ NWORKERS = psutil.cpu_count() or 1
58
+ USE_COLORS = not CI_TESTING and term_supports_colors()
59
+
60
+ HERE = os.path.abspath(os.path.dirname(__file__))
61
+ loadTestsFromTestCase = ( # noqa: N816
62
+ unittest.defaultTestLoader.loadTestsFromTestCase
63
+ )
64
+
65
+
66
+ def cprint(msg, color, bold=False, file=None):
67
+ if file is None:
68
+ file = sys.stderr if color == 'red' else sys.stdout
69
+ if USE_COLORS:
70
+ print_color(msg, color, bold=bold, file=file)
71
+ else:
72
+ print(msg, file=file)
73
+
74
+
75
+ class TestLoader:
76
+
77
+ testdir = HERE
78
+ skip_files = ['test_memleaks.py']
79
+ if "WHEELHOUSE_UPLOADER_USERNAME" in os.environ:
80
+ skip_files.extend(['test_osx.py', 'test_linux.py', 'test_posix.py'])
81
+
82
+ def _get_testmods(self):
83
+ return [
84
+ os.path.join(self.testdir, x)
85
+ for x in os.listdir(self.testdir)
86
+ if x.startswith('test_')
87
+ and x.endswith('.py')
88
+ and x not in self.skip_files
89
+ ]
90
+
91
+ def _iter_testmod_classes(self):
92
+ """Iterate over all test files in this directory and return
93
+ all TestCase classes in them.
94
+ """
95
+ for path in self._get_testmods():
96
+ mod = import_module_by_path(path)
97
+ for name in dir(mod):
98
+ obj = getattr(mod, name)
99
+ if isinstance(obj, type) and issubclass(
100
+ obj, unittest.TestCase
101
+ ):
102
+ yield obj
103
+
104
+ def all(self):
105
+ suite = unittest.TestSuite()
106
+ for obj in self._iter_testmod_classes():
107
+ test = loadTestsFromTestCase(obj)
108
+ suite.addTest(test)
109
+ return suite
110
+
111
+ def last_failed(self):
112
+ # ...from previously failed test run
113
+ suite = unittest.TestSuite()
114
+ if not os.path.isfile(FAILED_TESTS_FNAME):
115
+ return suite
116
+ with open(FAILED_TESTS_FNAME) as f:
117
+ names = f.read().split()
118
+ for n in names:
119
+ test = unittest.defaultTestLoader.loadTestsFromName(n)
120
+ suite.addTest(test)
121
+ return suite
122
+
123
+ def from_name(self, name):
124
+ if name.endswith('.py'):
125
+ name = os.path.splitext(os.path.basename(name))[0]
126
+ return unittest.defaultTestLoader.loadTestsFromName(name)
127
+
128
+
129
+ class ColouredResult(unittest.TextTestResult):
130
+ def addSuccess(self, test):
131
+ unittest.TestResult.addSuccess(self, test)
132
+ cprint("OK", "green")
133
+
134
+ def addError(self, test, err):
135
+ unittest.TestResult.addError(self, test, err)
136
+ cprint("ERROR", "red", bold=True)
137
+
138
+ def addFailure(self, test, err):
139
+ unittest.TestResult.addFailure(self, test, err)
140
+ cprint("FAIL", "red")
141
+
142
+ def addSkip(self, test, reason):
143
+ unittest.TestResult.addSkip(self, test, reason)
144
+ cprint("skipped: %s" % reason.strip(), "brown")
145
+
146
+ def printErrorList(self, flavour, errors):
147
+ flavour = hilite(flavour, "red", bold=flavour == 'ERROR')
148
+ super().printErrorList(flavour, errors)
149
+
150
+
151
+ class ColouredTextRunner(unittest.TextTestRunner):
152
+ """A coloured text runner which also prints failed tests on
153
+ KeyboardInterrupt and save failed tests in a file so that they can
154
+ be re-run.
155
+ """
156
+
157
+ resultclass = ColouredResult if USE_COLORS else unittest.TextTestResult
158
+
159
+ def __init__(self, *args, **kwargs):
160
+ super().__init__(*args, **kwargs)
161
+ self.failed_tnames = set()
162
+
163
+ def _makeResult(self):
164
+ # Store result instance so that it can be accessed on
165
+ # KeyboardInterrupt.
166
+ self.result = super()._makeResult()
167
+ return self.result
168
+
169
+ def _write_last_failed(self):
170
+ if self.failed_tnames:
171
+ with open(FAILED_TESTS_FNAME, "w") as f:
172
+ for tname in self.failed_tnames:
173
+ f.write(tname + '\n')
174
+
175
+ def _save_result(self, result):
176
+ if not result.wasSuccessful():
177
+ for t in result.errors + result.failures:
178
+ tname = t[0].id()
179
+ self.failed_tnames.add(tname)
180
+
181
+ def _run(self, suite):
182
+ try:
183
+ result = super().run(suite)
184
+ except (KeyboardInterrupt, SystemExit):
185
+ result = self.runner.result
186
+ result.printErrors()
187
+ raise sys.exit(1)
188
+ else:
189
+ self._save_result(result)
190
+ return result
191
+
192
+ def _exit(self, success):
193
+ if success:
194
+ cprint("SUCCESS", "green", bold=True)
195
+ safe_rmpath(FAILED_TESTS_FNAME)
196
+ sys.exit(0)
197
+ else:
198
+ cprint("FAILED", "red", bold=True)
199
+ self._write_last_failed()
200
+ sys.exit(1)
201
+
202
+ def run(self, suite):
203
+ result = self._run(suite)
204
+ self._exit(result.wasSuccessful())
205
+
206
+
207
+ class ParallelRunner(ColouredTextRunner):
208
+ @staticmethod
209
+ def _parallelize(suite):
210
+ def fdopen(fd, mode, *kwds):
211
+ stream = orig_fdopen(fd, mode)
212
+ atexit.register(stream.close)
213
+ return stream
214
+
215
+ # Monkey patch concurrencytest lib bug (fdopen() stream not closed).
216
+ # https://github.com/cgoldberg/concurrencytest/issues/11
217
+ orig_fdopen = os.fdopen
218
+ concurrencytest.os.fdopen = fdopen
219
+ forker = concurrencytest.fork_for_tests(NWORKERS)
220
+ return concurrencytest.ConcurrentTestSuite(suite, forker)
221
+
222
+ @staticmethod
223
+ def _split_suite(suite):
224
+ serial = unittest.TestSuite()
225
+ parallel = unittest.TestSuite()
226
+ for test in suite:
227
+ if test.countTestCases() == 0:
228
+ continue
229
+ if isinstance(test, unittest.TestSuite):
230
+ test_class = test._tests[0].__class__
231
+ elif isinstance(test, unittest.TestCase):
232
+ test_class = test
233
+ else:
234
+ raise TypeError("can't recognize type %r" % test)
235
+
236
+ if getattr(test_class, '_serialrun', False):
237
+ serial.addTest(test)
238
+ else:
239
+ parallel.addTest(test)
240
+ return (serial, parallel)
241
+
242
+ def run(self, suite):
243
+ ser_suite, par_suite = self._split_suite(suite)
244
+ par_suite = self._parallelize(par_suite)
245
+
246
+ # run parallel
247
+ cprint(
248
+ "starting parallel tests using %s workers" % NWORKERS,
249
+ "green",
250
+ bold=True,
251
+ )
252
+ t = time.time()
253
+ par = self._run(par_suite)
254
+ par_elapsed = time.time() - t
255
+
256
+ # At this point we should have N zombies (the workers), which
257
+ # will disappear with wait().
258
+ orphans = psutil.Process().children()
259
+ gone, alive = psutil.wait_procs(orphans, timeout=1)
260
+ if alive:
261
+ cprint("alive processes %s" % alive, "red")
262
+ reap_children()
263
+
264
+ # run serial
265
+ t = time.time()
266
+ ser = self._run(ser_suite)
267
+ ser_elapsed = time.time() - t
268
+
269
+ # print
270
+ if not par.wasSuccessful() and ser_suite.countTestCases() > 0:
271
+ par.printErrors() # print them again at the bottom
272
+ par_fails, par_errs, par_skips = map(
273
+ len, (par.failures, par.errors, par.skipped)
274
+ )
275
+ ser_fails, ser_errs, ser_skips = map(
276
+ len, (ser.failures, ser.errors, ser.skipped)
277
+ )
278
+ print(
279
+ textwrap.dedent(
280
+ """
281
+ +----------+----------+----------+----------+----------+----------+
282
+ | | total | failures | errors | skipped | time |
283
+ +----------+----------+----------+----------+----------+----------+
284
+ | parallel | %3s | %3s | %3s | %3s | %.2fs |
285
+ +----------+----------+----------+----------+----------+----------+
286
+ | serial | %3s | %3s | %3s | %3s | %.2fs |
287
+ +----------+----------+----------+----------+----------+----------+
288
+ """
289
+ % (
290
+ par.testsRun,
291
+ par_fails,
292
+ par_errs,
293
+ par_skips,
294
+ par_elapsed,
295
+ ser.testsRun,
296
+ ser_fails,
297
+ ser_errs,
298
+ ser_skips,
299
+ ser_elapsed,
300
+ )
301
+ )
302
+ )
303
+ print(
304
+ "Ran %s tests in %.3fs using %s workers"
305
+ % (
306
+ par.testsRun + ser.testsRun,
307
+ par_elapsed + ser_elapsed,
308
+ NWORKERS,
309
+ )
310
+ )
311
+ ok = par.wasSuccessful() and ser.wasSuccessful()
312
+ self._exit(ok)
313
+
314
+
315
+ def get_runner(parallel=False):
316
+ def warn(msg):
317
+ cprint(msg + " Running serial tests instead.", "red")
318
+
319
+ if parallel:
320
+ if psutil.WINDOWS:
321
+ warn("Can't run parallel tests on Windows.")
322
+ elif concurrencytest is None:
323
+ warn("concurrencytest module is not installed.")
324
+ elif NWORKERS == 1:
325
+ warn("Only 1 CPU available.")
326
+ else:
327
+ return ParallelRunner(verbosity=VERBOSITY)
328
+ return ColouredTextRunner(verbosity=VERBOSITY)
329
+
330
+
331
+ # Used by test_*,py modules.
332
+ def run_from_name(name):
333
+ if CI_TESTING:
334
+ print_sysinfo()
335
+ suite = TestLoader().from_name(name)
336
+ runner = get_runner()
337
+ runner.run(suite)
338
+
339
+
340
+ def setup():
341
+ psutil._set_debug(True)
342
+
343
+
344
+ def main():
345
+ setup()
346
+ usage = "python3 -m psutil.tests [opts] [test-name]"
347
+ parser = optparse.OptionParser(usage=usage, description="run unit tests")
348
+ parser.add_option(
349
+ "--last-failed",
350
+ action="store_true",
351
+ default=False,
352
+ help="only run last failed tests",
353
+ )
354
+ parser.add_option(
355
+ "--parallel",
356
+ action="store_true",
357
+ default=False,
358
+ help="run tests in parallel",
359
+ )
360
+ opts, args = parser.parse_args()
361
+
362
+ if not opts.last_failed:
363
+ safe_rmpath(FAILED_TESTS_FNAME)
364
+
365
+ # loader
366
+ loader = TestLoader()
367
+ if args:
368
+ if len(args) > 1:
369
+ parser.print_usage()
370
+ return sys.exit(1)
371
+ else:
372
+ suite = loader.from_name(args[0])
373
+ elif opts.last_failed:
374
+ suite = loader.last_failed()
375
+ else:
376
+ suite = loader.all()
377
+
378
+ if CI_TESTING:
379
+ print_sysinfo()
380
+ runner = get_runner(opts.parallel)
381
+ runner.run(suite)
382
+
383
+
384
+ if __name__ == '__main__':
385
+ main()
venv/lib/python3.10/site-packages/psutil/tests/test_connections.py ADDED
@@ -0,0 +1,576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Tests for net_connections() and Process.connections() APIs."""
8
+
9
+ import os
10
+ import socket
11
+ import textwrap
12
+ import unittest
13
+ from contextlib import closing
14
+ from socket import AF_INET
15
+ from socket import AF_INET6
16
+ from socket import SOCK_DGRAM
17
+ from socket import SOCK_STREAM
18
+
19
+ import psutil
20
+ from psutil import FREEBSD
21
+ from psutil import LINUX
22
+ from psutil import MACOS
23
+ from psutil import NETBSD
24
+ from psutil import OPENBSD
25
+ from psutil import POSIX
26
+ from psutil import SUNOS
27
+ from psutil import WINDOWS
28
+ from psutil._common import supports_ipv6
29
+ from psutil._compat import PY3
30
+ from psutil.tests import AF_UNIX
31
+ from psutil.tests import HAS_CONNECTIONS_UNIX
32
+ from psutil.tests import SKIP_SYSCONS
33
+ from psutil.tests import PsutilTestCase
34
+ from psutil.tests import bind_socket
35
+ from psutil.tests import bind_unix_socket
36
+ from psutil.tests import check_connection_ntuple
37
+ from psutil.tests import create_sockets
38
+ from psutil.tests import filter_proc_connections
39
+ from psutil.tests import reap_children
40
+ from psutil.tests import retry_on_failure
41
+ from psutil.tests import serialrun
42
+ from psutil.tests import skip_on_access_denied
43
+ from psutil.tests import tcp_socketpair
44
+ from psutil.tests import unix_socketpair
45
+ from psutil.tests import wait_for_file
46
+
47
+
48
+ SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object())
49
+
50
+
51
+ def this_proc_connections(kind):
52
+ cons = psutil.Process().connections(kind=kind)
53
+ if kind in ("all", "unix"):
54
+ return filter_proc_connections(cons)
55
+ return cons
56
+
57
+
58
+ @serialrun
59
+ class ConnectionTestCase(PsutilTestCase):
60
+ def setUp(self):
61
+ self.assertEqual(this_proc_connections(kind='all'), [])
62
+
63
+ def tearDown(self):
64
+ # Make sure we closed all resources.
65
+ self.assertEqual(this_proc_connections(kind='all'), [])
66
+
67
+ def compare_procsys_connections(self, pid, proc_cons, kind='all'):
68
+ """Given a process PID and its list of connections compare
69
+ those against system-wide connections retrieved via
70
+ psutil.net_connections.
71
+ """
72
+ try:
73
+ sys_cons = psutil.net_connections(kind=kind)
74
+ except psutil.AccessDenied:
75
+ # On MACOS, system-wide connections are retrieved by iterating
76
+ # over all processes
77
+ if MACOS:
78
+ return
79
+ else:
80
+ raise
81
+ # Filter for this proc PID and exlucde PIDs from the tuple.
82
+ sys_cons = [c[:-1] for c in sys_cons if c.pid == pid]
83
+ sys_cons.sort()
84
+ proc_cons.sort()
85
+ self.assertEqual(proc_cons, sys_cons)
86
+
87
+
88
+ class TestBasicOperations(ConnectionTestCase):
89
+ @unittest.skipIf(SKIP_SYSCONS, "requires root")
90
+ def test_system(self):
91
+ with create_sockets():
92
+ for conn in psutil.net_connections(kind='all'):
93
+ check_connection_ntuple(conn)
94
+
95
+ def test_process(self):
96
+ with create_sockets():
97
+ for conn in this_proc_connections(kind='all'):
98
+ check_connection_ntuple(conn)
99
+
100
+ def test_invalid_kind(self):
101
+ self.assertRaises(ValueError, this_proc_connections, kind='???')
102
+ self.assertRaises(ValueError, psutil.net_connections, kind='???')
103
+
104
+
105
+ @serialrun
106
+ class TestUnconnectedSockets(ConnectionTestCase):
107
+ """Tests sockets which are open but not connected to anything."""
108
+
109
+ def get_conn_from_sock(self, sock):
110
+ cons = this_proc_connections(kind='all')
111
+ smap = dict([(c.fd, c) for c in cons])
112
+ if NETBSD or FREEBSD:
113
+ # NetBSD opens a UNIX socket to /var/log/run
114
+ # so there may be more connections.
115
+ return smap[sock.fileno()]
116
+ else:
117
+ self.assertEqual(len(cons), 1)
118
+ if cons[0].fd != -1:
119
+ self.assertEqual(smap[sock.fileno()].fd, sock.fileno())
120
+ return cons[0]
121
+
122
+ def check_socket(self, sock):
123
+ """Given a socket, makes sure it matches the one obtained
124
+ via psutil. It assumes this process created one connection
125
+ only (the one supposed to be checked).
126
+ """
127
+ conn = self.get_conn_from_sock(sock)
128
+ check_connection_ntuple(conn)
129
+
130
+ # fd, family, type
131
+ if conn.fd != -1:
132
+ self.assertEqual(conn.fd, sock.fileno())
133
+ self.assertEqual(conn.family, sock.family)
134
+ # see: http://bugs.python.org/issue30204
135
+ self.assertEqual(
136
+ conn.type, sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
137
+ )
138
+
139
+ # local address
140
+ laddr = sock.getsockname()
141
+ if not laddr and PY3 and isinstance(laddr, bytes):
142
+ # See: http://bugs.python.org/issue30205
143
+ laddr = laddr.decode()
144
+ if sock.family == AF_INET6:
145
+ laddr = laddr[:2]
146
+ self.assertEqual(conn.laddr, laddr)
147
+
148
+ # XXX Solaris can't retrieve system-wide UNIX sockets
149
+ if sock.family == AF_UNIX and HAS_CONNECTIONS_UNIX:
150
+ cons = this_proc_connections(kind='all')
151
+ self.compare_procsys_connections(os.getpid(), cons, kind='all')
152
+ return conn
153
+
154
+ def test_tcp_v4(self):
155
+ addr = ("127.0.0.1", 0)
156
+ with closing(bind_socket(AF_INET, SOCK_STREAM, addr=addr)) as sock:
157
+ conn = self.check_socket(sock)
158
+ self.assertEqual(conn.raddr, ())
159
+ self.assertEqual(conn.status, psutil.CONN_LISTEN)
160
+
161
+ @unittest.skipIf(not supports_ipv6(), "IPv6 not supported")
162
+ def test_tcp_v6(self):
163
+ addr = ("::1", 0)
164
+ with closing(bind_socket(AF_INET6, SOCK_STREAM, addr=addr)) as sock:
165
+ conn = self.check_socket(sock)
166
+ self.assertEqual(conn.raddr, ())
167
+ self.assertEqual(conn.status, psutil.CONN_LISTEN)
168
+
169
+ def test_udp_v4(self):
170
+ addr = ("127.0.0.1", 0)
171
+ with closing(bind_socket(AF_INET, SOCK_DGRAM, addr=addr)) as sock:
172
+ conn = self.check_socket(sock)
173
+ self.assertEqual(conn.raddr, ())
174
+ self.assertEqual(conn.status, psutil.CONN_NONE)
175
+
176
+ @unittest.skipIf(not supports_ipv6(), "IPv6 not supported")
177
+ def test_udp_v6(self):
178
+ addr = ("::1", 0)
179
+ with closing(bind_socket(AF_INET6, SOCK_DGRAM, addr=addr)) as sock:
180
+ conn = self.check_socket(sock)
181
+ self.assertEqual(conn.raddr, ())
182
+ self.assertEqual(conn.status, psutil.CONN_NONE)
183
+
184
+ @unittest.skipIf(not POSIX, 'POSIX only')
185
+ def test_unix_tcp(self):
186
+ testfn = self.get_testfn()
187
+ with closing(bind_unix_socket(testfn, type=SOCK_STREAM)) as sock:
188
+ conn = self.check_socket(sock)
189
+ self.assertEqual(conn.raddr, "")
190
+ self.assertEqual(conn.status, psutil.CONN_NONE)
191
+
192
+ @unittest.skipIf(not POSIX, 'POSIX only')
193
+ def test_unix_udp(self):
194
+ testfn = self.get_testfn()
195
+ with closing(bind_unix_socket(testfn, type=SOCK_STREAM)) as sock:
196
+ conn = self.check_socket(sock)
197
+ self.assertEqual(conn.raddr, "")
198
+ self.assertEqual(conn.status, psutil.CONN_NONE)
199
+
200
+
201
+ @serialrun
202
+ class TestConnectedSocket(ConnectionTestCase):
203
+ """Test socket pairs which are actually connected to
204
+ each other.
205
+ """
206
+
207
+ # On SunOS, even after we close() it, the server socket stays around
208
+ # in TIME_WAIT state.
209
+ @unittest.skipIf(SUNOS, "unreliable on SUONS")
210
+ def test_tcp(self):
211
+ addr = ("127.0.0.1", 0)
212
+ self.assertEqual(this_proc_connections(kind='tcp4'), [])
213
+ server, client = tcp_socketpair(AF_INET, addr=addr)
214
+ try:
215
+ cons = this_proc_connections(kind='tcp4')
216
+ self.assertEqual(len(cons), 2)
217
+ self.assertEqual(cons[0].status, psutil.CONN_ESTABLISHED)
218
+ self.assertEqual(cons[1].status, psutil.CONN_ESTABLISHED)
219
+ # May not be fast enough to change state so it stays
220
+ # commenteed.
221
+ # client.close()
222
+ # cons = this_proc_connections(kind='all')
223
+ # self.assertEqual(len(cons), 1)
224
+ # self.assertEqual(cons[0].status, psutil.CONN_CLOSE_WAIT)
225
+ finally:
226
+ server.close()
227
+ client.close()
228
+
229
+ @unittest.skipIf(not POSIX, 'POSIX only')
230
+ def test_unix(self):
231
+ testfn = self.get_testfn()
232
+ server, client = unix_socketpair(testfn)
233
+ try:
234
+ cons = this_proc_connections(kind='unix')
235
+ assert not (cons[0].laddr and cons[0].raddr), cons
236
+ assert not (cons[1].laddr and cons[1].raddr), cons
237
+ if NETBSD or FREEBSD:
238
+ # On NetBSD creating a UNIX socket will cause
239
+ # a UNIX connection to /var/run/log.
240
+ cons = [c for c in cons if c.raddr != '/var/run/log']
241
+ self.assertEqual(len(cons), 2, msg=cons)
242
+ if LINUX or FREEBSD or SUNOS or OPENBSD:
243
+ # remote path is never set
244
+ self.assertEqual(cons[0].raddr, "")
245
+ self.assertEqual(cons[1].raddr, "")
246
+ # one local address should though
247
+ self.assertEqual(testfn, cons[0].laddr or cons[1].laddr)
248
+ else:
249
+ # On other systems either the laddr or raddr
250
+ # of both peers are set.
251
+ self.assertEqual(cons[0].laddr or cons[1].laddr, testfn)
252
+ finally:
253
+ server.close()
254
+ client.close()
255
+
256
+
257
+ class TestFilters(ConnectionTestCase):
258
+ def test_filters(self):
259
+ def check(kind, families, types):
260
+ for conn in this_proc_connections(kind=kind):
261
+ self.assertIn(conn.family, families)
262
+ self.assertIn(conn.type, types)
263
+ if not SKIP_SYSCONS:
264
+ for conn in psutil.net_connections(kind=kind):
265
+ self.assertIn(conn.family, families)
266
+ self.assertIn(conn.type, types)
267
+
268
+ with create_sockets():
269
+ check(
270
+ 'all',
271
+ [AF_INET, AF_INET6, AF_UNIX],
272
+ [SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET],
273
+ )
274
+ check('inet', [AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM])
275
+ check('inet4', [AF_INET], [SOCK_STREAM, SOCK_DGRAM])
276
+ check('tcp', [AF_INET, AF_INET6], [SOCK_STREAM])
277
+ check('tcp4', [AF_INET], [SOCK_STREAM])
278
+ check('tcp6', [AF_INET6], [SOCK_STREAM])
279
+ check('udp', [AF_INET, AF_INET6], [SOCK_DGRAM])
280
+ check('udp4', [AF_INET], [SOCK_DGRAM])
281
+ check('udp6', [AF_INET6], [SOCK_DGRAM])
282
+ if HAS_CONNECTIONS_UNIX:
283
+ check(
284
+ 'unix',
285
+ [AF_UNIX],
286
+ [SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET],
287
+ )
288
+
289
+ @skip_on_access_denied(only_if=MACOS)
290
+ def test_combos(self):
291
+ reap_children()
292
+
293
+ def check_conn(proc, conn, family, type, laddr, raddr, status, kinds):
294
+ all_kinds = (
295
+ "all",
296
+ "inet",
297
+ "inet4",
298
+ "inet6",
299
+ "tcp",
300
+ "tcp4",
301
+ "tcp6",
302
+ "udp",
303
+ "udp4",
304
+ "udp6",
305
+ )
306
+ check_connection_ntuple(conn)
307
+ self.assertEqual(conn.family, family)
308
+ self.assertEqual(conn.type, type)
309
+ self.assertEqual(conn.laddr, laddr)
310
+ self.assertEqual(conn.raddr, raddr)
311
+ self.assertEqual(conn.status, status)
312
+ for kind in all_kinds:
313
+ cons = proc.connections(kind=kind)
314
+ if kind in kinds:
315
+ self.assertNotEqual(cons, [])
316
+ else:
317
+ self.assertEqual(cons, [])
318
+ # compare against system-wide connections
319
+ # XXX Solaris can't retrieve system-wide UNIX
320
+ # sockets.
321
+ if HAS_CONNECTIONS_UNIX:
322
+ self.compare_procsys_connections(proc.pid, [conn])
323
+
324
+ tcp_template = textwrap.dedent("""
325
+ import socket, time
326
+ s = socket.socket({family}, socket.SOCK_STREAM)
327
+ s.bind(('{addr}', 0))
328
+ s.listen(5)
329
+ with open('{testfn}', 'w') as f:
330
+ f.write(str(s.getsockname()[:2]))
331
+ time.sleep(60)
332
+ """)
333
+
334
+ udp_template = textwrap.dedent("""
335
+ import socket, time
336
+ s = socket.socket({family}, socket.SOCK_DGRAM)
337
+ s.bind(('{addr}', 0))
338
+ with open('{testfn}', 'w') as f:
339
+ f.write(str(s.getsockname()[:2]))
340
+ time.sleep(60)
341
+ """)
342
+
343
+ # must be relative on Windows
344
+ testfile = os.path.basename(self.get_testfn(dir=os.getcwd()))
345
+ tcp4_template = tcp_template.format(
346
+ family=int(AF_INET), addr="127.0.0.1", testfn=testfile
347
+ )
348
+ udp4_template = udp_template.format(
349
+ family=int(AF_INET), addr="127.0.0.1", testfn=testfile
350
+ )
351
+ tcp6_template = tcp_template.format(
352
+ family=int(AF_INET6), addr="::1", testfn=testfile
353
+ )
354
+ udp6_template = udp_template.format(
355
+ family=int(AF_INET6), addr="::1", testfn=testfile
356
+ )
357
+
358
+ # launch various subprocess instantiating a socket of various
359
+ # families and types to enrich psutil results
360
+ tcp4_proc = self.pyrun(tcp4_template)
361
+ tcp4_addr = eval(wait_for_file(testfile, delete=True)) # noqa
362
+ udp4_proc = self.pyrun(udp4_template)
363
+ udp4_addr = eval(wait_for_file(testfile, delete=True)) # noqa
364
+ if supports_ipv6():
365
+ tcp6_proc = self.pyrun(tcp6_template)
366
+ tcp6_addr = eval(wait_for_file(testfile, delete=True)) # noqa
367
+ udp6_proc = self.pyrun(udp6_template)
368
+ udp6_addr = eval(wait_for_file(testfile, delete=True)) # noqa
369
+ else:
370
+ tcp6_proc = None
371
+ udp6_proc = None
372
+ tcp6_addr = None
373
+ udp6_addr = None
374
+
375
+ for p in psutil.Process().children():
376
+ cons = p.connections()
377
+ self.assertEqual(len(cons), 1)
378
+ for conn in cons:
379
+ # TCP v4
380
+ if p.pid == tcp4_proc.pid:
381
+ check_conn(
382
+ p,
383
+ conn,
384
+ AF_INET,
385
+ SOCK_STREAM,
386
+ tcp4_addr,
387
+ (),
388
+ psutil.CONN_LISTEN,
389
+ ("all", "inet", "inet4", "tcp", "tcp4"),
390
+ )
391
+ # UDP v4
392
+ elif p.pid == udp4_proc.pid:
393
+ check_conn(
394
+ p,
395
+ conn,
396
+ AF_INET,
397
+ SOCK_DGRAM,
398
+ udp4_addr,
399
+ (),
400
+ psutil.CONN_NONE,
401
+ ("all", "inet", "inet4", "udp", "udp4"),
402
+ )
403
+ # TCP v6
404
+ elif p.pid == getattr(tcp6_proc, "pid", None):
405
+ check_conn(
406
+ p,
407
+ conn,
408
+ AF_INET6,
409
+ SOCK_STREAM,
410
+ tcp6_addr,
411
+ (),
412
+ psutil.CONN_LISTEN,
413
+ ("all", "inet", "inet6", "tcp", "tcp6"),
414
+ )
415
+ # UDP v6
416
+ elif p.pid == getattr(udp6_proc, "pid", None):
417
+ check_conn(
418
+ p,
419
+ conn,
420
+ AF_INET6,
421
+ SOCK_DGRAM,
422
+ udp6_addr,
423
+ (),
424
+ psutil.CONN_NONE,
425
+ ("all", "inet", "inet6", "udp", "udp6"),
426
+ )
427
+
428
+ def test_count(self):
429
+ with create_sockets():
430
+ # tcp
431
+ cons = this_proc_connections(kind='tcp')
432
+ self.assertEqual(len(cons), 2 if supports_ipv6() else 1)
433
+ for conn in cons:
434
+ self.assertIn(conn.family, (AF_INET, AF_INET6))
435
+ self.assertEqual(conn.type, SOCK_STREAM)
436
+ # tcp4
437
+ cons = this_proc_connections(kind='tcp4')
438
+ self.assertEqual(len(cons), 1)
439
+ self.assertEqual(cons[0].family, AF_INET)
440
+ self.assertEqual(cons[0].type, SOCK_STREAM)
441
+ # tcp6
442
+ if supports_ipv6():
443
+ cons = this_proc_connections(kind='tcp6')
444
+ self.assertEqual(len(cons), 1)
445
+ self.assertEqual(cons[0].family, AF_INET6)
446
+ self.assertEqual(cons[0].type, SOCK_STREAM)
447
+ # udp
448
+ cons = this_proc_connections(kind='udp')
449
+ self.assertEqual(len(cons), 2 if supports_ipv6() else 1)
450
+ for conn in cons:
451
+ self.assertIn(conn.family, (AF_INET, AF_INET6))
452
+ self.assertEqual(conn.type, SOCK_DGRAM)
453
+ # udp4
454
+ cons = this_proc_connections(kind='udp4')
455
+ self.assertEqual(len(cons), 1)
456
+ self.assertEqual(cons[0].family, AF_INET)
457
+ self.assertEqual(cons[0].type, SOCK_DGRAM)
458
+ # udp6
459
+ if supports_ipv6():
460
+ cons = this_proc_connections(kind='udp6')
461
+ self.assertEqual(len(cons), 1)
462
+ self.assertEqual(cons[0].family, AF_INET6)
463
+ self.assertEqual(cons[0].type, SOCK_DGRAM)
464
+ # inet
465
+ cons = this_proc_connections(kind='inet')
466
+ self.assertEqual(len(cons), 4 if supports_ipv6() else 2)
467
+ for conn in cons:
468
+ self.assertIn(conn.family, (AF_INET, AF_INET6))
469
+ self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))
470
+ # inet6
471
+ if supports_ipv6():
472
+ cons = this_proc_connections(kind='inet6')
473
+ self.assertEqual(len(cons), 2)
474
+ for conn in cons:
475
+ self.assertEqual(conn.family, AF_INET6)
476
+ self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))
477
+ # Skipped on BSD becayse by default the Python process
478
+ # creates a UNIX socket to '/var/run/log'.
479
+ if HAS_CONNECTIONS_UNIX and not (FREEBSD or NETBSD):
480
+ cons = this_proc_connections(kind='unix')
481
+ self.assertEqual(len(cons), 3)
482
+ for conn in cons:
483
+ self.assertEqual(conn.family, AF_UNIX)
484
+ self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))
485
+
486
+
487
+ @unittest.skipIf(SKIP_SYSCONS, "requires root")
488
+ class TestSystemWideConnections(ConnectionTestCase):
489
+ """Tests for net_connections()."""
490
+
491
+ def test_it(self):
492
+ def check(cons, families, types_):
493
+ for conn in cons:
494
+ self.assertIn(conn.family, families, msg=conn)
495
+ if conn.family != AF_UNIX:
496
+ self.assertIn(conn.type, types_, msg=conn)
497
+ check_connection_ntuple(conn)
498
+
499
+ with create_sockets():
500
+ from psutil._common import conn_tmap
501
+
502
+ for kind, groups in conn_tmap.items():
503
+ # XXX: SunOS does not retrieve UNIX sockets.
504
+ if kind == 'unix' and not HAS_CONNECTIONS_UNIX:
505
+ continue
506
+ families, types_ = groups
507
+ cons = psutil.net_connections(kind)
508
+ self.assertEqual(len(cons), len(set(cons)))
509
+ check(cons, families, types_)
510
+
511
+ @retry_on_failure()
512
+ def test_multi_sockets_procs(self):
513
+ # Creates multiple sub processes, each creating different
514
+ # sockets. For each process check that proc.connections()
515
+ # and net_connections() return the same results.
516
+ # This is done mainly to check whether net_connections()'s
517
+ # pid is properly set, see:
518
+ # https://github.com/giampaolo/psutil/issues/1013
519
+ with create_sockets() as socks:
520
+ expected = len(socks)
521
+ pids = []
522
+ times = 10
523
+ fnames = []
524
+ for _ in range(times):
525
+ fname = self.get_testfn()
526
+ fnames.append(fname)
527
+ src = textwrap.dedent("""\
528
+ import time, os
529
+ from psutil.tests import create_sockets
530
+ with create_sockets():
531
+ with open(r'%s', 'w') as f:
532
+ f.write("hello")
533
+ time.sleep(60)
534
+ """ % fname)
535
+ sproc = self.pyrun(src)
536
+ pids.append(sproc.pid)
537
+
538
+ # sync
539
+ for fname in fnames:
540
+ wait_for_file(fname)
541
+
542
+ syscons = [
543
+ x for x in psutil.net_connections(kind='all') if x.pid in pids
544
+ ]
545
+ for pid in pids:
546
+ self.assertEqual(
547
+ len([x for x in syscons if x.pid == pid]), expected
548
+ )
549
+ p = psutil.Process(pid)
550
+ self.assertEqual(len(p.connections('all')), expected)
551
+
552
+
553
+ class TestMisc(PsutilTestCase):
554
+ def test_connection_constants(self):
555
+ ints = []
556
+ strs = []
557
+ for name in dir(psutil):
558
+ if name.startswith('CONN_'):
559
+ num = getattr(psutil, name)
560
+ str_ = str(num)
561
+ assert str_.isupper(), str_
562
+ self.assertNotIn(str, strs)
563
+ self.assertNotIn(num, ints)
564
+ ints.append(num)
565
+ strs.append(str_)
566
+ if SUNOS:
567
+ psutil.CONN_IDLE # noqa
568
+ psutil.CONN_BOUND # noqa
569
+ if WINDOWS:
570
+ psutil.CONN_DELETE_TCB # noqa
571
+
572
+
573
+ if __name__ == '__main__':
574
+ from psutil.tests.runner import run_from_name
575
+
576
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_contracts.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Contracts tests. These tests mainly check API sanity in terms of
8
+ returned types and APIs availability.
9
+ Some of these are duplicates of tests test_system.py and test_process.py.
10
+ """
11
+
12
+ import platform
13
+ import signal
14
+ import unittest
15
+
16
+ import psutil
17
+ from psutil import AIX
18
+ from psutil import FREEBSD
19
+ from psutil import LINUX
20
+ from psutil import MACOS
21
+ from psutil import NETBSD
22
+ from psutil import OPENBSD
23
+ from psutil import POSIX
24
+ from psutil import SUNOS
25
+ from psutil import WINDOWS
26
+ from psutil._compat import long
27
+ from psutil.tests import GITHUB_ACTIONS
28
+ from psutil.tests import HAS_CPU_FREQ
29
+ from psutil.tests import HAS_NET_IO_COUNTERS
30
+ from psutil.tests import HAS_SENSORS_FANS
31
+ from psutil.tests import HAS_SENSORS_TEMPERATURES
32
+ from psutil.tests import PYPY
33
+ from psutil.tests import SKIP_SYSCONS
34
+ from psutil.tests import PsutilTestCase
35
+ from psutil.tests import create_sockets
36
+ from psutil.tests import enum
37
+ from psutil.tests import is_namedtuple
38
+ from psutil.tests import kernel_version
39
+
40
+
41
+ # ===================================================================
42
+ # --- APIs availability
43
+ # ===================================================================
44
+
45
+ # Make sure code reflects what doc promises in terms of APIs
46
+ # availability.
47
+
48
+
49
+ class TestAvailConstantsAPIs(PsutilTestCase):
50
+ def test_PROCFS_PATH(self):
51
+ self.assertEqual(hasattr(psutil, "PROCFS_PATH"), LINUX or SUNOS or AIX)
52
+
53
+ def test_win_priority(self):
54
+ ae = self.assertEqual
55
+ ae(hasattr(psutil, "ABOVE_NORMAL_PRIORITY_CLASS"), WINDOWS)
56
+ ae(hasattr(psutil, "BELOW_NORMAL_PRIORITY_CLASS"), WINDOWS)
57
+ ae(hasattr(psutil, "HIGH_PRIORITY_CLASS"), WINDOWS)
58
+ ae(hasattr(psutil, "IDLE_PRIORITY_CLASS"), WINDOWS)
59
+ ae(hasattr(psutil, "NORMAL_PRIORITY_CLASS"), WINDOWS)
60
+ ae(hasattr(psutil, "REALTIME_PRIORITY_CLASS"), WINDOWS)
61
+
62
+ def test_linux_ioprio_linux(self):
63
+ ae = self.assertEqual
64
+ ae(hasattr(psutil, "IOPRIO_CLASS_NONE"), LINUX)
65
+ ae(hasattr(psutil, "IOPRIO_CLASS_RT"), LINUX)
66
+ ae(hasattr(psutil, "IOPRIO_CLASS_BE"), LINUX)
67
+ ae(hasattr(psutil, "IOPRIO_CLASS_IDLE"), LINUX)
68
+
69
+ def test_linux_ioprio_windows(self):
70
+ ae = self.assertEqual
71
+ ae(hasattr(psutil, "IOPRIO_HIGH"), WINDOWS)
72
+ ae(hasattr(psutil, "IOPRIO_NORMAL"), WINDOWS)
73
+ ae(hasattr(psutil, "IOPRIO_LOW"), WINDOWS)
74
+ ae(hasattr(psutil, "IOPRIO_VERYLOW"), WINDOWS)
75
+
76
+ @unittest.skipIf(
77
+ GITHUB_ACTIONS and LINUX, "unsupported on GITHUB_ACTIONS + LINUX"
78
+ )
79
+ def test_rlimit(self):
80
+ ae = self.assertEqual
81
+ ae(hasattr(psutil, "RLIM_INFINITY"), LINUX or FREEBSD)
82
+ ae(hasattr(psutil, "RLIMIT_AS"), LINUX or FREEBSD)
83
+ ae(hasattr(psutil, "RLIMIT_CORE"), LINUX or FREEBSD)
84
+ ae(hasattr(psutil, "RLIMIT_CPU"), LINUX or FREEBSD)
85
+ ae(hasattr(psutil, "RLIMIT_DATA"), LINUX or FREEBSD)
86
+ ae(hasattr(psutil, "RLIMIT_FSIZE"), LINUX or FREEBSD)
87
+ ae(hasattr(psutil, "RLIMIT_MEMLOCK"), LINUX or FREEBSD)
88
+ ae(hasattr(psutil, "RLIMIT_NOFILE"), LINUX or FREEBSD)
89
+ ae(hasattr(psutil, "RLIMIT_NPROC"), LINUX or FREEBSD)
90
+ ae(hasattr(psutil, "RLIMIT_RSS"), LINUX or FREEBSD)
91
+ ae(hasattr(psutil, "RLIMIT_STACK"), LINUX or FREEBSD)
92
+
93
+ ae(hasattr(psutil, "RLIMIT_LOCKS"), LINUX)
94
+ if POSIX:
95
+ if kernel_version() >= (2, 6, 8):
96
+ ae(hasattr(psutil, "RLIMIT_MSGQUEUE"), LINUX)
97
+ if kernel_version() >= (2, 6, 12):
98
+ ae(hasattr(psutil, "RLIMIT_NICE"), LINUX)
99
+ if kernel_version() >= (2, 6, 12):
100
+ ae(hasattr(psutil, "RLIMIT_RTPRIO"), LINUX)
101
+ if kernel_version() >= (2, 6, 25):
102
+ ae(hasattr(psutil, "RLIMIT_RTTIME"), LINUX)
103
+ if kernel_version() >= (2, 6, 8):
104
+ ae(hasattr(psutil, "RLIMIT_SIGPENDING"), LINUX)
105
+
106
+ ae(hasattr(psutil, "RLIMIT_SWAP"), FREEBSD)
107
+ ae(hasattr(psutil, "RLIMIT_SBSIZE"), FREEBSD)
108
+ ae(hasattr(psutil, "RLIMIT_NPTS"), FREEBSD)
109
+
110
+
111
+ class TestAvailSystemAPIs(PsutilTestCase):
112
+ def test_win_service_iter(self):
113
+ self.assertEqual(hasattr(psutil, "win_service_iter"), WINDOWS)
114
+
115
+ def test_win_service_get(self):
116
+ self.assertEqual(hasattr(psutil, "win_service_get"), WINDOWS)
117
+
118
+ def test_cpu_freq(self):
119
+ self.assertEqual(
120
+ hasattr(psutil, "cpu_freq"),
121
+ LINUX or MACOS or WINDOWS or FREEBSD or OPENBSD,
122
+ )
123
+
124
+ def test_sensors_temperatures(self):
125
+ self.assertEqual(
126
+ hasattr(psutil, "sensors_temperatures"), LINUX or FREEBSD
127
+ )
128
+
129
+ def test_sensors_fans(self):
130
+ self.assertEqual(hasattr(psutil, "sensors_fans"), LINUX)
131
+
132
+ def test_battery(self):
133
+ self.assertEqual(
134
+ hasattr(psutil, "sensors_battery"),
135
+ LINUX or WINDOWS or FREEBSD or MACOS,
136
+ )
137
+
138
+
139
+ class TestAvailProcessAPIs(PsutilTestCase):
140
+ def test_environ(self):
141
+ self.assertEqual(
142
+ hasattr(psutil.Process, "environ"),
143
+ LINUX
144
+ or MACOS
145
+ or WINDOWS
146
+ or AIX
147
+ or SUNOS
148
+ or FREEBSD
149
+ or OPENBSD
150
+ or NETBSD,
151
+ )
152
+
153
+ def test_uids(self):
154
+ self.assertEqual(hasattr(psutil.Process, "uids"), POSIX)
155
+
156
+ def test_gids(self):
157
+ self.assertEqual(hasattr(psutil.Process, "uids"), POSIX)
158
+
159
+ def test_terminal(self):
160
+ self.assertEqual(hasattr(psutil.Process, "terminal"), POSIX)
161
+
162
+ def test_ionice(self):
163
+ self.assertEqual(hasattr(psutil.Process, "ionice"), LINUX or WINDOWS)
164
+
165
+ @unittest.skipIf(
166
+ GITHUB_ACTIONS and LINUX, "unsupported on GITHUB_ACTIONS + LINUX"
167
+ )
168
+ def test_rlimit(self):
169
+ self.assertEqual(hasattr(psutil.Process, "rlimit"), LINUX or FREEBSD)
170
+
171
+ def test_io_counters(self):
172
+ hasit = hasattr(psutil.Process, "io_counters")
173
+ self.assertEqual(hasit, not (MACOS or SUNOS))
174
+
175
+ def test_num_fds(self):
176
+ self.assertEqual(hasattr(psutil.Process, "num_fds"), POSIX)
177
+
178
+ def test_num_handles(self):
179
+ self.assertEqual(hasattr(psutil.Process, "num_handles"), WINDOWS)
180
+
181
+ def test_cpu_affinity(self):
182
+ self.assertEqual(
183
+ hasattr(psutil.Process, "cpu_affinity"),
184
+ LINUX or WINDOWS or FREEBSD,
185
+ )
186
+
187
+ def test_cpu_num(self):
188
+ self.assertEqual(
189
+ hasattr(psutil.Process, "cpu_num"), LINUX or FREEBSD or SUNOS
190
+ )
191
+
192
+ def test_memory_maps(self):
193
+ hasit = hasattr(psutil.Process, "memory_maps")
194
+ self.assertEqual(hasit, not (OPENBSD or NETBSD or AIX or MACOS))
195
+
196
+
197
+ # ===================================================================
198
+ # --- API types
199
+ # ===================================================================
200
+
201
+
202
+ class TestSystemAPITypes(PsutilTestCase):
203
+ """Check the return types of system related APIs.
204
+ Mainly we want to test we never return unicode on Python 2, see:
205
+ https://github.com/giampaolo/psutil/issues/1039.
206
+ """
207
+
208
+ @classmethod
209
+ def setUpClass(cls):
210
+ cls.proc = psutil.Process()
211
+
212
+ def assert_ntuple_of_nums(self, nt, type_=float, gezero=True):
213
+ assert is_namedtuple(nt)
214
+ for n in nt:
215
+ self.assertIsInstance(n, type_)
216
+ if gezero:
217
+ self.assertGreaterEqual(n, 0)
218
+
219
+ def test_cpu_times(self):
220
+ self.assert_ntuple_of_nums(psutil.cpu_times())
221
+ for nt in psutil.cpu_times(percpu=True):
222
+ self.assert_ntuple_of_nums(nt)
223
+
224
+ def test_cpu_percent(self):
225
+ self.assertIsInstance(psutil.cpu_percent(interval=None), float)
226
+ self.assertIsInstance(psutil.cpu_percent(interval=0.00001), float)
227
+
228
+ def test_cpu_times_percent(self):
229
+ self.assert_ntuple_of_nums(psutil.cpu_times_percent(interval=None))
230
+ self.assert_ntuple_of_nums(psutil.cpu_times_percent(interval=0.0001))
231
+
232
+ def test_cpu_count(self):
233
+ self.assertIsInstance(psutil.cpu_count(), int)
234
+
235
+ # TODO: remove this once 1892 is fixed
236
+ @unittest.skipIf(
237
+ MACOS and platform.machine() == 'arm64', "skipped due to #1892"
238
+ )
239
+ @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
240
+ def test_cpu_freq(self):
241
+ if psutil.cpu_freq() is None:
242
+ raise self.skipTest("cpu_freq() returns None")
243
+ self.assert_ntuple_of_nums(psutil.cpu_freq(), type_=(float, int, long))
244
+
245
+ def test_disk_io_counters(self):
246
+ # Duplicate of test_system.py. Keep it anyway.
247
+ for k, v in psutil.disk_io_counters(perdisk=True).items():
248
+ self.assertIsInstance(k, str)
249
+ self.assert_ntuple_of_nums(v, type_=(int, long))
250
+
251
+ def test_disk_partitions(self):
252
+ # Duplicate of test_system.py. Keep it anyway.
253
+ for disk in psutil.disk_partitions():
254
+ self.assertIsInstance(disk.device, str)
255
+ self.assertIsInstance(disk.mountpoint, str)
256
+ self.assertIsInstance(disk.fstype, str)
257
+ self.assertIsInstance(disk.opts, str)
258
+ self.assertIsInstance(disk.maxfile, (int, type(None)))
259
+ self.assertIsInstance(disk.maxpath, (int, type(None)))
260
+
261
+ @unittest.skipIf(SKIP_SYSCONS, "requires root")
262
+ def test_net_connections(self):
263
+ with create_sockets():
264
+ ret = psutil.net_connections('all')
265
+ self.assertEqual(len(ret), len(set(ret)))
266
+ for conn in ret:
267
+ assert is_namedtuple(conn)
268
+
269
+ def test_net_if_addrs(self):
270
+ # Duplicate of test_system.py. Keep it anyway.
271
+ for ifname, addrs in psutil.net_if_addrs().items():
272
+ self.assertIsInstance(ifname, str)
273
+ for addr in addrs:
274
+ if enum is not None and not PYPY:
275
+ self.assertIsInstance(addr.family, enum.IntEnum)
276
+ else:
277
+ self.assertIsInstance(addr.family, int)
278
+ self.assertIsInstance(addr.address, str)
279
+ self.assertIsInstance(addr.netmask, (str, type(None)))
280
+ self.assertIsInstance(addr.broadcast, (str, type(None)))
281
+
282
+ def test_net_if_stats(self):
283
+ # Duplicate of test_system.py. Keep it anyway.
284
+ for ifname, info in psutil.net_if_stats().items():
285
+ self.assertIsInstance(ifname, str)
286
+ self.assertIsInstance(info.isup, bool)
287
+ if enum is not None:
288
+ self.assertIsInstance(info.duplex, enum.IntEnum)
289
+ else:
290
+ self.assertIsInstance(info.duplex, int)
291
+ self.assertIsInstance(info.speed, int)
292
+ self.assertIsInstance(info.mtu, int)
293
+
294
+ @unittest.skipIf(not HAS_NET_IO_COUNTERS, 'not supported')
295
+ def test_net_io_counters(self):
296
+ # Duplicate of test_system.py. Keep it anyway.
297
+ for ifname in psutil.net_io_counters(pernic=True):
298
+ self.assertIsInstance(ifname, str)
299
+
300
+ @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
301
+ def test_sensors_fans(self):
302
+ # Duplicate of test_system.py. Keep it anyway.
303
+ for name, units in psutil.sensors_fans().items():
304
+ self.assertIsInstance(name, str)
305
+ for unit in units:
306
+ self.assertIsInstance(unit.label, str)
307
+ self.assertIsInstance(unit.current, (float, int, type(None)))
308
+
309
+ @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
310
+ def test_sensors_temperatures(self):
311
+ # Duplicate of test_system.py. Keep it anyway.
312
+ for name, units in psutil.sensors_temperatures().items():
313
+ self.assertIsInstance(name, str)
314
+ for unit in units:
315
+ self.assertIsInstance(unit.label, str)
316
+ self.assertIsInstance(unit.current, (float, int, type(None)))
317
+ self.assertIsInstance(unit.high, (float, int, type(None)))
318
+ self.assertIsInstance(unit.critical, (float, int, type(None)))
319
+
320
+ def test_boot_time(self):
321
+ # Duplicate of test_system.py. Keep it anyway.
322
+ self.assertIsInstance(psutil.boot_time(), float)
323
+
324
+ def test_users(self):
325
+ # Duplicate of test_system.py. Keep it anyway.
326
+ for user in psutil.users():
327
+ self.assertIsInstance(user.name, str)
328
+ self.assertIsInstance(user.terminal, (str, type(None)))
329
+ self.assertIsInstance(user.host, (str, type(None)))
330
+ self.assertIsInstance(user.pid, (int, type(None)))
331
+
332
+
333
+ class TestProcessWaitType(PsutilTestCase):
334
+ @unittest.skipIf(not POSIX, "not POSIX")
335
+ def test_negative_signal(self):
336
+ p = psutil.Process(self.spawn_testproc().pid)
337
+ p.terminate()
338
+ code = p.wait()
339
+ self.assertEqual(code, -signal.SIGTERM)
340
+ if enum is not None:
341
+ self.assertIsInstance(code, enum.IntEnum)
342
+ else:
343
+ self.assertIsInstance(code, int)
344
+
345
+
346
+ if __name__ == '__main__':
347
+ from psutil.tests.runner import run_from_name
348
+
349
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_linux.py ADDED
@@ -0,0 +1,2350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Linux specific tests."""
8
+
9
+ from __future__ import division
10
+
11
+ import collections
12
+ import contextlib
13
+ import errno
14
+ import glob
15
+ import io
16
+ import os
17
+ import re
18
+ import shutil
19
+ import socket
20
+ import struct
21
+ import textwrap
22
+ import time
23
+ import unittest
24
+ import warnings
25
+
26
+ import psutil
27
+ from psutil import LINUX
28
+ from psutil._compat import PY3
29
+ from psutil._compat import FileNotFoundError
30
+ from psutil._compat import basestring
31
+ from psutil._compat import u
32
+ from psutil.tests import GITHUB_ACTIONS
33
+ from psutil.tests import GLOBAL_TIMEOUT
34
+ from psutil.tests import HAS_BATTERY
35
+ from psutil.tests import HAS_CPU_FREQ
36
+ from psutil.tests import HAS_GETLOADAVG
37
+ from psutil.tests import HAS_RLIMIT
38
+ from psutil.tests import PYPY
39
+ from psutil.tests import TOLERANCE_DISK_USAGE
40
+ from psutil.tests import TOLERANCE_SYS_MEM
41
+ from psutil.tests import PsutilTestCase
42
+ from psutil.tests import ThreadTask
43
+ from psutil.tests import call_until
44
+ from psutil.tests import mock
45
+ from psutil.tests import reload_module
46
+ from psutil.tests import retry_on_failure
47
+ from psutil.tests import safe_rmpath
48
+ from psutil.tests import sh
49
+ from psutil.tests import skip_on_not_implemented
50
+ from psutil.tests import which
51
+
52
+
53
+ if LINUX:
54
+ from psutil._pslinux import CLOCK_TICKS
55
+ from psutil._pslinux import RootFsDeviceFinder
56
+ from psutil._pslinux import calculate_avail_vmem
57
+ from psutil._pslinux import open_binary
58
+
59
+
60
+ HERE = os.path.abspath(os.path.dirname(__file__))
61
+ SIOCGIFADDR = 0x8915
62
+ SIOCGIFCONF = 0x8912
63
+ SIOCGIFHWADDR = 0x8927
64
+ SIOCGIFNETMASK = 0x891B
65
+ SIOCGIFBRDADDR = 0x8919
66
+ if LINUX:
67
+ SECTOR_SIZE = 512
68
+ EMPTY_TEMPERATURES = not glob.glob('/sys/class/hwmon/hwmon*')
69
+
70
+
71
+ # =====================================================================
72
+ # --- utils
73
+ # =====================================================================
74
+
75
+
76
+ def get_ipv4_address(ifname):
77
+ import fcntl
78
+
79
+ ifname = ifname[:15]
80
+ if PY3:
81
+ ifname = bytes(ifname, 'ascii')
82
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
83
+ with contextlib.closing(s):
84
+ return socket.inet_ntoa(
85
+ fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack('256s', ifname))[
86
+ 20:24
87
+ ]
88
+ )
89
+
90
+
91
+ def get_ipv4_netmask(ifname):
92
+ import fcntl
93
+
94
+ ifname = ifname[:15]
95
+ if PY3:
96
+ ifname = bytes(ifname, 'ascii')
97
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
98
+ with contextlib.closing(s):
99
+ return socket.inet_ntoa(
100
+ fcntl.ioctl(
101
+ s.fileno(), SIOCGIFNETMASK, struct.pack('256s', ifname)
102
+ )[20:24]
103
+ )
104
+
105
+
106
+ def get_ipv4_broadcast(ifname):
107
+ import fcntl
108
+
109
+ ifname = ifname[:15]
110
+ if PY3:
111
+ ifname = bytes(ifname, 'ascii')
112
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
113
+ with contextlib.closing(s):
114
+ return socket.inet_ntoa(
115
+ fcntl.ioctl(
116
+ s.fileno(), SIOCGIFBRDADDR, struct.pack('256s', ifname)
117
+ )[20:24]
118
+ )
119
+
120
+
121
+ def get_ipv6_addresses(ifname):
122
+ with open("/proc/net/if_inet6") as f:
123
+ all_fields = []
124
+ for line in f.readlines():
125
+ fields = line.split()
126
+ if fields[-1] == ifname:
127
+ all_fields.append(fields)
128
+
129
+ if len(all_fields) == 0:
130
+ raise ValueError("could not find interface %r" % ifname)
131
+
132
+ for i in range(len(all_fields)):
133
+ unformatted = all_fields[i][0]
134
+ groups = []
135
+ for j in range(0, len(unformatted), 4):
136
+ groups.append(unformatted[j : j + 4])
137
+ formatted = ":".join(groups)
138
+ packed = socket.inet_pton(socket.AF_INET6, formatted)
139
+ all_fields[i] = socket.inet_ntop(socket.AF_INET6, packed)
140
+ return all_fields
141
+
142
+
143
+ def get_mac_address(ifname):
144
+ import fcntl
145
+
146
+ ifname = ifname[:15]
147
+ if PY3:
148
+ ifname = bytes(ifname, 'ascii')
149
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
150
+ with contextlib.closing(s):
151
+ info = fcntl.ioctl(
152
+ s.fileno(), SIOCGIFHWADDR, struct.pack('256s', ifname)
153
+ )
154
+ if PY3:
155
+
156
+ def ord(x):
157
+ return x
158
+
159
+ else:
160
+ import __builtin__
161
+
162
+ ord = __builtin__.ord
163
+ return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
164
+
165
+
166
+ def free_swap():
167
+ """Parse 'free' cmd and return swap memory's s total, used and free
168
+ values.
169
+ """
170
+ out = sh(["free", "-b"], env={"LANG": "C.UTF-8"})
171
+ lines = out.split('\n')
172
+ for line in lines:
173
+ if line.startswith('Swap'):
174
+ _, total, used, free = line.split()
175
+ nt = collections.namedtuple('free', 'total used free')
176
+ return nt(int(total), int(used), int(free))
177
+ raise ValueError(
178
+ "can't find 'Swap' in 'free' output:\n%s" % '\n'.join(lines)
179
+ )
180
+
181
+
182
+ def free_physmem():
183
+ """Parse 'free' cmd and return physical memory's total, used
184
+ and free values.
185
+ """
186
+ # Note: free can have 2 different formats, invalidating 'shared'
187
+ # and 'cached' memory which may have different positions so we
188
+ # do not return them.
189
+ # https://github.com/giampaolo/psutil/issues/538#issuecomment-57059946
190
+ out = sh(["free", "-b"], env={"LANG": "C.UTF-8"})
191
+ lines = out.split('\n')
192
+ for line in lines:
193
+ if line.startswith('Mem'):
194
+ total, used, free, shared = (int(x) for x in line.split()[1:5])
195
+ nt = collections.namedtuple(
196
+ 'free', 'total used free shared output'
197
+ )
198
+ return nt(total, used, free, shared, out)
199
+ raise ValueError(
200
+ "can't find 'Mem' in 'free' output:\n%s" % '\n'.join(lines)
201
+ )
202
+
203
+
204
+ def vmstat(stat):
205
+ out = sh(["vmstat", "-s"], env={"LANG": "C.UTF-8"})
206
+ for line in out.split("\n"):
207
+ line = line.strip()
208
+ if stat in line:
209
+ return int(line.split(' ')[0])
210
+ raise ValueError("can't find %r in 'vmstat' output" % stat)
211
+
212
+
213
+ def get_free_version_info():
214
+ out = sh(["free", "-V"]).strip()
215
+ if 'UNKNOWN' in out:
216
+ raise unittest.SkipTest("can't determine free version")
217
+ return tuple(map(int, re.findall(r'\d+', out.split()[-1])))
218
+
219
+
220
+ @contextlib.contextmanager
221
+ def mock_open_content(pairs):
222
+ """Mock open() builtin and forces it to return a certain content
223
+ for a given path. `pairs` is a {"path": "content", ...} dict.
224
+ """
225
+
226
+ def open_mock(name, *args, **kwargs):
227
+ if name in pairs:
228
+ content = pairs[name]
229
+ if PY3:
230
+ if isinstance(content, basestring):
231
+ return io.StringIO(content)
232
+ else:
233
+ return io.BytesIO(content)
234
+ else:
235
+ return io.BytesIO(content)
236
+ else:
237
+ return orig_open(name, *args, **kwargs)
238
+
239
+ orig_open = open
240
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
241
+ with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
242
+ yield m
243
+
244
+
245
+ @contextlib.contextmanager
246
+ def mock_open_exception(for_path, exc):
247
+ """Mock open() builtin and raises `exc` if the path being opened
248
+ matches `for_path`.
249
+ """
250
+
251
+ def open_mock(name, *args, **kwargs):
252
+ if name == for_path:
253
+ raise exc
254
+ else:
255
+ return orig_open(name, *args, **kwargs)
256
+
257
+ orig_open = open
258
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
259
+ with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
260
+ yield m
261
+
262
+
263
+ # =====================================================================
264
+ # --- system virtual memory
265
+ # =====================================================================
266
+
267
+
268
+ @unittest.skipIf(not LINUX, "LINUX only")
269
+ class TestSystemVirtualMemoryAgainstFree(PsutilTestCase):
270
+ def test_total(self):
271
+ cli_value = free_physmem().total
272
+ psutil_value = psutil.virtual_memory().total
273
+ self.assertEqual(cli_value, psutil_value)
274
+
275
+ @retry_on_failure()
276
+ def test_used(self):
277
+ # Older versions of procps used slab memory to calculate used memory.
278
+ # This got changed in:
279
+ # https://gitlab.com/procps-ng/procps/commit/
280
+ # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
281
+ if get_free_version_info() < (3, 3, 12):
282
+ raise self.skipTest("old free version")
283
+ cli_value = free_physmem().used
284
+ psutil_value = psutil.virtual_memory().used
285
+ self.assertAlmostEqual(
286
+ cli_value, psutil_value, delta=TOLERANCE_SYS_MEM
287
+ )
288
+
289
+ @retry_on_failure()
290
+ def test_free(self):
291
+ cli_value = free_physmem().free
292
+ psutil_value = psutil.virtual_memory().free
293
+ self.assertAlmostEqual(
294
+ cli_value, psutil_value, delta=TOLERANCE_SYS_MEM
295
+ )
296
+
297
+ @retry_on_failure()
298
+ def test_shared(self):
299
+ free = free_physmem()
300
+ free_value = free.shared
301
+ if free_value == 0:
302
+ raise unittest.SkipTest("free does not support 'shared' column")
303
+ psutil_value = psutil.virtual_memory().shared
304
+ self.assertAlmostEqual(
305
+ free_value,
306
+ psutil_value,
307
+ delta=TOLERANCE_SYS_MEM,
308
+ msg='%s %s \n%s' % (free_value, psutil_value, free.output),
309
+ )
310
+
311
+ @retry_on_failure()
312
+ def test_available(self):
313
+ # "free" output format has changed at some point:
314
+ # https://github.com/giampaolo/psutil/issues/538#issuecomment-147192098
315
+ out = sh(["free", "-b"])
316
+ lines = out.split('\n')
317
+ if 'available' not in lines[0]:
318
+ raise unittest.SkipTest("free does not support 'available' column")
319
+ else:
320
+ free_value = int(lines[1].split()[-1])
321
+ psutil_value = psutil.virtual_memory().available
322
+ self.assertAlmostEqual(
323
+ free_value,
324
+ psutil_value,
325
+ delta=TOLERANCE_SYS_MEM,
326
+ msg='%s %s \n%s' % (free_value, psutil_value, out),
327
+ )
328
+
329
+
330
+ @unittest.skipIf(not LINUX, "LINUX only")
331
+ class TestSystemVirtualMemoryAgainstVmstat(PsutilTestCase):
332
+ def test_total(self):
333
+ vmstat_value = vmstat('total memory') * 1024
334
+ psutil_value = psutil.virtual_memory().total
335
+ self.assertAlmostEqual(
336
+ vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM
337
+ )
338
+
339
+ @retry_on_failure()
340
+ def test_used(self):
341
+ # Older versions of procps used slab memory to calculate used memory.
342
+ # This got changed in:
343
+ # https://gitlab.com/procps-ng/procps/commit/
344
+ # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
345
+ if get_free_version_info() < (3, 3, 12):
346
+ raise self.skipTest("old free version")
347
+ vmstat_value = vmstat('used memory') * 1024
348
+ psutil_value = psutil.virtual_memory().used
349
+ self.assertAlmostEqual(
350
+ vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM
351
+ )
352
+
353
+ @retry_on_failure()
354
+ def test_free(self):
355
+ vmstat_value = vmstat('free memory') * 1024
356
+ psutil_value = psutil.virtual_memory().free
357
+ self.assertAlmostEqual(
358
+ vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM
359
+ )
360
+
361
+ @retry_on_failure()
362
+ def test_buffers(self):
363
+ vmstat_value = vmstat('buffer memory') * 1024
364
+ psutil_value = psutil.virtual_memory().buffers
365
+ self.assertAlmostEqual(
366
+ vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM
367
+ )
368
+
369
+ @retry_on_failure()
370
+ def test_active(self):
371
+ vmstat_value = vmstat('active memory') * 1024
372
+ psutil_value = psutil.virtual_memory().active
373
+ self.assertAlmostEqual(
374
+ vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM
375
+ )
376
+
377
+ @retry_on_failure()
378
+ def test_inactive(self):
379
+ vmstat_value = vmstat('inactive memory') * 1024
380
+ psutil_value = psutil.virtual_memory().inactive
381
+ self.assertAlmostEqual(
382
+ vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM
383
+ )
384
+
385
+
386
+ @unittest.skipIf(not LINUX, "LINUX only")
387
+ class TestSystemVirtualMemoryMocks(PsutilTestCase):
388
+ def test_warnings_on_misses(self):
389
+ # Emulate a case where /proc/meminfo provides few info.
390
+ # psutil is supposed to set the missing fields to 0 and
391
+ # raise a warning.
392
+ content = textwrap.dedent("""\
393
+ Active(anon): 6145416 kB
394
+ Active(file): 2950064 kB
395
+ Inactive(anon): 574764 kB
396
+ Inactive(file): 1567648 kB
397
+ MemAvailable: -1 kB
398
+ MemFree: 2057400 kB
399
+ MemTotal: 16325648 kB
400
+ SReclaimable: 346648 kB
401
+ """).encode()
402
+ with mock_open_content({'/proc/meminfo': content}) as m:
403
+ with warnings.catch_warnings(record=True) as ws:
404
+ warnings.simplefilter("always")
405
+ ret = psutil.virtual_memory()
406
+ assert m.called
407
+ self.assertEqual(len(ws), 1)
408
+ w = ws[0]
409
+ self.assertIn(
410
+ "memory stats couldn't be determined", str(w.message)
411
+ )
412
+ self.assertIn("cached", str(w.message))
413
+ self.assertIn("shared", str(w.message))
414
+ self.assertIn("active", str(w.message))
415
+ self.assertIn("inactive", str(w.message))
416
+ self.assertIn("buffers", str(w.message))
417
+ self.assertIn("available", str(w.message))
418
+ self.assertEqual(ret.cached, 0)
419
+ self.assertEqual(ret.active, 0)
420
+ self.assertEqual(ret.inactive, 0)
421
+ self.assertEqual(ret.shared, 0)
422
+ self.assertEqual(ret.buffers, 0)
423
+ self.assertEqual(ret.available, 0)
424
+ self.assertEqual(ret.slab, 0)
425
+
426
+ @retry_on_failure()
427
+ def test_avail_old_percent(self):
428
+ # Make sure that our calculation of avail mem for old kernels
429
+ # is off by max 15%.
430
+ mems = {}
431
+ with open_binary('/proc/meminfo') as f:
432
+ for line in f:
433
+ fields = line.split()
434
+ mems[fields[0]] = int(fields[1]) * 1024
435
+
436
+ a = calculate_avail_vmem(mems)
437
+ if b'MemAvailable:' in mems:
438
+ b = mems[b'MemAvailable:']
439
+ diff_percent = abs(a - b) / a * 100
440
+ self.assertLess(diff_percent, 15)
441
+
442
+ def test_avail_old_comes_from_kernel(self):
443
+ # Make sure "MemAvailable:" coluimn is used instead of relying
444
+ # on our internal algorithm to calculate avail mem.
445
+ content = textwrap.dedent("""\
446
+ Active: 9444728 kB
447
+ Active(anon): 6145416 kB
448
+ Active(file): 2950064 kB
449
+ Buffers: 287952 kB
450
+ Cached: 4818144 kB
451
+ Inactive(file): 1578132 kB
452
+ Inactive(anon): 574764 kB
453
+ Inactive(file): 1567648 kB
454
+ MemAvailable: 6574984 kB
455
+ MemFree: 2057400 kB
456
+ MemTotal: 16325648 kB
457
+ Shmem: 577588 kB
458
+ SReclaimable: 346648 kB
459
+ """).encode()
460
+ with mock_open_content({'/proc/meminfo': content}) as m:
461
+ with warnings.catch_warnings(record=True) as ws:
462
+ ret = psutil.virtual_memory()
463
+ assert m.called
464
+ self.assertEqual(ret.available, 6574984 * 1024)
465
+ w = ws[0]
466
+ self.assertIn(
467
+ "inactive memory stats couldn't be determined", str(w.message)
468
+ )
469
+
470
+ def test_avail_old_missing_fields(self):
471
+ # Remove Active(file), Inactive(file) and SReclaimable
472
+ # from /proc/meminfo and make sure the fallback is used
473
+ # (free + cached),
474
+ content = textwrap.dedent("""\
475
+ Active: 9444728 kB
476
+ Active(anon): 6145416 kB
477
+ Buffers: 287952 kB
478
+ Cached: 4818144 kB
479
+ Inactive(file): 1578132 kB
480
+ Inactive(anon): 574764 kB
481
+ MemFree: 2057400 kB
482
+ MemTotal: 16325648 kB
483
+ Shmem: 577588 kB
484
+ """).encode()
485
+ with mock_open_content({"/proc/meminfo": content}) as m:
486
+ with warnings.catch_warnings(record=True) as ws:
487
+ ret = psutil.virtual_memory()
488
+ assert m.called
489
+ self.assertEqual(ret.available, 2057400 * 1024 + 4818144 * 1024)
490
+ w = ws[0]
491
+ self.assertIn(
492
+ "inactive memory stats couldn't be determined", str(w.message)
493
+ )
494
+
495
+ def test_avail_old_missing_zoneinfo(self):
496
+ # Remove /proc/zoneinfo file. Make sure fallback is used
497
+ # (free + cached).
498
+ content = textwrap.dedent("""\
499
+ Active: 9444728 kB
500
+ Active(anon): 6145416 kB
501
+ Active(file): 2950064 kB
502
+ Buffers: 287952 kB
503
+ Cached: 4818144 kB
504
+ Inactive(file): 1578132 kB
505
+ Inactive(anon): 574764 kB
506
+ Inactive(file): 1567648 kB
507
+ MemFree: 2057400 kB
508
+ MemTotal: 16325648 kB
509
+ Shmem: 577588 kB
510
+ SReclaimable: 346648 kB
511
+ """).encode()
512
+ with mock_open_content({"/proc/meminfo": content}):
513
+ with mock_open_exception(
514
+ "/proc/zoneinfo",
515
+ IOError(errno.ENOENT, 'no such file or directory'),
516
+ ):
517
+ with warnings.catch_warnings(record=True) as ws:
518
+ ret = psutil.virtual_memory()
519
+ self.assertEqual(
520
+ ret.available, 2057400 * 1024 + 4818144 * 1024
521
+ )
522
+ w = ws[0]
523
+ self.assertIn(
524
+ "inactive memory stats couldn't be determined",
525
+ str(w.message),
526
+ )
527
+
528
+ def test_virtual_memory_mocked(self):
529
+ # Emulate /proc/meminfo because neither vmstat nor free return slab.
530
+ content = textwrap.dedent("""\
531
+ MemTotal: 100 kB
532
+ MemFree: 2 kB
533
+ MemAvailable: 3 kB
534
+ Buffers: 4 kB
535
+ Cached: 5 kB
536
+ SwapCached: 6 kB
537
+ Active: 7 kB
538
+ Inactive: 8 kB
539
+ Active(anon): 9 kB
540
+ Inactive(anon): 10 kB
541
+ Active(file): 11 kB
542
+ Inactive(file): 12 kB
543
+ Unevictable: 13 kB
544
+ Mlocked: 14 kB
545
+ SwapTotal: 15 kB
546
+ SwapFree: 16 kB
547
+ Dirty: 17 kB
548
+ Writeback: 18 kB
549
+ AnonPages: 19 kB
550
+ Mapped: 20 kB
551
+ Shmem: 21 kB
552
+ Slab: 22 kB
553
+ SReclaimable: 23 kB
554
+ SUnreclaim: 24 kB
555
+ KernelStack: 25 kB
556
+ PageTables: 26 kB
557
+ NFS_Unstable: 27 kB
558
+ Bounce: 28 kB
559
+ WritebackTmp: 29 kB
560
+ CommitLimit: 30 kB
561
+ Committed_AS: 31 kB
562
+ VmallocTotal: 32 kB
563
+ VmallocUsed: 33 kB
564
+ VmallocChunk: 34 kB
565
+ HardwareCorrupted: 35 kB
566
+ AnonHugePages: 36 kB
567
+ ShmemHugePages: 37 kB
568
+ ShmemPmdMapped: 38 kB
569
+ CmaTotal: 39 kB
570
+ CmaFree: 40 kB
571
+ HugePages_Total: 41 kB
572
+ HugePages_Free: 42 kB
573
+ HugePages_Rsvd: 43 kB
574
+ HugePages_Surp: 44 kB
575
+ Hugepagesize: 45 kB
576
+ DirectMap46k: 46 kB
577
+ DirectMap47M: 47 kB
578
+ DirectMap48G: 48 kB
579
+ """).encode()
580
+ with mock_open_content({"/proc/meminfo": content}) as m:
581
+ mem = psutil.virtual_memory()
582
+ assert m.called
583
+ self.assertEqual(mem.total, 100 * 1024)
584
+ self.assertEqual(mem.free, 2 * 1024)
585
+ self.assertEqual(mem.buffers, 4 * 1024)
586
+ # cached mem also includes reclaimable memory
587
+ self.assertEqual(mem.cached, (5 + 23) * 1024)
588
+ self.assertEqual(mem.shared, 21 * 1024)
589
+ self.assertEqual(mem.active, 7 * 1024)
590
+ self.assertEqual(mem.inactive, 8 * 1024)
591
+ self.assertEqual(mem.slab, 22 * 1024)
592
+ self.assertEqual(mem.available, 3 * 1024)
593
+
594
+
595
+ # =====================================================================
596
+ # --- system swap memory
597
+ # =====================================================================
598
+
599
+
600
+ @unittest.skipIf(not LINUX, "LINUX only")
601
+ class TestSystemSwapMemory(PsutilTestCase):
602
+ @staticmethod
603
+ def meminfo_has_swap_info():
604
+ """Return True if /proc/meminfo provides swap metrics."""
605
+ with open("/proc/meminfo") as f:
606
+ data = f.read()
607
+ return 'SwapTotal:' in data and 'SwapFree:' in data
608
+
609
+ def test_total(self):
610
+ free_value = free_swap().total
611
+ psutil_value = psutil.swap_memory().total
612
+ return self.assertAlmostEqual(
613
+ free_value, psutil_value, delta=TOLERANCE_SYS_MEM
614
+ )
615
+
616
+ @retry_on_failure()
617
+ def test_used(self):
618
+ free_value = free_swap().used
619
+ psutil_value = psutil.swap_memory().used
620
+ return self.assertAlmostEqual(
621
+ free_value, psutil_value, delta=TOLERANCE_SYS_MEM
622
+ )
623
+
624
+ @retry_on_failure()
625
+ def test_free(self):
626
+ free_value = free_swap().free
627
+ psutil_value = psutil.swap_memory().free
628
+ return self.assertAlmostEqual(
629
+ free_value, psutil_value, delta=TOLERANCE_SYS_MEM
630
+ )
631
+
632
+ def test_missing_sin_sout(self):
633
+ with mock.patch('psutil._common.open', create=True) as m:
634
+ with warnings.catch_warnings(record=True) as ws:
635
+ warnings.simplefilter("always")
636
+ ret = psutil.swap_memory()
637
+ assert m.called
638
+ self.assertEqual(len(ws), 1)
639
+ w = ws[0]
640
+ self.assertIn(
641
+ "'sin' and 'sout' swap memory stats couldn't "
642
+ "be determined",
643
+ str(w.message),
644
+ )
645
+ self.assertEqual(ret.sin, 0)
646
+ self.assertEqual(ret.sout, 0)
647
+
648
+ def test_no_vmstat_mocked(self):
649
+ # see https://github.com/giampaolo/psutil/issues/722
650
+ with mock_open_exception(
651
+ "/proc/vmstat", IOError(errno.ENOENT, 'no such file or directory')
652
+ ) as m:
653
+ with warnings.catch_warnings(record=True) as ws:
654
+ warnings.simplefilter("always")
655
+ ret = psutil.swap_memory()
656
+ assert m.called
657
+ self.assertEqual(len(ws), 1)
658
+ w = ws[0]
659
+ self.assertIn(
660
+ "'sin' and 'sout' swap memory stats couldn't "
661
+ "be determined and were set to 0",
662
+ str(w.message),
663
+ )
664
+ self.assertEqual(ret.sin, 0)
665
+ self.assertEqual(ret.sout, 0)
666
+
667
+ def test_meminfo_against_sysinfo(self):
668
+ # Make sure the content of /proc/meminfo about swap memory
669
+ # matches sysinfo() syscall, see:
670
+ # https://github.com/giampaolo/psutil/issues/1015
671
+ if not self.meminfo_has_swap_info():
672
+ return unittest.skip("/proc/meminfo has no swap metrics")
673
+ with mock.patch('psutil._pslinux.cext.linux_sysinfo') as m:
674
+ swap = psutil.swap_memory()
675
+ assert not m.called
676
+ import psutil._psutil_linux as cext
677
+
678
+ _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
679
+ total *= unit_multiplier
680
+ free *= unit_multiplier
681
+ self.assertEqual(swap.total, total)
682
+ self.assertAlmostEqual(swap.free, free, delta=TOLERANCE_SYS_MEM)
683
+
684
+ def test_emulate_meminfo_has_no_metrics(self):
685
+ # Emulate a case where /proc/meminfo provides no swap metrics
686
+ # in which case sysinfo() syscall is supposed to be used
687
+ # as a fallback.
688
+ with mock_open_content({"/proc/meminfo": b""}) as m:
689
+ psutil.swap_memory()
690
+ assert m.called
691
+
692
+
693
+ # =====================================================================
694
+ # --- system CPU
695
+ # =====================================================================
696
+
697
+
698
+ @unittest.skipIf(not LINUX, "LINUX only")
699
+ class TestSystemCPUTimes(PsutilTestCase):
700
+ def test_fields(self):
701
+ fields = psutil.cpu_times()._fields
702
+ kernel_ver = re.findall(r'\d+\.\d+\.\d+', os.uname()[2])[0]
703
+ kernel_ver_info = tuple(map(int, kernel_ver.split('.')))
704
+ if kernel_ver_info >= (2, 6, 11):
705
+ self.assertIn('steal', fields)
706
+ else:
707
+ self.assertNotIn('steal', fields)
708
+ if kernel_ver_info >= (2, 6, 24):
709
+ self.assertIn('guest', fields)
710
+ else:
711
+ self.assertNotIn('guest', fields)
712
+ if kernel_ver_info >= (3, 2, 0):
713
+ self.assertIn('guest_nice', fields)
714
+ else:
715
+ self.assertNotIn('guest_nice', fields)
716
+
717
+
718
+ @unittest.skipIf(not LINUX, "LINUX only")
719
+ class TestSystemCPUCountLogical(PsutilTestCase):
720
+ @unittest.skipIf(
721
+ not os.path.exists("/sys/devices/system/cpu/online"),
722
+ "/sys/devices/system/cpu/online does not exist",
723
+ )
724
+ def test_against_sysdev_cpu_online(self):
725
+ with open("/sys/devices/system/cpu/online") as f:
726
+ value = f.read().strip()
727
+ if "-" in str(value):
728
+ value = int(value.split('-')[1]) + 1
729
+ self.assertEqual(psutil.cpu_count(), value)
730
+
731
+ @unittest.skipIf(
732
+ not os.path.exists("/sys/devices/system/cpu"),
733
+ "/sys/devices/system/cpu does not exist",
734
+ )
735
+ def test_against_sysdev_cpu_num(self):
736
+ ls = os.listdir("/sys/devices/system/cpu")
737
+ count = len([x for x in ls if re.search(r"cpu\d+$", x) is not None])
738
+ self.assertEqual(psutil.cpu_count(), count)
739
+
740
+ @unittest.skipIf(not which("nproc"), "nproc utility not available")
741
+ def test_against_nproc(self):
742
+ num = int(sh("nproc --all"))
743
+ self.assertEqual(psutil.cpu_count(logical=True), num)
744
+
745
+ @unittest.skipIf(not which("lscpu"), "lscpu utility not available")
746
+ def test_against_lscpu(self):
747
+ out = sh("lscpu -p")
748
+ num = len([x for x in out.split('\n') if not x.startswith('#')])
749
+ self.assertEqual(psutil.cpu_count(logical=True), num)
750
+
751
+ def test_emulate_fallbacks(self):
752
+ import psutil._pslinux
753
+
754
+ original = psutil._pslinux.cpu_count_logical()
755
+ # Here we want to mock os.sysconf("SC_NPROCESSORS_ONLN") in
756
+ # order to cause the parsing of /proc/cpuinfo and /proc/stat.
757
+ with mock.patch(
758
+ 'psutil._pslinux.os.sysconf', side_effect=ValueError
759
+ ) as m:
760
+ self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
761
+ assert m.called
762
+
763
+ # Let's have open() return empty data and make sure None is
764
+ # returned ('cause we mimic os.cpu_count()).
765
+ with mock.patch('psutil._common.open', create=True) as m:
766
+ self.assertIsNone(psutil._pslinux.cpu_count_logical())
767
+ self.assertEqual(m.call_count, 2)
768
+ # /proc/stat should be the last one
769
+ self.assertEqual(m.call_args[0][0], '/proc/stat')
770
+
771
+ # Let's push this a bit further and make sure /proc/cpuinfo
772
+ # parsing works as expected.
773
+ with open('/proc/cpuinfo', 'rb') as f:
774
+ cpuinfo_data = f.read()
775
+ fake_file = io.BytesIO(cpuinfo_data)
776
+ with mock.patch(
777
+ 'psutil._common.open', return_value=fake_file, create=True
778
+ ) as m:
779
+ self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
780
+
781
+ # Finally, let's make /proc/cpuinfo return meaningless data;
782
+ # this way we'll fall back on relying on /proc/stat
783
+ with mock_open_content({"/proc/cpuinfo": b""}) as m:
784
+ self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
785
+ assert m.called
786
+
787
+
788
+ @unittest.skipIf(not LINUX, "LINUX only")
789
+ class TestSystemCPUCountCores(PsutilTestCase):
790
+ @unittest.skipIf(not which("lscpu"), "lscpu utility not available")
791
+ def test_against_lscpu(self):
792
+ out = sh("lscpu -p")
793
+ core_ids = set()
794
+ for line in out.split('\n'):
795
+ if not line.startswith('#'):
796
+ fields = line.split(',')
797
+ core_ids.add(fields[1])
798
+ self.assertEqual(psutil.cpu_count(logical=False), len(core_ids))
799
+
800
+ def test_method_2(self):
801
+ meth_1 = psutil._pslinux.cpu_count_cores()
802
+ with mock.patch('glob.glob', return_value=[]) as m:
803
+ meth_2 = psutil._pslinux.cpu_count_cores()
804
+ assert m.called
805
+ if meth_1 is not None:
806
+ self.assertEqual(meth_1, meth_2)
807
+
808
+ def test_emulate_none(self):
809
+ with mock.patch('glob.glob', return_value=[]) as m1:
810
+ with mock.patch('psutil._common.open', create=True) as m2:
811
+ self.assertIsNone(psutil._pslinux.cpu_count_cores())
812
+ assert m1.called
813
+ assert m2.called
814
+
815
+
816
+ @unittest.skipIf(not LINUX, "LINUX only")
817
+ class TestSystemCPUFrequency(PsutilTestCase):
818
+ @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
819
+ def test_emulate_use_second_file(self):
820
+ # https://github.com/giampaolo/psutil/issues/981
821
+ def path_exists_mock(path):
822
+ if path.startswith("/sys/devices/system/cpu/cpufreq/policy"):
823
+ return False
824
+ else:
825
+ return orig_exists(path)
826
+
827
+ orig_exists = os.path.exists
828
+ with mock.patch(
829
+ "os.path.exists", side_effect=path_exists_mock, create=True
830
+ ):
831
+ assert psutil.cpu_freq()
832
+
833
+ @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
834
+ def test_emulate_use_cpuinfo(self):
835
+ # Emulate a case where /sys/devices/system/cpu/cpufreq* does not
836
+ # exist and /proc/cpuinfo is used instead.
837
+ def path_exists_mock(path):
838
+ if path.startswith('/sys/devices/system/cpu/'):
839
+ return False
840
+ else:
841
+ return os_path_exists(path)
842
+
843
+ os_path_exists = os.path.exists
844
+ try:
845
+ with mock.patch("os.path.exists", side_effect=path_exists_mock):
846
+ reload_module(psutil._pslinux)
847
+ ret = psutil.cpu_freq()
848
+ assert ret, ret
849
+ self.assertEqual(ret.max, 0.0)
850
+ self.assertEqual(ret.min, 0.0)
851
+ for freq in psutil.cpu_freq(percpu=True):
852
+ self.assertEqual(freq.max, 0.0)
853
+ self.assertEqual(freq.min, 0.0)
854
+ finally:
855
+ reload_module(psutil._pslinux)
856
+ reload_module(psutil)
857
+
858
+ @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
859
+ def test_emulate_data(self):
860
+ def open_mock(name, *args, **kwargs):
861
+ if name.endswith('/scaling_cur_freq') and name.startswith(
862
+ "/sys/devices/system/cpu/cpufreq/policy"
863
+ ):
864
+ return io.BytesIO(b"500000")
865
+ elif name.endswith('/scaling_min_freq') and name.startswith(
866
+ "/sys/devices/system/cpu/cpufreq/policy"
867
+ ):
868
+ return io.BytesIO(b"600000")
869
+ elif name.endswith('/scaling_max_freq') and name.startswith(
870
+ "/sys/devices/system/cpu/cpufreq/policy"
871
+ ):
872
+ return io.BytesIO(b"700000")
873
+ elif name == '/proc/cpuinfo':
874
+ return io.BytesIO(b"cpu MHz : 500")
875
+ else:
876
+ return orig_open(name, *args, **kwargs)
877
+
878
+ orig_open = open
879
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
880
+ with mock.patch(patch_point, side_effect=open_mock):
881
+ with mock.patch('os.path.exists', return_value=True):
882
+ freq = psutil.cpu_freq()
883
+ self.assertEqual(freq.current, 500.0)
884
+ # when /proc/cpuinfo is used min and max frequencies are not
885
+ # available and are set to 0.
886
+ if freq.min != 0.0:
887
+ self.assertEqual(freq.min, 600.0)
888
+ if freq.max != 0.0:
889
+ self.assertEqual(freq.max, 700.0)
890
+
891
+ @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
892
+ def test_emulate_multi_cpu(self):
893
+ def open_mock(name, *args, **kwargs):
894
+ n = name
895
+ if n.endswith('/scaling_cur_freq') and n.startswith(
896
+ "/sys/devices/system/cpu/cpufreq/policy0"
897
+ ):
898
+ return io.BytesIO(b"100000")
899
+ elif n.endswith('/scaling_min_freq') and n.startswith(
900
+ "/sys/devices/system/cpu/cpufreq/policy0"
901
+ ):
902
+ return io.BytesIO(b"200000")
903
+ elif n.endswith('/scaling_max_freq') and n.startswith(
904
+ "/sys/devices/system/cpu/cpufreq/policy0"
905
+ ):
906
+ return io.BytesIO(b"300000")
907
+ elif n.endswith('/scaling_cur_freq') and n.startswith(
908
+ "/sys/devices/system/cpu/cpufreq/policy1"
909
+ ):
910
+ return io.BytesIO(b"400000")
911
+ elif n.endswith('/scaling_min_freq') and n.startswith(
912
+ "/sys/devices/system/cpu/cpufreq/policy1"
913
+ ):
914
+ return io.BytesIO(b"500000")
915
+ elif n.endswith('/scaling_max_freq') and n.startswith(
916
+ "/sys/devices/system/cpu/cpufreq/policy1"
917
+ ):
918
+ return io.BytesIO(b"600000")
919
+ elif name == '/proc/cpuinfo':
920
+ return io.BytesIO(b"cpu MHz : 100\ncpu MHz : 400")
921
+ else:
922
+ return orig_open(name, *args, **kwargs)
923
+
924
+ orig_open = open
925
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
926
+ with mock.patch(patch_point, side_effect=open_mock):
927
+ with mock.patch('os.path.exists', return_value=True):
928
+ with mock.patch(
929
+ 'psutil._pslinux.cpu_count_logical', return_value=2
930
+ ):
931
+ freq = psutil.cpu_freq(percpu=True)
932
+ self.assertEqual(freq[0].current, 100.0)
933
+ if freq[0].min != 0.0:
934
+ self.assertEqual(freq[0].min, 200.0)
935
+ if freq[0].max != 0.0:
936
+ self.assertEqual(freq[0].max, 300.0)
937
+ self.assertEqual(freq[1].current, 400.0)
938
+ if freq[1].min != 0.0:
939
+ self.assertEqual(freq[1].min, 500.0)
940
+ if freq[1].max != 0.0:
941
+ self.assertEqual(freq[1].max, 600.0)
942
+
943
+ @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
944
+ def test_emulate_no_scaling_cur_freq_file(self):
945
+ # See: https://github.com/giampaolo/psutil/issues/1071
946
+ def open_mock(name, *args, **kwargs):
947
+ if name.endswith('/scaling_cur_freq'):
948
+ raise IOError(errno.ENOENT, "")
949
+ elif name.endswith('/cpuinfo_cur_freq'):
950
+ return io.BytesIO(b"200000")
951
+ elif name == '/proc/cpuinfo':
952
+ return io.BytesIO(b"cpu MHz : 200")
953
+ else:
954
+ return orig_open(name, *args, **kwargs)
955
+
956
+ orig_open = open
957
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
958
+ with mock.patch(patch_point, side_effect=open_mock):
959
+ with mock.patch('os.path.exists', return_value=True):
960
+ with mock.patch(
961
+ 'psutil._pslinux.cpu_count_logical', return_value=1
962
+ ):
963
+ freq = psutil.cpu_freq()
964
+ self.assertEqual(freq.current, 200)
965
+
966
+
967
+ @unittest.skipIf(not LINUX, "LINUX only")
968
+ class TestSystemCPUStats(PsutilTestCase):
969
+ def test_ctx_switches(self):
970
+ vmstat_value = vmstat("context switches")
971
+ psutil_value = psutil.cpu_stats().ctx_switches
972
+ self.assertAlmostEqual(vmstat_value, psutil_value, delta=500)
973
+
974
+ def test_interrupts(self):
975
+ vmstat_value = vmstat("interrupts")
976
+ psutil_value = psutil.cpu_stats().interrupts
977
+ self.assertAlmostEqual(vmstat_value, psutil_value, delta=500)
978
+
979
+
980
+ @unittest.skipIf(not LINUX, "LINUX only")
981
+ class TestLoadAvg(PsutilTestCase):
982
+ @unittest.skipIf(not HAS_GETLOADAVG, "not supported")
983
+ def test_getloadavg(self):
984
+ psutil_value = psutil.getloadavg()
985
+ with open("/proc/loadavg") as f:
986
+ proc_value = f.read().split()
987
+
988
+ self.assertAlmostEqual(float(proc_value[0]), psutil_value[0], delta=1)
989
+ self.assertAlmostEqual(float(proc_value[1]), psutil_value[1], delta=1)
990
+ self.assertAlmostEqual(float(proc_value[2]), psutil_value[2], delta=1)
991
+
992
+
993
+ # =====================================================================
994
+ # --- system network
995
+ # =====================================================================
996
+
997
+
998
+ @unittest.skipIf(not LINUX, "LINUX only")
999
+ class TestSystemNetIfAddrs(PsutilTestCase):
1000
+ def test_ips(self):
1001
+ for name, addrs in psutil.net_if_addrs().items():
1002
+ for addr in addrs:
1003
+ if addr.family == psutil.AF_LINK:
1004
+ self.assertEqual(addr.address, get_mac_address(name))
1005
+ elif addr.family == socket.AF_INET:
1006
+ self.assertEqual(addr.address, get_ipv4_address(name))
1007
+ self.assertEqual(addr.netmask, get_ipv4_netmask(name))
1008
+ if addr.broadcast is not None:
1009
+ self.assertEqual(
1010
+ addr.broadcast, get_ipv4_broadcast(name)
1011
+ )
1012
+ else:
1013
+ self.assertEqual(get_ipv4_broadcast(name), '0.0.0.0')
1014
+ elif addr.family == socket.AF_INET6:
1015
+ # IPv6 addresses can have a percent symbol at the end.
1016
+ # E.g. these 2 are equivalent:
1017
+ # "fe80::1ff:fe23:4567:890a"
1018
+ # "fe80::1ff:fe23:4567:890a%eth0"
1019
+ # That is the "zone id" portion, which usually is the name
1020
+ # of the network interface.
1021
+ address = addr.address.split('%')[0]
1022
+ self.assertIn(address, get_ipv6_addresses(name))
1023
+
1024
+ # XXX - not reliable when having virtual NICs installed by Docker.
1025
+ # @unittest.skipIf(not which('ip'), "'ip' utility not available")
1026
+ # def test_net_if_names(self):
1027
+ # out = sh("ip addr").strip()
1028
+ # nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
1029
+ # found = 0
1030
+ # for line in out.split('\n'):
1031
+ # line = line.strip()
1032
+ # if re.search(r"^\d+:", line):
1033
+ # found += 1
1034
+ # name = line.split(':')[1].strip()
1035
+ # self.assertIn(name, nics)
1036
+ # self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
1037
+ # pprint.pformat(nics), out))
1038
+
1039
+
1040
+ @unittest.skipIf(not LINUX, "LINUX only")
1041
+ class TestSystemNetIfStats(PsutilTestCase):
1042
+ @unittest.skipIf(not which("ifconfig"), "ifconfig utility not available")
1043
+ def test_against_ifconfig(self):
1044
+ for name, stats in psutil.net_if_stats().items():
1045
+ try:
1046
+ out = sh("ifconfig %s" % name)
1047
+ except RuntimeError:
1048
+ pass
1049
+ else:
1050
+ self.assertEqual(stats.isup, 'RUNNING' in out, msg=out)
1051
+ self.assertEqual(
1052
+ stats.mtu, int(re.findall(r'(?i)MTU[: ](\d+)', out)[0])
1053
+ )
1054
+
1055
+ def test_mtu(self):
1056
+ for name, stats in psutil.net_if_stats().items():
1057
+ with open("/sys/class/net/%s/mtu" % name) as f:
1058
+ self.assertEqual(stats.mtu, int(f.read().strip()))
1059
+
1060
+ @unittest.skipIf(not which("ifconfig"), "ifconfig utility not available")
1061
+ def test_flags(self):
1062
+ # first line looks like this:
1063
+ # "eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500"
1064
+ matches_found = 0
1065
+ for name, stats in psutil.net_if_stats().items():
1066
+ try:
1067
+ out = sh("ifconfig %s" % name)
1068
+ except RuntimeError:
1069
+ pass
1070
+ else:
1071
+ match = re.search(r"flags=(\d+)?<(.*?)>", out)
1072
+ if match and len(match.groups()) >= 2:
1073
+ matches_found += 1
1074
+ ifconfig_flags = set(match.group(2).lower().split(","))
1075
+ psutil_flags = set(stats.flags.split(","))
1076
+ self.assertEqual(ifconfig_flags, psutil_flags)
1077
+ else:
1078
+ # ifconfig has a different output on CentOS 6
1079
+ # let's try that
1080
+ match = re.search(r"(.*) MTU:(\d+) Metric:(\d+)", out)
1081
+ if match and len(match.groups()) >= 3:
1082
+ matches_found += 1
1083
+ ifconfig_flags = set(match.group(1).lower().split())
1084
+ psutil_flags = set(stats.flags.split(","))
1085
+ self.assertEqual(ifconfig_flags, psutil_flags)
1086
+
1087
+ if not matches_found:
1088
+ raise self.fail("no matches were found")
1089
+
1090
+
1091
+ @unittest.skipIf(not LINUX, "LINUX only")
1092
+ class TestSystemNetIOCounters(PsutilTestCase):
1093
+ @unittest.skipIf(not which("ifconfig"), "ifconfig utility not available")
1094
+ @retry_on_failure()
1095
+ def test_against_ifconfig(self):
1096
+ def ifconfig(nic):
1097
+ ret = {}
1098
+ out = sh("ifconfig %s" % nic)
1099
+ ret['packets_recv'] = int(
1100
+ re.findall(r'RX packets[: ](\d+)', out)[0]
1101
+ )
1102
+ ret['packets_sent'] = int(
1103
+ re.findall(r'TX packets[: ](\d+)', out)[0]
1104
+ )
1105
+ ret['errin'] = int(re.findall(r'errors[: ](\d+)', out)[0])
1106
+ ret['errout'] = int(re.findall(r'errors[: ](\d+)', out)[1])
1107
+ ret['dropin'] = int(re.findall(r'dropped[: ](\d+)', out)[0])
1108
+ ret['dropout'] = int(re.findall(r'dropped[: ](\d+)', out)[1])
1109
+ ret['bytes_recv'] = int(
1110
+ re.findall(r'RX (?:packets \d+ +)?bytes[: ](\d+)', out)[0]
1111
+ )
1112
+ ret['bytes_sent'] = int(
1113
+ re.findall(r'TX (?:packets \d+ +)?bytes[: ](\d+)', out)[0]
1114
+ )
1115
+ return ret
1116
+
1117
+ nio = psutil.net_io_counters(pernic=True, nowrap=False)
1118
+ for name, stats in nio.items():
1119
+ try:
1120
+ ifconfig_ret = ifconfig(name)
1121
+ except RuntimeError:
1122
+ continue
1123
+ self.assertAlmostEqual(
1124
+ stats.bytes_recv, ifconfig_ret['bytes_recv'], delta=1024 * 5
1125
+ )
1126
+ self.assertAlmostEqual(
1127
+ stats.bytes_sent, ifconfig_ret['bytes_sent'], delta=1024 * 5
1128
+ )
1129
+ self.assertAlmostEqual(
1130
+ stats.packets_recv, ifconfig_ret['packets_recv'], delta=1024
1131
+ )
1132
+ self.assertAlmostEqual(
1133
+ stats.packets_sent, ifconfig_ret['packets_sent'], delta=1024
1134
+ )
1135
+ self.assertAlmostEqual(
1136
+ stats.errin, ifconfig_ret['errin'], delta=10
1137
+ )
1138
+ self.assertAlmostEqual(
1139
+ stats.errout, ifconfig_ret['errout'], delta=10
1140
+ )
1141
+ self.assertAlmostEqual(
1142
+ stats.dropin, ifconfig_ret['dropin'], delta=10
1143
+ )
1144
+ self.assertAlmostEqual(
1145
+ stats.dropout, ifconfig_ret['dropout'], delta=10
1146
+ )
1147
+
1148
+
1149
+ @unittest.skipIf(not LINUX, "LINUX only")
1150
+ class TestSystemNetConnections(PsutilTestCase):
1151
+ @mock.patch('psutil._pslinux.socket.inet_ntop', side_effect=ValueError)
1152
+ @mock.patch('psutil._pslinux.supports_ipv6', return_value=False)
1153
+ def test_emulate_ipv6_unsupported(self, supports_ipv6, inet_ntop):
1154
+ # see: https://github.com/giampaolo/psutil/issues/623
1155
+ try:
1156
+ s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
1157
+ self.addCleanup(s.close)
1158
+ s.bind(("::1", 0))
1159
+ except socket.error:
1160
+ pass
1161
+ psutil.net_connections(kind='inet6')
1162
+
1163
+ def test_emulate_unix(self):
1164
+ content = textwrap.dedent("""\
1165
+ 0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n
1166
+ 0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ
1167
+ 0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O
1168
+ 000000000000000000000000000000000000000000000000000000
1169
+ """)
1170
+ with mock_open_content({"/proc/net/unix": content}) as m:
1171
+ psutil.net_connections(kind='unix')
1172
+ assert m.called
1173
+
1174
+
1175
+ # =====================================================================
1176
+ # --- system disks
1177
+ # =====================================================================
1178
+
1179
+
1180
+ @unittest.skipIf(not LINUX, "LINUX only")
1181
+ class TestSystemDiskPartitions(PsutilTestCase):
1182
+ @unittest.skipIf(not hasattr(os, 'statvfs'), "os.statvfs() not available")
1183
+ @skip_on_not_implemented()
1184
+ def test_against_df(self):
1185
+ # test psutil.disk_usage() and psutil.disk_partitions()
1186
+ # against "df -a"
1187
+ def df(path):
1188
+ out = sh('df -P -B 1 "%s"' % path).strip()
1189
+ lines = out.split('\n')
1190
+ lines.pop(0)
1191
+ line = lines.pop(0)
1192
+ dev, total, used, free = line.split()[:4]
1193
+ if dev == 'none':
1194
+ dev = ''
1195
+ total, used, free = int(total), int(used), int(free)
1196
+ return dev, total, used, free
1197
+
1198
+ for part in psutil.disk_partitions(all=False):
1199
+ usage = psutil.disk_usage(part.mountpoint)
1200
+ _, total, used, free = df(part.mountpoint)
1201
+ self.assertEqual(usage.total, total)
1202
+ self.assertAlmostEqual(
1203
+ usage.free, free, delta=TOLERANCE_DISK_USAGE
1204
+ )
1205
+ self.assertAlmostEqual(
1206
+ usage.used, used, delta=TOLERANCE_DISK_USAGE
1207
+ )
1208
+
1209
+ def test_zfs_fs(self):
1210
+ # Test that ZFS partitions are returned.
1211
+ with open("/proc/filesystems") as f:
1212
+ data = f.read()
1213
+ if 'zfs' in data:
1214
+ for part in psutil.disk_partitions():
1215
+ if part.fstype == 'zfs':
1216
+ break
1217
+ else:
1218
+ raise self.fail("couldn't find any ZFS partition")
1219
+ else:
1220
+ # No ZFS partitions on this system. Let's fake one.
1221
+ fake_file = io.StringIO(u("nodev\tzfs\n"))
1222
+ with mock.patch(
1223
+ 'psutil._common.open', return_value=fake_file, create=True
1224
+ ) as m1:
1225
+ with mock.patch(
1226
+ 'psutil._pslinux.cext.disk_partitions',
1227
+ return_value=[('/dev/sdb3', '/', 'zfs', 'rw')],
1228
+ ) as m2:
1229
+ ret = psutil.disk_partitions()
1230
+ assert m1.called
1231
+ assert m2.called
1232
+ assert ret
1233
+ self.assertEqual(ret[0].fstype, 'zfs')
1234
+
1235
+ def test_emulate_realpath_fail(self):
1236
+ # See: https://github.com/giampaolo/psutil/issues/1307
1237
+ try:
1238
+ with mock.patch(
1239
+ 'os.path.realpath', return_value='/non/existent'
1240
+ ) as m:
1241
+ with self.assertRaises(FileNotFoundError):
1242
+ psutil.disk_partitions()
1243
+ assert m.called
1244
+ finally:
1245
+ psutil.PROCFS_PATH = "/proc"
1246
+
1247
+
1248
+ @unittest.skipIf(not LINUX, "LINUX only")
1249
+ class TestSystemDiskIoCounters(PsutilTestCase):
1250
+ def test_emulate_kernel_2_4(self):
1251
+ # Tests /proc/diskstats parsing format for 2.4 kernels, see:
1252
+ # https://github.com/giampaolo/psutil/issues/767
1253
+ content = " 3 0 1 hda 2 3 4 5 6 7 8 9 10 11 12"
1254
+ with mock_open_content({'/proc/diskstats': content}):
1255
+ with mock.patch(
1256
+ 'psutil._pslinux.is_storage_device', return_value=True
1257
+ ):
1258
+ ret = psutil.disk_io_counters(nowrap=False)
1259
+ self.assertEqual(ret.read_count, 1)
1260
+ self.assertEqual(ret.read_merged_count, 2)
1261
+ self.assertEqual(ret.read_bytes, 3 * SECTOR_SIZE)
1262
+ self.assertEqual(ret.read_time, 4)
1263
+ self.assertEqual(ret.write_count, 5)
1264
+ self.assertEqual(ret.write_merged_count, 6)
1265
+ self.assertEqual(ret.write_bytes, 7 * SECTOR_SIZE)
1266
+ self.assertEqual(ret.write_time, 8)
1267
+ self.assertEqual(ret.busy_time, 10)
1268
+
1269
+ def test_emulate_kernel_2_6_full(self):
1270
+ # Tests /proc/diskstats parsing format for 2.6 kernels,
1271
+ # lines reporting all metrics:
1272
+ # https://github.com/giampaolo/psutil/issues/767
1273
+ content = " 3 0 hda 1 2 3 4 5 6 7 8 9 10 11"
1274
+ with mock_open_content({"/proc/diskstats": content}):
1275
+ with mock.patch(
1276
+ 'psutil._pslinux.is_storage_device', return_value=True
1277
+ ):
1278
+ ret = psutil.disk_io_counters(nowrap=False)
1279
+ self.assertEqual(ret.read_count, 1)
1280
+ self.assertEqual(ret.read_merged_count, 2)
1281
+ self.assertEqual(ret.read_bytes, 3 * SECTOR_SIZE)
1282
+ self.assertEqual(ret.read_time, 4)
1283
+ self.assertEqual(ret.write_count, 5)
1284
+ self.assertEqual(ret.write_merged_count, 6)
1285
+ self.assertEqual(ret.write_bytes, 7 * SECTOR_SIZE)
1286
+ self.assertEqual(ret.write_time, 8)
1287
+ self.assertEqual(ret.busy_time, 10)
1288
+
1289
+ def test_emulate_kernel_2_6_limited(self):
1290
+ # Tests /proc/diskstats parsing format for 2.6 kernels,
1291
+ # where one line of /proc/partitions return a limited
1292
+ # amount of metrics when it bumps into a partition
1293
+ # (instead of a disk). See:
1294
+ # https://github.com/giampaolo/psutil/issues/767
1295
+ with mock_open_content({"/proc/diskstats": " 3 1 hda 1 2 3 4"}):
1296
+ with mock.patch(
1297
+ 'psutil._pslinux.is_storage_device', return_value=True
1298
+ ):
1299
+ ret = psutil.disk_io_counters(nowrap=False)
1300
+ self.assertEqual(ret.read_count, 1)
1301
+ self.assertEqual(ret.read_bytes, 2 * SECTOR_SIZE)
1302
+ self.assertEqual(ret.write_count, 3)
1303
+ self.assertEqual(ret.write_bytes, 4 * SECTOR_SIZE)
1304
+
1305
+ self.assertEqual(ret.read_merged_count, 0)
1306
+ self.assertEqual(ret.read_time, 0)
1307
+ self.assertEqual(ret.write_merged_count, 0)
1308
+ self.assertEqual(ret.write_time, 0)
1309
+ self.assertEqual(ret.busy_time, 0)
1310
+
1311
+ def test_emulate_include_partitions(self):
1312
+ # Make sure that when perdisk=True disk partitions are returned,
1313
+ # see:
1314
+ # https://github.com/giampaolo/psutil/pull/1313#issuecomment-408626842
1315
+ content = textwrap.dedent("""\
1316
+ 3 0 nvme0n1 1 2 3 4 5 6 7 8 9 10 11
1317
+ 3 0 nvme0n1p1 1 2 3 4 5 6 7 8 9 10 11
1318
+ """)
1319
+ with mock_open_content({"/proc/diskstats": content}):
1320
+ with mock.patch(
1321
+ 'psutil._pslinux.is_storage_device', return_value=False
1322
+ ):
1323
+ ret = psutil.disk_io_counters(perdisk=True, nowrap=False)
1324
+ self.assertEqual(len(ret), 2)
1325
+ self.assertEqual(ret['nvme0n1'].read_count, 1)
1326
+ self.assertEqual(ret['nvme0n1p1'].read_count, 1)
1327
+ self.assertEqual(ret['nvme0n1'].write_count, 5)
1328
+ self.assertEqual(ret['nvme0n1p1'].write_count, 5)
1329
+
1330
+ def test_emulate_exclude_partitions(self):
1331
+ # Make sure that when perdisk=False partitions (e.g. 'sda1',
1332
+ # 'nvme0n1p1') are skipped and not included in the total count.
1333
+ # https://github.com/giampaolo/psutil/pull/1313#issuecomment-408626842
1334
+ content = textwrap.dedent("""\
1335
+ 3 0 nvme0n1 1 2 3 4 5 6 7 8 9 10 11
1336
+ 3 0 nvme0n1p1 1 2 3 4 5 6 7 8 9 10 11
1337
+ """)
1338
+ with mock_open_content({"/proc/diskstats": content}):
1339
+ with mock.patch(
1340
+ 'psutil._pslinux.is_storage_device', return_value=False
1341
+ ):
1342
+ ret = psutil.disk_io_counters(perdisk=False, nowrap=False)
1343
+ self.assertIsNone(ret)
1344
+
1345
+ #
1346
+ def is_storage_device(name):
1347
+ return name == 'nvme0n1'
1348
+
1349
+ content = textwrap.dedent("""\
1350
+ 3 0 nvme0n1 1 2 3 4 5 6 7 8 9 10 11
1351
+ 3 0 nvme0n1p1 1 2 3 4 5 6 7 8 9 10 11
1352
+ """)
1353
+ with mock_open_content({"/proc/diskstats": content}):
1354
+ with mock.patch(
1355
+ 'psutil._pslinux.is_storage_device',
1356
+ create=True,
1357
+ side_effect=is_storage_device,
1358
+ ):
1359
+ ret = psutil.disk_io_counters(perdisk=False, nowrap=False)
1360
+ self.assertEqual(ret.read_count, 1)
1361
+ self.assertEqual(ret.write_count, 5)
1362
+
1363
+ def test_emulate_use_sysfs(self):
1364
+ def exists(path):
1365
+ if path == '/proc/diskstats':
1366
+ return False
1367
+ return True
1368
+
1369
+ wprocfs = psutil.disk_io_counters(perdisk=True)
1370
+ with mock.patch(
1371
+ 'psutil._pslinux.os.path.exists', create=True, side_effect=exists
1372
+ ):
1373
+ wsysfs = psutil.disk_io_counters(perdisk=True)
1374
+ self.assertEqual(len(wprocfs), len(wsysfs))
1375
+
1376
+ def test_emulate_not_impl(self):
1377
+ def exists(path):
1378
+ return False
1379
+
1380
+ with mock.patch(
1381
+ 'psutil._pslinux.os.path.exists', create=True, side_effect=exists
1382
+ ):
1383
+ self.assertRaises(NotImplementedError, psutil.disk_io_counters)
1384
+
1385
+
1386
+ @unittest.skipIf(not LINUX, "LINUX only")
1387
+ class TestRootFsDeviceFinder(PsutilTestCase):
1388
+ def setUp(self):
1389
+ dev = os.stat("/").st_dev
1390
+ self.major = os.major(dev)
1391
+ self.minor = os.minor(dev)
1392
+
1393
+ def test_call_methods(self):
1394
+ finder = RootFsDeviceFinder()
1395
+ if os.path.exists("/proc/partitions"):
1396
+ finder.ask_proc_partitions()
1397
+ else:
1398
+ self.assertRaises(FileNotFoundError, finder.ask_proc_partitions)
1399
+ if os.path.exists(
1400
+ "/sys/dev/block/%s:%s/uevent" % (self.major, self.minor)
1401
+ ):
1402
+ finder.ask_sys_dev_block()
1403
+ else:
1404
+ self.assertRaises(FileNotFoundError, finder.ask_sys_dev_block)
1405
+ finder.ask_sys_class_block()
1406
+
1407
+ @unittest.skipIf(GITHUB_ACTIONS, "unsupported on GITHUB_ACTIONS")
1408
+ def test_comparisons(self):
1409
+ finder = RootFsDeviceFinder()
1410
+ self.assertIsNotNone(finder.find())
1411
+
1412
+ a = b = c = None
1413
+ if os.path.exists("/proc/partitions"):
1414
+ a = finder.ask_proc_partitions()
1415
+ if os.path.exists(
1416
+ "/sys/dev/block/%s:%s/uevent" % (self.major, self.minor)
1417
+ ):
1418
+ b = finder.ask_sys_class_block()
1419
+ c = finder.ask_sys_dev_block()
1420
+
1421
+ base = a or b or c
1422
+ if base and a:
1423
+ self.assertEqual(base, a)
1424
+ if base and b:
1425
+ self.assertEqual(base, b)
1426
+ if base and c:
1427
+ self.assertEqual(base, c)
1428
+
1429
+ @unittest.skipIf(not which("findmnt"), "findmnt utility not available")
1430
+ @unittest.skipIf(GITHUB_ACTIONS, "unsupported on GITHUB_ACTIONS")
1431
+ def test_against_findmnt(self):
1432
+ psutil_value = RootFsDeviceFinder().find()
1433
+ findmnt_value = sh("findmnt -o SOURCE -rn /")
1434
+ self.assertEqual(psutil_value, findmnt_value)
1435
+
1436
+ def test_disk_partitions_mocked(self):
1437
+ with mock.patch(
1438
+ 'psutil._pslinux.cext.disk_partitions',
1439
+ return_value=[('/dev/root', '/', 'ext4', 'rw')],
1440
+ ) as m:
1441
+ part = psutil.disk_partitions()[0]
1442
+ assert m.called
1443
+ if not GITHUB_ACTIONS:
1444
+ self.assertNotEqual(part.device, "/dev/root")
1445
+ self.assertEqual(part.device, RootFsDeviceFinder().find())
1446
+ else:
1447
+ self.assertEqual(part.device, "/dev/root")
1448
+
1449
+
1450
+ # =====================================================================
1451
+ # --- misc
1452
+ # =====================================================================
1453
+
1454
+
1455
+ @unittest.skipIf(not LINUX, "LINUX only")
1456
+ class TestMisc(PsutilTestCase):
1457
+ def test_boot_time(self):
1458
+ vmstat_value = vmstat('boot time')
1459
+ psutil_value = psutil.boot_time()
1460
+ self.assertEqual(int(vmstat_value), int(psutil_value))
1461
+
1462
+ def test_no_procfs_on_import(self):
1463
+ my_procfs = self.get_testfn()
1464
+ os.mkdir(my_procfs)
1465
+
1466
+ with open(os.path.join(my_procfs, 'stat'), 'w') as f:
1467
+ f.write('cpu 0 0 0 0 0 0 0 0 0 0\n')
1468
+ f.write('cpu0 0 0 0 0 0 0 0 0 0 0\n')
1469
+ f.write('cpu1 0 0 0 0 0 0 0 0 0 0\n')
1470
+
1471
+ try:
1472
+ orig_open = open
1473
+
1474
+ def open_mock(name, *args, **kwargs):
1475
+ if name.startswith('/proc'):
1476
+ raise IOError(errno.ENOENT, 'rejecting access for test')
1477
+ return orig_open(name, *args, **kwargs)
1478
+
1479
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1480
+ with mock.patch(patch_point, side_effect=open_mock):
1481
+ reload_module(psutil)
1482
+
1483
+ self.assertRaises(IOError, psutil.cpu_times)
1484
+ self.assertRaises(IOError, psutil.cpu_times, percpu=True)
1485
+ self.assertRaises(IOError, psutil.cpu_percent)
1486
+ self.assertRaises(IOError, psutil.cpu_percent, percpu=True)
1487
+ self.assertRaises(IOError, psutil.cpu_times_percent)
1488
+ self.assertRaises(
1489
+ IOError, psutil.cpu_times_percent, percpu=True
1490
+ )
1491
+
1492
+ psutil.PROCFS_PATH = my_procfs
1493
+
1494
+ self.assertEqual(psutil.cpu_percent(), 0)
1495
+ self.assertEqual(sum(psutil.cpu_times_percent()), 0)
1496
+
1497
+ # since we don't know the number of CPUs at import time,
1498
+ # we awkwardly say there are none until the second call
1499
+ per_cpu_percent = psutil.cpu_percent(percpu=True)
1500
+ self.assertEqual(sum(per_cpu_percent), 0)
1501
+
1502
+ # ditto awkward length
1503
+ per_cpu_times_percent = psutil.cpu_times_percent(percpu=True)
1504
+ self.assertEqual(sum(map(sum, per_cpu_times_percent)), 0)
1505
+
1506
+ # much user, very busy
1507
+ with open(os.path.join(my_procfs, 'stat'), 'w') as f:
1508
+ f.write('cpu 1 0 0 0 0 0 0 0 0 0\n')
1509
+ f.write('cpu0 1 0 0 0 0 0 0 0 0 0\n')
1510
+ f.write('cpu1 1 0 0 0 0 0 0 0 0 0\n')
1511
+
1512
+ self.assertNotEqual(psutil.cpu_percent(), 0)
1513
+ self.assertNotEqual(sum(psutil.cpu_percent(percpu=True)), 0)
1514
+ self.assertNotEqual(sum(psutil.cpu_times_percent()), 0)
1515
+ self.assertNotEqual(
1516
+ sum(map(sum, psutil.cpu_times_percent(percpu=True))), 0
1517
+ )
1518
+ finally:
1519
+ shutil.rmtree(my_procfs)
1520
+ reload_module(psutil)
1521
+
1522
+ self.assertEqual(psutil.PROCFS_PATH, '/proc')
1523
+
1524
+ def test_cpu_steal_decrease(self):
1525
+ # Test cumulative cpu stats decrease. We should ignore this.
1526
+ # See issue #1210.
1527
+ content = textwrap.dedent("""\
1528
+ cpu 0 0 0 0 0 0 0 1 0 0
1529
+ cpu0 0 0 0 0 0 0 0 1 0 0
1530
+ cpu1 0 0 0 0 0 0 0 1 0 0
1531
+ """).encode()
1532
+ with mock_open_content({"/proc/stat": content}) as m:
1533
+ # first call to "percent" functions should read the new stat file
1534
+ # and compare to the "real" file read at import time - so the
1535
+ # values are meaningless
1536
+ psutil.cpu_percent()
1537
+ assert m.called
1538
+ psutil.cpu_percent(percpu=True)
1539
+ psutil.cpu_times_percent()
1540
+ psutil.cpu_times_percent(percpu=True)
1541
+
1542
+ content = textwrap.dedent("""\
1543
+ cpu 1 0 0 0 0 0 0 0 0 0
1544
+ cpu0 1 0 0 0 0 0 0 0 0 0
1545
+ cpu1 1 0 0 0 0 0 0 0 0 0
1546
+ """).encode()
1547
+ with mock_open_content({"/proc/stat": content}):
1548
+ # Increase "user" while steal goes "backwards" to zero.
1549
+ cpu_percent = psutil.cpu_percent()
1550
+ assert m.called
1551
+ cpu_percent_percpu = psutil.cpu_percent(percpu=True)
1552
+ cpu_times_percent = psutil.cpu_times_percent()
1553
+ cpu_times_percent_percpu = psutil.cpu_times_percent(percpu=True)
1554
+ self.assertNotEqual(cpu_percent, 0)
1555
+ self.assertNotEqual(sum(cpu_percent_percpu), 0)
1556
+ self.assertNotEqual(sum(cpu_times_percent), 0)
1557
+ self.assertNotEqual(sum(cpu_times_percent), 100.0)
1558
+ self.assertNotEqual(sum(map(sum, cpu_times_percent_percpu)), 0)
1559
+ self.assertNotEqual(sum(map(sum, cpu_times_percent_percpu)), 100.0)
1560
+ self.assertEqual(cpu_times_percent.steal, 0)
1561
+ self.assertNotEqual(cpu_times_percent.user, 0)
1562
+
1563
+ def test_boot_time_mocked(self):
1564
+ with mock.patch('psutil._common.open', create=True) as m:
1565
+ self.assertRaises(RuntimeError, psutil._pslinux.boot_time)
1566
+ assert m.called
1567
+
1568
+ def test_users(self):
1569
+ # Make sure the C extension converts ':0' and ':0.0' to
1570
+ # 'localhost'.
1571
+ for user in psutil.users():
1572
+ self.assertNotIn(user.host, (":0", ":0.0"))
1573
+
1574
+ def test_procfs_path(self):
1575
+ tdir = self.get_testfn()
1576
+ os.mkdir(tdir)
1577
+ try:
1578
+ psutil.PROCFS_PATH = tdir
1579
+ self.assertRaises(IOError, psutil.virtual_memory)
1580
+ self.assertRaises(IOError, psutil.cpu_times)
1581
+ self.assertRaises(IOError, psutil.cpu_times, percpu=True)
1582
+ self.assertRaises(IOError, psutil.boot_time)
1583
+ # self.assertRaises(IOError, psutil.pids)
1584
+ self.assertRaises(IOError, psutil.net_connections)
1585
+ self.assertRaises(IOError, psutil.net_io_counters)
1586
+ self.assertRaises(IOError, psutil.net_if_stats)
1587
+ # self.assertRaises(IOError, psutil.disk_io_counters)
1588
+ self.assertRaises(IOError, psutil.disk_partitions)
1589
+ self.assertRaises(psutil.NoSuchProcess, psutil.Process)
1590
+ finally:
1591
+ psutil.PROCFS_PATH = "/proc"
1592
+
1593
+ @retry_on_failure()
1594
+ def test_issue_687(self):
1595
+ # In case of thread ID:
1596
+ # - pid_exists() is supposed to return False
1597
+ # - Process(tid) is supposed to work
1598
+ # - pids() should not return the TID
1599
+ # See: https://github.com/giampaolo/psutil/issues/687
1600
+ with ThreadTask():
1601
+ p = psutil.Process()
1602
+ threads = p.threads()
1603
+ self.assertEqual(len(threads), 2)
1604
+ tid = sorted(threads, key=lambda x: x.id)[1].id
1605
+ self.assertNotEqual(p.pid, tid)
1606
+ pt = psutil.Process(tid)
1607
+ pt.as_dict()
1608
+ self.assertNotIn(tid, psutil.pids())
1609
+
1610
+ def test_pid_exists_no_proc_status(self):
1611
+ # Internally pid_exists relies on /proc/{pid}/status.
1612
+ # Emulate a case where this file is empty in which case
1613
+ # psutil is supposed to fall back on using pids().
1614
+ with mock_open_content({"/proc/%s/status": ""}) as m:
1615
+ assert psutil.pid_exists(os.getpid())
1616
+ assert m.called
1617
+
1618
+
1619
+ # =====================================================================
1620
+ # --- sensors
1621
+ # =====================================================================
1622
+
1623
+
1624
+ @unittest.skipIf(not LINUX, "LINUX only")
1625
+ @unittest.skipIf(not HAS_BATTERY, "no battery")
1626
+ class TestSensorsBattery(PsutilTestCase):
1627
+ @unittest.skipIf(not which("acpi"), "acpi utility not available")
1628
+ def test_percent(self):
1629
+ out = sh("acpi -b")
1630
+ acpi_value = int(out.split(",")[1].strip().replace('%', ''))
1631
+ psutil_value = psutil.sensors_battery().percent
1632
+ self.assertAlmostEqual(acpi_value, psutil_value, delta=1)
1633
+
1634
+ def test_emulate_power_plugged(self):
1635
+ # Pretend the AC power cable is connected.
1636
+ def open_mock(name, *args, **kwargs):
1637
+ if name.endswith(('AC0/online', 'AC/online')):
1638
+ return io.BytesIO(b"1")
1639
+ else:
1640
+ return orig_open(name, *args, **kwargs)
1641
+
1642
+ orig_open = open
1643
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1644
+ with mock.patch(patch_point, side_effect=open_mock) as m:
1645
+ self.assertEqual(psutil.sensors_battery().power_plugged, True)
1646
+ self.assertEqual(
1647
+ psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNLIMITED
1648
+ )
1649
+ assert m.called
1650
+
1651
+ def test_emulate_power_plugged_2(self):
1652
+ # Same as above but pretend /AC0/online does not exist in which
1653
+ # case code relies on /status file.
1654
+ def open_mock(name, *args, **kwargs):
1655
+ if name.endswith(('AC0/online', 'AC/online')):
1656
+ raise IOError(errno.ENOENT, "")
1657
+ elif name.endswith("/status"):
1658
+ return io.StringIO(u("charging"))
1659
+ else:
1660
+ return orig_open(name, *args, **kwargs)
1661
+
1662
+ orig_open = open
1663
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1664
+ with mock.patch(patch_point, side_effect=open_mock) as m:
1665
+ self.assertEqual(psutil.sensors_battery().power_plugged, True)
1666
+ assert m.called
1667
+
1668
+ def test_emulate_power_not_plugged(self):
1669
+ # Pretend the AC power cable is not connected.
1670
+ def open_mock(name, *args, **kwargs):
1671
+ if name.endswith(('AC0/online', 'AC/online')):
1672
+ return io.BytesIO(b"0")
1673
+ else:
1674
+ return orig_open(name, *args, **kwargs)
1675
+
1676
+ orig_open = open
1677
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1678
+ with mock.patch(patch_point, side_effect=open_mock) as m:
1679
+ self.assertEqual(psutil.sensors_battery().power_plugged, False)
1680
+ assert m.called
1681
+
1682
+ def test_emulate_power_not_plugged_2(self):
1683
+ # Same as above but pretend /AC0/online does not exist in which
1684
+ # case code relies on /status file.
1685
+ def open_mock(name, *args, **kwargs):
1686
+ if name.endswith(('AC0/online', 'AC/online')):
1687
+ raise IOError(errno.ENOENT, "")
1688
+ elif name.endswith("/status"):
1689
+ return io.StringIO(u("discharging"))
1690
+ else:
1691
+ return orig_open(name, *args, **kwargs)
1692
+
1693
+ orig_open = open
1694
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1695
+ with mock.patch(patch_point, side_effect=open_mock) as m:
1696
+ self.assertEqual(psutil.sensors_battery().power_plugged, False)
1697
+ assert m.called
1698
+
1699
+ def test_emulate_power_undetermined(self):
1700
+ # Pretend we can't know whether the AC power cable not
1701
+ # connected (assert fallback to False).
1702
+ def open_mock(name, *args, **kwargs):
1703
+ if name.startswith((
1704
+ '/sys/class/power_supply/AC0/online',
1705
+ '/sys/class/power_supply/AC/online',
1706
+ )):
1707
+ raise IOError(errno.ENOENT, "")
1708
+ elif name.startswith("/sys/class/power_supply/BAT0/status"):
1709
+ return io.BytesIO(b"???")
1710
+ else:
1711
+ return orig_open(name, *args, **kwargs)
1712
+
1713
+ orig_open = open
1714
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1715
+ with mock.patch(patch_point, side_effect=open_mock) as m:
1716
+ self.assertIsNone(psutil.sensors_battery().power_plugged)
1717
+ assert m.called
1718
+
1719
+ def test_emulate_energy_full_0(self):
1720
+ # Emulate a case where energy_full files returns 0.
1721
+ with mock_open_content(
1722
+ {"/sys/class/power_supply/BAT0/energy_full": b"0"}
1723
+ ) as m:
1724
+ self.assertEqual(psutil.sensors_battery().percent, 0)
1725
+ assert m.called
1726
+
1727
+ def test_emulate_energy_full_not_avail(self):
1728
+ # Emulate a case where energy_full file does not exist.
1729
+ # Expected fallback on /capacity.
1730
+ with mock_open_exception(
1731
+ "/sys/class/power_supply/BAT0/energy_full",
1732
+ IOError(errno.ENOENT, ""),
1733
+ ):
1734
+ with mock_open_exception(
1735
+ "/sys/class/power_supply/BAT0/charge_full",
1736
+ IOError(errno.ENOENT, ""),
1737
+ ):
1738
+ with mock_open_content(
1739
+ {"/sys/class/power_supply/BAT0/capacity": b"88"}
1740
+ ):
1741
+ self.assertEqual(psutil.sensors_battery().percent, 88)
1742
+
1743
+ def test_emulate_no_power(self):
1744
+ # Emulate a case where /AC0/online file nor /BAT0/status exist.
1745
+ with mock_open_exception(
1746
+ "/sys/class/power_supply/AC/online", IOError(errno.ENOENT, "")
1747
+ ):
1748
+ with mock_open_exception(
1749
+ "/sys/class/power_supply/AC0/online", IOError(errno.ENOENT, "")
1750
+ ):
1751
+ with mock_open_exception(
1752
+ "/sys/class/power_supply/BAT0/status",
1753
+ IOError(errno.ENOENT, ""),
1754
+ ):
1755
+ self.assertIsNone(psutil.sensors_battery().power_plugged)
1756
+
1757
+
1758
+ @unittest.skipIf(not LINUX, "LINUX only")
1759
+ class TestSensorsBatteryEmulated(PsutilTestCase):
1760
+ def test_it(self):
1761
+ def open_mock(name, *args, **kwargs):
1762
+ if name.endswith("/energy_now"):
1763
+ return io.StringIO(u("60000000"))
1764
+ elif name.endswith("/power_now"):
1765
+ return io.StringIO(u("0"))
1766
+ elif name.endswith("/energy_full"):
1767
+ return io.StringIO(u("60000001"))
1768
+ else:
1769
+ return orig_open(name, *args, **kwargs)
1770
+
1771
+ orig_open = open
1772
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1773
+ with mock.patch('os.listdir', return_value=["BAT0"]) as mlistdir:
1774
+ with mock.patch(patch_point, side_effect=open_mock) as mopen:
1775
+ self.assertIsNotNone(psutil.sensors_battery())
1776
+ assert mlistdir.called
1777
+ assert mopen.called
1778
+
1779
+
1780
+ @unittest.skipIf(not LINUX, "LINUX only")
1781
+ class TestSensorsTemperatures(PsutilTestCase):
1782
+ def test_emulate_class_hwmon(self):
1783
+ def open_mock(name, *args, **kwargs):
1784
+ if name.endswith('/name'):
1785
+ return io.StringIO(u("name"))
1786
+ elif name.endswith('/temp1_label'):
1787
+ return io.StringIO(u("label"))
1788
+ elif name.endswith('/temp1_input'):
1789
+ return io.BytesIO(b"30000")
1790
+ elif name.endswith('/temp1_max'):
1791
+ return io.BytesIO(b"40000")
1792
+ elif name.endswith('/temp1_crit'):
1793
+ return io.BytesIO(b"50000")
1794
+ else:
1795
+ return orig_open(name, *args, **kwargs)
1796
+
1797
+ orig_open = open
1798
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1799
+ with mock.patch(patch_point, side_effect=open_mock):
1800
+ # Test case with /sys/class/hwmon
1801
+ with mock.patch(
1802
+ 'glob.glob', return_value=['/sys/class/hwmon/hwmon0/temp1']
1803
+ ):
1804
+ temp = psutil.sensors_temperatures()['name'][0]
1805
+ self.assertEqual(temp.label, 'label')
1806
+ self.assertEqual(temp.current, 30.0)
1807
+ self.assertEqual(temp.high, 40.0)
1808
+ self.assertEqual(temp.critical, 50.0)
1809
+
1810
+ def test_emulate_class_thermal(self):
1811
+ def open_mock(name, *args, **kwargs):
1812
+ if name.endswith('0_temp'):
1813
+ return io.BytesIO(b"50000")
1814
+ elif name.endswith('temp'):
1815
+ return io.BytesIO(b"30000")
1816
+ elif name.endswith('0_type'):
1817
+ return io.StringIO(u("critical"))
1818
+ elif name.endswith('type'):
1819
+ return io.StringIO(u("name"))
1820
+ else:
1821
+ return orig_open(name, *args, **kwargs)
1822
+
1823
+ def glob_mock(path):
1824
+ if path == '/sys/class/hwmon/hwmon*/temp*_*': # noqa
1825
+ return []
1826
+ elif path == '/sys/class/hwmon/hwmon*/device/temp*_*':
1827
+ return []
1828
+ elif path == '/sys/class/thermal/thermal_zone*':
1829
+ return ['/sys/class/thermal/thermal_zone0']
1830
+ elif path == '/sys/class/thermal/thermal_zone0/trip_point*':
1831
+ return [
1832
+ '/sys/class/thermal/thermal_zone1/trip_point_0_type',
1833
+ '/sys/class/thermal/thermal_zone1/trip_point_0_temp',
1834
+ ]
1835
+ return []
1836
+
1837
+ orig_open = open
1838
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1839
+ with mock.patch(patch_point, side_effect=open_mock):
1840
+ with mock.patch('glob.glob', create=True, side_effect=glob_mock):
1841
+ temp = psutil.sensors_temperatures()['name'][0]
1842
+ self.assertEqual(temp.label, '')
1843
+ self.assertEqual(temp.current, 30.0)
1844
+ self.assertEqual(temp.high, 50.0)
1845
+ self.assertEqual(temp.critical, 50.0)
1846
+
1847
+
1848
+ @unittest.skipIf(not LINUX, "LINUX only")
1849
+ class TestSensorsFans(PsutilTestCase):
1850
+ def test_emulate_data(self):
1851
+ def open_mock(name, *args, **kwargs):
1852
+ if name.endswith('/name'):
1853
+ return io.StringIO(u("name"))
1854
+ elif name.endswith('/fan1_label'):
1855
+ return io.StringIO(u("label"))
1856
+ elif name.endswith('/fan1_input'):
1857
+ return io.StringIO(u("2000"))
1858
+ else:
1859
+ return orig_open(name, *args, **kwargs)
1860
+
1861
+ orig_open = open
1862
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1863
+ with mock.patch(patch_point, side_effect=open_mock):
1864
+ with mock.patch(
1865
+ 'glob.glob', return_value=['/sys/class/hwmon/hwmon2/fan1']
1866
+ ):
1867
+ fan = psutil.sensors_fans()['name'][0]
1868
+ self.assertEqual(fan.label, 'label')
1869
+ self.assertEqual(fan.current, 2000)
1870
+
1871
+
1872
+ # =====================================================================
1873
+ # --- test process
1874
+ # =====================================================================
1875
+
1876
+
1877
+ @unittest.skipIf(not LINUX, "LINUX only")
1878
+ class TestProcess(PsutilTestCase):
1879
+ @retry_on_failure()
1880
+ def test_parse_smaps_vs_memory_maps(self):
1881
+ sproc = self.spawn_testproc()
1882
+ uss, pss, swap = psutil._pslinux.Process(sproc.pid)._parse_smaps()
1883
+ maps = psutil.Process(sproc.pid).memory_maps(grouped=False)
1884
+ self.assertAlmostEqual(
1885
+ uss,
1886
+ sum([x.private_dirty + x.private_clean for x in maps]),
1887
+ delta=4096,
1888
+ )
1889
+ self.assertAlmostEqual(pss, sum([x.pss for x in maps]), delta=4096)
1890
+ self.assertAlmostEqual(swap, sum([x.swap for x in maps]), delta=4096)
1891
+
1892
+ def test_parse_smaps_mocked(self):
1893
+ # See: https://github.com/giampaolo/psutil/issues/1222
1894
+ content = textwrap.dedent("""\
1895
+ fffff0 r-xp 00000000 00:00 0 [vsyscall]
1896
+ Size: 1 kB
1897
+ Rss: 2 kB
1898
+ Pss: 3 kB
1899
+ Shared_Clean: 4 kB
1900
+ Shared_Dirty: 5 kB
1901
+ Private_Clean: 6 kB
1902
+ Private_Dirty: 7 kB
1903
+ Referenced: 8 kB
1904
+ Anonymous: 9 kB
1905
+ LazyFree: 10 kB
1906
+ AnonHugePages: 11 kB
1907
+ ShmemPmdMapped: 12 kB
1908
+ Shared_Hugetlb: 13 kB
1909
+ Private_Hugetlb: 14 kB
1910
+ Swap: 15 kB
1911
+ SwapPss: 16 kB
1912
+ KernelPageSize: 17 kB
1913
+ MMUPageSize: 18 kB
1914
+ Locked: 19 kB
1915
+ VmFlags: rd ex
1916
+ """).encode()
1917
+ with mock_open_content({"/proc/%s/smaps" % os.getpid(): content}) as m:
1918
+ p = psutil._pslinux.Process(os.getpid())
1919
+ uss, pss, swap = p._parse_smaps()
1920
+ assert m.called
1921
+ self.assertEqual(uss, (6 + 7 + 14) * 1024)
1922
+ self.assertEqual(pss, 3 * 1024)
1923
+ self.assertEqual(swap, 15 * 1024)
1924
+
1925
+ # On PYPY file descriptors are not closed fast enough.
1926
+ @unittest.skipIf(PYPY, "unreliable on PYPY")
1927
+ def test_open_files_mode(self):
1928
+ def get_test_file(fname):
1929
+ p = psutil.Process()
1930
+ giveup_at = time.time() + GLOBAL_TIMEOUT
1931
+ while True:
1932
+ for file in p.open_files():
1933
+ if file.path == os.path.abspath(fname):
1934
+ return file
1935
+ elif time.time() > giveup_at:
1936
+ break
1937
+ raise RuntimeError("timeout looking for test file")
1938
+
1939
+ #
1940
+ testfn = self.get_testfn()
1941
+ with open(testfn, "w"):
1942
+ self.assertEqual(get_test_file(testfn).mode, "w")
1943
+ with open(testfn):
1944
+ self.assertEqual(get_test_file(testfn).mode, "r")
1945
+ with open(testfn, "a"):
1946
+ self.assertEqual(get_test_file(testfn).mode, "a")
1947
+ #
1948
+ with open(testfn, "r+"):
1949
+ self.assertEqual(get_test_file(testfn).mode, "r+")
1950
+ with open(testfn, "w+"):
1951
+ self.assertEqual(get_test_file(testfn).mode, "r+")
1952
+ with open(testfn, "a+"):
1953
+ self.assertEqual(get_test_file(testfn).mode, "a+")
1954
+ # note: "x" bit is not supported
1955
+ if PY3:
1956
+ safe_rmpath(testfn)
1957
+ with open(testfn, "x"):
1958
+ self.assertEqual(get_test_file(testfn).mode, "w")
1959
+ safe_rmpath(testfn)
1960
+ with open(testfn, "x+"):
1961
+ self.assertEqual(get_test_file(testfn).mode, "r+")
1962
+
1963
+ def test_open_files_file_gone(self):
1964
+ # simulates a file which gets deleted during open_files()
1965
+ # execution
1966
+ p = psutil.Process()
1967
+ files = p.open_files()
1968
+ with open(self.get_testfn(), 'w'):
1969
+ # give the kernel some time to see the new file
1970
+ call_until(p.open_files, "len(ret) != %i" % len(files))
1971
+ with mock.patch(
1972
+ 'psutil._pslinux.os.readlink',
1973
+ side_effect=OSError(errno.ENOENT, ""),
1974
+ ) as m:
1975
+ self.assertEqual(p.open_files(), [])
1976
+ assert m.called
1977
+ # also simulate the case where os.readlink() returns EINVAL
1978
+ # in which case psutil is supposed to 'continue'
1979
+ with mock.patch(
1980
+ 'psutil._pslinux.os.readlink',
1981
+ side_effect=OSError(errno.EINVAL, ""),
1982
+ ) as m:
1983
+ self.assertEqual(p.open_files(), [])
1984
+ assert m.called
1985
+
1986
+ def test_open_files_fd_gone(self):
1987
+ # Simulate a case where /proc/{pid}/fdinfo/{fd} disappears
1988
+ # while iterating through fds.
1989
+ # https://travis-ci.org/giampaolo/psutil/jobs/225694530
1990
+ p = psutil.Process()
1991
+ files = p.open_files()
1992
+ with open(self.get_testfn(), 'w'):
1993
+ # give the kernel some time to see the new file
1994
+ call_until(p.open_files, "len(ret) != %i" % len(files))
1995
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
1996
+ with mock.patch(
1997
+ patch_point, side_effect=IOError(errno.ENOENT, "")
1998
+ ) as m:
1999
+ self.assertEqual(p.open_files(), [])
2000
+ assert m.called
2001
+
2002
+ def test_open_files_enametoolong(self):
2003
+ # Simulate a case where /proc/{pid}/fd/{fd} symlink
2004
+ # points to a file with full path longer than PATH_MAX, see:
2005
+ # https://github.com/giampaolo/psutil/issues/1940
2006
+ p = psutil.Process()
2007
+ files = p.open_files()
2008
+ with open(self.get_testfn(), 'w'):
2009
+ # give the kernel some time to see the new file
2010
+ call_until(p.open_files, "len(ret) != %i" % len(files))
2011
+ patch_point = 'psutil._pslinux.os.readlink'
2012
+ with mock.patch(
2013
+ patch_point, side_effect=OSError(errno.ENAMETOOLONG, "")
2014
+ ) as m:
2015
+ with mock.patch("psutil._pslinux.debug"):
2016
+ self.assertEqual(p.open_files(), [])
2017
+ assert m.called
2018
+
2019
+ # --- mocked tests
2020
+
2021
+ def test_terminal_mocked(self):
2022
+ with mock.patch(
2023
+ 'psutil._pslinux._psposix.get_terminal_map', return_value={}
2024
+ ) as m:
2025
+ self.assertIsNone(psutil._pslinux.Process(os.getpid()).terminal())
2026
+ assert m.called
2027
+
2028
+ # TODO: re-enable this test.
2029
+ # def test_num_ctx_switches_mocked(self):
2030
+ # with mock.patch('psutil._common.open', create=True) as m:
2031
+ # self.assertRaises(
2032
+ # NotImplementedError,
2033
+ # psutil._pslinux.Process(os.getpid()).num_ctx_switches)
2034
+ # assert m.called
2035
+
2036
+ def test_cmdline_mocked(self):
2037
+ # see: https://github.com/giampaolo/psutil/issues/639
2038
+ p = psutil.Process()
2039
+ fake_file = io.StringIO(u('foo\x00bar\x00'))
2040
+ with mock.patch(
2041
+ 'psutil._common.open', return_value=fake_file, create=True
2042
+ ) as m:
2043
+ self.assertEqual(p.cmdline(), ['foo', 'bar'])
2044
+ assert m.called
2045
+ fake_file = io.StringIO(u('foo\x00bar\x00\x00'))
2046
+ with mock.patch(
2047
+ 'psutil._common.open', return_value=fake_file, create=True
2048
+ ) as m:
2049
+ self.assertEqual(p.cmdline(), ['foo', 'bar', ''])
2050
+ assert m.called
2051
+
2052
+ def test_cmdline_spaces_mocked(self):
2053
+ # see: https://github.com/giampaolo/psutil/issues/1179
2054
+ p = psutil.Process()
2055
+ fake_file = io.StringIO(u('foo bar '))
2056
+ with mock.patch(
2057
+ 'psutil._common.open', return_value=fake_file, create=True
2058
+ ) as m:
2059
+ self.assertEqual(p.cmdline(), ['foo', 'bar'])
2060
+ assert m.called
2061
+ fake_file = io.StringIO(u('foo bar '))
2062
+ with mock.patch(
2063
+ 'psutil._common.open', return_value=fake_file, create=True
2064
+ ) as m:
2065
+ self.assertEqual(p.cmdline(), ['foo', 'bar', ''])
2066
+ assert m.called
2067
+
2068
+ def test_cmdline_mixed_separators(self):
2069
+ # https://github.com/giampaolo/psutil/issues/
2070
+ # 1179#issuecomment-552984549
2071
+ p = psutil.Process()
2072
+ fake_file = io.StringIO(u('foo\x20bar\x00'))
2073
+ with mock.patch(
2074
+ 'psutil._common.open', return_value=fake_file, create=True
2075
+ ) as m:
2076
+ self.assertEqual(p.cmdline(), ['foo', 'bar'])
2077
+ assert m.called
2078
+
2079
+ def test_readlink_path_deleted_mocked(self):
2080
+ with mock.patch(
2081
+ 'psutil._pslinux.os.readlink', return_value='/home/foo (deleted)'
2082
+ ):
2083
+ self.assertEqual(psutil.Process().exe(), "/home/foo")
2084
+ self.assertEqual(psutil.Process().cwd(), "/home/foo")
2085
+
2086
+ def test_threads_mocked(self):
2087
+ # Test the case where os.listdir() returns a file (thread)
2088
+ # which no longer exists by the time we open() it (race
2089
+ # condition). threads() is supposed to ignore that instead
2090
+ # of raising NSP.
2091
+ def open_mock_1(name, *args, **kwargs):
2092
+ if name.startswith('/proc/%s/task' % os.getpid()):
2093
+ raise IOError(errno.ENOENT, "")
2094
+ else:
2095
+ return orig_open(name, *args, **kwargs)
2096
+
2097
+ orig_open = open
2098
+ patch_point = 'builtins.open' if PY3 else '__builtin__.open'
2099
+ with mock.patch(patch_point, side_effect=open_mock_1) as m:
2100
+ ret = psutil.Process().threads()
2101
+ assert m.called
2102
+ self.assertEqual(ret, [])
2103
+
2104
+ # ...but if it bumps into something != ENOENT we want an
2105
+ # exception.
2106
+ def open_mock_2(name, *args, **kwargs):
2107
+ if name.startswith('/proc/%s/task' % os.getpid()):
2108
+ raise IOError(errno.EPERM, "")
2109
+ else:
2110
+ return orig_open(name, *args, **kwargs)
2111
+
2112
+ with mock.patch(patch_point, side_effect=open_mock_2):
2113
+ self.assertRaises(psutil.AccessDenied, psutil.Process().threads)
2114
+
2115
+ def test_exe_mocked(self):
2116
+ with mock.patch(
2117
+ 'psutil._pslinux.readlink', side_effect=OSError(errno.ENOENT, "")
2118
+ ) as m:
2119
+ ret = psutil.Process().exe()
2120
+ assert m.called
2121
+ self.assertEqual(ret, "")
2122
+
2123
+ def test_issue_1014(self):
2124
+ # Emulates a case where smaps file does not exist. In this case
2125
+ # wrap_exception decorator should not raise NoSuchProcess.
2126
+ with mock_open_exception(
2127
+ '/proc/%s/smaps' % os.getpid(), IOError(errno.ENOENT, "")
2128
+ ) as m:
2129
+ p = psutil.Process()
2130
+ with self.assertRaises(FileNotFoundError):
2131
+ p.memory_maps()
2132
+ assert m.called
2133
+
2134
+ @unittest.skipIf(not HAS_RLIMIT, "not supported")
2135
+ def test_rlimit_zombie(self):
2136
+ # Emulate a case where rlimit() raises ENOSYS, which may
2137
+ # happen in case of zombie process:
2138
+ # https://travis-ci.org/giampaolo/psutil/jobs/51368273
2139
+ with mock.patch(
2140
+ "psutil._pslinux.prlimit", side_effect=OSError(errno.ENOSYS, "")
2141
+ ) as m1:
2142
+ with mock.patch(
2143
+ "psutil._pslinux.Process._is_zombie", return_value=True
2144
+ ) as m2:
2145
+ p = psutil.Process()
2146
+ p.name()
2147
+ with self.assertRaises(psutil.ZombieProcess) as exc:
2148
+ p.rlimit(psutil.RLIMIT_NOFILE)
2149
+ assert m1.called
2150
+ assert m2.called
2151
+ self.assertEqual(exc.exception.pid, p.pid)
2152
+ self.assertEqual(exc.exception.name, p.name())
2153
+
2154
+ def test_stat_file_parsing(self):
2155
+ args = [
2156
+ "0", # pid
2157
+ "(cat)", # name
2158
+ "Z", # status
2159
+ "1", # ppid
2160
+ "0", # pgrp
2161
+ "0", # session
2162
+ "0", # tty
2163
+ "0", # tpgid
2164
+ "0", # flags
2165
+ "0", # minflt
2166
+ "0", # cminflt
2167
+ "0", # majflt
2168
+ "0", # cmajflt
2169
+ "2", # utime
2170
+ "3", # stime
2171
+ "4", # cutime
2172
+ "5", # cstime
2173
+ "0", # priority
2174
+ "0", # nice
2175
+ "0", # num_threads
2176
+ "0", # itrealvalue
2177
+ "6", # starttime
2178
+ "0", # vsize
2179
+ "0", # rss
2180
+ "0", # rsslim
2181
+ "0", # startcode
2182
+ "0", # endcode
2183
+ "0", # startstack
2184
+ "0", # kstkesp
2185
+ "0", # kstkeip
2186
+ "0", # signal
2187
+ "0", # blocked
2188
+ "0", # sigignore
2189
+ "0", # sigcatch
2190
+ "0", # wchan
2191
+ "0", # nswap
2192
+ "0", # cnswap
2193
+ "0", # exit_signal
2194
+ "6", # processor
2195
+ "0", # rt priority
2196
+ "0", # policy
2197
+ "7", # delayacct_blkio_ticks
2198
+ ]
2199
+ content = " ".join(args).encode()
2200
+ with mock_open_content({"/proc/%s/stat" % os.getpid(): content}):
2201
+ p = psutil.Process()
2202
+ self.assertEqual(p.name(), 'cat')
2203
+ self.assertEqual(p.status(), psutil.STATUS_ZOMBIE)
2204
+ self.assertEqual(p.ppid(), 1)
2205
+ self.assertEqual(
2206
+ p.create_time(), 6 / CLOCK_TICKS + psutil.boot_time()
2207
+ )
2208
+ cpu = p.cpu_times()
2209
+ self.assertEqual(cpu.user, 2 / CLOCK_TICKS)
2210
+ self.assertEqual(cpu.system, 3 / CLOCK_TICKS)
2211
+ self.assertEqual(cpu.children_user, 4 / CLOCK_TICKS)
2212
+ self.assertEqual(cpu.children_system, 5 / CLOCK_TICKS)
2213
+ self.assertEqual(cpu.iowait, 7 / CLOCK_TICKS)
2214
+ self.assertEqual(p.cpu_num(), 6)
2215
+
2216
+ def test_status_file_parsing(self):
2217
+ content = textwrap.dedent("""\
2218
+ Uid:\t1000\t1001\t1002\t1003
2219
+ Gid:\t1004\t1005\t1006\t1007
2220
+ Threads:\t66
2221
+ Cpus_allowed:\tf
2222
+ Cpus_allowed_list:\t0-7
2223
+ voluntary_ctxt_switches:\t12
2224
+ nonvoluntary_ctxt_switches:\t13""").encode()
2225
+ with mock_open_content({"/proc/%s/status" % os.getpid(): content}):
2226
+ p = psutil.Process()
2227
+ self.assertEqual(p.num_ctx_switches().voluntary, 12)
2228
+ self.assertEqual(p.num_ctx_switches().involuntary, 13)
2229
+ self.assertEqual(p.num_threads(), 66)
2230
+ uids = p.uids()
2231
+ self.assertEqual(uids.real, 1000)
2232
+ self.assertEqual(uids.effective, 1001)
2233
+ self.assertEqual(uids.saved, 1002)
2234
+ gids = p.gids()
2235
+ self.assertEqual(gids.real, 1004)
2236
+ self.assertEqual(gids.effective, 1005)
2237
+ self.assertEqual(gids.saved, 1006)
2238
+ self.assertEqual(p._proc._get_eligible_cpus(), list(range(8)))
2239
+
2240
+ def test_connections_enametoolong(self):
2241
+ # Simulate a case where /proc/{pid}/fd/{fd} symlink points to
2242
+ # a file with full path longer than PATH_MAX, see:
2243
+ # https://github.com/giampaolo/psutil/issues/1940
2244
+ with mock.patch(
2245
+ 'psutil._pslinux.os.readlink',
2246
+ side_effect=OSError(errno.ENAMETOOLONG, ""),
2247
+ ) as m:
2248
+ p = psutil.Process()
2249
+ with mock.patch("psutil._pslinux.debug"):
2250
+ self.assertEqual(p.connections(), [])
2251
+ assert m.called
2252
+
2253
+
2254
+ @unittest.skipIf(not LINUX, "LINUX only")
2255
+ class TestProcessAgainstStatus(PsutilTestCase):
2256
+ """/proc/pid/stat and /proc/pid/status have many values in common.
2257
+ Whenever possible, psutil uses /proc/pid/stat (it's faster).
2258
+ For all those cases we check that the value found in
2259
+ /proc/pid/stat (by psutil) matches the one found in
2260
+ /proc/pid/status.
2261
+ """
2262
+
2263
+ @classmethod
2264
+ def setUpClass(cls):
2265
+ cls.proc = psutil.Process()
2266
+
2267
+ def read_status_file(self, linestart):
2268
+ with psutil._psplatform.open_text(
2269
+ '/proc/%s/status' % self.proc.pid
2270
+ ) as f:
2271
+ for line in f:
2272
+ line = line.strip()
2273
+ if line.startswith(linestart):
2274
+ value = line.partition('\t')[2]
2275
+ try:
2276
+ return int(value)
2277
+ except ValueError:
2278
+ return value
2279
+ raise ValueError("can't find %r" % linestart)
2280
+
2281
+ def test_name(self):
2282
+ value = self.read_status_file("Name:")
2283
+ self.assertEqual(self.proc.name(), value)
2284
+
2285
+ def test_status(self):
2286
+ value = self.read_status_file("State:")
2287
+ value = value[value.find('(') + 1 : value.rfind(')')]
2288
+ value = value.replace(' ', '-')
2289
+ self.assertEqual(self.proc.status(), value)
2290
+
2291
+ def test_ppid(self):
2292
+ value = self.read_status_file("PPid:")
2293
+ self.assertEqual(self.proc.ppid(), value)
2294
+
2295
+ def test_num_threads(self):
2296
+ value = self.read_status_file("Threads:")
2297
+ self.assertEqual(self.proc.num_threads(), value)
2298
+
2299
+ def test_uids(self):
2300
+ value = self.read_status_file("Uid:")
2301
+ value = tuple(map(int, value.split()[1:4]))
2302
+ self.assertEqual(self.proc.uids(), value)
2303
+
2304
+ def test_gids(self):
2305
+ value = self.read_status_file("Gid:")
2306
+ value = tuple(map(int, value.split()[1:4]))
2307
+ self.assertEqual(self.proc.gids(), value)
2308
+
2309
+ @retry_on_failure()
2310
+ def test_num_ctx_switches(self):
2311
+ value = self.read_status_file("voluntary_ctxt_switches:")
2312
+ self.assertEqual(self.proc.num_ctx_switches().voluntary, value)
2313
+ value = self.read_status_file("nonvoluntary_ctxt_switches:")
2314
+ self.assertEqual(self.proc.num_ctx_switches().involuntary, value)
2315
+
2316
+ def test_cpu_affinity(self):
2317
+ value = self.read_status_file("Cpus_allowed_list:")
2318
+ if '-' in str(value):
2319
+ min_, max_ = map(int, value.split('-'))
2320
+ self.assertEqual(
2321
+ self.proc.cpu_affinity(), list(range(min_, max_ + 1))
2322
+ )
2323
+
2324
+ def test_cpu_affinity_eligible_cpus(self):
2325
+ value = self.read_status_file("Cpus_allowed_list:")
2326
+ with mock.patch("psutil._pslinux.per_cpu_times") as m:
2327
+ self.proc._proc._get_eligible_cpus()
2328
+ if '-' in str(value):
2329
+ assert not m.called
2330
+ else:
2331
+ assert m.called
2332
+
2333
+
2334
+ # =====================================================================
2335
+ # --- test utils
2336
+ # =====================================================================
2337
+
2338
+
2339
+ @unittest.skipIf(not LINUX, "LINUX only")
2340
+ class TestUtils(PsutilTestCase):
2341
+ def test_readlink(self):
2342
+ with mock.patch("os.readlink", return_value="foo (deleted)") as m:
2343
+ self.assertEqual(psutil._psplatform.readlink("bar"), "foo")
2344
+ assert m.called
2345
+
2346
+
2347
+ if __name__ == '__main__':
2348
+ from psutil.tests.runner import run_from_name
2349
+
2350
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_memleaks.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Tests for detecting function memory leaks (typically the ones
8
+ implemented in C). It does so by calling a function many times and
9
+ checking whether process memory usage keeps increasing between
10
+ calls or over time.
11
+ Note that this may produce false positives (especially on Windows
12
+ for some reason).
13
+ PyPy appears to be completely unstable for this framework, probably
14
+ because of how its JIT handles memory, so tests are skipped.
15
+ """
16
+
17
+ from __future__ import print_function
18
+
19
+ import functools
20
+ import os
21
+ import platform
22
+ import unittest
23
+
24
+ import psutil
25
+ import psutil._common
26
+ from psutil import LINUX
27
+ from psutil import MACOS
28
+ from psutil import OPENBSD
29
+ from psutil import POSIX
30
+ from psutil import SUNOS
31
+ from psutil import WINDOWS
32
+ from psutil._compat import ProcessLookupError
33
+ from psutil._compat import super
34
+ from psutil.tests import HAS_CPU_AFFINITY
35
+ from psutil.tests import HAS_CPU_FREQ
36
+ from psutil.tests import HAS_ENVIRON
37
+ from psutil.tests import HAS_IONICE
38
+ from psutil.tests import HAS_MEMORY_MAPS
39
+ from psutil.tests import HAS_NET_IO_COUNTERS
40
+ from psutil.tests import HAS_PROC_CPU_NUM
41
+ from psutil.tests import HAS_PROC_IO_COUNTERS
42
+ from psutil.tests import HAS_RLIMIT
43
+ from psutil.tests import HAS_SENSORS_BATTERY
44
+ from psutil.tests import HAS_SENSORS_FANS
45
+ from psutil.tests import HAS_SENSORS_TEMPERATURES
46
+ from psutil.tests import TestMemoryLeak
47
+ from psutil.tests import create_sockets
48
+ from psutil.tests import get_testfn
49
+ from psutil.tests import process_namespace
50
+ from psutil.tests import skip_on_access_denied
51
+ from psutil.tests import spawn_testproc
52
+ from psutil.tests import system_namespace
53
+ from psutil.tests import terminate
54
+
55
+
56
+ cext = psutil._psplatform.cext
57
+ thisproc = psutil.Process()
58
+ FEW_TIMES = 5
59
+
60
+
61
+ def fewtimes_if_linux():
62
+ """Decorator for those Linux functions which are implemented in pure
63
+ Python, and which we want to run faster.
64
+ """
65
+
66
+ def decorator(fun):
67
+ @functools.wraps(fun)
68
+ def wrapper(self, *args, **kwargs):
69
+ if LINUX:
70
+ before = self.__class__.times
71
+ try:
72
+ self.__class__.times = FEW_TIMES
73
+ return fun(self, *args, **kwargs)
74
+ finally:
75
+ self.__class__.times = before
76
+ else:
77
+ return fun(self, *args, **kwargs)
78
+
79
+ return wrapper
80
+
81
+ return decorator
82
+
83
+
84
+ # ===================================================================
85
+ # Process class
86
+ # ===================================================================
87
+
88
+
89
+ class TestProcessObjectLeaks(TestMemoryLeak):
90
+ """Test leaks of Process class methods."""
91
+
92
+ proc = thisproc
93
+
94
+ def test_coverage(self):
95
+ ns = process_namespace(None)
96
+ ns.test_class_coverage(self, ns.getters + ns.setters)
97
+
98
+ @fewtimes_if_linux()
99
+ def test_name(self):
100
+ self.execute(self.proc.name)
101
+
102
+ @fewtimes_if_linux()
103
+ def test_cmdline(self):
104
+ self.execute(self.proc.cmdline)
105
+
106
+ @fewtimes_if_linux()
107
+ def test_exe(self):
108
+ self.execute(self.proc.exe)
109
+
110
+ @fewtimes_if_linux()
111
+ def test_ppid(self):
112
+ self.execute(self.proc.ppid)
113
+
114
+ @unittest.skipIf(not POSIX, "POSIX only")
115
+ @fewtimes_if_linux()
116
+ def test_uids(self):
117
+ self.execute(self.proc.uids)
118
+
119
+ @unittest.skipIf(not POSIX, "POSIX only")
120
+ @fewtimes_if_linux()
121
+ def test_gids(self):
122
+ self.execute(self.proc.gids)
123
+
124
+ @fewtimes_if_linux()
125
+ def test_status(self):
126
+ self.execute(self.proc.status)
127
+
128
+ def test_nice(self):
129
+ self.execute(self.proc.nice)
130
+
131
+ def test_nice_set(self):
132
+ niceness = thisproc.nice()
133
+ self.execute(lambda: self.proc.nice(niceness))
134
+
135
+ @unittest.skipIf(not HAS_IONICE, "not supported")
136
+ def test_ionice(self):
137
+ self.execute(self.proc.ionice)
138
+
139
+ @unittest.skipIf(not HAS_IONICE, "not supported")
140
+ def test_ionice_set(self):
141
+ if WINDOWS:
142
+ value = thisproc.ionice()
143
+ self.execute(lambda: self.proc.ionice(value))
144
+ else:
145
+ self.execute(lambda: self.proc.ionice(psutil.IOPRIO_CLASS_NONE))
146
+ fun = functools.partial(cext.proc_ioprio_set, os.getpid(), -1, 0)
147
+ self.execute_w_exc(OSError, fun)
148
+
149
+ @unittest.skipIf(not HAS_PROC_IO_COUNTERS, "not supported")
150
+ @fewtimes_if_linux()
151
+ def test_io_counters(self):
152
+ self.execute(self.proc.io_counters)
153
+
154
+ @unittest.skipIf(POSIX, "worthless on POSIX")
155
+ def test_username(self):
156
+ # always open 1 handle on Windows (only once)
157
+ psutil.Process().username()
158
+ self.execute(self.proc.username)
159
+
160
+ @fewtimes_if_linux()
161
+ def test_create_time(self):
162
+ self.execute(self.proc.create_time)
163
+
164
+ @fewtimes_if_linux()
165
+ @skip_on_access_denied(only_if=OPENBSD)
166
+ def test_num_threads(self):
167
+ self.execute(self.proc.num_threads)
168
+
169
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
170
+ def test_num_handles(self):
171
+ self.execute(self.proc.num_handles)
172
+
173
+ @unittest.skipIf(not POSIX, "POSIX only")
174
+ @fewtimes_if_linux()
175
+ def test_num_fds(self):
176
+ self.execute(self.proc.num_fds)
177
+
178
+ @fewtimes_if_linux()
179
+ def test_num_ctx_switches(self):
180
+ self.execute(self.proc.num_ctx_switches)
181
+
182
+ @fewtimes_if_linux()
183
+ @skip_on_access_denied(only_if=OPENBSD)
184
+ def test_threads(self):
185
+ self.execute(self.proc.threads)
186
+
187
+ @fewtimes_if_linux()
188
+ def test_cpu_times(self):
189
+ self.execute(self.proc.cpu_times)
190
+
191
+ @fewtimes_if_linux()
192
+ @unittest.skipIf(not HAS_PROC_CPU_NUM, "not supported")
193
+ def test_cpu_num(self):
194
+ self.execute(self.proc.cpu_num)
195
+
196
+ @fewtimes_if_linux()
197
+ def test_memory_info(self):
198
+ self.execute(self.proc.memory_info)
199
+
200
+ @fewtimes_if_linux()
201
+ def test_memory_full_info(self):
202
+ self.execute(self.proc.memory_full_info)
203
+
204
+ @unittest.skipIf(not POSIX, "POSIX only")
205
+ @fewtimes_if_linux()
206
+ def test_terminal(self):
207
+ self.execute(self.proc.terminal)
208
+
209
+ def test_resume(self):
210
+ times = FEW_TIMES if POSIX else self.times
211
+ self.execute(self.proc.resume, times=times)
212
+
213
+ @fewtimes_if_linux()
214
+ def test_cwd(self):
215
+ self.execute(self.proc.cwd)
216
+
217
+ @unittest.skipIf(not HAS_CPU_AFFINITY, "not supported")
218
+ def test_cpu_affinity(self):
219
+ self.execute(self.proc.cpu_affinity)
220
+
221
+ @unittest.skipIf(not HAS_CPU_AFFINITY, "not supported")
222
+ def test_cpu_affinity_set(self):
223
+ affinity = thisproc.cpu_affinity()
224
+ self.execute(lambda: self.proc.cpu_affinity(affinity))
225
+ self.execute_w_exc(ValueError, lambda: self.proc.cpu_affinity([-1]))
226
+
227
+ @fewtimes_if_linux()
228
+ def test_open_files(self):
229
+ with open(get_testfn(), 'w'):
230
+ self.execute(self.proc.open_files)
231
+
232
+ @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
233
+ @fewtimes_if_linux()
234
+ def test_memory_maps(self):
235
+ self.execute(self.proc.memory_maps)
236
+
237
+ @unittest.skipIf(not LINUX, "LINUX only")
238
+ @unittest.skipIf(not HAS_RLIMIT, "not supported")
239
+ def test_rlimit(self):
240
+ self.execute(lambda: self.proc.rlimit(psutil.RLIMIT_NOFILE))
241
+
242
+ @unittest.skipIf(not LINUX, "LINUX only")
243
+ @unittest.skipIf(not HAS_RLIMIT, "not supported")
244
+ def test_rlimit_set(self):
245
+ limit = thisproc.rlimit(psutil.RLIMIT_NOFILE)
246
+ self.execute(lambda: self.proc.rlimit(psutil.RLIMIT_NOFILE, limit))
247
+ self.execute_w_exc((OSError, ValueError), lambda: self.proc.rlimit(-1))
248
+
249
+ @fewtimes_if_linux()
250
+ # Windows implementation is based on a single system-wide
251
+ # function (tested later).
252
+ @unittest.skipIf(WINDOWS, "worthless on WINDOWS")
253
+ def test_connections(self):
254
+ # TODO: UNIX sockets are temporarily implemented by parsing
255
+ # 'pfiles' cmd output; we don't want that part of the code to
256
+ # be executed.
257
+ with create_sockets():
258
+ kind = 'inet' if SUNOS else 'all'
259
+ self.execute(lambda: self.proc.connections(kind))
260
+
261
+ @unittest.skipIf(not HAS_ENVIRON, "not supported")
262
+ def test_environ(self):
263
+ self.execute(self.proc.environ)
264
+
265
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
266
+ def test_proc_info(self):
267
+ self.execute(lambda: cext.proc_info(os.getpid()))
268
+
269
+
270
+ class TestTerminatedProcessLeaks(TestProcessObjectLeaks):
271
+ """Repeat the tests above looking for leaks occurring when dealing
272
+ with terminated processes raising NoSuchProcess exception.
273
+ The C functions are still invoked but will follow different code
274
+ paths. We'll check those code paths.
275
+ """
276
+
277
+ @classmethod
278
+ def setUpClass(cls):
279
+ super().setUpClass()
280
+ cls.subp = spawn_testproc()
281
+ cls.proc = psutil.Process(cls.subp.pid)
282
+ cls.proc.kill()
283
+ cls.proc.wait()
284
+
285
+ @classmethod
286
+ def tearDownClass(cls):
287
+ super().tearDownClass()
288
+ terminate(cls.subp)
289
+
290
+ def call(self, fun):
291
+ try:
292
+ fun()
293
+ except psutil.NoSuchProcess:
294
+ pass
295
+
296
+ if WINDOWS:
297
+
298
+ def test_kill(self):
299
+ self.execute(self.proc.kill)
300
+
301
+ def test_terminate(self):
302
+ self.execute(self.proc.terminate)
303
+
304
+ def test_suspend(self):
305
+ self.execute(self.proc.suspend)
306
+
307
+ def test_resume(self):
308
+ self.execute(self.proc.resume)
309
+
310
+ def test_wait(self):
311
+ self.execute(self.proc.wait)
312
+
313
+ def test_proc_info(self):
314
+ # test dual implementation
315
+ def call():
316
+ try:
317
+ return cext.proc_info(self.proc.pid)
318
+ except ProcessLookupError:
319
+ pass
320
+
321
+ self.execute(call)
322
+
323
+
324
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
325
+ class TestProcessDualImplementation(TestMemoryLeak):
326
+ def test_cmdline_peb_true(self):
327
+ self.execute(lambda: cext.proc_cmdline(os.getpid(), use_peb=True))
328
+
329
+ def test_cmdline_peb_false(self):
330
+ self.execute(lambda: cext.proc_cmdline(os.getpid(), use_peb=False))
331
+
332
+
333
+ # ===================================================================
334
+ # system APIs
335
+ # ===================================================================
336
+
337
+
338
+ class TestModuleFunctionsLeaks(TestMemoryLeak):
339
+ """Test leaks of psutil module functions."""
340
+
341
+ def test_coverage(self):
342
+ ns = system_namespace()
343
+ ns.test_class_coverage(self, ns.all)
344
+
345
+ # --- cpu
346
+
347
+ @fewtimes_if_linux()
348
+ def test_cpu_count(self): # logical
349
+ self.execute(lambda: psutil.cpu_count(logical=True))
350
+
351
+ @fewtimes_if_linux()
352
+ def test_cpu_count_cores(self):
353
+ self.execute(lambda: psutil.cpu_count(logical=False))
354
+
355
+ @fewtimes_if_linux()
356
+ def test_cpu_times(self):
357
+ self.execute(psutil.cpu_times)
358
+
359
+ @fewtimes_if_linux()
360
+ def test_per_cpu_times(self):
361
+ self.execute(lambda: psutil.cpu_times(percpu=True))
362
+
363
+ @fewtimes_if_linux()
364
+ def test_cpu_stats(self):
365
+ self.execute(psutil.cpu_stats)
366
+
367
+ @fewtimes_if_linux()
368
+ # TODO: remove this once 1892 is fixed
369
+ @unittest.skipIf(
370
+ MACOS and platform.machine() == 'arm64', "skipped due to #1892"
371
+ )
372
+ @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
373
+ def test_cpu_freq(self):
374
+ self.execute(psutil.cpu_freq)
375
+
376
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
377
+ def test_getloadavg(self):
378
+ psutil.getloadavg()
379
+ self.execute(psutil.getloadavg)
380
+
381
+ # --- mem
382
+
383
+ def test_virtual_memory(self):
384
+ self.execute(psutil.virtual_memory)
385
+
386
+ # TODO: remove this skip when this gets fixed
387
+ @unittest.skipIf(SUNOS, "worthless on SUNOS (uses a subprocess)")
388
+ def test_swap_memory(self):
389
+ self.execute(psutil.swap_memory)
390
+
391
+ def test_pid_exists(self):
392
+ times = FEW_TIMES if POSIX else self.times
393
+ self.execute(lambda: psutil.pid_exists(os.getpid()), times=times)
394
+
395
+ # --- disk
396
+
397
+ def test_disk_usage(self):
398
+ times = FEW_TIMES if POSIX else self.times
399
+ self.execute(lambda: psutil.disk_usage('.'), times=times)
400
+
401
+ def test_disk_partitions(self):
402
+ self.execute(psutil.disk_partitions)
403
+
404
+ @unittest.skipIf(
405
+ LINUX and not os.path.exists('/proc/diskstats'),
406
+ '/proc/diskstats not available on this Linux version',
407
+ )
408
+ @fewtimes_if_linux()
409
+ def test_disk_io_counters(self):
410
+ self.execute(lambda: psutil.disk_io_counters(nowrap=False))
411
+
412
+ # --- proc
413
+
414
+ @fewtimes_if_linux()
415
+ def test_pids(self):
416
+ self.execute(psutil.pids)
417
+
418
+ # --- net
419
+
420
+ @fewtimes_if_linux()
421
+ @unittest.skipIf(not HAS_NET_IO_COUNTERS, 'not supported')
422
+ def test_net_io_counters(self):
423
+ self.execute(lambda: psutil.net_io_counters(nowrap=False))
424
+
425
+ @fewtimes_if_linux()
426
+ @unittest.skipIf(MACOS and os.getuid() != 0, "need root access")
427
+ def test_net_connections(self):
428
+ # always opens and handle on Windows() (once)
429
+ psutil.net_connections(kind='all')
430
+ with create_sockets():
431
+ self.execute(lambda: psutil.net_connections(kind='all'))
432
+
433
+ def test_net_if_addrs(self):
434
+ # Note: verified that on Windows this was a false positive.
435
+ tolerance = 80 * 1024 if WINDOWS else self.tolerance
436
+ self.execute(psutil.net_if_addrs, tolerance=tolerance)
437
+
438
+ def test_net_if_stats(self):
439
+ self.execute(psutil.net_if_stats)
440
+
441
+ # --- sensors
442
+
443
+ @fewtimes_if_linux()
444
+ @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
445
+ def test_sensors_battery(self):
446
+ self.execute(psutil.sensors_battery)
447
+
448
+ @fewtimes_if_linux()
449
+ @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
450
+ def test_sensors_temperatures(self):
451
+ self.execute(psutil.sensors_temperatures)
452
+
453
+ @fewtimes_if_linux()
454
+ @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
455
+ def test_sensors_fans(self):
456
+ self.execute(psutil.sensors_fans)
457
+
458
+ # --- others
459
+
460
+ @fewtimes_if_linux()
461
+ def test_boot_time(self):
462
+ self.execute(psutil.boot_time)
463
+
464
+ def test_users(self):
465
+ self.execute(psutil.users)
466
+
467
+ def test_set_debug(self):
468
+ self.execute(lambda: psutil._set_debug(False))
469
+
470
+ if WINDOWS:
471
+
472
+ # --- win services
473
+
474
+ def test_win_service_iter(self):
475
+ self.execute(cext.winservice_enumerate)
476
+
477
+ def test_win_service_get(self):
478
+ pass
479
+
480
+ def test_win_service_get_config(self):
481
+ name = next(psutil.win_service_iter()).name()
482
+ self.execute(lambda: cext.winservice_query_config(name))
483
+
484
+ def test_win_service_get_status(self):
485
+ name = next(psutil.win_service_iter()).name()
486
+ self.execute(lambda: cext.winservice_query_status(name))
487
+
488
+ def test_win_service_get_description(self):
489
+ name = next(psutil.win_service_iter()).name()
490
+ self.execute(lambda: cext.winservice_query_descr(name))
491
+
492
+
493
+ if __name__ == '__main__':
494
+ from psutil.tests.runner import run_from_name
495
+
496
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_misc.py ADDED
@@ -0,0 +1,1014 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
5
+ # Use of this source code is governed by a BSD-style license that can be
6
+ # found in the LICENSE file.
7
+
8
+ """Miscellaneous tests."""
9
+
10
+ import ast
11
+ import collections
12
+ import errno
13
+ import json
14
+ import os
15
+ import pickle
16
+ import socket
17
+ import stat
18
+ import unittest
19
+
20
+ import psutil
21
+ import psutil.tests
22
+ from psutil import LINUX
23
+ from psutil import POSIX
24
+ from psutil import WINDOWS
25
+ from psutil._common import bcat
26
+ from psutil._common import cat
27
+ from psutil._common import debug
28
+ from psutil._common import isfile_strict
29
+ from psutil._common import memoize
30
+ from psutil._common import memoize_when_activated
31
+ from psutil._common import parse_environ_block
32
+ from psutil._common import supports_ipv6
33
+ from psutil._common import wrap_numbers
34
+ from psutil._compat import PY3
35
+ from psutil._compat import FileNotFoundError
36
+ from psutil._compat import redirect_stderr
37
+ from psutil.tests import APPVEYOR
38
+ from psutil.tests import CI_TESTING
39
+ from psutil.tests import HAS_BATTERY
40
+ from psutil.tests import HAS_MEMORY_MAPS
41
+ from psutil.tests import HAS_NET_IO_COUNTERS
42
+ from psutil.tests import HAS_SENSORS_BATTERY
43
+ from psutil.tests import HAS_SENSORS_FANS
44
+ from psutil.tests import HAS_SENSORS_TEMPERATURES
45
+ from psutil.tests import PYTHON_EXE
46
+ from psutil.tests import PYTHON_EXE_ENV
47
+ from psutil.tests import SCRIPTS_DIR
48
+ from psutil.tests import PsutilTestCase
49
+ from psutil.tests import mock
50
+ from psutil.tests import reload_module
51
+ from psutil.tests import sh
52
+
53
+
54
+ # ===================================================================
55
+ # --- Test classes' repr(), str(), ...
56
+ # ===================================================================
57
+
58
+
59
+ class TestSpecialMethods(PsutilTestCase):
60
+ def test_check_pid_range(self):
61
+ with self.assertRaises(OverflowError):
62
+ psutil._psplatform.cext.check_pid_range(2**128)
63
+ with self.assertRaises(psutil.NoSuchProcess):
64
+ psutil.Process(2**128)
65
+
66
+ def test_process__repr__(self, func=repr):
67
+ p = psutil.Process(self.spawn_testproc().pid)
68
+ r = func(p)
69
+ self.assertIn("psutil.Process", r)
70
+ self.assertIn("pid=%s" % p.pid, r)
71
+ self.assertIn(
72
+ "name='%s'" % str(p.name()), r.replace("name=u'", "name='")
73
+ )
74
+ self.assertIn("status=", r)
75
+ self.assertNotIn("exitcode=", r)
76
+ p.terminate()
77
+ p.wait()
78
+ r = func(p)
79
+ self.assertIn("status='terminated'", r)
80
+ self.assertIn("exitcode=", r)
81
+
82
+ with mock.patch.object(
83
+ psutil.Process,
84
+ "name",
85
+ side_effect=psutil.ZombieProcess(os.getpid()),
86
+ ):
87
+ p = psutil.Process()
88
+ r = func(p)
89
+ self.assertIn("pid=%s" % p.pid, r)
90
+ self.assertIn("status='zombie'", r)
91
+ self.assertNotIn("name=", r)
92
+ with mock.patch.object(
93
+ psutil.Process,
94
+ "name",
95
+ side_effect=psutil.NoSuchProcess(os.getpid()),
96
+ ):
97
+ p = psutil.Process()
98
+ r = func(p)
99
+ self.assertIn("pid=%s" % p.pid, r)
100
+ self.assertIn("terminated", r)
101
+ self.assertNotIn("name=", r)
102
+ with mock.patch.object(
103
+ psutil.Process,
104
+ "name",
105
+ side_effect=psutil.AccessDenied(os.getpid()),
106
+ ):
107
+ p = psutil.Process()
108
+ r = func(p)
109
+ self.assertIn("pid=%s" % p.pid, r)
110
+ self.assertNotIn("name=", r)
111
+
112
+ def test_process__str__(self):
113
+ self.test_process__repr__(func=str)
114
+
115
+ def test_error__repr__(self):
116
+ self.assertEqual(repr(psutil.Error()), "psutil.Error()")
117
+
118
+ def test_error__str__(self):
119
+ self.assertEqual(str(psutil.Error()), "")
120
+
121
+ def test_no_such_process__repr__(self):
122
+ self.assertEqual(
123
+ repr(psutil.NoSuchProcess(321)),
124
+ "psutil.NoSuchProcess(pid=321, msg='process no longer exists')",
125
+ )
126
+ self.assertEqual(
127
+ repr(psutil.NoSuchProcess(321, name="name", msg="msg")),
128
+ "psutil.NoSuchProcess(pid=321, name='name', msg='msg')",
129
+ )
130
+
131
+ def test_no_such_process__str__(self):
132
+ self.assertEqual(
133
+ str(psutil.NoSuchProcess(321)),
134
+ "process no longer exists (pid=321)",
135
+ )
136
+ self.assertEqual(
137
+ str(psutil.NoSuchProcess(321, name="name", msg="msg")),
138
+ "msg (pid=321, name='name')",
139
+ )
140
+
141
+ def test_zombie_process__repr__(self):
142
+ self.assertEqual(
143
+ repr(psutil.ZombieProcess(321)),
144
+ 'psutil.ZombieProcess(pid=321, msg="PID still '
145
+ 'exists but it\'s a zombie")',
146
+ )
147
+ self.assertEqual(
148
+ repr(psutil.ZombieProcess(321, name="name", ppid=320, msg="foo")),
149
+ "psutil.ZombieProcess(pid=321, ppid=320, name='name', msg='foo')",
150
+ )
151
+
152
+ def test_zombie_process__str__(self):
153
+ self.assertEqual(
154
+ str(psutil.ZombieProcess(321)),
155
+ "PID still exists but it's a zombie (pid=321)",
156
+ )
157
+ self.assertEqual(
158
+ str(psutil.ZombieProcess(321, name="name", ppid=320, msg="foo")),
159
+ "foo (pid=321, ppid=320, name='name')",
160
+ )
161
+
162
+ def test_access_denied__repr__(self):
163
+ self.assertEqual(
164
+ repr(psutil.AccessDenied(321)), "psutil.AccessDenied(pid=321)"
165
+ )
166
+ self.assertEqual(
167
+ repr(psutil.AccessDenied(321, name="name", msg="msg")),
168
+ "psutil.AccessDenied(pid=321, name='name', msg='msg')",
169
+ )
170
+
171
+ def test_access_denied__str__(self):
172
+ self.assertEqual(str(psutil.AccessDenied(321)), "(pid=321)")
173
+ self.assertEqual(
174
+ str(psutil.AccessDenied(321, name="name", msg="msg")),
175
+ "msg (pid=321, name='name')",
176
+ )
177
+
178
+ def test_timeout_expired__repr__(self):
179
+ self.assertEqual(
180
+ repr(psutil.TimeoutExpired(5)),
181
+ "psutil.TimeoutExpired(seconds=5, msg='timeout after 5 seconds')",
182
+ )
183
+ self.assertEqual(
184
+ repr(psutil.TimeoutExpired(5, pid=321, name="name")),
185
+ "psutil.TimeoutExpired(pid=321, name='name', seconds=5, "
186
+ "msg='timeout after 5 seconds')",
187
+ )
188
+
189
+ def test_timeout_expired__str__(self):
190
+ self.assertEqual(
191
+ str(psutil.TimeoutExpired(5)), "timeout after 5 seconds"
192
+ )
193
+ self.assertEqual(
194
+ str(psutil.TimeoutExpired(5, pid=321, name="name")),
195
+ "timeout after 5 seconds (pid=321, name='name')",
196
+ )
197
+
198
+ def test_process__eq__(self):
199
+ p1 = psutil.Process()
200
+ p2 = psutil.Process()
201
+ self.assertEqual(p1, p2)
202
+ p2._ident = (0, 0)
203
+ self.assertNotEqual(p1, p2)
204
+ self.assertNotEqual(p1, 'foo')
205
+
206
+ def test_process__hash__(self):
207
+ s = set([psutil.Process(), psutil.Process()])
208
+ self.assertEqual(len(s), 1)
209
+
210
+
211
+ # ===================================================================
212
+ # --- Misc, generic, corner cases
213
+ # ===================================================================
214
+
215
+
216
+ class TestMisc(PsutilTestCase):
217
+ def test__all__(self):
218
+ dir_psutil = dir(psutil)
219
+ for name in dir_psutil:
220
+ if name in (
221
+ 'long',
222
+ 'tests',
223
+ 'test',
224
+ 'PermissionError',
225
+ 'ProcessLookupError',
226
+ ):
227
+ continue
228
+ if not name.startswith('_'):
229
+ try:
230
+ __import__(name)
231
+ except ImportError:
232
+ if name not in psutil.__all__:
233
+ fun = getattr(psutil, name)
234
+ if fun is None:
235
+ continue
236
+ if (
237
+ fun.__doc__ is not None
238
+ and 'deprecated' not in fun.__doc__.lower()
239
+ ):
240
+ raise self.fail('%r not in psutil.__all__' % name)
241
+
242
+ # Import 'star' will break if __all__ is inconsistent, see:
243
+ # https://github.com/giampaolo/psutil/issues/656
244
+ # Can't do `from psutil import *` as it won't work on python 3
245
+ # so we simply iterate over __all__.
246
+ for name in psutil.__all__:
247
+ self.assertIn(name, dir_psutil)
248
+
249
+ def test_version(self):
250
+ self.assertEqual(
251
+ '.'.join([str(x) for x in psutil.version_info]), psutil.__version__
252
+ )
253
+
254
+ def test_process_as_dict_no_new_names(self):
255
+ # See https://github.com/giampaolo/psutil/issues/813
256
+ p = psutil.Process()
257
+ p.foo = '1'
258
+ self.assertNotIn('foo', p.as_dict())
259
+
260
+ def test_serialization(self):
261
+ def check(ret):
262
+ if json is not None:
263
+ json.loads(json.dumps(ret))
264
+ a = pickle.dumps(ret)
265
+ b = pickle.loads(a)
266
+ self.assertEqual(ret, b)
267
+
268
+ check(psutil.Process().as_dict())
269
+ check(psutil.virtual_memory())
270
+ check(psutil.swap_memory())
271
+ check(psutil.cpu_times())
272
+ check(psutil.cpu_times_percent(interval=0))
273
+ check(psutil.net_io_counters())
274
+ if LINUX and not os.path.exists('/proc/diskstats'):
275
+ pass
276
+ else:
277
+ if not APPVEYOR:
278
+ check(psutil.disk_io_counters())
279
+ check(psutil.disk_partitions())
280
+ check(psutil.disk_usage(os.getcwd()))
281
+ check(psutil.users())
282
+
283
+ # # XXX: https://github.com/pypa/setuptools/pull/2896
284
+ # @unittest.skipIf(APPVEYOR, "temporarily disabled due to setuptools bug")
285
+ # def test_setup_script(self):
286
+ # setup_py = os.path.join(ROOT_DIR, 'setup.py')
287
+ # if CI_TESTING and not os.path.exists(setup_py):
288
+ # return self.skipTest("can't find setup.py")
289
+ # module = import_module_by_path(setup_py)
290
+ # self.assertRaises(SystemExit, module.setup)
291
+ # self.assertEqual(module.get_version(), psutil.__version__)
292
+
293
+ def test_ad_on_process_creation(self):
294
+ # We are supposed to be able to instantiate Process also in case
295
+ # of zombie processes or access denied.
296
+ with mock.patch.object(
297
+ psutil.Process, 'create_time', side_effect=psutil.AccessDenied
298
+ ) as meth:
299
+ psutil.Process()
300
+ assert meth.called
301
+ with mock.patch.object(
302
+ psutil.Process, 'create_time', side_effect=psutil.ZombieProcess(1)
303
+ ) as meth:
304
+ psutil.Process()
305
+ assert meth.called
306
+ with mock.patch.object(
307
+ psutil.Process, 'create_time', side_effect=ValueError
308
+ ) as meth:
309
+ with self.assertRaises(ValueError):
310
+ psutil.Process()
311
+ assert meth.called
312
+
313
+ def test_sanity_version_check(self):
314
+ # see: https://github.com/giampaolo/psutil/issues/564
315
+ with mock.patch(
316
+ "psutil._psplatform.cext.version", return_value="0.0.0"
317
+ ):
318
+ with self.assertRaises(ImportError) as cm:
319
+ reload_module(psutil)
320
+ self.assertIn("version conflict", str(cm.exception).lower())
321
+
322
+
323
+ # ===================================================================
324
+ # --- psutil/_common.py utils
325
+ # ===================================================================
326
+
327
+
328
+ class TestMemoizeDecorator(PsutilTestCase):
329
+ def setUp(self):
330
+ self.calls = []
331
+
332
+ tearDown = setUp
333
+
334
+ def run_against(self, obj, expected_retval=None):
335
+ # no args
336
+ for _ in range(2):
337
+ ret = obj()
338
+ self.assertEqual(self.calls, [((), {})])
339
+ if expected_retval is not None:
340
+ self.assertEqual(ret, expected_retval)
341
+ # with args
342
+ for _ in range(2):
343
+ ret = obj(1)
344
+ self.assertEqual(self.calls, [((), {}), ((1,), {})])
345
+ if expected_retval is not None:
346
+ self.assertEqual(ret, expected_retval)
347
+ # with args + kwargs
348
+ for _ in range(2):
349
+ ret = obj(1, bar=2)
350
+ self.assertEqual(
351
+ self.calls, [((), {}), ((1,), {}), ((1,), {'bar': 2})]
352
+ )
353
+ if expected_retval is not None:
354
+ self.assertEqual(ret, expected_retval)
355
+ # clear cache
356
+ self.assertEqual(len(self.calls), 3)
357
+ obj.cache_clear()
358
+ ret = obj()
359
+ if expected_retval is not None:
360
+ self.assertEqual(ret, expected_retval)
361
+ self.assertEqual(len(self.calls), 4)
362
+ # docstring
363
+ self.assertEqual(obj.__doc__, "My docstring.")
364
+
365
+ def test_function(self):
366
+ @memoize
367
+ def foo(*args, **kwargs):
368
+ """My docstring."""
369
+ baseclass.calls.append((args, kwargs))
370
+ return 22
371
+
372
+ baseclass = self
373
+ self.run_against(foo, expected_retval=22)
374
+
375
+ def test_class(self):
376
+ @memoize
377
+ class Foo:
378
+ """My docstring."""
379
+
380
+ def __init__(self, *args, **kwargs):
381
+ baseclass.calls.append((args, kwargs))
382
+
383
+ def bar(self):
384
+ return 22
385
+
386
+ baseclass = self
387
+ self.run_against(Foo, expected_retval=None)
388
+ self.assertEqual(Foo().bar(), 22)
389
+
390
+ def test_class_singleton(self):
391
+ # @memoize can be used against classes to create singletons
392
+ @memoize
393
+ class Bar:
394
+ def __init__(self, *args, **kwargs):
395
+ pass
396
+
397
+ self.assertIs(Bar(), Bar())
398
+ self.assertEqual(id(Bar()), id(Bar()))
399
+ self.assertEqual(id(Bar(1)), id(Bar(1)))
400
+ self.assertEqual(id(Bar(1, foo=3)), id(Bar(1, foo=3)))
401
+ self.assertNotEqual(id(Bar(1)), id(Bar(2)))
402
+
403
+ def test_staticmethod(self):
404
+ class Foo:
405
+ @staticmethod
406
+ @memoize
407
+ def bar(*args, **kwargs):
408
+ """My docstring."""
409
+ baseclass.calls.append((args, kwargs))
410
+ return 22
411
+
412
+ baseclass = self
413
+ self.run_against(Foo().bar, expected_retval=22)
414
+
415
+ def test_classmethod(self):
416
+ class Foo:
417
+ @classmethod
418
+ @memoize
419
+ def bar(cls, *args, **kwargs):
420
+ """My docstring."""
421
+ baseclass.calls.append((args, kwargs))
422
+ return 22
423
+
424
+ baseclass = self
425
+ self.run_against(Foo().bar, expected_retval=22)
426
+
427
+ def test_original(self):
428
+ # This was the original test before I made it dynamic to test it
429
+ # against different types. Keeping it anyway.
430
+ @memoize
431
+ def foo(*args, **kwargs):
432
+ """Foo docstring."""
433
+ calls.append(None)
434
+ return (args, kwargs)
435
+
436
+ calls = []
437
+ # no args
438
+ for _ in range(2):
439
+ ret = foo()
440
+ expected = ((), {})
441
+ self.assertEqual(ret, expected)
442
+ self.assertEqual(len(calls), 1)
443
+ # with args
444
+ for _ in range(2):
445
+ ret = foo(1)
446
+ expected = ((1,), {})
447
+ self.assertEqual(ret, expected)
448
+ self.assertEqual(len(calls), 2)
449
+ # with args + kwargs
450
+ for _ in range(2):
451
+ ret = foo(1, bar=2)
452
+ expected = ((1,), {'bar': 2})
453
+ self.assertEqual(ret, expected)
454
+ self.assertEqual(len(calls), 3)
455
+ # clear cache
456
+ foo.cache_clear()
457
+ ret = foo()
458
+ expected = ((), {})
459
+ self.assertEqual(ret, expected)
460
+ self.assertEqual(len(calls), 4)
461
+ # docstring
462
+ self.assertEqual(foo.__doc__, "Foo docstring.")
463
+
464
+
465
+ class TestCommonModule(PsutilTestCase):
466
+ def test_memoize_when_activated(self):
467
+ class Foo:
468
+ @memoize_when_activated
469
+ def foo(self):
470
+ calls.append(None)
471
+
472
+ f = Foo()
473
+ calls = []
474
+ f.foo()
475
+ f.foo()
476
+ self.assertEqual(len(calls), 2)
477
+
478
+ # activate
479
+ calls = []
480
+ f.foo.cache_activate(f)
481
+ f.foo()
482
+ f.foo()
483
+ self.assertEqual(len(calls), 1)
484
+
485
+ # deactivate
486
+ calls = []
487
+ f.foo.cache_deactivate(f)
488
+ f.foo()
489
+ f.foo()
490
+ self.assertEqual(len(calls), 2)
491
+
492
+ def test_parse_environ_block(self):
493
+ def k(s):
494
+ return s.upper() if WINDOWS else s
495
+
496
+ self.assertEqual(parse_environ_block("a=1\0"), {k("a"): "1"})
497
+ self.assertEqual(
498
+ parse_environ_block("a=1\0b=2\0\0"), {k("a"): "1", k("b"): "2"}
499
+ )
500
+ self.assertEqual(
501
+ parse_environ_block("a=1\0b=\0\0"), {k("a"): "1", k("b"): ""}
502
+ )
503
+ # ignore everything after \0\0
504
+ self.assertEqual(
505
+ parse_environ_block("a=1\0b=2\0\0c=3\0"),
506
+ {k("a"): "1", k("b"): "2"},
507
+ )
508
+ # ignore everything that is not an assignment
509
+ self.assertEqual(parse_environ_block("xxx\0a=1\0"), {k("a"): "1"})
510
+ self.assertEqual(parse_environ_block("a=1\0=b=2\0"), {k("a"): "1"})
511
+ # do not fail if the block is incomplete
512
+ self.assertEqual(parse_environ_block("a=1\0b=2"), {k("a"): "1"})
513
+
514
+ def test_supports_ipv6(self):
515
+ self.addCleanup(supports_ipv6.cache_clear)
516
+ if supports_ipv6():
517
+ with mock.patch('psutil._common.socket') as s:
518
+ s.has_ipv6 = False
519
+ supports_ipv6.cache_clear()
520
+ assert not supports_ipv6()
521
+
522
+ supports_ipv6.cache_clear()
523
+ with mock.patch(
524
+ 'psutil._common.socket.socket', side_effect=socket.error
525
+ ) as s:
526
+ assert not supports_ipv6()
527
+ assert s.called
528
+
529
+ supports_ipv6.cache_clear()
530
+ with mock.patch(
531
+ 'psutil._common.socket.socket', side_effect=socket.gaierror
532
+ ) as s:
533
+ assert not supports_ipv6()
534
+ supports_ipv6.cache_clear()
535
+ assert s.called
536
+
537
+ supports_ipv6.cache_clear()
538
+ with mock.patch(
539
+ 'psutil._common.socket.socket.bind',
540
+ side_effect=socket.gaierror,
541
+ ) as s:
542
+ assert not supports_ipv6()
543
+ supports_ipv6.cache_clear()
544
+ assert s.called
545
+ else:
546
+ with self.assertRaises(socket.error):
547
+ sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
548
+ try:
549
+ sock.bind(("::1", 0))
550
+ finally:
551
+ sock.close()
552
+
553
+ def test_isfile_strict(self):
554
+ this_file = os.path.abspath(__file__)
555
+ assert isfile_strict(this_file)
556
+ assert not isfile_strict(os.path.dirname(this_file))
557
+ with mock.patch(
558
+ 'psutil._common.os.stat', side_effect=OSError(errno.EPERM, "foo")
559
+ ):
560
+ self.assertRaises(OSError, isfile_strict, this_file)
561
+ with mock.patch(
562
+ 'psutil._common.os.stat', side_effect=OSError(errno.EACCES, "foo")
563
+ ):
564
+ self.assertRaises(OSError, isfile_strict, this_file)
565
+ with mock.patch(
566
+ 'psutil._common.os.stat', side_effect=OSError(errno.ENOENT, "foo")
567
+ ):
568
+ assert not isfile_strict(this_file)
569
+ with mock.patch('psutil._common.stat.S_ISREG', return_value=False):
570
+ assert not isfile_strict(this_file)
571
+
572
+ def test_debug(self):
573
+ if PY3:
574
+ from io import StringIO
575
+ else:
576
+ from StringIO import StringIO
577
+
578
+ with redirect_stderr(StringIO()) as f:
579
+ debug("hello")
580
+ msg = f.getvalue()
581
+ assert msg.startswith("psutil-debug"), msg
582
+ self.assertIn("hello", msg)
583
+ self.assertIn(__file__.replace('.pyc', '.py'), msg)
584
+
585
+ # supposed to use repr(exc)
586
+ with redirect_stderr(StringIO()) as f:
587
+ debug(ValueError("this is an error"))
588
+ msg = f.getvalue()
589
+ self.assertIn("ignoring ValueError", msg)
590
+ self.assertIn("'this is an error'", msg)
591
+
592
+ # supposed to use str(exc), because of extra info about file name
593
+ with redirect_stderr(StringIO()) as f:
594
+ exc = OSError(2, "no such file")
595
+ exc.filename = "/foo"
596
+ debug(exc)
597
+ msg = f.getvalue()
598
+ self.assertIn("no such file", msg)
599
+ self.assertIn("/foo", msg)
600
+
601
+ def test_cat_bcat(self):
602
+ testfn = self.get_testfn()
603
+ with open(testfn, "w") as f:
604
+ f.write("foo")
605
+ self.assertEqual(cat(testfn), "foo")
606
+ self.assertEqual(bcat(testfn), b"foo")
607
+ self.assertRaises(FileNotFoundError, cat, testfn + '-invalid')
608
+ self.assertRaises(FileNotFoundError, bcat, testfn + '-invalid')
609
+ self.assertEqual(cat(testfn + '-invalid', fallback="bar"), "bar")
610
+ self.assertEqual(bcat(testfn + '-invalid', fallback="bar"), "bar")
611
+
612
+
613
+ # ===================================================================
614
+ # --- Tests for wrap_numbers() function.
615
+ # ===================================================================
616
+
617
+
618
+ nt = collections.namedtuple('foo', 'a b c')
619
+
620
+
621
+ class TestWrapNumbers(PsutilTestCase):
622
+ def setUp(self):
623
+ wrap_numbers.cache_clear()
624
+
625
+ tearDown = setUp
626
+
627
+ def test_first_call(self):
628
+ input = {'disk1': nt(5, 5, 5)}
629
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
630
+
631
+ def test_input_hasnt_changed(self):
632
+ input = {'disk1': nt(5, 5, 5)}
633
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
634
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
635
+
636
+ def test_increase_but_no_wrap(self):
637
+ input = {'disk1': nt(5, 5, 5)}
638
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
639
+ input = {'disk1': nt(10, 15, 20)}
640
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
641
+ input = {'disk1': nt(20, 25, 30)}
642
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
643
+ input = {'disk1': nt(20, 25, 30)}
644
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
645
+
646
+ def test_wrap(self):
647
+ # let's say 100 is the threshold
648
+ input = {'disk1': nt(100, 100, 100)}
649
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
650
+ # first wrap restarts from 10
651
+ input = {'disk1': nt(100, 100, 10)}
652
+ self.assertEqual(
653
+ wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 110)}
654
+ )
655
+ # then it remains the same
656
+ input = {'disk1': nt(100, 100, 10)}
657
+ self.assertEqual(
658
+ wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 110)}
659
+ )
660
+ # then it goes up
661
+ input = {'disk1': nt(100, 100, 90)}
662
+ self.assertEqual(
663
+ wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 190)}
664
+ )
665
+ # then it wraps again
666
+ input = {'disk1': nt(100, 100, 20)}
667
+ self.assertEqual(
668
+ wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 210)}
669
+ )
670
+ # and remains the same
671
+ input = {'disk1': nt(100, 100, 20)}
672
+ self.assertEqual(
673
+ wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 210)}
674
+ )
675
+ # now wrap another num
676
+ input = {'disk1': nt(50, 100, 20)}
677
+ self.assertEqual(
678
+ wrap_numbers(input, 'disk_io'), {'disk1': nt(150, 100, 210)}
679
+ )
680
+ # and again
681
+ input = {'disk1': nt(40, 100, 20)}
682
+ self.assertEqual(
683
+ wrap_numbers(input, 'disk_io'), {'disk1': nt(190, 100, 210)}
684
+ )
685
+ # keep it the same
686
+ input = {'disk1': nt(40, 100, 20)}
687
+ self.assertEqual(
688
+ wrap_numbers(input, 'disk_io'), {'disk1': nt(190, 100, 210)}
689
+ )
690
+
691
+ def test_changing_keys(self):
692
+ # Emulate a case where the second call to disk_io()
693
+ # (or whatever) provides a new disk, then the new disk
694
+ # disappears on the third call.
695
+ input = {'disk1': nt(5, 5, 5)}
696
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
697
+ input = {'disk1': nt(5, 5, 5), 'disk2': nt(7, 7, 7)}
698
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
699
+ input = {'disk1': nt(8, 8, 8)}
700
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
701
+
702
+ def test_changing_keys_w_wrap(self):
703
+ input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 100)}
704
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
705
+ # disk 2 wraps
706
+ input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 10)}
707
+ self.assertEqual(
708
+ wrap_numbers(input, 'disk_io'),
709
+ {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 110)},
710
+ )
711
+ # disk 2 disappears
712
+ input = {'disk1': nt(50, 50, 50)}
713
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
714
+
715
+ # then it appears again; the old wrap is supposed to be
716
+ # gone.
717
+ input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 100)}
718
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
719
+ # remains the same
720
+ input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 100)}
721
+ self.assertEqual(wrap_numbers(input, 'disk_io'), input)
722
+ # and then wraps again
723
+ input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 10)}
724
+ self.assertEqual(
725
+ wrap_numbers(input, 'disk_io'),
726
+ {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 110)},
727
+ )
728
+
729
+ def test_real_data(self):
730
+ d = {
731
+ 'nvme0n1': (300, 508, 640, 1571, 5970, 1987, 2049, 451751, 47048),
732
+ 'nvme0n1p1': (1171, 2, 5600256, 1024, 516, 0, 0, 0, 8),
733
+ 'nvme0n1p2': (54, 54, 2396160, 5165056, 4, 24, 30, 1207, 28),
734
+ 'nvme0n1p3': (2389, 4539, 5154, 150, 4828, 1844, 2019, 398, 348),
735
+ }
736
+ self.assertEqual(wrap_numbers(d, 'disk_io'), d)
737
+ self.assertEqual(wrap_numbers(d, 'disk_io'), d)
738
+ # decrease this ↓
739
+ d = {
740
+ 'nvme0n1': (100, 508, 640, 1571, 5970, 1987, 2049, 451751, 47048),
741
+ 'nvme0n1p1': (1171, 2, 5600256, 1024, 516, 0, 0, 0, 8),
742
+ 'nvme0n1p2': (54, 54, 2396160, 5165056, 4, 24, 30, 1207, 28),
743
+ 'nvme0n1p3': (2389, 4539, 5154, 150, 4828, 1844, 2019, 398, 348),
744
+ }
745
+ out = wrap_numbers(d, 'disk_io')
746
+ self.assertEqual(out['nvme0n1'][0], 400)
747
+
748
+ # --- cache tests
749
+
750
+ def test_cache_first_call(self):
751
+ input = {'disk1': nt(5, 5, 5)}
752
+ wrap_numbers(input, 'disk_io')
753
+ cache = wrap_numbers.cache_info()
754
+ self.assertEqual(cache[0], {'disk_io': input})
755
+ self.assertEqual(cache[1], {'disk_io': {}})
756
+ self.assertEqual(cache[2], {'disk_io': {}})
757
+
758
+ def test_cache_call_twice(self):
759
+ input = {'disk1': nt(5, 5, 5)}
760
+ wrap_numbers(input, 'disk_io')
761
+ input = {'disk1': nt(10, 10, 10)}
762
+ wrap_numbers(input, 'disk_io')
763
+ cache = wrap_numbers.cache_info()
764
+ self.assertEqual(cache[0], {'disk_io': input})
765
+ self.assertEqual(
766
+ cache[1],
767
+ {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 0}},
768
+ )
769
+ self.assertEqual(cache[2], {'disk_io': {}})
770
+
771
+ def test_cache_wrap(self):
772
+ # let's say 100 is the threshold
773
+ input = {'disk1': nt(100, 100, 100)}
774
+ wrap_numbers(input, 'disk_io')
775
+
776
+ # first wrap restarts from 10
777
+ input = {'disk1': nt(100, 100, 10)}
778
+ wrap_numbers(input, 'disk_io')
779
+ cache = wrap_numbers.cache_info()
780
+ self.assertEqual(cache[0], {'disk_io': input})
781
+ self.assertEqual(
782
+ cache[1],
783
+ {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 100}},
784
+ )
785
+ self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}})
786
+
787
+ def check_cache_info():
788
+ cache = wrap_numbers.cache_info()
789
+ self.assertEqual(
790
+ cache[1],
791
+ {
792
+ 'disk_io': {
793
+ ('disk1', 0): 0,
794
+ ('disk1', 1): 0,
795
+ ('disk1', 2): 100,
796
+ }
797
+ },
798
+ )
799
+ self.assertEqual(
800
+ cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}}
801
+ )
802
+
803
+ # then it remains the same
804
+ input = {'disk1': nt(100, 100, 10)}
805
+ wrap_numbers(input, 'disk_io')
806
+ cache = wrap_numbers.cache_info()
807
+ self.assertEqual(cache[0], {'disk_io': input})
808
+ check_cache_info()
809
+
810
+ # then it goes up
811
+ input = {'disk1': nt(100, 100, 90)}
812
+ wrap_numbers(input, 'disk_io')
813
+ cache = wrap_numbers.cache_info()
814
+ self.assertEqual(cache[0], {'disk_io': input})
815
+ check_cache_info()
816
+
817
+ # then it wraps again
818
+ input = {'disk1': nt(100, 100, 20)}
819
+ wrap_numbers(input, 'disk_io')
820
+ cache = wrap_numbers.cache_info()
821
+ self.assertEqual(cache[0], {'disk_io': input})
822
+ self.assertEqual(
823
+ cache[1],
824
+ {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 190}},
825
+ )
826
+ self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}})
827
+
828
+ def test_cache_changing_keys(self):
829
+ input = {'disk1': nt(5, 5, 5)}
830
+ wrap_numbers(input, 'disk_io')
831
+ input = {'disk1': nt(5, 5, 5), 'disk2': nt(7, 7, 7)}
832
+ wrap_numbers(input, 'disk_io')
833
+ cache = wrap_numbers.cache_info()
834
+ self.assertEqual(cache[0], {'disk_io': input})
835
+ self.assertEqual(
836
+ cache[1],
837
+ {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 0}},
838
+ )
839
+ self.assertEqual(cache[2], {'disk_io': {}})
840
+
841
+ def test_cache_clear(self):
842
+ input = {'disk1': nt(5, 5, 5)}
843
+ wrap_numbers(input, 'disk_io')
844
+ wrap_numbers(input, 'disk_io')
845
+ wrap_numbers.cache_clear('disk_io')
846
+ self.assertEqual(wrap_numbers.cache_info(), ({}, {}, {}))
847
+ wrap_numbers.cache_clear('disk_io')
848
+ wrap_numbers.cache_clear('?!?')
849
+
850
+ @unittest.skipIf(not HAS_NET_IO_COUNTERS, 'not supported')
851
+ def test_cache_clear_public_apis(self):
852
+ if not psutil.disk_io_counters() or not psutil.net_io_counters():
853
+ return self.skipTest("no disks or NICs available")
854
+ psutil.disk_io_counters()
855
+ psutil.net_io_counters()
856
+ caches = wrap_numbers.cache_info()
857
+ for cache in caches:
858
+ self.assertIn('psutil.disk_io_counters', cache)
859
+ self.assertIn('psutil.net_io_counters', cache)
860
+
861
+ psutil.disk_io_counters.cache_clear()
862
+ caches = wrap_numbers.cache_info()
863
+ for cache in caches:
864
+ self.assertIn('psutil.net_io_counters', cache)
865
+ self.assertNotIn('psutil.disk_io_counters', cache)
866
+
867
+ psutil.net_io_counters.cache_clear()
868
+ caches = wrap_numbers.cache_info()
869
+ self.assertEqual(caches, ({}, {}, {}))
870
+
871
+
872
+ # ===================================================================
873
+ # --- Example script tests
874
+ # ===================================================================
875
+
876
+
877
+ @unittest.skipIf(
878
+ not os.path.exists(SCRIPTS_DIR), "can't locate scripts directory"
879
+ )
880
+ class TestScripts(PsutilTestCase):
881
+ """Tests for scripts in the "scripts" directory."""
882
+
883
+ @staticmethod
884
+ def assert_stdout(exe, *args, **kwargs):
885
+ kwargs.setdefault("env", PYTHON_EXE_ENV)
886
+ exe = '%s' % os.path.join(SCRIPTS_DIR, exe)
887
+ cmd = [PYTHON_EXE, exe]
888
+ for arg in args:
889
+ cmd.append(arg)
890
+ try:
891
+ out = sh(cmd, **kwargs).strip()
892
+ except RuntimeError as err:
893
+ if 'AccessDenied' in str(err):
894
+ return str(err)
895
+ else:
896
+ raise
897
+ assert out, out
898
+ return out
899
+
900
+ @staticmethod
901
+ def assert_syntax(exe):
902
+ exe = os.path.join(SCRIPTS_DIR, exe)
903
+ with open(exe, encoding="utf8") if PY3 else open(exe) as f:
904
+ src = f.read()
905
+ ast.parse(src)
906
+
907
+ def test_coverage(self):
908
+ # make sure all example scripts have a test method defined
909
+ meths = dir(self)
910
+ for name in os.listdir(SCRIPTS_DIR):
911
+ if name.endswith('.py'):
912
+ if 'test_' + os.path.splitext(name)[0] not in meths:
913
+ # self.assert_stdout(name)
914
+ raise self.fail(
915
+ 'no test defined for %r script'
916
+ % os.path.join(SCRIPTS_DIR, name)
917
+ )
918
+
919
+ @unittest.skipIf(not POSIX, "POSIX only")
920
+ def test_executable(self):
921
+ for root, dirs, files in os.walk(SCRIPTS_DIR):
922
+ for file in files:
923
+ if file.endswith('.py'):
924
+ path = os.path.join(root, file)
925
+ if not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]:
926
+ raise self.fail('%r is not executable' % path)
927
+
928
+ def test_disk_usage(self):
929
+ self.assert_stdout('disk_usage.py')
930
+
931
+ def test_free(self):
932
+ self.assert_stdout('free.py')
933
+
934
+ def test_meminfo(self):
935
+ self.assert_stdout('meminfo.py')
936
+
937
+ def test_procinfo(self):
938
+ self.assert_stdout('procinfo.py', str(os.getpid()))
939
+
940
+ @unittest.skipIf(CI_TESTING and not psutil.users(), "no users")
941
+ def test_who(self):
942
+ self.assert_stdout('who.py')
943
+
944
+ def test_ps(self):
945
+ self.assert_stdout('ps.py')
946
+
947
+ def test_pstree(self):
948
+ self.assert_stdout('pstree.py')
949
+
950
+ def test_netstat(self):
951
+ self.assert_stdout('netstat.py')
952
+
953
+ def test_ifconfig(self):
954
+ self.assert_stdout('ifconfig.py')
955
+
956
+ @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
957
+ def test_pmap(self):
958
+ self.assert_stdout('pmap.py', str(os.getpid()))
959
+
960
+ def test_procsmem(self):
961
+ if 'uss' not in psutil.Process().memory_full_info()._fields:
962
+ raise self.skipTest("not supported")
963
+ self.assert_stdout('procsmem.py')
964
+
965
+ def test_killall(self):
966
+ self.assert_syntax('killall.py')
967
+
968
+ def test_nettop(self):
969
+ self.assert_syntax('nettop.py')
970
+
971
+ def test_top(self):
972
+ self.assert_syntax('top.py')
973
+
974
+ def test_iotop(self):
975
+ self.assert_syntax('iotop.py')
976
+
977
+ def test_pidof(self):
978
+ output = self.assert_stdout('pidof.py', psutil.Process().name())
979
+ self.assertIn(str(os.getpid()), output)
980
+
981
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
982
+ def test_winservices(self):
983
+ self.assert_stdout('winservices.py')
984
+
985
+ def test_cpu_distribution(self):
986
+ self.assert_syntax('cpu_distribution.py')
987
+
988
+ @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
989
+ def test_temperatures(self):
990
+ if not psutil.sensors_temperatures():
991
+ self.skipTest("no temperatures")
992
+ self.assert_stdout('temperatures.py')
993
+
994
+ @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
995
+ def test_fans(self):
996
+ if not psutil.sensors_fans():
997
+ self.skipTest("no fans")
998
+ self.assert_stdout('fans.py')
999
+
1000
+ @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
1001
+ @unittest.skipIf(not HAS_BATTERY, "no battery")
1002
+ def test_battery(self):
1003
+ self.assert_stdout('battery.py')
1004
+
1005
+ @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
1006
+ @unittest.skipIf(not HAS_BATTERY, "no battery")
1007
+ def test_sensors(self):
1008
+ self.assert_stdout('sensors.py')
1009
+
1010
+
1011
+ if __name__ == '__main__':
1012
+ from psutil.tests.runner import run_from_name
1013
+
1014
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_osx.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """macOS specific tests."""
8
+
9
+ import platform
10
+ import re
11
+ import time
12
+ import unittest
13
+
14
+ import psutil
15
+ from psutil import MACOS
16
+ from psutil import POSIX
17
+ from psutil.tests import HAS_BATTERY
18
+ from psutil.tests import TOLERANCE_DISK_USAGE
19
+ from psutil.tests import TOLERANCE_SYS_MEM
20
+ from psutil.tests import PsutilTestCase
21
+ from psutil.tests import retry_on_failure
22
+ from psutil.tests import sh
23
+ from psutil.tests import spawn_testproc
24
+ from psutil.tests import terminate
25
+
26
+
27
+ if POSIX:
28
+ from psutil._psutil_posix import getpagesize
29
+
30
+
31
+ def sysctl(cmdline):
32
+ """Expects a sysctl command with an argument and parse the result
33
+ returning only the value of interest.
34
+ """
35
+ out = sh(cmdline)
36
+ result = out.split()[1]
37
+ try:
38
+ return int(result)
39
+ except ValueError:
40
+ return result
41
+
42
+
43
+ def vm_stat(field):
44
+ """Wrapper around 'vm_stat' cmdline utility."""
45
+ out = sh('vm_stat')
46
+ for line in out.split('\n'):
47
+ if field in line:
48
+ break
49
+ else:
50
+ raise ValueError("line not found")
51
+ return int(re.search(r'\d+', line).group(0)) * getpagesize()
52
+
53
+
54
+ @unittest.skipIf(not MACOS, "MACOS only")
55
+ class TestProcess(PsutilTestCase):
56
+ @classmethod
57
+ def setUpClass(cls):
58
+ cls.pid = spawn_testproc().pid
59
+
60
+ @classmethod
61
+ def tearDownClass(cls):
62
+ terminate(cls.pid)
63
+
64
+ def test_process_create_time(self):
65
+ output = sh("ps -o lstart -p %s" % self.pid)
66
+ start_ps = output.replace('STARTED', '').strip()
67
+ hhmmss = start_ps.split(' ')[-2]
68
+ year = start_ps.split(' ')[-1]
69
+ start_psutil = psutil.Process(self.pid).create_time()
70
+ self.assertEqual(
71
+ hhmmss, time.strftime("%H:%M:%S", time.localtime(start_psutil))
72
+ )
73
+ self.assertEqual(
74
+ year, time.strftime("%Y", time.localtime(start_psutil))
75
+ )
76
+
77
+
78
+ @unittest.skipIf(not MACOS, "MACOS only")
79
+ class TestSystemAPIs(PsutilTestCase):
80
+
81
+ # --- disk
82
+
83
+ @retry_on_failure()
84
+ def test_disks(self):
85
+ # test psutil.disk_usage() and psutil.disk_partitions()
86
+ # against "df -a"
87
+ def df(path):
88
+ out = sh('df -k "%s"' % path).strip()
89
+ lines = out.split('\n')
90
+ lines.pop(0)
91
+ line = lines.pop(0)
92
+ dev, total, used, free = line.split()[:4]
93
+ if dev == 'none':
94
+ dev = ''
95
+ total = int(total) * 1024
96
+ used = int(used) * 1024
97
+ free = int(free) * 1024
98
+ return dev, total, used, free
99
+
100
+ for part in psutil.disk_partitions(all=False):
101
+ usage = psutil.disk_usage(part.mountpoint)
102
+ dev, total, used, free = df(part.mountpoint)
103
+ self.assertEqual(part.device, dev)
104
+ self.assertEqual(usage.total, total)
105
+ self.assertAlmostEqual(
106
+ usage.free, free, delta=TOLERANCE_DISK_USAGE
107
+ )
108
+ self.assertAlmostEqual(
109
+ usage.used, used, delta=TOLERANCE_DISK_USAGE
110
+ )
111
+
112
+ # --- cpu
113
+
114
+ def test_cpu_count_logical(self):
115
+ num = sysctl("sysctl hw.logicalcpu")
116
+ self.assertEqual(num, psutil.cpu_count(logical=True))
117
+
118
+ def test_cpu_count_cores(self):
119
+ num = sysctl("sysctl hw.physicalcpu")
120
+ self.assertEqual(num, psutil.cpu_count(logical=False))
121
+
122
+ # TODO: remove this once 1892 is fixed
123
+ @unittest.skipIf(platform.machine() == 'arm64', "skipped due to #1892")
124
+ def test_cpu_freq(self):
125
+ freq = psutil.cpu_freq()
126
+ self.assertEqual(
127
+ freq.current * 1000 * 1000, sysctl("sysctl hw.cpufrequency")
128
+ )
129
+ self.assertEqual(
130
+ freq.min * 1000 * 1000, sysctl("sysctl hw.cpufrequency_min")
131
+ )
132
+ self.assertEqual(
133
+ freq.max * 1000 * 1000, sysctl("sysctl hw.cpufrequency_max")
134
+ )
135
+
136
+ # --- virtual mem
137
+
138
+ def test_vmem_total(self):
139
+ sysctl_hwphymem = sysctl('sysctl hw.memsize')
140
+ self.assertEqual(sysctl_hwphymem, psutil.virtual_memory().total)
141
+
142
+ @retry_on_failure()
143
+ def test_vmem_free(self):
144
+ vmstat_val = vm_stat("free")
145
+ psutil_val = psutil.virtual_memory().free
146
+ self.assertAlmostEqual(psutil_val, vmstat_val, delta=TOLERANCE_SYS_MEM)
147
+
148
+ @retry_on_failure()
149
+ def test_vmem_active(self):
150
+ vmstat_val = vm_stat("active")
151
+ psutil_val = psutil.virtual_memory().active
152
+ self.assertAlmostEqual(psutil_val, vmstat_val, delta=TOLERANCE_SYS_MEM)
153
+
154
+ @retry_on_failure()
155
+ def test_vmem_inactive(self):
156
+ vmstat_val = vm_stat("inactive")
157
+ psutil_val = psutil.virtual_memory().inactive
158
+ self.assertAlmostEqual(psutil_val, vmstat_val, delta=TOLERANCE_SYS_MEM)
159
+
160
+ @retry_on_failure()
161
+ def test_vmem_wired(self):
162
+ vmstat_val = vm_stat("wired")
163
+ psutil_val = psutil.virtual_memory().wired
164
+ self.assertAlmostEqual(psutil_val, vmstat_val, delta=TOLERANCE_SYS_MEM)
165
+
166
+ # --- swap mem
167
+
168
+ @retry_on_failure()
169
+ def test_swapmem_sin(self):
170
+ vmstat_val = vm_stat("Pageins")
171
+ psutil_val = psutil.swap_memory().sin
172
+ self.assertAlmostEqual(psutil_val, vmstat_val, delta=TOLERANCE_SYS_MEM)
173
+
174
+ @retry_on_failure()
175
+ def test_swapmem_sout(self):
176
+ vmstat_val = vm_stat("Pageout")
177
+ psutil_val = psutil.swap_memory().sout
178
+ self.assertAlmostEqual(psutil_val, vmstat_val, delta=TOLERANCE_SYS_MEM)
179
+
180
+ # --- network
181
+
182
+ def test_net_if_stats(self):
183
+ for name, stats in psutil.net_if_stats().items():
184
+ try:
185
+ out = sh("ifconfig %s" % name)
186
+ except RuntimeError:
187
+ pass
188
+ else:
189
+ self.assertEqual(stats.isup, 'RUNNING' in out, msg=out)
190
+ self.assertEqual(
191
+ stats.mtu, int(re.findall(r'mtu (\d+)', out)[0])
192
+ )
193
+
194
+ # --- sensors_battery
195
+
196
+ @unittest.skipIf(not HAS_BATTERY, "no battery")
197
+ def test_sensors_battery(self):
198
+ out = sh("pmset -g batt")
199
+ percent = re.search(r"(\d+)%", out).group(1)
200
+ drawing_from = re.search("Now drawing from '([^']+)'", out).group(1)
201
+ power_plugged = drawing_from == "AC Power"
202
+ psutil_result = psutil.sensors_battery()
203
+ self.assertEqual(psutil_result.power_plugged, power_plugged)
204
+ self.assertEqual(psutil_result.percent, int(percent))
205
+
206
+
207
+ if __name__ == '__main__':
208
+ from psutil.tests.runner import run_from_name
209
+
210
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_process.py ADDED
@@ -0,0 +1,1636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Tests for psutil.Process class."""
8
+
9
+ import collections
10
+ import errno
11
+ import getpass
12
+ import itertools
13
+ import os
14
+ import signal
15
+ import socket
16
+ import stat
17
+ import subprocess
18
+ import sys
19
+ import textwrap
20
+ import time
21
+ import types
22
+ import unittest
23
+
24
+ import psutil
25
+ from psutil import AIX
26
+ from psutil import BSD
27
+ from psutil import LINUX
28
+ from psutil import MACOS
29
+ from psutil import NETBSD
30
+ from psutil import OPENBSD
31
+ from psutil import OSX
32
+ from psutil import POSIX
33
+ from psutil import SUNOS
34
+ from psutil import WINDOWS
35
+ from psutil._common import open_text
36
+ from psutil._compat import PY3
37
+ from psutil._compat import FileNotFoundError
38
+ from psutil._compat import long
39
+ from psutil._compat import super
40
+ from psutil.tests import APPVEYOR
41
+ from psutil.tests import CI_TESTING
42
+ from psutil.tests import GITHUB_ACTIONS
43
+ from psutil.tests import GLOBAL_TIMEOUT
44
+ from psutil.tests import HAS_CPU_AFFINITY
45
+ from psutil.tests import HAS_ENVIRON
46
+ from psutil.tests import HAS_IONICE
47
+ from psutil.tests import HAS_MEMORY_MAPS
48
+ from psutil.tests import HAS_PROC_CPU_NUM
49
+ from psutil.tests import HAS_PROC_IO_COUNTERS
50
+ from psutil.tests import HAS_RLIMIT
51
+ from psutil.tests import HAS_THREADS
52
+ from psutil.tests import MACOS_11PLUS
53
+ from psutil.tests import PYPY
54
+ from psutil.tests import PYTHON_EXE
55
+ from psutil.tests import PYTHON_EXE_ENV
56
+ from psutil.tests import PsutilTestCase
57
+ from psutil.tests import ThreadTask
58
+ from psutil.tests import call_until
59
+ from psutil.tests import copyload_shared_lib
60
+ from psutil.tests import create_c_exe
61
+ from psutil.tests import create_py_exe
62
+ from psutil.tests import mock
63
+ from psutil.tests import process_namespace
64
+ from psutil.tests import reap_children
65
+ from psutil.tests import retry_on_failure
66
+ from psutil.tests import sh
67
+ from psutil.tests import skip_on_access_denied
68
+ from psutil.tests import skip_on_not_implemented
69
+ from psutil.tests import wait_for_pid
70
+
71
+
72
+ # ===================================================================
73
+ # --- psutil.Process class tests
74
+ # ===================================================================
75
+
76
+
77
+ class TestProcess(PsutilTestCase):
78
+ """Tests for psutil.Process class."""
79
+
80
+ def spawn_psproc(self, *args, **kwargs):
81
+ sproc = self.spawn_testproc(*args, **kwargs)
82
+ try:
83
+ return psutil.Process(sproc.pid)
84
+ except psutil.NoSuchProcess:
85
+ self.assertPidGone(sproc.pid)
86
+ raise
87
+
88
+ # ---
89
+
90
+ def test_pid(self):
91
+ p = psutil.Process()
92
+ self.assertEqual(p.pid, os.getpid())
93
+ with self.assertRaises(AttributeError):
94
+ p.pid = 33
95
+
96
+ def test_kill(self):
97
+ p = self.spawn_psproc()
98
+ p.kill()
99
+ code = p.wait()
100
+ if WINDOWS:
101
+ self.assertEqual(code, signal.SIGTERM)
102
+ else:
103
+ self.assertEqual(code, -signal.SIGKILL)
104
+ self.assertProcessGone(p)
105
+
106
+ def test_terminate(self):
107
+ p = self.spawn_psproc()
108
+ p.terminate()
109
+ code = p.wait()
110
+ if WINDOWS:
111
+ self.assertEqual(code, signal.SIGTERM)
112
+ else:
113
+ self.assertEqual(code, -signal.SIGTERM)
114
+ self.assertProcessGone(p)
115
+
116
+ def test_send_signal(self):
117
+ sig = signal.SIGKILL if POSIX else signal.SIGTERM
118
+ p = self.spawn_psproc()
119
+ p.send_signal(sig)
120
+ code = p.wait()
121
+ if WINDOWS:
122
+ self.assertEqual(code, sig)
123
+ else:
124
+ self.assertEqual(code, -sig)
125
+ self.assertProcessGone(p)
126
+
127
+ @unittest.skipIf(not POSIX, "not POSIX")
128
+ def test_send_signal_mocked(self):
129
+ sig = signal.SIGTERM
130
+ p = self.spawn_psproc()
131
+ with mock.patch(
132
+ 'psutil.os.kill', side_effect=OSError(errno.ESRCH, "")
133
+ ):
134
+ self.assertRaises(psutil.NoSuchProcess, p.send_signal, sig)
135
+
136
+ p = self.spawn_psproc()
137
+ with mock.patch(
138
+ 'psutil.os.kill', side_effect=OSError(errno.EPERM, "")
139
+ ):
140
+ self.assertRaises(psutil.AccessDenied, p.send_signal, sig)
141
+
142
+ def test_wait_exited(self):
143
+ # Test waitpid() + WIFEXITED -> WEXITSTATUS.
144
+ # normal return, same as exit(0)
145
+ cmd = [PYTHON_EXE, "-c", "pass"]
146
+ p = self.spawn_psproc(cmd)
147
+ code = p.wait()
148
+ self.assertEqual(code, 0)
149
+ self.assertProcessGone(p)
150
+ # exit(1), implicit in case of error
151
+ cmd = [PYTHON_EXE, "-c", "1 / 0"]
152
+ p = self.spawn_psproc(cmd, stderr=subprocess.PIPE)
153
+ code = p.wait()
154
+ self.assertEqual(code, 1)
155
+ self.assertProcessGone(p)
156
+ # via sys.exit()
157
+ cmd = [PYTHON_EXE, "-c", "import sys; sys.exit(5);"]
158
+ p = self.spawn_psproc(cmd)
159
+ code = p.wait()
160
+ self.assertEqual(code, 5)
161
+ self.assertProcessGone(p)
162
+ # via os._exit()
163
+ cmd = [PYTHON_EXE, "-c", "import os; os._exit(5);"]
164
+ p = self.spawn_psproc(cmd)
165
+ code = p.wait()
166
+ self.assertEqual(code, 5)
167
+ self.assertProcessGone(p)
168
+
169
+ @unittest.skipIf(NETBSD, "fails on NETBSD")
170
+ def test_wait_stopped(self):
171
+ p = self.spawn_psproc()
172
+ if POSIX:
173
+ # Test waitpid() + WIFSTOPPED and WIFCONTINUED.
174
+ # Note: if a process is stopped it ignores SIGTERM.
175
+ p.send_signal(signal.SIGSTOP)
176
+ self.assertRaises(psutil.TimeoutExpired, p.wait, timeout=0.001)
177
+ p.send_signal(signal.SIGCONT)
178
+ self.assertRaises(psutil.TimeoutExpired, p.wait, timeout=0.001)
179
+ p.send_signal(signal.SIGTERM)
180
+ self.assertEqual(p.wait(), -signal.SIGTERM)
181
+ self.assertEqual(p.wait(), -signal.SIGTERM)
182
+ else:
183
+ p.suspend()
184
+ self.assertRaises(psutil.TimeoutExpired, p.wait, timeout=0.001)
185
+ p.resume()
186
+ self.assertRaises(psutil.TimeoutExpired, p.wait, timeout=0.001)
187
+ p.terminate()
188
+ self.assertEqual(p.wait(), signal.SIGTERM)
189
+ self.assertEqual(p.wait(), signal.SIGTERM)
190
+
191
+ def test_wait_non_children(self):
192
+ # Test wait() against a process which is not our direct
193
+ # child.
194
+ child, grandchild = self.spawn_children_pair()
195
+ self.assertRaises(psutil.TimeoutExpired, child.wait, 0.01)
196
+ self.assertRaises(psutil.TimeoutExpired, grandchild.wait, 0.01)
197
+ # We also terminate the direct child otherwise the
198
+ # grandchild will hang until the parent is gone.
199
+ child.terminate()
200
+ grandchild.terminate()
201
+ child_ret = child.wait()
202
+ grandchild_ret = grandchild.wait()
203
+ if POSIX:
204
+ self.assertEqual(child_ret, -signal.SIGTERM)
205
+ # For processes which are not our children we're supposed
206
+ # to get None.
207
+ self.assertEqual(grandchild_ret, None)
208
+ else:
209
+ self.assertEqual(child_ret, signal.SIGTERM)
210
+ self.assertEqual(child_ret, signal.SIGTERM)
211
+
212
+ def test_wait_timeout(self):
213
+ p = self.spawn_psproc()
214
+ p.name()
215
+ self.assertRaises(psutil.TimeoutExpired, p.wait, 0.01)
216
+ self.assertRaises(psutil.TimeoutExpired, p.wait, 0)
217
+ self.assertRaises(ValueError, p.wait, -1)
218
+
219
+ def test_wait_timeout_nonblocking(self):
220
+ p = self.spawn_psproc()
221
+ self.assertRaises(psutil.TimeoutExpired, p.wait, 0)
222
+ p.kill()
223
+ stop_at = time.time() + GLOBAL_TIMEOUT
224
+ while time.time() < stop_at:
225
+ try:
226
+ code = p.wait(0)
227
+ break
228
+ except psutil.TimeoutExpired:
229
+ pass
230
+ else:
231
+ raise self.fail('timeout')
232
+ if POSIX:
233
+ self.assertEqual(code, -signal.SIGKILL)
234
+ else:
235
+ self.assertEqual(code, signal.SIGTERM)
236
+ self.assertProcessGone(p)
237
+
238
+ def test_cpu_percent(self):
239
+ p = psutil.Process()
240
+ p.cpu_percent(interval=0.001)
241
+ p.cpu_percent(interval=0.001)
242
+ for _ in range(100):
243
+ percent = p.cpu_percent(interval=None)
244
+ self.assertIsInstance(percent, float)
245
+ self.assertGreaterEqual(percent, 0.0)
246
+ with self.assertRaises(ValueError):
247
+ p.cpu_percent(interval=-1)
248
+
249
+ def test_cpu_percent_numcpus_none(self):
250
+ # See: https://github.com/giampaolo/psutil/issues/1087
251
+ with mock.patch('psutil.cpu_count', return_value=None) as m:
252
+ psutil.Process().cpu_percent()
253
+ assert m.called
254
+
255
+ def test_cpu_times(self):
256
+ times = psutil.Process().cpu_times()
257
+ assert (times.user > 0.0) or (times.system > 0.0), times
258
+ assert times.children_user >= 0.0, times
259
+ assert times.children_system >= 0.0, times
260
+ if LINUX:
261
+ assert times.iowait >= 0.0, times
262
+ # make sure returned values can be pretty printed with strftime
263
+ for name in times._fields:
264
+ time.strftime("%H:%M:%S", time.localtime(getattr(times, name)))
265
+
266
+ def test_cpu_times_2(self):
267
+ user_time, kernel_time = psutil.Process().cpu_times()[:2]
268
+ utime, ktime = os.times()[:2]
269
+
270
+ # Use os.times()[:2] as base values to compare our results
271
+ # using a tolerance of +/- 0.1 seconds.
272
+ # It will fail if the difference between the values is > 0.1s.
273
+ if (max([user_time, utime]) - min([user_time, utime])) > 0.1:
274
+ raise self.fail("expected: %s, found: %s" % (utime, user_time))
275
+
276
+ if (max([kernel_time, ktime]) - min([kernel_time, ktime])) > 0.1:
277
+ raise self.fail("expected: %s, found: %s" % (ktime, kernel_time))
278
+
279
+ @unittest.skipIf(not HAS_PROC_CPU_NUM, "not supported")
280
+ def test_cpu_num(self):
281
+ p = psutil.Process()
282
+ num = p.cpu_num()
283
+ self.assertGreaterEqual(num, 0)
284
+ if psutil.cpu_count() == 1:
285
+ self.assertEqual(num, 0)
286
+ self.assertIn(p.cpu_num(), range(psutil.cpu_count()))
287
+
288
+ def test_create_time(self):
289
+ p = self.spawn_psproc()
290
+ now = time.time()
291
+ create_time = p.create_time()
292
+
293
+ # Use time.time() as base value to compare our result using a
294
+ # tolerance of +/- 1 second.
295
+ # It will fail if the difference between the values is > 2s.
296
+ difference = abs(create_time - now)
297
+ if difference > 2:
298
+ raise self.fail(
299
+ "expected: %s, found: %s, difference: %s"
300
+ % (now, create_time, difference)
301
+ )
302
+
303
+ # make sure returned value can be pretty printed with strftime
304
+ time.strftime("%Y %m %d %H:%M:%S", time.localtime(p.create_time()))
305
+
306
+ @unittest.skipIf(not POSIX, 'POSIX only')
307
+ def test_terminal(self):
308
+ terminal = psutil.Process().terminal()
309
+ if terminal is not None:
310
+ tty = os.path.realpath(sh('tty'))
311
+ self.assertEqual(terminal, tty)
312
+
313
+ @unittest.skipIf(not HAS_PROC_IO_COUNTERS, 'not supported')
314
+ @skip_on_not_implemented(only_if=LINUX)
315
+ def test_io_counters(self):
316
+ p = psutil.Process()
317
+ # test reads
318
+ io1 = p.io_counters()
319
+ with open(PYTHON_EXE, 'rb') as f:
320
+ f.read()
321
+ io2 = p.io_counters()
322
+ if not BSD and not AIX:
323
+ self.assertGreater(io2.read_count, io1.read_count)
324
+ self.assertEqual(io2.write_count, io1.write_count)
325
+ if LINUX:
326
+ self.assertGreater(io2.read_chars, io1.read_chars)
327
+ self.assertEqual(io2.write_chars, io1.write_chars)
328
+ else:
329
+ self.assertGreaterEqual(io2.read_bytes, io1.read_bytes)
330
+ self.assertGreaterEqual(io2.write_bytes, io1.write_bytes)
331
+
332
+ # test writes
333
+ io1 = p.io_counters()
334
+ with open(self.get_testfn(), 'wb') as f:
335
+ if PY3:
336
+ f.write(bytes("x" * 1000000, 'ascii'))
337
+ else:
338
+ f.write("x" * 1000000)
339
+ io2 = p.io_counters()
340
+ self.assertGreaterEqual(io2.write_count, io1.write_count)
341
+ self.assertGreaterEqual(io2.write_bytes, io1.write_bytes)
342
+ self.assertGreaterEqual(io2.read_count, io1.read_count)
343
+ self.assertGreaterEqual(io2.read_bytes, io1.read_bytes)
344
+ if LINUX:
345
+ self.assertGreater(io2.write_chars, io1.write_chars)
346
+ self.assertGreaterEqual(io2.read_chars, io1.read_chars)
347
+
348
+ # sanity check
349
+ for i in range(len(io2)):
350
+ if BSD and i >= 2:
351
+ # On BSD read_bytes and write_bytes are always set to -1.
352
+ continue
353
+ self.assertGreaterEqual(io2[i], 0)
354
+ self.assertGreaterEqual(io2[i], 0)
355
+
356
+ @unittest.skipIf(not HAS_IONICE, "not supported")
357
+ @unittest.skipIf(not LINUX, "linux only")
358
+ def test_ionice_linux(self):
359
+ def cleanup(init):
360
+ ioclass, value = init
361
+ if ioclass == psutil.IOPRIO_CLASS_NONE:
362
+ value = 0
363
+ p.ionice(ioclass, value)
364
+
365
+ p = psutil.Process()
366
+ if not CI_TESTING:
367
+ self.assertEqual(p.ionice()[0], psutil.IOPRIO_CLASS_NONE)
368
+ self.assertEqual(psutil.IOPRIO_CLASS_NONE, 0)
369
+ self.assertEqual(psutil.IOPRIO_CLASS_RT, 1) # high
370
+ self.assertEqual(psutil.IOPRIO_CLASS_BE, 2) # normal
371
+ self.assertEqual(psutil.IOPRIO_CLASS_IDLE, 3) # low
372
+ init = p.ionice()
373
+ self.addCleanup(cleanup, init)
374
+
375
+ # low
376
+ p.ionice(psutil.IOPRIO_CLASS_IDLE)
377
+ self.assertEqual(tuple(p.ionice()), (psutil.IOPRIO_CLASS_IDLE, 0))
378
+ with self.assertRaises(ValueError): # accepts no value
379
+ p.ionice(psutil.IOPRIO_CLASS_IDLE, value=7)
380
+ # normal
381
+ p.ionice(psutil.IOPRIO_CLASS_BE)
382
+ self.assertEqual(tuple(p.ionice()), (psutil.IOPRIO_CLASS_BE, 0))
383
+ p.ionice(psutil.IOPRIO_CLASS_BE, value=7)
384
+ self.assertEqual(tuple(p.ionice()), (psutil.IOPRIO_CLASS_BE, 7))
385
+ with self.assertRaises(ValueError):
386
+ p.ionice(psutil.IOPRIO_CLASS_BE, value=8)
387
+ try:
388
+ p.ionice(psutil.IOPRIO_CLASS_RT, value=7)
389
+ except psutil.AccessDenied:
390
+ pass
391
+ # errs
392
+ with self.assertRaisesRegex(ValueError, "ioclass accepts no value"):
393
+ p.ionice(psutil.IOPRIO_CLASS_NONE, 1)
394
+ with self.assertRaisesRegex(ValueError, "ioclass accepts no value"):
395
+ p.ionice(psutil.IOPRIO_CLASS_IDLE, 1)
396
+ with self.assertRaisesRegex(
397
+ ValueError, "'ioclass' argument must be specified"
398
+ ):
399
+ p.ionice(value=1)
400
+
401
+ @unittest.skipIf(not HAS_IONICE, "not supported")
402
+ @unittest.skipIf(not WINDOWS, 'not supported on this win version')
403
+ def test_ionice_win(self):
404
+ p = psutil.Process()
405
+ if not CI_TESTING:
406
+ self.assertEqual(p.ionice(), psutil.IOPRIO_NORMAL)
407
+ init = p.ionice()
408
+ self.addCleanup(p.ionice, init)
409
+
410
+ # base
411
+ p.ionice(psutil.IOPRIO_VERYLOW)
412
+ self.assertEqual(p.ionice(), psutil.IOPRIO_VERYLOW)
413
+ p.ionice(psutil.IOPRIO_LOW)
414
+ self.assertEqual(p.ionice(), psutil.IOPRIO_LOW)
415
+ try:
416
+ p.ionice(psutil.IOPRIO_HIGH)
417
+ except psutil.AccessDenied:
418
+ pass
419
+ else:
420
+ self.assertEqual(p.ionice(), psutil.IOPRIO_HIGH)
421
+ # errs
422
+ with self.assertRaisesRegex(
423
+ TypeError, "value argument not accepted on Windows"
424
+ ):
425
+ p.ionice(psutil.IOPRIO_NORMAL, value=1)
426
+ with self.assertRaisesRegex(ValueError, "is not a valid priority"):
427
+ p.ionice(psutil.IOPRIO_HIGH + 1)
428
+
429
+ @unittest.skipIf(not HAS_RLIMIT, "not supported")
430
+ def test_rlimit_get(self):
431
+ import resource
432
+
433
+ p = psutil.Process(os.getpid())
434
+ names = [x for x in dir(psutil) if x.startswith('RLIMIT')]
435
+ assert names, names
436
+ for name in names:
437
+ value = getattr(psutil, name)
438
+ self.assertGreaterEqual(value, 0)
439
+ if name in dir(resource):
440
+ self.assertEqual(value, getattr(resource, name))
441
+ # XXX - On PyPy RLIMIT_INFINITY returned by
442
+ # resource.getrlimit() is reported as a very big long
443
+ # number instead of -1. It looks like a bug with PyPy.
444
+ if PYPY:
445
+ continue
446
+ self.assertEqual(p.rlimit(value), resource.getrlimit(value))
447
+ else:
448
+ ret = p.rlimit(value)
449
+ self.assertEqual(len(ret), 2)
450
+ self.assertGreaterEqual(ret[0], -1)
451
+ self.assertGreaterEqual(ret[1], -1)
452
+
453
+ @unittest.skipIf(not HAS_RLIMIT, "not supported")
454
+ def test_rlimit_set(self):
455
+ p = self.spawn_psproc()
456
+ p.rlimit(psutil.RLIMIT_NOFILE, (5, 5))
457
+ self.assertEqual(p.rlimit(psutil.RLIMIT_NOFILE), (5, 5))
458
+ # If pid is 0 prlimit() applies to the calling process and
459
+ # we don't want that.
460
+ if LINUX:
461
+ with self.assertRaisesRegex(ValueError, "can't use prlimit"):
462
+ psutil._psplatform.Process(0).rlimit(0)
463
+ with self.assertRaises(ValueError):
464
+ p.rlimit(psutil.RLIMIT_NOFILE, (5, 5, 5))
465
+
466
+ @unittest.skipIf(not HAS_RLIMIT, "not supported")
467
+ def test_rlimit(self):
468
+ p = psutil.Process()
469
+ testfn = self.get_testfn()
470
+ soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
471
+ try:
472
+ p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard))
473
+ with open(testfn, "wb") as f:
474
+ f.write(b"X" * 1024)
475
+ # write() or flush() doesn't always cause the exception
476
+ # but close() will.
477
+ with self.assertRaises(IOError) as exc:
478
+ with open(testfn, "wb") as f:
479
+ f.write(b"X" * 1025)
480
+ self.assertEqual(
481
+ exc.exception.errno if PY3 else exc.exception[0], errno.EFBIG
482
+ )
483
+ finally:
484
+ p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
485
+ self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard))
486
+
487
+ @unittest.skipIf(not HAS_RLIMIT, "not supported")
488
+ def test_rlimit_infinity(self):
489
+ # First set a limit, then re-set it by specifying INFINITY
490
+ # and assume we overridden the previous limit.
491
+ p = psutil.Process()
492
+ soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
493
+ try:
494
+ p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard))
495
+ p.rlimit(psutil.RLIMIT_FSIZE, (psutil.RLIM_INFINITY, hard))
496
+ with open(self.get_testfn(), "wb") as f:
497
+ f.write(b"X" * 2048)
498
+ finally:
499
+ p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
500
+ self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard))
501
+
502
+ @unittest.skipIf(not HAS_RLIMIT, "not supported")
503
+ def test_rlimit_infinity_value(self):
504
+ # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really
505
+ # big number on a platform with large file support. On these
506
+ # platforms we need to test that the get/setrlimit functions
507
+ # properly convert the number to a C long long and that the
508
+ # conversion doesn't raise an error.
509
+ p = psutil.Process()
510
+ soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
511
+ self.assertEqual(psutil.RLIM_INFINITY, hard)
512
+ p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
513
+
514
+ def test_num_threads(self):
515
+ # on certain platforms such as Linux we might test for exact
516
+ # thread number, since we always have with 1 thread per process,
517
+ # but this does not apply across all platforms (MACOS, Windows)
518
+ p = psutil.Process()
519
+ if OPENBSD:
520
+ try:
521
+ step1 = p.num_threads()
522
+ except psutil.AccessDenied:
523
+ raise unittest.SkipTest("on OpenBSD this requires root access")
524
+ else:
525
+ step1 = p.num_threads()
526
+
527
+ with ThreadTask():
528
+ step2 = p.num_threads()
529
+ self.assertEqual(step2, step1 + 1)
530
+
531
+ @unittest.skipIf(not WINDOWS, 'WINDOWS only')
532
+ def test_num_handles(self):
533
+ # a better test is done later into test/_windows.py
534
+ p = psutil.Process()
535
+ self.assertGreater(p.num_handles(), 0)
536
+
537
+ @unittest.skipIf(not HAS_THREADS, 'not supported')
538
+ def test_threads(self):
539
+ p = psutil.Process()
540
+ if OPENBSD:
541
+ try:
542
+ step1 = p.threads()
543
+ except psutil.AccessDenied:
544
+ raise unittest.SkipTest("on OpenBSD this requires root access")
545
+ else:
546
+ step1 = p.threads()
547
+
548
+ with ThreadTask():
549
+ step2 = p.threads()
550
+ self.assertEqual(len(step2), len(step1) + 1)
551
+ athread = step2[0]
552
+ # test named tuple
553
+ self.assertEqual(athread.id, athread[0])
554
+ self.assertEqual(athread.user_time, athread[1])
555
+ self.assertEqual(athread.system_time, athread[2])
556
+
557
+ @retry_on_failure()
558
+ @skip_on_access_denied(only_if=MACOS)
559
+ @unittest.skipIf(not HAS_THREADS, 'not supported')
560
+ def test_threads_2(self):
561
+ p = self.spawn_psproc()
562
+ if OPENBSD:
563
+ try:
564
+ p.threads()
565
+ except psutil.AccessDenied:
566
+ raise unittest.SkipTest("on OpenBSD this requires root access")
567
+ self.assertAlmostEqual(
568
+ p.cpu_times().user,
569
+ sum([x.user_time for x in p.threads()]),
570
+ delta=0.1,
571
+ )
572
+ self.assertAlmostEqual(
573
+ p.cpu_times().system,
574
+ sum([x.system_time for x in p.threads()]),
575
+ delta=0.1,
576
+ )
577
+
578
+ @retry_on_failure()
579
+ def test_memory_info(self):
580
+ p = psutil.Process()
581
+
582
+ # step 1 - get a base value to compare our results
583
+ rss1, vms1 = p.memory_info()[:2]
584
+ percent1 = p.memory_percent()
585
+ self.assertGreater(rss1, 0)
586
+ self.assertGreater(vms1, 0)
587
+
588
+ # step 2 - allocate some memory
589
+ memarr = [None] * 1500000
590
+
591
+ rss2, vms2 = p.memory_info()[:2]
592
+ percent2 = p.memory_percent()
593
+
594
+ # step 3 - make sure that the memory usage bumped up
595
+ self.assertGreater(rss2, rss1)
596
+ self.assertGreaterEqual(vms2, vms1) # vms might be equal
597
+ self.assertGreater(percent2, percent1)
598
+ del memarr
599
+
600
+ if WINDOWS:
601
+ mem = p.memory_info()
602
+ self.assertEqual(mem.rss, mem.wset)
603
+ self.assertEqual(mem.vms, mem.pagefile)
604
+
605
+ mem = p.memory_info()
606
+ for name in mem._fields:
607
+ self.assertGreaterEqual(getattr(mem, name), 0)
608
+
609
+ def test_memory_full_info(self):
610
+ p = psutil.Process()
611
+ total = psutil.virtual_memory().total
612
+ mem = p.memory_full_info()
613
+ for name in mem._fields:
614
+ value = getattr(mem, name)
615
+ self.assertGreaterEqual(value, 0, msg=(name, value))
616
+ if name == 'vms' and OSX or LINUX:
617
+ continue
618
+ self.assertLessEqual(value, total, msg=(name, value, total))
619
+ if LINUX or WINDOWS or MACOS:
620
+ self.assertGreaterEqual(mem.uss, 0)
621
+ if LINUX:
622
+ self.assertGreaterEqual(mem.pss, 0)
623
+ self.assertGreaterEqual(mem.swap, 0)
624
+
625
+ @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
626
+ def test_memory_maps(self):
627
+ p = psutil.Process()
628
+ maps = p.memory_maps()
629
+ self.assertEqual(len(maps), len(set(maps)))
630
+ ext_maps = p.memory_maps(grouped=False)
631
+
632
+ for nt in maps:
633
+ if not nt.path.startswith('['):
634
+ assert os.path.isabs(nt.path), nt.path
635
+ if POSIX:
636
+ try:
637
+ assert os.path.exists(nt.path) or os.path.islink(
638
+ nt.path
639
+ ), nt.path
640
+ except AssertionError:
641
+ if not LINUX:
642
+ raise
643
+ else:
644
+ # https://github.com/giampaolo/psutil/issues/759
645
+ with open_text('/proc/self/smaps') as f:
646
+ data = f.read()
647
+ if "%s (deleted)" % nt.path not in data:
648
+ raise
649
+ else:
650
+ # XXX - On Windows we have this strange behavior with
651
+ # 64 bit dlls: they are visible via explorer but cannot
652
+ # be accessed via os.stat() (wtf?).
653
+ if '64' not in os.path.basename(nt.path):
654
+ try:
655
+ st = os.stat(nt.path)
656
+ except FileNotFoundError:
657
+ pass
658
+ else:
659
+ assert stat.S_ISREG(st.st_mode), nt.path
660
+ for nt in ext_maps:
661
+ for fname in nt._fields:
662
+ value = getattr(nt, fname)
663
+ if fname == 'path':
664
+ continue
665
+ if fname in ('addr', 'perms'):
666
+ assert value, value
667
+ else:
668
+ self.assertIsInstance(value, (int, long))
669
+ assert value >= 0, value
670
+
671
+ @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
672
+ def test_memory_maps_lists_lib(self):
673
+ # Make sure a newly loaded shared lib is listed.
674
+ p = psutil.Process()
675
+ with copyload_shared_lib() as path:
676
+
677
+ def normpath(p):
678
+ return os.path.realpath(os.path.normcase(p))
679
+
680
+ libpaths = [normpath(x.path) for x in p.memory_maps()]
681
+ self.assertIn(normpath(path), libpaths)
682
+
683
+ def test_memory_percent(self):
684
+ p = psutil.Process()
685
+ p.memory_percent()
686
+ self.assertRaises(ValueError, p.memory_percent, memtype="?!?")
687
+ if LINUX or MACOS or WINDOWS:
688
+ p.memory_percent(memtype='uss')
689
+
690
+ def test_is_running(self):
691
+ p = self.spawn_psproc()
692
+ assert p.is_running()
693
+ assert p.is_running()
694
+ p.kill()
695
+ p.wait()
696
+ assert not p.is_running()
697
+ assert not p.is_running()
698
+
699
+ def test_exe(self):
700
+ p = self.spawn_psproc()
701
+ exe = p.exe()
702
+ try:
703
+ self.assertEqual(exe, PYTHON_EXE)
704
+ except AssertionError:
705
+ if WINDOWS and len(exe) == len(PYTHON_EXE):
706
+ # on Windows we don't care about case sensitivity
707
+ normcase = os.path.normcase
708
+ self.assertEqual(normcase(exe), normcase(PYTHON_EXE))
709
+ else:
710
+ # certain platforms such as BSD are more accurate returning:
711
+ # "/usr/local/bin/python2.7"
712
+ # ...instead of:
713
+ # "/usr/local/bin/python"
714
+ # We do not want to consider this difference in accuracy
715
+ # an error.
716
+ ver = "%s.%s" % (sys.version_info[0], sys.version_info[1])
717
+ try:
718
+ self.assertEqual(
719
+ exe.replace(ver, ''), PYTHON_EXE.replace(ver, '')
720
+ )
721
+ except AssertionError:
722
+ # Typically MACOS. Really not sure what to do here.
723
+ pass
724
+
725
+ out = sh([exe, "-c", "import os; print('hey')"])
726
+ self.assertEqual(out, 'hey')
727
+
728
+ def test_cmdline(self):
729
+ cmdline = [PYTHON_EXE, "-c", "import time; time.sleep(60)"]
730
+ p = self.spawn_psproc(cmdline)
731
+ # XXX - most of the times the underlying sysctl() call on Net
732
+ # and Open BSD returns a truncated string.
733
+ # Also /proc/pid/cmdline behaves the same so it looks
734
+ # like this is a kernel bug.
735
+ # XXX - AIX truncates long arguments in /proc/pid/cmdline
736
+ if NETBSD or OPENBSD or AIX:
737
+ self.assertEqual(p.cmdline()[0], PYTHON_EXE)
738
+ else:
739
+ if MACOS and CI_TESTING:
740
+ pyexe = p.cmdline()[0]
741
+ if pyexe != PYTHON_EXE:
742
+ self.assertEqual(
743
+ ' '.join(p.cmdline()[1:]), ' '.join(cmdline[1:])
744
+ )
745
+ return
746
+ self.assertEqual(' '.join(p.cmdline()), ' '.join(cmdline))
747
+
748
+ @unittest.skipIf(PYPY, "broken on PYPY")
749
+ def test_long_cmdline(self):
750
+ cmdline = [PYTHON_EXE]
751
+ cmdline.extend(["-v"] * 50)
752
+ cmdline.extend(["-c", "import time; time.sleep(10)"])
753
+ p = self.spawn_psproc(cmdline)
754
+ if OPENBSD:
755
+ # XXX: for some reason the test process may turn into a
756
+ # zombie (don't know why).
757
+ try:
758
+ self.assertEqual(p.cmdline(), cmdline)
759
+ except psutil.ZombieProcess:
760
+ raise self.skipTest("OPENBSD: process turned into zombie")
761
+ else:
762
+ self.assertEqual(p.cmdline(), cmdline)
763
+
764
+ def test_name(self):
765
+ p = self.spawn_psproc()
766
+ name = p.name().lower()
767
+ pyexe = os.path.basename(os.path.realpath(sys.executable)).lower()
768
+ assert pyexe.startswith(name), (pyexe, name)
769
+
770
+ @unittest.skipIf(PYPY, "unreliable on PYPY")
771
+ def test_long_name(self):
772
+ pyexe = create_py_exe(self.get_testfn(suffix="0123456789" * 2))
773
+ cmdline = [pyexe, "-c", "import time; time.sleep(10)"]
774
+ p = self.spawn_psproc(cmdline)
775
+ if OPENBSD:
776
+ # XXX: for some reason the test process may turn into a
777
+ # zombie (don't know why). Because the name() is long, all
778
+ # UNIX kernels truncate it to 15 chars, so internally psutil
779
+ # tries to guess the full name() from the cmdline(). But the
780
+ # cmdline() of a zombie on OpenBSD fails (internally), so we
781
+ # just compare the first 15 chars. Full explanation:
782
+ # https://github.com/giampaolo/psutil/issues/2239
783
+ try:
784
+ self.assertEqual(p.name(), os.path.basename(pyexe))
785
+ except AssertionError:
786
+ if p.status() == psutil.STATUS_ZOMBIE:
787
+ assert os.path.basename(pyexe).startswith(p.name())
788
+ else:
789
+ raise
790
+ else:
791
+ self.assertEqual(p.name(), os.path.basename(pyexe))
792
+
793
+ # XXX
794
+ @unittest.skipIf(SUNOS, "broken on SUNOS")
795
+ @unittest.skipIf(AIX, "broken on AIX")
796
+ @unittest.skipIf(PYPY, "broken on PYPY")
797
+ def test_prog_w_funky_name(self):
798
+ # Test that name(), exe() and cmdline() correctly handle programs
799
+ # with funky chars such as spaces and ")", see:
800
+ # https://github.com/giampaolo/psutil/issues/628
801
+ pyexe = create_py_exe(self.get_testfn(suffix='foo bar )'))
802
+ cmdline = [pyexe, "-c", "import time; time.sleep(10)"]
803
+ p = self.spawn_psproc(cmdline)
804
+ self.assertEqual(p.cmdline(), cmdline)
805
+ self.assertEqual(p.name(), os.path.basename(pyexe))
806
+ self.assertEqual(os.path.normcase(p.exe()), os.path.normcase(pyexe))
807
+
808
+ @unittest.skipIf(not POSIX, 'POSIX only')
809
+ def test_uids(self):
810
+ p = psutil.Process()
811
+ real, effective, saved = p.uids()
812
+ # os.getuid() refers to "real" uid
813
+ self.assertEqual(real, os.getuid())
814
+ # os.geteuid() refers to "effective" uid
815
+ self.assertEqual(effective, os.geteuid())
816
+ # No such thing as os.getsuid() ("saved" uid), but starting
817
+ # from python 2.7 we have os.getresuid() which returns all
818
+ # of them.
819
+ if hasattr(os, "getresuid"):
820
+ self.assertEqual(os.getresuid(), p.uids())
821
+
822
+ @unittest.skipIf(not POSIX, 'POSIX only')
823
+ def test_gids(self):
824
+ p = psutil.Process()
825
+ real, effective, saved = p.gids()
826
+ # os.getuid() refers to "real" uid
827
+ self.assertEqual(real, os.getgid())
828
+ # os.geteuid() refers to "effective" uid
829
+ self.assertEqual(effective, os.getegid())
830
+ # No such thing as os.getsgid() ("saved" gid), but starting
831
+ # from python 2.7 we have os.getresgid() which returns all
832
+ # of them.
833
+ if hasattr(os, "getresuid"):
834
+ self.assertEqual(os.getresgid(), p.gids())
835
+
836
+ def test_nice(self):
837
+ def cleanup(init):
838
+ try:
839
+ p.nice(init)
840
+ except psutil.AccessDenied:
841
+ pass
842
+
843
+ p = psutil.Process()
844
+ self.assertRaises(TypeError, p.nice, "str")
845
+ init = p.nice()
846
+ self.addCleanup(cleanup, init)
847
+
848
+ if WINDOWS:
849
+ highest_prio = None
850
+ for prio in [
851
+ psutil.IDLE_PRIORITY_CLASS,
852
+ psutil.BELOW_NORMAL_PRIORITY_CLASS,
853
+ psutil.NORMAL_PRIORITY_CLASS,
854
+ psutil.ABOVE_NORMAL_PRIORITY_CLASS,
855
+ psutil.HIGH_PRIORITY_CLASS,
856
+ psutil.REALTIME_PRIORITY_CLASS,
857
+ ]:
858
+ with self.subTest(prio=prio):
859
+ try:
860
+ p.nice(prio)
861
+ except psutil.AccessDenied:
862
+ pass
863
+ else:
864
+ new_prio = p.nice()
865
+ # The OS may limit our maximum priority,
866
+ # even if the function succeeds. For higher
867
+ # priorities, we match either the expected
868
+ # value or the highest so far.
869
+ if prio in (
870
+ psutil.ABOVE_NORMAL_PRIORITY_CLASS,
871
+ psutil.HIGH_PRIORITY_CLASS,
872
+ psutil.REALTIME_PRIORITY_CLASS,
873
+ ):
874
+ if new_prio == prio or highest_prio is None:
875
+ highest_prio = prio
876
+ self.assertEqual(new_prio, highest_prio)
877
+ else:
878
+ self.assertEqual(new_prio, prio)
879
+ else:
880
+ try:
881
+ if hasattr(os, "getpriority"):
882
+ self.assertEqual(
883
+ os.getpriority(os.PRIO_PROCESS, os.getpid()), p.nice()
884
+ )
885
+ p.nice(1)
886
+ self.assertEqual(p.nice(), 1)
887
+ if hasattr(os, "getpriority"):
888
+ self.assertEqual(
889
+ os.getpriority(os.PRIO_PROCESS, os.getpid()), p.nice()
890
+ )
891
+ # XXX - going back to previous nice value raises
892
+ # AccessDenied on MACOS
893
+ if not MACOS:
894
+ p.nice(0)
895
+ self.assertEqual(p.nice(), 0)
896
+ except psutil.AccessDenied:
897
+ pass
898
+
899
+ def test_status(self):
900
+ p = psutil.Process()
901
+ self.assertEqual(p.status(), psutil.STATUS_RUNNING)
902
+
903
+ def test_username(self):
904
+ p = self.spawn_psproc()
905
+ username = p.username()
906
+ if WINDOWS:
907
+ domain, username = username.split('\\')
908
+ getpass_user = getpass.getuser()
909
+ if getpass_user.endswith('$'):
910
+ # When running as a service account (most likely to be
911
+ # NetworkService), these user name calculations don't produce
912
+ # the same result, causing the test to fail.
913
+ raise unittest.SkipTest('running as service account')
914
+ self.assertEqual(username, getpass_user)
915
+ if 'USERDOMAIN' in os.environ:
916
+ self.assertEqual(domain, os.environ['USERDOMAIN'])
917
+ else:
918
+ self.assertEqual(username, getpass.getuser())
919
+
920
+ def test_cwd(self):
921
+ p = self.spawn_psproc()
922
+ self.assertEqual(p.cwd(), os.getcwd())
923
+
924
+ def test_cwd_2(self):
925
+ cmd = [
926
+ PYTHON_EXE,
927
+ "-c",
928
+ "import os, time; os.chdir('..'); time.sleep(60)",
929
+ ]
930
+ p = self.spawn_psproc(cmd)
931
+ call_until(p.cwd, "ret == os.path.dirname(os.getcwd())")
932
+
933
+ @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
934
+ def test_cpu_affinity(self):
935
+ p = psutil.Process()
936
+ initial = p.cpu_affinity()
937
+ assert initial, initial
938
+ self.addCleanup(p.cpu_affinity, initial)
939
+
940
+ if hasattr(os, "sched_getaffinity"):
941
+ self.assertEqual(initial, list(os.sched_getaffinity(p.pid)))
942
+ self.assertEqual(len(initial), len(set(initial)))
943
+
944
+ all_cpus = list(range(len(psutil.cpu_percent(percpu=True))))
945
+ for n in all_cpus:
946
+ p.cpu_affinity([n])
947
+ self.assertEqual(p.cpu_affinity(), [n])
948
+ if hasattr(os, "sched_getaffinity"):
949
+ self.assertEqual(
950
+ p.cpu_affinity(), list(os.sched_getaffinity(p.pid))
951
+ )
952
+ # also test num_cpu()
953
+ if hasattr(p, "num_cpu"):
954
+ self.assertEqual(p.cpu_affinity()[0], p.num_cpu())
955
+
956
+ # [] is an alias for "all eligible CPUs"; on Linux this may
957
+ # not be equal to all available CPUs, see:
958
+ # https://github.com/giampaolo/psutil/issues/956
959
+ p.cpu_affinity([])
960
+ if LINUX:
961
+ self.assertEqual(p.cpu_affinity(), p._proc._get_eligible_cpus())
962
+ else:
963
+ self.assertEqual(p.cpu_affinity(), all_cpus)
964
+ if hasattr(os, "sched_getaffinity"):
965
+ self.assertEqual(
966
+ p.cpu_affinity(), list(os.sched_getaffinity(p.pid))
967
+ )
968
+ #
969
+ self.assertRaises(TypeError, p.cpu_affinity, 1)
970
+ p.cpu_affinity(initial)
971
+ # it should work with all iterables, not only lists
972
+ p.cpu_affinity(set(all_cpus))
973
+ p.cpu_affinity(tuple(all_cpus))
974
+
975
+ @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
976
+ def test_cpu_affinity_errs(self):
977
+ p = self.spawn_psproc()
978
+ invalid_cpu = [len(psutil.cpu_times(percpu=True)) + 10]
979
+ self.assertRaises(ValueError, p.cpu_affinity, invalid_cpu)
980
+ self.assertRaises(ValueError, p.cpu_affinity, range(10000, 11000))
981
+ self.assertRaises(TypeError, p.cpu_affinity, [0, "1"])
982
+ self.assertRaises(ValueError, p.cpu_affinity, [0, -1])
983
+
984
+ @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
985
+ def test_cpu_affinity_all_combinations(self):
986
+ p = psutil.Process()
987
+ initial = p.cpu_affinity()
988
+ assert initial, initial
989
+ self.addCleanup(p.cpu_affinity, initial)
990
+
991
+ # All possible CPU set combinations.
992
+ if len(initial) > 12:
993
+ initial = initial[:12] # ...otherwise it will take forever
994
+ combos = []
995
+ for i in range(len(initial) + 1):
996
+ for subset in itertools.combinations(initial, i):
997
+ if subset:
998
+ combos.append(list(subset))
999
+
1000
+ for combo in combos:
1001
+ p.cpu_affinity(combo)
1002
+ self.assertEqual(sorted(p.cpu_affinity()), sorted(combo))
1003
+
1004
+ # TODO: #595
1005
+ @unittest.skipIf(BSD, "broken on BSD")
1006
+ # can't find any process file on Appveyor
1007
+ @unittest.skipIf(APPVEYOR, "unreliable on APPVEYOR")
1008
+ def test_open_files(self):
1009
+ p = psutil.Process()
1010
+ testfn = self.get_testfn()
1011
+ files = p.open_files()
1012
+ self.assertNotIn(testfn, files)
1013
+ with open(testfn, 'wb') as f:
1014
+ f.write(b'x' * 1024)
1015
+ f.flush()
1016
+ # give the kernel some time to see the new file
1017
+ files = call_until(p.open_files, "len(ret) != %i" % len(files))
1018
+ filenames = [os.path.normcase(x.path) for x in files]
1019
+ self.assertIn(os.path.normcase(testfn), filenames)
1020
+ if LINUX:
1021
+ for file in files:
1022
+ if file.path == testfn:
1023
+ self.assertEqual(file.position, 1024)
1024
+ for file in files:
1025
+ assert os.path.isfile(file.path), file
1026
+
1027
+ # another process
1028
+ cmdline = "import time; f = open(r'%s', 'r'); time.sleep(60);" % testfn
1029
+ p = self.spawn_psproc([PYTHON_EXE, "-c", cmdline])
1030
+
1031
+ for x in range(100):
1032
+ filenames = [os.path.normcase(x.path) for x in p.open_files()]
1033
+ if testfn in filenames:
1034
+ break
1035
+ time.sleep(0.01)
1036
+ else:
1037
+ self.assertIn(os.path.normcase(testfn), filenames)
1038
+ for file in filenames:
1039
+ assert os.path.isfile(file), file
1040
+
1041
+ # TODO: #595
1042
+ @unittest.skipIf(BSD, "broken on BSD")
1043
+ # can't find any process file on Appveyor
1044
+ @unittest.skipIf(APPVEYOR, "unreliable on APPVEYOR")
1045
+ def test_open_files_2(self):
1046
+ # test fd and path fields
1047
+ p = psutil.Process()
1048
+ normcase = os.path.normcase
1049
+ testfn = self.get_testfn()
1050
+ with open(testfn, 'w') as fileobj:
1051
+ for file in p.open_files():
1052
+ if (
1053
+ normcase(file.path) == normcase(fileobj.name)
1054
+ or file.fd == fileobj.fileno()
1055
+ ):
1056
+ break
1057
+ else:
1058
+ raise self.fail(
1059
+ "no file found; files=%s" % (repr(p.open_files()))
1060
+ )
1061
+ self.assertEqual(normcase(file.path), normcase(fileobj.name))
1062
+ if WINDOWS:
1063
+ self.assertEqual(file.fd, -1)
1064
+ else:
1065
+ self.assertEqual(file.fd, fileobj.fileno())
1066
+ # test positions
1067
+ ntuple = p.open_files()[0]
1068
+ self.assertEqual(ntuple[0], ntuple.path)
1069
+ self.assertEqual(ntuple[1], ntuple.fd)
1070
+ # test file is gone
1071
+ self.assertNotIn(fileobj.name, p.open_files())
1072
+
1073
+ @unittest.skipIf(not POSIX, 'POSIX only')
1074
+ def test_num_fds(self):
1075
+ p = psutil.Process()
1076
+ testfn = self.get_testfn()
1077
+ start = p.num_fds()
1078
+ file = open(testfn, 'w')
1079
+ self.addCleanup(file.close)
1080
+ self.assertEqual(p.num_fds(), start + 1)
1081
+ sock = socket.socket()
1082
+ self.addCleanup(sock.close)
1083
+ self.assertEqual(p.num_fds(), start + 2)
1084
+ file.close()
1085
+ sock.close()
1086
+ self.assertEqual(p.num_fds(), start)
1087
+
1088
+ @skip_on_not_implemented(only_if=LINUX)
1089
+ @unittest.skipIf(OPENBSD or NETBSD, "not reliable on OPENBSD & NETBSD")
1090
+ def test_num_ctx_switches(self):
1091
+ p = psutil.Process()
1092
+ before = sum(p.num_ctx_switches())
1093
+ for _ in range(2):
1094
+ time.sleep(0.05) # this shall ensure a context switch happens
1095
+ after = sum(p.num_ctx_switches())
1096
+ if after > before:
1097
+ return
1098
+ raise self.fail("num ctx switches still the same after 2 iterations")
1099
+
1100
+ def test_ppid(self):
1101
+ p = psutil.Process()
1102
+ if hasattr(os, 'getppid'):
1103
+ self.assertEqual(p.ppid(), os.getppid())
1104
+ p = self.spawn_psproc()
1105
+ self.assertEqual(p.ppid(), os.getpid())
1106
+
1107
+ def test_parent(self):
1108
+ p = self.spawn_psproc()
1109
+ self.assertEqual(p.parent().pid, os.getpid())
1110
+
1111
+ lowest_pid = psutil.pids()[0]
1112
+ self.assertIsNone(psutil.Process(lowest_pid).parent())
1113
+
1114
+ def test_parent_multi(self):
1115
+ parent = psutil.Process()
1116
+ child, grandchild = self.spawn_children_pair()
1117
+ self.assertEqual(grandchild.parent(), child)
1118
+ self.assertEqual(child.parent(), parent)
1119
+
1120
+ @retry_on_failure()
1121
+ def test_parents(self):
1122
+ parent = psutil.Process()
1123
+ assert parent.parents()
1124
+ child, grandchild = self.spawn_children_pair()
1125
+ self.assertEqual(child.parents()[0], parent)
1126
+ self.assertEqual(grandchild.parents()[0], child)
1127
+ self.assertEqual(grandchild.parents()[1], parent)
1128
+
1129
+ def test_children(self):
1130
+ parent = psutil.Process()
1131
+ self.assertEqual(parent.children(), [])
1132
+ self.assertEqual(parent.children(recursive=True), [])
1133
+ # On Windows we set the flag to 0 in order to cancel out the
1134
+ # CREATE_NO_WINDOW flag (enabled by default) which creates
1135
+ # an extra "conhost.exe" child.
1136
+ child = self.spawn_psproc(creationflags=0)
1137
+ children1 = parent.children()
1138
+ children2 = parent.children(recursive=True)
1139
+ for children in (children1, children2):
1140
+ self.assertEqual(len(children), 1)
1141
+ self.assertEqual(children[0].pid, child.pid)
1142
+ self.assertEqual(children[0].ppid(), parent.pid)
1143
+
1144
+ def test_children_recursive(self):
1145
+ # Test children() against two sub processes, p1 and p2, where
1146
+ # p1 (our child) spawned p2 (our grandchild).
1147
+ parent = psutil.Process()
1148
+ child, grandchild = self.spawn_children_pair()
1149
+ self.assertEqual(parent.children(), [child])
1150
+ self.assertEqual(parent.children(recursive=True), [child, grandchild])
1151
+ # If the intermediate process is gone there's no way for
1152
+ # children() to recursively find it.
1153
+ child.terminate()
1154
+ child.wait()
1155
+ self.assertEqual(parent.children(recursive=True), [])
1156
+
1157
+ def test_children_duplicates(self):
1158
+ # find the process which has the highest number of children
1159
+ table = collections.defaultdict(int)
1160
+ for p in psutil.process_iter():
1161
+ try:
1162
+ table[p.ppid()] += 1
1163
+ except psutil.Error:
1164
+ pass
1165
+ # this is the one, now let's make sure there are no duplicates
1166
+ pid = sorted(table.items(), key=lambda x: x[1])[-1][0]
1167
+ if LINUX and pid == 0:
1168
+ raise self.skipTest("PID 0")
1169
+ p = psutil.Process(pid)
1170
+ try:
1171
+ c = p.children(recursive=True)
1172
+ except psutil.AccessDenied: # windows
1173
+ pass
1174
+ else:
1175
+ self.assertEqual(len(c), len(set(c)))
1176
+
1177
+ def test_parents_and_children(self):
1178
+ parent = psutil.Process()
1179
+ child, grandchild = self.spawn_children_pair()
1180
+ # forward
1181
+ children = parent.children(recursive=True)
1182
+ self.assertEqual(len(children), 2)
1183
+ self.assertEqual(children[0], child)
1184
+ self.assertEqual(children[1], grandchild)
1185
+ # backward
1186
+ parents = grandchild.parents()
1187
+ self.assertEqual(parents[0], child)
1188
+ self.assertEqual(parents[1], parent)
1189
+
1190
+ def test_suspend_resume(self):
1191
+ p = self.spawn_psproc()
1192
+ p.suspend()
1193
+ for _ in range(100):
1194
+ if p.status() == psutil.STATUS_STOPPED:
1195
+ break
1196
+ time.sleep(0.01)
1197
+ p.resume()
1198
+ self.assertNotEqual(p.status(), psutil.STATUS_STOPPED)
1199
+
1200
+ def test_invalid_pid(self):
1201
+ self.assertRaises(TypeError, psutil.Process, "1")
1202
+ self.assertRaises(ValueError, psutil.Process, -1)
1203
+
1204
+ def test_as_dict(self):
1205
+ p = psutil.Process()
1206
+ d = p.as_dict(attrs=['exe', 'name'])
1207
+ self.assertEqual(sorted(d.keys()), ['exe', 'name'])
1208
+
1209
+ p = psutil.Process(min(psutil.pids()))
1210
+ d = p.as_dict(attrs=['connections'], ad_value='foo')
1211
+ if not isinstance(d['connections'], list):
1212
+ self.assertEqual(d['connections'], 'foo')
1213
+
1214
+ # Test ad_value is set on AccessDenied.
1215
+ with mock.patch(
1216
+ 'psutil.Process.nice', create=True, side_effect=psutil.AccessDenied
1217
+ ):
1218
+ self.assertEqual(
1219
+ p.as_dict(attrs=["nice"], ad_value=1), {"nice": 1}
1220
+ )
1221
+
1222
+ # Test that NoSuchProcess bubbles up.
1223
+ with mock.patch(
1224
+ 'psutil.Process.nice',
1225
+ create=True,
1226
+ side_effect=psutil.NoSuchProcess(p.pid, "name"),
1227
+ ):
1228
+ self.assertRaises(psutil.NoSuchProcess, p.as_dict, attrs=["nice"])
1229
+
1230
+ # Test that ZombieProcess is swallowed.
1231
+ with mock.patch(
1232
+ 'psutil.Process.nice',
1233
+ create=True,
1234
+ side_effect=psutil.ZombieProcess(p.pid, "name"),
1235
+ ):
1236
+ self.assertEqual(
1237
+ p.as_dict(attrs=["nice"], ad_value="foo"), {"nice": "foo"}
1238
+ )
1239
+
1240
+ # By default APIs raising NotImplementedError are
1241
+ # supposed to be skipped.
1242
+ with mock.patch(
1243
+ 'psutil.Process.nice', create=True, side_effect=NotImplementedError
1244
+ ):
1245
+ d = p.as_dict()
1246
+ self.assertNotIn('nice', list(d.keys()))
1247
+ # ...unless the user explicitly asked for some attr.
1248
+ with self.assertRaises(NotImplementedError):
1249
+ p.as_dict(attrs=["nice"])
1250
+
1251
+ # errors
1252
+ with self.assertRaises(TypeError):
1253
+ p.as_dict('name')
1254
+ with self.assertRaises(ValueError):
1255
+ p.as_dict(['foo'])
1256
+ with self.assertRaises(ValueError):
1257
+ p.as_dict(['foo', 'bar'])
1258
+
1259
+ def test_oneshot(self):
1260
+ p = psutil.Process()
1261
+ with mock.patch("psutil._psplatform.Process.cpu_times") as m:
1262
+ with p.oneshot():
1263
+ p.cpu_times()
1264
+ p.cpu_times()
1265
+ self.assertEqual(m.call_count, 1)
1266
+
1267
+ with mock.patch("psutil._psplatform.Process.cpu_times") as m:
1268
+ p.cpu_times()
1269
+ p.cpu_times()
1270
+ self.assertEqual(m.call_count, 2)
1271
+
1272
+ def test_oneshot_twice(self):
1273
+ # Test the case where the ctx manager is __enter__ed twice.
1274
+ # The second __enter__ is supposed to resut in a NOOP.
1275
+ p = psutil.Process()
1276
+ with mock.patch("psutil._psplatform.Process.cpu_times") as m1:
1277
+ with mock.patch("psutil._psplatform.Process.oneshot_enter") as m2:
1278
+ with p.oneshot():
1279
+ p.cpu_times()
1280
+ p.cpu_times()
1281
+ with p.oneshot():
1282
+ p.cpu_times()
1283
+ p.cpu_times()
1284
+ self.assertEqual(m1.call_count, 1)
1285
+ self.assertEqual(m2.call_count, 1)
1286
+
1287
+ with mock.patch("psutil._psplatform.Process.cpu_times") as m:
1288
+ p.cpu_times()
1289
+ p.cpu_times()
1290
+ self.assertEqual(m.call_count, 2)
1291
+
1292
+ def test_oneshot_cache(self):
1293
+ # Make sure oneshot() cache is nonglobal. Instead it's
1294
+ # supposed to be bound to the Process instance, see:
1295
+ # https://github.com/giampaolo/psutil/issues/1373
1296
+ p1, p2 = self.spawn_children_pair()
1297
+ p1_ppid = p1.ppid()
1298
+ p2_ppid = p2.ppid()
1299
+ self.assertNotEqual(p1_ppid, p2_ppid)
1300
+ with p1.oneshot():
1301
+ self.assertEqual(p1.ppid(), p1_ppid)
1302
+ self.assertEqual(p2.ppid(), p2_ppid)
1303
+ with p2.oneshot():
1304
+ self.assertEqual(p1.ppid(), p1_ppid)
1305
+ self.assertEqual(p2.ppid(), p2_ppid)
1306
+
1307
+ def test_halfway_terminated_process(self):
1308
+ # Test that NoSuchProcess exception gets raised in case the
1309
+ # process dies after we create the Process object.
1310
+ # Example:
1311
+ # >>> proc = Process(1234)
1312
+ # >>> time.sleep(2) # time-consuming task, process dies in meantime
1313
+ # >>> proc.name()
1314
+ # Refers to Issue #15
1315
+ def assert_raises_nsp(fun, fun_name):
1316
+ try:
1317
+ ret = fun()
1318
+ except psutil.ZombieProcess: # differentiate from NSP
1319
+ raise
1320
+ except psutil.NoSuchProcess:
1321
+ pass
1322
+ except psutil.AccessDenied:
1323
+ if OPENBSD and fun_name in ('threads', 'num_threads'):
1324
+ return
1325
+ raise
1326
+ else:
1327
+ # NtQuerySystemInformation succeeds even if process is gone.
1328
+ if WINDOWS and fun_name in ('exe', 'name'):
1329
+ return
1330
+ raise self.fail(
1331
+ "%r didn't raise NSP and returned %r instead" % (fun, ret)
1332
+ )
1333
+
1334
+ p = self.spawn_psproc()
1335
+ p.terminate()
1336
+ p.wait()
1337
+ if WINDOWS: # XXX
1338
+ call_until(psutil.pids, "%s not in ret" % p.pid)
1339
+ self.assertProcessGone(p)
1340
+
1341
+ ns = process_namespace(p)
1342
+ for fun, name in ns.iter(ns.all):
1343
+ assert_raises_nsp(fun, name)
1344
+
1345
+ @unittest.skipIf(not POSIX, 'POSIX only')
1346
+ def test_zombie_process(self):
1347
+ parent, zombie = self.spawn_zombie()
1348
+ self.assertProcessZombie(zombie)
1349
+
1350
+ @unittest.skipIf(not POSIX, 'POSIX only')
1351
+ def test_zombie_process_is_running_w_exc(self):
1352
+ # Emulate a case where internally is_running() raises
1353
+ # ZombieProcess.
1354
+ p = psutil.Process()
1355
+ with mock.patch(
1356
+ "psutil.Process", side_effect=psutil.ZombieProcess(0)
1357
+ ) as m:
1358
+ assert p.is_running()
1359
+ assert m.called
1360
+
1361
+ @unittest.skipIf(not POSIX, 'POSIX only')
1362
+ def test_zombie_process_status_w_exc(self):
1363
+ # Emulate a case where internally status() raises
1364
+ # ZombieProcess.
1365
+ p = psutil.Process()
1366
+ with mock.patch(
1367
+ "psutil._psplatform.Process.status",
1368
+ side_effect=psutil.ZombieProcess(0),
1369
+ ) as m:
1370
+ self.assertEqual(p.status(), psutil.STATUS_ZOMBIE)
1371
+ assert m.called
1372
+
1373
+ def test_reused_pid(self):
1374
+ # Emulate a case where PID has been reused by another process.
1375
+ subp = self.spawn_testproc()
1376
+ p = psutil.Process(subp.pid)
1377
+ p._ident = (p.pid, p.create_time() + 100)
1378
+ assert not p.is_running()
1379
+ assert p != psutil.Process(subp.pid)
1380
+ msg = "process no longer exists and its PID has been reused"
1381
+ ns = process_namespace(p)
1382
+ for fun, name in ns.iter(ns.setters + ns.killers, clear_cache=False):
1383
+ with self.subTest(name=name):
1384
+ self.assertRaisesRegex(psutil.NoSuchProcess, msg, fun)
1385
+ self.assertRaisesRegex(psutil.NoSuchProcess, msg, p.ppid)
1386
+ self.assertRaisesRegex(psutil.NoSuchProcess, msg, p.parent)
1387
+ self.assertRaisesRegex(psutil.NoSuchProcess, msg, p.parents)
1388
+ self.assertRaisesRegex(psutil.NoSuchProcess, msg, p.children)
1389
+
1390
+ def test_pid_0(self):
1391
+ # Process(0) is supposed to work on all platforms except Linux
1392
+ if 0 not in psutil.pids():
1393
+ self.assertRaises(psutil.NoSuchProcess, psutil.Process, 0)
1394
+ # These 2 are a contradiction, but "ps" says PID 1's parent
1395
+ # is PID 0.
1396
+ assert not psutil.pid_exists(0)
1397
+ self.assertEqual(psutil.Process(1).ppid(), 0)
1398
+ return
1399
+
1400
+ p = psutil.Process(0)
1401
+ exc = psutil.AccessDenied if WINDOWS else ValueError
1402
+ self.assertRaises(exc, p.wait)
1403
+ self.assertRaises(exc, p.terminate)
1404
+ self.assertRaises(exc, p.suspend)
1405
+ self.assertRaises(exc, p.resume)
1406
+ self.assertRaises(exc, p.kill)
1407
+ self.assertRaises(exc, p.send_signal, signal.SIGTERM)
1408
+
1409
+ # test all methods
1410
+ ns = process_namespace(p)
1411
+ for fun, name in ns.iter(ns.getters + ns.setters):
1412
+ try:
1413
+ ret = fun()
1414
+ except psutil.AccessDenied:
1415
+ pass
1416
+ else:
1417
+ if name in ("uids", "gids"):
1418
+ self.assertEqual(ret.real, 0)
1419
+ elif name == "username":
1420
+ user = 'NT AUTHORITY\\SYSTEM' if WINDOWS else 'root'
1421
+ self.assertEqual(p.username(), user)
1422
+ elif name == "name":
1423
+ assert name, name
1424
+
1425
+ if not OPENBSD:
1426
+ self.assertIn(0, psutil.pids())
1427
+ assert psutil.pid_exists(0)
1428
+
1429
+ @unittest.skipIf(not HAS_ENVIRON, "not supported")
1430
+ def test_environ(self):
1431
+ def clean_dict(d):
1432
+ # Most of these are problematic on Travis.
1433
+ d.pop("PLAT", None)
1434
+ d.pop("HOME", None)
1435
+ if MACOS:
1436
+ d.pop("__CF_USER_TEXT_ENCODING", None)
1437
+ d.pop("VERSIONER_PYTHON_PREFER_32_BIT", None)
1438
+ d.pop("VERSIONER_PYTHON_VERSION", None)
1439
+ return dict([
1440
+ (
1441
+ k.replace("\r", "").replace("\n", ""),
1442
+ v.replace("\r", "").replace("\n", ""),
1443
+ )
1444
+ for k, v in d.items()
1445
+ ])
1446
+
1447
+ self.maxDiff = None
1448
+ p = psutil.Process()
1449
+ d1 = clean_dict(p.environ())
1450
+ d2 = clean_dict(os.environ.copy())
1451
+ if not OSX and GITHUB_ACTIONS:
1452
+ self.assertEqual(d1, d2)
1453
+
1454
+ @unittest.skipIf(not HAS_ENVIRON, "not supported")
1455
+ @unittest.skipIf(not POSIX, "POSIX only")
1456
+ @unittest.skipIf(
1457
+ MACOS_11PLUS,
1458
+ "macOS 11+ can't get another process environment, issue #2084",
1459
+ )
1460
+ def test_weird_environ(self):
1461
+ # environment variables can contain values without an equals sign
1462
+ code = textwrap.dedent("""
1463
+ #include <unistd.h>
1464
+ #include <fcntl.h>
1465
+
1466
+ char * const argv[] = {"cat", 0};
1467
+ char * const envp[] = {"A=1", "X", "C=3", 0};
1468
+
1469
+ int main(void) {
1470
+ // Close stderr on exec so parent can wait for the
1471
+ // execve to finish.
1472
+ if (fcntl(2, F_SETFD, FD_CLOEXEC) != 0)
1473
+ return 0;
1474
+ return execve("/bin/cat", argv, envp);
1475
+ }
1476
+ """)
1477
+ cexe = create_c_exe(self.get_testfn(), c_code=code)
1478
+ sproc = self.spawn_testproc(
1479
+ [cexe], stdin=subprocess.PIPE, stderr=subprocess.PIPE
1480
+ )
1481
+ p = psutil.Process(sproc.pid)
1482
+ wait_for_pid(p.pid)
1483
+ assert p.is_running()
1484
+ # Wait for process to exec or exit.
1485
+ self.assertEqual(sproc.stderr.read(), b"")
1486
+ if MACOS and CI_TESTING:
1487
+ try:
1488
+ env = p.environ()
1489
+ except psutil.AccessDenied:
1490
+ # XXX: fails sometimes with:
1491
+ # PermissionError from 'sysctl(KERN_PROCARGS2) -> EIO'
1492
+ return
1493
+ else:
1494
+ env = p.environ()
1495
+ self.assertEqual(env, {"A": "1", "C": "3"})
1496
+ sproc.communicate()
1497
+ self.assertEqual(sproc.returncode, 0)
1498
+
1499
+
1500
+ # ===================================================================
1501
+ # --- Limited user tests
1502
+ # ===================================================================
1503
+
1504
+
1505
+ if POSIX and os.getuid() == 0:
1506
+
1507
+ class LimitedUserTestCase(TestProcess):
1508
+ """Repeat the previous tests by using a limited user.
1509
+ Executed only on UNIX and only if the user who run the test script
1510
+ is root.
1511
+ """
1512
+
1513
+ # the uid/gid the test suite runs under
1514
+ if hasattr(os, 'getuid'):
1515
+ PROCESS_UID = os.getuid()
1516
+ PROCESS_GID = os.getgid()
1517
+
1518
+ def __init__(self, *args, **kwargs):
1519
+ super().__init__(*args, **kwargs)
1520
+ # re-define all existent test methods in order to
1521
+ # ignore AccessDenied exceptions
1522
+ for attr in [x for x in dir(self) if x.startswith('test')]:
1523
+ meth = getattr(self, attr)
1524
+
1525
+ def test_(self):
1526
+ try:
1527
+ meth() # noqa
1528
+ except psutil.AccessDenied:
1529
+ pass
1530
+
1531
+ setattr(self, attr, types.MethodType(test_, self))
1532
+
1533
+ def setUp(self):
1534
+ super().setUp()
1535
+ os.setegid(1000)
1536
+ os.seteuid(1000)
1537
+
1538
+ def tearDown(self):
1539
+ os.setegid(self.PROCESS_UID)
1540
+ os.seteuid(self.PROCESS_GID)
1541
+ super().tearDown()
1542
+
1543
+ def test_nice(self):
1544
+ try:
1545
+ psutil.Process().nice(-1)
1546
+ except psutil.AccessDenied:
1547
+ pass
1548
+ else:
1549
+ raise self.fail("exception not raised")
1550
+
1551
+ @unittest.skipIf(1, "causes problem as root")
1552
+ def test_zombie_process(self):
1553
+ pass
1554
+
1555
+
1556
+ # ===================================================================
1557
+ # --- psutil.Popen tests
1558
+ # ===================================================================
1559
+
1560
+
1561
+ class TestPopen(PsutilTestCase):
1562
+ """Tests for psutil.Popen class."""
1563
+
1564
+ @classmethod
1565
+ def tearDownClass(cls):
1566
+ reap_children()
1567
+
1568
+ def test_misc(self):
1569
+ # XXX this test causes a ResourceWarning on Python 3 because
1570
+ # psutil.__subproc instance doesn't get properly freed.
1571
+ # Not sure what to do though.
1572
+ cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
1573
+ with psutil.Popen(
1574
+ cmd,
1575
+ stdout=subprocess.PIPE,
1576
+ stderr=subprocess.PIPE,
1577
+ env=PYTHON_EXE_ENV,
1578
+ ) as proc:
1579
+ proc.name()
1580
+ proc.cpu_times()
1581
+ proc.stdin # noqa
1582
+ self.assertTrue(dir(proc))
1583
+ self.assertRaises(AttributeError, getattr, proc, 'foo')
1584
+ proc.terminate()
1585
+ if POSIX:
1586
+ self.assertEqual(proc.wait(5), -signal.SIGTERM)
1587
+ else:
1588
+ self.assertEqual(proc.wait(5), signal.SIGTERM)
1589
+
1590
+ def test_ctx_manager(self):
1591
+ with psutil.Popen(
1592
+ [PYTHON_EXE, "-V"],
1593
+ stdout=subprocess.PIPE,
1594
+ stderr=subprocess.PIPE,
1595
+ stdin=subprocess.PIPE,
1596
+ env=PYTHON_EXE_ENV,
1597
+ ) as proc:
1598
+ proc.communicate()
1599
+ assert proc.stdout.closed
1600
+ assert proc.stderr.closed
1601
+ assert proc.stdin.closed
1602
+ self.assertEqual(proc.returncode, 0)
1603
+
1604
+ def test_kill_terminate(self):
1605
+ # subprocess.Popen()'s terminate(), kill() and send_signal() do
1606
+ # not raise exception after the process is gone. psutil.Popen
1607
+ # diverges from that.
1608
+ cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
1609
+ with psutil.Popen(
1610
+ cmd,
1611
+ stdout=subprocess.PIPE,
1612
+ stderr=subprocess.PIPE,
1613
+ env=PYTHON_EXE_ENV,
1614
+ ) as proc:
1615
+ proc.terminate()
1616
+ proc.wait()
1617
+ self.assertRaises(psutil.NoSuchProcess, proc.terminate)
1618
+ self.assertRaises(psutil.NoSuchProcess, proc.kill)
1619
+ self.assertRaises(
1620
+ psutil.NoSuchProcess, proc.send_signal, signal.SIGTERM
1621
+ )
1622
+ if WINDOWS:
1623
+ self.assertRaises(
1624
+ psutil.NoSuchProcess, proc.send_signal, signal.CTRL_C_EVENT
1625
+ )
1626
+ self.assertRaises(
1627
+ psutil.NoSuchProcess,
1628
+ proc.send_signal,
1629
+ signal.CTRL_BREAK_EVENT,
1630
+ )
1631
+
1632
+
1633
+ if __name__ == '__main__':
1634
+ from psutil.tests.runner import run_from_name
1635
+
1636
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_process_all.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Iterate over all process PIDs and for each one of them invoke and
8
+ test all psutil.Process() methods.
9
+ """
10
+
11
+ import enum
12
+ import errno
13
+ import multiprocessing
14
+ import os
15
+ import stat
16
+ import time
17
+ import traceback
18
+
19
+ import psutil
20
+ from psutil import AIX
21
+ from psutil import BSD
22
+ from psutil import FREEBSD
23
+ from psutil import LINUX
24
+ from psutil import MACOS
25
+ from psutil import NETBSD
26
+ from psutil import OPENBSD
27
+ from psutil import OSX
28
+ from psutil import POSIX
29
+ from psutil import WINDOWS
30
+ from psutil._compat import PY3
31
+ from psutil._compat import long
32
+ from psutil._compat import unicode
33
+ from psutil.tests import CI_TESTING
34
+ from psutil.tests import VALID_PROC_STATUSES
35
+ from psutil.tests import PsutilTestCase
36
+ from psutil.tests import check_connection_ntuple
37
+ from psutil.tests import create_sockets
38
+ from psutil.tests import is_namedtuple
39
+ from psutil.tests import is_win_secure_system_proc
40
+ from psutil.tests import process_namespace
41
+ from psutil.tests import serialrun
42
+
43
+
44
+ # Cuts the time in half, but (e.g.) on macOS the process pool stays
45
+ # alive after join() (multiprocessing bug?), messing up other tests.
46
+ USE_PROC_POOL = LINUX and not CI_TESTING
47
+
48
+
49
+ def proc_info(pid):
50
+ tcase = PsutilTestCase()
51
+
52
+ def check_exception(exc, proc, name, ppid):
53
+ tcase.assertEqual(exc.pid, pid)
54
+ if exc.name is not None:
55
+ tcase.assertEqual(exc.name, name)
56
+ if isinstance(exc, psutil.ZombieProcess):
57
+ tcase.assertProcessZombie(proc)
58
+ if exc.ppid is not None:
59
+ tcase.assertGreaterEqual(exc.ppid, 0)
60
+ tcase.assertEqual(exc.ppid, ppid)
61
+ elif isinstance(exc, psutil.NoSuchProcess):
62
+ tcase.assertProcessGone(proc)
63
+ str(exc)
64
+ repr(exc)
65
+
66
+ def do_wait():
67
+ if pid != 0:
68
+ try:
69
+ proc.wait(0)
70
+ except psutil.Error as exc:
71
+ check_exception(exc, proc, name, ppid)
72
+
73
+ try:
74
+ proc = psutil.Process(pid)
75
+ except psutil.NoSuchProcess:
76
+ tcase.assertPidGone(pid)
77
+ return {}
78
+ try:
79
+ d = proc.as_dict(['ppid', 'name'])
80
+ except psutil.NoSuchProcess:
81
+ tcase.assertProcessGone(proc)
82
+ else:
83
+ name, ppid = d['name'], d['ppid']
84
+ info = {'pid': proc.pid}
85
+ ns = process_namespace(proc)
86
+ # We don't use oneshot() because in order not to fool
87
+ # check_exception() in case of NSP.
88
+ for fun, fun_name in ns.iter(ns.getters, clear_cache=False):
89
+ try:
90
+ info[fun_name] = fun()
91
+ except psutil.Error as exc:
92
+ check_exception(exc, proc, name, ppid)
93
+ continue
94
+ do_wait()
95
+ return info
96
+
97
+
98
+ @serialrun
99
+ class TestFetchAllProcesses(PsutilTestCase):
100
+ """Test which iterates over all running processes and performs
101
+ some sanity checks against Process API's returned values.
102
+ Uses a process pool to get info about all processes.
103
+ """
104
+
105
+ def setUp(self):
106
+ # Using a pool in a CI env may result in deadlock, see:
107
+ # https://github.com/giampaolo/psutil/issues/2104
108
+ if USE_PROC_POOL:
109
+ self.pool = multiprocessing.Pool()
110
+
111
+ def tearDown(self):
112
+ if USE_PROC_POOL:
113
+ self.pool.terminate()
114
+ self.pool.join()
115
+
116
+ def iter_proc_info(self):
117
+ # Fixes "can't pickle <function proc_info>: it's not the
118
+ # same object as test_process_all.proc_info".
119
+ from psutil.tests.test_process_all import proc_info
120
+
121
+ if USE_PROC_POOL:
122
+ return self.pool.imap_unordered(proc_info, psutil.pids())
123
+ else:
124
+ ls = []
125
+ for pid in psutil.pids():
126
+ ls.append(proc_info(pid))
127
+ return ls
128
+
129
+ def test_all(self):
130
+ failures = []
131
+ for info in self.iter_proc_info():
132
+ for name, value in info.items():
133
+ meth = getattr(self, name)
134
+ try:
135
+ meth(value, info)
136
+ except Exception: # noqa: BLE001
137
+ s = '\n' + '=' * 70 + '\n'
138
+ s += "FAIL: name=test_%s, pid=%s, ret=%s\ninfo=%s\n" % (
139
+ name,
140
+ info['pid'],
141
+ repr(value),
142
+ info,
143
+ )
144
+ s += '-' * 70
145
+ s += "\n%s" % traceback.format_exc()
146
+ s = "\n".join((" " * 4) + i for i in s.splitlines()) + "\n"
147
+ failures.append(s)
148
+ else:
149
+ if value not in (0, 0.0, [], None, '', {}):
150
+ assert value, value
151
+ if failures:
152
+ raise self.fail(''.join(failures))
153
+
154
+ def cmdline(self, ret, info):
155
+ self.assertIsInstance(ret, list)
156
+ for part in ret:
157
+ self.assertIsInstance(part, str)
158
+
159
+ def exe(self, ret, info):
160
+ self.assertIsInstance(ret, (str, unicode))
161
+ self.assertEqual(ret.strip(), ret)
162
+ if ret:
163
+ if WINDOWS and not ret.endswith('.exe'):
164
+ return # May be "Registry", "MemCompression", ...
165
+ assert os.path.isabs(ret), ret
166
+ # Note: os.stat() may return False even if the file is there
167
+ # hence we skip the test, see:
168
+ # http://stackoverflow.com/questions/3112546/os-path-exists-lies
169
+ if POSIX and os.path.isfile(ret):
170
+ if hasattr(os, 'access') and hasattr(os, "X_OK"):
171
+ # XXX: may fail on MACOS
172
+ try:
173
+ assert os.access(ret, os.X_OK)
174
+ except AssertionError:
175
+ if os.path.exists(ret) and not CI_TESTING:
176
+ raise
177
+
178
+ def pid(self, ret, info):
179
+ self.assertIsInstance(ret, int)
180
+ self.assertGreaterEqual(ret, 0)
181
+
182
+ def ppid(self, ret, info):
183
+ self.assertIsInstance(ret, (int, long))
184
+ self.assertGreaterEqual(ret, 0)
185
+ proc_info(ret)
186
+
187
+ def name(self, ret, info):
188
+ self.assertIsInstance(ret, (str, unicode))
189
+ if WINDOWS and not ret and is_win_secure_system_proc(info['pid']):
190
+ # https://github.com/giampaolo/psutil/issues/2338
191
+ return
192
+ # on AIX, "<exiting>" processes don't have names
193
+ if not AIX:
194
+ assert ret, repr(ret)
195
+
196
+ def create_time(self, ret, info):
197
+ self.assertIsInstance(ret, float)
198
+ try:
199
+ self.assertGreaterEqual(ret, 0)
200
+ except AssertionError:
201
+ # XXX
202
+ if OPENBSD and info['status'] == psutil.STATUS_ZOMBIE:
203
+ pass
204
+ else:
205
+ raise
206
+ # this can't be taken for granted on all platforms
207
+ # self.assertGreaterEqual(ret, psutil.boot_time())
208
+ # make sure returned value can be pretty printed
209
+ # with strftime
210
+ time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))
211
+
212
+ def uids(self, ret, info):
213
+ assert is_namedtuple(ret)
214
+ for uid in ret:
215
+ self.assertIsInstance(uid, int)
216
+ self.assertGreaterEqual(uid, 0)
217
+
218
+ def gids(self, ret, info):
219
+ assert is_namedtuple(ret)
220
+ # note: testing all gids as above seems not to be reliable for
221
+ # gid == 30 (nodoby); not sure why.
222
+ for gid in ret:
223
+ self.assertIsInstance(gid, int)
224
+ if not MACOS and not NETBSD:
225
+ self.assertGreaterEqual(gid, 0)
226
+
227
+ def username(self, ret, info):
228
+ self.assertIsInstance(ret, str)
229
+ self.assertEqual(ret.strip(), ret)
230
+ assert ret.strip()
231
+
232
+ def status(self, ret, info):
233
+ self.assertIsInstance(ret, str)
234
+ assert ret, ret
235
+ self.assertNotEqual(ret, '?') # XXX
236
+ self.assertIn(ret, VALID_PROC_STATUSES)
237
+
238
+ def io_counters(self, ret, info):
239
+ assert is_namedtuple(ret)
240
+ for field in ret:
241
+ self.assertIsInstance(field, (int, long))
242
+ if field != -1:
243
+ self.assertGreaterEqual(field, 0)
244
+
245
+ def ionice(self, ret, info):
246
+ if LINUX:
247
+ self.assertIsInstance(ret.ioclass, int)
248
+ self.assertIsInstance(ret.value, int)
249
+ self.assertGreaterEqual(ret.ioclass, 0)
250
+ self.assertGreaterEqual(ret.value, 0)
251
+ else: # Windows, Cygwin
252
+ choices = [
253
+ psutil.IOPRIO_VERYLOW,
254
+ psutil.IOPRIO_LOW,
255
+ psutil.IOPRIO_NORMAL,
256
+ psutil.IOPRIO_HIGH,
257
+ ]
258
+ self.assertIsInstance(ret, int)
259
+ self.assertGreaterEqual(ret, 0)
260
+ self.assertIn(ret, choices)
261
+
262
+ def num_threads(self, ret, info):
263
+ self.assertIsInstance(ret, int)
264
+ if WINDOWS and ret == 0 and is_win_secure_system_proc(info['pid']):
265
+ # https://github.com/giampaolo/psutil/issues/2338
266
+ return
267
+ self.assertGreaterEqual(ret, 1)
268
+
269
+ def threads(self, ret, info):
270
+ self.assertIsInstance(ret, list)
271
+ for t in ret:
272
+ assert is_namedtuple(t)
273
+ self.assertGreaterEqual(t.id, 0)
274
+ self.assertGreaterEqual(t.user_time, 0)
275
+ self.assertGreaterEqual(t.system_time, 0)
276
+ for field in t:
277
+ self.assertIsInstance(field, (int, float))
278
+
279
+ def cpu_times(self, ret, info):
280
+ assert is_namedtuple(ret)
281
+ for n in ret:
282
+ self.assertIsInstance(n, float)
283
+ self.assertGreaterEqual(n, 0)
284
+ # TODO: check ntuple fields
285
+
286
+ def cpu_percent(self, ret, info):
287
+ self.assertIsInstance(ret, float)
288
+ assert 0.0 <= ret <= 100.0, ret
289
+
290
+ def cpu_num(self, ret, info):
291
+ self.assertIsInstance(ret, int)
292
+ if FREEBSD and ret == -1:
293
+ return
294
+ self.assertGreaterEqual(ret, 0)
295
+ if psutil.cpu_count() == 1:
296
+ self.assertEqual(ret, 0)
297
+ self.assertIn(ret, list(range(psutil.cpu_count())))
298
+
299
+ def memory_info(self, ret, info):
300
+ assert is_namedtuple(ret)
301
+ for value in ret:
302
+ self.assertIsInstance(value, (int, long))
303
+ self.assertGreaterEqual(value, 0)
304
+ if WINDOWS:
305
+ self.assertGreaterEqual(ret.peak_wset, ret.wset)
306
+ self.assertGreaterEqual(ret.peak_paged_pool, ret.paged_pool)
307
+ self.assertGreaterEqual(ret.peak_nonpaged_pool, ret.nonpaged_pool)
308
+ self.assertGreaterEqual(ret.peak_pagefile, ret.pagefile)
309
+
310
+ def memory_full_info(self, ret, info):
311
+ assert is_namedtuple(ret)
312
+ total = psutil.virtual_memory().total
313
+ for name in ret._fields:
314
+ value = getattr(ret, name)
315
+ self.assertIsInstance(value, (int, long))
316
+ self.assertGreaterEqual(value, 0, msg=(name, value))
317
+ if LINUX or OSX and name in ('vms', 'data'):
318
+ # On Linux there are processes (e.g. 'goa-daemon') whose
319
+ # VMS is incredibly high for some reason.
320
+ continue
321
+ self.assertLessEqual(value, total, msg=(name, value, total))
322
+
323
+ if LINUX:
324
+ self.assertGreaterEqual(ret.pss, ret.uss)
325
+
326
+ def open_files(self, ret, info):
327
+ self.assertIsInstance(ret, list)
328
+ for f in ret:
329
+ self.assertIsInstance(f.fd, int)
330
+ self.assertIsInstance(f.path, str)
331
+ self.assertEqual(f.path.strip(), f.path)
332
+ if WINDOWS:
333
+ self.assertEqual(f.fd, -1)
334
+ elif LINUX:
335
+ self.assertIsInstance(f.position, int)
336
+ self.assertIsInstance(f.mode, str)
337
+ self.assertIsInstance(f.flags, int)
338
+ self.assertGreaterEqual(f.position, 0)
339
+ self.assertIn(f.mode, ('r', 'w', 'a', 'r+', 'a+'))
340
+ self.assertGreater(f.flags, 0)
341
+ elif BSD and not f.path:
342
+ # XXX see: https://github.com/giampaolo/psutil/issues/595
343
+ continue
344
+ assert os.path.isabs(f.path), f
345
+ try:
346
+ st = os.stat(f.path)
347
+ except FileNotFoundError:
348
+ pass
349
+ else:
350
+ assert stat.S_ISREG(st.st_mode), f
351
+
352
+ def num_fds(self, ret, info):
353
+ self.assertIsInstance(ret, int)
354
+ self.assertGreaterEqual(ret, 0)
355
+
356
+ def connections(self, ret, info):
357
+ with create_sockets():
358
+ self.assertEqual(len(ret), len(set(ret)))
359
+ for conn in ret:
360
+ assert is_namedtuple(conn)
361
+ check_connection_ntuple(conn)
362
+
363
+ def cwd(self, ret, info):
364
+ self.assertIsInstance(ret, (str, unicode))
365
+ self.assertEqual(ret.strip(), ret)
366
+ if ret:
367
+ assert os.path.isabs(ret), ret
368
+ try:
369
+ st = os.stat(ret)
370
+ except OSError as err:
371
+ if WINDOWS and psutil._psplatform.is_permission_err(err):
372
+ pass
373
+ # directory has been removed in mean time
374
+ elif err.errno != errno.ENOENT:
375
+ raise
376
+ else:
377
+ assert stat.S_ISDIR(st.st_mode)
378
+
379
+ def memory_percent(self, ret, info):
380
+ self.assertIsInstance(ret, float)
381
+ assert 0 <= ret <= 100, ret
382
+
383
+ def is_running(self, ret, info):
384
+ self.assertIsInstance(ret, bool)
385
+
386
+ def cpu_affinity(self, ret, info):
387
+ self.assertIsInstance(ret, list)
388
+ self.assertNotEqual(ret, [])
389
+ cpus = list(range(psutil.cpu_count()))
390
+ for n in ret:
391
+ self.assertIsInstance(n, int)
392
+ self.assertIn(n, cpus)
393
+
394
+ def terminal(self, ret, info):
395
+ self.assertIsInstance(ret, (str, type(None)))
396
+ if ret is not None:
397
+ assert os.path.isabs(ret), ret
398
+ assert os.path.exists(ret), ret
399
+
400
+ def memory_maps(self, ret, info):
401
+ for nt in ret:
402
+ self.assertIsInstance(nt.addr, str)
403
+ self.assertIsInstance(nt.perms, str)
404
+ self.assertIsInstance(nt.path, str)
405
+ for fname in nt._fields:
406
+ value = getattr(nt, fname)
407
+ if fname == 'path':
408
+ if not value.startswith(("[", "anon_inode:")):
409
+ assert os.path.isabs(nt.path), nt.path
410
+ # commented as on Linux we might get
411
+ # '/foo/bar (deleted)'
412
+ # assert os.path.exists(nt.path), nt.path
413
+ elif fname == 'addr':
414
+ assert value, repr(value)
415
+ elif fname == 'perms':
416
+ if not WINDOWS:
417
+ assert value, repr(value)
418
+ else:
419
+ self.assertIsInstance(value, (int, long))
420
+ self.assertGreaterEqual(value, 0)
421
+
422
+ def num_handles(self, ret, info):
423
+ self.assertIsInstance(ret, int)
424
+ self.assertGreaterEqual(ret, 0)
425
+
426
+ def nice(self, ret, info):
427
+ self.assertIsInstance(ret, int)
428
+ if POSIX:
429
+ assert -20 <= ret <= 20, ret
430
+ else:
431
+ priorities = [
432
+ getattr(psutil, x)
433
+ for x in dir(psutil)
434
+ if x.endswith('_PRIORITY_CLASS')
435
+ ]
436
+ self.assertIn(ret, priorities)
437
+ if PY3:
438
+ self.assertIsInstance(ret, enum.IntEnum)
439
+ else:
440
+ self.assertIsInstance(ret, int)
441
+
442
+ def num_ctx_switches(self, ret, info):
443
+ assert is_namedtuple(ret)
444
+ for value in ret:
445
+ self.assertIsInstance(value, (int, long))
446
+ self.assertGreaterEqual(value, 0)
447
+
448
+ def rlimit(self, ret, info):
449
+ self.assertIsInstance(ret, tuple)
450
+ self.assertEqual(len(ret), 2)
451
+ self.assertGreaterEqual(ret[0], -1)
452
+ self.assertGreaterEqual(ret[1], -1)
453
+
454
+ def environ(self, ret, info):
455
+ self.assertIsInstance(ret, dict)
456
+ for k, v in ret.items():
457
+ self.assertIsInstance(k, str)
458
+ self.assertIsInstance(v, str)
459
+
460
+
461
+ if __name__ == '__main__':
462
+ from psutil.tests.runner import run_from_name
463
+
464
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_sunos.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Sun OS specific tests."""
8
+
9
+ import os
10
+ import unittest
11
+
12
+ import psutil
13
+ from psutil import SUNOS
14
+ from psutil.tests import PsutilTestCase
15
+ from psutil.tests import sh
16
+
17
+
18
+ @unittest.skipIf(not SUNOS, "SUNOS only")
19
+ class SunOSSpecificTestCase(PsutilTestCase):
20
+ def test_swap_memory(self):
21
+ out = sh('env PATH=/usr/sbin:/sbin:%s swap -l' % os.environ['PATH'])
22
+ lines = out.strip().split('\n')[1:]
23
+ if not lines:
24
+ raise ValueError('no swap device(s) configured')
25
+ total = free = 0
26
+ for line in lines:
27
+ fields = line.split()
28
+ total = int(fields[3]) * 512
29
+ free = int(fields[4]) * 512
30
+ used = total - free
31
+
32
+ psutil_swap = psutil.swap_memory()
33
+ self.assertEqual(psutil_swap.total, total)
34
+ self.assertEqual(psutil_swap.used, used)
35
+ self.assertEqual(psutil_swap.free, free)
36
+
37
+ def test_cpu_count(self):
38
+ out = sh("/usr/sbin/psrinfo")
39
+ self.assertEqual(psutil.cpu_count(), len(out.split('\n')))
40
+
41
+
42
+ if __name__ == '__main__':
43
+ from psutil.tests.runner import run_from_name
44
+
45
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_system.py ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Tests for system APIS."""
8
+
9
+ import contextlib
10
+ import datetime
11
+ import errno
12
+ import os
13
+ import platform
14
+ import pprint
15
+ import shutil
16
+ import signal
17
+ import socket
18
+ import sys
19
+ import time
20
+ import unittest
21
+
22
+ import psutil
23
+ from psutil import AIX
24
+ from psutil import BSD
25
+ from psutil import FREEBSD
26
+ from psutil import LINUX
27
+ from psutil import MACOS
28
+ from psutil import NETBSD
29
+ from psutil import OPENBSD
30
+ from psutil import POSIX
31
+ from psutil import SUNOS
32
+ from psutil import WINDOWS
33
+ from psutil._compat import PY3
34
+ from psutil._compat import FileNotFoundError
35
+ from psutil._compat import long
36
+ from psutil.tests import ASCII_FS
37
+ from psutil.tests import CI_TESTING
38
+ from psutil.tests import DEVNULL
39
+ from psutil.tests import GITHUB_ACTIONS
40
+ from psutil.tests import GLOBAL_TIMEOUT
41
+ from psutil.tests import HAS_BATTERY
42
+ from psutil.tests import HAS_CPU_FREQ
43
+ from psutil.tests import HAS_GETLOADAVG
44
+ from psutil.tests import HAS_NET_IO_COUNTERS
45
+ from psutil.tests import HAS_SENSORS_BATTERY
46
+ from psutil.tests import HAS_SENSORS_FANS
47
+ from psutil.tests import HAS_SENSORS_TEMPERATURES
48
+ from psutil.tests import IS_64BIT
49
+ from psutil.tests import MACOS_12PLUS
50
+ from psutil.tests import PYPY
51
+ from psutil.tests import UNICODE_SUFFIX
52
+ from psutil.tests import PsutilTestCase
53
+ from psutil.tests import check_net_address
54
+ from psutil.tests import enum
55
+ from psutil.tests import mock
56
+ from psutil.tests import retry_on_failure
57
+
58
+
59
+ # ===================================================================
60
+ # --- System-related API tests
61
+ # ===================================================================
62
+
63
+
64
+ class TestProcessAPIs(PsutilTestCase):
65
+ def test_process_iter(self):
66
+ self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
67
+ sproc = self.spawn_testproc()
68
+ self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
69
+ p = psutil.Process(sproc.pid)
70
+ p.kill()
71
+ p.wait()
72
+ self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])
73
+
74
+ # assert there are no duplicates
75
+ ls = [x for x in psutil.process_iter()]
76
+ self.assertEqual(
77
+ sorted(ls, key=lambda x: x.pid),
78
+ sorted(set(ls), key=lambda x: x.pid),
79
+ )
80
+
81
+ with mock.patch(
82
+ 'psutil.Process', side_effect=psutil.NoSuchProcess(os.getpid())
83
+ ):
84
+ self.assertEqual(list(psutil.process_iter()), [])
85
+ with mock.patch(
86
+ 'psutil.Process', side_effect=psutil.AccessDenied(os.getpid())
87
+ ):
88
+ with self.assertRaises(psutil.AccessDenied):
89
+ list(psutil.process_iter())
90
+
91
+ def test_prcess_iter_w_attrs(self):
92
+ for p in psutil.process_iter(attrs=['pid']):
93
+ self.assertEqual(list(p.info.keys()), ['pid'])
94
+ with self.assertRaises(ValueError):
95
+ list(psutil.process_iter(attrs=['foo']))
96
+ with mock.patch(
97
+ "psutil._psplatform.Process.cpu_times",
98
+ side_effect=psutil.AccessDenied(0, ""),
99
+ ) as m:
100
+ for p in psutil.process_iter(attrs=["pid", "cpu_times"]):
101
+ self.assertIsNone(p.info['cpu_times'])
102
+ self.assertGreaterEqual(p.info['pid'], 0)
103
+ assert m.called
104
+ with mock.patch(
105
+ "psutil._psplatform.Process.cpu_times",
106
+ side_effect=psutil.AccessDenied(0, ""),
107
+ ) as m:
108
+ flag = object()
109
+ for p in psutil.process_iter(
110
+ attrs=["pid", "cpu_times"], ad_value=flag
111
+ ):
112
+ self.assertIs(p.info['cpu_times'], flag)
113
+ self.assertGreaterEqual(p.info['pid'], 0)
114
+ assert m.called
115
+
116
+ @unittest.skipIf(
117
+ PYPY and WINDOWS, "spawn_testproc() unreliable on PYPY + WINDOWS"
118
+ )
119
+ def test_wait_procs(self):
120
+ def callback(p):
121
+ pids.append(p.pid)
122
+
123
+ pids = []
124
+ sproc1 = self.spawn_testproc()
125
+ sproc2 = self.spawn_testproc()
126
+ sproc3 = self.spawn_testproc()
127
+ procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)]
128
+ self.assertRaises(ValueError, psutil.wait_procs, procs, timeout=-1)
129
+ self.assertRaises(TypeError, psutil.wait_procs, procs, callback=1)
130
+ t = time.time()
131
+ gone, alive = psutil.wait_procs(procs, timeout=0.01, callback=callback)
132
+
133
+ self.assertLess(time.time() - t, 0.5)
134
+ self.assertEqual(gone, [])
135
+ self.assertEqual(len(alive), 3)
136
+ self.assertEqual(pids, [])
137
+ for p in alive:
138
+ self.assertFalse(hasattr(p, 'returncode'))
139
+
140
+ @retry_on_failure(30)
141
+ def test_1(procs, callback):
142
+ gone, alive = psutil.wait_procs(
143
+ procs, timeout=0.03, callback=callback
144
+ )
145
+ self.assertEqual(len(gone), 1)
146
+ self.assertEqual(len(alive), 2)
147
+ return gone, alive
148
+
149
+ sproc3.terminate()
150
+ gone, alive = test_1(procs, callback)
151
+ self.assertIn(sproc3.pid, [x.pid for x in gone])
152
+ if POSIX:
153
+ self.assertEqual(gone.pop().returncode, -signal.SIGTERM)
154
+ else:
155
+ self.assertEqual(gone.pop().returncode, 1)
156
+ self.assertEqual(pids, [sproc3.pid])
157
+ for p in alive:
158
+ self.assertFalse(hasattr(p, 'returncode'))
159
+
160
+ @retry_on_failure(30)
161
+ def test_2(procs, callback):
162
+ gone, alive = psutil.wait_procs(
163
+ procs, timeout=0.03, callback=callback
164
+ )
165
+ self.assertEqual(len(gone), 3)
166
+ self.assertEqual(len(alive), 0)
167
+ return gone, alive
168
+
169
+ sproc1.terminate()
170
+ sproc2.terminate()
171
+ gone, alive = test_2(procs, callback)
172
+ self.assertEqual(set(pids), set([sproc1.pid, sproc2.pid, sproc3.pid]))
173
+ for p in gone:
174
+ self.assertTrue(hasattr(p, 'returncode'))
175
+
176
+ @unittest.skipIf(
177
+ PYPY and WINDOWS, "spawn_testproc() unreliable on PYPY + WINDOWS"
178
+ )
179
+ def test_wait_procs_no_timeout(self):
180
+ sproc1 = self.spawn_testproc()
181
+ sproc2 = self.spawn_testproc()
182
+ sproc3 = self.spawn_testproc()
183
+ procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)]
184
+ for p in procs:
185
+ p.terminate()
186
+ psutil.wait_procs(procs)
187
+
188
+ def test_pid_exists(self):
189
+ sproc = self.spawn_testproc()
190
+ self.assertTrue(psutil.pid_exists(sproc.pid))
191
+ p = psutil.Process(sproc.pid)
192
+ p.kill()
193
+ p.wait()
194
+ self.assertFalse(psutil.pid_exists(sproc.pid))
195
+ self.assertFalse(psutil.pid_exists(-1))
196
+ self.assertEqual(psutil.pid_exists(0), 0 in psutil.pids())
197
+
198
+ def test_pid_exists_2(self):
199
+ pids = psutil.pids()
200
+ for pid in pids:
201
+ try:
202
+ assert psutil.pid_exists(pid)
203
+ except AssertionError:
204
+ # in case the process disappeared in meantime fail only
205
+ # if it is no longer in psutil.pids()
206
+ time.sleep(0.1)
207
+ self.assertNotIn(pid, psutil.pids())
208
+ pids = range(max(pids) + 15000, max(pids) + 16000)
209
+ for pid in pids:
210
+ self.assertFalse(psutil.pid_exists(pid), msg=pid)
211
+
212
+
213
+ class TestMiscAPIs(PsutilTestCase):
214
+ def test_boot_time(self):
215
+ bt = psutil.boot_time()
216
+ self.assertIsInstance(bt, float)
217
+ self.assertGreater(bt, 0)
218
+ self.assertLess(bt, time.time())
219
+
220
+ @unittest.skipIf(CI_TESTING and not psutil.users(), "unreliable on CI")
221
+ def test_users(self):
222
+ users = psutil.users()
223
+ self.assertNotEqual(users, [])
224
+ for user in users:
225
+ with self.subTest(user=user):
226
+ assert user.name
227
+ self.assertIsInstance(user.name, str)
228
+ self.assertIsInstance(user.terminal, (str, type(None)))
229
+ if user.host is not None:
230
+ self.assertIsInstance(user.host, (str, type(None)))
231
+ user.terminal # noqa
232
+ user.host # noqa
233
+ self.assertGreater(user.started, 0.0)
234
+ datetime.datetime.fromtimestamp(user.started)
235
+ if WINDOWS or OPENBSD:
236
+ self.assertIsNone(user.pid)
237
+ else:
238
+ psutil.Process(user.pid)
239
+
240
+ def test_test(self):
241
+ # test for psutil.test() function
242
+ stdout = sys.stdout
243
+ sys.stdout = DEVNULL
244
+ try:
245
+ psutil.test()
246
+ finally:
247
+ sys.stdout = stdout
248
+
249
+ def test_os_constants(self):
250
+ names = [
251
+ "POSIX",
252
+ "WINDOWS",
253
+ "LINUX",
254
+ "MACOS",
255
+ "FREEBSD",
256
+ "OPENBSD",
257
+ "NETBSD",
258
+ "BSD",
259
+ "SUNOS",
260
+ ]
261
+ for name in names:
262
+ self.assertIsInstance(getattr(psutil, name), bool, msg=name)
263
+
264
+ if os.name == 'posix':
265
+ assert psutil.POSIX
266
+ assert not psutil.WINDOWS
267
+ names.remove("POSIX")
268
+ if "linux" in sys.platform.lower():
269
+ assert psutil.LINUX
270
+ names.remove("LINUX")
271
+ elif "bsd" in sys.platform.lower():
272
+ assert psutil.BSD
273
+ self.assertEqual(
274
+ [psutil.FREEBSD, psutil.OPENBSD, psutil.NETBSD].count(
275
+ True
276
+ ),
277
+ 1,
278
+ )
279
+ names.remove("BSD")
280
+ names.remove("FREEBSD")
281
+ names.remove("OPENBSD")
282
+ names.remove("NETBSD")
283
+ elif (
284
+ "sunos" in sys.platform.lower()
285
+ or "solaris" in sys.platform.lower()
286
+ ):
287
+ assert psutil.SUNOS
288
+ names.remove("SUNOS")
289
+ elif "darwin" in sys.platform.lower():
290
+ assert psutil.MACOS
291
+ names.remove("MACOS")
292
+ else:
293
+ assert psutil.WINDOWS
294
+ assert not psutil.POSIX
295
+ names.remove("WINDOWS")
296
+
297
+ # assert all other constants are set to False
298
+ for name in names:
299
+ self.assertFalse(getattr(psutil, name), msg=name)
300
+
301
+
302
+ class TestMemoryAPIs(PsutilTestCase):
303
+ def test_virtual_memory(self):
304
+ mem = psutil.virtual_memory()
305
+ assert mem.total > 0, mem
306
+ assert mem.available > 0, mem
307
+ assert 0 <= mem.percent <= 100, mem
308
+ assert mem.used > 0, mem
309
+ assert mem.free >= 0, mem
310
+ for name in mem._fields:
311
+ value = getattr(mem, name)
312
+ if name != 'percent':
313
+ self.assertIsInstance(value, (int, long))
314
+ if name != 'total':
315
+ if not value >= 0:
316
+ raise self.fail("%r < 0 (%s)" % (name, value))
317
+ if value > mem.total:
318
+ raise self.fail(
319
+ "%r > total (total=%s, %s=%s)"
320
+ % (name, mem.total, name, value)
321
+ )
322
+
323
+ def test_swap_memory(self):
324
+ mem = psutil.swap_memory()
325
+ self.assertEqual(
326
+ mem._fields, ('total', 'used', 'free', 'percent', 'sin', 'sout')
327
+ )
328
+
329
+ assert mem.total >= 0, mem
330
+ assert mem.used >= 0, mem
331
+ if mem.total > 0:
332
+ # likely a system with no swap partition
333
+ assert mem.free > 0, mem
334
+ else:
335
+ assert mem.free == 0, mem
336
+ assert 0 <= mem.percent <= 100, mem
337
+ assert mem.sin >= 0, mem
338
+ assert mem.sout >= 0, mem
339
+
340
+
341
+ class TestCpuAPIs(PsutilTestCase):
342
+ def test_cpu_count_logical(self):
343
+ logical = psutil.cpu_count()
344
+ self.assertIsNotNone(logical)
345
+ self.assertEqual(logical, len(psutil.cpu_times(percpu=True)))
346
+ self.assertGreaterEqual(logical, 1)
347
+ #
348
+ if os.path.exists("/proc/cpuinfo"):
349
+ with open("/proc/cpuinfo") as fd:
350
+ cpuinfo_data = fd.read()
351
+ if "physical id" not in cpuinfo_data:
352
+ raise unittest.SkipTest("cpuinfo doesn't include physical id")
353
+
354
+ def test_cpu_count_cores(self):
355
+ logical = psutil.cpu_count()
356
+ cores = psutil.cpu_count(logical=False)
357
+ if cores is None:
358
+ raise self.skipTest("cpu_count_cores() is None")
359
+ if WINDOWS and sys.getwindowsversion()[:2] <= (6, 1): # <= Vista
360
+ self.assertIsNone(cores)
361
+ else:
362
+ self.assertGreaterEqual(cores, 1)
363
+ self.assertGreaterEqual(logical, cores)
364
+
365
+ def test_cpu_count_none(self):
366
+ # https://github.com/giampaolo/psutil/issues/1085
367
+ for val in (-1, 0, None):
368
+ with mock.patch(
369
+ 'psutil._psplatform.cpu_count_logical', return_value=val
370
+ ) as m:
371
+ self.assertIsNone(psutil.cpu_count())
372
+ assert m.called
373
+ with mock.patch(
374
+ 'psutil._psplatform.cpu_count_cores', return_value=val
375
+ ) as m:
376
+ self.assertIsNone(psutil.cpu_count(logical=False))
377
+ assert m.called
378
+
379
+ def test_cpu_times(self):
380
+ # Check type, value >= 0, str().
381
+ total = 0
382
+ times = psutil.cpu_times()
383
+ sum(times)
384
+ for cp_time in times:
385
+ self.assertIsInstance(cp_time, float)
386
+ self.assertGreaterEqual(cp_time, 0.0)
387
+ total += cp_time
388
+ self.assertAlmostEqual(total, sum(times))
389
+ str(times)
390
+ # CPU times are always supposed to increase over time
391
+ # or at least remain the same and that's because time
392
+ # cannot go backwards.
393
+ # Surprisingly sometimes this might not be the case (at
394
+ # least on Windows and Linux), see:
395
+ # https://github.com/giampaolo/psutil/issues/392
396
+ # https://github.com/giampaolo/psutil/issues/645
397
+ # if not WINDOWS:
398
+ # last = psutil.cpu_times()
399
+ # for x in range(100):
400
+ # new = psutil.cpu_times()
401
+ # for field in new._fields:
402
+ # new_t = getattr(new, field)
403
+ # last_t = getattr(last, field)
404
+ # self.assertGreaterEqual(new_t, last_t,
405
+ # msg="%s %s" % (new_t, last_t))
406
+ # last = new
407
+
408
+ def test_cpu_times_time_increases(self):
409
+ # Make sure time increases between calls.
410
+ t1 = sum(psutil.cpu_times())
411
+ stop_at = time.time() + GLOBAL_TIMEOUT
412
+ while time.time() < stop_at:
413
+ t2 = sum(psutil.cpu_times())
414
+ if t2 > t1:
415
+ return
416
+ raise self.fail("time remained the same")
417
+
418
+ def test_per_cpu_times(self):
419
+ # Check type, value >= 0, str().
420
+ for times in psutil.cpu_times(percpu=True):
421
+ total = 0
422
+ sum(times)
423
+ for cp_time in times:
424
+ self.assertIsInstance(cp_time, float)
425
+ self.assertGreaterEqual(cp_time, 0.0)
426
+ total += cp_time
427
+ self.assertAlmostEqual(total, sum(times))
428
+ str(times)
429
+ self.assertEqual(
430
+ len(psutil.cpu_times(percpu=True)[0]),
431
+ len(psutil.cpu_times(percpu=False)),
432
+ )
433
+
434
+ # Note: in theory CPU times are always supposed to increase over
435
+ # time or remain the same but never go backwards. In practice
436
+ # sometimes this is not the case.
437
+ # This issue seemd to be afflict Windows:
438
+ # https://github.com/giampaolo/psutil/issues/392
439
+ # ...but it turns out also Linux (rarely) behaves the same.
440
+ # last = psutil.cpu_times(percpu=True)
441
+ # for x in range(100):
442
+ # new = psutil.cpu_times(percpu=True)
443
+ # for index in range(len(new)):
444
+ # newcpu = new[index]
445
+ # lastcpu = last[index]
446
+ # for field in newcpu._fields:
447
+ # new_t = getattr(newcpu, field)
448
+ # last_t = getattr(lastcpu, field)
449
+ # self.assertGreaterEqual(
450
+ # new_t, last_t, msg="%s %s" % (lastcpu, newcpu))
451
+ # last = new
452
+
453
+ def test_per_cpu_times_2(self):
454
+ # Simulate some work load then make sure time have increased
455
+ # between calls.
456
+ tot1 = psutil.cpu_times(percpu=True)
457
+ giveup_at = time.time() + GLOBAL_TIMEOUT
458
+ while True:
459
+ if time.time() >= giveup_at:
460
+ return self.fail("timeout")
461
+ tot2 = psutil.cpu_times(percpu=True)
462
+ for t1, t2 in zip(tot1, tot2):
463
+ t1, t2 = psutil._cpu_busy_time(t1), psutil._cpu_busy_time(t2)
464
+ difference = t2 - t1
465
+ if difference >= 0.05:
466
+ return
467
+
468
+ @unittest.skipIf(CI_TESTING and OPENBSD, "unreliable on OPENBSD + CI")
469
+ def test_cpu_times_comparison(self):
470
+ # Make sure the sum of all per cpu times is almost equal to
471
+ # base "one cpu" times. On OpenBSD the sum of per-CPUs is
472
+ # higher for some reason.
473
+ base = psutil.cpu_times()
474
+ per_cpu = psutil.cpu_times(percpu=True)
475
+ summed_values = base._make([sum(num) for num in zip(*per_cpu)])
476
+ for field in base._fields:
477
+ with self.subTest(field=field, base=base, per_cpu=per_cpu):
478
+ self.assertAlmostEqual(
479
+ getattr(base, field),
480
+ getattr(summed_values, field),
481
+ delta=1,
482
+ )
483
+
484
+ def _test_cpu_percent(self, percent, last_ret, new_ret):
485
+ try:
486
+ self.assertIsInstance(percent, float)
487
+ self.assertGreaterEqual(percent, 0.0)
488
+ self.assertIsNot(percent, -0.0)
489
+ self.assertLessEqual(percent, 100.0 * psutil.cpu_count())
490
+ except AssertionError as err:
491
+ raise AssertionError(
492
+ "\n%s\nlast=%s\nnew=%s"
493
+ % (err, pprint.pformat(last_ret), pprint.pformat(new_ret))
494
+ )
495
+
496
+ def test_cpu_percent(self):
497
+ last = psutil.cpu_percent(interval=0.001)
498
+ for _ in range(100):
499
+ new = psutil.cpu_percent(interval=None)
500
+ self._test_cpu_percent(new, last, new)
501
+ last = new
502
+ with self.assertRaises(ValueError):
503
+ psutil.cpu_percent(interval=-1)
504
+
505
+ def test_per_cpu_percent(self):
506
+ last = psutil.cpu_percent(interval=0.001, percpu=True)
507
+ self.assertEqual(len(last), psutil.cpu_count())
508
+ for _ in range(100):
509
+ new = psutil.cpu_percent(interval=None, percpu=True)
510
+ for percent in new:
511
+ self._test_cpu_percent(percent, last, new)
512
+ last = new
513
+ with self.assertRaises(ValueError):
514
+ psutil.cpu_percent(interval=-1, percpu=True)
515
+
516
+ def test_cpu_times_percent(self):
517
+ last = psutil.cpu_times_percent(interval=0.001)
518
+ for _ in range(100):
519
+ new = psutil.cpu_times_percent(interval=None)
520
+ for percent in new:
521
+ self._test_cpu_percent(percent, last, new)
522
+ self._test_cpu_percent(sum(new), last, new)
523
+ last = new
524
+ with self.assertRaises(ValueError):
525
+ psutil.cpu_times_percent(interval=-1)
526
+
527
+ def test_per_cpu_times_percent(self):
528
+ last = psutil.cpu_times_percent(interval=0.001, percpu=True)
529
+ self.assertEqual(len(last), psutil.cpu_count())
530
+ for _ in range(100):
531
+ new = psutil.cpu_times_percent(interval=None, percpu=True)
532
+ for cpu in new:
533
+ for percent in cpu:
534
+ self._test_cpu_percent(percent, last, new)
535
+ self._test_cpu_percent(sum(cpu), last, new)
536
+ last = new
537
+
538
+ def test_per_cpu_times_percent_negative(self):
539
+ # see: https://github.com/giampaolo/psutil/issues/645
540
+ psutil.cpu_times_percent(percpu=True)
541
+ zero_times = [
542
+ x._make([0 for x in range(len(x._fields))])
543
+ for x in psutil.cpu_times(percpu=True)
544
+ ]
545
+ with mock.patch('psutil.cpu_times', return_value=zero_times):
546
+ for cpu in psutil.cpu_times_percent(percpu=True):
547
+ for percent in cpu:
548
+ self._test_cpu_percent(percent, None, None)
549
+
550
+ def test_cpu_stats(self):
551
+ # Tested more extensively in per-platform test modules.
552
+ infos = psutil.cpu_stats()
553
+ self.assertEqual(
554
+ infos._fields,
555
+ ('ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'),
556
+ )
557
+ for name in infos._fields:
558
+ value = getattr(infos, name)
559
+ self.assertGreaterEqual(value, 0)
560
+ # on AIX, ctx_switches is always 0
561
+ if not AIX and name in ('ctx_switches', 'interrupts'):
562
+ self.assertGreater(value, 0)
563
+
564
+ # TODO: remove this once 1892 is fixed
565
+ @unittest.skipIf(
566
+ MACOS and platform.machine() == 'arm64', "skipped due to #1892"
567
+ )
568
+ @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
569
+ def test_cpu_freq(self):
570
+ def check_ls(ls):
571
+ for nt in ls:
572
+ self.assertEqual(nt._fields, ('current', 'min', 'max'))
573
+ if nt.max != 0.0:
574
+ self.assertLessEqual(nt.current, nt.max)
575
+ for name in nt._fields:
576
+ value = getattr(nt, name)
577
+ self.assertIsInstance(value, (int, long, float))
578
+ self.assertGreaterEqual(value, 0)
579
+
580
+ ls = psutil.cpu_freq(percpu=True)
581
+ if FREEBSD and not ls:
582
+ raise self.skipTest("returns empty list on FreeBSD")
583
+
584
+ assert ls, ls
585
+ check_ls([psutil.cpu_freq(percpu=False)])
586
+
587
+ if LINUX:
588
+ self.assertEqual(len(ls), psutil.cpu_count())
589
+
590
+ @unittest.skipIf(not HAS_GETLOADAVG, "not supported")
591
+ def test_getloadavg(self):
592
+ loadavg = psutil.getloadavg()
593
+ self.assertEqual(len(loadavg), 3)
594
+ for load in loadavg:
595
+ self.assertIsInstance(load, float)
596
+ self.assertGreaterEqual(load, 0.0)
597
+
598
+
599
+ class TestDiskAPIs(PsutilTestCase):
600
+ @unittest.skipIf(PYPY and not IS_64BIT, "unreliable on PYPY32 + 32BIT")
601
+ def test_disk_usage(self):
602
+ usage = psutil.disk_usage(os.getcwd())
603
+ self.assertEqual(usage._fields, ('total', 'used', 'free', 'percent'))
604
+
605
+ assert usage.total > 0, usage
606
+ assert usage.used > 0, usage
607
+ assert usage.free > 0, usage
608
+ assert usage.total > usage.used, usage
609
+ assert usage.total > usage.free, usage
610
+ assert 0 <= usage.percent <= 100, usage.percent
611
+ if hasattr(shutil, 'disk_usage'):
612
+ # py >= 3.3, see: http://bugs.python.org/issue12442
613
+ shutil_usage = shutil.disk_usage(os.getcwd())
614
+ tolerance = 5 * 1024 * 1024 # 5MB
615
+ self.assertEqual(usage.total, shutil_usage.total)
616
+ self.assertAlmostEqual(
617
+ usage.free, shutil_usage.free, delta=tolerance
618
+ )
619
+ if not MACOS_12PLUS:
620
+ # see https://github.com/giampaolo/psutil/issues/2147
621
+ self.assertAlmostEqual(
622
+ usage.used, shutil_usage.used, delta=tolerance
623
+ )
624
+
625
+ # if path does not exist OSError ENOENT is expected across
626
+ # all platforms
627
+ fname = self.get_testfn()
628
+ with self.assertRaises(FileNotFoundError):
629
+ psutil.disk_usage(fname)
630
+
631
+ @unittest.skipIf(not ASCII_FS, "not an ASCII fs")
632
+ def test_disk_usage_unicode(self):
633
+ # See: https://github.com/giampaolo/psutil/issues/416
634
+ with self.assertRaises(UnicodeEncodeError):
635
+ psutil.disk_usage(UNICODE_SUFFIX)
636
+
637
+ def test_disk_usage_bytes(self):
638
+ psutil.disk_usage(b'.')
639
+
640
+ def test_disk_partitions(self):
641
+ def check_ntuple(nt):
642
+ self.assertIsInstance(nt.device, str)
643
+ self.assertIsInstance(nt.mountpoint, str)
644
+ self.assertIsInstance(nt.fstype, str)
645
+ self.assertIsInstance(nt.opts, str)
646
+ self.assertIsInstance(nt.maxfile, (int, type(None)))
647
+ self.assertIsInstance(nt.maxpath, (int, type(None)))
648
+ if nt.maxfile is not None and not GITHUB_ACTIONS:
649
+ self.assertGreater(nt.maxfile, 0)
650
+ if nt.maxpath is not None:
651
+ self.assertGreater(nt.maxpath, 0)
652
+
653
+ # all = False
654
+ ls = psutil.disk_partitions(all=False)
655
+ self.assertTrue(ls, msg=ls)
656
+ for disk in ls:
657
+ check_ntuple(disk)
658
+ if WINDOWS and 'cdrom' in disk.opts:
659
+ continue
660
+ if not POSIX:
661
+ assert os.path.exists(disk.device), disk
662
+ else:
663
+ # we cannot make any assumption about this, see:
664
+ # http://goo.gl/p9c43
665
+ disk.device # noqa
666
+ # on modern systems mount points can also be files
667
+ assert os.path.exists(disk.mountpoint), disk
668
+ assert disk.fstype, disk
669
+
670
+ # all = True
671
+ ls = psutil.disk_partitions(all=True)
672
+ self.assertTrue(ls, msg=ls)
673
+ for disk in psutil.disk_partitions(all=True):
674
+ check_ntuple(disk)
675
+ if not WINDOWS and disk.mountpoint:
676
+ try:
677
+ os.stat(disk.mountpoint)
678
+ except OSError as err:
679
+ if GITHUB_ACTIONS and MACOS and err.errno == errno.EIO:
680
+ continue
681
+ # http://mail.python.org/pipermail/python-dev/
682
+ # 2012-June/120787.html
683
+ if err.errno not in (errno.EPERM, errno.EACCES):
684
+ raise
685
+ else:
686
+ assert os.path.exists(disk.mountpoint), disk
687
+
688
+ # ---
689
+
690
+ def find_mount_point(path):
691
+ path = os.path.abspath(path)
692
+ while not os.path.ismount(path):
693
+ path = os.path.dirname(path)
694
+ return path.lower()
695
+
696
+ mount = find_mount_point(__file__)
697
+ mounts = [
698
+ x.mountpoint.lower()
699
+ for x in psutil.disk_partitions(all=True)
700
+ if x.mountpoint
701
+ ]
702
+ self.assertIn(mount, mounts)
703
+
704
+ @unittest.skipIf(
705
+ LINUX and not os.path.exists('/proc/diskstats'),
706
+ '/proc/diskstats not available on this linux version',
707
+ )
708
+ @unittest.skipIf(
709
+ CI_TESTING and not psutil.disk_io_counters(), "unreliable on CI"
710
+ ) # no visible disks
711
+ def test_disk_io_counters(self):
712
+ def check_ntuple(nt):
713
+ self.assertEqual(nt[0], nt.read_count)
714
+ self.assertEqual(nt[1], nt.write_count)
715
+ self.assertEqual(nt[2], nt.read_bytes)
716
+ self.assertEqual(nt[3], nt.write_bytes)
717
+ if not (OPENBSD or NETBSD):
718
+ self.assertEqual(nt[4], nt.read_time)
719
+ self.assertEqual(nt[5], nt.write_time)
720
+ if LINUX:
721
+ self.assertEqual(nt[6], nt.read_merged_count)
722
+ self.assertEqual(nt[7], nt.write_merged_count)
723
+ self.assertEqual(nt[8], nt.busy_time)
724
+ elif FREEBSD:
725
+ self.assertEqual(nt[6], nt.busy_time)
726
+ for name in nt._fields:
727
+ assert getattr(nt, name) >= 0, nt
728
+
729
+ ret = psutil.disk_io_counters(perdisk=False)
730
+ assert ret is not None, "no disks on this system?"
731
+ check_ntuple(ret)
732
+ ret = psutil.disk_io_counters(perdisk=True)
733
+ # make sure there are no duplicates
734
+ self.assertEqual(len(ret), len(set(ret)))
735
+ for key in ret:
736
+ assert key, key
737
+ check_ntuple(ret[key])
738
+
739
+ def test_disk_io_counters_no_disks(self):
740
+ # Emulate a case where no disks are installed, see:
741
+ # https://github.com/giampaolo/psutil/issues/1062
742
+ with mock.patch(
743
+ 'psutil._psplatform.disk_io_counters', return_value={}
744
+ ) as m:
745
+ self.assertIsNone(psutil.disk_io_counters(perdisk=False))
746
+ self.assertEqual(psutil.disk_io_counters(perdisk=True), {})
747
+ assert m.called
748
+
749
+
750
+ class TestNetAPIs(PsutilTestCase):
751
+ @unittest.skipIf(not HAS_NET_IO_COUNTERS, 'not supported')
752
+ def test_net_io_counters(self):
753
+ def check_ntuple(nt):
754
+ self.assertEqual(nt[0], nt.bytes_sent)
755
+ self.assertEqual(nt[1], nt.bytes_recv)
756
+ self.assertEqual(nt[2], nt.packets_sent)
757
+ self.assertEqual(nt[3], nt.packets_recv)
758
+ self.assertEqual(nt[4], nt.errin)
759
+ self.assertEqual(nt[5], nt.errout)
760
+ self.assertEqual(nt[6], nt.dropin)
761
+ self.assertEqual(nt[7], nt.dropout)
762
+ assert nt.bytes_sent >= 0, nt
763
+ assert nt.bytes_recv >= 0, nt
764
+ assert nt.packets_sent >= 0, nt
765
+ assert nt.packets_recv >= 0, nt
766
+ assert nt.errin >= 0, nt
767
+ assert nt.errout >= 0, nt
768
+ assert nt.dropin >= 0, nt
769
+ assert nt.dropout >= 0, nt
770
+
771
+ ret = psutil.net_io_counters(pernic=False)
772
+ check_ntuple(ret)
773
+ ret = psutil.net_io_counters(pernic=True)
774
+ self.assertNotEqual(ret, [])
775
+ for key in ret:
776
+ self.assertTrue(key)
777
+ self.assertIsInstance(key, str)
778
+ check_ntuple(ret[key])
779
+
780
+ @unittest.skipIf(not HAS_NET_IO_COUNTERS, 'not supported')
781
+ def test_net_io_counters_no_nics(self):
782
+ # Emulate a case where no NICs are installed, see:
783
+ # https://github.com/giampaolo/psutil/issues/1062
784
+ with mock.patch(
785
+ 'psutil._psplatform.net_io_counters', return_value={}
786
+ ) as m:
787
+ self.assertIsNone(psutil.net_io_counters(pernic=False))
788
+ self.assertEqual(psutil.net_io_counters(pernic=True), {})
789
+ assert m.called
790
+
791
+ def test_net_if_addrs(self):
792
+ nics = psutil.net_if_addrs()
793
+ assert nics, nics
794
+
795
+ nic_stats = psutil.net_if_stats()
796
+
797
+ # Not reliable on all platforms (net_if_addrs() reports more
798
+ # interfaces).
799
+ # self.assertEqual(sorted(nics.keys()),
800
+ # sorted(psutil.net_io_counters(pernic=True).keys()))
801
+
802
+ families = set([socket.AF_INET, socket.AF_INET6, psutil.AF_LINK])
803
+ for nic, addrs in nics.items():
804
+ self.assertIsInstance(nic, str)
805
+ self.assertEqual(len(set(addrs)), len(addrs))
806
+ for addr in addrs:
807
+ self.assertIsInstance(addr.family, int)
808
+ self.assertIsInstance(addr.address, str)
809
+ self.assertIsInstance(addr.netmask, (str, type(None)))
810
+ self.assertIsInstance(addr.broadcast, (str, type(None)))
811
+ self.assertIn(addr.family, families)
812
+ if PY3 and not PYPY:
813
+ self.assertIsInstance(addr.family, enum.IntEnum)
814
+ if nic_stats[nic].isup:
815
+ # Do not test binding to addresses of interfaces
816
+ # that are down
817
+ if addr.family == socket.AF_INET:
818
+ s = socket.socket(addr.family)
819
+ with contextlib.closing(s):
820
+ s.bind((addr.address, 0))
821
+ elif addr.family == socket.AF_INET6:
822
+ info = socket.getaddrinfo(
823
+ addr.address,
824
+ 0,
825
+ socket.AF_INET6,
826
+ socket.SOCK_STREAM,
827
+ 0,
828
+ socket.AI_PASSIVE,
829
+ )[0]
830
+ af, socktype, proto, canonname, sa = info
831
+ s = socket.socket(af, socktype, proto)
832
+ with contextlib.closing(s):
833
+ s.bind(sa)
834
+ for ip in (
835
+ addr.address,
836
+ addr.netmask,
837
+ addr.broadcast,
838
+ addr.ptp,
839
+ ):
840
+ if ip is not None:
841
+ # TODO: skip AF_INET6 for now because I get:
842
+ # AddressValueError: Only hex digits permitted in
843
+ # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0'
844
+ if addr.family != socket.AF_INET6:
845
+ check_net_address(ip, addr.family)
846
+ # broadcast and ptp addresses are mutually exclusive
847
+ if addr.broadcast:
848
+ self.assertIsNone(addr.ptp)
849
+ elif addr.ptp:
850
+ self.assertIsNone(addr.broadcast)
851
+
852
+ if BSD or MACOS or SUNOS:
853
+ if hasattr(socket, "AF_LINK"):
854
+ self.assertEqual(psutil.AF_LINK, socket.AF_LINK)
855
+ elif LINUX:
856
+ self.assertEqual(psutil.AF_LINK, socket.AF_PACKET)
857
+ elif WINDOWS:
858
+ self.assertEqual(psutil.AF_LINK, -1)
859
+
860
+ def test_net_if_addrs_mac_null_bytes(self):
861
+ # Simulate that the underlying C function returns an incomplete
862
+ # MAC address. psutil is supposed to fill it with null bytes.
863
+ # https://github.com/giampaolo/psutil/issues/786
864
+ if POSIX:
865
+ ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)]
866
+ else:
867
+ ret = [('em1', -1, '06-3d-29', None, None, None)]
868
+ with mock.patch(
869
+ 'psutil._psplatform.net_if_addrs', return_value=ret
870
+ ) as m:
871
+ addr = psutil.net_if_addrs()['em1'][0]
872
+ assert m.called
873
+ if POSIX:
874
+ self.assertEqual(addr.address, '06:3d:29:00:00:00')
875
+ else:
876
+ self.assertEqual(addr.address, '06-3d-29-00-00-00')
877
+
878
+ def test_net_if_stats(self):
879
+ nics = psutil.net_if_stats()
880
+ assert nics, nics
881
+ all_duplexes = (
882
+ psutil.NIC_DUPLEX_FULL,
883
+ psutil.NIC_DUPLEX_HALF,
884
+ psutil.NIC_DUPLEX_UNKNOWN,
885
+ )
886
+ for name, stats in nics.items():
887
+ self.assertIsInstance(name, str)
888
+ isup, duplex, speed, mtu, flags = stats
889
+ self.assertIsInstance(isup, bool)
890
+ self.assertIn(duplex, all_duplexes)
891
+ self.assertIn(duplex, all_duplexes)
892
+ self.assertGreaterEqual(speed, 0)
893
+ self.assertGreaterEqual(mtu, 0)
894
+ self.assertIsInstance(flags, str)
895
+
896
+ @unittest.skipIf(
897
+ not (LINUX or BSD or MACOS), "LINUX or BSD or MACOS specific"
898
+ )
899
+ def test_net_if_stats_enodev(self):
900
+ # See: https://github.com/giampaolo/psutil/issues/1279
901
+ with mock.patch(
902
+ 'psutil._psutil_posix.net_if_mtu',
903
+ side_effect=OSError(errno.ENODEV, ""),
904
+ ) as m:
905
+ ret = psutil.net_if_stats()
906
+ self.assertEqual(ret, {})
907
+ assert m.called
908
+
909
+
910
+ class TestSensorsAPIs(PsutilTestCase):
911
+ @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
912
+ def test_sensors_temperatures(self):
913
+ temps = psutil.sensors_temperatures()
914
+ for name, entries in temps.items():
915
+ self.assertIsInstance(name, str)
916
+ for entry in entries:
917
+ self.assertIsInstance(entry.label, str)
918
+ if entry.current is not None:
919
+ self.assertGreaterEqual(entry.current, 0)
920
+ if entry.high is not None:
921
+ self.assertGreaterEqual(entry.high, 0)
922
+ if entry.critical is not None:
923
+ self.assertGreaterEqual(entry.critical, 0)
924
+
925
+ @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
926
+ def test_sensors_temperatures_fahreneit(self):
927
+ d = {'coretemp': [('label', 50.0, 60.0, 70.0)]}
928
+ with mock.patch(
929
+ "psutil._psplatform.sensors_temperatures", return_value=d
930
+ ) as m:
931
+ temps = psutil.sensors_temperatures(fahrenheit=True)['coretemp'][0]
932
+ assert m.called
933
+ self.assertEqual(temps.current, 122.0)
934
+ self.assertEqual(temps.high, 140.0)
935
+ self.assertEqual(temps.critical, 158.0)
936
+
937
+ @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
938
+ @unittest.skipIf(not HAS_BATTERY, "no battery")
939
+ def test_sensors_battery(self):
940
+ ret = psutil.sensors_battery()
941
+ self.assertGreaterEqual(ret.percent, 0)
942
+ self.assertLessEqual(ret.percent, 100)
943
+ if ret.secsleft not in (
944
+ psutil.POWER_TIME_UNKNOWN,
945
+ psutil.POWER_TIME_UNLIMITED,
946
+ ):
947
+ self.assertGreaterEqual(ret.secsleft, 0)
948
+ else:
949
+ if ret.secsleft == psutil.POWER_TIME_UNLIMITED:
950
+ self.assertTrue(ret.power_plugged)
951
+ self.assertIsInstance(ret.power_plugged, bool)
952
+
953
+ @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
954
+ def test_sensors_fans(self):
955
+ fans = psutil.sensors_fans()
956
+ for name, entries in fans.items():
957
+ self.assertIsInstance(name, str)
958
+ for entry in entries:
959
+ self.assertIsInstance(entry.label, str)
960
+ self.assertIsInstance(entry.current, (int, long))
961
+ self.assertGreaterEqual(entry.current, 0)
962
+
963
+
964
+ if __name__ == '__main__':
965
+ from psutil.tests.runner import run_from_name
966
+
967
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_testutils.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
5
+ # Use of this source code is governed by a BSD-style license that can be
6
+ # found in the LICENSE file.
7
+
8
+ """Tests for testing utils (psutil.tests namespace)."""
9
+
10
+ import collections
11
+ import contextlib
12
+ import errno
13
+ import os
14
+ import socket
15
+ import stat
16
+ import subprocess
17
+ import unittest
18
+
19
+ import psutil
20
+ import psutil.tests
21
+ from psutil import FREEBSD
22
+ from psutil import NETBSD
23
+ from psutil import POSIX
24
+ from psutil._common import open_binary
25
+ from psutil._common import open_text
26
+ from psutil._common import supports_ipv6
27
+ from psutil.tests import CI_TESTING
28
+ from psutil.tests import COVERAGE
29
+ from psutil.tests import HAS_CONNECTIONS_UNIX
30
+ from psutil.tests import PYTHON_EXE
31
+ from psutil.tests import PYTHON_EXE_ENV
32
+ from psutil.tests import PsutilTestCase
33
+ from psutil.tests import TestMemoryLeak
34
+ from psutil.tests import bind_socket
35
+ from psutil.tests import bind_unix_socket
36
+ from psutil.tests import call_until
37
+ from psutil.tests import chdir
38
+ from psutil.tests import create_sockets
39
+ from psutil.tests import filter_proc_connections
40
+ from psutil.tests import get_free_port
41
+ from psutil.tests import is_namedtuple
42
+ from psutil.tests import mock
43
+ from psutil.tests import process_namespace
44
+ from psutil.tests import reap_children
45
+ from psutil.tests import retry
46
+ from psutil.tests import retry_on_failure
47
+ from psutil.tests import safe_mkdir
48
+ from psutil.tests import safe_rmpath
49
+ from psutil.tests import serialrun
50
+ from psutil.tests import system_namespace
51
+ from psutil.tests import tcp_socketpair
52
+ from psutil.tests import terminate
53
+ from psutil.tests import unix_socketpair
54
+ from psutil.tests import wait_for_file
55
+ from psutil.tests import wait_for_pid
56
+
57
+
58
+ # ===================================================================
59
+ # --- Unit tests for test utilities.
60
+ # ===================================================================
61
+
62
+
63
+ class TestRetryDecorator(PsutilTestCase):
64
+ @mock.patch('time.sleep')
65
+ def test_retry_success(self, sleep):
66
+ # Fail 3 times out of 5; make sure the decorated fun returns.
67
+
68
+ @retry(retries=5, interval=1, logfun=None)
69
+ def foo():
70
+ while queue:
71
+ queue.pop()
72
+ 1 / 0 # noqa
73
+ return 1
74
+
75
+ queue = list(range(3))
76
+ self.assertEqual(foo(), 1)
77
+ self.assertEqual(sleep.call_count, 3)
78
+
79
+ @mock.patch('time.sleep')
80
+ def test_retry_failure(self, sleep):
81
+ # Fail 6 times out of 5; th function is supposed to raise exc.
82
+ @retry(retries=5, interval=1, logfun=None)
83
+ def foo():
84
+ while queue:
85
+ queue.pop()
86
+ 1 / 0 # noqa
87
+ return 1
88
+
89
+ queue = list(range(6))
90
+ self.assertRaises(ZeroDivisionError, foo)
91
+ self.assertEqual(sleep.call_count, 5)
92
+
93
+ @mock.patch('time.sleep')
94
+ def test_exception_arg(self, sleep):
95
+ @retry(exception=ValueError, interval=1)
96
+ def foo():
97
+ raise TypeError
98
+
99
+ self.assertRaises(TypeError, foo)
100
+ self.assertEqual(sleep.call_count, 0)
101
+
102
+ @mock.patch('time.sleep')
103
+ def test_no_interval_arg(self, sleep):
104
+ # if interval is not specified sleep is not supposed to be called
105
+
106
+ @retry(retries=5, interval=None, logfun=None)
107
+ def foo():
108
+ 1 / 0 # noqa
109
+
110
+ self.assertRaises(ZeroDivisionError, foo)
111
+ self.assertEqual(sleep.call_count, 0)
112
+
113
+ @mock.patch('time.sleep')
114
+ def test_retries_arg(self, sleep):
115
+ @retry(retries=5, interval=1, logfun=None)
116
+ def foo():
117
+ 1 / 0 # noqa
118
+
119
+ self.assertRaises(ZeroDivisionError, foo)
120
+ self.assertEqual(sleep.call_count, 5)
121
+
122
+ @mock.patch('time.sleep')
123
+ def test_retries_and_timeout_args(self, sleep):
124
+ self.assertRaises(ValueError, retry, retries=5, timeout=1)
125
+
126
+
127
+ class TestSyncTestUtils(PsutilTestCase):
128
+ def test_wait_for_pid(self):
129
+ wait_for_pid(os.getpid())
130
+ nopid = max(psutil.pids()) + 99999
131
+ with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])):
132
+ self.assertRaises(psutil.NoSuchProcess, wait_for_pid, nopid)
133
+
134
+ def test_wait_for_file(self):
135
+ testfn = self.get_testfn()
136
+ with open(testfn, 'w') as f:
137
+ f.write('foo')
138
+ wait_for_file(testfn)
139
+ assert not os.path.exists(testfn)
140
+
141
+ def test_wait_for_file_empty(self):
142
+ testfn = self.get_testfn()
143
+ with open(testfn, 'w'):
144
+ pass
145
+ wait_for_file(testfn, empty=True)
146
+ assert not os.path.exists(testfn)
147
+
148
+ def test_wait_for_file_no_file(self):
149
+ testfn = self.get_testfn()
150
+ with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])):
151
+ self.assertRaises(IOError, wait_for_file, testfn)
152
+
153
+ def test_wait_for_file_no_delete(self):
154
+ testfn = self.get_testfn()
155
+ with open(testfn, 'w') as f:
156
+ f.write('foo')
157
+ wait_for_file(testfn, delete=False)
158
+ assert os.path.exists(testfn)
159
+
160
+ def test_call_until(self):
161
+ ret = call_until(lambda: 1, "ret == 1")
162
+ self.assertEqual(ret, 1)
163
+
164
+
165
+ class TestFSTestUtils(PsutilTestCase):
166
+ def test_open_text(self):
167
+ with open_text(__file__) as f:
168
+ self.assertEqual(f.mode, 'r')
169
+
170
+ def test_open_binary(self):
171
+ with open_binary(__file__) as f:
172
+ self.assertEqual(f.mode, 'rb')
173
+
174
+ def test_safe_mkdir(self):
175
+ testfn = self.get_testfn()
176
+ safe_mkdir(testfn)
177
+ assert os.path.isdir(testfn)
178
+ safe_mkdir(testfn)
179
+ assert os.path.isdir(testfn)
180
+
181
+ def test_safe_rmpath(self):
182
+ # test file is removed
183
+ testfn = self.get_testfn()
184
+ open(testfn, 'w').close()
185
+ safe_rmpath(testfn)
186
+ assert not os.path.exists(testfn)
187
+ # test no exception if path does not exist
188
+ safe_rmpath(testfn)
189
+ # test dir is removed
190
+ os.mkdir(testfn)
191
+ safe_rmpath(testfn)
192
+ assert not os.path.exists(testfn)
193
+ # test other exceptions are raised
194
+ with mock.patch(
195
+ 'psutil.tests.os.stat', side_effect=OSError(errno.EINVAL, "")
196
+ ) as m:
197
+ with self.assertRaises(OSError):
198
+ safe_rmpath(testfn)
199
+ assert m.called
200
+
201
+ def test_chdir(self):
202
+ testfn = self.get_testfn()
203
+ base = os.getcwd()
204
+ os.mkdir(testfn)
205
+ with chdir(testfn):
206
+ self.assertEqual(os.getcwd(), os.path.join(base, testfn))
207
+ self.assertEqual(os.getcwd(), base)
208
+
209
+
210
+ class TestProcessUtils(PsutilTestCase):
211
+ def test_reap_children(self):
212
+ subp = self.spawn_testproc()
213
+ p = psutil.Process(subp.pid)
214
+ assert p.is_running()
215
+ reap_children()
216
+ assert not p.is_running()
217
+ assert not psutil.tests._pids_started
218
+ assert not psutil.tests._subprocesses_started
219
+
220
+ def test_spawn_children_pair(self):
221
+ child, grandchild = self.spawn_children_pair()
222
+ self.assertNotEqual(child.pid, grandchild.pid)
223
+ assert child.is_running()
224
+ assert grandchild.is_running()
225
+ children = psutil.Process().children()
226
+ self.assertEqual(children, [child])
227
+ children = psutil.Process().children(recursive=True)
228
+ self.assertEqual(len(children), 2)
229
+ self.assertIn(child, children)
230
+ self.assertIn(grandchild, children)
231
+ self.assertEqual(child.ppid(), os.getpid())
232
+ self.assertEqual(grandchild.ppid(), child.pid)
233
+
234
+ terminate(child)
235
+ assert not child.is_running()
236
+ assert grandchild.is_running()
237
+
238
+ terminate(grandchild)
239
+ assert not grandchild.is_running()
240
+
241
+ @unittest.skipIf(not POSIX, "POSIX only")
242
+ def test_spawn_zombie(self):
243
+ parent, zombie = self.spawn_zombie()
244
+ self.assertEqual(zombie.status(), psutil.STATUS_ZOMBIE)
245
+
246
+ def test_terminate(self):
247
+ # by subprocess.Popen
248
+ p = self.spawn_testproc()
249
+ terminate(p)
250
+ self.assertPidGone(p.pid)
251
+ terminate(p)
252
+ # by psutil.Process
253
+ p = psutil.Process(self.spawn_testproc().pid)
254
+ terminate(p)
255
+ self.assertPidGone(p.pid)
256
+ terminate(p)
257
+ # by psutil.Popen
258
+ cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
259
+ p = psutil.Popen(
260
+ cmd,
261
+ stdout=subprocess.PIPE,
262
+ stderr=subprocess.PIPE,
263
+ env=PYTHON_EXE_ENV,
264
+ )
265
+ terminate(p)
266
+ self.assertPidGone(p.pid)
267
+ terminate(p)
268
+ # by PID
269
+ pid = self.spawn_testproc().pid
270
+ terminate(pid)
271
+ self.assertPidGone(p.pid)
272
+ terminate(pid)
273
+ # zombie
274
+ if POSIX:
275
+ parent, zombie = self.spawn_zombie()
276
+ terminate(parent)
277
+ terminate(zombie)
278
+ self.assertPidGone(parent.pid)
279
+ self.assertPidGone(zombie.pid)
280
+
281
+
282
+ class TestNetUtils(PsutilTestCase):
283
+ def bind_socket(self):
284
+ port = get_free_port()
285
+ with contextlib.closing(bind_socket(addr=('', port))) as s:
286
+ self.assertEqual(s.getsockname()[1], port)
287
+
288
+ @unittest.skipIf(not POSIX, "POSIX only")
289
+ def test_bind_unix_socket(self):
290
+ name = self.get_testfn()
291
+ sock = bind_unix_socket(name)
292
+ with contextlib.closing(sock):
293
+ self.assertEqual(sock.family, socket.AF_UNIX)
294
+ self.assertEqual(sock.type, socket.SOCK_STREAM)
295
+ self.assertEqual(sock.getsockname(), name)
296
+ assert os.path.exists(name)
297
+ assert stat.S_ISSOCK(os.stat(name).st_mode)
298
+ # UDP
299
+ name = self.get_testfn()
300
+ sock = bind_unix_socket(name, type=socket.SOCK_DGRAM)
301
+ with contextlib.closing(sock):
302
+ self.assertEqual(sock.type, socket.SOCK_DGRAM)
303
+
304
+ def tcp_tcp_socketpair(self):
305
+ addr = ("127.0.0.1", get_free_port())
306
+ server, client = tcp_socketpair(socket.AF_INET, addr=addr)
307
+ with contextlib.closing(server):
308
+ with contextlib.closing(client):
309
+ # Ensure they are connected and the positions are
310
+ # correct.
311
+ self.assertEqual(server.getsockname(), addr)
312
+ self.assertEqual(client.getpeername(), addr)
313
+ self.assertNotEqual(client.getsockname(), addr)
314
+
315
+ @unittest.skipIf(not POSIX, "POSIX only")
316
+ @unittest.skipIf(
317
+ NETBSD or FREEBSD, "/var/run/log UNIX socket opened by default"
318
+ )
319
+ def test_unix_socketpair(self):
320
+ p = psutil.Process()
321
+ num_fds = p.num_fds()
322
+ self.assertEqual(
323
+ filter_proc_connections(p.connections(kind='unix')), []
324
+ )
325
+ name = self.get_testfn()
326
+ server, client = unix_socketpair(name)
327
+ try:
328
+ assert os.path.exists(name)
329
+ assert stat.S_ISSOCK(os.stat(name).st_mode)
330
+ self.assertEqual(p.num_fds() - num_fds, 2)
331
+ self.assertEqual(
332
+ len(filter_proc_connections(p.connections(kind='unix'))), 2
333
+ )
334
+ self.assertEqual(server.getsockname(), name)
335
+ self.assertEqual(client.getpeername(), name)
336
+ finally:
337
+ client.close()
338
+ server.close()
339
+
340
+ def test_create_sockets(self):
341
+ with create_sockets() as socks:
342
+ fams = collections.defaultdict(int)
343
+ types = collections.defaultdict(int)
344
+ for s in socks:
345
+ fams[s.family] += 1
346
+ # work around http://bugs.python.org/issue30204
347
+ types[s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)] += 1
348
+ self.assertGreaterEqual(fams[socket.AF_INET], 2)
349
+ if supports_ipv6():
350
+ self.assertGreaterEqual(fams[socket.AF_INET6], 2)
351
+ if POSIX and HAS_CONNECTIONS_UNIX:
352
+ self.assertGreaterEqual(fams[socket.AF_UNIX], 2)
353
+ self.assertGreaterEqual(types[socket.SOCK_STREAM], 2)
354
+ self.assertGreaterEqual(types[socket.SOCK_DGRAM], 2)
355
+
356
+
357
+ @serialrun
358
+ class TestMemLeakClass(TestMemoryLeak):
359
+ @retry_on_failure()
360
+ def test_times(self):
361
+ def fun():
362
+ cnt['cnt'] += 1
363
+
364
+ cnt = {'cnt': 0}
365
+ self.execute(fun, times=10, warmup_times=15)
366
+ self.assertEqual(cnt['cnt'], 26)
367
+
368
+ def test_param_err(self):
369
+ self.assertRaises(ValueError, self.execute, lambda: 0, times=0)
370
+ self.assertRaises(ValueError, self.execute, lambda: 0, times=-1)
371
+ self.assertRaises(ValueError, self.execute, lambda: 0, warmup_times=-1)
372
+ self.assertRaises(ValueError, self.execute, lambda: 0, tolerance=-1)
373
+ self.assertRaises(ValueError, self.execute, lambda: 0, retries=-1)
374
+
375
+ @retry_on_failure()
376
+ @unittest.skipIf(CI_TESTING, "skipped on CI")
377
+ @unittest.skipIf(COVERAGE, "skipped during test coverage")
378
+ def test_leak_mem(self):
379
+ ls = []
380
+
381
+ def fun(ls=ls):
382
+ ls.append("x" * 124 * 1024)
383
+
384
+ try:
385
+ # will consume around 30M in total
386
+ self.assertRaisesRegex(
387
+ AssertionError, "extra-mem", self.execute, fun, times=50
388
+ )
389
+ finally:
390
+ del ls
391
+
392
+ def test_unclosed_files(self):
393
+ def fun():
394
+ f = open(__file__)
395
+ self.addCleanup(f.close)
396
+ box.append(f)
397
+
398
+ box = []
399
+ kind = "fd" if POSIX else "handle"
400
+ self.assertRaisesRegex(
401
+ AssertionError, "unclosed " + kind, self.execute, fun
402
+ )
403
+
404
+ def test_tolerance(self):
405
+ def fun():
406
+ ls.append("x" * 24 * 1024)
407
+
408
+ ls = []
409
+ times = 100
410
+ self.execute(
411
+ fun, times=times, warmup_times=0, tolerance=200 * 1024 * 1024
412
+ )
413
+ self.assertEqual(len(ls), times + 1)
414
+
415
+ def test_execute_w_exc(self):
416
+ def fun_1():
417
+ 1 / 0 # noqa
418
+
419
+ self.execute_w_exc(ZeroDivisionError, fun_1)
420
+ with self.assertRaises(ZeroDivisionError):
421
+ self.execute_w_exc(OSError, fun_1)
422
+
423
+ def fun_2():
424
+ pass
425
+
426
+ with self.assertRaises(AssertionError):
427
+ self.execute_w_exc(ZeroDivisionError, fun_2)
428
+
429
+
430
+ class TestTestingUtils(PsutilTestCase):
431
+ def test_process_namespace(self):
432
+ p = psutil.Process()
433
+ ns = process_namespace(p)
434
+ ns.test()
435
+ fun = [x for x in ns.iter(ns.getters) if x[1] == 'ppid'][0][0]
436
+ self.assertEqual(fun(), p.ppid())
437
+
438
+ def test_system_namespace(self):
439
+ ns = system_namespace()
440
+ fun = [x for x in ns.iter(ns.getters) if x[1] == 'net_if_addrs'][0][0]
441
+ self.assertEqual(fun(), psutil.net_if_addrs())
442
+
443
+
444
+ class TestOtherUtils(PsutilTestCase):
445
+ def test_is_namedtuple(self):
446
+ assert is_namedtuple(collections.namedtuple('foo', 'a b c')(1, 2, 3))
447
+ assert not is_namedtuple(tuple())
448
+
449
+
450
+ if __name__ == '__main__':
451
+ from psutil.tests.runner import run_from_name
452
+
453
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_unicode.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
5
+ # Use of this source code is governed by a BSD-style license that can be
6
+ # found in the LICENSE file.
7
+
8
+ """Notes about unicode handling in psutil
9
+ ======================================.
10
+
11
+ Starting from version 5.3.0 psutil adds unicode support, see:
12
+ https://github.com/giampaolo/psutil/issues/1040
13
+ The notes below apply to *any* API returning a string such as
14
+ process exe(), cwd() or username():
15
+
16
+ * all strings are encoded by using the OS filesystem encoding
17
+ (sys.getfilesystemencoding()) which varies depending on the platform
18
+ (e.g. "UTF-8" on macOS, "mbcs" on Win)
19
+ * no API call is supposed to crash with UnicodeDecodeError
20
+ * instead, in case of badly encoded data returned by the OS, the
21
+ following error handlers are used to replace the corrupted characters in
22
+ the string:
23
+ * Python 3: sys.getfilesystemencodeerrors() (PY 3.6+) or
24
+ "surrogatescape" on POSIX and "replace" on Windows
25
+ * Python 2: "replace"
26
+ * on Python 2 all APIs return bytes (str type), never unicode
27
+ * on Python 2, you can go back to unicode by doing:
28
+
29
+ >>> unicode(p.exe(), sys.getdefaultencoding(), errors="replace")
30
+
31
+ For a detailed explanation of how psutil handles unicode see #1040.
32
+
33
+ Tests
34
+ =====
35
+
36
+ List of APIs returning or dealing with a string:
37
+ ('not tested' means they are not tested to deal with non-ASCII strings):
38
+
39
+ * Process.cmdline()
40
+ * Process.connections('unix')
41
+ * Process.cwd()
42
+ * Process.environ()
43
+ * Process.exe()
44
+ * Process.memory_maps()
45
+ * Process.name()
46
+ * Process.open_files()
47
+ * Process.username() (not tested)
48
+
49
+ * disk_io_counters() (not tested)
50
+ * disk_partitions() (not tested)
51
+ * disk_usage(str)
52
+ * net_connections('unix')
53
+ * net_if_addrs() (not tested)
54
+ * net_if_stats() (not tested)
55
+ * net_io_counters() (not tested)
56
+ * sensors_fans() (not tested)
57
+ * sensors_temperatures() (not tested)
58
+ * users() (not tested)
59
+
60
+ * WindowsService.binpath() (not tested)
61
+ * WindowsService.description() (not tested)
62
+ * WindowsService.display_name() (not tested)
63
+ * WindowsService.name() (not tested)
64
+ * WindowsService.status() (not tested)
65
+ * WindowsService.username() (not tested)
66
+
67
+ In here we create a unicode path with a funky non-ASCII name and (where
68
+ possible) make psutil return it back (e.g. on name(), exe(), open_files(),
69
+ etc.) and make sure that:
70
+
71
+ * psutil never crashes with UnicodeDecodeError
72
+ * the returned path matches
73
+ """
74
+
75
+ import os
76
+ import shutil
77
+ import traceback
78
+ import unittest
79
+ import warnings
80
+ from contextlib import closing
81
+
82
+ import psutil
83
+ from psutil import BSD
84
+ from psutil import POSIX
85
+ from psutil import WINDOWS
86
+ from psutil._compat import PY3
87
+ from psutil._compat import super
88
+ from psutil._compat import u
89
+ from psutil.tests import APPVEYOR
90
+ from psutil.tests import ASCII_FS
91
+ from psutil.tests import CI_TESTING
92
+ from psutil.tests import HAS_CONNECTIONS_UNIX
93
+ from psutil.tests import HAS_ENVIRON
94
+ from psutil.tests import HAS_MEMORY_MAPS
95
+ from psutil.tests import INVALID_UNICODE_SUFFIX
96
+ from psutil.tests import PYPY
97
+ from psutil.tests import TESTFN_PREFIX
98
+ from psutil.tests import UNICODE_SUFFIX
99
+ from psutil.tests import PsutilTestCase
100
+ from psutil.tests import bind_unix_socket
101
+ from psutil.tests import chdir
102
+ from psutil.tests import copyload_shared_lib
103
+ from psutil.tests import create_py_exe
104
+ from psutil.tests import get_testfn
105
+ from psutil.tests import safe_mkdir
106
+ from psutil.tests import safe_rmpath
107
+ from psutil.tests import serialrun
108
+ from psutil.tests import skip_on_access_denied
109
+ from psutil.tests import spawn_testproc
110
+ from psutil.tests import terminate
111
+
112
+
113
+ if APPVEYOR:
114
+
115
+ def safe_rmpath(path): # NOQA
116
+ # TODO - this is quite random and I'm not sure why it happens,
117
+ # nor I can reproduce it locally:
118
+ # https://ci.appveyor.com/project/giampaolo/psutil/build/job/
119
+ # jiq2cgd6stsbtn60
120
+ # safe_rmpath() happens after reap_children() so this is weird
121
+ # Perhaps wait_procs() on Windows is broken? Maybe because
122
+ # of STILL_ACTIVE?
123
+ # https://github.com/giampaolo/psutil/blob/
124
+ # 68c7a70728a31d8b8b58f4be6c4c0baa2f449eda/psutil/arch/
125
+ # windows/process_info.c#L146
126
+ from psutil.tests import safe_rmpath as rm
127
+
128
+ try:
129
+ return rm(path)
130
+ except WindowsError:
131
+ traceback.print_exc()
132
+
133
+
134
+ def try_unicode(suffix):
135
+ """Return True if both the fs and the subprocess module can
136
+ deal with a unicode file name.
137
+ """
138
+ sproc = None
139
+ testfn = get_testfn(suffix=suffix)
140
+ try:
141
+ safe_rmpath(testfn)
142
+ create_py_exe(testfn)
143
+ sproc = spawn_testproc(cmd=[testfn])
144
+ shutil.copyfile(testfn, testfn + '-2')
145
+ safe_rmpath(testfn + '-2')
146
+ except (UnicodeEncodeError, IOError):
147
+ return False
148
+ else:
149
+ return True
150
+ finally:
151
+ if sproc is not None:
152
+ terminate(sproc)
153
+ safe_rmpath(testfn)
154
+
155
+
156
+ # ===================================================================
157
+ # FS APIs
158
+ # ===================================================================
159
+
160
+
161
+ class BaseUnicodeTest(PsutilTestCase):
162
+ funky_suffix = None
163
+
164
+ @classmethod
165
+ def setUpClass(cls):
166
+ super().setUpClass()
167
+ cls.skip_tests = False
168
+ cls.funky_name = None
169
+ if cls.funky_suffix is not None:
170
+ if not try_unicode(cls.funky_suffix):
171
+ cls.skip_tests = True
172
+ else:
173
+ cls.funky_name = get_testfn(suffix=cls.funky_suffix)
174
+ create_py_exe(cls.funky_name)
175
+
176
+ def setUp(self):
177
+ super().setUp()
178
+ if self.skip_tests:
179
+ raise self.skipTest("can't handle unicode str")
180
+
181
+
182
+ @serialrun
183
+ @unittest.skipIf(ASCII_FS, "ASCII fs")
184
+ @unittest.skipIf(PYPY and not PY3, "too much trouble on PYPY2")
185
+ class TestFSAPIs(BaseUnicodeTest):
186
+ """Test FS APIs with a funky, valid, UTF8 path name."""
187
+
188
+ funky_suffix = UNICODE_SUFFIX
189
+
190
+ def expect_exact_path_match(self):
191
+ # Do not expect psutil to correctly handle unicode paths on
192
+ # Python 2 if os.listdir() is not able either.
193
+ here = '.' if isinstance(self.funky_name, str) else u('.')
194
+ with warnings.catch_warnings():
195
+ warnings.simplefilter("ignore")
196
+ return self.funky_name in os.listdir(here)
197
+
198
+ # ---
199
+
200
+ def test_proc_exe(self):
201
+ cmd = [self.funky_name, "-c", "import time; time.sleep(10)"]
202
+ subp = self.spawn_testproc(cmd)
203
+ p = psutil.Process(subp.pid)
204
+ exe = p.exe()
205
+ self.assertIsInstance(exe, str)
206
+ if self.expect_exact_path_match():
207
+ self.assertEqual(
208
+ os.path.normcase(exe), os.path.normcase(self.funky_name)
209
+ )
210
+
211
+ def test_proc_name(self):
212
+ cmd = [self.funky_name, "-c", "import time; time.sleep(10)"]
213
+ subp = self.spawn_testproc(cmd)
214
+ name = psutil.Process(subp.pid).name()
215
+ self.assertIsInstance(name, str)
216
+ if self.expect_exact_path_match():
217
+ self.assertEqual(name, os.path.basename(self.funky_name))
218
+
219
+ def test_proc_cmdline(self):
220
+ cmd = [self.funky_name, "-c", "import time; time.sleep(10)"]
221
+ subp = self.spawn_testproc(cmd)
222
+ p = psutil.Process(subp.pid)
223
+ cmdline = p.cmdline()
224
+ for part in cmdline:
225
+ self.assertIsInstance(part, str)
226
+ if self.expect_exact_path_match():
227
+ self.assertEqual(cmdline, cmd)
228
+
229
+ def test_proc_cwd(self):
230
+ dname = self.funky_name + "2"
231
+ self.addCleanup(safe_rmpath, dname)
232
+ safe_mkdir(dname)
233
+ with chdir(dname):
234
+ p = psutil.Process()
235
+ cwd = p.cwd()
236
+ self.assertIsInstance(p.cwd(), str)
237
+ if self.expect_exact_path_match():
238
+ self.assertEqual(cwd, dname)
239
+
240
+ @unittest.skipIf(PYPY and WINDOWS, "fails on PYPY + WINDOWS")
241
+ def test_proc_open_files(self):
242
+ p = psutil.Process()
243
+ start = set(p.open_files())
244
+ with open(self.funky_name, 'rb'):
245
+ new = set(p.open_files())
246
+ path = (new - start).pop().path
247
+ self.assertIsInstance(path, str)
248
+ if BSD and not path:
249
+ # XXX - see https://github.com/giampaolo/psutil/issues/595
250
+ return self.skipTest("open_files on BSD is broken")
251
+ if self.expect_exact_path_match():
252
+ self.assertEqual(
253
+ os.path.normcase(path), os.path.normcase(self.funky_name)
254
+ )
255
+
256
+ @unittest.skipIf(not POSIX, "POSIX only")
257
+ def test_proc_connections(self):
258
+ name = self.get_testfn(suffix=self.funky_suffix)
259
+ try:
260
+ sock = bind_unix_socket(name)
261
+ except UnicodeEncodeError:
262
+ if PY3:
263
+ raise
264
+ else:
265
+ raise unittest.SkipTest("not supported")
266
+ with closing(sock):
267
+ conn = psutil.Process().connections('unix')[0]
268
+ self.assertIsInstance(conn.laddr, str)
269
+ self.assertEqual(conn.laddr, name)
270
+
271
+ @unittest.skipIf(not POSIX, "POSIX only")
272
+ @unittest.skipIf(not HAS_CONNECTIONS_UNIX, "can't list UNIX sockets")
273
+ @skip_on_access_denied()
274
+ def test_net_connections(self):
275
+ def find_sock(cons):
276
+ for conn in cons:
277
+ if os.path.basename(conn.laddr).startswith(TESTFN_PREFIX):
278
+ return conn
279
+ raise ValueError("connection not found")
280
+
281
+ name = self.get_testfn(suffix=self.funky_suffix)
282
+ try:
283
+ sock = bind_unix_socket(name)
284
+ except UnicodeEncodeError:
285
+ if PY3:
286
+ raise
287
+ else:
288
+ raise unittest.SkipTest("not supported")
289
+ with closing(sock):
290
+ cons = psutil.net_connections(kind='unix')
291
+ conn = find_sock(cons)
292
+ self.assertIsInstance(conn.laddr, str)
293
+ self.assertEqual(conn.laddr, name)
294
+
295
+ def test_disk_usage(self):
296
+ dname = self.funky_name + "2"
297
+ self.addCleanup(safe_rmpath, dname)
298
+ safe_mkdir(dname)
299
+ psutil.disk_usage(dname)
300
+
301
+ @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
302
+ @unittest.skipIf(not PY3, "ctypes does not support unicode on PY2")
303
+ @unittest.skipIf(PYPY, "unstable on PYPY")
304
+ def test_memory_maps(self):
305
+ # XXX: on Python 2, using ctypes.CDLL with a unicode path
306
+ # opens a message box which blocks the test run.
307
+ with copyload_shared_lib(suffix=self.funky_suffix) as funky_path:
308
+
309
+ def normpath(p):
310
+ return os.path.realpath(os.path.normcase(p))
311
+
312
+ libpaths = [
313
+ normpath(x.path) for x in psutil.Process().memory_maps()
314
+ ]
315
+ # ...just to have a clearer msg in case of failure
316
+ libpaths = [x for x in libpaths if TESTFN_PREFIX in x]
317
+ self.assertIn(normpath(funky_path), libpaths)
318
+ for path in libpaths:
319
+ self.assertIsInstance(path, str)
320
+
321
+
322
+ @unittest.skipIf(CI_TESTING, "unreliable on CI")
323
+ class TestFSAPIsWithInvalidPath(TestFSAPIs):
324
+ """Test FS APIs with a funky, invalid path name."""
325
+
326
+ funky_suffix = INVALID_UNICODE_SUFFIX
327
+
328
+ def expect_exact_path_match(self):
329
+ # Invalid unicode names are supposed to work on Python 2.
330
+ return True
331
+
332
+
333
+ # ===================================================================
334
+ # Non fs APIs
335
+ # ===================================================================
336
+
337
+
338
+ class TestNonFSAPIS(BaseUnicodeTest):
339
+ """Unicode tests for non fs-related APIs."""
340
+
341
+ funky_suffix = UNICODE_SUFFIX if PY3 else 'è'
342
+
343
+ @unittest.skipIf(not HAS_ENVIRON, "not supported")
344
+ @unittest.skipIf(PYPY and WINDOWS, "segfaults on PYPY + WINDOWS")
345
+ def test_proc_environ(self):
346
+ # Note: differently from others, this test does not deal
347
+ # with fs paths. On Python 2 subprocess module is broken as
348
+ # it's not able to handle with non-ASCII env vars, so
349
+ # we use "è", which is part of the extended ASCII table
350
+ # (unicode point <= 255).
351
+ env = os.environ.copy()
352
+ env['FUNNY_ARG'] = self.funky_suffix
353
+ sproc = self.spawn_testproc(env=env)
354
+ p = psutil.Process(sproc.pid)
355
+ env = p.environ()
356
+ for k, v in env.items():
357
+ self.assertIsInstance(k, str)
358
+ self.assertIsInstance(v, str)
359
+ self.assertEqual(env['FUNNY_ARG'], self.funky_suffix)
360
+
361
+
362
+ if __name__ == '__main__':
363
+ from psutil.tests.runner import run_from_name
364
+
365
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/psutil/tests/test_windows.py ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: UTF-8 -*
3
+
4
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
5
+ # Use of this source code is governed by a BSD-style license that can be
6
+ # found in the LICENSE file.
7
+
8
+ """Windows specific tests."""
9
+
10
+ import datetime
11
+ import errno
12
+ import glob
13
+ import os
14
+ import platform
15
+ import re
16
+ import signal
17
+ import subprocess
18
+ import sys
19
+ import time
20
+ import unittest
21
+ import warnings
22
+
23
+ import psutil
24
+ from psutil import WINDOWS
25
+ from psutil._compat import FileNotFoundError
26
+ from psutil._compat import super
27
+ from psutil._compat import which
28
+ from psutil.tests import APPVEYOR
29
+ from psutil.tests import GITHUB_ACTIONS
30
+ from psutil.tests import HAS_BATTERY
31
+ from psutil.tests import IS_64BIT
32
+ from psutil.tests import PY3
33
+ from psutil.tests import PYPY
34
+ from psutil.tests import TOLERANCE_DISK_USAGE
35
+ from psutil.tests import TOLERANCE_SYS_MEM
36
+ from psutil.tests import PsutilTestCase
37
+ from psutil.tests import mock
38
+ from psutil.tests import retry_on_failure
39
+ from psutil.tests import sh
40
+ from psutil.tests import spawn_testproc
41
+ from psutil.tests import terminate
42
+
43
+
44
+ if WINDOWS and not PYPY:
45
+ with warnings.catch_warnings():
46
+ warnings.simplefilter("ignore")
47
+ import win32api # requires "pip install pywin32"
48
+ import win32con
49
+ import win32process
50
+ import wmi # requires "pip install wmi" / "make setup-dev-env"
51
+
52
+ if WINDOWS:
53
+ from psutil._pswindows import convert_oserror
54
+
55
+
56
+ cext = psutil._psplatform.cext
57
+
58
+
59
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
60
+ @unittest.skipIf(PYPY, "pywin32 not available on PYPY")
61
+ # https://github.com/giampaolo/psutil/pull/1762#issuecomment-632892692
62
+ @unittest.skipIf(GITHUB_ACTIONS and not PY3, "pywin32 broken on GITHUB + PY2")
63
+ class WindowsTestCase(PsutilTestCase):
64
+ pass
65
+
66
+
67
+ def powershell(cmd):
68
+ """Currently not used, but available just in case. Usage:
69
+
70
+ >>> powershell(
71
+ "Get-CIMInstance Win32_PageFileUsage | Select AllocatedBaseSize")
72
+ """
73
+ if not which("powershell.exe"):
74
+ raise unittest.SkipTest("powershell.exe not available")
75
+ cmdline = (
76
+ 'powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive '
77
+ + '-NoProfile -WindowStyle Hidden -Command "%s"' % cmd
78
+ )
79
+ return sh(cmdline)
80
+
81
+
82
+ def wmic(path, what, converter=int):
83
+ """Currently not used, but available just in case. Usage:
84
+
85
+ >>> wmic("Win32_OperatingSystem", "FreePhysicalMemory")
86
+ 2134124534
87
+ """
88
+ out = sh("wmic path %s get %s" % (path, what)).strip()
89
+ data = "".join(out.splitlines()[1:]).strip() # get rid of the header
90
+ if converter is not None:
91
+ if "," in what:
92
+ return tuple([converter(x) for x in data.split()])
93
+ else:
94
+ return converter(data)
95
+ else:
96
+ return data
97
+
98
+
99
+ # ===================================================================
100
+ # System APIs
101
+ # ===================================================================
102
+
103
+
104
+ class TestCpuAPIs(WindowsTestCase):
105
+ @unittest.skipIf(
106
+ 'NUMBER_OF_PROCESSORS' not in os.environ,
107
+ 'NUMBER_OF_PROCESSORS env var is not available',
108
+ )
109
+ def test_cpu_count_vs_NUMBER_OF_PROCESSORS(self):
110
+ # Will likely fail on many-cores systems:
111
+ # https://stackoverflow.com/questions/31209256
112
+ num_cpus = int(os.environ['NUMBER_OF_PROCESSORS'])
113
+ self.assertEqual(num_cpus, psutil.cpu_count())
114
+
115
+ def test_cpu_count_vs_GetSystemInfo(self):
116
+ # Will likely fail on many-cores systems:
117
+ # https://stackoverflow.com/questions/31209256
118
+ sys_value = win32api.GetSystemInfo()[5]
119
+ psutil_value = psutil.cpu_count()
120
+ self.assertEqual(sys_value, psutil_value)
121
+
122
+ def test_cpu_count_logical_vs_wmi(self):
123
+ w = wmi.WMI()
124
+ procs = sum(
125
+ proc.NumberOfLogicalProcessors for proc in w.Win32_Processor()
126
+ )
127
+ self.assertEqual(psutil.cpu_count(), procs)
128
+
129
+ def test_cpu_count_cores_vs_wmi(self):
130
+ w = wmi.WMI()
131
+ cores = sum(proc.NumberOfCores for proc in w.Win32_Processor())
132
+ self.assertEqual(psutil.cpu_count(logical=False), cores)
133
+
134
+ def test_cpu_count_vs_cpu_times(self):
135
+ self.assertEqual(
136
+ psutil.cpu_count(), len(psutil.cpu_times(percpu=True))
137
+ )
138
+
139
+ def test_cpu_freq(self):
140
+ w = wmi.WMI()
141
+ proc = w.Win32_Processor()[0]
142
+ self.assertEqual(proc.CurrentClockSpeed, psutil.cpu_freq().current)
143
+ self.assertEqual(proc.MaxClockSpeed, psutil.cpu_freq().max)
144
+
145
+
146
+ class TestSystemAPIs(WindowsTestCase):
147
+ def test_nic_names(self):
148
+ out = sh('ipconfig /all')
149
+ nics = psutil.net_io_counters(pernic=True).keys()
150
+ for nic in nics:
151
+ if "pseudo-interface" in nic.replace(' ', '-').lower():
152
+ continue
153
+ if nic not in out:
154
+ raise self.fail(
155
+ "%r nic wasn't found in 'ipconfig /all' output" % nic
156
+ )
157
+
158
+ def test_total_phymem(self):
159
+ w = wmi.WMI().Win32_ComputerSystem()[0]
160
+ self.assertEqual(
161
+ int(w.TotalPhysicalMemory), psutil.virtual_memory().total
162
+ )
163
+
164
+ def test_free_phymem(self):
165
+ w = wmi.WMI().Win32_PerfRawData_PerfOS_Memory()[0]
166
+ self.assertAlmostEqual(
167
+ int(w.AvailableBytes),
168
+ psutil.virtual_memory().free,
169
+ delta=TOLERANCE_SYS_MEM,
170
+ )
171
+
172
+ def test_total_swapmem(self):
173
+ w = wmi.WMI().Win32_PerfRawData_PerfOS_Memory()[0]
174
+ self.assertEqual(
175
+ int(w.CommitLimit) - psutil.virtual_memory().total,
176
+ psutil.swap_memory().total,
177
+ )
178
+ if psutil.swap_memory().total == 0:
179
+ self.assertEqual(0, psutil.swap_memory().free)
180
+ self.assertEqual(0, psutil.swap_memory().used)
181
+
182
+ def test_percent_swapmem(self):
183
+ if psutil.swap_memory().total > 0:
184
+ w = wmi.WMI().Win32_PerfRawData_PerfOS_PagingFile(Name="_Total")[0]
185
+ # calculate swap usage to percent
186
+ percentSwap = int(w.PercentUsage) * 100 / int(w.PercentUsage_Base)
187
+ # exact percent may change but should be reasonable
188
+ # assert within +/- 5% and between 0 and 100%
189
+ self.assertGreaterEqual(psutil.swap_memory().percent, 0)
190
+ self.assertAlmostEqual(
191
+ psutil.swap_memory().percent, percentSwap, delta=5
192
+ )
193
+ self.assertLessEqual(psutil.swap_memory().percent, 100)
194
+
195
+ # @unittest.skipIf(wmi is None, "wmi module is not installed")
196
+ # def test__UPTIME(self):
197
+ # # _UPTIME constant is not public but it is used internally
198
+ # # as value to return for pid 0 creation time.
199
+ # # WMI behaves the same.
200
+ # w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
201
+ # p = psutil.Process(0)
202
+ # wmic_create = str(w.CreationDate.split('.')[0])
203
+ # psutil_create = time.strftime("%Y%m%d%H%M%S",
204
+ # time.localtime(p.create_time()))
205
+
206
+ # Note: this test is not very reliable
207
+ @unittest.skipIf(APPVEYOR, "test not relieable on appveyor")
208
+ @retry_on_failure()
209
+ def test_pids(self):
210
+ # Note: this test might fail if the OS is starting/killing
211
+ # other processes in the meantime
212
+ w = wmi.WMI().Win32_Process()
213
+ wmi_pids = set([x.ProcessId for x in w])
214
+ psutil_pids = set(psutil.pids())
215
+ self.assertEqual(wmi_pids, psutil_pids)
216
+
217
+ @retry_on_failure()
218
+ def test_disks(self):
219
+ ps_parts = psutil.disk_partitions(all=True)
220
+ wmi_parts = wmi.WMI().Win32_LogicalDisk()
221
+ for ps_part in ps_parts:
222
+ for wmi_part in wmi_parts:
223
+ if ps_part.device.replace('\\', '') == wmi_part.DeviceID:
224
+ if not ps_part.mountpoint:
225
+ # this is usually a CD-ROM with no disk inserted
226
+ break
227
+ if 'cdrom' in ps_part.opts:
228
+ break
229
+ if ps_part.mountpoint.startswith('A:'):
230
+ break # floppy
231
+ try:
232
+ usage = psutil.disk_usage(ps_part.mountpoint)
233
+ except FileNotFoundError:
234
+ # usually this is the floppy
235
+ break
236
+ self.assertEqual(usage.total, int(wmi_part.Size))
237
+ wmi_free = int(wmi_part.FreeSpace)
238
+ self.assertEqual(usage.free, wmi_free)
239
+ # 10 MB tolerance
240
+ if abs(usage.free - wmi_free) > 10 * 1024 * 1024:
241
+ raise self.fail(
242
+ "psutil=%s, wmi=%s" % (usage.free, wmi_free)
243
+ )
244
+ break
245
+ else:
246
+ raise self.fail("can't find partition %s" % repr(ps_part))
247
+
248
+ @retry_on_failure()
249
+ def test_disk_usage(self):
250
+ for disk in psutil.disk_partitions():
251
+ if 'cdrom' in disk.opts:
252
+ continue
253
+ sys_value = win32api.GetDiskFreeSpaceEx(disk.mountpoint)
254
+ psutil_value = psutil.disk_usage(disk.mountpoint)
255
+ self.assertAlmostEqual(
256
+ sys_value[0], psutil_value.free, delta=TOLERANCE_DISK_USAGE
257
+ )
258
+ self.assertAlmostEqual(
259
+ sys_value[1], psutil_value.total, delta=TOLERANCE_DISK_USAGE
260
+ )
261
+ self.assertEqual(
262
+ psutil_value.used, psutil_value.total - psutil_value.free
263
+ )
264
+
265
+ def test_disk_partitions(self):
266
+ sys_value = [
267
+ x + '\\'
268
+ for x in win32api.GetLogicalDriveStrings().split("\\\x00")
269
+ if x and not x.startswith('A:')
270
+ ]
271
+ psutil_value = [
272
+ x.mountpoint
273
+ for x in psutil.disk_partitions(all=True)
274
+ if not x.mountpoint.startswith('A:')
275
+ ]
276
+ self.assertEqual(sys_value, psutil_value)
277
+
278
+ def test_net_if_stats(self):
279
+ ps_names = set(cext.net_if_stats())
280
+ wmi_adapters = wmi.WMI().Win32_NetworkAdapter()
281
+ wmi_names = set()
282
+ for wmi_adapter in wmi_adapters:
283
+ wmi_names.add(wmi_adapter.Name)
284
+ wmi_names.add(wmi_adapter.NetConnectionID)
285
+ self.assertTrue(
286
+ ps_names & wmi_names,
287
+ "no common entries in %s, %s" % (ps_names, wmi_names),
288
+ )
289
+
290
+ def test_boot_time(self):
291
+ wmi_os = wmi.WMI().Win32_OperatingSystem()
292
+ wmi_btime_str = wmi_os[0].LastBootUpTime.split('.')[0]
293
+ wmi_btime_dt = datetime.datetime.strptime(
294
+ wmi_btime_str, "%Y%m%d%H%M%S"
295
+ )
296
+ psutil_dt = datetime.datetime.fromtimestamp(psutil.boot_time())
297
+ diff = abs((wmi_btime_dt - psutil_dt).total_seconds())
298
+ self.assertLessEqual(diff, 5)
299
+
300
+ def test_boot_time_fluctuation(self):
301
+ # https://github.com/giampaolo/psutil/issues/1007
302
+ with mock.patch('psutil._pswindows.cext.boot_time', return_value=5):
303
+ self.assertEqual(psutil.boot_time(), 5)
304
+ with mock.patch('psutil._pswindows.cext.boot_time', return_value=4):
305
+ self.assertEqual(psutil.boot_time(), 5)
306
+ with mock.patch('psutil._pswindows.cext.boot_time', return_value=6):
307
+ self.assertEqual(psutil.boot_time(), 5)
308
+ with mock.patch('psutil._pswindows.cext.boot_time', return_value=333):
309
+ self.assertEqual(psutil.boot_time(), 333)
310
+
311
+
312
+ # ===================================================================
313
+ # sensors_battery()
314
+ # ===================================================================
315
+
316
+
317
+ class TestSensorsBattery(WindowsTestCase):
318
+ def test_has_battery(self):
319
+ if win32api.GetPwrCapabilities()['SystemBatteriesPresent']:
320
+ self.assertIsNotNone(psutil.sensors_battery())
321
+ else:
322
+ self.assertIsNone(psutil.sensors_battery())
323
+
324
+ @unittest.skipIf(not HAS_BATTERY, "no battery")
325
+ def test_percent(self):
326
+ w = wmi.WMI()
327
+ battery_wmi = w.query('select * from Win32_Battery')[0]
328
+ battery_psutil = psutil.sensors_battery()
329
+ self.assertAlmostEqual(
330
+ battery_psutil.percent,
331
+ battery_wmi.EstimatedChargeRemaining,
332
+ delta=1,
333
+ )
334
+
335
+ @unittest.skipIf(not HAS_BATTERY, "no battery")
336
+ def test_power_plugged(self):
337
+ w = wmi.WMI()
338
+ battery_wmi = w.query('select * from Win32_Battery')[0]
339
+ battery_psutil = psutil.sensors_battery()
340
+ # Status codes:
341
+ # https://msdn.microsoft.com/en-us/library/aa394074(v=vs.85).aspx
342
+ self.assertEqual(
343
+ battery_psutil.power_plugged, battery_wmi.BatteryStatus == 2
344
+ )
345
+
346
+ def test_emulate_no_battery(self):
347
+ with mock.patch(
348
+ "psutil._pswindows.cext.sensors_battery",
349
+ return_value=(0, 128, 0, 0),
350
+ ) as m:
351
+ self.assertIsNone(psutil.sensors_battery())
352
+ assert m.called
353
+
354
+ def test_emulate_power_connected(self):
355
+ with mock.patch(
356
+ "psutil._pswindows.cext.sensors_battery", return_value=(1, 0, 0, 0)
357
+ ) as m:
358
+ self.assertEqual(
359
+ psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNLIMITED
360
+ )
361
+ assert m.called
362
+
363
+ def test_emulate_power_charging(self):
364
+ with mock.patch(
365
+ "psutil._pswindows.cext.sensors_battery", return_value=(0, 8, 0, 0)
366
+ ) as m:
367
+ self.assertEqual(
368
+ psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNLIMITED
369
+ )
370
+ assert m.called
371
+
372
+ def test_emulate_secs_left_unknown(self):
373
+ with mock.patch(
374
+ "psutil._pswindows.cext.sensors_battery",
375
+ return_value=(0, 0, 0, -1),
376
+ ) as m:
377
+ self.assertEqual(
378
+ psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNKNOWN
379
+ )
380
+ assert m.called
381
+
382
+
383
+ # ===================================================================
384
+ # Process APIs
385
+ # ===================================================================
386
+
387
+
388
+ class TestProcess(WindowsTestCase):
389
+ @classmethod
390
+ def setUpClass(cls):
391
+ cls.pid = spawn_testproc().pid
392
+
393
+ @classmethod
394
+ def tearDownClass(cls):
395
+ terminate(cls.pid)
396
+
397
+ def test_issue_24(self):
398
+ p = psutil.Process(0)
399
+ self.assertRaises(psutil.AccessDenied, p.kill)
400
+
401
+ def test_special_pid(self):
402
+ p = psutil.Process(4)
403
+ self.assertEqual(p.name(), 'System')
404
+ # use __str__ to access all common Process properties to check
405
+ # that nothing strange happens
406
+ str(p)
407
+ p.username()
408
+ self.assertGreaterEqual(p.create_time(), 0.0)
409
+ try:
410
+ rss, vms = p.memory_info()[:2]
411
+ except psutil.AccessDenied:
412
+ # expected on Windows Vista and Windows 7
413
+ if platform.uname()[1] not in ('vista', 'win-7', 'win7'):
414
+ raise
415
+ else:
416
+ self.assertGreater(rss, 0)
417
+
418
+ def test_send_signal(self):
419
+ p = psutil.Process(self.pid)
420
+ self.assertRaises(ValueError, p.send_signal, signal.SIGINT)
421
+
422
+ def test_num_handles_increment(self):
423
+ p = psutil.Process(os.getpid())
424
+ before = p.num_handles()
425
+ handle = win32api.OpenProcess(
426
+ win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, os.getpid()
427
+ )
428
+ after = p.num_handles()
429
+ self.assertEqual(after, before + 1)
430
+ win32api.CloseHandle(handle)
431
+ self.assertEqual(p.num_handles(), before)
432
+
433
+ def test_ctrl_signals(self):
434
+ p = psutil.Process(self.spawn_testproc().pid)
435
+ p.send_signal(signal.CTRL_C_EVENT)
436
+ p.send_signal(signal.CTRL_BREAK_EVENT)
437
+ p.kill()
438
+ p.wait()
439
+ self.assertRaises(
440
+ psutil.NoSuchProcess, p.send_signal, signal.CTRL_C_EVENT
441
+ )
442
+ self.assertRaises(
443
+ psutil.NoSuchProcess, p.send_signal, signal.CTRL_BREAK_EVENT
444
+ )
445
+
446
+ def test_username(self):
447
+ name = win32api.GetUserNameEx(win32con.NameSamCompatible)
448
+ if name.endswith('$'):
449
+ # When running as a service account (most likely to be
450
+ # NetworkService), these user name calculations don't produce the
451
+ # same result, causing the test to fail.
452
+ raise unittest.SkipTest('running as service account')
453
+ self.assertEqual(psutil.Process().username(), name)
454
+
455
+ def test_cmdline(self):
456
+ sys_value = re.sub('[ ]+', ' ', win32api.GetCommandLine()).strip()
457
+ psutil_value = ' '.join(psutil.Process().cmdline())
458
+ if sys_value[0] == '"' != psutil_value[0]:
459
+ # The PyWin32 command line may retain quotes around argv[0] if they
460
+ # were used unnecessarily, while psutil will omit them. So remove
461
+ # the first 2 quotes from sys_value if not in psutil_value.
462
+ # A path to an executable will not contain quotes, so this is safe.
463
+ sys_value = sys_value.replace('"', '', 2)
464
+ self.assertEqual(sys_value, psutil_value)
465
+
466
+ # XXX - occasional failures
467
+
468
+ # def test_cpu_times(self):
469
+ # handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
470
+ # win32con.FALSE, os.getpid())
471
+ # self.addCleanup(win32api.CloseHandle, handle)
472
+ # sys_value = win32process.GetProcessTimes(handle)
473
+ # psutil_value = psutil.Process().cpu_times()
474
+ # self.assertAlmostEqual(
475
+ # psutil_value.user, sys_value['UserTime'] / 10000000.0,
476
+ # delta=0.2)
477
+ # self.assertAlmostEqual(
478
+ # psutil_value.user, sys_value['KernelTime'] / 10000000.0,
479
+ # delta=0.2)
480
+
481
+ def test_nice(self):
482
+ handle = win32api.OpenProcess(
483
+ win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, os.getpid()
484
+ )
485
+ self.addCleanup(win32api.CloseHandle, handle)
486
+ sys_value = win32process.GetPriorityClass(handle)
487
+ psutil_value = psutil.Process().nice()
488
+ self.assertEqual(psutil_value, sys_value)
489
+
490
+ def test_memory_info(self):
491
+ handle = win32api.OpenProcess(
492
+ win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, self.pid
493
+ )
494
+ self.addCleanup(win32api.CloseHandle, handle)
495
+ sys_value = win32process.GetProcessMemoryInfo(handle)
496
+ psutil_value = psutil.Process(self.pid).memory_info()
497
+ self.assertEqual(
498
+ sys_value['PeakWorkingSetSize'], psutil_value.peak_wset
499
+ )
500
+ self.assertEqual(sys_value['WorkingSetSize'], psutil_value.wset)
501
+ self.assertEqual(
502
+ sys_value['QuotaPeakPagedPoolUsage'], psutil_value.peak_paged_pool
503
+ )
504
+ self.assertEqual(
505
+ sys_value['QuotaPagedPoolUsage'], psutil_value.paged_pool
506
+ )
507
+ self.assertEqual(
508
+ sys_value['QuotaPeakNonPagedPoolUsage'],
509
+ psutil_value.peak_nonpaged_pool,
510
+ )
511
+ self.assertEqual(
512
+ sys_value['QuotaNonPagedPoolUsage'], psutil_value.nonpaged_pool
513
+ )
514
+ self.assertEqual(sys_value['PagefileUsage'], psutil_value.pagefile)
515
+ self.assertEqual(
516
+ sys_value['PeakPagefileUsage'], psutil_value.peak_pagefile
517
+ )
518
+
519
+ self.assertEqual(psutil_value.rss, psutil_value.wset)
520
+ self.assertEqual(psutil_value.vms, psutil_value.pagefile)
521
+
522
+ def test_wait(self):
523
+ handle = win32api.OpenProcess(
524
+ win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, self.pid
525
+ )
526
+ self.addCleanup(win32api.CloseHandle, handle)
527
+ p = psutil.Process(self.pid)
528
+ p.terminate()
529
+ psutil_value = p.wait()
530
+ sys_value = win32process.GetExitCodeProcess(handle)
531
+ self.assertEqual(psutil_value, sys_value)
532
+
533
+ def test_cpu_affinity(self):
534
+ def from_bitmask(x):
535
+ return [i for i in range(64) if (1 << i) & x]
536
+
537
+ handle = win32api.OpenProcess(
538
+ win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, self.pid
539
+ )
540
+ self.addCleanup(win32api.CloseHandle, handle)
541
+ sys_value = from_bitmask(
542
+ win32process.GetProcessAffinityMask(handle)[0]
543
+ )
544
+ psutil_value = psutil.Process(self.pid).cpu_affinity()
545
+ self.assertEqual(psutil_value, sys_value)
546
+
547
+ def test_io_counters(self):
548
+ handle = win32api.OpenProcess(
549
+ win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, os.getpid()
550
+ )
551
+ self.addCleanup(win32api.CloseHandle, handle)
552
+ sys_value = win32process.GetProcessIoCounters(handle)
553
+ psutil_value = psutil.Process().io_counters()
554
+ self.assertEqual(
555
+ psutil_value.read_count, sys_value['ReadOperationCount']
556
+ )
557
+ self.assertEqual(
558
+ psutil_value.write_count, sys_value['WriteOperationCount']
559
+ )
560
+ self.assertEqual(
561
+ psutil_value.read_bytes, sys_value['ReadTransferCount']
562
+ )
563
+ self.assertEqual(
564
+ psutil_value.write_bytes, sys_value['WriteTransferCount']
565
+ )
566
+ self.assertEqual(
567
+ psutil_value.other_count, sys_value['OtherOperationCount']
568
+ )
569
+ self.assertEqual(
570
+ psutil_value.other_bytes, sys_value['OtherTransferCount']
571
+ )
572
+
573
+ def test_num_handles(self):
574
+ import ctypes
575
+ import ctypes.wintypes
576
+
577
+ PROCESS_QUERY_INFORMATION = 0x400
578
+ handle = ctypes.windll.kernel32.OpenProcess(
579
+ PROCESS_QUERY_INFORMATION, 0, self.pid
580
+ )
581
+ self.addCleanup(ctypes.windll.kernel32.CloseHandle, handle)
582
+
583
+ hndcnt = ctypes.wintypes.DWORD()
584
+ ctypes.windll.kernel32.GetProcessHandleCount(
585
+ handle, ctypes.byref(hndcnt)
586
+ )
587
+ sys_value = hndcnt.value
588
+ psutil_value = psutil.Process(self.pid).num_handles()
589
+ self.assertEqual(psutil_value, sys_value)
590
+
591
+ def test_error_partial_copy(self):
592
+ # https://github.com/giampaolo/psutil/issues/875
593
+ exc = WindowsError()
594
+ exc.winerror = 299
595
+ with mock.patch("psutil._psplatform.cext.proc_cwd", side_effect=exc):
596
+ with mock.patch("time.sleep") as m:
597
+ p = psutil.Process()
598
+ self.assertRaises(psutil.AccessDenied, p.cwd)
599
+ self.assertGreaterEqual(m.call_count, 5)
600
+
601
+ def test_exe(self):
602
+ # NtQuerySystemInformation succeeds if process is gone. Make sure
603
+ # it raises NSP for a non existent pid.
604
+ pid = psutil.pids()[-1] + 99999
605
+ proc = psutil._psplatform.Process(pid)
606
+ self.assertRaises(psutil.NoSuchProcess, proc.exe)
607
+
608
+
609
+ class TestProcessWMI(WindowsTestCase):
610
+ """Compare Process API results with WMI."""
611
+
612
+ @classmethod
613
+ def setUpClass(cls):
614
+ cls.pid = spawn_testproc().pid
615
+
616
+ @classmethod
617
+ def tearDownClass(cls):
618
+ terminate(cls.pid)
619
+
620
+ def test_name(self):
621
+ w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
622
+ p = psutil.Process(self.pid)
623
+ self.assertEqual(p.name(), w.Caption)
624
+
625
+ # This fail on github because using virtualenv for test environment
626
+ @unittest.skipIf(GITHUB_ACTIONS, "unreliable path on GITHUB_ACTIONS")
627
+ def test_exe(self):
628
+ w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
629
+ p = psutil.Process(self.pid)
630
+ # Note: wmi reports the exe as a lower case string.
631
+ # Being Windows paths case-insensitive we ignore that.
632
+ self.assertEqual(p.exe().lower(), w.ExecutablePath.lower())
633
+
634
+ def test_cmdline(self):
635
+ w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
636
+ p = psutil.Process(self.pid)
637
+ self.assertEqual(' '.join(p.cmdline()), w.CommandLine.replace('"', ''))
638
+
639
+ def test_username(self):
640
+ w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
641
+ p = psutil.Process(self.pid)
642
+ domain, _, username = w.GetOwner()
643
+ username = "%s\\%s" % (domain, username)
644
+ self.assertEqual(p.username(), username)
645
+
646
+ @retry_on_failure()
647
+ def test_memory_rss(self):
648
+ w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
649
+ p = psutil.Process(self.pid)
650
+ rss = p.memory_info().rss
651
+ self.assertEqual(rss, int(w.WorkingSetSize))
652
+
653
+ @retry_on_failure()
654
+ def test_memory_vms(self):
655
+ w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
656
+ p = psutil.Process(self.pid)
657
+ vms = p.memory_info().vms
658
+ # http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx
659
+ # ...claims that PageFileUsage is represented in Kilo
660
+ # bytes but funnily enough on certain platforms bytes are
661
+ # returned instead.
662
+ wmi_usage = int(w.PageFileUsage)
663
+ if vms not in (wmi_usage, wmi_usage * 1024):
664
+ raise self.fail("wmi=%s, psutil=%s" % (wmi_usage, vms))
665
+
666
+ def test_create_time(self):
667
+ w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
668
+ p = psutil.Process(self.pid)
669
+ wmic_create = str(w.CreationDate.split('.')[0])
670
+ psutil_create = time.strftime(
671
+ "%Y%m%d%H%M%S", time.localtime(p.create_time())
672
+ )
673
+ self.assertEqual(wmic_create, psutil_create)
674
+
675
+
676
+ # ---
677
+
678
+
679
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
680
+ class TestDualProcessImplementation(PsutilTestCase):
681
+ """Certain APIs on Windows have 2 internal implementations, one
682
+ based on documented Windows APIs, another one based
683
+ NtQuerySystemInformation() which gets called as fallback in
684
+ case the first fails because of limited permission error.
685
+ Here we test that the two methods return the exact same value,
686
+ see:
687
+ https://github.com/giampaolo/psutil/issues/304.
688
+ """
689
+
690
+ @classmethod
691
+ def setUpClass(cls):
692
+ cls.pid = spawn_testproc().pid
693
+
694
+ @classmethod
695
+ def tearDownClass(cls):
696
+ terminate(cls.pid)
697
+
698
+ def test_memory_info(self):
699
+ mem_1 = psutil.Process(self.pid).memory_info()
700
+ with mock.patch(
701
+ "psutil._psplatform.cext.proc_memory_info",
702
+ side_effect=OSError(errno.EPERM, "msg"),
703
+ ) as fun:
704
+ mem_2 = psutil.Process(self.pid).memory_info()
705
+ self.assertEqual(len(mem_1), len(mem_2))
706
+ for i in range(len(mem_1)):
707
+ self.assertGreaterEqual(mem_1[i], 0)
708
+ self.assertGreaterEqual(mem_2[i], 0)
709
+ self.assertAlmostEqual(mem_1[i], mem_2[i], delta=512)
710
+ assert fun.called
711
+
712
+ def test_create_time(self):
713
+ ctime = psutil.Process(self.pid).create_time()
714
+ with mock.patch(
715
+ "psutil._psplatform.cext.proc_times",
716
+ side_effect=OSError(errno.EPERM, "msg"),
717
+ ) as fun:
718
+ self.assertEqual(psutil.Process(self.pid).create_time(), ctime)
719
+ assert fun.called
720
+
721
+ def test_cpu_times(self):
722
+ cpu_times_1 = psutil.Process(self.pid).cpu_times()
723
+ with mock.patch(
724
+ "psutil._psplatform.cext.proc_times",
725
+ side_effect=OSError(errno.EPERM, "msg"),
726
+ ) as fun:
727
+ cpu_times_2 = psutil.Process(self.pid).cpu_times()
728
+ assert fun.called
729
+ self.assertAlmostEqual(
730
+ cpu_times_1.user, cpu_times_2.user, delta=0.01
731
+ )
732
+ self.assertAlmostEqual(
733
+ cpu_times_1.system, cpu_times_2.system, delta=0.01
734
+ )
735
+
736
+ def test_io_counters(self):
737
+ io_counters_1 = psutil.Process(self.pid).io_counters()
738
+ with mock.patch(
739
+ "psutil._psplatform.cext.proc_io_counters",
740
+ side_effect=OSError(errno.EPERM, "msg"),
741
+ ) as fun:
742
+ io_counters_2 = psutil.Process(self.pid).io_counters()
743
+ for i in range(len(io_counters_1)):
744
+ self.assertAlmostEqual(
745
+ io_counters_1[i], io_counters_2[i], delta=5
746
+ )
747
+ assert fun.called
748
+
749
+ def test_num_handles(self):
750
+ num_handles = psutil.Process(self.pid).num_handles()
751
+ with mock.patch(
752
+ "psutil._psplatform.cext.proc_num_handles",
753
+ side_effect=OSError(errno.EPERM, "msg"),
754
+ ) as fun:
755
+ self.assertEqual(
756
+ psutil.Process(self.pid).num_handles(), num_handles
757
+ )
758
+ assert fun.called
759
+
760
+ def test_cmdline(self):
761
+ for pid in psutil.pids():
762
+ try:
763
+ a = cext.proc_cmdline(pid, use_peb=True)
764
+ b = cext.proc_cmdline(pid, use_peb=False)
765
+ except OSError as err:
766
+ err = convert_oserror(err)
767
+ if not isinstance(
768
+ err, (psutil.AccessDenied, psutil.NoSuchProcess)
769
+ ):
770
+ raise
771
+ else:
772
+ self.assertEqual(a, b)
773
+
774
+
775
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
776
+ class RemoteProcessTestCase(PsutilTestCase):
777
+ """Certain functions require calling ReadProcessMemory.
778
+ This trivially works when called on the current process.
779
+ Check that this works on other processes, especially when they
780
+ have a different bitness.
781
+ """
782
+
783
+ @staticmethod
784
+ def find_other_interpreter():
785
+ # find a python interpreter that is of the opposite bitness from us
786
+ code = "import sys; sys.stdout.write(str(sys.maxsize > 2**32))"
787
+
788
+ # XXX: a different and probably more stable approach might be to access
789
+ # the registry but accessing 64 bit paths from a 32 bit process
790
+ for filename in glob.glob(r"C:\Python*\python.exe"):
791
+ proc = subprocess.Popen(
792
+ args=[filename, "-c", code],
793
+ stdout=subprocess.PIPE,
794
+ stderr=subprocess.STDOUT,
795
+ )
796
+ output, _ = proc.communicate()
797
+ proc.wait()
798
+ if output == str(not IS_64BIT):
799
+ return filename
800
+
801
+ test_args = ["-c", "import sys; sys.stdin.read()"]
802
+
803
+ def setUp(self):
804
+ super().setUp()
805
+
806
+ other_python = self.find_other_interpreter()
807
+ if other_python is None:
808
+ raise unittest.SkipTest(
809
+ "could not find interpreter with opposite bitness"
810
+ )
811
+ if IS_64BIT:
812
+ self.python64 = sys.executable
813
+ self.python32 = other_python
814
+ else:
815
+ self.python64 = other_python
816
+ self.python32 = sys.executable
817
+
818
+ env = os.environ.copy()
819
+ env["THINK_OF_A_NUMBER"] = str(os.getpid())
820
+ self.proc32 = self.spawn_testproc(
821
+ [self.python32] + self.test_args, env=env, stdin=subprocess.PIPE
822
+ )
823
+ self.proc64 = self.spawn_testproc(
824
+ [self.python64] + self.test_args, env=env, stdin=subprocess.PIPE
825
+ )
826
+
827
+ def tearDown(self):
828
+ super().tearDown()
829
+ self.proc32.communicate()
830
+ self.proc64.communicate()
831
+
832
+ def test_cmdline_32(self):
833
+ p = psutil.Process(self.proc32.pid)
834
+ self.assertEqual(len(p.cmdline()), 3)
835
+ self.assertEqual(p.cmdline()[1:], self.test_args)
836
+
837
+ def test_cmdline_64(self):
838
+ p = psutil.Process(self.proc64.pid)
839
+ self.assertEqual(len(p.cmdline()), 3)
840
+ self.assertEqual(p.cmdline()[1:], self.test_args)
841
+
842
+ def test_cwd_32(self):
843
+ p = psutil.Process(self.proc32.pid)
844
+ self.assertEqual(p.cwd(), os.getcwd())
845
+
846
+ def test_cwd_64(self):
847
+ p = psutil.Process(self.proc64.pid)
848
+ self.assertEqual(p.cwd(), os.getcwd())
849
+
850
+ def test_environ_32(self):
851
+ p = psutil.Process(self.proc32.pid)
852
+ e = p.environ()
853
+ self.assertIn("THINK_OF_A_NUMBER", e)
854
+ self.assertEqual(e["THINK_OF_A_NUMBER"], str(os.getpid()))
855
+
856
+ def test_environ_64(self):
857
+ p = psutil.Process(self.proc64.pid)
858
+ try:
859
+ p.environ()
860
+ except psutil.AccessDenied:
861
+ pass
862
+
863
+
864
+ # ===================================================================
865
+ # Windows services
866
+ # ===================================================================
867
+
868
+
869
+ @unittest.skipIf(not WINDOWS, "WINDOWS only")
870
+ class TestServices(PsutilTestCase):
871
+ def test_win_service_iter(self):
872
+ valid_statuses = set([
873
+ "running",
874
+ "paused",
875
+ "start",
876
+ "pause",
877
+ "continue",
878
+ "stop",
879
+ "stopped",
880
+ ])
881
+ valid_start_types = set(["automatic", "manual", "disabled"])
882
+ valid_statuses = set([
883
+ "running",
884
+ "paused",
885
+ "start_pending",
886
+ "pause_pending",
887
+ "continue_pending",
888
+ "stop_pending",
889
+ "stopped",
890
+ ])
891
+ for serv in psutil.win_service_iter():
892
+ data = serv.as_dict()
893
+ self.assertIsInstance(data['name'], str)
894
+ self.assertNotEqual(data['name'].strip(), "")
895
+ self.assertIsInstance(data['display_name'], str)
896
+ self.assertIsInstance(data['username'], str)
897
+ self.assertIn(data['status'], valid_statuses)
898
+ if data['pid'] is not None:
899
+ psutil.Process(data['pid'])
900
+ self.assertIsInstance(data['binpath'], str)
901
+ self.assertIsInstance(data['username'], str)
902
+ self.assertIsInstance(data['start_type'], str)
903
+ self.assertIn(data['start_type'], valid_start_types)
904
+ self.assertIn(data['status'], valid_statuses)
905
+ self.assertIsInstance(data['description'], str)
906
+ pid = serv.pid()
907
+ if pid is not None:
908
+ p = psutil.Process(pid)
909
+ self.assertTrue(p.is_running())
910
+ # win_service_get
911
+ s = psutil.win_service_get(serv.name())
912
+ # test __eq__
913
+ self.assertEqual(serv, s)
914
+
915
+ def test_win_service_get(self):
916
+ ERROR_SERVICE_DOES_NOT_EXIST = (
917
+ psutil._psplatform.cext.ERROR_SERVICE_DOES_NOT_EXIST
918
+ )
919
+ ERROR_ACCESS_DENIED = psutil._psplatform.cext.ERROR_ACCESS_DENIED
920
+
921
+ name = next(psutil.win_service_iter()).name()
922
+ with self.assertRaises(psutil.NoSuchProcess) as cm:
923
+ psutil.win_service_get(name + '???')
924
+ self.assertEqual(cm.exception.name, name + '???')
925
+
926
+ # test NoSuchProcess
927
+ service = psutil.win_service_get(name)
928
+ if PY3:
929
+ args = (0, "msg", 0, ERROR_SERVICE_DOES_NOT_EXIST)
930
+ else:
931
+ args = (ERROR_SERVICE_DOES_NOT_EXIST, "msg")
932
+ exc = WindowsError(*args)
933
+ with mock.patch(
934
+ "psutil._psplatform.cext.winservice_query_status", side_effect=exc
935
+ ):
936
+ self.assertRaises(psutil.NoSuchProcess, service.status)
937
+ with mock.patch(
938
+ "psutil._psplatform.cext.winservice_query_config", side_effect=exc
939
+ ):
940
+ self.assertRaises(psutil.NoSuchProcess, service.username)
941
+
942
+ # test AccessDenied
943
+ if PY3:
944
+ args = (0, "msg", 0, ERROR_ACCESS_DENIED)
945
+ else:
946
+ args = (ERROR_ACCESS_DENIED, "msg")
947
+ exc = WindowsError(*args)
948
+ with mock.patch(
949
+ "psutil._psplatform.cext.winservice_query_status", side_effect=exc
950
+ ):
951
+ self.assertRaises(psutil.AccessDenied, service.status)
952
+ with mock.patch(
953
+ "psutil._psplatform.cext.winservice_query_config", side_effect=exc
954
+ ):
955
+ self.assertRaises(psutil.AccessDenied, service.username)
956
+
957
+ # test __str__ and __repr__
958
+ self.assertIn(service.name(), str(service))
959
+ self.assertIn(service.display_name(), str(service))
960
+ self.assertIn(service.name(), repr(service))
961
+ self.assertIn(service.display_name(), repr(service))
962
+
963
+
964
+ if __name__ == '__main__':
965
+ from psutil.tests.runner import run_from_name
966
+
967
+ run_from_name(__file__)
venv/lib/python3.10/site-packages/rouge_score/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The rouge_score Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
venv/lib/python3.10/site-packages/rouge_score/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (179 Bytes). View file
 
venv/lib/python3.10/site-packages/rouge_score/__pycache__/create_pyrouge_files.cpython-310.pyc ADDED
Binary file (2.27 kB). View file
 
venv/lib/python3.10/site-packages/rouge_score/__pycache__/io.cpython-310.pyc ADDED
Binary file (5.32 kB). View file
 
venv/lib/python3.10/site-packages/rouge_score/__pycache__/io_test.cpython-310.pyc ADDED
Binary file (3.47 kB). View file