I've searched for documentation, but couldn't find any. There were a couple that didn't explain much.
Can someone explain to me Nose's
assert_raises(what should I put here?)
function and how to use it?
While the accepted answer is correct, I think there is a better use to assert_raises method.
If you simply want to assert that an exception occurs, it's probably simpler and cleaner to use #raises syntax.
#raises(HTTPError)
def test_exception_is_raised:
call_your_method(p1, p2)
However, assume you want to do bit more with the raised exception, for example: we need to assert that raised HTTPError is of type 401: Unauthorized, instead of 500: Server Error.
In such a situation above syntax is not that helpful, we should use the assert_raises but in a different way.
If we do not pass it a callable as the second parameter assert_raises will return back a context which we can use to further test the exception details.
def test_exception_is_raised:
with assert_raises(HTTPError) as cm:
call_your_method(p1, p2)
ex = cm.exception # raised exception is available through exception property of context
ok_(ex.code == 401, 'HTTPError should be Unauthorized!')
The assert_raises() function tests to make sure a function call raises a specified exception when presented with certain parameters.
For example, if you had a function add that adds two numbers, it should probably raise a TypeError when you pass it, say, an integer and a string. So:
from nose.tools import assert_raises
def add(x, y):
return x + y
assert_raises(TypeError, add, 2, "0")
The first argument is the exception type you expect. The second is the function to call. The rest of the arguments will be passed to the function (in this case, they will become x and y inside the function).
If the expected exception is raised by the function, the assertion passes.
Related
According to a given protocol (which I cannot change, only implement), some function initialize_foo() is supposed to be called only once:
def initialize_foo():
"""
...
Note:
You must call this function exactly once.
"""
I would like to recognize a protocol abuse where it is called twice, and raise an exception:
_foo_initialized = False
def initialize_foo():
"""
...
Note:
You must call this function exactly once.
"""
if _foo_initialized:
raise <what>?
...
_foo_initialized = True
The problem is what class's object to raise. Looking at the standard exceptions, I can't find anything to subclass except Exception, which seems too general.
What is the general practice in this case?
I'd use RuntimeError.
It is often used for that sort of stuff, even in the standard library. You can find an example very similar to your use case in the warnings module:
if self._entered:
raise RuntimeError("Cannot enter %r twice" % self)
Another example is in threading:
if self._started.is_set():
raise RuntimeError("threads can only be started once")
You can also consider raising an ad-hoc exception (possibly a subclass of RuntimeError) if that error is supposed to be caught and if you feel that RuntimeError may be ambiguous.
I would recommend you to subclass a warning, instead of having an exception, since I have a feeling that a lot of times you'd rather continue running after this happens.
I have an outer function that calls an inner function by passing the arguments along. Is it possible to test that both functions throw the same exception/error without knowing the exact error type?
I'm looking for something like:
def test_invalidInput_throwsSameError(self):
arg = 'invalidarg'
self.assertRaisesSameError(
innerFunction(arg),
outerFunction(arg)
)
Assuming you're using unittest (and python2.7 or newer) and that you're not doing something pathological like raising old-style class instances as errors, you can get the exception from the error context if you use assertRaises as a context manager.
with self.assertRaises(Exception) as err_context1:
innerFunction(arg)
with self.assertRaises(Exception) as err_context2:
outerFunction(arg)
# Or some other measure of "sameness"
self.assertEqual(
type(err_context1.exception),
type(err_context2.exception))
First call the first function and capture what exception it raises:
try:
innerfunction(arg)
except Exception as e:
pass
else:
e = None
Then assert that the other function raises the same exception:
self.assertRaises(e, outerfunction, arg)
I believe this will do what you want; just add it as another method of your TestCase class:
def assertRaisesSameError(self, *funcs, bases=(Exception,)):
exceptions = []
for func in funcs:
with self.assertRaises(base) as error_context:
func()
exceptions.append(error_context.exception)
for exc in exceptions:
self.assertEqual(type(exc), type(exc[-1]))
I haven't tested this, but it should work. For simplicity this only takes functions with no arguments, so if your function does have arguments, you'll have to make a wrapper (even just with a lambda). It would not be hard at all to expand this to allow for passing in the *args and **kwargs.
Let me know of any changes anyone thinks should be made.
I have a function:
def f(x):
if x == 'dog':
print('ok')
elif x == 'cat':
print('ok')
else:
raise MyException('Not an x i would expect')
I m adding an exception in case one day i change whatever supplies x to f() and forget to fix f(), so that i can easily find the problem.
Is this the wrong way to "remember" to change f() when needed?
Secondly, f() is a part of another function that might get a decorator that handles certain exceptions:
#an_exception_handler
def g(x):
f(x)
return 1000
I don't want #an_exception_handler to accidentally handle MyException (if MyException is child of ValueError for example, and #an_exception_handler handles ValueError).
Should MyException be a custom exception, or use an existing rarely occurring exception?
If you really don't want to make MyException a subclass of ValueError you should definitely make your own exception class, except you find another exception class that describes the exception equally good.
To be honest, your way of handling "all ValueErrors but this one" (and by concept this definitely is a ValueError) feels a bit inconsidtent. What are you trying to accomplish with that?
As PM 2Ring pointed out in his comment, an assertion would also be a good way to go. Probably better than another exception.
Does Python has a feature that allows one to evaluate a function or expression and if the evaluation fails (an exception is raised) return a default value.
Pseudo-code:
evaluator(function/expression, default_value)
The evaluator will try to execute the function or expression and return the result is the execution is successful, otherwise the default_value is returned.
I know I create a user defined function using try and except to achieve this but I want to know if the batteries are already included before going off and creating a custom solution.
In order to reuse code, you can create a decorating function (that accepts a default value) and decorate your functions with it:
def handle_exceptions(default):
def wrap(f):
def inner(*a):
try:
return f(*a)
except Exception, e:
return default
return inner
return wrap
Now let's see an example:
#handle_exceptions("Invalid Argument")
def test(num):
return 15/num
#handle_exceptions("Input should be Strings only!")
def test2(s1, s2):
return s2 in s1
print test(0) # "Invalid Argument"
print test(15) # 1
print test2("abc", "b") # True
print test2("abc", 1) # Input should be Strings only!
No, the standard way to do this is with try... except.
There is no mechanism to hide or suppress any generic exception within a function. I suspect many Python users would consider indiscriminate use of such a function to be un-Pythonic for a couple reasons:
It hides information about what particular exception occurred. (You might not want to handle all exceptions, since some could come from other libraries and indicate conditions that your program can't recover from, like running out of disk space.)
It hides the fact that an exception occurred at all; the default value returned in case of an exception might coincide with a valid non-default value. (Sometimes reasonable, sometimes not really so.)
One of the principles of the Pythonic philosophy, I believe, is that "explicit is better than implicit," so Python generally avoids automatic type casting and error recovery, which are features of more "implicit- friendly"languages like Perl.
Although the try... except form can be a bit verbose, in my opinion it has a lot of advantages in terms of clearly showing where an exception may occur and what the control flow is around that exception.
Could you please explain why does the followin function return "1" when there is an exception? What is the purpose of returning "1"?
def initialize():
"""
Starting point for the program.
"""
try:
go = Car()
print "Instance of Car created"
except KeyboardInterrupt:
return 1
It's a fairly common idiom in C to return a non-zero value in case of an error.
My hunch here is that the person who created this function was used to programming in C and unfamiliar with exception handling. It's impossible to tell without a larger code sample, but if I'm right, then there is probably some sort of error handling present where this function is called in the case that this function returns 1, or a non-zero value.
If this is the case, a more proper way to use the exception would be to either use raise to pass the exception upward to be handled else where, or handle the exception right there in the function.
In my opinion there's no need to do this, only if the Car() constructor takes too long and you want to deal with it once initialize() returns.