/
test_process.py
executable file
·1636 lines (1476 loc) · 60.1 KB
/
test_process.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for psutil.Process class."""
import collections
import errno
import getpass
import itertools
import os
import signal
import socket
import stat
import subprocess
import sys
import textwrap
import time
import types
import unittest
import psutil
from psutil import AIX
from psutil import BSD
from psutil import LINUX
from psutil import MACOS
from psutil import NETBSD
from psutil import OPENBSD
from psutil import OSX
from psutil import POSIX
from psutil import SUNOS
from psutil import WINDOWS
from psutil._common import open_text
from psutil._compat import PY3
from psutil._compat import FileNotFoundError
from psutil._compat import long
from psutil._compat import super
from psutil.tests import APPVEYOR
from psutil.tests import CI_TESTING
from psutil.tests import GITHUB_ACTIONS
from psutil.tests import GLOBAL_TIMEOUT
from psutil.tests import HAS_CPU_AFFINITY
from psutil.tests import HAS_ENVIRON
from psutil.tests import HAS_IONICE
from psutil.tests import HAS_MEMORY_MAPS
from psutil.tests import HAS_PROC_CPU_NUM
from psutil.tests import HAS_PROC_IO_COUNTERS
from psutil.tests import HAS_RLIMIT
from psutil.tests import HAS_THREADS
from psutil.tests import MACOS_11PLUS
from psutil.tests import PYPY
from psutil.tests import PYTHON_EXE
from psutil.tests import PYTHON_EXE_ENV
from psutil.tests import PsutilTestCase
from psutil.tests import ThreadTask
from psutil.tests import call_until
from psutil.tests import copyload_shared_lib
from psutil.tests import create_c_exe
from psutil.tests import create_py_exe
from psutil.tests import mock
from psutil.tests import process_namespace
from psutil.tests import reap_children
from psutil.tests import retry_on_failure
from psutil.tests import sh
from psutil.tests import skip_on_access_denied
from psutil.tests import skip_on_not_implemented
from psutil.tests import wait_for_pid
# ===================================================================
# --- psutil.Process class tests
# ===================================================================
class TestProcess(PsutilTestCase):
"""Tests for psutil.Process class."""
def spawn_psproc(self, *args, **kwargs):
sproc = self.spawn_testproc(*args, **kwargs)
try:
return psutil.Process(sproc.pid)
except psutil.NoSuchProcess:
self.assertPidGone(sproc.pid)
raise
# ---
def test_pid(self):
p = psutil.Process()
self.assertEqual(p.pid, os.getpid())
with self.assertRaises(AttributeError):
p.pid = 33
def test_kill(self):
p = self.spawn_psproc()
p.kill()
code = p.wait()
if WINDOWS:
self.assertEqual(code, signal.SIGTERM)
else:
self.assertEqual(code, -signal.SIGKILL)
self.assertProcessGone(p)
def test_terminate(self):
p = self.spawn_psproc()
p.terminate()
code = p.wait()
if WINDOWS:
self.assertEqual(code, signal.SIGTERM)
else:
self.assertEqual(code, -signal.SIGTERM)
self.assertProcessGone(p)
def test_send_signal(self):
sig = signal.SIGKILL if POSIX else signal.SIGTERM
p = self.spawn_psproc()
p.send_signal(sig)
code = p.wait()
if WINDOWS:
self.assertEqual(code, sig)
else:
self.assertEqual(code, -sig)
self.assertProcessGone(p)
@unittest.skipIf(not POSIX, "not POSIX")
def test_send_signal_mocked(self):
sig = signal.SIGTERM
p = self.spawn_psproc()
with mock.patch(
'psutil.os.kill', side_effect=OSError(errno.ESRCH, "")
):
self.assertRaises(psutil.NoSuchProcess, p.send_signal, sig)
p = self.spawn_psproc()
with mock.patch(
'psutil.os.kill', side_effect=OSError(errno.EPERM, "")
):
self.assertRaises(psutil.AccessDenied, p.send_signal, sig)
def test_wait_exited(self):
# Test waitpid() + WIFEXITED -> WEXITSTATUS.
# normal return, same as exit(0)
cmd = [PYTHON_EXE, "-c", "pass"]
p = self.spawn_psproc(cmd)
code = p.wait()
self.assertEqual(code, 0)
self.assertProcessGone(p)
# exit(1), implicit in case of error
cmd = [PYTHON_EXE, "-c", "1 / 0"]
p = self.spawn_psproc(cmd, stderr=subprocess.PIPE)
code = p.wait()
self.assertEqual(code, 1)
self.assertProcessGone(p)
# via sys.exit()
cmd = [PYTHON_EXE, "-c", "import sys; sys.exit(5);"]
p = self.spawn_psproc(cmd)
code = p.wait()
self.assertEqual(code, 5)
self.assertProcessGone(p)
# via os._exit()
cmd = [PYTHON_EXE, "-c", "import os; os._exit(5);"]
p = self.spawn_psproc(cmd)
code = p.wait()
self.assertEqual(code, 5)
self.assertProcessGone(p)
@unittest.skipIf(NETBSD, "fails on NETBSD")
def test_wait_stopped(self):
p = self.spawn_psproc()
if POSIX:
# Test waitpid() + WIFSTOPPED and WIFCONTINUED.
# Note: if a process is stopped it ignores SIGTERM.
p.send_signal(signal.SIGSTOP)
self.assertRaises(psutil.TimeoutExpired, p.wait, timeout=0.001)
p.send_signal(signal.SIGCONT)
self.assertRaises(psutil.TimeoutExpired, p.wait, timeout=0.001)
p.send_signal(signal.SIGTERM)
self.assertEqual(p.wait(), -signal.SIGTERM)
self.assertEqual(p.wait(), -signal.SIGTERM)
else:
p.suspend()
self.assertRaises(psutil.TimeoutExpired, p.wait, timeout=0.001)
p.resume()
self.assertRaises(psutil.TimeoutExpired, p.wait, timeout=0.001)
p.terminate()
self.assertEqual(p.wait(), signal.SIGTERM)
self.assertEqual(p.wait(), signal.SIGTERM)
def test_wait_non_children(self):
# Test wait() against a process which is not our direct
# child.
child, grandchild = self.spawn_children_pair()
self.assertRaises(psutil.TimeoutExpired, child.wait, 0.01)
self.assertRaises(psutil.TimeoutExpired, grandchild.wait, 0.01)
# We also terminate the direct child otherwise the
# grandchild will hang until the parent is gone.
child.terminate()
grandchild.terminate()
child_ret = child.wait()
grandchild_ret = grandchild.wait()
if POSIX:
self.assertEqual(child_ret, -signal.SIGTERM)
# For processes which are not our children we're supposed
# to get None.
self.assertEqual(grandchild_ret, None)
else:
self.assertEqual(child_ret, signal.SIGTERM)
self.assertEqual(child_ret, signal.SIGTERM)
def test_wait_timeout(self):
p = self.spawn_psproc()
p.name()
self.assertRaises(psutil.TimeoutExpired, p.wait, 0.01)
self.assertRaises(psutil.TimeoutExpired, p.wait, 0)
self.assertRaises(ValueError, p.wait, -1)
def test_wait_timeout_nonblocking(self):
p = self.spawn_psproc()
self.assertRaises(psutil.TimeoutExpired, p.wait, 0)
p.kill()
stop_at = time.time() + GLOBAL_TIMEOUT
while time.time() < stop_at:
try:
code = p.wait(0)
break
except psutil.TimeoutExpired:
pass
else:
raise self.fail('timeout')
if POSIX:
self.assertEqual(code, -signal.SIGKILL)
else:
self.assertEqual(code, signal.SIGTERM)
self.assertProcessGone(p)
def test_cpu_percent(self):
p = psutil.Process()
p.cpu_percent(interval=0.001)
p.cpu_percent(interval=0.001)
for _ in range(100):
percent = p.cpu_percent(interval=None)
self.assertIsInstance(percent, float)
self.assertGreaterEqual(percent, 0.0)
with self.assertRaises(ValueError):
p.cpu_percent(interval=-1)
def test_cpu_percent_numcpus_none(self):
# See: https://github.com/giampaolo/psutil/issues/1087
with mock.patch('psutil.cpu_count', return_value=None) as m:
psutil.Process().cpu_percent()
assert m.called
def test_cpu_times(self):
times = psutil.Process().cpu_times()
assert (times.user > 0.0) or (times.system > 0.0), times
assert times.children_user >= 0.0, times
assert times.children_system >= 0.0, times
if LINUX:
assert times.iowait >= 0.0, times
# make sure returned values can be pretty printed with strftime
for name in times._fields:
time.strftime("%H:%M:%S", time.localtime(getattr(times, name)))
def test_cpu_times_2(self):
user_time, kernel_time = psutil.Process().cpu_times()[:2]
utime, ktime = os.times()[:2]
# Use os.times()[:2] as base values to compare our results
# using a tolerance of +/- 0.1 seconds.
# It will fail if the difference between the values is > 0.1s.
if (max([user_time, utime]) - min([user_time, utime])) > 0.1:
raise self.fail("expected: %s, found: %s" % (utime, user_time))
if (max([kernel_time, ktime]) - min([kernel_time, ktime])) > 0.1:
raise self.fail("expected: %s, found: %s" % (ktime, kernel_time))
@unittest.skipIf(not HAS_PROC_CPU_NUM, "not supported")
def test_cpu_num(self):
p = psutil.Process()
num = p.cpu_num()
self.assertGreaterEqual(num, 0)
if psutil.cpu_count() == 1:
self.assertEqual(num, 0)
self.assertIn(p.cpu_num(), range(psutil.cpu_count()))
def test_create_time(self):
p = self.spawn_psproc()
now = time.time()
create_time = p.create_time()
# Use time.time() as base value to compare our result using a
# tolerance of +/- 1 second.
# It will fail if the difference between the values is > 2s.
difference = abs(create_time - now)
if difference > 2:
raise self.fail(
"expected: %s, found: %s, difference: %s"
% (now, create_time, difference)
)
# make sure returned value can be pretty printed with strftime
time.strftime("%Y %m %d %H:%M:%S", time.localtime(p.create_time()))
@unittest.skipIf(not POSIX, 'POSIX only')
def test_terminal(self):
terminal = psutil.Process().terminal()
if terminal is not None:
tty = os.path.realpath(sh('tty'))
self.assertEqual(terminal, tty)
@unittest.skipIf(not HAS_PROC_IO_COUNTERS, 'not supported')
@skip_on_not_implemented(only_if=LINUX)
def test_io_counters(self):
p = psutil.Process()
# test reads
io1 = p.io_counters()
with open(PYTHON_EXE, 'rb') as f:
f.read()
io2 = p.io_counters()
if not BSD and not AIX:
self.assertGreater(io2.read_count, io1.read_count)
self.assertEqual(io2.write_count, io1.write_count)
if LINUX:
self.assertGreater(io2.read_chars, io1.read_chars)
self.assertEqual(io2.write_chars, io1.write_chars)
else:
self.assertGreaterEqual(io2.read_bytes, io1.read_bytes)
self.assertGreaterEqual(io2.write_bytes, io1.write_bytes)
# test writes
io1 = p.io_counters()
with open(self.get_testfn(), 'wb') as f:
if PY3:
f.write(bytes("x" * 1000000, 'ascii'))
else:
f.write("x" * 1000000)
io2 = p.io_counters()
self.assertGreaterEqual(io2.write_count, io1.write_count)
self.assertGreaterEqual(io2.write_bytes, io1.write_bytes)
self.assertGreaterEqual(io2.read_count, io1.read_count)
self.assertGreaterEqual(io2.read_bytes, io1.read_bytes)
if LINUX:
self.assertGreater(io2.write_chars, io1.write_chars)
self.assertGreaterEqual(io2.read_chars, io1.read_chars)
# sanity check
for i in range(len(io2)):
if BSD and i >= 2:
# On BSD read_bytes and write_bytes are always set to -1.
continue
self.assertGreaterEqual(io2[i], 0)
self.assertGreaterEqual(io2[i], 0)
@unittest.skipIf(not HAS_IONICE, "not supported")
@unittest.skipIf(not LINUX, "linux only")
def test_ionice_linux(self):
def cleanup(init):
ioclass, value = init
if ioclass == psutil.IOPRIO_CLASS_NONE:
value = 0
p.ionice(ioclass, value)
p = psutil.Process()
if not CI_TESTING:
self.assertEqual(p.ionice()[0], psutil.IOPRIO_CLASS_NONE)
self.assertEqual(psutil.IOPRIO_CLASS_NONE, 0)
self.assertEqual(psutil.IOPRIO_CLASS_RT, 1) # high
self.assertEqual(psutil.IOPRIO_CLASS_BE, 2) # normal
self.assertEqual(psutil.IOPRIO_CLASS_IDLE, 3) # low
init = p.ionice()
self.addCleanup(cleanup, init)
# low
p.ionice(psutil.IOPRIO_CLASS_IDLE)
self.assertEqual(tuple(p.ionice()), (psutil.IOPRIO_CLASS_IDLE, 0))
with self.assertRaises(ValueError): # accepts no value
p.ionice(psutil.IOPRIO_CLASS_IDLE, value=7)
# normal
p.ionice(psutil.IOPRIO_CLASS_BE)
self.assertEqual(tuple(p.ionice()), (psutil.IOPRIO_CLASS_BE, 0))
p.ionice(psutil.IOPRIO_CLASS_BE, value=7)
self.assertEqual(tuple(p.ionice()), (psutil.IOPRIO_CLASS_BE, 7))
with self.assertRaises(ValueError):
p.ionice(psutil.IOPRIO_CLASS_BE, value=8)
try:
p.ionice(psutil.IOPRIO_CLASS_RT, value=7)
except psutil.AccessDenied:
pass
# errs
with self.assertRaisesRegex(ValueError, "ioclass accepts no value"):
p.ionice(psutil.IOPRIO_CLASS_NONE, 1)
with self.assertRaisesRegex(ValueError, "ioclass accepts no value"):
p.ionice(psutil.IOPRIO_CLASS_IDLE, 1)
with self.assertRaisesRegex(
ValueError, "'ioclass' argument must be specified"
):
p.ionice(value=1)
@unittest.skipIf(not HAS_IONICE, "not supported")
@unittest.skipIf(not WINDOWS, 'not supported on this win version')
def test_ionice_win(self):
p = psutil.Process()
if not CI_TESTING:
self.assertEqual(p.ionice(), psutil.IOPRIO_NORMAL)
init = p.ionice()
self.addCleanup(p.ionice, init)
# base
p.ionice(psutil.IOPRIO_VERYLOW)
self.assertEqual(p.ionice(), psutil.IOPRIO_VERYLOW)
p.ionice(psutil.IOPRIO_LOW)
self.assertEqual(p.ionice(), psutil.IOPRIO_LOW)
try:
p.ionice(psutil.IOPRIO_HIGH)
except psutil.AccessDenied:
pass
else:
self.assertEqual(p.ionice(), psutil.IOPRIO_HIGH)
# errs
with self.assertRaisesRegex(
TypeError, "value argument not accepted on Windows"
):
p.ionice(psutil.IOPRIO_NORMAL, value=1)
with self.assertRaisesRegex(ValueError, "is not a valid priority"):
p.ionice(psutil.IOPRIO_HIGH + 1)
@unittest.skipIf(not HAS_RLIMIT, "not supported")
def test_rlimit_get(self):
import resource
p = psutil.Process(os.getpid())
names = [x for x in dir(psutil) if x.startswith('RLIMIT')]
assert names, names
for name in names:
value = getattr(psutil, name)
self.assertGreaterEqual(value, 0)
if name in dir(resource):
self.assertEqual(value, getattr(resource, name))
# XXX - On PyPy RLIMIT_INFINITY returned by
# resource.getrlimit() is reported as a very big long
# number instead of -1. It looks like a bug with PyPy.
if PYPY:
continue
self.assertEqual(p.rlimit(value), resource.getrlimit(value))
else:
ret = p.rlimit(value)
self.assertEqual(len(ret), 2)
self.assertGreaterEqual(ret[0], -1)
self.assertGreaterEqual(ret[1], -1)
@unittest.skipIf(not HAS_RLIMIT, "not supported")
def test_rlimit_set(self):
p = self.spawn_psproc()
p.rlimit(psutil.RLIMIT_NOFILE, (5, 5))
self.assertEqual(p.rlimit(psutil.RLIMIT_NOFILE), (5, 5))
# If pid is 0 prlimit() applies to the calling process and
# we don't want that.
if LINUX:
with self.assertRaisesRegex(ValueError, "can't use prlimit"):
psutil._psplatform.Process(0).rlimit(0)
with self.assertRaises(ValueError):
p.rlimit(psutil.RLIMIT_NOFILE, (5, 5, 5))
@unittest.skipIf(not HAS_RLIMIT, "not supported")
def test_rlimit(self):
p = psutil.Process()
testfn = self.get_testfn()
soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
try:
p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard))
with open(testfn, "wb") as f:
f.write(b"X" * 1024)
# write() or flush() doesn't always cause the exception
# but close() will.
with self.assertRaises(IOError) as exc:
with open(testfn, "wb") as f:
f.write(b"X" * 1025)
self.assertEqual(
exc.exception.errno if PY3 else exc.exception[0], errno.EFBIG
)
finally:
p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard))
@unittest.skipIf(not HAS_RLIMIT, "not supported")
def test_rlimit_infinity(self):
# First set a limit, then re-set it by specifying INFINITY
# and assume we overridden the previous limit.
p = psutil.Process()
soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
try:
p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard))
p.rlimit(psutil.RLIMIT_FSIZE, (psutil.RLIM_INFINITY, hard))
with open(self.get_testfn(), "wb") as f:
f.write(b"X" * 2048)
finally:
p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard))
@unittest.skipIf(not HAS_RLIMIT, "not supported")
def test_rlimit_infinity_value(self):
# RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really
# big number on a platform with large file support. On these
# platforms we need to test that the get/setrlimit functions
# properly convert the number to a C long long and that the
# conversion doesn't raise an error.
p = psutil.Process()
soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
self.assertEqual(psutil.RLIM_INFINITY, hard)
p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
def test_num_threads(self):
# on certain platforms such as Linux we might test for exact
# thread number, since we always have with 1 thread per process,
# but this does not apply across all platforms (MACOS, Windows)
p = psutil.Process()
if OPENBSD:
try:
step1 = p.num_threads()
except psutil.AccessDenied:
raise unittest.SkipTest("on OpenBSD this requires root access")
else:
step1 = p.num_threads()
with ThreadTask():
step2 = p.num_threads()
self.assertEqual(step2, step1 + 1)
@unittest.skipIf(not WINDOWS, 'WINDOWS only')
def test_num_handles(self):
# a better test is done later into test/_windows.py
p = psutil.Process()
self.assertGreater(p.num_handles(), 0)
@unittest.skipIf(not HAS_THREADS, 'not supported')
def test_threads(self):
p = psutil.Process()
if OPENBSD:
try:
step1 = p.threads()
except psutil.AccessDenied:
raise unittest.SkipTest("on OpenBSD this requires root access")
else:
step1 = p.threads()
with ThreadTask():
step2 = p.threads()
self.assertEqual(len(step2), len(step1) + 1)
athread = step2[0]
# test named tuple
self.assertEqual(athread.id, athread[0])
self.assertEqual(athread.user_time, athread[1])
self.assertEqual(athread.system_time, athread[2])
@retry_on_failure()
@skip_on_access_denied(only_if=MACOS)
@unittest.skipIf(not HAS_THREADS, 'not supported')
def test_threads_2(self):
p = self.spawn_psproc()
if OPENBSD:
try:
p.threads()
except psutil.AccessDenied:
raise unittest.SkipTest("on OpenBSD this requires root access")
self.assertAlmostEqual(
p.cpu_times().user,
sum([x.user_time for x in p.threads()]),
delta=0.1,
)
self.assertAlmostEqual(
p.cpu_times().system,
sum([x.system_time for x in p.threads()]),
delta=0.1,
)
@retry_on_failure()
def test_memory_info(self):
p = psutil.Process()
# step 1 - get a base value to compare our results
rss1, vms1 = p.memory_info()[:2]
percent1 = p.memory_percent()
self.assertGreater(rss1, 0)
self.assertGreater(vms1, 0)
# step 2 - allocate some memory
memarr = [None] * 1500000
rss2, vms2 = p.memory_info()[:2]
percent2 = p.memory_percent()
# step 3 - make sure that the memory usage bumped up
self.assertGreater(rss2, rss1)
self.assertGreaterEqual(vms2, vms1) # vms might be equal
self.assertGreater(percent2, percent1)
del memarr
if WINDOWS:
mem = p.memory_info()
self.assertEqual(mem.rss, mem.wset)
self.assertEqual(mem.vms, mem.pagefile)
mem = p.memory_info()
for name in mem._fields:
self.assertGreaterEqual(getattr(mem, name), 0)
def test_memory_full_info(self):
p = psutil.Process()
total = psutil.virtual_memory().total
mem = p.memory_full_info()
for name in mem._fields:
value = getattr(mem, name)
self.assertGreaterEqual(value, 0, msg=(name, value))
if name == 'vms' and OSX or LINUX:
continue
self.assertLessEqual(value, total, msg=(name, value, total))
if LINUX or WINDOWS or MACOS:
self.assertGreaterEqual(mem.uss, 0)
if LINUX:
self.assertGreaterEqual(mem.pss, 0)
self.assertGreaterEqual(mem.swap, 0)
@unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
def test_memory_maps(self):
p = psutil.Process()
maps = p.memory_maps()
self.assertEqual(len(maps), len(set(maps)))
ext_maps = p.memory_maps(grouped=False)
for nt in maps:
if not nt.path.startswith('['):
assert os.path.isabs(nt.path), nt.path
if POSIX:
try:
assert os.path.exists(nt.path) or os.path.islink(
nt.path
), nt.path
except AssertionError:
if not LINUX:
raise
else:
# https://github.com/giampaolo/psutil/issues/759
with open_text('/proc/self/smaps') as f:
data = f.read()
if "%s (deleted)" % nt.path not in data:
raise
else:
# XXX - On Windows we have this strange behavior with
# 64 bit dlls: they are visible via explorer but cannot
# be accessed via os.stat() (wtf?).
if '64' not in os.path.basename(nt.path):
try:
st = os.stat(nt.path)
except FileNotFoundError:
pass
else:
assert stat.S_ISREG(st.st_mode), nt.path
for nt in ext_maps:
for fname in nt._fields:
value = getattr(nt, fname)
if fname == 'path':
continue
if fname in ('addr', 'perms'):
assert value, value
else:
self.assertIsInstance(value, (int, long))
assert value >= 0, value
@unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
def test_memory_maps_lists_lib(self):
# Make sure a newly loaded shared lib is listed.
p = psutil.Process()
with copyload_shared_lib() as path:
def normpath(p):
return os.path.realpath(os.path.normcase(p))
libpaths = [normpath(x.path) for x in p.memory_maps()]
self.assertIn(normpath(path), libpaths)
def test_memory_percent(self):
p = psutil.Process()
p.memory_percent()
self.assertRaises(ValueError, p.memory_percent, memtype="?!?")
if LINUX or MACOS or WINDOWS:
p.memory_percent(memtype='uss')
def test_is_running(self):
p = self.spawn_psproc()
assert p.is_running()
assert p.is_running()
p.kill()
p.wait()
assert not p.is_running()
assert not p.is_running()
def test_exe(self):
p = self.spawn_psproc()
exe = p.exe()
try:
self.assertEqual(exe, PYTHON_EXE)
except AssertionError:
if WINDOWS and len(exe) == len(PYTHON_EXE):
# on Windows we don't care about case sensitivity
normcase = os.path.normcase
self.assertEqual(normcase(exe), normcase(PYTHON_EXE))
else:
# certain platforms such as BSD are more accurate returning:
# "/usr/local/bin/python2.7"
# ...instead of:
# "/usr/local/bin/python"
# We do not want to consider this difference in accuracy
# an error.
ver = "%s.%s" % (sys.version_info[0], sys.version_info[1])
try:
self.assertEqual(
exe.replace(ver, ''), PYTHON_EXE.replace(ver, '')
)
except AssertionError:
# Typically MACOS. Really not sure what to do here.
pass
out = sh([exe, "-c", "import os; print('hey')"])
self.assertEqual(out, 'hey')
def test_cmdline(self):
cmdline = [PYTHON_EXE, "-c", "import time; time.sleep(60)"]
p = self.spawn_psproc(cmdline)
# XXX - most of the times the underlying sysctl() call on Net
# and Open BSD returns a truncated string.
# Also /proc/pid/cmdline behaves the same so it looks
# like this is a kernel bug.
# XXX - AIX truncates long arguments in /proc/pid/cmdline
if NETBSD or OPENBSD or AIX:
self.assertEqual(p.cmdline()[0], PYTHON_EXE)
else:
if MACOS and CI_TESTING:
pyexe = p.cmdline()[0]
if pyexe != PYTHON_EXE:
self.assertEqual(
' '.join(p.cmdline()[1:]), ' '.join(cmdline[1:])
)
return
self.assertEqual(' '.join(p.cmdline()), ' '.join(cmdline))
@unittest.skipIf(PYPY, "broken on PYPY")
def test_long_cmdline(self):
cmdline = [PYTHON_EXE]
cmdline.extend(["-v"] * 50)
cmdline.extend(["-c", "time.sleep(10)"])
p = self.spawn_psproc(cmdline)
if OPENBSD:
# XXX: for some reason the test process may turn into a
# zombie (don't know why).
try:
self.assertEqual(p.cmdline(), cmdline)
except psutil.ZombieProcess:
raise self.skipTest("OPENBSD: process turned into zombie")
else:
self.assertEqual(p.cmdline(), cmdline)
def test_name(self):
p = self.spawn_psproc(PYTHON_EXE)
name = p.name().lower()
pyexe = os.path.basename(os.path.realpath(sys.executable)).lower()
assert pyexe.startswith(name), (pyexe, name)
@unittest.skipIf(PYPY, "unreliable on PYPY")
def test_long_name(self):
pyexe = create_py_exe(self.get_testfn(suffix="0123456789" * 2))
cmdline = [pyexe, "-c", "time.sleep(10)"]
p = self.spawn_psproc(cmdline)
if OPENBSD:
# XXX: for some reason the test process may turn into a
# zombie (don't know why). Because the name() is long, all
# UNIX kernels truncate it to 15 chars, so internally psutil
# tries to guess the full name() from the cmdline(). But the
# cmdline() of a zombie on OpenBSD fails (internally), so we
# just compare the first 15 chars. Full explanation:
# https://github.com/giampaolo/psutil/issues/2239
try:
self.assertEqual(p.name(), os.path.basename(pyexe))
except AssertionError:
if p.status() == psutil.STATUS_ZOMBIE:
assert os.path.basename(pyexe).startswith(p.name())
else:
raise
else:
self.assertEqual(p.name(), os.path.basename(pyexe))
# XXX
@unittest.skipIf(SUNOS, "broken on SUNOS")
@unittest.skipIf(AIX, "broken on AIX")
@unittest.skipIf(PYPY, "broken on PYPY")
def test_prog_w_funky_name(self):
# Test that name(), exe() and cmdline() correctly handle programs
# with funky chars such as spaces and ")", see:
# https://github.com/giampaolo/psutil/issues/628
pyexe = create_py_exe(self.get_testfn(suffix='foo bar )'))
cmdline = [pyexe, "-c", "time.sleep(10)"]
p = self.spawn_psproc(cmdline)
self.assertEqual(p.cmdline(), cmdline)
self.assertEqual(p.name(), os.path.basename(pyexe))
self.assertEqual(os.path.normcase(p.exe()), os.path.normcase(pyexe))
@unittest.skipIf(not POSIX, 'POSIX only')
def test_uids(self):
p = psutil.Process()
real, effective, saved = p.uids()
# os.getuid() refers to "real" uid
self.assertEqual(real, os.getuid())
# os.geteuid() refers to "effective" uid
self.assertEqual(effective, os.geteuid())
# No such thing as os.getsuid() ("saved" uid), but starting
# from python 2.7 we have os.getresuid() which returns all
# of them.
if hasattr(os, "getresuid"):
self.assertEqual(os.getresuid(), p.uids())
@unittest.skipIf(not POSIX, 'POSIX only')
def test_gids(self):
p = psutil.Process()
real, effective, saved = p.gids()
# os.getuid() refers to "real" uid
self.assertEqual(real, os.getgid())
# os.geteuid() refers to "effective" uid
self.assertEqual(effective, os.getegid())
# No such thing as os.getsgid() ("saved" gid), but starting
# from python 2.7 we have os.getresgid() which returns all
# of them.
if hasattr(os, "getresuid"):
self.assertEqual(os.getresgid(), p.gids())
def test_nice(self):
def cleanup(init):
try:
p.nice(init)
except psutil.AccessDenied:
pass
p = psutil.Process()
self.assertRaises(TypeError, p.nice, "str")
init = p.nice()
self.addCleanup(cleanup, init)
if WINDOWS:
highest_prio = None
for prio in [
psutil.IDLE_PRIORITY_CLASS,
psutil.BELOW_NORMAL_PRIORITY_CLASS,
psutil.NORMAL_PRIORITY_CLASS,
psutil.ABOVE_NORMAL_PRIORITY_CLASS,
psutil.HIGH_PRIORITY_CLASS,
psutil.REALTIME_PRIORITY_CLASS,
]:
with self.subTest(prio=prio):
try:
p.nice(prio)
except psutil.AccessDenied:
pass
else:
new_prio = p.nice()
# The OS may limit our maximum priority,
# even if the function succeeds. For higher
# priorities, we match either the expected
# value or the highest so far.
if prio in (
psutil.ABOVE_NORMAL_PRIORITY_CLASS,
psutil.HIGH_PRIORITY_CLASS,
psutil.REALTIME_PRIORITY_CLASS,
):
if new_prio == prio or highest_prio is None:
highest_prio = prio
self.assertEqual(new_prio, highest_prio)
else:
self.assertEqual(new_prio, prio)
else:
try:
if hasattr(os, "getpriority"):
self.assertEqual(
os.getpriority(os.PRIO_PROCESS, os.getpid()), p.nice()
)
p.nice(1)
self.assertEqual(p.nice(), 1)
if hasattr(os, "getpriority"):
self.assertEqual(
os.getpriority(os.PRIO_PROCESS, os.getpid()), p.nice()
)
# XXX - going back to previous nice value raises
# AccessDenied on MACOS
if not MACOS:
p.nice(0)
self.assertEqual(p.nice(), 0)
except psutil.AccessDenied:
pass
def test_status(self):
p = psutil.Process()
self.assertEqual(p.status(), psutil.STATUS_RUNNING)
def test_username(self):
p = self.spawn_psproc()
username = p.username()
if WINDOWS:
domain, username = username.split('\\')
getpass_user = getpass.getuser()
if getpass_user.endswith('$'):
# When running as a service account (most likely to be
# NetworkService), these user name calculations don't produce
# the same result, causing the test to fail.
raise unittest.SkipTest('running as service account')
self.assertEqual(username, getpass_user)
if 'USERDOMAIN' in os.environ:
self.assertEqual(domain, os.environ['USERDOMAIN'])
else:
self.assertEqual(username, getpass.getuser())
def test_cwd(self):
p = self.spawn_psproc()
self.assertEqual(p.cwd(), os.getcwd())
def test_cwd_2(self):
cmd = [
PYTHON_EXE,
"-c",
"import os, time; os.chdir('..'); time.sleep(60)",
]
p = self.spawn_psproc(cmd)
call_until(p.cwd, "ret == os.path.dirname(os.getcwd())")
@unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
def test_cpu_affinity(self):
p = psutil.Process()
initial = p.cpu_affinity()
assert initial, initial
self.addCleanup(p.cpu_affinity, initial)
if hasattr(os, "sched_getaffinity"):
self.assertEqual(initial, list(os.sched_getaffinity(p.pid)))
self.assertEqual(len(initial), len(set(initial)))
all_cpus = list(range(len(psutil.cpu_percent(percpu=True))))
for n in all_cpus:
p.cpu_affinity([n])
self.assertEqual(p.cpu_affinity(), [n])
if hasattr(os, "sched_getaffinity"):
self.assertEqual(
p.cpu_affinity(), list(os.sched_getaffinity(p.pid))
)
# also test num_cpu()
if hasattr(p, "num_cpu"):
self.assertEqual(p.cpu_affinity()[0], p.num_cpu())
# [] is an alias for "all eligible CPUs"; on Linux this may
# not be equal to all available CPUs, see:
# https://github.com/giampaolo/psutil/issues/956
p.cpu_affinity([])
if LINUX:
self.assertEqual(p.cpu_affinity(), p._proc._get_eligible_cpus())
else:
self.assertEqual(p.cpu_affinity(), all_cpus)
if hasattr(os, "sched_getaffinity"):
self.assertEqual(
p.cpu_affinity(), list(os.sched_getaffinity(p.pid))
)
#
self.assertRaises(TypeError, p.cpu_affinity, 1)
p.cpu_affinity(initial)
# it should work with all iterables, not only lists
p.cpu_affinity(set(all_cpus))
p.cpu_affinity(tuple(all_cpus))
@unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
def test_cpu_affinity_errs(self):
p = self.spawn_psproc()
invalid_cpu = [len(psutil.cpu_times(percpu=True)) + 10]
self.assertRaises(ValueError, p.cpu_affinity, invalid_cpu)
self.assertRaises(ValueError, p.cpu_affinity, range(10000, 11000))
self.assertRaises(TypeError, p.cpu_affinity, [0, "1"])
self.assertRaises(ValueError, p.cpu_affinity, [0, -1])
@unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
def test_cpu_affinity_all_combinations(self):
p = psutil.Process()
initial = p.cpu_affinity()
assert initial, initial
self.addCleanup(p.cpu_affinity, initial)
# All possible CPU set combinations.
if len(initial) > 12:
initial = initial[:12] # ...otherwise it will take forever
combos = []
for i in range(len(initial) + 1):
for subset in itertools.combinations(initial, i):
if subset:
combos.append(list(subset))
for combo in combos: