title: Can I use mocks in testing Flask app functions?
body: <p>I'm trying to test some routes on my Flask app that call external APIs, which I want to mock. </p>
  
  <p>The routes are set up like this:</p>
  
  <pre><code>@app.route('/url/&lt;string::arg&gt;')
  def route_function(arg):
      data = external_api(arg)
      response = make_response(data)
      # configure response
      return response
  </code></pre>
  
  <p>I originally tried something like this:</p>
  
  <pre><code>class TestFlaskApp(unittest.TestCase):
      def setUp(self):
          self.app = app.test_client()
  
      @patch('external_api',
             side_effect=mock_api)
      def test_flask_route(self, api):
          result = app.get('/url/arg')
          self.assertEqual(result.status_code, 200)
          api.assert_called_once_with('arg')
  </code></pre>
  
  <p>...which failed. The mock API function wasn't called, since I assume the mock does not apply in the app context.</p>
  
  <p>I also tried this, thinking I might be able to test the route functions directly and thus avoid having to use the app context:</p>
  
  <pre><code>class TestAppFunctions(unittest.TestCase):
      @patch('external_api',
             side_effect=mock_api)
      def test_flask_function(self, api):
          result = my_flask_app.route_function('arg')
          self.assertEqual(result.status_code, 200)
          api.assert_called_once_with('arg')
  </code></pre>
  
  <p>...but this didn't work either, since to make a response, <code>route_function</code> needs the app context.</p>
  
  <p>So is there a way to mock inside the app context? How else can I test these routes without triggering external API calls?</p>