title: How to Mock: pytest.raises DID NOT RAISE <class 'subprocess.TimeoutExpired'>
body: <p>I am using <code>subprocess</code> for a task, and I have a <code>try/except</code> block for catching <code>TimeoutExpired</code>. I try to mock my object using <code>side_effect</code> so I can catch the fake exception with <code>pytest.raises</code>. Whatever I do, I get <code>DID NOT RAISE &lt;class 'subprocess.TimeoutExpired'&gt;</code>.
  I have tried many things, and even though I'm not so experienced with mocking, I believe something like that should in principle work:</p>
  <pre><code># my_check.py
  from subprocess import TimeoutExpired, PIPE, check_output
  
  class Check:
      def __init__(self, name):
          self.name = name
          self.status = self.get_status()
  
      def get_status(self):
          try:
              out = check_output([&quot;ls&quot;], universal_newlines=True, stderr=PIPE, timeout=2)
          except TimeoutExpired as e:
              print(f&quot;Command timed out: {e}&quot;)
              raise
  
          if self.name in out:
              return True
          return False
  
  
  # test_my_check.py
  import pytest
  from unittest import mock
  from subprocess import TimeoutExpired
  
  @mock.patch(&quot;src.my_check.Check&quot;, autospec=True)
  def test_is_installed_exception(check_fake):
      check_fake.get_status.side_effect = TimeoutExpired
      obj_fake = check_fake(&quot;random_file.txt&quot;)
      with pytest.raises(TimeoutExpired):
          obj_fake.get_status()
  </code></pre>
  <p>For some reason it doesn't work though, and I can't get my head around what's wrong.</p>