|
| 1 | +import unittest |
| 2 | + |
| 3 | +from pydantic import BaseModel |
| 4 | +from fastapi_router_controller import Controller, ControllersTags |
| 5 | +from fastapi import APIRouter, Depends, FastAPI, Query |
| 6 | +from fastapi.testclient import TestClient |
| 7 | + |
| 8 | +parent_router = APIRouter() |
| 9 | +child_router = APIRouter() |
| 10 | + |
| 11 | +parent_controller = Controller(parent_router, openapi_tag={"name": "parent"}) |
| 12 | +child_controller = Controller(child_router, openapi_tag={"name": "child"}) |
| 13 | + |
| 14 | +class Object(BaseModel): |
| 15 | + id: str |
| 16 | + |
| 17 | + |
| 18 | +def get_x(): |
| 19 | + class Foo: |
| 20 | + def create(self): |
| 21 | + return "XXX" |
| 22 | + |
| 23 | + return Foo() |
| 24 | + |
| 25 | +class Filter(BaseModel): |
| 26 | + foo: str |
| 27 | + |
| 28 | +@parent_controller.resource() |
| 29 | +class Base: |
| 30 | + def __init__(self): |
| 31 | + self.bla = 'foo' |
| 32 | + |
| 33 | + @parent_controller.route.get( |
| 34 | + "/hambu", tags=["parent"], response_model=Object, |
| 35 | + ) |
| 36 | + def hambu(self): |
| 37 | + return Object(id="hambu-%s" % self.bla) |
| 38 | + |
| 39 | +# With the 'resource' decorator define the controller Class linked to the Controller router arguments |
| 40 | +@child_controller.resource() |
| 41 | +class Controller(Base): |
| 42 | + def __init__(self, x=Depends(get_x)): |
| 43 | + super().__init__() |
| 44 | + self.x = x |
| 45 | + |
| 46 | + @child_controller.route.get( |
| 47 | + "/", tags=["child"], summary="return a object", response_model=Object, |
| 48 | + ) |
| 49 | + def root( |
| 50 | + self, id: str = Query(..., title="itemId", description="The id of the object"), |
| 51 | + ): |
| 52 | + id += self.x.create() + self.bla |
| 53 | + return Object(id=id) |
| 54 | + |
| 55 | +def create_app(): |
| 56 | + app = FastAPI( |
| 57 | + title="A application using fastapi_router_controller", |
| 58 | + version="0.1.0", |
| 59 | + openapi_tags=ControllersTags, |
| 60 | + ) |
| 61 | + |
| 62 | + app.include_router(Controller.router()) |
| 63 | + return app |
| 64 | + |
| 65 | +class TestRoutes(unittest.TestCase): |
| 66 | + def setUp(self): |
| 67 | + app = create_app() |
| 68 | + self.client = TestClient(app) |
| 69 | + |
| 70 | + def test_root(self): |
| 71 | + response = self.client.get("/?id=12") |
| 72 | + self.assertEqual(response.status_code, 200) |
| 73 | + self.assertEqual(response.json(), {"id": "12XXXfoo"}) |
| 74 | + |
| 75 | + def test_hambu(self): |
| 76 | + response = self.client.get("/hambu") |
| 77 | + self.assertEqual(response.status_code, 200) |
| 78 | + self.assertEqual(response.json(), {"id": "hambu-foo"}) |
0 commit comments