factory: Use str(Exception) instead of Exception.message

`Exception.message` is remove in python3.
We should always use `str(Exception)` to get the reason.

BUG=chromium:999876
TEST=make test
TEST=make lint

Change-Id: I327cac3e0f20de3ed95c1679961087f6f1331b3d
Reviewed-on: https://chromium-review.googlesource.com/1890460
Tested-by: Yilin Yang <kerker@chromium.org>
Commit-Ready: ChromeOS CL Exonerator Bot <chromiumos-cl-exonerator@appspot.gserviceaccount.com>
Legacy-Commit-Queue: Commit Bot <commit-bot@chromium.org>
Reviewed-by: Cheng-Han Yang <chenghan@chromium.org>
diff --git a/py/bundle_creator/docker/worker.py b/py/bundle_creator/docker/worker.py
index a7fa747..8864d90 100644
--- a/py/bundle_creator/docker/worker.py
+++ b/py/bundle_creator/docker/worker.py
@@ -60,7 +60,7 @@
     response_proto = factorybundle_pb2.WorkerResult()
     response_proto.status = factorybundle_pb2.WorkerResult.FAILED
     response_proto.original_request.MergeFrom(request_proto)
-    response_proto.error_message = e.message
+    response_proto.error_message = str(e)
     ResponseResult(tasks, response_proto)
 
 
diff --git a/py/device/ambient_light_sensor.py b/py/device/ambient_light_sensor.py
index 443108d..ae1c7f4 100644
--- a/py/device/ambient_light_sensor.py
+++ b/py/device/ambient_light_sensor.py
@@ -47,7 +47,7 @@
       self._device.WriteSpecialFile(
           os.path.join(self._iio_path, filename), value)
     except Exception as e:
-      raise AmbientLightSensorException(e.message)
+      raise AmbientLightSensorException(str(e))
 
   def _GetSysfsValue(self, filename, path=None):
     del path  # Unused.
@@ -55,7 +55,7 @@
       return self._device.ReadSpecialFile(os.path.join(
           self._iio_path, filename)).strip()
     except Exception as e:
-      raise AmbientLightSensorException(e.message)
+      raise AmbientLightSensorException(str(e))
 
   def CleanUpCalibrationValues(self):
     """Cleans up calibration values."""
@@ -76,21 +76,21 @@
     try:
       self._SetSysfsValue(signal_name, value)
     except Exception as e:
-      raise AmbientLightSensorException(e.message)
+      raise AmbientLightSensorException(str(e))
 
   def SetCalibrationIntercept(self, value):
     """Sets the calibration bias to sysfs."""
     try:
       self._SetSysfsValue(IN_ILLUMINANCE_BIAS, str(value))
     except Exception as e:
-      raise AmbientLightSensorException(e.message)
+      raise AmbientLightSensorException(str(e))
 
   def SetCalibrationSlope(self, value):
     """Sets the calibration scale to sysfs."""
     try:
       self._SetSysfsValue(IN_ILLUMINANCE_SCALE, str(value))
     except Exception as e:
-      raise AmbientLightSensorException(e.message)
+      raise AmbientLightSensorException(str(e))
 
   def GetLuxValue(self):
     """Reads the LUX raw value from sysfs."""
@@ -98,7 +98,7 @@
       return int(self._GetSysfsValue(self.input_entry))
     except Exception as e:
       logging.exception('Failed to get illuminance value')
-      raise AmbientLightSensorException(e.message)
+      raise AmbientLightSensorException(str(e))
 
   def ForceLightInit(self):
     """Froce als to apply the vpd value."""
@@ -109,7 +109,7 @@
     except Exception as e:
       logging.exception('Failed to invoke light-init.sh (%s, illuminance)',
                         device_name)
-      raise AmbientLightSensorException(e.message)
+      raise AmbientLightSensorException(str(e))
 
 
 class AmbientLightSensor(types.DeviceComponent):
diff --git a/py/device/vsync_sensor.py b/py/device/vsync_sensor.py
index aa3fce4..85444b4 100644
--- a/py/device/vsync_sensor.py
+++ b/py/device/vsync_sensor.py
@@ -56,25 +56,25 @@
     try:
       return self._device.ReadFile(os.path.join(path, filename)).strip()
     except Exception as e:
-      raise VSyncSensorException(e.message)
+      raise VSyncSensorException(str(e))
 
   def GetCount(self):
     try:
       return int(self._GetSysfsValue(IN_COUNT))
     except Exception as e:
-      raise VSyncSensorException("Failed to read count: %s" % e.message)
+      raise VSyncSensorException("Failed to read count: %s" % str(e))
 
   def GetFrequency(self):
     try:
       return int(self._GetSysfsValue(FREQUENCY))
     except Exception as e:
-      raise VSyncSensorException("Failed to read freq: %s" % e.message)
+      raise VSyncSensorException("Failed to read freq: %s" % str(e))
 
   def SetFrequency(self, freq):
     try:
       self._SetSysfsValue(FREQUENCY, str(freq))
     except Exception as e:
-      raise VSyncSensorException("Failed to set freq: %s" % e.message)
+      raise VSyncSensorException("Failed to set freq: %s" % str(e))
 
 
 class VSyncSensor(types.DeviceComponent):
diff --git a/py/goofy/goofy.py b/py/goofy/goofy.py
index 1f2918c..677c5ed 100755
--- a/py/goofy/goofy.py
+++ b/py/goofy/goofy.py
@@ -1117,7 +1117,7 @@
         logging.info('Active test list: %s', self.test_list.test_list_id)
       except type_utils.TestListError as e:
         logging.exception('Invalid active test list: %s', active_test_list)
-        startup_errors.append(e.message)
+        startup_errors.append(str(e))
 
       # Show all startup errors.
       if startup_errors:
diff --git a/py/hwid/service/appengine/git_util.py b/py/hwid/service/appengine/git_util.py
index 1b4f330..f9558d6 100644
--- a/py/hwid/service/appengine/git_util.py
+++ b/py/hwid/service/appengine/git_util.py
@@ -294,7 +294,7 @@
   try:
     commit_hash = branch_info['revision']
   except KeyError as ex:
-    raise GitUtilException('KeyError: %r' % ex.message)
+    raise GitUtilException('KeyError: %r' % str(ex))
 
   return commit_hash
 
diff --git a/py/hwid/service/appengine/hwid_api.py b/py/hwid/service/appengine/hwid_api.py
index d68c161..2cbeb7f 100644
--- a/py/hwid/service/appengine/hwid_api.py
+++ b/py/hwid/service/appengine/hwid_api.py
@@ -318,8 +318,8 @@
     try:
       self._hwid_validator.Validate(request.hwidConfigContents)
     except hwid_validator.ValidationError as e:
-      logging.exception('ValidationError: %r', e.message)
-      return hwid_api_messages.ValidateConfigResponse(errorMessage=e.message)
+      logging.exception('ValidationError: %r', str(e))
+      return hwid_api_messages.ValidateConfigResponse(errorMessage=str(e))
 
     return hwid_api_messages.ValidateConfigResponse()
 
@@ -347,9 +347,9 @@
       self._hwid_validator.ValidateChange(updated_contents,
                                           request.prevHwidConfigContents)
     except hwid_validator.ValidationError as e:
-      logging.exception('ValidationError: %r', e.message)
+      logging.exception('ValidationError: %r', str(e))
       return hwid_api_messages.ValidateConfigAndUpdateChecksumResponse(
-          errorMessage=e.message)
+          errorMessage=str(e))
 
     return hwid_api_messages.ValidateConfigAndUpdateChecksumResponse(
         newHwidConfigContents=updated_contents)
diff --git a/py/hwid/service/appengine/hwid_validator.py b/py/hwid/service/appengine/hwid_validator.py
index c4b57d8..5acb5d1 100644
--- a/py/hwid/service/appengine/hwid_validator.py
+++ b/py/hwid/service/appengine/hwid_validator.py
@@ -39,7 +39,7 @@
       database.Database.LoadData(
           hwid_config_contents, expected_checksum=expected_checksum)
     except HWIDException as e:
