How to assert operators < and>= are not implemente

2019-07-17 06:42发布

问题:

Initially I was not using the unittest framework, so to test that two objects of the same class are not comparable using the operators < and >= I did something like:

try:
    o1 < o2
    assert False
except TypeError:
    pass

after that, though, I decided to start using the unittest module, so I'm converting my tests to the way tests are written with the same module.

I was trying to accomplish the equivalent thing as above with:

self.assertRaises(TypeError, o1 < o2)

but this does not quite work, because o1 < o2 tries to call the operator <, instead of being a reference to a function, which should be called as part of the test.

Is there a way to accomplish what I need without needing to wrap o1 < o2 in a function?

回答1:

Use assertRaises as a context manager:

with self.assertRaises(TypeError):
    o1 < o2

Here is an explanation of the with statement. Here are the docs. TL;DR: It allows the execution of a code block with a "context", i.e. things to be set up and disposed before/after the execution, error handling etc.

In the case of assertRaises, its context manager simply checks whether an execption of the required type has been raised, by checking the exc agrument passed to its __exit__ method.