title: FastAPI - mocking path function has no effect
body: <p>I've got a simple <a href="https://fastapi.tiangolo.com/" rel="noreferrer">FastAPI</a> application and I'm trying to create tests with <code>pytest</code> for it.</p>
  
  <p>My goal is to test how app behaves in case of different errors.</p>
  
  <p>I've got a simple healthcheck route in my app:</p>
  
  <pre class="lang-py prettyprint-override"><code>from fastapi import APIRouter
  
  router = APIRouter()
  
  
  @router.get("/health")
  async def health():
      return "It's working ✨"
  </code></pre>
  
  <p>Now in my pytest module I'm trying to patch above function so that it raises different errors.
  I'm using <code>unittest.mock</code> but I'm getting very strange behavior.</p>
  
  <pre class="lang-py prettyprint-override"><code>import pytest
  from unittest import mock
  
  from fastapi import HTTPException
  from starlette.testclient import TestClient
  
  import app.api.health
  from app.main import app  # this is my application (FastAPI instance) with the `router` attached
  
  
  @pytest.fixture()
  def client():
      with TestClient(app) as test_client:
          yield test_client
  
  
  def test_simple(client):
      def mock_health_function():
          raise HTTPException(status_code=400, detail='gibberish')
  
      with mock.patch('app.api.health.health', mock_health_function):
          response = client.get(HEALTHCHECK_PATH)
  
          with pytest.raises(HTTPException):  # this check passes successfully - my exception is raised
              app.api.health.health()
  
      assert response.status_code != 200  # this check does not pass. The original function was called as if nothing was patched
  </code></pre>
  
  <p>Despite the fact that the exact same function is called inside the test, API test client still calls the original function when I hit the endpoint.</p>
  
  <p>Why does <code>mock.patch</code> not work properly when function is not called directly in the test?</p>
  
  <p>Or maybe I should approach my problem in some different way?</p>