title: How to patch Python's raise (or return) keyword for the purpose of unit testing?
body: <p>What is the namespace for Python keywords that mock.patch is able to catch?</p>
  
  <p>When someone wants to patch open or print then <code>mock.patch("builtins.open")</code> or <code>mock.patch("mymodule.open")</code> can be used, but that doesn't works, for example, with <code>raise</code>.</p>
  
  <p>If I have <code>raise somemodule.SomeException</code> statement then I could easily test if the exception is raised, but how I can assert that actually raise keyword has been invoked. Like (with the help of <code>pytest</code> and <code>pytest-mock</code>):</p>
  
  <pre><code>def test_myfunction_calls_raise(self, mocker):
      mocked = mocker.patch("mymodule.raise")
      mymodule.myfunction()
      mocked.assert_called_once()
  </code></pre>
  
  <hr>
  
  <p>EDIT: I've got <a href="https://stackoverflow.com/a/56841434/11703358">a very nice answer</a> and so mock.patch isn't applicable. Beside that and beside obvious solution - testing the outcome - is there some other meaningful technique to test if Python keyword (<code>raise</code>, <code>return</code>, ...) has been called in a code?</p>
  
  <p>EDIT 2:
  Actual code I want to test (pynput's Listener stop() doesn't work well in Xfce, so I have to raise the exception to stop the Listener thread):</p>
  
  <pre><code>import pynput
  # ...
  
  def stop(self):
      """Stops listener by raising an exception."""
      try:
          raise pynput.mouse.Listener.StopException
      except pynput.mouse.Listener.StopException:
          return False
  </code></pre>
  
  <p>EDIT 3: The method from above is unittested with the following two test methods:</p>
  
  <pre><code>def test_stop_stops_listener(self, mocker):
      """StopException is raised if MagicMock has got StopException attribute."""
      mocked = mocker.patch("pynput.mouse.Listener")
      with pytest.raises(TypeError):  # catching classes that do not inherit from BaseException is not allowed
          base.BaseMouse().stop()
      assert hasattr(mocked, "StopException")
  
  def test_stop_returns_False(self, mocker):
      assert base.BaseMouse().stop() is False
  </code></pre>