title: how to mock a method decorated with Python Flask route()
body: <p>I need to unit test whether a method decorated by a Flask <code>route()</code> gets called or not.</p>
  
  <p>I'd like to do this <em>without</em> modifying the original code under test, if possible, so mocking the method would suite my requirements perfectly.</p>
  
  <p>Hence I am asking this <em>specific</em> question about how to mock a decorated request method (I want to stress this to try to avoid people wasting their time with less specific answers)...</p>
  
  <p>Sample application <code>jflask.py</code>:</p>
  
  <pre><code>from flask import Flask
  app = Flask(__name__)
  app.config.from_object(__name__)
  
  @app.route('/hello')           # This method represents the code under test.
  def hello():                   # I want to assert that this method gets
      return 'Hello, World'      # called without modifying this code.
  
  if __name__ == "__main__":
      app.run()
  </code></pre>
  
  <p>In the unit test I'm using <code>@patch()</code> to mock the method so I can assert it was called, but the assertion fails. I.e. the mock method doesn't get called, when I expect it to.</p>
  
  <p>Sample unit test <code>test_hello.py</code>:</p>
  
  <pre><code>import unittest
  import jflask
  from unittest.mock import patch
  
  class jTest(unittest.TestCase):
      def setUp(self):
          #jflask.app.testing = True
          self.app = jflask.app.test_client()
  
      @patch('jflask.hello')                # mock the hello() method
      def test_hello(self, mock_method):
          rv = self.app.get('/hello')
          mock_method.assert_called()    # this assertion fails
  </code></pre>
  
  <p>What am I doing wrong ?</p>
  
  <hr>
  
  <p><em>Background</em></p>
  
  <p>Some background information about the <em>actual</em> behaviour I'm trying to test
  (since the above is just a condensed test case, and may not seem entirely sane by itself).</p>
  
  <p>In the actual code I am unit testing, there is a <code>before_request()</code> handler
  installed for the app. This gets called by Flask before each request is handled, and in
  certain situations this handler has been designed to return a response value, which
  causes Flask request processing to stop (in this application's case, this feature is used to centrally validate request parameters), so that the usual routed request handler will (deliberately) not get called.</p>
  
  <p>My unit tests need to assert that request processing gets stopped
  or continues, appropriately depending on the situation.
  Hence, my test needs to mock the real request handler and assert whether
  it was called or not.</p>