Coverage for docs_src/app_testing/app_b/main.py: 100%

25 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1from typing import Union 1abcdef

2 

3from fastapi import FastAPI, Header, HTTPException 1abcdef

4from pydantic import BaseModel 1abcdef

5 

6fake_secret_token = "coneofsilence" 1abcdef

7 

8fake_db = { 1abcdef

9 "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, 

10 "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"}, 

11} 

12 

13app = FastAPI() 1abcdef

14 

15 

16class Item(BaseModel): 1abcdef

17 id: str 1abcdef

18 title: str 1abcdef

19 description: Union[str, None] = None 1abcdef

20 

21 

22@app.get("/items/{item_id}", response_model=Item) 1abcdef

23async def read_main(item_id: str, x_token: str = Header()): 1abcdef

24 if x_token != fake_secret_token: 1ghijkl

25 raise HTTPException(status_code=400, detail="Invalid X-Token header") 1ghijkl

26 if item_id not in fake_db: 1ghijkl

27 raise HTTPException(status_code=404, detail="Item not found") 1ghijkl

28 return fake_db[item_id] 1ghijkl

29 

30 

31@app.post("/items/", response_model=Item) 1abcdef

32async def create_item(item: Item, x_token: str = Header()): 1abcdef

33 if x_token != fake_secret_token: 1ghijkl

34 raise HTTPException(status_code=400, detail="Invalid X-Token header") 1ghijkl

35 if item.id in fake_db: 1ghijkl

36 raise HTTPException(status_code=409, detail="Item already exists") 1ghijkl

37 fake_db[item.id] = item 1ghijkl

38 return item 1ghijkl