python - 在 Python27 中读取导致 py.test 失败的 top 命令
问题描述
我正在使用 py.test 对我的应用程序进行单元测试,并且针对这段特定的代码遇到了错误的测试失败:
# get current cpu usage in %
def get_cpu_use_perc(self):
cpu_use = os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip('\\')
print('-DBG- CPU Use call from terminal returns: {}'.format(cpu_use))
self._cpu_use = float(cpu_use)
return self._cpu_use
我对 py.test 很陌生,所以我不太确定如何解决这个问题。我已经单独测试了这个特定的函数,它返回了一个我期望的数字。查看文档,尝试使用标准输出时似乎存在问题。我已经测试了其他使用 os.popen('command_here').readline() 的代码并且工作正常,所以我认为它与顶部有关。
这个命令导致测试失败怎么办?有没有更好的方法来获取树莓派上的 CPU 使用率而不使用与 py.test 一起使用的 top?是否有一个标记或我可以添加的东西来允许该工具捕获我想要的信息?
编辑:这是单元测试代码片段的更新:
import time
from system_monitor import system_monitor
# create object
sys_mon = system_monitor()
# simplified unit test
def test_memory(num_checks=20):
cpu_use_perc = sys_mon.get_cpu_use_perc()
assert float(cpu_use_perc) < 5.0 # tested CPU usage, too high for testing
当我从命令行运行这个单元测试时,我看到:
>>>sudo python test_sys_mon.py
-DBG- CPU Use call from terminal returns: 3.2
当我使用与 setup.py 集成的 py.test 运行我的测试套件时,我看到:
>>>sudo python setup.py test
--- other test stuff passing here that is not important...
...
> cpu_use_perc = sys_mon.get_cpu_use_perc()
src/system_monitor/test/test_sys_mon.py:128:
self = <system_monitor.system_monitor.system_monitor object at 0xb58a6ad0>
def get_cpu_use_perc(self):
cpu_use = os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip('\\')
print('-DBG- CPU Use call from terminal returns: {}'.format(cpu_use))
> self._cpu_use = float(cpu_use)
E ValueError: could not convert string to float:
src/system_monitor/system_monitor.py:50: ValueError
------------------------- Captured stdout call -----------------------------
-DBG- CPU Use call from terminal returns:
------------------------- Captured stderr call -----------------------------
看起来这os.popen()
正在返回一个空字符串,但我不确定如何解决这个问题,所以我可以将 top 命令与 py.test 一起使用
解决方案
推荐阅读
- java - 如何连接到连接到同一本地网络的用户并在 Android 应用程序中在他们之间共享信息
- angular - Angular 6 输入标签:无法重新声明块范围变量“ngDevMode”。ngx-标签输入
- python - sklearn make_scorer 函数的类型错误
- html - 没有协议或域路径的规范链接类型,使用正斜杠和文件扩展名自动生成
- angular - Angular Forms 为对象的每个属性创建控件
- data-warehouse - 这是在维度模型中使用桥接表的正确方法吗?
- html - 具有 vh 相对高度的父级的 HTML5 % 高度子级
- html - 使用VB.NET将网页表行中的值提取为字符串
- laravel - 如何在 Laravel 5 中使用 Codeception 在单元测试中模拟身份验证用户?
- selenium - 无法单击“使用电子邮件注册”按钮