init home-assistant
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Tests for the System Monitor component."""
|
||||
203
home-assistant/tests/components/systemmonitor/conftest.py
Normal file
203
home-assistant/tests/components/systemmonitor/conftest.py
Normal file
@@ -0,0 +1,203 @@
|
||||
"""Fixtures for the System Monitor integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Generator
|
||||
import socket
|
||||
from unittest.mock import AsyncMock, Mock, NonCallableMock, patch
|
||||
|
||||
from psutil import NoSuchProcess, Process
|
||||
from psutil._common import sdiskpart, sdiskusage, shwtemp, snetio, snicaddr, sswap
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.systemmonitor.const import DOMAIN
|
||||
from homeassistant.components.systemmonitor.coordinator import VirtualMemory
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_sys_platform() -> Generator[None]:
|
||||
"""Mock sys platform to Linux."""
|
||||
with patch("sys.platform", "linux"):
|
||||
yield
|
||||
|
||||
|
||||
class MockProcess(Process):
|
||||
"""Mock a Process class."""
|
||||
|
||||
def __init__(self, name: str, ex: bool = False) -> None:
|
||||
"""Initialize the process."""
|
||||
super().__init__(1)
|
||||
self._name = name
|
||||
self._ex = ex
|
||||
self._create_time = 1708700400
|
||||
|
||||
def name(self):
|
||||
"""Return a name."""
|
||||
if self._ex:
|
||||
raise NoSuchProcess(1, self._name)
|
||||
return self._name
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
"""Mock setup entry."""
|
||||
with patch(
|
||||
"homeassistant.components.systemmonitor.async_setup_entry",
|
||||
return_value=True,
|
||||
) as mock_setup_entry:
|
||||
yield mock_setup_entry
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry() -> MockConfigEntry:
|
||||
"""Mock ConfigEntry."""
|
||||
return MockConfigEntry(
|
||||
title="System Monitor",
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"binary_sensor": {"process": ["python3", "pip"]},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def mock_added_config_entry(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> MockConfigEntry:
|
||||
"""Mock ConfigEntry that's been added to HA."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert DOMAIN in hass.config_entries.async_domains()
|
||||
return mock_config_entry
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_process() -> list[MockProcess]:
|
||||
"""Mock process."""
|
||||
_process_python = MockProcess("python3")
|
||||
_process_pip = MockProcess("pip")
|
||||
return [_process_python, _process_pip]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_psutil(mock_process: list[MockProcess]) -> Generator:
|
||||
"""Mock psutil."""
|
||||
with patch(
|
||||
"homeassistant.components.systemmonitor.ha_psutil.PsutilWrapper",
|
||||
) as psutil_wrapper:
|
||||
_wrapper = psutil_wrapper.return_value
|
||||
_wrapper.psutil = NonCallableMock()
|
||||
mock_psutil = _wrapper.psutil
|
||||
mock_psutil.disk_usage.return_value = sdiskusage(
|
||||
500 * 1024**3, 300 * 1024**3, 200 * 1024**3, 60.0
|
||||
)
|
||||
mock_psutil.swap_memory.return_value = sswap(
|
||||
100 * 1024**2, 60 * 1024**2, 40 * 1024**2, 60.0, 1, 1
|
||||
)
|
||||
mock_psutil.virtual_memory.return_value = VirtualMemory(
|
||||
100 * 1024**2,
|
||||
40 * 1024**2,
|
||||
40.0,
|
||||
60 * 1024**2,
|
||||
30 * 1024**2,
|
||||
)
|
||||
mock_psutil.net_io_counters.return_value = {
|
||||
"eth0": snetio(100 * 1024**2, 100 * 1024**2, 50, 50, 0, 0, 0, 0),
|
||||
"eth1": snetio(200 * 1024**2, 200 * 1024**2, 150, 150, 0, 0, 0, 0),
|
||||
"vethxyzxyz": snetio(300 * 1024**2, 300 * 1024**2, 150, 150, 0, 0, 0, 0),
|
||||
}
|
||||
mock_psutil.net_if_addrs.return_value = {
|
||||
"eth0": [
|
||||
snicaddr(
|
||||
socket.AF_INET,
|
||||
"192.168.1.1",
|
||||
"255.255.255.0",
|
||||
"255.255.255.255",
|
||||
None,
|
||||
),
|
||||
snicaddr(
|
||||
socket.AF_INET6,
|
||||
"fe80::baf2:8a90:4f78:b1cb%end0",
|
||||
"ffff:ffff:ffff:ffff::",
|
||||
None,
|
||||
None,
|
||||
),
|
||||
snicaddr(
|
||||
socket.AF_INET6,
|
||||
"2a00:1f:2103:3a01:3333:2222:1111:0000",
|
||||
"ffff:ffff:ffff:ffff::",
|
||||
None,
|
||||
None,
|
||||
),
|
||||
],
|
||||
"eth1": [
|
||||
snicaddr(
|
||||
socket.AF_INET,
|
||||
"192.168.10.1",
|
||||
"255.255.255.0",
|
||||
"255.255.255.255",
|
||||
None,
|
||||
)
|
||||
],
|
||||
"vethxyzxyz": [
|
||||
snicaddr(
|
||||
socket.AF_INET,
|
||||
"172.16.10.1",
|
||||
"255.255.255.0",
|
||||
"255.255.255.255",
|
||||
None,
|
||||
)
|
||||
],
|
||||
}
|
||||
mock_psutil.cpu_percent.return_value = 10.0
|
||||
mock_psutil.boot_time.return_value = 1703973338.0
|
||||
mock_psutil.process_iter.return_value = mock_process
|
||||
# sensors_temperatures not available on MacOS so we
|
||||
# need to override the spec
|
||||
mock_psutil.sensors_temperatures = Mock()
|
||||
mock_psutil.sensors_temperatures.return_value = {
|
||||
"cpu0-thermal": [shwtemp("cpu0-thermal", 50.0, 60.0, 70.0)]
|
||||
}
|
||||
mock_psutil.disk_partitions.return_value = [
|
||||
sdiskpart("test", "/", "ext4", ""),
|
||||
sdiskpart("test2", "/media/share", "ext4", ""),
|
||||
sdiskpart("test3", "/incorrect", "", ""),
|
||||
sdiskpart("hosts", "/etc/hosts", "bind", ""),
|
||||
sdiskpart("proc", "/proc/run", "proc", ""),
|
||||
]
|
||||
mock_psutil.boot_time.return_value = 1708786800.0
|
||||
mock_psutil.NoSuchProcess = NoSuchProcess
|
||||
yield mock_psutil
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_os() -> Generator:
|
||||
"""Mock os."""
|
||||
|
||||
def isdir(path: str) -> bool:
|
||||
"""Mock os.path.isdir."""
|
||||
return path != "/etc/hosts"
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.systemmonitor.coordinator.os") as mock_os,
|
||||
patch("homeassistant.components.systemmonitor.util.os") as mock_os_util,
|
||||
):
|
||||
mock_os_util.name = "nt"
|
||||
mock_os.getloadavg.return_value = (1, 2, 3)
|
||||
mock_os_util.path.isdir = isdir
|
||||
yield mock_os
|
||||
@@ -0,0 +1,21 @@
|
||||
# serializer version: 1
|
||||
# name: test_binary_sensor[System Monitor Process pip - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'running',
|
||||
'friendly_name': 'System Monitor Process pip',
|
||||
'icon': 'mdi:cpu-64-bit',
|
||||
})
|
||||
# ---
|
||||
# name: test_binary_sensor[System Monitor Process pip - state]
|
||||
'on'
|
||||
# ---
|
||||
# name: test_binary_sensor[System Monitor Process python3 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'running',
|
||||
'friendly_name': 'System Monitor Process python3',
|
||||
'icon': 'mdi:cpu-64-bit',
|
||||
})
|
||||
# ---
|
||||
# name: test_binary_sensor[System Monitor Process python3 - state]
|
||||
'on'
|
||||
# ---
|
||||
@@ -0,0 +1,119 @@
|
||||
# serializer version: 1
|
||||
# name: test_diagnostics
|
||||
dict({
|
||||
'coordinators': dict({
|
||||
'data': dict({
|
||||
'addresses': dict({
|
||||
'eth0': "[snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.1.1', netmask='255.255.255.0', broadcast='255.255.255.255', ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fe80::baf2:8a90:4f78:b1cb%end0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='2a00:1f:2103:3a01:3333:2222:1111:0000', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None)]",
|
||||
'eth1': "[snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.10.1', netmask='255.255.255.0', broadcast='255.255.255.255', ptp=None)]",
|
||||
'vethxyzxyz': "[snicaddr(family=<AddressFamily.AF_INET: 2>, address='172.16.10.1', netmask='255.255.255.0', broadcast='255.255.255.255', ptp=None)]",
|
||||
}),
|
||||
'boot_time': '2024-02-24 15:00:00+00:00',
|
||||
'cpu_percent': '10.0',
|
||||
'disk_usage': dict({
|
||||
'/': 'sdiskusage(total=536870912000, used=322122547200, free=214748364800, percent=60.0)',
|
||||
'/home/notexist/': 'sdiskusage(total=536870912000, used=322122547200, free=214748364800, percent=60.0)',
|
||||
'/media/share': 'sdiskusage(total=536870912000, used=322122547200, free=214748364800, percent=60.0)',
|
||||
}),
|
||||
'io_counters': dict({
|
||||
'eth0': 'snetio(bytes_sent=104857600, bytes_recv=104857600, packets_sent=50, packets_recv=50, errin=0, errout=0, dropin=0, dropout=0)',
|
||||
'eth1': 'snetio(bytes_sent=209715200, bytes_recv=209715200, packets_sent=150, packets_recv=150, errin=0, errout=0, dropin=0, dropout=0)',
|
||||
'vethxyzxyz': 'snetio(bytes_sent=314572800, bytes_recv=314572800, packets_sent=150, packets_recv=150, errin=0, errout=0, dropin=0, dropout=0)',
|
||||
}),
|
||||
'load': '(1, 2, 3)',
|
||||
'memory': 'VirtualMemory(total=104857600, available=41943040, percent=40.0, used=62914560, free=31457280)',
|
||||
'processes': "[tests.components.systemmonitor.conftest.MockProcess(pid=1, name='python3', status='sleeping', started='2024-02-23 15:00:00'), tests.components.systemmonitor.conftest.MockProcess(pid=1, name='pip', status='sleeping', started='2024-02-23 15:00:00')]",
|
||||
'swap': 'sswap(total=104857600, used=62914560, free=41943040, percent=60.0, sin=1, sout=1)',
|
||||
'temperatures': dict({
|
||||
'cpu0-thermal': "[shwtemp(label='cpu0-thermal', current=50.0, high=60.0, critical=70.0)]",
|
||||
}),
|
||||
}),
|
||||
'last_update_success': True,
|
||||
}),
|
||||
'entry': dict({
|
||||
'data': dict({
|
||||
}),
|
||||
'disabled_by': None,
|
||||
'discovery_keys': dict({
|
||||
}),
|
||||
'domain': 'systemmonitor',
|
||||
'minor_version': 3,
|
||||
'options': dict({
|
||||
'binary_sensor': dict({
|
||||
'process': list([
|
||||
'python3',
|
||||
'pip',
|
||||
]),
|
||||
}),
|
||||
'resources': list([
|
||||
'disk_use_percent_/',
|
||||
'disk_use_percent_/home/notexist/',
|
||||
'memory_free_',
|
||||
'network_out_eth0',
|
||||
'process_python3',
|
||||
]),
|
||||
}),
|
||||
'pref_disable_new_entities': False,
|
||||
'pref_disable_polling': False,
|
||||
'source': 'user',
|
||||
'title': 'System Monitor',
|
||||
'unique_id': None,
|
||||
'version': 1,
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
# name: test_diagnostics_missing_items[test_diagnostics_missing_items]
|
||||
dict({
|
||||
'coordinators': dict({
|
||||
'data': dict({
|
||||
'addresses': None,
|
||||
'boot_time': '2024-02-24 15:00:00+00:00',
|
||||
'cpu_percent': '10.0',
|
||||
'disk_usage': dict({
|
||||
'/': 'sdiskusage(total=536870912000, used=322122547200, free=214748364800, percent=60.0)',
|
||||
'/home/notexist/': 'sdiskusage(total=536870912000, used=322122547200, free=214748364800, percent=60.0)',
|
||||
'/media/share': 'sdiskusage(total=536870912000, used=322122547200, free=214748364800, percent=60.0)',
|
||||
}),
|
||||
'io_counters': None,
|
||||
'load': '(1, 2, 3)',
|
||||
'memory': 'VirtualMemory(total=104857600, available=41943040, percent=40.0, used=62914560, free=31457280)',
|
||||
'processes': "[tests.components.systemmonitor.conftest.MockProcess(pid=1, name='python3', status='sleeping', started='2024-02-23 15:00:00'), tests.components.systemmonitor.conftest.MockProcess(pid=1, name='pip', status='sleeping', started='2024-02-23 15:00:00')]",
|
||||
'swap': 'sswap(total=104857600, used=62914560, free=41943040, percent=60.0, sin=1, sout=1)',
|
||||
'temperatures': dict({
|
||||
'cpu0-thermal': "[shwtemp(label='cpu0-thermal', current=50.0, high=60.0, critical=70.0)]",
|
||||
}),
|
||||
}),
|
||||
'last_update_success': True,
|
||||
}),
|
||||
'entry': dict({
|
||||
'data': dict({
|
||||
}),
|
||||
'disabled_by': None,
|
||||
'discovery_keys': dict({
|
||||
}),
|
||||
'domain': 'systemmonitor',
|
||||
'minor_version': 3,
|
||||
'options': dict({
|
||||
'binary_sensor': dict({
|
||||
'process': list([
|
||||
'python3',
|
||||
'pip',
|
||||
]),
|
||||
}),
|
||||
'resources': list([
|
||||
'disk_use_percent_/',
|
||||
'disk_use_percent_/home/notexist/',
|
||||
'memory_free_',
|
||||
'network_out_eth0',
|
||||
'process_python3',
|
||||
]),
|
||||
}),
|
||||
'pref_disable_new_entities': False,
|
||||
'pref_disable_polling': False,
|
||||
'source': 'user',
|
||||
'title': 'System Monitor',
|
||||
'unique_id': None,
|
||||
'version': 1,
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
@@ -0,0 +1,356 @@
|
||||
# serializer version: 1
|
||||
# name: test_sensor[System Monitor Disk free / - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Disk free /',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfInformation.GIBIBYTES: 'GiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk free / - state]
|
||||
'200.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk free /media/share - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Disk free /media/share',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfInformation.GIBIBYTES: 'GiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk free /media/share - state]
|
||||
'200.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk usage / - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Disk usage /',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': '%',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk usage / - state]
|
||||
'60.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk usage /home/notexist/ - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Disk usage /home/notexist/',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': '%',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk usage /home/notexist/ - state]
|
||||
'60.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk usage /media/share - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Disk usage /media/share',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': '%',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk usage /media/share - state]
|
||||
'60.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk use / - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Disk use /',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfInformation.GIBIBYTES: 'GiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk use / - state]
|
||||
'300.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk use /media/share - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Disk use /media/share',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfInformation.GIBIBYTES: 'GiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Disk use /media/share - state]
|
||||
'300.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor IPv4 address eth0 - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor IPv4 address eth0',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor IPv4 address eth0 - state]
|
||||
'192.168.1.1'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor IPv4 address eth1 - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor IPv4 address eth1',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor IPv4 address eth1 - state]
|
||||
'192.168.10.1'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor IPv6 address eth0 - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor IPv6 address eth0',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor IPv6 address eth0 - state]
|
||||
'2a00:1f:2103:3a01:3333:2222:1111:0000'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor IPv6 address eth1 - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor IPv6 address eth1',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor IPv6 address eth1 - state]
|
||||
'unknown'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Last boot - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'timestamp',
|
||||
'friendly_name': 'System Monitor Last boot',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Last boot - state]
|
||||
'2024-02-24T15:00:00+00:00'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Load (15m) - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Load (15m)',
|
||||
'icon': 'mdi:cpu-64-bit',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Load (15m) - state]
|
||||
'3'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Load (1m) - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Load (1m)',
|
||||
'icon': 'mdi:cpu-64-bit',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Load (1m) - state]
|
||||
'1'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Load (5m) - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Load (5m)',
|
||||
'icon': 'mdi:cpu-64-bit',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Load (5m) - state]
|
||||
'2'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Memory free - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Memory free',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfInformation.MEBIBYTES: 'MiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Memory free - state]
|
||||
'40.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Memory usage - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Memory usage',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': '%',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Memory usage - state]
|
||||
'40.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Memory use - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Memory use',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfInformation.MEBIBYTES: 'MiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Memory use - state]
|
||||
'60.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network in eth0 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Network in eth0',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
'unit_of_measurement': <UnitOfInformation.MEBIBYTES: 'MiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network in eth0 - state]
|
||||
'100.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network in eth1 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Network in eth1',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
'unit_of_measurement': <UnitOfInformation.MEBIBYTES: 'MiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network in eth1 - state]
|
||||
'200.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network out eth0 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Network out eth0',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
'unit_of_measurement': <UnitOfInformation.MEBIBYTES: 'MiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network out eth0 - state]
|
||||
'100.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network out eth1 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Network out eth1',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
'unit_of_measurement': <UnitOfInformation.MEBIBYTES: 'MiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network out eth1 - state]
|
||||
'200.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network throughput in eth0 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_rate',
|
||||
'friendly_name': 'System Monitor Network throughput in eth0',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfDataRate.MEGABYTES_PER_SECOND: 'MB/s'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network throughput in eth0 - state]
|
||||
'unknown'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network throughput in eth1 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_rate',
|
||||
'friendly_name': 'System Monitor Network throughput in eth1',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfDataRate.MEGABYTES_PER_SECOND: 'MB/s'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network throughput in eth1 - state]
|
||||
'unknown'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network throughput out eth0 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_rate',
|
||||
'friendly_name': 'System Monitor Network throughput out eth0',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfDataRate.MEGABYTES_PER_SECOND: 'MB/s'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network throughput out eth0 - state]
|
||||
'unknown'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network throughput out eth1 - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_rate',
|
||||
'friendly_name': 'System Monitor Network throughput out eth1',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfDataRate.MEGABYTES_PER_SECOND: 'MB/s'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Network throughput out eth1 - state]
|
||||
'unknown'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Packets in eth0 - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Packets in eth0',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Packets in eth0 - state]
|
||||
'50'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Packets in eth1 - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Packets in eth1',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Packets in eth1 - state]
|
||||
'150'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Packets out eth0 - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Packets out eth0',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Packets out eth0 - state]
|
||||
'50'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Packets out eth1 - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Packets out eth1',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Packets out eth1 - state]
|
||||
'150'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Processor temperature - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'temperature',
|
||||
'friendly_name': 'System Monitor Processor temperature',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfTemperature.CELSIUS: '°C'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Processor temperature - state]
|
||||
'50.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Processor use - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Processor use',
|
||||
'icon': 'mdi:cpu-64-bit',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': '%',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Processor use - state]
|
||||
'10'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Swap free - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Swap free',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfInformation.MEBIBYTES: 'MiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Swap free - state]
|
||||
'40.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Swap usage - attributes]
|
||||
ReadOnlyDict({
|
||||
'friendly_name': 'System Monitor Swap usage',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': '%',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Swap usage - state]
|
||||
'60.0'
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Swap use - attributes]
|
||||
ReadOnlyDict({
|
||||
'device_class': 'data_size',
|
||||
'friendly_name': 'System Monitor Swap use',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': <UnitOfInformation.MEBIBYTES: 'MiB'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor[System Monitor Swap use - state]
|
||||
'60.0'
|
||||
# ---
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Test System Monitor binary sensor."""
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
|
||||
from homeassistant.components.systemmonitor.binary_sensor import get_cpu_icon
|
||||
from homeassistant.components.systemmonitor.const import DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import STATE_OFF, STATE_ON
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from .conftest import MockProcess
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_binary_sensor(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
entity_registry: er.EntityRegistry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test the binary sensor."""
|
||||
mock_config_entry = MockConfigEntry(
|
||||
title="System Monitor",
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"binary_sensor": {"process": ["python3", "pip"]},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
},
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
process_binary_sensor = hass.states.get(
|
||||
"binary_sensor.system_monitor_process_python3"
|
||||
)
|
||||
assert process_binary_sensor is not None
|
||||
|
||||
for entity in er.async_entries_for_config_entry(
|
||||
entity_registry, mock_config_entry.entry_id
|
||||
):
|
||||
if entity.domain == BINARY_SENSOR_DOMAIN:
|
||||
state = hass.states.get(entity.entity_id)
|
||||
assert state.state == snapshot(name=f"{state.name} - state")
|
||||
assert state.attributes == snapshot(name=f"{state.name} - attributes")
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_binary_sensor_icon(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test the sensor icon for 32bit/64bit system."""
|
||||
|
||||
get_cpu_icon.cache_clear()
|
||||
with patch("sys.maxsize", 2**32):
|
||||
assert get_cpu_icon() == "mdi:cpu-32-bit"
|
||||
get_cpu_icon.cache_clear()
|
||||
with patch("sys.maxsize", 2**64):
|
||||
assert get_cpu_icon() == "mdi:cpu-64-bit"
|
||||
|
||||
|
||||
async def test_sensor_process_fails(
|
||||
hass: HomeAssistant,
|
||||
mock_added_config_entry: ConfigEntry,
|
||||
mock_psutil: Mock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test process not exist failure."""
|
||||
process_sensor = hass.states.get("binary_sensor.system_monitor_process_python3")
|
||||
assert process_sensor is not None
|
||||
assert process_sensor.state == STATE_ON
|
||||
|
||||
_process = MockProcess("python3", True)
|
||||
|
||||
mock_psutil.process_iter.return_value = [_process]
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
process_sensor = hass.states.get("binary_sensor.system_monitor_process_python3")
|
||||
assert process_sensor is not None
|
||||
assert process_sensor.state == STATE_OFF
|
||||
|
||||
assert "Failed to load process with ID: 1, old name: python3" in caplog.text
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Test the System Monitor config flow."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.systemmonitor.const import CONF_PROCESS, DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
|
||||
"""Test we get the form."""
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["step_id"] == "user"
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["options"] == {}
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_form_already_configured(
|
||||
hass: HomeAssistant, mock_setup_entry: AsyncMock
|
||||
) -> None:
|
||||
"""Test abort when already configured."""
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
source=config_entries.SOURCE_USER,
|
||||
options={},
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["step_id"] == "user"
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
async def test_add_and_remove_processes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test adding and removing process sensors."""
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
source=config_entries.SOURCE_USER,
|
||||
data={},
|
||||
options={},
|
||||
entry_id="1",
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(config_entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_PROCESS: ["systemd"],
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"binary_sensor": {
|
||||
CONF_PROCESS: ["systemd"],
|
||||
}
|
||||
}
|
||||
|
||||
# Add another
|
||||
result = await hass.config_entries.options.async_init(config_entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_PROCESS: ["systemd", "octave-cli"],
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"binary_sensor": {
|
||||
CONF_PROCESS: ["systemd", "octave-cli"],
|
||||
},
|
||||
}
|
||||
|
||||
assert (
|
||||
entity_registry.async_get("binary_sensor.system_monitor_process_systemd")
|
||||
is not None
|
||||
)
|
||||
assert (
|
||||
entity_registry.async_get("binary_sensor.system_monitor_process_octave_cli")
|
||||
is not None
|
||||
)
|
||||
|
||||
# Remove one
|
||||
result = await hass.config_entries.options.async_init(config_entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_PROCESS: ["systemd"],
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"binary_sensor": {
|
||||
CONF_PROCESS: ["systemd"],
|
||||
},
|
||||
}
|
||||
|
||||
# Remove last
|
||||
result = await hass.config_entries.options.async_init(config_entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_PROCESS: [],
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"binary_sensor": {CONF_PROCESS: []},
|
||||
}
|
||||
|
||||
assert (
|
||||
entity_registry.async_get("binary_sensor.systemmonitor_process_systemd") is None
|
||||
)
|
||||
assert (
|
||||
entity_registry.async_get("binary_sensor.systemmonitor_process_octave_cli")
|
||||
is None
|
||||
)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Tests for the diagnostics data provided by the System Monitor integration."""
|
||||
|
||||
from unittest.mock import Mock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from syrupy import SnapshotAssertion
|
||||
from syrupy.filters import props
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
from tests.components.diagnostics import get_diagnostics_for_config_entry
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
async def test_diagnostics(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_added_config_entry: MockConfigEntry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test diagnostics."""
|
||||
assert await get_diagnostics_for_config_entry(
|
||||
hass, hass_client, mock_added_config_entry
|
||||
) == snapshot(exclude=props("last_update", "entry_id", "created_at", "modified_at"))
|
||||
|
||||
|
||||
async def test_diagnostics_missing_items(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
snapshot: SnapshotAssertion,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test diagnostics."""
|
||||
mock_psutil.net_if_addrs.return_value = None
|
||||
mock_psutil.net_io_counters.return_value = None
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
|
||||
assert await get_diagnostics_for_config_entry(
|
||||
hass, hass_client, mock_config_entry
|
||||
) == snapshot(
|
||||
exclude=props("last_update", "entry_id", "created_at", "modified_at"),
|
||||
name="test_diagnostics_missing_items",
|
||||
)
|
||||
143
home-assistant/tests/components/systemmonitor/test_init.py
Normal file
143
home-assistant/tests/components/systemmonitor/test_init.py
Normal file
@@ -0,0 +1,143 @@
|
||||
"""Test for System Monitor init."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import Mock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.systemmonitor.const import CONF_PROCESS, DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntry, ConfigEntryState
|
||||
from homeassistant.const import STATE_OFF, STATE_ON
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_load_unload_entry(
|
||||
hass: HomeAssistant, mock_added_config_entry: ConfigEntry
|
||||
) -> None:
|
||||
"""Test load and unload an entry."""
|
||||
|
||||
assert mock_added_config_entry.state is ConfigEntryState.LOADED
|
||||
assert await hass.config_entries.async_unload(mock_added_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert mock_added_config_entry.state is ConfigEntryState.NOT_LOADED
|
||||
|
||||
|
||||
async def test_adding_processor_to_options(
|
||||
hass: HomeAssistant, mock_added_config_entry: ConfigEntry
|
||||
) -> None:
|
||||
"""Test options listener."""
|
||||
process_sensor = hass.states.get("binary_sensor.system_monitor_process_systemd")
|
||||
assert process_sensor is None
|
||||
|
||||
result = await hass.config_entries.options.async_init(
|
||||
mock_added_config_entry.entry_id
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_PROCESS: ["python3", "pip", "systemd"],
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"binary_sensor": {
|
||||
CONF_PROCESS: ["python3", "pip", "systemd"],
|
||||
},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
}
|
||||
|
||||
process_sensor = hass.states.get("binary_sensor.system_monitor_process_systemd")
|
||||
assert process_sensor is not None
|
||||
assert process_sensor.state == STATE_OFF
|
||||
|
||||
|
||||
async def test_migrate_process_sensor_to_binary_sensors(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test process not exist failure."""
|
||||
mock_config_entry = MockConfigEntry(
|
||||
title="System Monitor",
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"sensor": {"process": ["python3", "pip"]},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
},
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
process_sensor = hass.states.get("binary_sensor.system_monitor_process_python3")
|
||||
assert process_sensor is not None
|
||||
assert process_sensor.state == STATE_ON
|
||||
|
||||
assert mock_config_entry.minor_version == 3
|
||||
assert mock_config_entry.options == {
|
||||
"binary_sensor": {"process": ["python3", "pip"]},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def test_migration_from_future_version(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test migration from future version."""
|
||||
mock_config_entry = MockConfigEntry(
|
||||
title="System Monitor",
|
||||
domain=DOMAIN,
|
||||
version=2,
|
||||
data={},
|
||||
options={
|
||||
"sensor": {"process": ["python3", "pip"]},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
},
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.MIGRATION_ERROR
|
||||
546
home-assistant/tests/components/systemmonitor/test_sensor.py
Normal file
546
home-assistant/tests/components/systemmonitor/test_sensor.py
Normal file
@@ -0,0 +1,546 @@
|
||||
"""Test System Monitor sensor."""
|
||||
|
||||
from datetime import timedelta
|
||||
import socket
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from psutil._common import sdiskpart, sdiskusage, shwtemp, snetio, snicaddr
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
|
||||
from homeassistant.components.systemmonitor.const import DOMAIN
|
||||
from homeassistant.components.systemmonitor.coordinator import VirtualMemory
|
||||
from homeassistant.components.systemmonitor.sensor import get_cpu_icon
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_sensor(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
entity_registry: er.EntityRegistry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test the sensor."""
|
||||
mock_config_entry = MockConfigEntry(
|
||||
title="System Monitor",
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"binary_sensor": {"process": ["python3", "pip"]},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
},
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
memory_sensor = hass.states.get("sensor.system_monitor_memory_free")
|
||||
assert memory_sensor is not None
|
||||
assert memory_sensor.state == "40.0"
|
||||
assert memory_sensor.attributes == {
|
||||
"state_class": "measurement",
|
||||
"unit_of_measurement": "MiB",
|
||||
"device_class": "data_size",
|
||||
"friendly_name": "System Monitor Memory free",
|
||||
}
|
||||
|
||||
for entity in er.async_entries_for_config_entry(
|
||||
entity_registry, mock_config_entry.entry_id
|
||||
):
|
||||
if entity.domain == SENSOR_DOMAIN:
|
||||
state = hass.states.get(entity.entity_id)
|
||||
assert state.state == snapshot(name=f"{state.name} - state")
|
||||
assert state.attributes == snapshot(name=f"{state.name} - attributes")
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_process_sensor_not_loaded(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
entity_registry: er.EntityRegistry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test the process sensor is not loaded once migrated."""
|
||||
mock_config_entry = MockConfigEntry(
|
||||
title="System Monitor",
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"binary_sensor": {"process": ["python3", "pip"]},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
},
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
process_sensor = hass.states.get("sensor.system_monitor_process_python3")
|
||||
assert process_sensor is None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_sensor_not_loading_veth_networks(
|
||||
hass: HomeAssistant,
|
||||
mock_added_config_entry: ConfigEntry,
|
||||
) -> None:
|
||||
"""Test the sensor."""
|
||||
network_sensor_1 = hass.states.get("sensor.system_monitor_network_out_eth1")
|
||||
network_sensor_2 = hass.states.get(
|
||||
"sensor.sensor.system_monitor_network_out_vethxyzxyz"
|
||||
)
|
||||
assert network_sensor_1 is not None
|
||||
assert network_sensor_1.state == "200.0"
|
||||
assert network_sensor_2 is None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_sensor_icon(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test the sensor icon for 32bit/64bit system."""
|
||||
|
||||
get_cpu_icon.cache_clear()
|
||||
with patch("sys.maxsize", 2**32):
|
||||
assert get_cpu_icon() == "mdi:cpu-32-bit"
|
||||
get_cpu_icon.cache_clear()
|
||||
with patch("sys.maxsize", 2**64):
|
||||
assert get_cpu_icon() == "mdi:cpu-64-bit"
|
||||
|
||||
|
||||
async def test_sensor_updating(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test the sensor."""
|
||||
mock_config_entry = MockConfigEntry(
|
||||
title="System Monitor",
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"binary_sensor": {"process": ["python3", "pip"]},
|
||||
"resources": [
|
||||
"disk_use_percent_/",
|
||||
"disk_use_percent_/home/notexist/",
|
||||
"memory_free_",
|
||||
"network_out_eth0",
|
||||
"process_python3",
|
||||
],
|
||||
},
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
memory_sensor = hass.states.get("sensor.system_monitor_memory_free")
|
||||
assert memory_sensor is not None
|
||||
assert memory_sensor.state == "40.0"
|
||||
|
||||
mock_psutil.virtual_memory.side_effect = Exception("Failed to update")
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
memory_sensor = hass.states.get("sensor.system_monitor_memory_free")
|
||||
assert memory_sensor is not None
|
||||
assert memory_sensor.state == STATE_UNAVAILABLE
|
||||
|
||||
mock_psutil.virtual_memory.side_effect = None
|
||||
mock_psutil.virtual_memory.return_value = VirtualMemory(
|
||||
100 * 1024**2,
|
||||
25 * 1024**2,
|
||||
25.0,
|
||||
60 * 1024**2,
|
||||
30 * 1024**2,
|
||||
)
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
memory_sensor = hass.states.get("sensor.system_monitor_memory_free")
|
||||
assert memory_sensor is not None
|
||||
assert memory_sensor.state == "25.0"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_sensor_network_sensors(
|
||||
freezer: FrozenDateTimeFactory,
|
||||
hass: HomeAssistant,
|
||||
mock_added_config_entry: ConfigEntry,
|
||||
mock_psutil: Mock,
|
||||
) -> None:
|
||||
"""Test process not exist failure."""
|
||||
network_out_sensor = hass.states.get("sensor.system_monitor_network_out_eth1")
|
||||
packets_out_sensor = hass.states.get("sensor.system_monitor_packets_out_eth1")
|
||||
throughput_network_out_sensor = hass.states.get(
|
||||
"sensor.system_monitor_network_throughput_out_eth1"
|
||||
)
|
||||
|
||||
assert network_out_sensor is not None
|
||||
assert packets_out_sensor is not None
|
||||
assert throughput_network_out_sensor is not None
|
||||
assert network_out_sensor.state == "200.0"
|
||||
assert packets_out_sensor.state == "150"
|
||||
assert throughput_network_out_sensor.state == STATE_UNKNOWN
|
||||
|
||||
mock_psutil.net_io_counters.return_value = {
|
||||
"eth0": snetio(200 * 1024**2, 200 * 1024**2, 100, 100, 0, 0, 0, 0),
|
||||
"eth1": snetio(400 * 1024**2, 400 * 1024**2, 300, 300, 0, 0, 0, 0),
|
||||
}
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
network_out_sensor = hass.states.get("sensor.system_monitor_network_out_eth1")
|
||||
packets_out_sensor = hass.states.get("sensor.system_monitor_packets_out_eth1")
|
||||
throughput_network_out_sensor = hass.states.get(
|
||||
"sensor.system_monitor_network_throughput_out_eth1"
|
||||
)
|
||||
|
||||
assert network_out_sensor is not None
|
||||
assert packets_out_sensor is not None
|
||||
assert throughput_network_out_sensor is not None
|
||||
assert network_out_sensor.state == "400.0"
|
||||
assert packets_out_sensor.state == "300"
|
||||
assert float(throughput_network_out_sensor.state) == pytest.approx(3.493, rel=0.1)
|
||||
|
||||
mock_psutil.net_io_counters.return_value = {
|
||||
"eth0": snetio(100 * 1024**2, 100 * 1024**2, 50, 50, 0, 0, 0, 0),
|
||||
}
|
||||
mock_psutil.net_if_addrs.return_value = {
|
||||
"eth0": [
|
||||
snicaddr(
|
||||
socket.AF_INET,
|
||||
"192.168.1.1",
|
||||
"255.255.255.0",
|
||||
"255.255.255.255",
|
||||
None,
|
||||
)
|
||||
],
|
||||
}
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
network_out_sensor = hass.states.get("sensor.system_monitor_network_out_eth1")
|
||||
packets_out_sensor = hass.states.get("sensor.system_monitor_packets_out_eth1")
|
||||
throughput_network_out_sensor = hass.states.get(
|
||||
"sensor.system_monitor_network_throughput_out_eth1"
|
||||
)
|
||||
|
||||
assert network_out_sensor is not None
|
||||
assert packets_out_sensor is not None
|
||||
assert throughput_network_out_sensor is not None
|
||||
assert network_out_sensor.state == STATE_UNKNOWN
|
||||
assert packets_out_sensor.state == STATE_UNKNOWN
|
||||
assert throughput_network_out_sensor.state == STATE_UNKNOWN
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_missing_cpu_temperature(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the sensor when temperature missing."""
|
||||
mock_psutil.sensors_temperatures.return_value = {
|
||||
"not_exist": [shwtemp("not_exist", 50.0, 60.0, 70.0)]
|
||||
}
|
||||
mock_psutil.sensors_temperatures.return_value = {
|
||||
"not_exist": [shwtemp("not_exist", 50.0, 60.0, 70.0)]
|
||||
}
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# assert "Cannot read CPU / processor temperature information" in caplog.text
|
||||
temp_sensor = hass.states.get("sensor.system_monitor_processor_temperature")
|
||||
assert temp_sensor is None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_processor_temperature(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the disk failures."""
|
||||
|
||||
with patch("sys.platform", "linux"):
|
||||
mock_psutil.sensors_temperatures.return_value = {
|
||||
"cpu0-thermal": [shwtemp("cpu0-thermal", 50.0, 60.0, 70.0)]
|
||||
}
|
||||
mock_psutil.sensors_temperatures.side_effect = None
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
temp_entity = hass.states.get("sensor.system_monitor_processor_temperature")
|
||||
assert temp_entity.state == "50.0"
|
||||
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with patch("sys.platform", "nt"):
|
||||
mock_psutil.sensors_temperatures.return_value = None
|
||||
mock_psutil.sensors_temperatures.side_effect = AttributeError(
|
||||
"sensors_temperatures not exist"
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
temp_entity = hass.states.get("sensor.system_monitor_processor_temperature")
|
||||
assert temp_entity.state == STATE_UNAVAILABLE
|
||||
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with patch("sys.platform", "darwin"):
|
||||
mock_psutil.sensors_temperatures.return_value = {
|
||||
"cpu0-thermal": [shwtemp("cpu0-thermal", 50.0, 60.0, 70.0)]
|
||||
}
|
||||
mock_psutil.sensors_temperatures.side_effect = None
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
temp_entity = hass.states.get("sensor.system_monitor_processor_temperature")
|
||||
assert temp_entity.state == "50.0"
|
||||
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_exception_handling_disk_sensor(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_added_config_entry: ConfigEntry,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test the sensor."""
|
||||
disk_sensor = hass.states.get("sensor.system_monitor_disk_free")
|
||||
assert disk_sensor is not None
|
||||
assert disk_sensor.state == "200.0" # GiB
|
||||
|
||||
mock_psutil.disk_usage.return_value = None
|
||||
mock_psutil.disk_usage.side_effect = OSError("Could not update /")
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert "OS error for /" in caplog.text
|
||||
|
||||
disk_sensor = hass.states.get("sensor.system_monitor_disk_free")
|
||||
assert disk_sensor is not None
|
||||
assert disk_sensor.state == STATE_UNAVAILABLE
|
||||
|
||||
mock_psutil.disk_usage.return_value = None
|
||||
mock_psutil.disk_usage.side_effect = PermissionError("No access to /")
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert "OS error for /" in caplog.text
|
||||
|
||||
disk_sensor = hass.states.get("sensor.system_monitor_disk_free")
|
||||
assert disk_sensor is not None
|
||||
assert disk_sensor.state == STATE_UNAVAILABLE
|
||||
|
||||
mock_psutil.disk_usage.return_value = sdiskusage(
|
||||
500 * 1024**3, 350 * 1024**3, 150 * 1024**3, 70.0
|
||||
)
|
||||
mock_psutil.disk_usage.side_effect = None
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
disk_sensor = hass.states.get("sensor.system_monitor_disk_free")
|
||||
assert disk_sensor is not None
|
||||
assert disk_sensor.state == "150.0"
|
||||
assert disk_sensor.attributes["unit_of_measurement"] == "GiB"
|
||||
|
||||
disk_sensor = hass.states.get("sensor.system_monitor_disk_usage")
|
||||
assert disk_sensor is not None
|
||||
assert disk_sensor.state == "70.0"
|
||||
assert disk_sensor.attributes["unit_of_measurement"] == "%"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_cpu_percentage_is_zero_returns_unknown(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_added_config_entry: ConfigEntry,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test the sensor."""
|
||||
cpu_sensor = hass.states.get("sensor.system_monitor_processor_use")
|
||||
assert cpu_sensor is not None
|
||||
assert cpu_sensor.state == "10"
|
||||
|
||||
mock_psutil.cpu_percent.return_value = 0.0
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
cpu_sensor = hass.states.get("sensor.system_monitor_processor_use")
|
||||
assert cpu_sensor is not None
|
||||
assert cpu_sensor.state == STATE_UNKNOWN
|
||||
|
||||
mock_psutil.cpu_percent.return_value = 15.0
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
cpu_sensor = hass.states.get("sensor.system_monitor_processor_use")
|
||||
assert cpu_sensor is not None
|
||||
assert cpu_sensor.state == "15"
|
||||
|
||||
|
||||
async def test_remove_obsolete_entities(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_added_config_entry: ConfigEntry,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test we remove sensors that are not actual and disabled."""
|
||||
cpu_sensor = hass.states.get("sensor.system_monitor_processor_use")
|
||||
assert cpu_sensor is None
|
||||
cpu_sensor_entity = entity_registry.async_get("sensor.system_monitor_processor_use")
|
||||
assert cpu_sensor_entity.disabled is True
|
||||
|
||||
assert (
|
||||
len(
|
||||
entity_registry.entities.get_entries_for_config_entry_id(
|
||||
mock_added_config_entry.entry_id
|
||||
)
|
||||
)
|
||||
== 37
|
||||
)
|
||||
|
||||
entity_registry.async_update_entity(
|
||||
"sensor.system_monitor_processor_use", disabled_by=None
|
||||
)
|
||||
freezer.tick(timedelta(minutes=5))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
# Fake an entity which should be removed as not supported and disabled
|
||||
entity_registry.async_get_or_create(
|
||||
SENSOR_DOMAIN,
|
||||
DOMAIN,
|
||||
"network_out_veth12345",
|
||||
disabled_by=er.RegistryEntryDisabler.INTEGRATION,
|
||||
config_entry=mock_added_config_entry,
|
||||
has_entity_name=True,
|
||||
device_id=cpu_sensor_entity.device_id,
|
||||
translation_key="network_out",
|
||||
)
|
||||
# Fake an entity which should not be removed as not supported but not disabled
|
||||
entity_registry.async_get_or_create(
|
||||
SENSOR_DOMAIN,
|
||||
DOMAIN,
|
||||
"network_out_veth54321",
|
||||
disabled_by=None,
|
||||
config_entry=mock_added_config_entry,
|
||||
has_entity_name=True,
|
||||
device_id=cpu_sensor_entity.device_id,
|
||||
translation_key="network_out",
|
||||
)
|
||||
await hass.config_entries.async_reload(mock_added_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
len(
|
||||
entity_registry.entities.get_entries_for_config_entry_id(
|
||||
mock_added_config_entry.entry_id
|
||||
)
|
||||
)
|
||||
== 38
|
||||
)
|
||||
|
||||
assert (
|
||||
entity_registry.async_get("sensor.systemmonitor_network_out_veth12345") is None
|
||||
)
|
||||
assert (
|
||||
entity_registry.async_get("sensor.systemmonitor_network_out_veth54321")
|
||||
is not None
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_no_duplicate_disk_entities(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the sensor."""
|
||||
mock_psutil.disk_usage.return_value = sdiskusage(
|
||||
500 * 1024**3, 300 * 1024**3, 200 * 1024**3, 60.0
|
||||
)
|
||||
mock_psutil.disk_partitions.return_value = [
|
||||
sdiskpart("test", "/", "ext4", ""),
|
||||
sdiskpart("test2", "/media/share", "ext4", ""),
|
||||
sdiskpart("test3", "/incorrect", "", ""),
|
||||
sdiskpart("test4", "/media/frigate", "ext4", ""),
|
||||
sdiskpart("test4", "/media/FRIGATE", "ext4", ""),
|
||||
sdiskpart("hosts", "/etc/hosts", "bind", ""),
|
||||
sdiskpart("proc", "/proc/run", "proc", ""),
|
||||
]
|
||||
|
||||
mock_config_entry = MockConfigEntry(
|
||||
title="System Monitor",
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"binary_sensor": {"process": ["python3", "pip"]},
|
||||
},
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
disk_sensor = hass.states.get("sensor.system_monitor_disk_usage_media_frigate")
|
||||
assert disk_sensor is not None
|
||||
assert disk_sensor.state == "60.0"
|
||||
|
||||
assert "Platform systemmonitor does not generate unique IDs." not in caplog.text
|
||||
83
home-assistant/tests/components/systemmonitor/test_util.py
Normal file
83
home-assistant/tests/components/systemmonitor/test_util.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Test System Monitor utils."""
|
||||
|
||||
from unittest.mock import Mock
|
||||
|
||||
from psutil._common import sdiskpart
|
||||
import pytest
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("side_effect", "error_text"),
|
||||
[
|
||||
(PermissionError("No permission"), "No permission for running user to access"),
|
||||
(OSError("OS error"), "was excluded because of: OS error"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_disk_setup_failure(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
side_effect: Exception,
|
||||
error_text: str,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the disk failures."""
|
||||
|
||||
mock_psutil.disk_usage.side_effect = side_effect
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
disk_sensor = hass.states.get("sensor.system_monitor_disk_free_media_share")
|
||||
assert disk_sensor is None
|
||||
|
||||
assert error_text in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_disk_util(
|
||||
hass: HomeAssistant,
|
||||
mock_psutil: Mock,
|
||||
mock_os: Mock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test the disk failures."""
|
||||
|
||||
mock_psutil.psutil.disk_partitions.return_value = [
|
||||
sdiskpart("test", "/", "ext4", ""), # Should be ok
|
||||
sdiskpart("test2", "/media/share", "ext4", ""), # Should be ok
|
||||
sdiskpart("test3", "/incorrect", "", ""), # Should be skipped as no type
|
||||
sdiskpart(
|
||||
"proc", "/proc/run", "proc", ""
|
||||
), # Should be skipped as in skipped disk types
|
||||
sdiskpart(
|
||||
"test4",
|
||||
"/tmpfs/", # noqa: S108
|
||||
"tmpfs",
|
||||
"",
|
||||
), # Should be skipped as in skipped disk types
|
||||
sdiskpart("test5", "E:", "cd", "cdrom"), # Should be skipped as cdrom
|
||||
]
|
||||
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
disk_sensor1 = hass.states.get("sensor.system_monitor_disk_free")
|
||||
disk_sensor2 = hass.states.get("sensor.system_monitor_disk_free_media_share")
|
||||
disk_sensor3 = hass.states.get("sensor.system_monitor_disk_free_incorrect")
|
||||
disk_sensor4 = hass.states.get("sensor.system_monitor_disk_free_proc_run")
|
||||
disk_sensor5 = hass.states.get("sensor.system_monitor_disk_free_tmpfs")
|
||||
disk_sensor6 = hass.states.get("sensor.system_monitor_disk_free_e")
|
||||
assert disk_sensor1 is not None
|
||||
assert disk_sensor2 is not None
|
||||
assert disk_sensor3 is None
|
||||
assert disk_sensor4 is None
|
||||
assert disk_sensor5 is None
|
||||
assert disk_sensor6 is None
|
||||
Reference in New Issue
Block a user