#!/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.
"""Linux specific tests."""
from __future__ import division
import collections
import contextlib
import errno
import glob
import io
import os
import re
import shutil
import socket
import struct
import textwrap
import time
import unittest
import warnings
import psutil
from psutil import LINUX
from psutil._compat import PY3
from psutil._compat import FileNotFoundError
from psutil._compat import basestring
from psutil._compat import u
from psutil.tests import GITHUB_ACTIONS
from psutil.tests import GLOBAL_TIMEOUT
from psutil.tests import HAS_BATTERY
from psutil.tests import HAS_CPU_FREQ
from psutil.tests import HAS_GETLOADAVG
from psutil.tests import HAS_RLIMIT
from psutil.tests import PYPY
from psutil.tests import TOLERANCE_DISK_USAGE
from psutil.tests import TOLERANCE_SYS_MEM
from psutil.tests import PsutilTestCase
from psutil.tests import ThreadTask
from psutil.tests import call_until
from psutil.tests import mock
from psutil.tests import reload_module
from psutil.tests import retry_on_failure
from psutil.tests import safe_rmpath
from psutil.tests import sh
from psutil.tests import skip_on_not_implemented
from psutil.tests import which
if LINUX:
from psutil._pslinux import CLOCK_TICKS
from psutil._pslinux import RootFsDeviceFinder
from psutil._pslinux import calculate_avail_vmem
from psutil._pslinux import open_binary
HERE = os.path.abspath(os.path.dirname(__file__))
SIOCGIFADDR = 0x8915
SIOCGIFCONF = 0x8912
SIOCGIFHWADDR = 0x8927
SIOCGIFNETMASK = 0x891b
SIOCGIFBRDADDR = 0x8919
if LINUX:
SECTOR_SIZE = 512
EMPTY_TEMPERATURES = not glob.glob('/sys/class/hwmon/hwmon*')
# =====================================================================
# --- utils
# =====================================================================
def get_ipv4_address(ifname):
import fcntl
ifname = ifname[:15]
if PY3:
ifname = bytes(ifname, 'ascii')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with contextlib.closing(s):
return socket.inet_ntoa(
fcntl.ioctl(s.fileno(),
SIOCGIFADDR,
struct.pack('256s', ifname))[20:24])
def get_ipv4_netmask(ifname):
import fcntl
ifname = ifname[:15]
if PY3:
ifname = bytes(ifname, 'ascii')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with contextlib.closing(s):
return socket.inet_ntoa(
fcntl.ioctl(s.fileno(),
SIOCGIFNETMASK,
struct.pack('256s', ifname))[20:24])
def get_ipv4_broadcast(ifname):
import fcntl
ifname = ifname[:15]
if PY3:
ifname = bytes(ifname, 'ascii')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with contextlib.closing(s):
return socket.inet_ntoa(
fcntl.ioctl(s.fileno(),
SIOCGIFBRDADDR,
struct.pack('256s', ifname))[20:24])
def get_ipv6_addresses(ifname):
with open("/proc/net/if_inet6", 'rt') as f:
all_fields = []
for line in f.readlines():
fields = line.split()
if fields[-1] == ifname:
all_fields.append(fields)
if len(all_fields) == 0:
raise ValueError("could not find interface %r" % ifname)
for i in range(0, len(all_fields)):
unformatted = all_fields[i][0]
groups = []
for j in range(0, len(unformatted), 4):
groups.append(unformatted[j:j + 4])
formatted = ":".join(groups)
packed = socket.inet_pton(socket.AF_INET6, formatted)
all_fields[i] = socket.inet_ntop(socket.AF_INET6, packed)
return all_fields
def get_mac_address(ifname):
import fcntl
ifname = ifname[:15]
if PY3:
ifname = bytes(ifname, 'ascii')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with contextlib.closing(s):
info = fcntl.ioctl(
s.fileno(), SIOCGIFHWADDR, struct.pack('256s', ifname))
if PY3:
def ord(x):
return x
else:
import __builtin__
ord = __builtin__.ord
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
def free_swap():
"""Parse 'free' cmd and return swap memory's s total, used and free
values.
"""
out = sh(["free", "-b"], env={"LANG": "C.UTF-8"})
lines = out.split('\n')
for line in lines:
if line.startswith('Swap'):
_, total, used, free = line.split()
nt = collections.namedtuple('free', 'total used free')
return nt(int(total), int(used), int(free))
raise ValueError(
"can't find 'Swap' in 'free' output:\n%s" % '\n'.join(lines))
def free_physmem():
"""Parse 'free' cmd and return physical memory's total, used
and free values.
"""
# Note: free can have 2 different formats, invalidating 'shared'
# and 'cached' memory which may have different positions so we
# do not return them.
# https://github.com/giampaolo/psutil/issues/538#issuecomment-57059946
out = sh(["free", "-b"], env={"LANG": "C.UTF-8"})
lines = out.split('\n')
for line in lines:
if line.startswith('Mem'):
total, used, free, shared = \
[int(x) for x in line.split()[1:5]]
nt = collections.namedtuple(
'free', 'total used free shared output')
return nt(total, used, free, shared, out)
raise ValueError(
"can't find 'Mem' in 'free' output:\n%s" % '\n'.join(lines))
def vmstat(stat):
out = sh(["vmstat", "-s"], env={"LANG": "C.UTF-8"})
for line in out.split("\n"):
line = line.strip()
if stat in line:
return int(line.split(' ')[0])
raise ValueError("can't find %r in 'vmstat' output" % stat)
def get_free_version_info():
out = sh(["free", "-V"]).strip()
if 'UNKNOWN' in out:
raise unittest.SkipTest("can't determine free version")
return tuple(map(int, re.findall(r'\d+', out.split()[-1])))
@contextlib.contextmanager
def mock_open_content(for_path, content):
"""Mock open() builtin and forces it to return a certain `content`
on read() if the path being opened matches `for_path`.
"""
def open_mock(name, *args, **kwargs):
if name == for_path:
if PY3:
if isinstance(content, basestring):
return io.StringIO(content)
else:
return io.BytesIO(content)
else:
return io.BytesIO(content)
else:
return orig_open(name, *args, **kwargs)
orig_open = open
patch_point = 'builtins.open' if PY3 else '__builtin__.open'
with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
yield m
@contextlib.contextmanager
def mock_open_exception(for_path, exc):
"""Mock open() builtin and raises `exc` if the path being opened
matches `for_path`.
"""
def open_mock(name, *args, **kwargs):
if name == for_path:
raise exc
else:
return orig_open(name, *args, **kwargs)
orig_open = open
patch_point = 'builtins.open' if PY3 else '__builtin__.open'
with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
yield m
# =====================================================================
# --- system virtual memory
# =====================================================================
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemVirtualMemoryAgainstFree(PsutilTestCase):
def test_total(self):
cli_value = free_physmem().total
psutil_value = psutil.virtual_memory().total
self.assertEqual(cli_value, psutil_value)
@retry_on_failure()
def test_used(self):
# Older versions of procps used slab memory to calculate used memory.
# This got changed in:
# https://gitlab.com/procps-ng/procps/commit/
# 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
if get_free_version_info() < (3, 3, 12):
raise self.skipTest("old free version")
cli_value = free_physmem().used
psutil_value = psutil.virtual_memory().used
self.assertAlmostEqual(cli_value, psutil_value,
delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_free(self):
cli_value = free_physmem().free
psutil_value = psutil.virtual_memory().free
self.assertAlmostEqual(cli_value, psutil_value,
delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_shared(self):
free = free_physmem()
free_value = free.shared
if free_value == 0:
raise unittest.SkipTest("free does not support 'shared' column")
psutil_value = psutil.virtual_memory().shared
self.assertAlmostEqual(
free_value, psutil_value, delta=TOLERANCE_SYS_MEM,
msg='%s %s \n%s' % (free_value, psutil_value, free.output))
@retry_on_failure()
def test_available(self):
# "free" output format has changed at some point:
# https://github.com/giampaolo/psutil/issues/538#issuecomment-147192098
out = sh(["free", "-b"])
lines = out.split('\n')
if 'available' not in lines[0]:
raise unittest.SkipTest("free does not support 'available' column")
else:
free_value = int(lines[1].split()[-1])
psutil_value = psutil.virtual_memory().available
self.assertAlmostEqual(
free_value, psutil_value, delta=TOLERANCE_SYS_MEM,
msg='%s %s \n%s' % (free_value, psutil_value, out))
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemVirtualMemoryAgainstVmstat(PsutilTestCase):
def test_total(self):
vmstat_value = vmstat('total memory') * 1024
psutil_value = psutil.virtual_memory().total
self.assertAlmostEqual(
vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_used(self):
# Older versions of procps used slab memory to calculate used memory.
# This got changed in:
# https://gitlab.com/procps-ng/procps/commit/
# 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
if get_free_version_info() < (3, 3, 12):
raise self.skipTest("old free version")
vmstat_value = vmstat('used memory') * 1024
psutil_value = psutil.virtual_memory().used
self.assertAlmostEqual(
vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_free(self):
vmstat_value = vmstat('free memory') * 1024
psutil_value = psutil.virtual_memory().free
self.assertAlmostEqual(
vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_buffers(self):
vmstat_value = vmstat('buffer memory') * 1024
psutil_value = psutil.virtual_memory().buffers
self.assertAlmostEqual(
vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_active(self):
vmstat_value = vmstat('active memory') * 1024
psutil_value = psutil.virtual_memory().active
self.assertAlmostEqual(
vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_inactive(self):
vmstat_value = vmstat('inactive memory') * 1024
psutil_value = psutil.virtual_memory().inactive
self.assertAlmostEqual(
vmstat_value, psutil_value, delta=TOLERANCE_SYS_MEM)
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemVirtualMemoryMocks(PsutilTestCase):
def test_warnings_on_misses(self):
# Emulate a case where /proc/meminfo provides few info.
# psutil is supposed to set the missing fields to 0 and
# raise a warning.
with mock_open_content(
'/proc/meminfo',
textwrap.dedent("""\
Active(anon): 6145416 kB
Active(file): 2950064 kB
Inactive(anon): 574764 kB
Inactive(file): 1567648 kB
MemAvailable: -1 kB
MemFree: 2057400 kB
MemTotal: 16325648 kB
SReclaimable: 346648 kB
""").encode()) as m:
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
ret = psutil.virtual_memory()
assert m.called
self.assertEqual(len(ws), 1)
w = ws[0]
self.assertIn(
"memory stats couldn't be determined", str(w.message))
self.assertIn("cached", str(w.message))
self.assertIn("shared", str(w.message))
self.assertIn("active", str(w.message))
self.assertIn("inactive", str(w.message))
self.assertIn("buffers", str(w.message))
self.assertIn("available", str(w.message))
self.assertEqual(ret.cached, 0)
self.assertEqual(ret.active, 0)
self.assertEqual(ret.inactive, 0)
self.assertEqual(ret.shared, 0)
self.assertEqual(ret.buffers, 0)
self.assertEqual(ret.available, 0)
self.assertEqual(ret.slab, 0)
@retry_on_failure()
def test_avail_old_percent(self):
# Make sure that our calculation of avail mem for old kernels
# is off by max 15%.
mems = {}
with open_binary('/proc/meminfo') as f:
for line in f:
fields = line.split()
mems[fields[0]] = int(fields[1]) * 1024
a = calculate_avail_vmem(mems)
if b'MemAvailable:' in mems:
b = mems[b'MemAvailable:']
diff_percent = abs(a - b) / a * 100
self.assertLess(diff_percent, 15)
def test_avail_old_comes_from_kernel(self):
# Make sure "MemAvailable:" coluimn is used instead of relying
# on our internal algorithm to calculate avail mem.
with mock_open_content(
'/proc/meminfo',
textwrap.dedent("""\
Active: 9444728 kB
Active(anon): 6145416 kB
Active(file): 2950064 kB
Buffers: 287952 kB
Cached: 4818144 kB
Inactive(file): 1578132 kB
Inactive(anon): 574764 kB
Inactive(file): 1567648 kB
MemAvailable: 6574984 kB
MemFree: 2057400 kB
MemTotal: 16325648 kB
Shmem: 577588 kB
SReclaimable: 346648 kB
""").encode()) as m:
with warnings.catch_warnings(record=True) as ws:
ret = psutil.virtual_memory()
assert m.called
self.assertEqual(ret.available, 6574984 * 1024)
w = ws[0]
self.assertIn(
"inactive memory stats couldn't be determined", str(w.message))
def test_avail_old_missing_fields(self):
# Remove Active(file), Inactive(file) and SReclaimable
# from /proc/meminfo and make sure the fallback is used
# (free + cached),
with mock_open_content(
"/proc/meminfo",
textwrap.dedent("""\
Active: 9444728 kB
Active(anon): 6145416 kB
Buffers: 287952 kB
Cached: 4818144 kB
Inactive(file): 1578132 kB
Inactive(anon): 574764 kB
MemFree: 2057400 kB
MemTotal: 16325648 kB
Shmem: 577588 kB
""").encode()) as m:
with warnings.catch_warnings(record=True) as ws:
ret = psutil.virtual_memory()
assert m.called
self.assertEqual(ret.available, 2057400 * 1024 + 4818144 * 1024)
w = ws[0]
self.assertIn(
"inactive memory stats couldn't be determined", str(w.message))
def test_avail_old_missing_zoneinfo(self):
# Remove /proc/zoneinfo file. Make sure fallback is used
# (free + cached).
with mock_open_content(
"/proc/meminfo",
textwrap.dedent("""\
Active: 9444728 kB
Active(anon): 6145416 kB
Active(file): 2950064 kB
Buffers: 287952 kB
Cached: 4818144 kB
Inactive(file): 1578132 kB
Inactive(anon): 574764 kB
Inactive(file): 1567648 kB
MemFree: 2057400 kB
MemTotal: 16325648 kB
Shmem: 577588 kB
SReclaimable: 346648 kB
""").encode()):
with mock_open_exception(
"/proc/zoneinfo",
IOError(errno.ENOENT, 'no such file or directory')):
with warnings.catch_warnings(record=True) as ws:
ret = psutil.virtual_memory()
self.assertEqual(
ret.available, 2057400 * 1024 + 4818144 * 1024)
w = ws[0]
self.assertIn(
"inactive memory stats couldn't be determined",
str(w.message))
def test_virtual_memory_mocked(self):
# Emulate /proc/meminfo because neither vmstat nor free return slab.
def open_mock(name, *args, **kwargs):
if name == '/proc/meminfo':
return io.BytesIO(textwrap.dedent("""\
MemTotal: 100 kB
MemFree: 2 kB
MemAvailable: 3 kB
Buffers: 4 kB
Cached: 5 kB
SwapCached: 6 kB
Active: 7 kB
Inactive: 8 kB
Active(anon): 9 kB
Inactive(anon): 10 kB
Active(file): 11 kB
Inactive(file): 12 kB
Unevictable: 13 kB
Mlocked: 14 kB
SwapTotal: 15 kB
SwapFree: 16 kB
Dirty: 17 kB
Writeback: 18 kB
AnonPages: 19 kB
Mapped: 20 kB
Shmem: 21 kB
Slab: 22 kB
SReclaimable: 23 kB
SUnreclaim: 24 kB
KernelStack: 25 kB
PageTables: 26 kB
NFS_Unstable: 27 kB
Bounce: 28 kB
WritebackTmp: 29 kB
CommitLimit: 30 kB
Committed_AS: 31 kB
VmallocTotal: 32 kB
VmallocUsed: 33 kB
VmallocChunk: 34 kB
HardwareCorrupted: 35 kB
AnonHugePages: 36 kB
ShmemHugePages: 37 kB
ShmemPmdMapped: 38 kB
CmaTotal: 39 kB
CmaFree: 40 kB
HugePages_Total: 41 kB
HugePages_Free: 42 kB
HugePages_Rsvd: 43 kB
HugePages_Surp: 44 kB
Hugepagesize: 45 kB
DirectMap46k: 46 kB
DirectMap47M: 47 kB
DirectMap48G: 48 kB
""").encode())
else:
return orig_open(name, *args, **kwargs)
orig_open = open
patch_point = 'builtins.open' if PY3 else '__builtin__.open'
with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
mem = psutil.virtual_memory()
assert m.called
self.assertEqual(mem.total, 100 * 1024)
self.assertEqual(mem.free, 2 * 1024)
self.assertEqual(mem.buffers, 4 * 1024)
# cached mem also includes reclaimable memory
self.assertEqual(mem.cached, (5 + 23) * 1024)
self.assertEqual(mem.shared, 21 * 1024)
self.assertEqual(mem.active, 7 * 1024)
self.assertEqual(mem.inactive, 8 * 1024)
self.assertEqual(mem.slab, 22 * 1024)
self.assertEqual(mem.available, 3 * 1024)
# =====================================================================
# --- system swap memory
# =====================================================================
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemSwapMemory(PsutilTestCase):
@staticmethod
def meminfo_has_swap_info():
"""Return True if /proc/meminfo provides swap metrics."""
with open("/proc/meminfo") as f:
data = f.read()
return 'SwapTotal:' in data and 'SwapFree:' in data
def test_total(self):
free_value = free_swap().total
psutil_value = psutil.swap_memory().total
return self.assertAlmostEqual(
free_value, psutil_value, delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_used(self):
free_value = free_swap().used
psutil_value = psutil.swap_memory().used
return self.assertAlmostEqual(
free_value, psutil_value, delta=TOLERANCE_SYS_MEM)
@retry_on_failure()
def test_free(self):
free_value = free_swap().free
psutil_value = psutil.swap_memory().free
return self.assertAlmostEqual(
free_value, psutil_value, delta=TOLERANCE_SYS_MEM)
def test_missing_sin_sout(self):
with mock.patch('psutil._common.open', create=True) as m:
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
ret = psutil.swap_memory()
assert m.called
self.assertEqual(len(ws), 1)
w = ws[0]
self.assertIn(
"'sin' and 'sout' swap memory stats couldn't "
"be determined", str(w.message))
self.assertEqual(ret.sin, 0)
self.assertEqual(ret.sout, 0)
def test_no_vmstat_mocked(self):
# see https://github.com/giampaolo/psutil/issues/722
with mock_open_exception(
"/proc/vmstat",
IOError(errno.ENOENT, 'no such file or directory')) as m:
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
ret = psutil.swap_memory()
assert m.called
self.assertEqual(len(ws), 1)
w = ws[0]
self.assertIn(
"'sin' and 'sout' swap memory stats couldn't "
"be determined and were set to 0",
str(w.message))
self.assertEqual(ret.sin, 0)
self.assertEqual(ret.sout, 0)
def test_meminfo_against_sysinfo(self):
# Make sure the content of /proc/meminfo about swap memory
# matches sysinfo() syscall, see:
# https://github.com/giampaolo/psutil/issues/1015
if not self.meminfo_has_swap_info():
return unittest.skip("/proc/meminfo has no swap metrics")
with mock.patch('psutil._pslinux.cext.linux_sysinfo') as m:
swap = psutil.swap_memory()
assert not m.called
import psutil._psutil_linux as cext
_, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
total *= unit_multiplier
free *= unit_multiplier
self.assertEqual(swap.total, total)
self.assertAlmostEqual(swap.free, free, delta=TOLERANCE_SYS_MEM)
def test_emulate_meminfo_has_no_metrics(self):
# Emulate a case where /proc/meminfo provides no swap metrics
# in which case sysinfo() syscall is supposed to be used
# as a fallback.
with mock_open_content("/proc/meminfo", b"") as m:
psutil.swap_memory()
assert m.called
# =====================================================================
# --- system CPU
# =====================================================================
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemCPUTimes(PsutilTestCase):
def test_fields(self):
fields = psutil.cpu_times()._fields
kernel_ver = re.findall(r'\d+\.\d+\.\d+', os.uname()[2])[0]
kernel_ver_info = tuple(map(int, kernel_ver.split('.')))
if kernel_ver_info >= (2, 6, 11):
self.assertIn('steal', fields)
else:
self.assertNotIn('steal', fields)
if kernel_ver_info >= (2, 6, 24):
self.assertIn('guest', fields)
else:
self.assertNotIn('guest', fields)
if kernel_ver_info >= (3, 2, 0):
self.assertIn('guest_nice', fields)
else:
self.assertNotIn('guest_nice', fields)
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemCPUCountLogical(PsutilTestCase):
@unittest.skipIf(not os.path.exists("/sys/devices/system/cpu/online"),
"/sys/devices/system/cpu/online does not exist")
def test_against_sysdev_cpu_online(self):
with open("/sys/devices/system/cpu/online") as f:
value = f.read().strip()
if "-" in str(value):
value = int(value.split('-')[1]) + 1
self.assertEqual(psutil.cpu_count(), value)
@unittest.skipIf(not os.path.exists("/sys/devices/system/cpu"),
"/sys/devices/system/cpu does not exist")
def test_against_sysdev_cpu_num(self):
ls = os.listdir("/sys/devices/system/cpu")
count = len([x for x in ls if re.search(r"cpu\d+$", x) is not None])
self.assertEqual(psutil.cpu_count(), count)
@unittest.skipIf(not which("nproc"), "nproc utility not available")
def test_against_nproc(self):
num = int(sh("nproc --all"))
self.assertEqual(psutil.cpu_count(logical=True), num)
@unittest.skipIf(not which("lscpu"), "lscpu utility not available")
def test_against_lscpu(self):
out = sh("lscpu -p")
num = len([x for x in out.split('\n') if not x.startswith('#')])
self.assertEqual(psutil.cpu_count(logical=True), num)
def test_emulate_fallbacks(self):
import psutil._pslinux
original = psutil._pslinux.cpu_count_logical()
# Here we want to mock os.sysconf("SC_NPROCESSORS_ONLN") in
# order to cause the parsing of /proc/cpuinfo and /proc/stat.
with mock.patch(
'psutil._pslinux.os.sysconf', side_effect=ValueError) as m:
self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
assert m.called
# Let's have open() return empty data and make sure None is
# returned ('cause we mimic os.cpu_count()).
with mock.patch('psutil._common.open', create=True) as m:
self.assertIsNone(psutil._pslinux.cpu_count_logical())
self.assertEqual(m.call_count, 2)
# /proc/stat should be the last one
self.assertEqual(m.call_args[0][0], '/proc/stat')
# Let's push this a bit further and make sure /proc/cpuinfo
# parsing works as expected.
with open('/proc/cpuinfo', 'rb') as f:
cpuinfo_data = f.read()
fake_file = io.BytesIO(cpuinfo_data)
with mock.patch('psutil._common.open',
return_value=fake_file, create=True) as m:
self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
# Finally, let's make /proc/cpuinfo return meaningless data;
# this way we'll fall back on relying on /proc/stat
with mock_open_content('/proc/cpuinfo', b"") as m:
self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
assert m.called
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemCPUCountCores(PsutilTestCase):
@unittest.skipIf(not which("lscpu"), "lscpu utility not available")
def test_against_lscpu(self):
out = sh("lscpu -p")
core_ids = set()
for line in out.split('\n'):
if not line.startswith('#'):
fields = line.split(',')
core_ids.add(fields[1])
self.assertEqual(psutil.cpu_count(logical=False), len(core_ids))
def test_method_2(self):
meth_1 = psutil._pslinux.cpu_count_cores()
with mock.patch('glob.glob', return_value=[]) as m:
meth_2 = psutil._pslinux.cpu_count_cores()
assert m.called
if meth_1 is not None:
self.assertEqual(meth_1, meth_2)
def test_emulate_none(self):
with mock.patch('glob.glob', return_value=[]) as m1:
with mock.patch('psutil._common.open', create=True) as m2:
self.assertIsNone(psutil._pslinux.cpu_count_cores())
assert m1.called
assert m2.called
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemCPUFrequency(PsutilTestCase):
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
def test_emulate_use_second_file(self):
# https://github.com/giampaolo/psutil/issues/981
def path_exists_mock(path):
if path.startswith("/sys/devices/system/cpu/cpufreq/policy"):
return False
else:
return orig_exists(path)
orig_exists = os.path.exists
with mock.patch("os.path.exists", side_effect=path_exists_mock,
create=True):
assert psutil.cpu_freq()
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
def test_emulate_use_cpuinfo(self):
# Emulate a case where /sys/devices/system/cpu/cpufreq* does not
# exist and /proc/cpuinfo is used instead.
def path_exists_mock(path):
if path.startswith('/sys/devices/system/cpu/'):
return False
else:
return os_path_exists(path)
os_path_exists = os.path.exists
try:
with mock.patch("os.path.exists", side_effect=path_exists_mock):
reload_module(psutil._pslinux)
ret = psutil.cpu_freq()
assert ret
self.assertEqual(ret.max, 0.0)
self.assertEqual(ret.min, 0.0)
for freq in psutil.cpu_freq(percpu=True):
self.assertEqual(freq.max, 0.0)
self.assertEqual(freq.min, 0.0)
finally:
reload_module(psutil._pslinux)
reload_module(psutil)
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
def test_emulate_data(self):
def open_mock(name, *args, **kwargs):
if (name.endswith('/scaling_cur_freq') and
name.startswith("/sys/devices/system/cpu/cpufreq/policy")):
return io.BytesIO(b"500000")
elif (name.endswith('/scaling_min_freq') and
name.startswith("/sys/devices/system/cpu/cpufreq/policy")):
return io.BytesIO(b"600000")
elif (name.endswith('/scaling_max_freq') and
name.startswith("/sys/devices/system/cpu/cpufreq/policy")):
return io.BytesIO(b"700000")
elif name == '/proc/cpuinfo':
return io.BytesIO(b"cpu MHz : 500")
else:
return orig_open(name, *args, **kwargs)
orig_open = open
patch_point = 'builtins.open' if PY3 else '__builtin__.open'
with mock.patch(patch_point, side_effect=open_mock):
with mock.patch(
'os.path.exists', return_value=True):
freq = psutil.cpu_freq()
self.assertEqual(freq.current, 500.0)
# when /proc/cpuinfo is used min and max frequencies are not
# available and are set to 0.
if freq.min != 0.0:
self.assertEqual(freq.min, 600.0)
if freq.max != 0.0:
self.assertEqual(freq.max, 700.0)
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
def test_emulate_multi_cpu(self):
def open_mock(name, *args, **kwargs):
n = name
if (n.endswith('/scaling_cur_freq') and
n.startswith("/sys/devices/system/cpu/cpufreq/policy0")):
return io.BytesIO(b"100000")
elif (n.endswith('/scaling_min_freq') and
n.startswith("/sys/devices/system/cpu/cpufreq/policy0")):
return io.BytesIO(b"200000")
elif (n.endswith('/scaling_max_freq') and
n.startswith("/sys/devices/system/cpu/cpufreq/policy0")):
return io.BytesIO(b"300000")
elif (n.endswith('/scaling_cur_freq') and
n.startswith("/sys/devices/system/cpu/cpufreq/policy1")):
return io.BytesIO(b"400000")
elif (n.endswith('/scaling_min_freq') and
n.startswith("/sys/devices/system/cpu/cpufreq/policy1")):
return io.BytesIO(b"500000")
elif (n.endswith('/scaling_max_freq') and
n.startswith("/sys/devices/system/cpu/cpufreq/policy1")):
return io.BytesIO(b"600000")
elif name == '/proc/cpuinfo':
return io.BytesIO(b"cpu MHz : 100\n"
b"cpu MHz : 400")
else:
return orig_open(name, *args, **kwargs)
orig_open = open
patch_point = 'builtins.open' if PY3 else '__builtin__.open'
with mock.patch(patch_point, side_effect=open_mock):
with mock.patch('os.path.exists', return_value=True):
with mock.patch('psutil._pslinux.cpu_count_logical',
return_value=2):
freq = psutil.cpu_freq(percpu=True)
self.assertEqual(freq[0].current, 100.0)
if freq[0].min != 0.0:
self.assertEqual(freq[0].min, 200.0)
if freq[0].max != 0.0:
self.assertEqual(freq[0].max, 300.0)
self.assertEqual(freq[1].current, 400.0)
if freq[1].min != 0.0:
self.assertEqual(freq[1].min, 500.0)
if freq[1].max != 0.0:
self.assertEqual(freq[1].max, 600.0)
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
def test_emulate_no_scaling_cur_freq_file(self):
# See: https://github.com/giampaolo/psutil/issues/1071
def open_mock(name, *args, **kwargs):
if name.endswith('/scaling_cur_freq'):
raise IOError(errno.ENOENT, "")
elif name.endswith('/cpuinfo_cur_freq'):
return io.BytesIO(b"200000")
elif name == '/proc/cpuinfo':
return io.BytesIO(b"cpu MHz : 200")
else:
return orig_open(name, *args, **kwargs)
orig_open = open
patch_point = 'builtins.open' if PY3 else '__builtin__.open'
with mock.patch(patch_point, side_effect=open_mock):
with mock.patch('os.path.exists', return_value=True):
with mock.patch('psutil._pslinux.cpu_count_logical',
return_value=1):
freq = psutil.cpu_freq()
self.assertEqual(freq.current, 200)
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemCPUStats(PsutilTestCase):
def test_ctx_switches(self):
vmstat_value = vmstat("context switches")
psutil_value = psutil.cpu_stats().ctx_switches
self.assertAlmostEqual(vmstat_value, psutil_value, delta=500)
def test_interrupts(self):
vmstat_value = vmstat("interrupts")
psutil_value = psutil.cpu_stats().interrupts
self.assertAlmostEqual(vmstat_value, psutil_value, delta=500)
@unittest.skipIf(not LINUX, "LINUX only")
class TestLoadAvg(PsutilTestCase):
@unittest.skipIf(not HAS_GETLOADAVG, "not supported")
def test_getloadavg(self):
psutil_value = psutil.getloadavg()
with open("/proc/loadavg", "r") as f:
proc_value = f.read().split()
self.assertAlmostEqual(float(proc_value[0]), psutil_value[0], delta=1)
self.assertAlmostEqual(float(proc_value[1]), psutil_value[1], delta=1)
self.assertAlmostEqual(float(proc_value[2]), psutil_value[2], delta=1)
# =====================================================================
# --- system network
# =====================================================================
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemNetIfAddrs(PsutilTestCase):
def test_ips(self):
for name, addrs in psutil.net_if_addrs().items():
for addr in addrs:
if addr.family == psutil.AF_LINK:
self.assertEqual(addr.address, get_mac_address(name))
elif addr.family == socket.AF_INET:
self.assertEqual(addr.address, get_ipv4_address(name))
self.assertEqual(addr.netmask, get_ipv4_netmask(name))
if addr.broadcast is not None:
self.assertEqual(addr.broadcast,
get_ipv4_broadcast(name))
else:
self.assertEqual(get_ipv4_broadcast(name), '0.0.0.0')
elif addr.family == socket.AF_INET6:
# IPv6 addresses can have a percent symbol at the end.
# E.g. these 2 are equivalent:
# "fe80::1ff:fe23:4567:890a"
# "fe80::1ff:fe23:4567:890a%eth0"
# That is the "zone id" portion, which usually is the name
# of the network interface.
address = addr.address.split('%')[0]
self.assertIn(address, get_ipv6_addresses(name))
# XXX - not reliable when having virtual NICs installed by Docker.
# @unittest.skipIf(not which('ip'), "'ip' utility not available")
# def test_net_if_names(self):
# out = sh("ip addr").strip()
# nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
# found = 0
# for line in out.split('\n'):
# line = line.strip()
# if re.search(r"^\d+:", line):
# found += 1
# name = line.split(':')[1].strip()
# self.assertIn(name, nics)
# self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
# pprint.pformat(nics), out))
@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemNetIfStats(PsutilTestCase):
@unittest.skipIf(not which("ifconfig"), "ifconfig utility not available")
def test_against_ifconfig(self):
for name, stats in psutil.net_if_stats().items():
try:
out = sh("ifconfig %s" % name)
except RuntimeError:
pass
else:
self.assertEqual(stats.isup, 'RUNNING' in out, msg=out)
self.assertEqual(stats.mtu,
int(re.findall(r'(?i)MTU[: ](\d+)', out)[0]))
def test_mtu(self):
for name, stats in psutil.net_if_stats().items():
with open("/sys/class/net/%s/mtu" % name, "rt") as f:
self.assertEqual(stats.mtu, int(f.read().strip()))
@unittest.skipIf(not which("ifconfig"), "ifconfig utility not available")
def test_flags(self):
# first line looks like this:
# "eth0: flags=4163