I am unit testing my application with py.test and am running into false test failures for this specific piece of code:
# 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
I am pretty new to py.test, so I'm not too sure how to fix this. I have tested this specific function separately and it returns a number as I would expect. Looking through the documentation, it looks like there are issues when trying to use stdout. I have tested other code that uses os.popen('command_here').readline() and that works fine, so I assume it has to do with top.
What about this command is causing the test to fail? Is there a better way to get the CPU usage on a raspberry pi without using top that will work with py.test? Is there a marker or something I can add to allow the tool to capture the information I want?
EDIT: Here is an update for code snippet for the unit test:
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
When I run this unit test from the command line, I see:
>>>sudo python test_sys_mon.py
-DBG- CPU Use call from terminal returns: 3.2
When I run my test suite using py.test integrated with setup.py, I see:
>>>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 -----------------------------
It looks like this os.popen()
is returning an empty string, but I'm not sure how to fix this so I can use the top command with py.test