from typing import Annotated
import pytest
from fastapi import FastAPI, Query
from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from .utils import needs_py310
def get_client():
app = FastAPI()
with pytest.warns(FastAPIDeprecationWarning):
@app.get("/items/")
async def read_items(
q: Annotated[str | None, Query(regex="^fixedquery$")] = None,
):
if q:
return f"Hello {q}"
else:
return "Hello World"
client = TestClient(app)
return client
@needs_py310
def test_query_params_str_validations_no_query():
client = get_client()
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == "Hello World"
@needs_py310
def test_query_params_str_validations_q_fixedquery():
client = get_client()
response = client.get("/items/", params={"q": "fixedquery"})
assert response.status_code == 200
assert response.json() == "Hello fixedquery"
@needs_py310
def test_query_params_str_validations_item_query_nonregexquery():
client = get_client()
response = client.get("/items/", params={"q": "nonregexquery"})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_pattern_mismatch",
"loc": ["query", "q"],
"msg": "String should match pattern '^fixedquery