diff --git a/HISTORY.rst b/HISTORY.rst index 9c12ce95b..b5775bfd4 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -8,6 +8,8 @@ Bug tracker at https://github.com/giampaolo/psutil/issues - #798: [Windows] Process.open_files() returns and empty list on Windows 10. - #880: [Windows] Handle race condition inside psutil_net_connections. +- #885: ValueError is raised if a negative integer is passed to cpu_percent() + functions. 4.3.1 - 2016-09-01 diff --git a/psutil/__init__.py b/psutil/__init__.py index 7a557d075..0a6f3ec6f 100644 --- a/psutil/__init__.py +++ b/psutil/__init__.py @@ -921,13 +921,17 @@ def cpu_percent(self, interval=None): >>> """ blocking = interval is not None and interval > 0.0 + if interval is not None and interval < 0: + raise ValueError("interval is not positive (got %r)" % interval) num_cpus = cpu_count() or 1 + if POSIX: def timer(): return _timer() * num_cpus else: def timer(): return sum(cpu_times()) + if blocking: st1 = timer() pt1 = self._proc.cpu_times() @@ -1566,6 +1570,8 @@ def cpu_percent(interval=None, percpu=False): global _last_cpu_times global _last_per_cpu_times blocking = interval is not None and interval > 0.0 + if interval is not None and interval < 0: + raise ValueError("interval is not positive (got %r)" % interval) def calculate(t1, t2): t1_all = sum(t1) @@ -1639,6 +1645,8 @@ def cpu_times_percent(interval=None, percpu=False): global _last_cpu_times_2 global _last_per_cpu_times_2 blocking = interval is not None and interval > 0.0 + if interval is not None and interval < 0: + raise ValueError("interval is not positive (got %r)" % interval) def calculate(t1, t2): nums = [] diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index 0d7d06be3..78f057df9 100644 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -255,6 +255,8 @@ def test_cpu_percent(self): self.assertLessEqual(percent, 100.0) else: self.assertGreaterEqual(percent, 0.0) + with self.assertRaises(ValueError): + p.cpu_percent(interval=-1) def test_cpu_times(self): times = psutil.Process().cpu_times() diff --git a/psutil/tests/test_system.py b/psutil/tests/test_system.py index f5c9abd65..4a48a52bb 100644 --- a/psutil/tests/test_system.py +++ b/psutil/tests/test_system.py @@ -359,6 +359,8 @@ def test_cpu_percent(self): new = psutil.cpu_percent(interval=None) self._test_cpu_percent(new, last, new) last = new + with self.assertRaises(ValueError): + psutil.cpu_percent(interval=-1) def test_per_cpu_percent(self): last = psutil.cpu_percent(interval=0.001, percpu=True) @@ -368,6 +370,8 @@ def test_per_cpu_percent(self): for percent in new: self._test_cpu_percent(percent, last, new) last = new + with self.assertRaises(ValueError): + psutil.cpu_percent(interval=-1, percpu=True) def test_cpu_times_percent(self): last = psutil.cpu_times_percent(interval=0.001)