title: How to test a FastAPI api endpoint that consumes images?
body: <p>I am using pytest to test a FastAPI endpoint that gets in input an image in binary format as in</p>
  
  <pre class="lang-py prettyprint-override"><code>@app.post("/analyse")
  async def analyse(file: bytes = File(...)):
  
      image = Image.open(io.BytesIO(file)).convert("RGB")
      stats = process_image(image)
      return stats
  </code></pre>
  
  <p>After starting the server, I can manually test the endpoint successfully by running a call with <code>requests</code></p>
  
  <pre class="lang-py prettyprint-override"><code>import requests
  from requests_toolbelt.multipart.encoder import MultipartEncoder
  
  url = "http://127.0.0.1:8000/analyse"
  
  filename = "./example.jpg"
  m = MultipartEncoder(
          fields={'file': ('filename', open(filename, 'rb'), 'image/jpeg')}
      )
  r = requests.post(url, data=m, headers={'Content-Type': m.content_type}, timeout = 8000)
  assert r.status_code == 200
  </code></pre>
  
  <p>However, setting up tests in a function of the form:</p>
  
  <pre class="lang-py prettyprint-override"><code>from fastapi.testclient import TestClient
  from requests_toolbelt.multipart.encoder import MultipartEncoder
  from app.server import app
  
  client = TestClient(app)
  
  def test_image_analysis():
  
      filename = "example.jpg"
  
      m = MultipartEncoder(
          fields={'file': ('filename', open(filename, 'rb'), 'image/jpeg')}
          )
  
      response = client.post("/analyse",
                             data=m,
                             headers={"Content-Type": "multipart/form-data"}
                             )
  
      assert response.status_code == 200
  </code></pre>
  
  <p>when running tests with <code>python -m pytest</code>, that gives me back a </p>
  
  <pre><code>&gt;       assert response.status_code == 200
  E       assert 400 == 200
  E        +  where 400 = &lt;Response [400]&gt;.status_code
  
  tests\test_server.py:22: AssertionError
  -------------------------------------------------------- Captured log call --------------------------------------------------------- 
  ERROR    fastapi:routing.py:133 Error getting request body: can't concat NoneType to bytes
  ===================================================== short test summary info ====================================================== 
  FAILED tests/test_server.py::test_image_analysis - assert 400 == 200
  </code></pre>
  
  <p>what am I doing wrong?<br>
  What's the right way to write a test function <code>test_image_analysis()</code> using an image file? </p>