-      raise ValidationError(e.message)
+      raise ValidationError(str(e))
 
   def ValidateChange(self, hwid_config_contents, prev_hwid_config_contents):
     """Validates a HWID config change.
@@ -72,10 +72,10 @@
       verify_db_pattern.HWIDDBsPatternTest.VerifyParsedDatabasePattern(
           prev_db, db)
     except HWIDException as e:
-      raise ValidationError(e.message)
+      raise ValidationError(str(e))
 
     if db.project in CONFIG.board_mapping:
       try:
         vpg_module.GenerateVerificationPayload([db])
       except vpg_module.GenerateVerificationPayloadError as e:
-        raise ValidationError(e.message)
+        raise ValidationError(str(e))
diff --git a/py/hwid/service/appengine/ingestion.py b/py/hwid/service/appengine/ingestion.py
index 24ed1a6..6d086bc 100644
--- a/py/hwid/service/appengine/ingestion.py
+++ b/py/hwid/service/appengine/ingestion.py
@@ -298,7 +298,7 @@
       try:
         new_files = vpg_module.GenerateVerificationPayload(db_list)
       except vpg_module.GenerateVerificationPayloadError as ex:
-        logging.error('Generate Payload fail: %s', ex.message)
+        logging.error('Generate Payload fail: %s', str(ex))
         mail.send_mail(
             sender='ChromeOS HW Checker Bot <{}>'.format(self.hw_checker_mail),
             to=self.hw_checker_mail,
diff --git a/py/hwid/service/appengine/test/e2e_test.py b/py/hwid/service/appengine/test/e2e_test.py
index dd097bc..47c6de1 100755
--- a/py/hwid/service/appengine/test/e2e_test.py
+++ b/py/hwid/service/appengine/test/e2e_test.py
@@ -78,7 +78,7 @@
             f.write(json.dumps({'expect': expecting_output, 'got': r}))
             failed_tests.append((test['name'], f.name))
       except Exception as e:
-        logging.exception('Unknown failure at %s: %s', test['name'], e.message)
+        logging.exception('Unknown failure at %s: %s', test['name'], str(e))
         failed_tests.append(test['name'])
 
     logging.info('[%d/%d] Passed',
diff --git a/py/instalog/core.py b/py/instalog/core.py
index b266ce2..91fa9dc 100644
--- a/py/instalog/core.py
+++ b/py/instalog/core.py
@@ -299,7 +299,7 @@
             json_utils.WalkJSONPath(json_path, store_data))
       except Exception as e:
         return False, ('Error on inspect with JSON path `%s\': %s'
-                       % (json_path, e.message))
+                       % (json_path, str(e)))
 
   def Flush(self, plugin_id, timeout):
     """Flushes the given plugin with given timeout.
diff --git a/py/instalog/plugin_loader.py b/py/instalog/plugin_loader.py
index 0293292..e8f368b 100644
--- a/py/instalog/plugin_loader.py
+++ b/py/instalog/plugin_loader.py
@@ -132,7 +132,7 @@
         __import__(search_name)
         return sys.modules[search_name]
       except ImportError as e:
-        if e.message.startswith('No module named'):
+        if str(e).startswith('No module named'):
           continue
         # Any other ImportError problem.
         self._ReportException()
@@ -219,6 +219,6 @@
       return plugin_class(self.config, self._logger.name, self._store,
                           self._plugin_api)
     except arg_utils.ArgError as e:
-      self._ReportException('Error parsing arguments: %s' % e.message)
+      self._ReportException('Error parsing arguments: %s' % str(e))
     except Exception:
       self._ReportException()
diff --git a/py/test/fixture/whale/host/dolphin_server.py b/py/test/fixture/whale/host/dolphin_server.py
index b44b1b3..36f79f2 100755
--- a/py/test/fixture/whale/host/dolphin_server.py
+++ b/py/test/fixture/whale/host/dolphin_server.py
@@ -127,7 +127,7 @@
   except KeyboardInterrupt:
     sys.exit(0)
   except serial_server.SerialServerError as e:
-    sys.stderr.write('Error: ' + e.message)
+    sys.stderr.write('Error: ' + str(e))
     sys.exit(1)
 
 
diff --git a/py/test/fixture/whale/host/interrupt_handler.py b/py/test/fixture/whale/host/interrupt_handler.py
index e7f1fc4..6eab393 100755
--- a/py/test/fixture/whale/host/interrupt_handler.py
+++ b/py/test/fixture/whale/host/interrupt_handler.py
@@ -501,5 +501,5 @@
   except KeyboardInterrupt:
     sys.exit(0)
   except gpio_utils.GpioManagerError as e:
-    sys.stderr.write(e.message + '\n')
+    sys.stderr.write(str(e) + '\n')
     sys.exit(1)
diff --git a/py/test/fixture/whale/serial_client.py b/py/test/fixture/whale/serial_client.py
index fbd6311..815a7b1 100755
--- a/py/test/fixture/whale/serial_client.py
+++ b/py/test/fixture/whale/serial_client.py
@@ -181,7 +181,7 @@
   except KeyboardInterrupt:
     sys.exit(0)
   except SerialClientError as e:
-    sys.stderr.write(e.message + '\n')
+    sys.stderr.write(str(e) + '\n')
     sys.exit(1)
 
 
diff --git a/py/test/pytests/light_sensor_calibration.py b/py/test/pytests/light_sensor_calibration.py
index b183838..063c682 100644
--- a/py/test/pytests/light_sensor_calibration.py
+++ b/py/test/pytests/light_sensor_calibration.py
@@ -243,7 +243,7 @@
       self.als_controller = self.dut.ambient_light_sensor.GetController()
     except Exception as e:
       self._LogFailure(FAIL_ALS_NOT_FOUND,
-                       'Error getting ALS controller: %s' % e.message)
+                       'Error getting ALS controller: %s' % str(e))
       raise
 
     # Loads config.
@@ -253,7 +253,7 @@
         raise ValueError('No available configuration.')
       self._LogConfig()
     except Exception as e:
-      logging.exception('Error logging config file: %s', e.message)
+      logging.exception('Error logging config file: %s', str(e))
       raise
 
     self.read_delay = self.config['read_delay']
@@ -279,7 +279,7 @@
           fixture_conn=self.fixture_conn, fixture_cmd=self.args.chamber_cmd)
     except Exception as e:
       self._LogFailure(FAIL_CHAMBER_ERROR,
-                       'Error setting up ALS chamber: %s' % e.message)
+                       'Error setting up ALS chamber: %s' % str(e))
 
     self.all_sampled_lux = []  # mean of sampled lux for each light
     self.scale_factor = None  # value of calibrated scale factor
@@ -323,7 +323,7 @@
         self.als_controller.CleanUpCalibrationValues()
     except Exception as e:
       self._LogFailure(FAIL_ALS_CLEAN, 'Error cleaning up calibration values:'
-                       ' %s' % e.message)
+                       ' %s' % str(e))
       raise
 
     while True:
@@ -337,7 +337,7 @@
         self._SampleALS(light_name)
       except Exception as e:
         self._LogFailure(FAIL_ALS_SAMPLE, 'Error sampling lighting %d %s: %s' %
-                         (self.light_index, light_name, e.message))
+                         (self.light_index, light_name, str(e)))
         raise
 
     try:
@@ -345,7 +345,7 @@
       self._CheckALSOrdering()
     except Exception as e:
       self._LogFailure(FAIL_ALS_ORDER,
-                       'Error checking als ordering: %s' % e.message)
+                       'Error checking als ordering: %s' % str(e))
       raise
 
 
@@ -354,7 +354,7 @@
       self._CalculateCalibCoef()
     except Exception as e:
       self._LogFailure(FAIL_ALS_CALC, 'Error calculating calibration'
-                       ' coefficient: %s' % e.message)
+                       ' coefficient: %s' % str(e))
       raise
 
     try:
@@ -362,7 +362,7 @@
       self._SaveCalibCoefToVPD()
     except Exception as e:
       self._LogFailure(FAIL_ALS_VPD, 'Error setting calibration'
-                       ' coefficient to VPD: %s' % e.message)
+                       ' coefficient to VPD: %s' % str(e))
       raise
 
     try:
@@ -372,7 +372,7 @@
       self._ValidateALS(light_name)
     except Exception as e:
       self._LogFailure(FAIL_ALS_VALID,
-                       'Error validating calibrated ALS: %s' % e.message)
+                       'Error validating calibrated ALS: %s' % str(e))
       raise
 
   def _OnU2SInsertion(self, device):
@@ -411,7 +411,7 @@
       self.chamber.Connect()
     except Exception as e:
       self._LogFailure(FAIL_CHAMBER_ERROR, 'Error initializing the ALS fixture:'
-                       ' %s' % e.message)
+                       ' %s' % str(e))
       raise
     self._Log('Test fixture successfully initialized.')
 
@@ -423,7 +423,7 @@
       self.chamber.SetLight(light)
     except Exception as e:
       self._LogFailure(FAIL_CHAMBER_ERROR,
-                       'Error commanding ALS chamber: %s' % e.message)
+                       'Error commanding ALS chamber: %s' % str(e))
       raise
     self.Sleep(self.config['light_delay'])
 
@@ -450,7 +450,7 @@
           testlog.LogParam('elapsed', elapsed_time)
           self._Log('%r: %r' % (elapsed_time, buf[-1]))
     except ambient_light_sensor.AmbientLightSensorException as e:
-      logging.exception('Error reading ALS value: %s', e.message)
+      logging.exception('Error reading ALS value: %s', str(e))
       raise
     return float(np.mean(buf))
 
@@ -582,7 +582,7 @@
         self._ALSTest()
 
     except Exception as e:
-      fail_msg = e.message
+      fail_msg = str(e)
       self._ShowTestStatus(
           i18n.NoTranslation('ALS: FAIL %r' % fail_msg), style='color-bad')
       self.fail('Test ALS failed - %r.' % fail_msg)
diff --git a/py/test/pytests/retrieve_config.py b/py/test/pytests/retrieve_config.py
index e9e47d1..0834c4b 100644
--- a/py/test/pytests/retrieve_config.py
+++ b/py/test/pytests/retrieve_config.py
@@ -175,7 +175,7 @@
       logging.info('Saved config to %s.', self.config_save_path)
     except Exception as e:
       logging.exception('Failed to retrieve config from factory server.')
-      raise RetrieveConfigException(e.message)
+      raise RetrieveConfigException(str(e))
 
   def _RetrieveConfigFromUSB(self):
     """Loads json config from USB drive."""
@@ -206,7 +206,7 @@
       except IOError as e:
         logging.error('Failed to copy file %s to %s, %r', pathname,
                       self.config_save_path, e)
-        raise RetrieveConfigException(e.message)
+        raise RetrieveConfigException(str(e))
 
   def _OnUSBInsertion(self, device):
     self.usb_dev_path = device.device_node
diff --git a/py/test/pytests/wifi_throughput.py b/py/test/pytests/wifi_throughput.py
index 24c502a..96eec9f 100644
--- a/py/test/pytests/wifi_throughput.py
+++ b/py/test/pytests/wifi_throughput.py
@@ -406,10 +406,10 @@
                                ap_config.ssid, fn.__name__, status)
       except self._TestException as e:
         logging.exception('Failed to run %s(**kwargs=%s)', fn.__name__, kwargs)
-        e.message = '[%s] FAIL [%s] %s' % (
-            ap_config.ssid, fn.__name__, e.message)
-        self._log['failures'].append(e.message)
-        session.console.error(e.message)
+        message = '[%s] FAIL [%s] %s' % (
+            ap_config.ssid, fn.__name__, str(e))
+        self._log['failures'].append(message)
+        session.console.error(message)
         if abort:
           raise
 
diff --git a/py/test/run_pytest.py b/py/test/run_pytest.py
index 55deadb..a49d5af 100755
--- a/py/test/run_pytest.py
+++ b/py/test/run_pytest.py
@@ -97,7 +97,7 @@
     arg_spec = getattr(test, 'ARGS', [])
     test.args = Args(*arg_spec).Parse(args or {})
   except Exception as e:
-    return (False, e.message)
+    return (False, str(e))
 
   # Run the test and return the result.
   result = pytest_utils.RunTestCase(test)
diff --git a/py/test/test_ui_unittest.py b/py/test/test_ui_unittest.py
index a21ac46..351eda5 100755
--- a/py/test/test_ui_unittest.py
+++ b/py/test/test_ui_unittest.py
@@ -996,7 +996,7 @@
       try:
         next(iterable)
       except type_utils.TestFailure as e:
-        self.assertRegexpMatches(e.message, r'^Timed out')
+        self.assertRegexpMatches(str(e), r'^Timed out')
         break
 
       self.AssertEventsPosted(
diff --git a/py/tools/finalize_bundle.py b/py/tools/finalize_bundle.py
index ec5e939..862805b 100755
--- a/py/tools/finalize_bundle.py
+++ b/py/tools/finalize_bundle.py
@@ -218,7 +218,7 @@
                      'toolkit', 'test_image', 'release_image', 'firmware',
                      'hwid', 'has_firmware'])
     except ValueError as e:
-      logging.error(e.message)
+      logging.error(str(e))
       raise FinalizeBundleException(
           'Invalid manifest content. '
           'Please refer to setup/BUNDLE.md (https://goo.gl/pM1pxo)')
diff --git a/py/tools/flash_netboot.py b/py/tools/flash_netboot.py
index 2a7ac91..5aeff99 100755
--- a/py/tools/flash_netboot.py
+++ b/py/tools/flash_netboot.py
@@ -131,7 +131,7 @@
   try:
     netboot_flasher = FlashNetboot(args.image)
   except ValueError as e:
-    parser.error(e.message)
+    parser.error(str(e))
 
   sys.stdout.write(netboot_flasher.WarningMessage())
 
diff --git a/py/tools/ghost.py b/py/tools/ghost.py
index 5989b57..9e2790c 100755
--- a/py/tools/ghost.py
+++ b/py/tools/ghost.py
@@ -1202,13 +1202,13 @@
         # Don't show stack trace for RuntimeError, which we use in this file for
         # plausible and expected errors (such as can't connect to server).
         except RuntimeError as e:
-          logging.info('%s, retrying in %ds', e.message, _RETRY_INTERVAL)
+          logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
           time.sleep(_RETRY_INTERVAL)
         except Exception as e:
           unused_x, unused_y, exc_traceback = sys.exc_info()
           traceback.print_tb(exc_traceback)
           logging.info('%s: %s, retrying in %ds',
-                       e.__class__.__name__, e.message, _RETRY_INTERVAL)
+                       e.__class__.__name__, str(e), _RETRY_INTERVAL)
           time.sleep(_RETRY_INTERVAL)
 
         self.Reset()
diff --git a/py/tools/test_list_checker.py b/py/tools/test_list_checker.py
index 81b85f0..514dda3 100755
--- a/py/tools/test_list_checker.py
+++ b/py/tools/test_list_checker.py
@@ -41,7 +41,7 @@
   try:
     test_list.CheckValid()
   except Exception as e:
-    if isinstance(e, KeyError) and e.message == 'tests':
+    if isinstance(e, KeyError) and str(e) == 'tests':
       logging.warning('Test list "%s" does not have "tests" field. '
                       'Fine for generic test lists.', test_list_id)
     else:
diff --git a/py/utils/config_utils.py b/py/utils/config_utils.py
index 5a19273..e8c3386 100644
--- a/py/utils/config_utils.py
+++ b/py/utils/config_utils.py
@@ -513,7 +513,7 @@
       except Exception as e:
         # Only get the `message` property of the exception to prevent
         # from dumping whole schema data in the log.
-        raise ConfigInvalidError(e.message, raw_config_list.CollectDepend())
+        raise ConfigInvalidError(str(e), raw_config_list.CollectDepend())
 
     else:
       logger('Configuration schema <%s> not validated because jsonschema '