How to assert operators < and >= are not implemented?
<p>Initially I was not using the <code>unittest</code> framework, so to test that two objects of the same class are not comparable using the operators <code>&lt;</code> and <code>&gt;=</code> I did something like:</p>

<pre><code>try:
    o1 &lt; o2
    assert False
except TypeError:
    pass
</code></pre>

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

<p>I was trying to accomplish the equivalent thing as above with:</p>

<pre><code>self.assertRaises(TypeError, o1 &lt; o2)
</code></pre>

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

<p>Is there a way to accomplish what I need without needing to wrap <code>o1 &lt; o2</code> in a function?</p>

<p>Use <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow"><code>assertRaises</code></a> as a context manager:</p>

<pre><code>with self.assertRaises(TypeError):
    o1 &lt; o2
</code></pre>

<p><a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow">Here</a> is an explanation of the <code>with</code> statement. <a href="https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers" rel="nofollow">Here</a> 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.</p>

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

python unit-testing python-3.x exception python-unittest