I'm trying to run this test: self.assertRaises(AttributeError, branch[0].childrennodes), and branch[0] does not have an attribute childrennodes, so it should be throwing an AttributeError, which the assertRaises should catch, but when I run the test, the test fails because it is throwing an AttributeError.
Traceback (most recent call last):
File "/home/tttt/../tttt/tests.py", line 504, in test_get_categories_branch
self.assertRaises(AttributeError, branch[0].children_nodes)
AttributeError: 'Category' object has no attribute 'children_nodes'
Any ideas?
When the test is running, before calling self.assertRaises, Python needs to find the value of all the method's arguments. In doing so, it evaluates branch[0].children_nodes, which raises an AttributeError. Since we haven't invoked assertRaises yet, this exception is not caught, causing the test to fail.
The solution is to wrap branch[0].children_nodes in a function or a lambda:
self.assertRaises(AttributeError, lambda: branch[0].children_nodes)
assertRaises can also be used as a context manager (Since Python 2.7, or in PyPI package 'unittest2'):
with self.assertRaises(AttributeError):
branch[0].children_nodes
# etc
This is nice because it can be used on arbitrary blocks of code in the middle of a test, rather than having to create a new function just to define the block of code to which it applies.
It can give you access to the raised exception for further processing, if needed:
with self.assertRaises(AttributeError) as cm:
branch[0].children_nodes
self.assertEquals(cm.exception.special_attribute, 123)
I think its because assert raises only accepts a callable. It evalutes to see if the callable raises an exception, not if the statement itself does.
self.assertRaises(AttributeError, getattr, branch[0], "childrennodes")
should work.
EDIT:
As THC4k correctly says it gathers the statements at collection time and will error then, not at testing time.
Also this is a reason why I like nose, it has a decorator (raises) that is useful and clearer for these kind of tests.
#raises(AttributeError)
def test_1(self)
branch[0].childrennodes
pytest also has a similar context manager:
from pytest import raises
def test_raising():
with raises(AttributeError):
branch[0].childrennodes
Related
Consider the following example that uses __subclasscheck__ for a custom exception type:
class MyMeta(type):
def __subclasscheck__(self, subclass):
print(f'__subclasscheck__({self!r}, {subclass!r})')
class MyError(Exception, metaclass=MyMeta):
pass
Now when raising an exception of this type, the __subclasscheck__ method gets invoked; i.e. raise MyError() results in:
__subclasscheck__(<class '__main__.MyError'>, <class '__main__.MyError'>)
Traceback (most recent call last):
File "test.py", line 8, in <module>
raise MyError()
__main__.MyError
Here the first line of the output shows that __subclasscheck__ got invoked to check whether MyError is a subclass of itself, i.e. issubclass(MyError, MyError). I'd like to understand why that's necessary and how it's useful in general.
I'm using CPython 3.8.1 to reproduce this behavior. I also tried PyPy3 (3.6.9) and here __subclasscheck__ is not invoked.
I guess this is a CPython implementation detail. As stated in documentation to PyErr_NormalizeException:
Under certain circumstances, the values returned by PyErr_Fetch()
below can be “unnormalized”, meaning that *exc is a class object but
*val is not an instance of the same class.
So sometime during the processing of the raised error, CPython will normalize the exception, because otherwise it cannot assume that the value of the error is of the right type.
In your case it happens as follows:
Eventually while processing the exception, PyErr_Print is called, where it calls _PyErr_NormalizeException.
_PyErr_NormaliizeException calls PyObject_IsSubclass.
PyObject_IsSubclass uses __subclasscheck__ if it is provided.
I cannot say what those "certain circumstances" for "*exc is a class object but *val is not an instance of the same class" are (maybe needed for backward compatibility - I don't know).
My first assumption was, that it happens, when CPython ensures (i.e. here), that the exception is derived from BaseException.
The following code
class OldStyle():
pass
raise OldStyle
would raise OldStyle for Python2, but TypeError: exceptions must be old-style classes or derived from BaseException, not type for
class NewStyle(object):
pass
raise NewStyle
or TypeError: exceptions must derive from BaseException in Python3 because in Python3 all classes are "new style".
However, for this check not PyObject_IsSubclass but PyType_FastSubclass is used:
#define PyExceptionClass_Check(x) \
(PyType_Check((x)) && \
PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
i.e. only the tpflags are looked at.
I'm a minor contributor to a package where people are meant to do this (Foo.Bar.Bar is a class):
>>> from Foo.Bar import Bar
>>> s = Bar('a')
Sometimes people do this by mistake (Foo.Bar is a module):
>>> from Foo import Bar
>>> s = Bar('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
This might seems simple, but users still fail to debug it, I would like to make it easier. I can't change the names of Foo or Bar but I would like to add a more informative traceback like:
TypeError("'module' object is not callable, perhaps you meant to call 'Bar.Bar()'")
I read the Callable modules Q&A, and I know that I can't add a __call__ method to a module (and I don't want to wrap the whole module in a class just for this). Anyway, I don't want the module to be callable, I just want a custom traceback. Is there a clean solution for Python 3.x and 2.7+?
Add this to top of Bar.py: (Based on this question)
import sys
this_module = sys.modules[__name__]
class MyModule(sys.modules[__name__].__class__):
def __call__(self, *a, **k): # module callable
raise TypeError("'module' object is not callable, perhaps you meant to call 'Bar.Bar()'")
def __getattribute__(self, name):
return this_module.__getattribute__(name)
sys.modules[__name__] = MyModule(__name__)
# the rest of file
class Bar:
pass
Note: Tested with python3.6 & python2.7.
What you want is to change the error message when is is displayed to the user. One way to do that is to define your own excepthook.
Your own function could:
search the calling frame in the traceback object (which contains informations about the TypeError exception and the function which does that),
search the Bar object in the local variables,
alter the error message if the object is a module instead of a class or function.
In Foo.__init__.py you can install a your excepthook
import inspect
import sys
def _install_foo_excepthook():
_sys_excepthook = sys.excepthook
def _foo_excepthook(exc_type, exc_value, exc_traceback):
if exc_type is TypeError:
# -- find the last frame (source of the exception)
tb_frame = exc_traceback
while tb_frame.tb_next is not None:
tb_frame = tb_frame.tb_next
# -- search 'Bar' in the local variable
f_locals = tb_frame.tb_frame.f_locals
if 'Bar' in f_locals:
obj = f_locals['Bar']
if inspect.ismodule(obj):
# -- change the error message
exc_value.args = ("'module' object is not callable, perhaps you meant to call 'Foo.Bar.Bar()'",)
_sys_excepthook(exc_type, exc_value, exc_traceback)
sys.excepthook = _foo_excepthook
_install_foo_excepthook()
Of course, you need to enforce this algorithm…
With the following demo:
# coding: utf-8
from Foo import Bar
s = Bar('a')
You get:
Traceback (most recent call last):
File "/path/to/demo_bad.py", line 5, in <module>
s = Bar('a')
TypeError: 'module' object is not callable, perhaps you meant to call 'Foo.Bar.Bar()'
There are a lot of ways you could get a different error message, but they all have weird caveats and side effects.
Replacing the module's __class__ with a types.ModuleType subclass is probably the cleanest option, but it only works on Python 3.5+.
Besides the 3.5+ limitation, the primary weird side effects I've thought of for this option are that the module will be reported callable by the callable function, and that reloading the module will replace its class again unless you're careful to avoid such double-replacement.
Replacing the module object with a different object works on pre-3.5 Python versions, but it's very tricky to get completely right.
Submodules, reloading, global variables, any module functionality besides the custom error message... all of those are likely to break if you miss some subtle aspect of the implementation. Also, the module will be reported callable by callable, just like with the __class__ replacement.
Trying to modify the exception message after the exception is raised, for example in sys.excepthook, is possible, but there isn't a good way to tell that any particular TypeError came from trying to call your module as a function.
Probably the best you could do would be to check for a TypeError with a 'module' object is not callable message in a namespace where it looks plausible that your module would have been called - for example, if the Bar name is bound to the Foo.Bar module in either the frame's locals or globals - but that's still going to have plenty of false negatives and false positives. Also, sys.excepthook replacement isn't compatible with IPython, and whatever mechanism you use would probably conflict with something.
Right now, the problems you have are easy to understand and easy to explain. The problems you would have with any attempt to change the error message are likely to be much harder to understand and harder to explain. It's probably not a worthwhile tradeoff.
I'm using a Class provided by a client (I have no access to the object code), and I'm trying to check if a object has a attribute. The attribute itself is write only, so the hasattr fails:
>>> driver.console.con.input = 'm'
>>> hasattr(driver.console.con, 'input')
False
>>> simics> #driver.console.con.input
Traceback (most recent call last):
File "<string>", line 1, in <module>
Attribute: Failed converting 'input' attribute in object
'driver.console.con' to Python: input attribute in driver.console.con
object: not readable.
Is there a different way to check if an attribute exists?
You appear to have some kind of native code proxy that bridges Python to an extension, and it is rather breaking normal Python conventions
There are two possibilities:
The driver.console.con object has a namespace that implements attributes as descriptors, and the input descriptor only has a __set__ method (and possibly a __delete__ method). In that case, look for the descriptor:
if 'input' in vars(type(driver.console.con)):
# there is an `input` name in the namespace
attr = vars(type(driver.console.con))['input']
if hasattr(attr, '__set__'):
# can be set
...
Here the vars() function retrieves the namespace for the class used for driver.console.con.
The proxy uses __getattr__ (or even __getattribute__) and __setattr__ hooks to handle arbitrary attributes. You are out of luck here, you can't detect what attributes either method will support outside of hasattr() and trying to set the attribute directly. Use try...except guarding:
try:
driver.console.con.input = 'something'
except Attribute: # exactly what exception object does this throw?
# can't be set, not a writable attribute
pass
You may have to use a debugger or print() statement to figure out exactly what exception is being thrown (use a try...except Exception as ex: block to capture all exceptions then inspect ex); in the traceback in your question the exception message at the end looks decidedly non-standard. That project really should raise an AttributeError at that point.
Given the rather custom exception being thrown, my money is on option 2 (but option 1 is still a possibility if the __get__ method on the descriptor throws the exception).
For example, I want to test a function which has a syntax, in my unittest class's method, can I use code as the following?
self.assertRaises(SyntaxError, my_function)
When I use this, it just appears traceback of syntax error rather than showing how many tests have passed.
In order for the test to run, the code must be byte compiled by the Python interpreter. This happens when the module containing your function is imported, before the function is ever run. It is during the compilation that the SyntaxError is generated.
In your test module, you could wrap the import statement in a try/except:
raised = False
try:
import foo
except SyntaxError:
# A syntax error was generated during the import...
raised = True
self.assert_(raised, "'import foo' failed to raise a SyntaxError.")
or use one of the methods suggested by #alecxe, which look simpler and cleaner.
Following Warren Weckesser's explanation, you can test that an import function is throwing an error:
self.assertRaises(SyntaxError, __import__, "error_library")
For Python 2.7 and above, importlib.import_module() can/should be used instead:
self.assertRaises(SyntaxError, importlib.import_module, "error_library")
I want to setup a test suite wherein I will read a json file in setup_class method and in that json file I will mention which tests should run and which tests should not run. So with this approach I can mention which test cases to run by altering the json file only and not touching the test suite.
But in the setup_class method when I try to do the following:-
class TestCPU:
testme=False
#classmethod
def setup_class(cls):
cls.test_core.testme=True
def test_core(self):
print 'Test CPU Core'
assert 1
Executing below command:-
nosetests -s -a testme
It gives following error:-
File "/home/murtuza/HWTestCert/testCPU.py", line 7, in setup_class
cls.test_core.testme=False
AttributeError: 'instancemethod' object has no attribute 'testme'
So, is it possible to set the attributes of test methods during setup_class?
The way it is defined, testme is a member of the TestCPU class, and the <unbound method TestCPU.test_core> has no idea about this attribute. You can inject nose attribute by using cls.test_core.__dict__['testme']=True. However, the attributes are checked before your setup_class method is called, so even though the attribute will be set, your test will be skipped. But you can certainly decorate your test with attributes on import, like this:
import unittest
class TestCPU(unittest.TestCase):
def test_core(self):
print 'Test CPU Core'
assert 1
TestCPU.test_core.__dict__['testme']=True
You may also want to try --pdb option to nosetests, it will bring out debugger on error so that you can dive in to see what is wrong. It is definitely my second favorite thing in life.
I am sure there are multiple ways to achieve this, but here is one way you can do it.
Inside your test class, create a method that reads in your JSON file and creates a global array for methods to be skipped for testing - skiptests
All you need to do now is use a setup decorator for every test case method in your suite. Within this decorator, check if the current function is in skiptests. If so, call nosetests' custom decorator nose.tools.nottest which is used to skip a test. Otherwise, return the function being tested.
To put it in code:
def setup_test_method1(func):
if func.__name__ not in skiptests:
return func
else:
return nose.tools.nottest(func)
#with_setup(setup_test_method1)
def test_method1():
pass
I have not tested this code, but I think we can invoke a decorator within another decorator. In which case this could work.