Skip to content

Commit

Permalink
fix: fastapi example test not working. (tortoise#1029)
Browse files Browse the repository at this point in the history
  • Loading branch information
waketzheng committed Aug 1, 2022
1 parent 5e4ba80 commit f217293
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 80 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Expand Up @@ -21,6 +21,7 @@ Fixed
- Fixed ORA-01435 error while using `Oracle` database (#1155)
- Fixed processing of `ssl` option in MySQL connection string.
- Fixed type hinting for `QuerySetSingle`.
- Fastapi example test not working. (#1029)

0.19.1
------
Expand Down
32 changes: 12 additions & 20 deletions examples/fastapi/_tests.py
@@ -1,40 +1,32 @@
# mypy: no-disallow-untyped-decorators
# pylint: disable=E0611,E0401
import asyncio
from typing import Generator

import pytest
from fastapi.testclient import TestClient
from asgi_lifespan import LifespanManager
from httpx import AsyncClient
from main import app
from models import Users

from tortoise.contrib.test import finalizer, initializer


@pytest.fixture(scope="module")
def client() -> Generator:
initializer(["models"])
with TestClient(app) as c:
yield c
finalizer()
def anyio_backend():
return "asyncio"


@pytest.fixture(scope="module")
def event_loop(client: TestClient) -> Generator:
yield client.task.get_loop() # type: ignore
async def client():
async with LifespanManager(app):
async with AsyncClient(app=app, base_url="http://test") as c:
yield c


def test_create_user(client: TestClient, event_loop: asyncio.AbstractEventLoop): # nosec
response = client.post("/users", json={"username": "admin"})
@pytest.mark.anyio
async def test_create_user(client: AsyncClient): # nosec
response = await client.post("/users", json={"username": "admin"})
assert response.status_code == 200, response.text
data = response.json()
assert data["username"] == "admin"
assert "id" in data
user_id = data["id"]

async def get_user_by_db():
user = await Users.get(id=user_id)
return user

user_obj = event_loop.run_until_complete(get_user_by_db())
user_obj = await Users.get(id=user_id)
assert user_obj.id == user_id
145 changes: 85 additions & 60 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pyproject.toml
Expand Up @@ -77,6 +77,8 @@ starlette = "*"
pydantic = "*"
# FastAPI support
fastapi = "*"
httpx = "*"
asgi-lifespan = "*"
# Aiohttp support
aiohttp = "*"
# BlackSheep support
Expand Down

0 comments on commit f217293

Please sign in to comment.