Fix UnicodeDecodeError when reading file to determine virtual grain

This commit is contained in:
Ch3LL 2018-06-19 16:38:28 -04:00
parent 5b4897f050
commit c4334f3f14
No known key found for this signature in database
GPG Key ID: 132B55A7C13EFA73
2 changed files with 30 additions and 1 deletions

View File

@ -947,7 +947,7 @@ def _virtual(osdata):
if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
try:
with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
output = fhr.read()
output = salt.utils.stringutils.to_unicode(fhr.read())
if 'VirtualBox' in output:
grains['virtual'] = 'VirtualBox'
elif 'RHEV Hypervisor' in output:

View File

@ -946,3 +946,32 @@ class CoreGrainsTestCase(TestCase, LoaderModuleMockMixin):
grains = {k: v for k, v in os_grains.items()
if k in set(['product', 'productname'])}
self.assertEqual(grains, expectation)
@patch('os.path.isfile')
@patch('os.path.isdir')
def test_core_virtual_unicode(self, mock_file, mock_dir):
'''
test virtual grain with unicode character in product_name file
'''
def path_side_effect(path):
if path == '/sys/devices/virtual/dmi/id/product_name':
return True
return False
virt = 'kvm'
mock_file.side_effect = path_side_effect
mock_dir.side_effect = path_side_effect
with patch.object(salt.utils.platform, 'is_windows',
MagicMock(return_value=False)):
with patch.object(salt.utils.path, 'which',
MagicMock(return_value=True)):
with patch.dict(core.__salt__, {'cmd.run_all':
MagicMock(return_value={'pid': 78,
'retcode': 0,
'stderr': '',
'stdout': virt})}):
with patch('salt.utils.files.fopen',
mock_open(read_data='')):
osdata = {'kernel': 'Linux', }
ret = core._virtual(osdata)
self.assertEqual(ret['virtual'], virt)