title: pytest, raise_for_status with Failed: DID NOT RAISE <class 'requests.exceptions.HTTPError'>
body: <p>This is for documething something I stumbled upon for a long time.</p>
  <p>This is not working. The <code>try/except/else</code> clause will swallow the exception generated by <code>r.raise_for_status()</code>.</p>
  <pre><code>import requests
  from requests.exceptions import HTTPError
  import pytest
  import logging
  
  def fetch(url):
      &quot;&quot;&quot;HTTP request&quot;&quot;&quot;
      try:
          r = requests.get(url)
          r.raise_for_status()
      except HTTPError as err:
          logging.warning(f'Fetching url failed {err}')
      else:
          print(r.data)
  
  
  def test_fetch(mocker):
      &quot;&quot;&quot;Test.&quot;&quot;&quot;
      mock_response = mocker.Mock(requests.Response)
      expected_exc = HTTPError()
      mock_response.raise_for_status.side_effect = expected_exc
      mocker.patch.object(requests, 'get')
      requests.get.return_value = mock_response
      r = fetch('http://httpbin.org/status/400')
      with pytest.raises(HTTPError) as err_msg:
          r.raise_for_status()
  </code></pre>
  <p>The error message received from pytest is</p>
  <pre><code>
  example.py F                                                                                                                      [100%]
  
  ====================================================================== FAILURES =======================================================================
  _____________________________________________________________________ test_fetch ______________________________________________________________________
  
  mocker = &lt;pytest_mock.plugin.MockFixture object at 0x1095cd100&gt;
  
      def test_fetch(mocker):
          &quot;&quot;&quot;Test.&quot;&quot;&quot;
          mock_response = mocker.Mock(requests.Response)
          expected_exc = HTTPError()
          mock_response.raise_for_status.side_effect = expected_exc
          mocker.patch.object(requests, 'get')
          requests.get.return_value = mock_response
          with pytest.raises(HTTPError) as err_msg:
  &gt;           fetch('http://httpbin.org/status/400')
  E           Failed: DID NOT RAISE &lt;class 'requests.exceptions.HTTPError'&gt;
  
  example.py:25: Failed
  ------------------------------------------------------------------ Captured log call ------------------------------------------------------------------
  WARNING  root:example.py:12 Fetching url failed
  =============================================================== short test summary info ===============================================================
  FAILED example.py::test_fetch - Failed: DID NOT RAISE &lt;class 'requests.exceptions.HTTPError'&gt;
  ================================================================== 1 failed in 0.20s ==================================================================
  
  </code></pre>
  <p>I gave the answer below.</p>