From 20ad1e1aa859d3db4c623dbfc4ce0039daa34a47 Mon Sep 17 00:00:00 2001 From: Pavlo Shchelokovskyy Date: Fri, 17 Mar 2017 11:55:14 +0000 Subject: [PATCH] Fix file_has_content function for Py3 the reference file must be opened in binary mode, otherwise under Py3 it fails to update checksum with exception `Unicode must be encoded before hashing`. Change-Id: I3162fe9951750f5a41ef403b9a10ed68c0ba958a --- ironic/common/utils.py | 2 +- ironic/tests/unit/common/test_utils.py | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/ironic/common/utils.py b/ironic/common/utils.py index 30244e4e55..ab2788a51d 100644 --- a/ironic/common/utils.py +++ b/ironic/common/utils.py @@ -295,7 +295,7 @@ def file_has_content(path, content, hash_algo='md5'): :returns: True if the hash of reference content is the same as the hash of file's content, False otherwise """ - with open(path) as existing: + with open(path, 'rb') as existing: file_hash_hex = hash_file(existing, hash_algo=hash_algo) ref_hash = _get_hash_object(hash_algo) ref_hash.update(content) diff --git a/ironic/tests/unit/common/test_utils.py b/ironic/tests/unit/common/test_utils.py index 48527e7dee..cfb5e91c3f 100644 --- a/ironic/tests/unit/common/test_utils.py +++ b/ironic/tests/unit/common/test_utils.py @@ -250,15 +250,17 @@ class GenericUtilsTestCase(base.TestCase): data = b'Mary had a little lamb, its fleece as white as snow' ref = data with mock.patch('ironic.common.utils.open', - mock.mock_open(read_data=data)): + mock.mock_open(read_data=data)) as mopen: self.assertTrue(utils.file_has_content('foo', ref)) + mopen.assert_called_once_with('foo', 'rb') def test_file_has_content_differ(self): data = b'Mary had a little lamb, its fleece as white as snow' ref = data + b'!' with mock.patch('ironic.common.utils.open', - mock.mock_open(read_data=data)): + mock.mock_open(read_data=data)) as mopen: self.assertFalse(utils.file_has_content('foo', ref)) + mopen.assert_called_once_with('foo', 'rb') def test_is_valid_datapath_id(self): self.assertTrue(utils.is_valid_datapath_id("525400cf2d319fdf"))