From 6d5399e3f0ed8655ca2172e85af89aadb9006a1d Mon Sep 17 00:00:00 2001 From: pmateusz Date: Sun, 12 Jan 2025 14:39:45 +0100 Subject: [PATCH] Tutorial example for httpx AsyncClient --- tests/examples/httpx/tutorial/test_basics.py | 55 +++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/tests/examples/httpx/tutorial/test_basics.py b/tests/examples/httpx/tutorial/test_basics.py index 56eed8f..514cce9 100644 --- a/tests/examples/httpx/tutorial/test_basics.py +++ b/tests/examples/httpx/tutorial/test_basics.py @@ -1,8 +1,9 @@ from typing import Annotated import httpx +import pytest from meatie import api_ref, endpoint -from meatie_httpx import Client +from meatie_httpx import AsyncClient, Client from pydantic import BaseModel, Field @@ -30,6 +31,23 @@ def post_todo(self, todo: Annotated[Todo, api_ref("body")]) -> Todo: ... +class JsonPlaceholderAsyncClient(AsyncClient): + def __init__(self) -> None: + super().__init__(httpx.AsyncClient(base_url="https://jsonplaceholder.typicode.com")) + + @endpoint("/todos") + async def get_todos(self, user_id: Annotated[int, api_ref("userId")] = None) -> list[Todo]: + ... + + @endpoint("/users/{user_id}/todos") + async def get_todos_by_user(self, user_id: int) -> list[Todo]: + ... + + @endpoint("/todos") + async def post_todo(self, todo: Annotated[Todo, api_ref("body")]) -> Todo: + ... + + def test_todos_filter_by_user() -> None: # WHEN with JsonPlaceholderClient() as client: @@ -48,7 +66,7 @@ def test_todos_get_by_user() -> None: assert len(todos) == 20 -def test_post_todo() -> None: +async def test_post_todo() -> None: # GIVEN new_todo = Todo.model_construct(user_id=1, id=201, title="test post todo", completed=False) @@ -58,3 +76,36 @@ def test_post_todo() -> None: # THEN assert created_todo == new_todo + + +@pytest.mark.asyncio() +async def test_todos_filter_by_user_async() -> None: + # WHEN + async with JsonPlaceholderAsyncClient() as client: + todos = await client.get_todos(user_id=1) + + # THEN + assert all(todo.user_id == 1 for todo in todos) + + +@pytest.mark.asyncio() +async def test_todos_get_by_user_async() -> None: + # WHEN + async with JsonPlaceholderAsyncClient() as client: + todos = await client.get_todos_by_user(1) + + # THEN + assert len(todos) == 20 + + +@pytest.mark.asyncio() +async def test_post_todo_async() -> None: + # GIVEN + new_todo = Todo.model_construct(user_id=1, id=201, title="test post todo", completed=False) + + # WHEN + async with JsonPlaceholderAsyncClient() as client: + created_todo = await client.post_todo(new_todo) + + # THEN + assert created_todo == new_todo