Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TestClient calls wrong methd when fastapi.APIRouter().add_api_router() is used to setup the router #62

Open
johannes-mueller opened this issue Nov 7, 2023 · 0 comments

Comments

@johannes-mueller
Copy link

johannes-mueller commented Nov 7, 2023

TestClient always calls the GET routes, when routes are added using fastapi.APIRouter().add_api_router() no matter what method was requested.

Execute the following program

import asyncio
from async_asgi_testclient import TestClient as AsyncTestClient
from fastapi.testclient import TestClient

from fastapi import APIRouter, FastAPI


def get():
    print("called get", end=', ')

def post():
    print("called post", end=', ')

def put():
    print("called put", end=', ')

def delete():
    print("called delete", end=', ')

def make_router():
    router = APIRouter()
    router.add_api_route('/', get, methods=['GET'])
    router.add_api_route('/', post, methods=['POST'])
    router.add_api_route('/', put, methods=['PUT'])
    return router

api = FastAPI()
api.include_router(make_router(), prefix='/foo')


async def main():
    print("sync:")
    with TestClient(api) as client:
        print("GET request", client.get('/foo').status_code)
        print("POST request", client.post('/foo').status_code)
        print("PUT request", client.put('/foo').status_code)
        print("DELETE request", client.delete('/foo').status_code)
    print("async:")
    async with AsyncTestClient(api) as client:
        print("GET request", (await client.get('/foo')).status_code)
        print("POST request", (await client.post('/foo')).status_code)
        print("PUT request", (await client.put('/foo')).status_code)
        print("DELETE request", (await client.delete('/foo')).status_code)


asyncio.run(main())

output is

sync:
called get, GET request 200
called post, POST request 200
called put, PUT request 200
DELETE request 405
async:
called get, GET request 200
called get, POST request 200
called get, PUT request 200
called get, DELETE request 200

expected output is

sync:
called get, GET request 200
called post, POST request 200
called put, PUT request 200
DELETE request 405
async:
called get, GET request 200
called post, POST request 200
called put, PUT request 200
DELETE request 405

Python versions tested: 3.10, 3.11, 3.12
fastapi: 0.104.1
async-asgi-testclient: 1.4.11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant