Can I mock an exception that is replace in a custom error handler?
<p>In an attempt to use <code>patch</code> from <code>mock</code> to write unit tests to validate our custom <code>urllib2</code> error handler that logs the error before raising a custom error, I cannot get the custom error to <code>raise</code>. The mocked exception will always <code>raise</code> after the log line in <code>LoggingErrorHandler</code> executes successfully. i.e. my test code is looking for <code>CustomError</code>, but the function still, surprisingly, raises the <code>urllib2.HTTPError</code>.</p>

<p>Test code:</p>

<pre><code>@raises(CustomError)
def test_404_error_logging(self):
    ''' not the copy and paste code; enough to give you an idea '''
    http_error = urllib2.HTTPError("mock_url", 404, "Not Found", "mock_headers", None)
    with patch('function.that.invokes.error.handler', side_effect=http_error):
        test_client.get("bad url")
</code></pre>

<p>Custom error handler for urllib2 HTTPError handling:</p>

<pre><code>class LoggingErrorHandler(urllib2.HTTPErrorProcessor):
    ''' not the copy and paste code; enough to give you an idea '''
    def http_error_404(self, req, fp, code, msg, headers):
        log.debug("Look! An error! {0} {1}".format(code, msg))
        raise CustomError(req.get_full_url(), code, msg, body, headers)
</code></pre>

<p>CustomError is also our custom exception.</p>