首页 > 解决方案 > 在 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 一起使用

标签: pythonraspberry-pipytest

解决方案


诉诸模拟,而不是弃用 os.popen 考虑 subprocess.Popen 为

使用 subprocess.Popen 对 Python 代码进行单元测试

还可以考虑使用 ps 而不是 top

CalledProcessError:命令'('grep','route')'返回非零退出状态1


推荐阅读