86 lines
3.0 KiB
Python
86 lines
3.0 KiB
Python
import pytest
|
||
from function.system_monitor import SystemMonitor
|
||
from typing import Dict
|
||
|
||
class TestSystemMonitor:
|
||
@pytest.fixture
|
||
def system_monitor(self):
|
||
return SystemMonitor()
|
||
|
||
def test_get_system_resources(self, system_monitor):
|
||
"""测试获取系统资源信息"""
|
||
result = system_monitor.get_system_resources()
|
||
|
||
# 验证返回格式
|
||
assert isinstance(result, dict)
|
||
assert 'status' in result
|
||
assert result['status'] == 'success'
|
||
assert 'resources' in result
|
||
assert 'timestamp' in result
|
||
|
||
resources = result['resources']
|
||
|
||
# 验证GPU信息
|
||
assert 'gpu' in resources
|
||
if resources['gpu']: # 如果有GPU
|
||
gpu = resources['gpu'][0]
|
||
assert 'id' in gpu
|
||
assert 'name' in gpu
|
||
assert 'memory' in gpu
|
||
assert 'utilization' in gpu
|
||
assert 'temperature' in gpu
|
||
|
||
# 验证CPU信息
|
||
assert 'cpu' in resources
|
||
cpu = resources['cpu']
|
||
assert 'count' in cpu
|
||
assert 'utilization' in cpu
|
||
assert 'memory' in cpu
|
||
assert 'swap' in cpu
|
||
|
||
# 验证内存信息
|
||
memory = cpu['memory']
|
||
assert 'total' in memory
|
||
assert 'used' in memory
|
||
assert 'free' in memory
|
||
assert 'percent' in memory
|
||
assert memory['total'] > 0
|
||
assert 0 <= memory['percent'] <= 100
|
||
|
||
# 验证磁盘信息
|
||
assert 'disk' in resources
|
||
assert len(resources['disk']) > 0
|
||
for mount_point, disk_info in resources['disk'].items():
|
||
assert 'total' in disk_info
|
||
assert 'used' in disk_info
|
||
assert 'free' in disk_info
|
||
assert 'percent' in disk_info
|
||
assert disk_info['total'] > 0
|
||
assert 0 <= disk_info['percent'] <= 100
|
||
|
||
# 验证进程信息
|
||
assert 'processes' in resources
|
||
processes = resources['processes']
|
||
assert 'total' in processes
|
||
assert 'running' in processes
|
||
assert 'sleeping' in processes
|
||
assert processes['total'] > 0
|
||
assert processes['running'] >= 0
|
||
assert processes['sleeping'] >= 0
|
||
|
||
def test_error_handling(self, system_monitor, monkeypatch):
|
||
"""测试错误处理"""
|
||
def mock_gpu_error(*args, **kwargs):
|
||
raise Exception("GPU query failed")
|
||
|
||
# 模拟GPU查询错误
|
||
monkeypatch.setattr(system_monitor, '_get_gpu_info', mock_gpu_error)
|
||
|
||
result = system_monitor.get_system_resources()
|
||
assert result['status'] == 'success' # 即使GPU查询失败,其他资源信息仍应返回
|
||
assert result['resources']['gpu'] == [] # GPU信息应为空列表
|
||
|
||
# 验证其他资源信息仍然可用
|
||
assert 'cpu' in result['resources']
|
||
assert 'disk' in result['resources']
|
||
assert 'processes' in result['resources'] |