# FastAPIのAsyncClientテストで50xを例外にしない

## AsyncClientを使用したテストと50x
fastapiではasyncな関数をテスト関数にしたいときはAsyncClientという、httpxのhttp clientを使用する必要がある。
よく使う`TestClient`が使えない。

```python
import pytest
from httpx import AsyncClient

from .main import app

@pytest.mark.anyio
async def test_root():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Tomato"}
```

このクライアントは50x系のレスポンスが返却された際には、そのレスポンスを取得できるのではなくアクセス時に例外が投げられてしまう。
この挙動では50x系のレスポンスのテストを書きたいときに素直に書けない。

## 50xで例外を投げないようにする
方法は簡単で、`ASGITransport`というのを使って例外を投げないように指定すれば良い。

```python
import pytest
from httpx import AsyncClient

from .main import app

@pytest.mark.anyio
async def test_root():
    transport = httpx.ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as ac:
        response = await ac.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Tomato"}
```

## 参考
- https://www.python-httpx.org/async/
