Catch value error when extract log info from log name

We need to catch ValueError when we extract log information
from the file name provided by user.
Instead of raising an exception, we just log a warning to the
user. The normal usage can handle None uuid or timestamp or
validation-id.
This will aim to make the ValidationLog class more generic.

Change-Id: Iccc2a37b4c2c911e634a210de253ba1111e5b7e7
(cherry picked from commit 373bdb08d7)
This commit is contained in:
Mathieu Bultel 2020-06-10 15:43:32 +02:00 committed by mathieu bultel
parent b9ef0327dc
commit f208d26200
2 changed files with 26 additions and 2 deletions

View File

@ -37,6 +37,25 @@ class TestValidationLog(TestCase):
self.assertEquals(val.validation_id, 'foo')
self.assertEquals(val.datetime, '2020-03-30T13:17:22.447857Z')
@mock.patch('json.load')
@mock.patch('six.moves.builtins.open')
def test_validation_underscore_validation_id(self, mock_open, mock_json):
val = ValidationLog(
logfile='/tmp/123_foo_bar_2020-03-30T13:17:22.447857Z.json')
self.assertEquals(val.uuid, '123')
self.assertEquals(val.validation_id, 'foo_bar')
self.assertEquals(val.datetime, '2020-03-30T13:17:22.447857Z')
@mock.patch('json.load')
@mock.patch('six.moves.builtins.open')
def test_validation_wrong_log_file(self, mock_open, mock_json):
msg = ('Wrong log file format, it should be formed '
'such as {uuid}_{validation-id}_{timestamp}')
with mock.patch('logging.Logger.warning') as mock_log:
ValidationLog(
logfile='/tmp/foo_2020-03-30T13:17:22.447857Z.json')
mock_log.assert_called_with(msg)
@mock.patch('glob.glob')
@mock.patch('json.load',
return_value=fakes.VALIDATIONS_LOGS_CONTENTS_LIST[0])

View File

@ -41,9 +41,14 @@ class ValidationLog(object):
full_path = self.get_log_path()
self.content = self._get_content(full_path)
self.name = os.path.splitext(os.path.basename(full_path))[0]
# if we have a log file then extract uuid, validation_id and timestamp
if logfile:
self.uuid, self.validation_id, self.datetime = \
self.name.replace('.{}'.format(self.extension), '').split('_')
try:
self.uuid, _name = self.name.split('_', 1)
self.validation_id, self.datetime = _name.rsplit('_', 1)
except ValueError:
logging.warning('Wrong log file format, it should be formed '
'such as {uuid}_{validation-id}_{timestamp}')
def _get_content(self, file):
try: