From 6935bd2f069b51635441a1b7f42c56106950feb2 Mon Sep 17 00:00:00 2001 From: Thiago Paiva Date: Thu, 4 Feb 2016 11:29:06 -0300 Subject: [PATCH] Adding fancy exceptions messages OneViewException and its subclasses are meant to have a default message that can be overwritten by passing a custom message in the instantiation method. This patch ensure it happens without aid of the builtin class Exception and overwrite __str__ to include information about the class of the exception being thrown to ease debug. To obtain just the exception message, users can still access the exc.message variable. Change-Id: I278e38dadf9b612009156ecfce62a0d31e9caa94 --- oneview_client/exceptions.py | 7 +++++ oneview_client/tests/test_exceptions.py | 38 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 oneview_client/tests/test_exceptions.py diff --git a/oneview_client/exceptions.py b/oneview_client/exceptions.py index 1ae1438..1b1657b 100644 --- a/oneview_client/exceptions.py +++ b/oneview_client/exceptions.py @@ -19,6 +19,13 @@ class OneViewException(Exception): message = ("An error occurred in the OneView client.") + def __init__(self, msg=None): + if msg: + self.message = msg + + def __str__(self): + return "<%s> %s" % (self.__class__.__name__, self.message) + class OneViewConnectionError(OneViewException): message = ("Can't connect to OneView") diff --git a/oneview_client/tests/test_exceptions.py b/oneview_client/tests/test_exceptions.py new file mode 100644 index 0000000..605be22 --- /dev/null +++ b/oneview_client/tests/test_exceptions.py @@ -0,0 +1,38 @@ +# -*- encoding: utf-8 -*- +# +# (c) Copyright 2015 Hewlett Packard Enterprise Development LP +# Copyright 2015 Universidade Federal de Campina Grande +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +from oneview_client import exceptions + + +class Test(unittest.TestCase): + + def test_create_OneViewException_default_message(self): + exc = exceptions.OneViewException() + self.assertEqual( + str(exc), + "<%s> %s" % (exc.__class__.__name__, exc.message) + ) + + def test_create_OneViewException_message(self): + msg = "This is a custom message" + exc = exceptions.OneViewException(msg) + self.assertEqual( + str(exc), + "<%s> %s" % (exc.__class__.__name__, msg) + )