Skip to content

Commit

Permalink
fix 1062: avoid TypeError on disk|net_io_counters() if no disks or NI…
Browse files Browse the repository at this point in the history
…Cs are installed on the system
  • Loading branch information
giampaolo committed May 12, 2017
1 parent 959bddc commit 2d32a26
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
- 1047_: [Windows] Process username(): memory leak in case exception is thrown.
- 1048_: [Windows] users()'s host field report an invalid IP address.
- 1058_: fixed Python warnings.
- 1062_: disk_io_counters() and net_io_counters() raise TypeError if no disks
or NICs are installed on the system.

**Porting notes**

Expand Down
4 changes: 4 additions & 0 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2083,6 +2083,8 @@ def disk_io_counters(perdisk=False, nowrap=True):
executed first otherwise this function won't find any disk.
"""
rawdict = _psplatform.disk_io_counters()
if not rawdict:
return {} if perdisk else None
if nowrap:
rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters')
nt = getattr(_psplatform, "sdiskio", _common.sdiskio)
Expand Down Expand Up @@ -2131,6 +2133,8 @@ def net_io_counters(pernic=False, nowrap=True):
cache.
"""
rawdict = _psplatform.net_io_counters()
if not rawdict:
return {} if pernic else None
if nowrap:
rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters')
if pernic:
Expand Down
18 changes: 18 additions & 0 deletions psutil/tests/test_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,15 @@ def check_ntuple(nt):
self.assertIsInstance(key, str)
check_ntuple(ret[key])

def test_net_io_counters_no_nics(self):
# Emulate a case where no NICs are installed, see:
# https://github.com/giampaolo/psutil/issues/1062
with mock.patch('psutil._psplatform.net_io_counters',
return_value={}) as m:
self.assertIsNone(psutil.net_io_counters(pernic=False))
self.assertEqual(psutil.net_io_counters(pernic=True), {})
assert m.called

def test_net_if_addrs(self):
nics = psutil.net_if_addrs()
assert nics, nics
Expand Down Expand Up @@ -682,6 +691,15 @@ def check_ntuple(nt):
key = key[:-1]
self.assertNotIn(key, ret.keys())

def test_disk_io_counters_no_disks(self):
# Emulate a case where no disks are installed, see:
# https://github.com/giampaolo/psutil/issues/1062
with mock.patch('psutil._psplatform.disk_io_counters',
return_value={}) as m:
self.assertIsNone(psutil.disk_io_counters(perdisk=False))
self.assertEqual(psutil.disk_io_counters(perdisk=True), {})
assert m.called

# can't find users on APPVEYOR or TRAVIS
@unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(),
"unreliable on APPVEYOR or TRAVIS")
Expand Down

0 comments on commit 2d32a26

Please sign in to comment.