repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
pallets/flask | https://github.com/pallets/flask/blob/2579ce9f18e67ec3213c6eceb5240310ccd46af8/examples/celery/src/task_app/views.py | examples/celery/src/task_app/views.py | from celery.result import AsyncResult
from flask import Blueprint
from flask import request
from . import tasks
bp = Blueprint("tasks", __name__, url_prefix="/tasks")
@bp.get("/result/<id>")
def result(id: str) -> dict[str, object]:
result = AsyncResult(id)
ready = result.ready()
return {
"ready": ready,
"successful": result.successful() if ready else None,
"value": result.get() if ready else result.result,
}
@bp.post("/add")
def add() -> dict[str, object]:
a = request.form.get("a", type=int)
b = request.form.get("b", type=int)
result = tasks.add.delay(a, b)
return {"result_id": result.id}
@bp.post("/block")
def block() -> dict[str, object]:
result = tasks.block.delay()
return {"result_id": result.id}
@bp.post("/process")
def process() -> dict[str, object]:
result = tasks.process.delay(total=request.form.get("total", type=int))
return {"result_id": result.id}
| python | BSD-3-Clause | 2579ce9f18e67ec3213c6eceb5240310ccd46af8 | 2026-01-04T14:38:18.898398Z | false |
pallets/flask | https://github.com/pallets/flask/blob/2579ce9f18e67ec3213c6eceb5240310ccd46af8/examples/celery/src/task_app/__init__.py | examples/celery/src/task_app/__init__.py | from celery import Celery
from celery import Task
from flask import Flask
from flask import render_template
def create_app() -> Flask:
app = Flask(__name__)
app.config.from_mapping(
CELERY=dict(
broker_url="redis://localhost",
result_backend="redis://localhost",
task_ignore_result=True,
),
)
app.config.from_prefixed_env()
celery_init_app(app)
@app.route("/")
def index() -> str:
return render_template("index.html")
from . import views
app.register_blueprint(views.bp)
return app
def celery_init_app(app: Flask) -> Celery:
class FlaskTask(Task):
def __call__(self, *args: object, **kwargs: object) -> object:
with app.app_context():
return self.run(*args, **kwargs)
celery_app = Celery(app.name, task_cls=FlaskTask)
celery_app.config_from_object(app.config["CELERY"])
celery_app.set_default()
app.extensions["celery"] = celery_app
return celery_app
| python | BSD-3-Clause | 2579ce9f18e67ec3213c6eceb5240310ccd46af8 | 2026-01-04T14:38:18.898398Z | false |
pallets/flask | https://github.com/pallets/flask/blob/2579ce9f18e67ec3213c6eceb5240310ccd46af8/examples/javascript/js_example/views.py | examples/javascript/js_example/views.py | from flask import jsonify
from flask import render_template
from flask import request
from . import app
@app.route("/", defaults={"js": "fetch"})
@app.route("/<any(xhr, jquery, fetch):js>")
def index(js):
return render_template(f"{js}.html", js=js)
@app.route("/add", methods=["POST"])
def add():
a = request.form.get("a", 0, type=float)
b = request.form.get("b", 0, type=float)
return jsonify(result=a + b)
| python | BSD-3-Clause | 2579ce9f18e67ec3213c6eceb5240310ccd46af8 | 2026-01-04T14:38:18.898398Z | false |
pallets/flask | https://github.com/pallets/flask/blob/2579ce9f18e67ec3213c6eceb5240310ccd46af8/examples/javascript/js_example/__init__.py | examples/javascript/js_example/__init__.py | from flask import Flask
app = Flask(__name__)
from js_example import views # noqa: E402, F401
| python | BSD-3-Clause | 2579ce9f18e67ec3213c6eceb5240310ccd46af8 | 2026-01-04T14:38:18.898398Z | false |
pallets/flask | https://github.com/pallets/flask/blob/2579ce9f18e67ec3213c6eceb5240310ccd46af8/examples/javascript/tests/test_js_example.py | examples/javascript/tests/test_js_example.py | import pytest
from flask import template_rendered
@pytest.mark.parametrize(
("path", "template_name"),
(
("/", "fetch.html"),
("/plain", "xhr.html"),
("/fetch", "fetch.html"),
("/jquery", "jquery.html"),
),
)
def test_index(app, client, path, template_name):
def check(sender, template, context):
assert template.name == template_name
with template_rendered.connected_to(check, app):
client.get(path)
@pytest.mark.parametrize(
("a", "b", "result"), ((2, 3, 5), (2.5, 3, 5.5), (2, None, 2), (2, "b", 2))
)
def test_add(client, a, b, result):
response = client.post("/add", data={"a": a, "b": b})
assert response.get_json()["result"] == result
| python | BSD-3-Clause | 2579ce9f18e67ec3213c6eceb5240310ccd46af8 | 2026-01-04T14:38:18.898398Z | false |
pallets/flask | https://github.com/pallets/flask/blob/2579ce9f18e67ec3213c6eceb5240310ccd46af8/examples/javascript/tests/conftest.py | examples/javascript/tests/conftest.py | import pytest
from js_example import app
@pytest.fixture(name="app")
def fixture_app():
app.testing = True
yield app
app.testing = False
@pytest.fixture
def client(app):
return app.test_client()
| python | BSD-3-Clause | 2579ce9f18e67ec3213c6eceb5240310ccd46af8 | 2026-01-04T14:38:18.898398Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/sherlock_project/sites.py | sherlock_project/sites.py | """Sherlock Sites Information Module
This module supports storing information about websites.
This is the raw data that will be used to search for usernames.
"""
import json
import requests
import secrets
MANIFEST_URL = "https://raw.githubusercontent.com/sherlock-project/sherlock/master/sherlock_project/resources/data.json"
EXCLUSIONS_URL = "https://raw.githubusercontent.com/sherlock-project/sherlock/refs/heads/exclusions/false_positive_exclusions.txt"
class SiteInformation:
def __init__(self, name, url_home, url_username_format, username_claimed,
information, is_nsfw, username_unclaimed=secrets.token_urlsafe(10)):
"""Create Site Information Object.
Contains information about a specific website.
Keyword Arguments:
self -- This object.
name -- String which identifies site.
url_home -- String containing URL for home of site.
url_username_format -- String containing URL for Username format
on site.
NOTE: The string should contain the
token "{}" where the username should
be substituted. For example, a string
of "https://somesite.com/users/{}"
indicates that the individual
usernames would show up under the
"https://somesite.com/users/" area of
the website.
username_claimed -- String containing username which is known
to be claimed on website.
username_unclaimed -- String containing username which is known
to be unclaimed on website.
information -- Dictionary containing all known information
about website.
NOTE: Custom information about how to
actually detect the existence of the
username will be included in this
dictionary. This information will
be needed by the detection method,
but it is only recorded in this
object for future use.
is_nsfw -- Boolean indicating if site is Not Safe For Work.
Return Value:
Nothing.
"""
self.name = name
self.url_home = url_home
self.url_username_format = url_username_format
self.username_claimed = username_claimed
self.username_unclaimed = secrets.token_urlsafe(32)
self.information = information
self.is_nsfw = is_nsfw
return
def __str__(self):
"""Convert Object To String.
Keyword Arguments:
self -- This object.
Return Value:
Nicely formatted string to get information about this object.
"""
return f"{self.name} ({self.url_home})"
class SitesInformation:
def __init__(
self,
data_file_path: str|None = None,
honor_exclusions: bool = True,
do_not_exclude: list[str] = [],
):
"""Create Sites Information Object.
Contains information about all supported websites.
Keyword Arguments:
self -- This object.
data_file_path -- String which indicates path to data file.
The file name must end in ".json".
There are 3 possible formats:
* Absolute File Format
For example, "c:/stuff/data.json".
* Relative File Format
The current working directory is used
as the context.
For example, "data.json".
* URL Format
For example,
"https://example.com/data.json", or
"http://example.com/data.json".
An exception will be thrown if the path
to the data file is not in the expected
format, or if there was any problem loading
the file.
If this option is not specified, then a
default site list will be used.
Return Value:
Nothing.
"""
if not data_file_path:
# The default data file is the live data.json which is in the GitHub repo. The reason why we are using
# this instead of the local one is so that the user has the most up-to-date data. This prevents
# users from creating issue about false positives which has already been fixed or having outdated data
data_file_path = MANIFEST_URL
# Ensure that specified data file has correct extension.
if not data_file_path.lower().endswith(".json"):
raise FileNotFoundError(f"Incorrect JSON file extension for data file '{data_file_path}'.")
# if "http://" == data_file_path[:7].lower() or "https://" == data_file_path[:8].lower():
if data_file_path.lower().startswith("http"):
# Reference is to a URL.
try:
response = requests.get(url=data_file_path, timeout=30)
except Exception as error:
raise FileNotFoundError(
f"Problem while attempting to access data file URL '{data_file_path}': {error}"
)
if response.status_code != 200:
raise FileNotFoundError(f"Bad response while accessing "
f"data file URL '{data_file_path}'."
)
try:
site_data = response.json()
except Exception as error:
raise ValueError(
f"Problem parsing json contents at '{data_file_path}': {error}."
)
else:
# Reference is to a file.
try:
with open(data_file_path, "r", encoding="utf-8") as file:
try:
site_data = json.load(file)
except Exception as error:
raise ValueError(
f"Problem parsing json contents at '{data_file_path}': {error}."
)
except FileNotFoundError:
raise FileNotFoundError(f"Problem while attempting to access "
f"data file '{data_file_path}'."
)
site_data.pop('$schema', None)
if honor_exclusions:
try:
response = requests.get(url=EXCLUSIONS_URL, timeout=10)
if response.status_code == 200:
exclusions = response.text.splitlines()
exclusions = [exclusion.strip() for exclusion in exclusions]
for site in do_not_exclude:
if site in exclusions:
exclusions.remove(site)
for exclusion in exclusions:
try:
site_data.pop(exclusion, None)
except KeyError:
pass
except Exception:
# If there was any problem loading the exclusions, just continue without them
print("Warning: Could not load exclusions, continuing without them.")
honor_exclusions = False
self.sites = {}
# Add all site information from the json file to internal site list.
for site_name in site_data:
try:
self.sites[site_name] = \
SiteInformation(site_name,
site_data[site_name]["urlMain"],
site_data[site_name]["url"],
site_data[site_name]["username_claimed"],
site_data[site_name],
site_data[site_name].get("isNSFW",False)
)
except KeyError as error:
raise ValueError(
f"Problem parsing json contents at '{data_file_path}': Missing attribute {error}."
)
except TypeError:
print(f"Encountered TypeError parsing json contents for target '{site_name}' at {data_file_path}\nSkipping target.\n")
return
def remove_nsfw_sites(self, do_not_remove: list = []):
"""
Remove NSFW sites from the sites, if isNSFW flag is true for site
Keyword Arguments:
self -- This object.
Return Value:
None
"""
sites = {}
do_not_remove = [site.casefold() for site in do_not_remove]
for site in self.sites:
if self.sites[site].is_nsfw and site.casefold() not in do_not_remove:
continue
sites[site] = self.sites[site]
self.sites = sites
def site_name_list(self):
"""Get Site Name List.
Keyword Arguments:
self -- This object.
Return Value:
List of strings containing names of sites.
"""
return sorted([site.name for site in self], key=str.lower)
def __iter__(self):
"""Iterator For Object.
Keyword Arguments:
self -- This object.
Return Value:
Iterator for sites object.
"""
for site_name in self.sites:
yield self.sites[site_name]
def __len__(self):
"""Length For Object.
Keyword Arguments:
self -- This object.
Return Value:
Length of sites object.
"""
return len(self.sites)
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/sherlock_project/result.py | sherlock_project/result.py | """Sherlock Result Module
This module defines various objects for recording the results of queries.
"""
from enum import Enum
class QueryStatus(Enum):
"""Query Status Enumeration.
Describes status of query about a given username.
"""
CLAIMED = "Claimed" # Username Detected
AVAILABLE = "Available" # Username Not Detected
UNKNOWN = "Unknown" # Error Occurred While Trying To Detect Username
ILLEGAL = "Illegal" # Username Not Allowable For This Site
WAF = "WAF" # Request blocked by WAF (i.e. Cloudflare)
def __str__(self):
"""Convert Object To String.
Keyword Arguments:
self -- This object.
Return Value:
Nicely formatted string to get information about this object.
"""
return self.value
class QueryResult():
"""Query Result Object.
Describes result of query about a given username.
"""
def __init__(self, username, site_name, site_url_user, status,
query_time=None, context=None):
"""Create Query Result Object.
Contains information about a specific method of detecting usernames on
a given type of web sites.
Keyword Arguments:
self -- This object.
username -- String indicating username that query result
was about.
site_name -- String which identifies site.
site_url_user -- String containing URL for username on site.
NOTE: The site may or may not exist: this
just indicates what the name would
be, if it existed.
status -- Enumeration of type QueryStatus() indicating
the status of the query.
query_time -- Time (in seconds) required to perform query.
Default of None.
context -- String indicating any additional context
about the query. For example, if there was
an error, this might indicate the type of
error that occurred.
Default of None.
Return Value:
Nothing.
"""
self.username = username
self.site_name = site_name
self.site_url_user = site_url_user
self.status = status
self.query_time = query_time
self.context = context
return
def __str__(self):
"""Convert Object To String.
Keyword Arguments:
self -- This object.
Return Value:
Nicely formatted string to get information about this object.
"""
status = str(self.status)
if self.context is not None:
# There is extra context information available about the results.
# Append it to the normal response text.
status += f" ({self.context})"
return status
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/sherlock_project/__main__.py | sherlock_project/__main__.py | #! /usr/bin/env python3
"""
Sherlock: Find Usernames Across Social Networks Module
This module contains the main logic to search for usernames at social
networks.
"""
import sys
if __name__ == "__main__":
# Check if the user is using the correct version of Python
python_version = sys.version.split()[0]
if sys.version_info < (3, 9):
print(f"Sherlock requires Python 3.9+\nYou are using Python {python_version}, which is not supported by Sherlock.")
sys.exit(1)
from sherlock_project import sherlock
sherlock.main()
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/sherlock_project/sherlock.py | sherlock_project/sherlock.py | #! /usr/bin/env python3
"""
Sherlock: Find Usernames Across Social Networks Module
This module contains the main logic to search for usernames at social
networks.
"""
import sys
try:
from sherlock_project.__init__ import import_error_test_var # noqa: F401
except ImportError:
print("Did you run Sherlock with `python3 sherlock/sherlock.py ...`?")
print("This is an outdated method. Please see https://sherlockproject.xyz/installation for up to date instructions.")
sys.exit(1)
import csv
import signal
import pandas as pd
import os
import re
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from json import loads as json_loads
from time import monotonic
from typing import Optional
import requests
from requests_futures.sessions import FuturesSession
from sherlock_project.__init__ import (
__longname__,
__shortname__,
__version__,
forge_api_latest_release,
)
from sherlock_project.result import QueryStatus
from sherlock_project.result import QueryResult
from sherlock_project.notify import QueryNotify
from sherlock_project.notify import QueryNotifyPrint
from sherlock_project.sites import SitesInformation
from colorama import init
from argparse import ArgumentTypeError
class SherlockFuturesSession(FuturesSession):
def request(self, method, url, hooks=None, *args, **kwargs):
"""Request URL.
This extends the FuturesSession request method to calculate a response
time metric to each request.
It is taken (almost) directly from the following Stack Overflow answer:
https://github.com/ross/requests-futures#working-in-the-background
Keyword Arguments:
self -- This object.
method -- String containing method desired for request.
url -- String containing URL for request.
hooks -- Dictionary containing hooks to execute after
request finishes.
args -- Arguments.
kwargs -- Keyword arguments.
Return Value:
Request object.
"""
# Record the start time for the request.
if hooks is None:
hooks = {}
start = monotonic()
def response_time(resp, *args, **kwargs):
"""Response Time Hook.
Keyword Arguments:
resp -- Response object.
args -- Arguments.
kwargs -- Keyword arguments.
Return Value:
Nothing.
"""
resp.elapsed = monotonic() - start
return
# Install hook to execute when response completes.
# Make sure that the time measurement hook is first, so we will not
# track any later hook's execution time.
try:
if isinstance(hooks["response"], list):
hooks["response"].insert(0, response_time)
elif isinstance(hooks["response"], tuple):
# Convert tuple to list and insert time measurement hook first.
hooks["response"] = list(hooks["response"])
hooks["response"].insert(0, response_time)
else:
# Must have previously contained a single hook function,
# so convert to list.
hooks["response"] = [response_time, hooks["response"]]
except KeyError:
# No response hook was already defined, so install it ourselves.
hooks["response"] = [response_time]
return super(SherlockFuturesSession, self).request(
method, url, hooks=hooks, *args, **kwargs
)
def get_response(request_future, error_type, social_network):
# Default for Response object if some failure occurs.
response = None
error_context = "General Unknown Error"
exception_text = None
try:
response = request_future.result()
if response.status_code:
# Status code exists in response object
error_context = None
except requests.exceptions.HTTPError as errh:
error_context = "HTTP Error"
exception_text = str(errh)
except requests.exceptions.ProxyError as errp:
error_context = "Proxy Error"
exception_text = str(errp)
except requests.exceptions.ConnectionError as errc:
error_context = "Error Connecting"
exception_text = str(errc)
except requests.exceptions.Timeout as errt:
error_context = "Timeout Error"
exception_text = str(errt)
except requests.exceptions.RequestException as err:
error_context = "Unknown Error"
exception_text = str(err)
return response, error_context, exception_text
def interpolate_string(input_object, username):
if isinstance(input_object, str):
return input_object.replace("{}", username)
elif isinstance(input_object, dict):
return {k: interpolate_string(v, username) for k, v in input_object.items()}
elif isinstance(input_object, list):
return [interpolate_string(i, username) for i in input_object]
return input_object
def check_for_parameter(username):
"""checks if {?} exists in the username
if exist it means that sherlock is looking for more multiple username"""
return "{?}" in username
checksymbols = ["_", "-", "."]
def multiple_usernames(username):
"""replace the parameter with with symbols and return a list of usernames"""
allUsernames = []
for i in checksymbols:
allUsernames.append(username.replace("{?}", i))
return allUsernames
def sherlock(
username: str,
site_data: dict[str, dict[str, str]],
query_notify: QueryNotify,
dump_response: bool = False,
proxy: Optional[str] = None,
timeout: int = 60,
) -> dict[str, dict[str, str | QueryResult]]:
"""Run Sherlock Analysis.
Checks for existence of username on various social media sites.
Keyword Arguments:
username -- String indicating username that report
should be created against.
site_data -- Dictionary containing all of the site data.
query_notify -- Object with base type of QueryNotify().
This will be used to notify the caller about
query results.
proxy -- String indicating the proxy URL
timeout -- Time in seconds to wait before timing out request.
Default is 60 seconds.
Return Value:
Dictionary containing results from report. Key of dictionary is the name
of the social network site, and the value is another dictionary with
the following keys:
url_main: URL of main site.
url_user: URL of user on site (if account exists).
status: QueryResult() object indicating results of test for
account existence.
http_status: HTTP status code of query which checked for existence on
site.
response_text: Text that came back from request. May be None if
there was an HTTP error when checking for existence.
"""
# Notify caller that we are starting the query.
query_notify.start(username)
# Normal requests
underlying_session = requests.session()
# Limit number of workers to 20.
# This is probably vastly overkill.
if len(site_data) >= 20:
max_workers = 20
else:
max_workers = len(site_data)
# Create multi-threaded session for all requests.
session = SherlockFuturesSession(
max_workers=max_workers, session=underlying_session
)
# Results from analysis of all sites
results_total = {}
# First create futures for all requests. This allows for the requests to run in parallel
for social_network, net_info in site_data.items():
# Results from analysis of this specific site
results_site = {"url_main": net_info.get("urlMain")}
# Record URL of main site
# A user agent is needed because some sites don't return the correct
# information since they think that we are bots (Which we actually are...)
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:129.0) Gecko/20100101 Firefox/129.0",
}
if "headers" in net_info:
# Override/append any extra headers required by a given site.
headers.update(net_info["headers"])
# URL of user on site (if it exists)
url = interpolate_string(net_info["url"], username.replace(' ', '%20'))
# Don't make request if username is invalid for the site
regex_check = net_info.get("regexCheck")
if regex_check and re.search(regex_check, username) is None:
# No need to do the check at the site: this username is not allowed.
results_site["status"] = QueryResult(
username, social_network, url, QueryStatus.ILLEGAL
)
results_site["url_user"] = ""
results_site["http_status"] = ""
results_site["response_text"] = ""
query_notify.update(results_site["status"])
else:
# URL of user on site (if it exists)
results_site["url_user"] = url
url_probe = net_info.get("urlProbe")
request_method = net_info.get("request_method")
request_payload = net_info.get("request_payload")
request = None
if request_method is not None:
if request_method == "GET":
request = session.get
elif request_method == "HEAD":
request = session.head
elif request_method == "POST":
request = session.post
elif request_method == "PUT":
request = session.put
else:
raise RuntimeError(f"Unsupported request_method for {url}")
if request_payload is not None:
request_payload = interpolate_string(request_payload, username)
if url_probe is None:
# Probe URL is normal one seen by people out on the web.
url_probe = url
else:
# There is a special URL for probing existence separate
# from where the user profile normally can be found.
url_probe = interpolate_string(url_probe, username)
if request is None:
if net_info["errorType"] == "status_code":
# In most cases when we are detecting by status code,
# it is not necessary to get the entire body: we can
# detect fine with just the HEAD response.
request = session.head
else:
# Either this detect method needs the content associated
# with the GET response, or this specific website will
# not respond properly unless we request the whole page.
request = session.get
if net_info["errorType"] == "response_url":
# Site forwards request to a different URL if username not
# found. Disallow the redirect so we can capture the
# http status from the original URL request.
allow_redirects = False
else:
# Allow whatever redirect that the site wants to do.
# The final result of the request will be what is available.
allow_redirects = True
# This future starts running the request in a new thread, doesn't block the main thread
if proxy is not None:
proxies = {"http": proxy, "https": proxy}
future = request(
url=url_probe,
headers=headers,
proxies=proxies,
allow_redirects=allow_redirects,
timeout=timeout,
json=request_payload,
)
else:
future = request(
url=url_probe,
headers=headers,
allow_redirects=allow_redirects,
timeout=timeout,
json=request_payload,
)
# Store future in data for access later
net_info["request_future"] = future
# Add this site's results into final dictionary with all the other results.
results_total[social_network] = results_site
# Open the file containing account links
for social_network, net_info in site_data.items():
# Retrieve results again
results_site = results_total.get(social_network)
# Retrieve other site information again
url = results_site.get("url_user")
status = results_site.get("status")
if status is not None:
# We have already determined the user doesn't exist here
continue
# Get the expected error type
error_type = net_info["errorType"]
if isinstance(error_type, str):
error_type: list[str] = [error_type]
# Retrieve future and ensure it has finished
future = net_info["request_future"]
r, error_text, exception_text = get_response(
request_future=future, error_type=error_type, social_network=social_network
)
# Get response time for response of our request.
try:
response_time = r.elapsed
except AttributeError:
response_time = None
# Attempt to get request information
try:
http_status = r.status_code
except Exception:
http_status = "?"
try:
response_text = r.text.encode(r.encoding or "UTF-8")
except Exception:
response_text = ""
query_status = QueryStatus.UNKNOWN
error_context = None
# As WAFs advance and evolve, they will occasionally block Sherlock and
# lead to false positives and negatives. Fingerprints should be added
# here to filter results that fail to bypass WAFs. Fingerprints should
# be highly targetted. Comment at the end of each fingerprint to
# indicate target and date fingerprinted.
WAFHitMsgs = [
r'.loading-spinner{visibility:hidden}body.no-js .challenge-running{display:none}body.dark{background-color:#222;color:#d9d9d9}body.dark a{color:#fff}body.dark a:hover{color:#ee730a;text-decoration:underline}body.dark .lds-ring div{border-color:#999 transparent transparent}body.dark .font-red{color:#b20f03}body.dark', # 2024-05-13 Cloudflare
r'<span id="challenge-error-text">', # 2024-11-11 Cloudflare error page
r'AwsWafIntegration.forceRefreshToken', # 2024-11-11 Cloudfront (AWS)
r'{return l.onPageView}}),Object.defineProperty(r,"perimeterxIdentifiers",{enumerable:' # 2024-04-09 PerimeterX / Human Security
]
if error_text is not None:
error_context = error_text
elif any(hitMsg in r.text for hitMsg in WAFHitMsgs):
query_status = QueryStatus.WAF
else:
if any(errtype not in ["message", "status_code", "response_url"] for errtype in error_type):
error_context = f"Unknown error type '{error_type}' for {social_network}"
query_status = QueryStatus.UNKNOWN
else:
if "message" in error_type:
# error_flag True denotes no error found in the HTML
# error_flag False denotes error found in the HTML
error_flag = True
errors = net_info.get("errorMsg")
# errors will hold the error message
# it can be string or list
# by isinstance method we can detect that
# and handle the case for strings as normal procedure
# and if its list we can iterate the errors
if isinstance(errors, str):
# Checks if the error message is in the HTML
# if error is present we will set flag to False
if errors in r.text:
error_flag = False
else:
# If it's list, it will iterate all the error message
for error in errors:
if error in r.text:
error_flag = False
break
if error_flag:
query_status = QueryStatus.CLAIMED
else:
query_status = QueryStatus.AVAILABLE
if "status_code" in error_type and query_status is not QueryStatus.AVAILABLE:
error_codes = net_info.get("errorCode")
query_status = QueryStatus.CLAIMED
# Type consistency, allowing for both singlets and lists in manifest
if isinstance(error_codes, int):
error_codes = [error_codes]
if error_codes is not None and r.status_code in error_codes:
query_status = QueryStatus.AVAILABLE
elif r.status_code >= 300 or r.status_code < 200:
query_status = QueryStatus.AVAILABLE
if "response_url" in error_type and query_status is not QueryStatus.AVAILABLE:
# For this detection method, we have turned off the redirect.
# So, there is no need to check the response URL: it will always
# match the request. Instead, we will ensure that the response
# code indicates that the request was successful (i.e. no 404, or
# forward to some odd redirect).
if 200 <= r.status_code < 300:
query_status = QueryStatus.CLAIMED
else:
query_status = QueryStatus.AVAILABLE
if dump_response:
print("+++++++++++++++++++++")
print(f"TARGET NAME : {social_network}")
print(f"USERNAME : {username}")
print(f"TARGET URL : {url}")
print(f"TEST METHOD : {error_type}")
try:
print(f"STATUS CODES : {net_info['errorCode']}")
except KeyError:
pass
print("Results...")
try:
print(f"RESPONSE CODE : {r.status_code}")
except Exception:
pass
try:
print(f"ERROR TEXT : {net_info['errorMsg']}")
except KeyError:
pass
print(">>>>> BEGIN RESPONSE TEXT")
try:
print(r.text)
except Exception:
pass
print("<<<<< END RESPONSE TEXT")
print("VERDICT : " + str(query_status))
print("+++++++++++++++++++++")
# Notify caller about results of query.
result: QueryResult = QueryResult(
username=username,
site_name=social_network,
site_url_user=url,
status=query_status,
query_time=response_time,
context=error_context,
)
query_notify.update(result)
# Save status of request
results_site["status"] = result
# Save results from request
results_site["http_status"] = http_status
results_site["response_text"] = response_text
# Add this site's results into final dictionary with all of the other results.
results_total[social_network] = results_site
return results_total
def timeout_check(value):
"""Check Timeout Argument.
Checks timeout for validity.
Keyword Arguments:
value -- Time in seconds to wait before timing out request.
Return Value:
Floating point number representing the time (in seconds) that should be
used for the timeout.
NOTE: Will raise an exception if the timeout in invalid.
"""
float_value = float(value)
if float_value <= 0:
raise ArgumentTypeError(
f"Invalid timeout value: {value}. Timeout must be a positive number."
)
return float_value
def handler(signal_received, frame):
"""Exit gracefully without throwing errors
Source: https://www.devdungeon.com/content/python-catch-sigint-ctrl-c
"""
sys.exit(0)
def main():
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description=f"{__longname__} (Version {__version__})",
)
parser.add_argument(
"--version",
action="version",
version=f"{__shortname__} v{__version__}",
help="Display version information and dependencies.",
)
parser.add_argument(
"--verbose",
"-v",
"-d",
"--debug",
action="store_true",
dest="verbose",
default=False,
help="Display extra debugging information and metrics.",
)
parser.add_argument(
"--folderoutput",
"-fo",
dest="folderoutput",
help="If using multiple usernames, the output of the results will be saved to this folder.",
)
parser.add_argument(
"--output",
"-o",
dest="output",
help="If using single username, the output of the result will be saved to this file.",
)
parser.add_argument(
"--csv",
action="store_true",
dest="csv",
default=False,
help="Create Comma-Separated Values (CSV) File.",
)
parser.add_argument(
"--xlsx",
action="store_true",
dest="xlsx",
default=False,
help="Create the standard file for the modern Microsoft Excel spreadsheet (xlsx).",
)
parser.add_argument(
"--site",
action="append",
metavar="SITE_NAME",
dest="site_list",
default=[],
help="Limit analysis to just the listed sites. Add multiple options to specify more than one site.",
)
parser.add_argument(
"--proxy",
"-p",
metavar="PROXY_URL",
action="store",
dest="proxy",
default=None,
help="Make requests over a proxy. e.g. socks5://127.0.0.1:1080",
)
parser.add_argument(
"--dump-response",
action="store_true",
dest="dump_response",
default=False,
help="Dump the HTTP response to stdout for targeted debugging.",
)
parser.add_argument(
"--json",
"-j",
metavar="JSON_FILE",
dest="json_file",
default=None,
help="Load data from a JSON file or an online, valid, JSON file. Upstream PR numbers also accepted.",
)
parser.add_argument(
"--timeout",
action="store",
metavar="TIMEOUT",
dest="timeout",
type=timeout_check,
default=60,
help="Time (in seconds) to wait for response to requests (Default: 60)",
)
parser.add_argument(
"--print-all",
action="store_true",
dest="print_all",
default=False,
help="Output sites where the username was not found.",
)
parser.add_argument(
"--print-found",
action="store_true",
dest="print_found",
default=True,
help="Output sites where the username was found (also if exported as file).",
)
parser.add_argument(
"--no-color",
action="store_true",
dest="no_color",
default=False,
help="Don't color terminal output",
)
parser.add_argument(
"username",
nargs="+",
metavar="USERNAMES",
action="store",
help="One or more usernames to check with social networks. Check similar usernames using {?} (replace to '_', '-', '.').",
)
parser.add_argument(
"--browse",
"-b",
action="store_true",
dest="browse",
default=False,
help="Browse to all results on default browser.",
)
parser.add_argument(
"--local",
"-l",
action="store_true",
default=False,
help="Force the use of the local data.json file.",
)
parser.add_argument(
"--nsfw",
action="store_true",
default=False,
help="Include checking of NSFW sites from default list.",
)
# TODO deprecated in favor of --txt, retained for workflow compatibility, to be removed
# in future release
parser.add_argument(
"--no-txt",
action="store_true",
dest="no_txt",
default=False,
help="Disable creation of a txt file - WILL BE DEPRECATED",
)
parser.add_argument(
"--txt",
action="store_true",
dest="output_txt",
default=False,
help="Enable creation of a txt file",
)
parser.add_argument(
"--ignore-exclusions",
action="store_true",
dest="ignore_exclusions",
default=False,
help="Ignore upstream exclusions (may return more false positives)",
)
args = parser.parse_args()
# If the user presses CTRL-C, exit gracefully without throwing errors
signal.signal(signal.SIGINT, handler)
# Check for newer version of Sherlock. If it exists, let the user know about it
try:
latest_release_raw = requests.get(forge_api_latest_release, timeout=10).text
latest_release_json = json_loads(latest_release_raw)
latest_remote_tag = latest_release_json["tag_name"]
if latest_remote_tag[1:] != __version__:
print(
f"Update available! {__version__} --> {latest_remote_tag[1:]}"
f"\n{latest_release_json['html_url']}"
)
except Exception as error:
print(f"A problem occurred while checking for an update: {error}")
# Make prompts
if args.proxy is not None:
print("Using the proxy: " + args.proxy)
if args.no_color:
# Disable color output.
init(strip=True, convert=False)
else:
# Enable color output.
init(autoreset=True)
# Check if both output methods are entered as input.
if args.output is not None and args.folderoutput is not None:
print("You can only use one of the output methods.")
sys.exit(1)
# Check validity for single username output.
if args.output is not None and len(args.username) != 1:
print("You can only use --output with a single username")
sys.exit(1)
# Create object with all information about sites we are aware of.
try:
if args.local:
sites = SitesInformation(
os.path.join(os.path.dirname(__file__), "resources/data.json"),
honor_exclusions=False,
)
else:
json_file_location = args.json_file
if args.json_file:
# If --json parameter is a number, interpret it as a pull request number
if args.json_file.isnumeric():
pull_number = args.json_file
pull_url = f"https://api.github.com/repos/sherlock-project/sherlock/pulls/{pull_number}"
pull_request_raw = requests.get(pull_url, timeout=10).text
pull_request_json = json_loads(pull_request_raw)
# Check if it's a valid pull request
if "message" in pull_request_json:
print(f"ERROR: Pull request #{pull_number} not found.")
sys.exit(1)
head_commit_sha = pull_request_json["head"]["sha"]
json_file_location = f"https://raw.githubusercontent.com/sherlock-project/sherlock/{head_commit_sha}/sherlock_project/resources/data.json"
sites = SitesInformation(
data_file_path=json_file_location,
honor_exclusions=not args.ignore_exclusions,
do_not_exclude=args.site_list,
)
except Exception as error:
print(f"ERROR: {error}")
sys.exit(1)
if not args.nsfw:
sites.remove_nsfw_sites(do_not_remove=args.site_list)
# Create original dictionary from SitesInformation() object.
# Eventually, the rest of the code will be updated to use the new object
# directly, but this will glue the two pieces together.
site_data_all = {site.name: site.information for site in sites}
if args.site_list == []:
# Not desired to look at a sub-set of sites
site_data = site_data_all
else:
# User desires to selectively run queries on a sub-set of the site list.
# Make sure that the sites are supported & build up pruned site database.
site_data = {}
site_missing = []
for site in args.site_list:
counter = 0
for existing_site in site_data_all:
if site.lower() == existing_site.lower():
site_data[existing_site] = site_data_all[existing_site]
counter += 1
if counter == 0:
# Build up list of sites not supported for future error message.
site_missing.append(f"'{site}'")
if site_missing:
print(f"Error: Desired sites not found: {', '.join(site_missing)}.")
if not site_data:
sys.exit(1)
# Create notify object for query results.
query_notify = QueryNotifyPrint(
result=None, verbose=args.verbose, print_all=args.print_all, browse=args.browse
)
# Run report on all specified users.
all_usernames = []
for username in args.username:
if check_for_parameter(username):
for name in multiple_usernames(username):
all_usernames.append(name)
else:
all_usernames.append(username)
for username in all_usernames:
results = sherlock(
username,
site_data,
query_notify,
dump_response=args.dump_response,
proxy=args.proxy,
timeout=args.timeout,
)
if args.output:
result_file = args.output
elif args.folderoutput:
# The usernames results should be stored in a targeted folder.
# If the folder doesn't exist, create it first
os.makedirs(args.folderoutput, exist_ok=True)
result_file = os.path.join(args.folderoutput, f"{username}.txt")
else:
result_file = f"{username}.txt"
if args.output_txt:
with open(result_file, "w", encoding="utf-8") as file:
exists_counter = 0
for website_name in results:
dictionary = results[website_name]
if dictionary.get("status").status == QueryStatus.CLAIMED:
exists_counter += 1
file.write(dictionary["url_user"] + "\n")
file.write(f"Total Websites Username Detected On : {exists_counter}\n")
if args.csv:
result_file = f"{username}.csv"
if args.folderoutput:
# The usernames results should be stored in a targeted folder.
# If the folder doesn't exist, create it first
os.makedirs(args.folderoutput, exist_ok=True)
result_file = os.path.join(args.folderoutput, result_file)
with open(result_file, "w", newline="", encoding="utf-8") as csv_report:
writer = csv.writer(csv_report)
writer.writerow(
[
"username",
"name",
"url_main",
"url_user",
"exists",
"http_status",
"response_time_s",
]
)
for site in results:
if (
args.print_found
and not args.print_all
and results[site]["status"].status != QueryStatus.CLAIMED
):
continue
response_time_s = results[site]["status"].query_time
if response_time_s is None:
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | true |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/sherlock_project/__init__.py | sherlock_project/__init__.py | """ Sherlock Module
This module contains the main logic to search for usernames at social
networks.
"""
from importlib.metadata import version as pkg_version, PackageNotFoundError
import pathlib
import tomli
def get_version() -> str:
"""Fetch the version number of the installed package."""
try:
return pkg_version("sherlock_project")
except PackageNotFoundError:
pyproject_path: pathlib.Path = pathlib.Path(__file__).resolve().parent.parent / "pyproject.toml"
with pyproject_path.open("rb") as f:
pyproject_data = tomli.load(f)
return pyproject_data["tool"]["poetry"]["version"]
# This variable is only used to check for ImportErrors induced by users running as script rather than as module or package
import_error_test_var = None
__shortname__ = "Sherlock"
__longname__ = "Sherlock: Find Usernames Across Social Networks"
__version__ = get_version()
forge_api_latest_release = "https://api.github.com/repos/sherlock-project/sherlock/releases/latest"
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/sherlock_project/notify.py | sherlock_project/notify.py | """Sherlock Notify Module
This module defines the objects for notifying the caller about the
results of queries.
"""
from sherlock_project.result import QueryStatus
from colorama import Fore, Style
import webbrowser
# Global variable to count the number of results.
globvar = 0
class QueryNotify:
"""Query Notify Object.
Base class that describes methods available to notify the results of
a query.
It is intended that other classes inherit from this base class and
override the methods to implement specific functionality.
"""
def __init__(self, result=None):
"""Create Query Notify Object.
Contains information about a specific method of notifying the results
of a query.
Keyword Arguments:
self -- This object.
result -- Object of type QueryResult() containing
results for this query.
Return Value:
Nothing.
"""
self.result = result
# return
def start(self, message=None):
"""Notify Start.
Notify method for start of query. This method will be called before
any queries are performed. This method will typically be
overridden by higher level classes that will inherit from it.
Keyword Arguments:
self -- This object.
message -- Object that is used to give context to start
of query.
Default is None.
Return Value:
Nothing.
"""
# return
def update(self, result):
"""Notify Update.
Notify method for query result. This method will typically be
overridden by higher level classes that will inherit from it.
Keyword Arguments:
self -- This object.
result -- Object of type QueryResult() containing
results for this query.
Return Value:
Nothing.
"""
self.result = result
# return
def finish(self, message=None):
"""Notify Finish.
Notify method for finish of query. This method will be called after
all queries have been performed. This method will typically be
overridden by higher level classes that will inherit from it.
Keyword Arguments:
self -- This object.
message -- Object that is used to give context to start
of query.
Default is None.
Return Value:
Nothing.
"""
# return
def __str__(self):
"""Convert Object To String.
Keyword Arguments:
self -- This object.
Return Value:
Nicely formatted string to get information about this object.
"""
return str(self.result)
class QueryNotifyPrint(QueryNotify):
"""Query Notify Print Object.
Query notify class that prints results.
"""
def __init__(self, result=None, verbose=False, print_all=False, browse=False):
"""Create Query Notify Print Object.
Contains information about a specific method of notifying the results
of a query.
Keyword Arguments:
self -- This object.
result -- Object of type QueryResult() containing
results for this query.
verbose -- Boolean indicating whether to give verbose output.
print_all -- Boolean indicating whether to only print all sites, including not found.
browse -- Boolean indicating whether to open found sites in a web browser.
Return Value:
Nothing.
"""
super().__init__(result)
self.verbose = verbose
self.print_all = print_all
self.browse = browse
return
def start(self, message):
"""Notify Start.
Will print the title to the standard output.
Keyword Arguments:
self -- This object.
message -- String containing username that the series
of queries are about.
Return Value:
Nothing.
"""
title = "Checking username"
print(Style.BRIGHT + Fore.GREEN + "[" +
Fore.YELLOW + "*" +
Fore.GREEN + f"] {title}" +
Fore.WHITE + f" {message}" +
Fore.GREEN + " on:")
# An empty line between first line and the result(more clear output)
print('\r')
return
def countResults(self):
"""This function counts the number of results. Every time the function is called,
the number of results is increasing.
Keyword Arguments:
self -- This object.
Return Value:
The number of results by the time we call the function.
"""
global globvar
globvar += 1
return globvar
def update(self, result):
"""Notify Update.
Will print the query result to the standard output.
Keyword Arguments:
self -- This object.
result -- Object of type QueryResult() containing
results for this query.
Return Value:
Nothing.
"""
self.result = result
response_time_text = ""
if self.result.query_time is not None and self.verbose is True:
response_time_text = f" [{round(self.result.query_time * 1000)}ms]"
# Output to the terminal is desired.
if result.status == QueryStatus.CLAIMED:
self.countResults()
print(Style.BRIGHT + Fore.WHITE + "[" +
Fore.GREEN + "+" +
Fore.WHITE + "]" +
response_time_text +
Fore.GREEN +
f" {self.result.site_name}: " +
Style.RESET_ALL +
f"{self.result.site_url_user}")
if self.browse:
webbrowser.open(self.result.site_url_user, 2)
elif result.status == QueryStatus.AVAILABLE:
if self.print_all:
print(Style.BRIGHT + Fore.WHITE + "[" +
Fore.RED + "-" +
Fore.WHITE + "]" +
response_time_text +
Fore.GREEN + f" {self.result.site_name}:" +
Fore.YELLOW + " Not Found!")
elif result.status == QueryStatus.UNKNOWN:
if self.print_all:
print(Style.BRIGHT + Fore.WHITE + "[" +
Fore.RED + "-" +
Fore.WHITE + "]" +
Fore.GREEN + f" {self.result.site_name}:" +
Fore.RED + f" {self.result.context}" +
Fore.YELLOW + " ")
elif result.status == QueryStatus.ILLEGAL:
if self.print_all:
msg = "Illegal Username Format For This Site!"
print(Style.BRIGHT + Fore.WHITE + "[" +
Fore.RED + "-" +
Fore.WHITE + "]" +
Fore.GREEN + f" {self.result.site_name}:" +
Fore.YELLOW + f" {msg}")
elif result.status == QueryStatus.WAF:
if self.print_all:
print(Style.BRIGHT + Fore.WHITE + "[" +
Fore.RED + "-" +
Fore.WHITE + "]" +
Fore.GREEN + f" {self.result.site_name}:" +
Fore.RED + " Blocked by bot detection" +
Fore.YELLOW + " (proxy may help)")
else:
# It should be impossible to ever get here...
raise ValueError(
f"Unknown Query Status '{result.status}' for site '{self.result.site_name}'"
)
return
def finish(self, message="The processing has been finished."):
"""Notify Start.
Will print the last line to the standard output.
Keyword Arguments:
self -- This object.
message -- The 2 last phrases.
Return Value:
Nothing.
"""
NumberOfResults = self.countResults() - 1
print(Style.BRIGHT + Fore.GREEN + "[" +
Fore.YELLOW + "*" +
Fore.GREEN + "] Search completed with" +
Fore.WHITE + f" {NumberOfResults} " +
Fore.GREEN + "results" + Style.RESET_ALL
)
def __str__(self):
"""Convert Object To String.
Keyword Arguments:
self -- This object.
Return Value:
Nicely formatted string to get information about this object.
"""
return str(self.result)
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/tests/test_manifest.py | tests/test_manifest.py | import os
import json
import pytest
from jsonschema import validate
def test_validate_manifest_against_local_schema():
"""Ensures that the manifest matches the local schema, for situations where the schema is being changed."""
json_relative: str = '../sherlock_project/resources/data.json'
schema_relative: str = '../sherlock_project/resources/data.schema.json'
json_path: str = os.path.join(os.path.dirname(__file__), json_relative)
schema_path: str = os.path.join(os.path.dirname(__file__), schema_relative)
with open(json_path, 'r') as f:
jsondat = json.load(f)
with open(schema_path, 'r') as f:
schemadat = json.load(f)
validate(instance=jsondat, schema=schemadat)
@pytest.mark.online
def test_validate_manifest_against_remote_schema(remote_schema):
"""Ensures that the manifest matches the remote schema, so as to not unexpectedly break clients."""
json_relative: str = '../sherlock_project/resources/data.json'
json_path: str = os.path.join(os.path.dirname(__file__), json_relative)
with open(json_path, 'r') as f:
jsondat = json.load(f)
validate(instance=jsondat, schema=remote_schema)
# Ensure that the expected values are beind returned by the site list
@pytest.mark.parametrize("target_name,target_expected_err_type", [
('GitHub', 'status_code'),
('GitLab', 'message'),
])
def test_site_list_iterability (sites_info, target_name, target_expected_err_type):
assert sites_info[target_name]['errorType'] == target_expected_err_type
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/tests/conftest.py | tests/conftest.py | import os
import json
import urllib
import pytest
from sherlock_project.sites import SitesInformation
def fetch_local_manifest(honor_exclusions: bool = True) -> dict[str, dict[str, str]]:
sites_obj = SitesInformation(data_file_path=os.path.join(os.path.dirname(__file__), "../sherlock_project/resources/data.json"), honor_exclusions=honor_exclusions)
sites_iterable: dict[str, dict[str, str]] = {site.name: site.information for site in sites_obj}
return sites_iterable
@pytest.fixture()
def sites_obj():
sites_obj = SitesInformation(data_file_path=os.path.join(os.path.dirname(__file__), "../sherlock_project/resources/data.json"))
yield sites_obj
@pytest.fixture(scope="session")
def sites_info():
yield fetch_local_manifest()
@pytest.fixture(scope="session")
def remote_schema():
schema_url: str = 'https://raw.githubusercontent.com/sherlock-project/sherlock/master/sherlock_project/resources/data.schema.json'
with urllib.request.urlopen(schema_url) as remoteschema:
schemadat = json.load(remoteschema)
yield schemadat
def pytest_addoption(parser):
parser.addoption(
"--chunked-sites",
action="store",
default=None,
help="For tests utilizing chunked sites, include only the (comma-separated) site(s) specified.",
)
def pytest_generate_tests(metafunc):
if "chunked_sites" in metafunc.fixturenames:
sites_info = fetch_local_manifest(honor_exclusions=False)
# Ingest and apply site selections
site_filter: str | None = metafunc.config.getoption("--chunked-sites")
if site_filter:
selected_sites: list[str] = [site.strip() for site in site_filter.split(",")]
sites_info = {
site: data for site, data in sites_info.items()
if site in selected_sites
}
params = [{name: data} for name, data in sites_info.items()]
ids = list(sites_info.keys())
metafunc.parametrize("chunked_sites", params, ids=ids)
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/tests/test_validate_targets.py | tests/test_validate_targets.py | import pytest
import re
import rstr
from sherlock_project.sherlock import sherlock
from sherlock_project.notify import QueryNotify
from sherlock_project.result import QueryResult, QueryStatus
FALSE_POSITIVE_ATTEMPTS: int = 2 # Since the usernames are randomly generated, it's POSSIBLE that a real username can be hit
FALSE_POSITIVE_QUANTIFIER_UPPER_BOUND: int = 15 # If a pattern uses quantifiers such as `+` `*` or `{n,}`, limit the upper bound (0 to disable)
FALSE_POSITIVE_DEFAULT_PATTERN: str = r'^[a-zA-Z0-9]{7,20}$' # Used in absence of a regexCheck entry
def set_pattern_upper_bound(pattern: str, upper_bound: int = FALSE_POSITIVE_QUANTIFIER_UPPER_BOUND) -> str:
"""Set upper bound for regex patterns that use quantifiers such as `+` `*` or `{n,}`."""
def replace_upper_bound(match: re.Match) -> str: # type: ignore
lower_bound: int = int(match.group(1)) if match.group(1) else 0 # type: ignore
nonlocal upper_bound
upper_bound = upper_bound if lower_bound < upper_bound else lower_bound # type: ignore # noqa: F823
return f'{{{lower_bound},{upper_bound}}}'
pattern = re.sub(r'(?<!\\)\{(\d+),\}', replace_upper_bound, pattern) # {n,} # type: ignore
pattern = re.sub(r'(?<!\\)\+', f'{{1,{upper_bound}}}', pattern) # +
pattern = re.sub(r'(?<!\\)\*', f'{{0,{upper_bound}}}', pattern) # *
return pattern
def false_positive_check(sites_info: dict[str, dict[str, str]], site: str, pattern: str) -> QueryStatus:
"""Check if a site is likely to produce false positives."""
status: QueryStatus = QueryStatus.UNKNOWN
for _ in range(FALSE_POSITIVE_ATTEMPTS):
query_notify: QueryNotify = QueryNotify()
username: str = rstr.xeger(pattern)
result: QueryResult | str = sherlock(
username=username,
site_data=sites_info,
query_notify=query_notify,
)[site]['status']
if not hasattr(result, 'status'):
raise TypeError(f"Result for site {site} does not have 'status' attribute. Actual result: {result}")
if type(result.status) is not QueryStatus: # type: ignore
raise TypeError(f"Result status for site {site} is not of type QueryStatus. Actual type: {type(result.status)}") # type: ignore
status = result.status # type: ignore
if status in (QueryStatus.AVAILABLE, QueryStatus.WAF):
return status
return status
def false_negative_check(sites_info: dict[str, dict[str, str]], site: str) -> QueryStatus:
"""Check if a site is likely to produce false negatives."""
status: QueryStatus = QueryStatus.UNKNOWN
query_notify: QueryNotify = QueryNotify()
result: QueryResult | str = sherlock(
username=sites_info[site]['username_claimed'],
site_data=sites_info,
query_notify=query_notify,
)[site]['status']
if not hasattr(result, 'status'):
raise TypeError(f"Result for site {site} does not have 'status' attribute. Actual result: {result}")
if type(result.status) is not QueryStatus: # type: ignore
raise TypeError(f"Result status for site {site} is not of type QueryStatus. Actual type: {type(result.status)}") # type: ignore
status = result.status # type: ignore
return status
@pytest.mark.validate_targets
@pytest.mark.online
class Test_All_Targets:
@pytest.mark.validate_targets_fp
def test_false_pos(self, chunked_sites: dict[str, dict[str, str]]):
"""Iterate through all sites in the manifest to discover possible false-positive inducting targets."""
pattern: str
for site in chunked_sites:
try:
pattern = chunked_sites[site]['regexCheck']
except KeyError:
pattern = FALSE_POSITIVE_DEFAULT_PATTERN
if FALSE_POSITIVE_QUANTIFIER_UPPER_BOUND > 0:
pattern = set_pattern_upper_bound(pattern)
result: QueryStatus = false_positive_check(chunked_sites, site, pattern)
assert result is QueryStatus.AVAILABLE, f"{site} produced false positive with pattern {pattern}, result was {result}"
@pytest.mark.validate_targets_fn
def test_false_neg(self, chunked_sites: dict[str, dict[str, str]]):
"""Iterate through all sites in the manifest to discover possible false-negative inducting targets."""
for site in chunked_sites:
result: QueryStatus = false_negative_check(chunked_sites, site)
assert result is QueryStatus.CLAIMED, f"{site} produced false negative, result was {result}"
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/tests/sherlock_interactives.py | tests/sherlock_interactives.py | import os
import platform
import re
import subprocess
class Interactives:
def run_cli(args:str = "") -> str:
"""Pass arguments to Sherlock as a normal user on the command line"""
# Adapt for platform differences (Windows likes to be special)
if platform.system() == "Windows":
command:str = f"py -m sherlock_project {args}"
else:
command:str = f"sherlock {args}"
proc_out:str = ""
try:
proc_out = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
return proc_out.decode()
except subprocess.CalledProcessError as e:
raise InteractivesSubprocessError(e.output.decode())
def walk_sherlock_for_files_with(pattern: str) -> list[str]:
"""Check all files within the Sherlock package for matching patterns"""
pattern:re.Pattern = re.compile(pattern)
matching_files:list[str] = []
for root, dirs, files in os.walk("sherlock_project"):
for file in files:
file_path = os.path.join(root,file)
if "__pycache__" in file_path:
continue
with open(file_path, 'r', errors='ignore') as f:
if pattern.search(f.read()):
matching_files.append(file_path)
return matching_files
class InteractivesSubprocessError(Exception):
pass
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/tests/test_version.py | tests/test_version.py | import os
from sherlock_interactives import Interactives
import sherlock_project
def test_versioning() -> None:
# Ensure __version__ matches version presented to the user
assert sherlock_project.__version__ in Interactives.run_cli("--version")
# Ensure __init__ is single source of truth for __version__ in package
# Temporarily allows sherlock.py so as to not trigger early upgrades
found:list = Interactives.walk_sherlock_for_files_with(r'__version__ *= *')
expected:list = [
# Normalization is REQUIRED for Windows ( / vs \ )
os.path.normpath("sherlock_project/__init__.py"),
]
# Sorting is REQUIRED for Mac
assert sorted(found) == sorted(expected)
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/tests/test_ux.py | tests/test_ux.py | import pytest
from sherlock_project import sherlock
from sherlock_interactives import Interactives
from sherlock_interactives import InteractivesSubprocessError
def test_remove_nsfw(sites_obj):
nsfw_target: str = 'Pornhub'
assert nsfw_target in {site.name: site.information for site in sites_obj}
sites_obj.remove_nsfw_sites()
assert nsfw_target not in {site.name: site.information for site in sites_obj}
# Parametrized sites should *not* include Motherless, which is acting as the control
@pytest.mark.parametrize('nsfwsites', [
['Pornhub'],
['Pornhub', 'Xvideos'],
])
def test_nsfw_explicit_selection(sites_obj, nsfwsites):
for site in nsfwsites:
assert site in {site.name: site.information for site in sites_obj}
sites_obj.remove_nsfw_sites(do_not_remove=nsfwsites)
for site in nsfwsites:
assert site in {site.name: site.information for site in sites_obj}
assert 'Motherless' not in {site.name: site.information for site in sites_obj}
def test_wildcard_username_expansion():
assert sherlock.check_for_parameter('test{?}test') is True
assert sherlock.check_for_parameter('test{.}test') is False
assert sherlock.check_for_parameter('test{}test') is False
assert sherlock.check_for_parameter('testtest') is False
assert sherlock.check_for_parameter('test{?test') is False
assert sherlock.check_for_parameter('test?}test') is False
assert sherlock.multiple_usernames('test{?}test') == ["test_test" , "test-test" , "test.test"]
@pytest.mark.parametrize('cliargs', [
'',
'--site urghrtuight --egiotr',
'--',
])
def test_no_usernames_provided(cliargs):
with pytest.raises(InteractivesSubprocessError, match=r"error: the following arguments are required: USERNAMES"):
Interactives.run_cli(cliargs)
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/tests/test_probes.py | tests/test_probes.py | import pytest
import random
import string
import re
from sherlock_project.sherlock import sherlock
from sherlock_project.notify import QueryNotify
from sherlock_project.result import QueryStatus
#from sherlock_interactives import Interactives
def simple_query(sites_info: dict, site: str, username: str) -> QueryStatus:
query_notify = QueryNotify()
site_data: dict = {}
site_data[site] = sites_info[site]
return sherlock(
username=username,
site_data=site_data,
query_notify=query_notify,
)[site]['status'].status
@pytest.mark.online
class TestLiveTargets:
"""Actively test probes against live and trusted targets"""
# Known positives should only use sites trusted to be reliable and unchanging
@pytest.mark.parametrize('site,username',[
('GitLab', 'ppfeister'),
('AllMyLinks', 'blue'),
])
def test_known_positives_via_message(self, sites_info, site, username):
assert simple_query(sites_info=sites_info, site=site, username=username) is QueryStatus.CLAIMED
# Known positives should only use sites trusted to be reliable and unchanging
@pytest.mark.parametrize('site,username',[
('GitHub', 'ppfeister'),
('GitHub', 'sherlock-project'),
('Docker Hub', 'ppfeister'),
('Docker Hub', 'sherlock'),
])
def test_known_positives_via_status_code(self, sites_info, site, username):
assert simple_query(sites_info=sites_info, site=site, username=username) is QueryStatus.CLAIMED
# Known positives should only use sites trusted to be reliable and unchanging
@pytest.mark.parametrize('site,username',[
('Keybase', 'blue'),
('devRant', 'blue'),
])
def test_known_positives_via_response_url(self, sites_info, site, username):
assert simple_query(sites_info=sites_info, site=site, username=username) is QueryStatus.CLAIMED
# Randomly generate usernames of high length and test for positive availability
# Randomly generated usernames should be simple alnum for simplicity and high
# compatibility. Several attempts may be made ~just in case~ a real username is
# generated.
@pytest.mark.parametrize('site,random_len',[
('GitLab', 255),
('Codecademy', 30)
])
def test_likely_negatives_via_message(self, sites_info, site, random_len):
num_attempts: int = 3
attempted_usernames: list[str] = []
status: QueryStatus = QueryStatus.CLAIMED
for i in range(num_attempts):
acceptable_types = string.ascii_letters + string.digits
random_handle = ''.join(random.choice(acceptable_types) for _ in range (random_len))
attempted_usernames.append(random_handle)
status = simple_query(sites_info=sites_info, site=site, username=random_handle)
if status is QueryStatus.AVAILABLE:
break
assert status is QueryStatus.AVAILABLE, f"Could not validate available username after {num_attempts} attempts with randomly generated usernames {attempted_usernames}."
# Randomly generate usernames of high length and test for positive availability
# Randomly generated usernames should be simple alnum for simplicity and high
# compatibility. Several attempts may be made ~just in case~ a real username is
# generated.
@pytest.mark.parametrize('site,random_len',[
('GitHub', 39),
('Docker Hub', 30)
])
def test_likely_negatives_via_status_code(self, sites_info, site, random_len):
num_attempts: int = 3
attempted_usernames: list[str] = []
status: QueryStatus = QueryStatus.CLAIMED
for i in range(num_attempts):
acceptable_types = string.ascii_letters + string.digits
random_handle = ''.join(random.choice(acceptable_types) for _ in range (random_len))
attempted_usernames.append(random_handle)
status = simple_query(sites_info=sites_info, site=site, username=random_handle)
if status is QueryStatus.AVAILABLE:
break
assert status is QueryStatus.AVAILABLE, f"Could not validate available username after {num_attempts} attempts with randomly generated usernames {attempted_usernames}."
def test_username_illegal_regex(sites_info):
site: str = 'BitBucket'
invalid_handle: str = '*#$Y&*JRE'
pattern = re.compile(sites_info[site]['regexCheck'])
# Ensure that the username actually fails regex before testing sherlock
assert pattern.match(invalid_handle) is None
assert simple_query(sites_info=sites_info, site=site, username=invalid_handle) is QueryStatus.ILLEGAL
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/tests/few_test_basic.py | tests/few_test_basic.py | import sherlock_project
#from sherlock.sites import SitesInformation
#local_manifest = data_file_path=os.path.join(os.path.dirname(__file__), "../sherlock/resources/data.json")
def test_username_via_message():
sherlock_project.__main__("--version")
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/devel/site-list.py | devel/site-list.py | #!/usr/bin/env python
# This module generates the listing of supported sites which can be found in
# sites.mdx. It also organizes all the sites in alphanumeric order
import json
import os
DATA_REL_URI: str = "sherlock_project/resources/data.json"
DEFAULT_ENCODING = "utf-8"
# Read the data.json file
with open(DATA_REL_URI, "r", encoding=DEFAULT_ENCODING) as data_file:
data: dict = json.load(data_file)
# Removes schema-specific keywords for proper processing
social_networks = data.copy()
social_networks.pop('$schema', None)
# Sort the social networks in alphanumeric order
social_networks = sorted(social_networks.items())
# Make output dir where the site list will be written
os.mkdir("output")
# Write the list of supported sites to sites.mdx
with open("output/sites.mdx", "w", encoding=DEFAULT_ENCODING) as site_file:
site_file.write("---\n")
site_file.write("title: 'List of supported sites'\n")
site_file.write("sidebarTitle: 'Supported sites'\n")
site_file.write("icon: 'globe'\n")
site_file.write("description: 'Sherlock currently supports **400+** sites'\n")
site_file.write("---\n\n")
for social_network, info in social_networks:
url_main = info["urlMain"]
is_nsfw = "**(NSFW)**" if info.get("isNSFW") else ""
site_file.write(f"1. [{social_network}]({url_main}) {is_nsfw}\n")
# Overwrite the data.json file with sorted data
with open(DATA_REL_URI, "w", encoding=DEFAULT_ENCODING) as data_file:
sorted_data = json.dumps(data, indent=2, sort_keys=True)
data_file.write(sorted_data)
data_file.write("\n") # Keep the newline after writing data
print("Finished updating supported site listing!")
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
sherlock-project/sherlock | https://github.com/sherlock-project/sherlock/blob/8f1308b90d2b79296ce78d666e53d9be919efe02/devel/summarize_site_validation.py | devel/summarize_site_validation.py | #!/usr/bin/env python
# This module summarizes the results of site validation tests queued by
# workflow validate_modified_targets for presentation in Issue comments.
from defusedxml import ElementTree as ET
import sys
from pathlib import Path
def summarize_junit_xml(xml_path: Path) -> str:
tree = ET.parse(xml_path)
root = tree.getroot()
suite = root.find('testsuite')
pass_message: str = ":heavy_check_mark: Pass"
fail_message: str = ":x: Fail"
if suite is None:
raise ValueError("Invalid JUnit XML: No testsuite found")
summary_lines: list[str] = []
summary_lines.append("#### Automatic validation of changes\n")
summary_lines.append("| Target | F+ Check | F- Check |")
summary_lines.append("|---|---|---|")
failures = int(suite.get('failures', 0))
errors_detected: bool = False
results: dict[str, dict[str, str]] = {}
for testcase in suite.findall('testcase'):
test_name = testcase.get('name').split('[')[0]
site_name = testcase.get('name').split('[')[1].rstrip(']')
failure = testcase.find('failure')
error = testcase.find('error')
if site_name not in results:
results[site_name] = {}
if test_name == "test_false_neg":
results[site_name]['F- Check'] = pass_message if failure is None and error is None else fail_message
elif test_name == "test_false_pos":
results[site_name]['F+ Check'] = pass_message if failure is None and error is None else fail_message
if error is not None:
errors_detected = True
for result in results:
summary_lines.append(f"| {result} | {results[result].get('F+ Check', 'Error!')} | {results[result].get('F- Check', 'Error!')} |")
if failures > 0:
summary_lines.append("\n___\n" +
"\nFailures were detected on at least one updated target. Commits containing accuracy failures" +
" will often not be merged (unless a rationale is provided, such as false negatives due to regional differences).")
if errors_detected:
summary_lines.append("\n___\n" +
"\n**Errors were detected during validation. Please review the workflow logs.**")
return "\n".join(summary_lines)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: summarize_site_validation.py <junit-xml-file>")
sys.exit(1)
xml_path: Path = Path(sys.argv[1])
if not xml_path.is_file():
print(f"Error: File '{xml_path}' does not exist.")
sys.exit(1)
summary: str = summarize_junit_xml(xml_path)
print(summary)
| python | MIT | 8f1308b90d2b79296ce78d666e53d9be919efe02 | 2026-01-04T14:38:17.815883Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/pdm_build.py | pdm_build.py | import os
from typing import Any
from pdm.backend.hooks import Context
TIANGOLO_BUILD_PACKAGE = os.getenv("TIANGOLO_BUILD_PACKAGE", "fastapi")
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"].get(TIANGOLO_BUILD_PACKAGE)
if not config:
return
project_config: dict[str, Any] = config["project"]
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/translate.py | scripts/translate.py | import json
import secrets
import subprocess
from collections.abc import Iterable
from functools import lru_cache
from os import sep as pathsep
from pathlib import Path
from typing import Annotated
import git
import typer
import yaml
from github import Github
from pydantic_ai import Agent
from rich import print
non_translated_sections = (
f"reference{pathsep}",
"release-notes.md",
"fastapi-people.md",
"external-links.md",
"newsletter.md",
"management-tasks.md",
"management.md",
"contributing.md",
)
general_prompt_path = Path(__file__).absolute().parent / "llm-general-prompt.md"
general_prompt = general_prompt_path.read_text(encoding="utf-8")
app = typer.Typer()
@lru_cache
def get_langs() -> dict[str, str]:
return yaml.safe_load(Path("docs/language_names.yml").read_text(encoding="utf-8"))
def generate_lang_path(*, lang: str, path: Path) -> Path:
en_docs_path = Path("docs/en/docs")
assert str(path).startswith(str(en_docs_path)), (
f"Path must be inside {en_docs_path}"
)
lang_docs_path = Path(f"docs/{lang}/docs")
out_path = Path(str(path).replace(str(en_docs_path), str(lang_docs_path)))
return out_path
def generate_en_path(*, lang: str, path: Path) -> Path:
en_docs_path = Path("docs/en/docs")
assert not str(path).startswith(str(en_docs_path)), (
f"Path must not be inside {en_docs_path}"
)
lang_docs_path = Path(f"docs/{lang}/docs")
out_path = Path(str(path).replace(str(lang_docs_path), str(en_docs_path)))
return out_path
@app.command()
def translate_page(
*,
language: Annotated[str, typer.Option(envvar="LANGUAGE")],
en_path: Annotated[Path, typer.Option(envvar="EN_PATH")],
) -> None:
assert language != "en", (
"`en` is the source language, choose another language as translation target"
)
langs = get_langs()
language_name = langs[language]
lang_path = Path(f"docs/{language}")
lang_path.mkdir(exist_ok=True)
lang_prompt_path = lang_path / "llm-prompt.md"
assert lang_prompt_path.exists(), f"Prompt file not found: {lang_prompt_path}"
lang_prompt_content = lang_prompt_path.read_text(encoding="utf-8")
en_docs_path = Path("docs/en/docs")
assert str(en_path).startswith(str(en_docs_path)), (
f"Path must be inside {en_docs_path}"
)
out_path = generate_lang_path(lang=language, path=en_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
original_content = en_path.read_text(encoding="utf-8")
old_translation: str | None = None
if out_path.exists():
print(f"Found existing translation: {out_path}")
old_translation = out_path.read_text(encoding="utf-8")
print(f"Translating {en_path} to {language} ({language_name})")
agent = Agent("openai:gpt-5.2")
prompt_segments = [
general_prompt,
lang_prompt_content,
]
if old_translation:
prompt_segments.extend(
[
"There is an existing previous translation for the original English content, that may be outdated.",
"Update the translation only where necessary:",
"- If the original English content has added parts, also add these parts to the translation.",
"- If the original English content has removed parts, also remove them from the translation, unless you were instructed earlier to not do that in specific cases.",
"- If parts of the original English content have changed, also change those parts in the translation.",
"- If the previous translation violates current instructions, update it.",
"- Otherwise, preserve the original translation LINE-BY-LINE, AS-IS.",
"Do not:",
"- rephrase or rewrite correct lines just to improve the style.",
"- add or remove line breaks, unless the original English content changed.",
"- change formatting or whitespace unless absolutely required.",
"Only change what must be changed. The goal is to minimize diffs for easier human review.",
"UNLESS you were instructed earlier to behave different, there MUST NOT be whole sentences or partial sentences in the updated translation, which are not in the original English content, and there MUST NOT be whole sentences or partial sentences in the original English content, which are not in the updated translation. Remember: the updated translation shall be IN SYNC with the original English content.",
"Previous translation:",
f"%%%\n{old_translation}%%%",
]
)
prompt_segments.extend(
[
f"Translate to {language} ({language_name}).",
"Original content:",
f"%%%\n{original_content}%%%",
]
)
prompt = "\n\n".join(prompt_segments)
print(f"Running agent for {out_path}")
result = agent.run_sync(prompt)
out_content = f"{result.output.strip()}\n"
print(f"Saving translation to {out_path}")
out_path.write_text(out_content, encoding="utf-8", newline="\n")
def iter_all_en_paths() -> Iterable[Path]:
"""
Iterate on the markdown files to translate in order of priority.
"""
first_dirs = [
Path("docs/en/docs/learn"),
Path("docs/en/docs/tutorial"),
Path("docs/en/docs/advanced"),
Path("docs/en/docs/about"),
Path("docs/en/docs/how-to"),
]
first_parent = Path("docs/en/docs")
yield from first_parent.glob("*.md")
for dir_path in first_dirs:
yield from dir_path.rglob("*.md")
first_dirs_str = tuple(str(d) for d in first_dirs)
for path in Path("docs/en/docs").rglob("*.md"):
if str(path).startswith(first_dirs_str):
continue
if path.parent == first_parent:
continue
yield path
def iter_en_paths_to_translate() -> Iterable[Path]:
en_docs_root = Path("docs/en/docs/")
for path in iter_all_en_paths():
relpath = path.relative_to(en_docs_root)
if not str(relpath).startswith(non_translated_sections):
yield path
@app.command()
def translate_lang(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
paths_to_process = list(iter_en_paths_to_translate())
print("Original paths:")
for p in paths_to_process:
print(f" - {p}")
print(f"Total original paths: {len(paths_to_process)}")
missing_paths: list[Path] = []
skipped_paths: list[Path] = []
for p in paths_to_process:
lang_path = generate_lang_path(lang=language, path=p)
if lang_path.exists():
skipped_paths.append(p)
continue
missing_paths.append(p)
print("Paths to skip:")
for p in skipped_paths:
print(f" - {p}")
print(f"Total paths to skip: {len(skipped_paths)}")
print("Paths to process:")
for p in missing_paths:
print(f" - {p}")
print(f"Total paths to process: {len(missing_paths)}")
for p in missing_paths:
print(f"Translating: {p}")
translate_page(language="es", en_path=p)
print(f"Done translating: {p}")
def get_llm_translatable() -> list[str]:
translatable_langs = []
langs = get_langs()
for lang in langs:
if lang == "en":
continue
lang_prompt_path = Path(f"docs/{lang}/llm-prompt.md")
if lang_prompt_path.exists():
translatable_langs.append(lang)
return translatable_langs
@app.command()
def list_llm_translatable() -> list[str]:
translatable_langs = get_llm_translatable()
print("LLM translatable languages:", translatable_langs)
return translatable_langs
@app.command()
def llm_translatable_json(
language: Annotated[str | None, typer.Option(envvar="LANGUAGE")] = None,
) -> None:
translatable_langs = get_llm_translatable()
if language:
if language in translatable_langs:
print(json.dumps([language]))
return
else:
raise typer.Exit(code=1)
print(json.dumps(translatable_langs))
@app.command()
def commands_json(
command: Annotated[str | None, typer.Option(envvar="COMMAND")] = None,
) -> None:
available_commands = [
"translate-page",
"translate-lang",
"update-outdated",
"add-missing",
"update-and-add",
"remove-removable",
]
default_commands = [
"remove-removable",
"update-outdated",
"add-missing",
]
if command:
if command in available_commands:
print(json.dumps([command]))
return
else:
raise typer.Exit(code=1)
print(json.dumps(default_commands))
@app.command()
def list_removable(language: str) -> list[Path]:
removable_paths: list[Path] = []
lang_paths = Path(f"docs/{language}").rglob("*.md")
for path in lang_paths:
en_path = generate_en_path(lang=language, path=path)
if not en_path.exists():
removable_paths.append(path)
print(removable_paths)
return removable_paths
@app.command()
def list_all_removable() -> list[Path]:
all_removable_paths: list[Path] = []
langs = get_langs()
for lang in langs:
if lang == "en":
continue
removable_paths = list_removable(lang)
all_removable_paths.extend(removable_paths)
print(all_removable_paths)
return all_removable_paths
@app.command()
def remove_removable(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
removable_paths = list_removable(language)
for path in removable_paths:
path.unlink()
print(f"Removed: {path}")
print("Done removing all removable paths")
@app.command()
def remove_all_removable() -> None:
all_removable = list_all_removable()
for removable_path in all_removable:
removable_path.unlink()
print(f"Removed: {removable_path}")
print("Done removing all removable paths")
@app.command()
def list_missing(language: str) -> list[Path]:
missing_paths: list[Path] = []
en_lang_paths = list(iter_en_paths_to_translate())
for path in en_lang_paths:
lang_path = generate_lang_path(lang=language, path=path)
if not lang_path.exists():
missing_paths.append(path)
print(missing_paths)
return missing_paths
@app.command()
def list_outdated(language: str) -> list[Path]:
dir_path = Path(__file__).absolute().parent.parent
repo = git.Repo(dir_path)
outdated_paths: list[Path] = []
en_lang_paths = list(iter_en_paths_to_translate())
for path in en_lang_paths:
lang_path = generate_lang_path(lang=language, path=path)
if not lang_path.exists():
continue
en_commit_datetime = list(repo.iter_commits(paths=path, max_count=1))[
0
].committed_datetime
lang_commit_datetime = list(repo.iter_commits(paths=lang_path, max_count=1))[
0
].committed_datetime
if lang_commit_datetime < en_commit_datetime:
outdated_paths.append(path)
print(outdated_paths)
return outdated_paths
@app.command()
def update_outdated(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
outdated_paths = list_outdated(language)
for path in outdated_paths:
print(f"Updating lang: {language} path: {path}")
translate_page(language=language, en_path=path)
print(f"Done updating: {path}")
print("Done updating all outdated paths")
@app.command()
def add_missing(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
missing_paths = list_missing(language)
for path in missing_paths:
print(f"Adding lang: {language} path: {path}")
translate_page(language=language, en_path=path)
print(f"Done adding: {path}")
print("Done adding all missing paths")
@app.command()
def update_and_add(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
print(f"Updating outdated translations for {language}")
update_outdated(language=language)
print(f"Adding missing translations for {language}")
add_missing(language=language)
print(f"Done updating and adding for {language}")
@app.command()
def make_pr(
*,
language: Annotated[str | None, typer.Option(envvar="LANGUAGE")] = None,
command: Annotated[str | None, typer.Option(envvar="COMMAND")] = None,
github_token: Annotated[str, typer.Option(envvar="GITHUB_TOKEN")],
github_repository: Annotated[str, typer.Option(envvar="GITHUB_REPOSITORY")],
) -> None:
print("Setting up GitHub Actions git user")
repo = git.Repo(Path(__file__).absolute().parent.parent)
if not repo.is_dirty(untracked_files=True):
print("Repository is clean, no changes to commit")
return
subprocess.run(["git", "config", "user.name", "github-actions[bot]"], check=True)
subprocess.run(
["git", "config", "user.email", "github-actions[bot]@users.noreply.github.com"],
check=True,
)
branch_name = "translate"
if language:
branch_name += f"-{language}"
if command:
branch_name += f"-{command}"
branch_name += f"-{secrets.token_hex(4)}"
print(f"Creating a new branch {branch_name}")
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
print("Adding updated files")
git_path = Path("docs")
subprocess.run(["git", "add", str(git_path)], check=True)
print("Committing updated file")
message = "🌐 Update translations"
if language:
message += f" for {language}"
if command:
message += f" ({command})"
subprocess.run(["git", "commit", "-m", message], check=True)
print("Pushing branch")
subprocess.run(["git", "push", "origin", branch_name], check=True)
print("Creating PR")
g = Github(github_token)
gh_repo = g.get_repo(github_repository)
body = (
message
+ "\n\nThis PR was created automatically using LLMs."
+ f"\n\nIt uses the prompt file https://github.com/fastapi/fastapi/blob/master/docs/{language}/llm-prompt.md."
+ "\n\nIn most cases, it's better to make PRs updating that file so that the LLM can do a better job generating the translations than suggesting changes in this PR."
)
pr = gh_repo.create_pull(title=message, body=body, base="master", head=branch_name)
print(f"Created PR: {pr.number}")
print("Finished")
if __name__ == "__main__":
app()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/sponsors.py | scripts/sponsors.py | import logging
import secrets
import subprocess
from collections import defaultdict
from pathlib import Path
from typing import Any
import httpx
import yaml
from github import Github
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings
github_graphql_url = "https://api.github.com/graphql"
sponsors_query = """
query Q($after: String) {
user(login: "tiangolo") {
sponsorshipsAsMaintainer(first: 100, after: $after) {
edges {
cursor
node {
sponsorEntity {
... on Organization {
login
avatarUrl
url
}
... on User {
login
avatarUrl
url
}
}
tier {
name
monthlyPriceInDollars
}
}
}
}
}
}
"""
class SponsorEntity(BaseModel):
login: str
avatarUrl: str
url: str
class Tier(BaseModel):
name: str
monthlyPriceInDollars: float
class SponsorshipAsMaintainerNode(BaseModel):
sponsorEntity: SponsorEntity
tier: Tier
class SponsorshipAsMaintainerEdge(BaseModel):
cursor: str
node: SponsorshipAsMaintainerNode
class SponsorshipAsMaintainer(BaseModel):
edges: list[SponsorshipAsMaintainerEdge]
class SponsorsUser(BaseModel):
sponsorshipsAsMaintainer: SponsorshipAsMaintainer
class SponsorsResponseData(BaseModel):
user: SponsorsUser
class SponsorsResponse(BaseModel):
data: SponsorsResponseData
class Settings(BaseSettings):
sponsors_token: SecretStr
pr_token: SecretStr
github_repository: str
httpx_timeout: int = 30
def get_graphql_response(
*,
settings: Settings,
query: str,
after: str | None = None,
) -> dict[str, Any]:
headers = {"Authorization": f"token {settings.sponsors_token.get_secret_value()}"}
variables = {"after": after}
response = httpx.post(
github_graphql_url,
headers=headers,
timeout=settings.httpx_timeout,
json={"query": query, "variables": variables, "operationName": "Q"},
)
if response.status_code != 200:
logging.error(f"Response was not 200, after: {after}")
logging.error(response.text)
raise RuntimeError(response.text)
data = response.json()
if "errors" in data:
logging.error(f"Errors in response, after: {after}")
logging.error(data["errors"])
logging.error(response.text)
raise RuntimeError(response.text)
return data
def get_graphql_sponsor_edges(
*, settings: Settings, after: str | None = None
) -> list[SponsorshipAsMaintainerEdge]:
data = get_graphql_response(settings=settings, query=sponsors_query, after=after)
graphql_response = SponsorsResponse.model_validate(data)
return graphql_response.data.user.sponsorshipsAsMaintainer.edges
def get_individual_sponsors(
settings: Settings,
) -> defaultdict[float, dict[str, SponsorEntity]]:
nodes: list[SponsorshipAsMaintainerNode] = []
edges = get_graphql_sponsor_edges(settings=settings)
while edges:
for edge in edges:
nodes.append(edge.node)
last_edge = edges[-1]
edges = get_graphql_sponsor_edges(settings=settings, after=last_edge.cursor)
tiers: defaultdict[float, dict[str, SponsorEntity]] = defaultdict(dict)
for node in nodes:
tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = (
node.sponsorEntity
)
return tiers
def update_content(*, content_path: Path, new_content: Any) -> bool:
old_content = content_path.read_text(encoding="utf-8")
new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True)
if old_content == new_content:
logging.info(f"The content hasn't changed for {content_path}")
return False
content_path.write_text(new_content, encoding="utf-8")
logging.info(f"Updated {content_path}")
return True
def main() -> None:
logging.basicConfig(level=logging.INFO)
settings = Settings()
logging.info(f"Using config: {settings.model_dump_json()}")
g = Github(settings.pr_token.get_secret_value())
repo = g.get_repo(settings.github_repository)
tiers = get_individual_sponsors(settings=settings)
keys = list(tiers.keys())
keys.sort(reverse=True)
sponsors = []
for key in keys:
sponsor_group = []
for login, sponsor in tiers[key].items():
sponsor_group.append(
{"login": login, "avatarUrl": sponsor.avatarUrl, "url": sponsor.url}
)
sponsors.append(sponsor_group)
github_sponsors = {
"sponsors": sponsors,
}
# For local development
# github_sponsors_path = Path("../docs/en/data/github_sponsors.yml")
github_sponsors_path = Path("./docs/en/data/github_sponsors.yml")
updated = update_content(
content_path=github_sponsors_path, new_content=github_sponsors
)
if not updated:
logging.info("The data hasn't changed, finishing.")
return
logging.info("Setting up GitHub Actions git user")
subprocess.run(["git", "config", "user.name", "github-actions[bot]"], check=True)
subprocess.run(
["git", "config", "user.email", "github-actions[bot]@users.noreply.github.com"],
check=True,
)
branch_name = f"fastapi-people-sponsors-{secrets.token_hex(4)}"
logging.info(f"Creating a new branch {branch_name}")
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
logging.info("Adding updated file")
subprocess.run(
[
"git",
"add",
str(github_sponsors_path),
],
check=True,
)
logging.info("Committing updated file")
message = "👥 Update FastAPI People - Sponsors"
subprocess.run(["git", "commit", "-m", message], check=True)
logging.info("Pushing branch")
subprocess.run(["git", "push", "origin", branch_name], check=True)
logging.info("Creating PR")
pr = repo.create_pull(title=message, body=message, base="master", head=branch_name)
logging.info(f"Created PR: {pr.number}")
logging.info("Finished")
if __name__ == "__main__":
main()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/label_approved.py | scripts/label_approved.py | import logging
from typing import Literal
from github import Github
from github.PullRequestReview import PullRequestReview
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings
class LabelSettings(BaseModel):
await_label: str | None = None
number: int
default_config = {"approved-2": LabelSettings(await_label="awaiting-review", number=2)}
class Settings(BaseSettings):
github_repository: str
token: SecretStr
debug: bool | None = False
config: dict[str, LabelSettings] | Literal[""] = default_config
settings = Settings()
if settings.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
logging.debug(f"Using config: {settings.model_dump_json()}")
g = Github(settings.token.get_secret_value())
repo = g.get_repo(settings.github_repository)
for pr in repo.get_pulls(state="open"):
logging.info(f"Checking PR: #{pr.number}")
pr_labels = list(pr.get_labels())
pr_label_by_name = {label.name: label for label in pr_labels}
reviews = list(pr.get_reviews())
review_by_user: dict[str, PullRequestReview] = {}
for review in reviews:
if review.user.login in review_by_user:
stored_review = review_by_user[review.user.login]
if review.submitted_at >= stored_review.submitted_at:
review_by_user[review.user.login] = review
else:
review_by_user[review.user.login] = review
approved_reviews = [
review for review in review_by_user.values() if review.state == "APPROVED"
]
config = settings.config or default_config
for approved_label, conf in config.items():
logging.debug(f"Processing config: {conf.model_dump_json()}")
if conf.await_label is None or (conf.await_label in pr_label_by_name):
logging.debug(f"Processable PR: {pr.number}")
if len(approved_reviews) >= conf.number:
logging.info(f"Adding label to PR: {pr.number}")
pr.add_to_labels(approved_label)
if conf.await_label:
logging.info(f"Removing label from PR: {pr.number}")
pr.remove_from_labels(conf.await_label)
logging.info("Finished")
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/notify_translations.py | scripts/notify_translations.py | import logging
import random
import sys
import time
from pathlib import Path
from typing import Any, Union, cast
import httpx
from github import Github
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings
awaiting_label = "awaiting-review"
lang_all_label = "lang-all"
approved_label = "approved-1"
github_graphql_url = "https://api.github.com/graphql"
questions_translations_category_id = "DIC_kwDOCZduT84CT5P9"
all_discussions_query = """
query Q($category_id: ID) {
repository(name: "fastapi", owner: "fastapi") {
discussions(categoryId: $category_id, first: 100) {
nodes {
title
id
number
labels(first: 10) {
edges {
node {
id
name
}
}
}
}
}
}
}
"""
translation_discussion_query = """
query Q($after: String, $discussion_number: Int!) {
repository(name: "fastapi", owner: "fastapi") {
discussion(number: $discussion_number) {
comments(first: 100, after: $after) {
edges {
cursor
node {
id
url
body
}
}
}
}
}
}
"""
add_comment_mutation = """
mutation Q($discussion_id: ID!, $body: String!) {
addDiscussionComment(input: {discussionId: $discussion_id, body: $body}) {
comment {
id
url
body
}
}
}
"""
update_comment_mutation = """
mutation Q($comment_id: ID!, $body: String!) {
updateDiscussionComment(input: {commentId: $comment_id, body: $body}) {
comment {
id
url
body
}
}
}
"""
class Comment(BaseModel):
id: str
url: str
body: str
class UpdateDiscussionComment(BaseModel):
comment: Comment
class UpdateCommentData(BaseModel):
updateDiscussionComment: UpdateDiscussionComment
class UpdateCommentResponse(BaseModel):
data: UpdateCommentData
class AddDiscussionComment(BaseModel):
comment: Comment
class AddCommentData(BaseModel):
addDiscussionComment: AddDiscussionComment
class AddCommentResponse(BaseModel):
data: AddCommentData
class CommentsEdge(BaseModel):
node: Comment
cursor: str
class Comments(BaseModel):
edges: list[CommentsEdge]
class CommentsDiscussion(BaseModel):
comments: Comments
class CommentsRepository(BaseModel):
discussion: CommentsDiscussion
class CommentsData(BaseModel):
repository: CommentsRepository
class CommentsResponse(BaseModel):
data: CommentsData
class AllDiscussionsLabelNode(BaseModel):
id: str
name: str
class AllDiscussionsLabelsEdge(BaseModel):
node: AllDiscussionsLabelNode
class AllDiscussionsDiscussionLabels(BaseModel):
edges: list[AllDiscussionsLabelsEdge]
class AllDiscussionsDiscussionNode(BaseModel):
title: str
id: str
number: int
labels: AllDiscussionsDiscussionLabels
class AllDiscussionsDiscussions(BaseModel):
nodes: list[AllDiscussionsDiscussionNode]
class AllDiscussionsRepository(BaseModel):
discussions: AllDiscussionsDiscussions
class AllDiscussionsData(BaseModel):
repository: AllDiscussionsRepository
class AllDiscussionsResponse(BaseModel):
data: AllDiscussionsData
class Settings(BaseSettings):
model_config = {"env_ignore_empty": True}
github_repository: str
github_token: SecretStr
github_event_path: Path
github_event_name: Union[str, None] = None
httpx_timeout: int = 30
debug: Union[bool, None] = False
number: int | None = None
class PartialGitHubEventIssue(BaseModel):
number: int | None = None
class PartialGitHubEvent(BaseModel):
pull_request: PartialGitHubEventIssue | None = None
def get_graphql_response(
*,
settings: Settings,
query: str,
after: Union[str, None] = None,
category_id: Union[str, None] = None,
discussion_number: Union[int, None] = None,
discussion_id: Union[str, None] = None,
comment_id: Union[str, None] = None,
body: Union[str, None] = None,
) -> dict[str, Any]:
headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"}
variables = {
"after": after,
"category_id": category_id,
"discussion_number": discussion_number,
"discussion_id": discussion_id,
"comment_id": comment_id,
"body": body,
}
response = httpx.post(
github_graphql_url,
headers=headers,
timeout=settings.httpx_timeout,
json={"query": query, "variables": variables, "operationName": "Q"},
)
if response.status_code != 200:
logging.error(
f"Response was not 200, after: {after}, category_id: {category_id}"
)
logging.error(response.text)
raise RuntimeError(response.text)
data = response.json()
if "errors" in data:
logging.error(f"Errors in response, after: {after}, category_id: {category_id}")
logging.error(data["errors"])
logging.error(response.text)
raise RuntimeError(response.text)
return cast(dict[str, Any], data)
def get_graphql_translation_discussions(
*, settings: Settings
) -> list[AllDiscussionsDiscussionNode]:
data = get_graphql_response(
settings=settings,
query=all_discussions_query,
category_id=questions_translations_category_id,
)
graphql_response = AllDiscussionsResponse.model_validate(data)
return graphql_response.data.repository.discussions.nodes
def get_graphql_translation_discussion_comments_edges(
*, settings: Settings, discussion_number: int, after: Union[str, None] = None
) -> list[CommentsEdge]:
data = get_graphql_response(
settings=settings,
query=translation_discussion_query,
discussion_number=discussion_number,
after=after,
)
graphql_response = CommentsResponse.model_validate(data)
return graphql_response.data.repository.discussion.comments.edges
def get_graphql_translation_discussion_comments(
*, settings: Settings, discussion_number: int
) -> list[Comment]:
comment_nodes: list[Comment] = []
discussion_edges = get_graphql_translation_discussion_comments_edges(
settings=settings, discussion_number=discussion_number
)
while discussion_edges:
for discussion_edge in discussion_edges:
comment_nodes.append(discussion_edge.node)
last_edge = discussion_edges[-1]
discussion_edges = get_graphql_translation_discussion_comments_edges(
settings=settings,
discussion_number=discussion_number,
after=last_edge.cursor,
)
return comment_nodes
def create_comment(*, settings: Settings, discussion_id: str, body: str) -> Comment:
data = get_graphql_response(
settings=settings,
query=add_comment_mutation,
discussion_id=discussion_id,
body=body,
)
response = AddCommentResponse.model_validate(data)
return response.data.addDiscussionComment.comment
def update_comment(*, settings: Settings, comment_id: str, body: str) -> Comment:
data = get_graphql_response(
settings=settings,
query=update_comment_mutation,
comment_id=comment_id,
body=body,
)
response = UpdateCommentResponse.model_validate(data)
return response.data.updateDiscussionComment.comment
def main() -> None:
settings = Settings()
if settings.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
logging.debug(f"Using config: {settings.model_dump_json()}")
g = Github(settings.github_token.get_secret_value())
repo = g.get_repo(settings.github_repository)
if not settings.github_event_path.is_file():
raise RuntimeError(
f"No github event file available at: {settings.github_event_path}"
)
contents = settings.github_event_path.read_text()
github_event = PartialGitHubEvent.model_validate_json(contents)
logging.info(f"Using GitHub event: {github_event}")
number = (
github_event.pull_request and github_event.pull_request.number
) or settings.number
if number is None:
raise RuntimeError("No PR number available")
# Avoid race conditions with multiple labels
sleep_time = random.random() * 10 # random number between 0 and 10 seconds
logging.info(
f"Sleeping for {sleep_time} seconds to avoid "
"race conditions and multiple comments"
)
time.sleep(sleep_time)
# Get PR
logging.debug(f"Processing PR: #{number}")
pr = repo.get_pull(number)
label_strs = {label.name for label in pr.get_labels()}
langs = []
for label in label_strs:
if label.startswith("lang-") and not label == lang_all_label:
langs.append(label[5:])
logging.info(f"PR #{pr.number} has labels: {label_strs}")
if not langs or lang_all_label not in label_strs:
logging.info(f"PR #{pr.number} doesn't seem to be a translation PR, skipping")
sys.exit(0)
# Generate translation map, lang ID to discussion
discussions = get_graphql_translation_discussions(settings=settings)
lang_to_discussion_map: dict[str, AllDiscussionsDiscussionNode] = {}
for discussion in discussions:
for edge in discussion.labels.edges:
label = edge.node.name
if label.startswith("lang-") and not label == lang_all_label:
lang = label[5:]
lang_to_discussion_map[lang] = discussion
logging.debug(f"Using translations map: {lang_to_discussion_map}")
# Messages to create or check
new_translation_message = f"Good news everyone! 😉 There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}. 🎉 This requires 2 approvals from native speakers to be merged. 🤓"
done_translation_message = f"~There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}~ Good job! This is done. 🍰☕"
# Normally only one language, but still
for lang in langs:
if lang not in lang_to_discussion_map:
log_message = f"Could not find discussion for language: {lang}"
logging.error(log_message)
raise RuntimeError(log_message)
discussion = lang_to_discussion_map[lang]
logging.info(
f"Found a translation discussion for language: {lang} in discussion: #{discussion.number}"
)
already_notified_comment: Union[Comment, None] = None
already_done_comment: Union[Comment, None] = None
logging.info(
f"Checking current comments in discussion: #{discussion.number} to see if already notified about this PR: #{pr.number}"
)
comments = get_graphql_translation_discussion_comments(
settings=settings, discussion_number=discussion.number
)
for comment in comments:
if new_translation_message in comment.body:
already_notified_comment = comment
elif done_translation_message in comment.body:
already_done_comment = comment
logging.info(
f"Already notified comment: {already_notified_comment}, already done comment: {already_done_comment}"
)
if pr.state == "open" and awaiting_label in label_strs:
logging.info(
f"This PR seems to be a language translation and awaiting reviews: #{pr.number}"
)
if already_notified_comment:
logging.info(
f"This PR #{pr.number} was already notified in comment: {already_notified_comment.url}"
)
else:
logging.info(
f"Writing notification comment about PR #{pr.number} in Discussion: #{discussion.number}"
)
comment = create_comment(
settings=settings,
discussion_id=discussion.id,
body=new_translation_message,
)
logging.info(f"Notified in comment: {comment.url}")
elif pr.state == "closed" or approved_label in label_strs:
logging.info(f"Already approved or closed PR #{pr.number}")
if already_done_comment:
logging.info(
f"This PR #{pr.number} was already marked as done in comment: {already_done_comment.url}"
)
elif already_notified_comment:
updated_comment = update_comment(
settings=settings,
comment_id=already_notified_comment.id,
body=done_translation_message,
)
logging.info(f"Marked as done in comment: {updated_comment.url}")
else:
logging.info(
f"There doesn't seem to be anything to be done about PR #{pr.number}"
)
logging.info("Finished")
if __name__ == "__main__":
main()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/people.py | scripts/people.py | import logging
import secrets
import subprocess
import time
from collections import Counter
from collections.abc import Container
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Union
import httpx
import yaml
from github import Github
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings
github_graphql_url = "https://api.github.com/graphql"
questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0"
discussions_query = """
query Q($after: String, $category_id: ID) {
repository(name: "fastapi", owner: "fastapi") {
discussions(first: 100, after: $after, categoryId: $category_id) {
edges {
cursor
node {
number
author {
login
avatarUrl
url
}
createdAt
comments(first: 50) {
totalCount
nodes {
createdAt
author {
login
avatarUrl
url
}
isAnswer
replies(first: 10) {
totalCount
nodes {
createdAt
author {
login
avatarUrl
url
}
}
}
}
}
}
}
}
}
}
"""
class Author(BaseModel):
login: str
avatarUrl: str | None = None
url: str | None = None
class CommentsNode(BaseModel):
createdAt: datetime
author: Union[Author, None] = None
class Replies(BaseModel):
totalCount: int
nodes: list[CommentsNode]
class DiscussionsCommentsNode(CommentsNode):
replies: Replies
class DiscussionsComments(BaseModel):
totalCount: int
nodes: list[DiscussionsCommentsNode]
class DiscussionsNode(BaseModel):
number: int
author: Union[Author, None] = None
title: str | None = None
createdAt: datetime
comments: DiscussionsComments
class DiscussionsEdge(BaseModel):
cursor: str
node: DiscussionsNode
class Discussions(BaseModel):
edges: list[DiscussionsEdge]
class DiscussionsRepository(BaseModel):
discussions: Discussions
class DiscussionsResponseData(BaseModel):
repository: DiscussionsRepository
class DiscussionsResponse(BaseModel):
data: DiscussionsResponseData
class Settings(BaseSettings):
github_token: SecretStr
github_repository: str
httpx_timeout: int = 30
sleep_interval: int = 5
def get_graphql_response(
*,
settings: Settings,
query: str,
after: Union[str, None] = None,
category_id: Union[str, None] = None,
) -> dict[str, Any]:
headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"}
variables = {"after": after, "category_id": category_id}
response = httpx.post(
github_graphql_url,
headers=headers,
timeout=settings.httpx_timeout,
json={"query": query, "variables": variables, "operationName": "Q"},
)
if response.status_code != 200:
logging.error(
f"Response was not 200, after: {after}, category_id: {category_id}"
)
logging.error(response.text)
raise RuntimeError(response.text)
data = response.json()
if "errors" in data:
logging.error(f"Errors in response, after: {after}, category_id: {category_id}")
logging.error(data["errors"])
logging.error(response.text)
raise RuntimeError(response.text)
return data
def get_graphql_question_discussion_edges(
*,
settings: Settings,
after: Union[str, None] = None,
) -> list[DiscussionsEdge]:
data = get_graphql_response(
settings=settings,
query=discussions_query,
after=after,
category_id=questions_category_id,
)
graphql_response = DiscussionsResponse.model_validate(data)
return graphql_response.data.repository.discussions.edges
class DiscussionExpertsResults(BaseModel):
commenters: Counter[str]
last_month_commenters: Counter[str]
three_months_commenters: Counter[str]
six_months_commenters: Counter[str]
one_year_commenters: Counter[str]
authors: dict[str, Author]
def get_discussion_nodes(settings: Settings) -> list[DiscussionsNode]:
discussion_nodes: list[DiscussionsNode] = []
discussion_edges = get_graphql_question_discussion_edges(settings=settings)
while discussion_edges:
for discussion_edge in discussion_edges:
discussion_nodes.append(discussion_edge.node)
last_edge = discussion_edges[-1]
# Handle GitHub secondary rate limits, requests per minute
time.sleep(settings.sleep_interval)
discussion_edges = get_graphql_question_discussion_edges(
settings=settings, after=last_edge.cursor
)
return discussion_nodes
def get_discussions_experts(
discussion_nodes: list[DiscussionsNode],
) -> DiscussionExpertsResults:
commenters = Counter[str]()
last_month_commenters = Counter[str]()
three_months_commenters = Counter[str]()
six_months_commenters = Counter[str]()
one_year_commenters = Counter[str]()
authors: dict[str, Author] = {}
now = datetime.now(tz=timezone.utc)
one_month_ago = now - timedelta(days=30)
three_months_ago = now - timedelta(days=90)
six_months_ago = now - timedelta(days=180)
one_year_ago = now - timedelta(days=365)
for discussion in discussion_nodes:
discussion_author_name = None
if discussion.author:
authors[discussion.author.login] = discussion.author
discussion_author_name = discussion.author.login
discussion_commentors: dict[str, datetime] = {}
for comment in discussion.comments.nodes:
if comment.author:
authors[comment.author.login] = comment.author
if comment.author.login != discussion_author_name:
author_time = discussion_commentors.get(
comment.author.login, comment.createdAt
)
discussion_commentors[comment.author.login] = max(
author_time, comment.createdAt
)
for reply in comment.replies.nodes:
if reply.author:
authors[reply.author.login] = reply.author
if reply.author.login != discussion_author_name:
author_time = discussion_commentors.get(
reply.author.login, reply.createdAt
)
discussion_commentors[reply.author.login] = max(
author_time, reply.createdAt
)
for author_name, author_time in discussion_commentors.items():
commenters[author_name] += 1
if author_time > one_month_ago:
last_month_commenters[author_name] += 1
if author_time > three_months_ago:
three_months_commenters[author_name] += 1
if author_time > six_months_ago:
six_months_commenters[author_name] += 1
if author_time > one_year_ago:
one_year_commenters[author_name] += 1
discussion_experts_results = DiscussionExpertsResults(
authors=authors,
commenters=commenters,
last_month_commenters=last_month_commenters,
three_months_commenters=three_months_commenters,
six_months_commenters=six_months_commenters,
one_year_commenters=one_year_commenters,
)
return discussion_experts_results
def get_top_users(
*,
counter: Counter[str],
authors: dict[str, Author],
skip_users: Container[str],
min_count: int = 2,
) -> list[dict[str, Any]]:
users: list[dict[str, Any]] = []
for commenter, count in counter.most_common(50):
if commenter in skip_users:
continue
if count >= min_count:
author = authors[commenter]
users.append(
{
"login": commenter,
"count": count,
"avatarUrl": author.avatarUrl,
"url": author.url,
}
)
return users
def get_users_to_write(
*,
counter: Counter[str],
authors: dict[str, Author],
min_count: int = 2,
) -> list[dict[str, Any]]:
users: dict[str, Any] = {}
users_list: list[dict[str, Any]] = []
for user, count in counter.most_common(60):
if count >= min_count:
author = authors[user]
user_data = {
"login": user,
"count": count,
"avatarUrl": author.avatarUrl,
"url": author.url,
}
users[user] = user_data
users_list.append(user_data)
return users_list
def update_content(*, content_path: Path, new_content: Any) -> bool:
old_content = content_path.read_text(encoding="utf-8")
new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True)
if old_content == new_content:
logging.info(f"The content hasn't changed for {content_path}")
return False
content_path.write_text(new_content, encoding="utf-8")
logging.info(f"Updated {content_path}")
return True
def main() -> None:
logging.basicConfig(level=logging.INFO)
settings = Settings()
logging.info(f"Using config: {settings.model_dump_json()}")
g = Github(settings.github_token.get_secret_value())
repo = g.get_repo(settings.github_repository)
discussion_nodes = get_discussion_nodes(settings=settings)
experts_results = get_discussions_experts(discussion_nodes=discussion_nodes)
authors = experts_results.authors
maintainers_logins = {"tiangolo"}
maintainers = []
for login in maintainers_logins:
user = authors[login]
maintainers.append(
{
"login": login,
"answers": experts_results.commenters[login],
"avatarUrl": user.avatarUrl,
"url": user.url,
}
)
experts = get_users_to_write(
counter=experts_results.commenters,
authors=authors,
)
last_month_experts = get_users_to_write(
counter=experts_results.last_month_commenters,
authors=authors,
)
three_months_experts = get_users_to_write(
counter=experts_results.three_months_commenters,
authors=authors,
)
six_months_experts = get_users_to_write(
counter=experts_results.six_months_commenters,
authors=authors,
)
one_year_experts = get_users_to_write(
counter=experts_results.one_year_commenters,
authors=authors,
)
people = {
"maintainers": maintainers,
"experts": experts,
"last_month_experts": last_month_experts,
"three_months_experts": three_months_experts,
"six_months_experts": six_months_experts,
"one_year_experts": one_year_experts,
}
# For local development
# people_path = Path("../docs/en/data/people.yml")
people_path = Path("./docs/en/data/people.yml")
updated = update_content(content_path=people_path, new_content=people)
if not updated:
logging.info("The data hasn't changed, finishing.")
return
logging.info("Setting up GitHub Actions git user")
subprocess.run(["git", "config", "user.name", "github-actions[bot]"], check=True)
subprocess.run(
["git", "config", "user.email", "github-actions[bot]@users.noreply.github.com"],
check=True,
)
branch_name = f"fastapi-people-experts-{secrets.token_hex(4)}"
logging.info(f"Creating a new branch {branch_name}")
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
logging.info("Adding updated file")
subprocess.run(["git", "add", str(people_path)], check=True)
logging.info("Committing updated file")
message = "👥 Update FastAPI People - Experts"
subprocess.run(["git", "commit", "-m", message], check=True)
logging.info("Pushing branch")
subprocess.run(["git", "push", "origin", branch_name], check=True)
logging.info("Creating PR")
pr = repo.create_pull(title=message, body=message, base="master", head=branch_name)
logging.info(f"Created PR: {pr.number}")
logging.info("Finished")
if __name__ == "__main__":
main()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/docs.py | scripts/docs.py | import json
import logging
import os
import re
import shutil
import subprocess
from html.parser import HTMLParser
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing import Pool
from pathlib import Path
from typing import Any, Optional, Union
import mkdocs.utils
import typer
import yaml
from jinja2 import Template
from ruff.__main__ import find_ruff_bin
from slugify import slugify as py_slugify
logging.basicConfig(level=logging.INFO)
SUPPORTED_LANGS = {
"en",
"de",
"es",
"pt",
"ru",
}
app = typer.Typer()
mkdocs_name = "mkdocs.yml"
missing_translation_snippet = """
{!../../docs/missing-translation.md!}
"""
non_translated_sections = (
f"reference{os.sep}",
"release-notes.md",
"fastapi-people.md",
"external-links.md",
"newsletter.md",
"management-tasks.md",
"management.md",
"contributing.md",
)
docs_path = Path("docs")
en_docs_path = Path("docs/en")
en_config_path: Path = en_docs_path / mkdocs_name
site_path = Path("site").absolute()
build_site_path = Path("site_build").absolute()
header_pattern = re.compile(r"^(#{1,6}) (.+?)(?:\s*\{\s*(#.*)\s*\})?\s*$")
header_with_permalink_pattern = re.compile(r"^(#{1,6}) (.+?)(\s*\{\s*#.*\s*\})\s*$")
code_block3_pattern = re.compile(r"^\s*```")
code_block4_pattern = re.compile(r"^\s*````")
class VisibleTextExtractor(HTMLParser):
"""Extract visible text from a string with HTML tags."""
def __init__(self):
super().__init__()
self.text_parts = []
def handle_data(self, data):
self.text_parts.append(data)
def extract_visible_text(self, html: str) -> str:
self.reset()
self.text_parts = []
self.feed(html)
return "".join(self.text_parts).strip()
def slugify(text: str) -> str:
return py_slugify(
text,
replacements=[
("`", ""), # `dict`s -> dicts
("'s", "s"), # it's -> its
("'t", "t"), # don't -> dont
("**", ""), # **FastAPI**s -> FastAPIs
],
)
def get_en_config() -> dict[str, Any]:
return mkdocs.utils.yaml_load(en_config_path.read_text(encoding="utf-8"))
def get_lang_paths() -> list[Path]:
return sorted(docs_path.iterdir())
def lang_callback(lang: Optional[str]) -> Union[str, None]:
if lang is None:
return None
lang = lang.lower()
return lang
def complete_existing_lang(incomplete: str):
lang_path: Path
for lang_path in get_lang_paths():
if lang_path.is_dir() and lang_path.name.startswith(incomplete):
yield lang_path.name
@app.callback()
def callback() -> None:
# For MacOS with Cairo
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/opt/homebrew/lib"
@app.command()
def new_lang(lang: str = typer.Argument(..., callback=lang_callback)):
"""
Generate a new docs translation directory for the language LANG.
"""
new_path: Path = Path("docs") / lang
if new_path.exists():
typer.echo(f"The language was already created: {lang}")
raise typer.Abort()
new_path.mkdir()
new_config_path: Path = Path(new_path) / mkdocs_name
new_config_path.write_text("INHERIT: ../en/mkdocs.yml\n", encoding="utf-8")
new_config_docs_path: Path = new_path / "docs"
new_config_docs_path.mkdir()
en_index_path: Path = en_docs_path / "docs" / "index.md"
new_index_path: Path = new_config_docs_path / "index.md"
en_index_content = en_index_path.read_text(encoding="utf-8")
new_index_content = f"{missing_translation_snippet}\n\n{en_index_content}"
new_index_path.write_text(new_index_content, encoding="utf-8")
typer.secho(f"Successfully initialized: {new_path}", color=typer.colors.GREEN)
update_languages()
@app.command()
def build_lang(
lang: str = typer.Argument(
..., callback=lang_callback, autocompletion=complete_existing_lang
),
) -> None:
"""
Build the docs for a language.
"""
lang_path: Path = Path("docs") / lang
if not lang_path.is_dir():
typer.echo(f"The language translation doesn't seem to exist yet: {lang}")
raise typer.Abort()
typer.echo(f"Building docs for: {lang}")
build_site_dist_path = build_site_path / lang
if lang == "en":
dist_path = site_path
# Don't remove en dist_path as it might already contain other languages.
# When running build_all(), that function already removes site_path.
# All this is only relevant locally, on GitHub Actions all this is done through
# artifacts and multiple workflows, so it doesn't matter if directories are
# removed or not.
else:
dist_path = site_path / lang
shutil.rmtree(dist_path, ignore_errors=True)
current_dir = os.getcwd()
os.chdir(lang_path)
shutil.rmtree(build_site_dist_path, ignore_errors=True)
subprocess.run(["mkdocs", "build", "--site-dir", build_site_dist_path], check=True)
shutil.copytree(build_site_dist_path, dist_path, dirs_exist_ok=True)
os.chdir(current_dir)
typer.secho(f"Successfully built docs for: {lang}", color=typer.colors.GREEN)
index_sponsors_template = """
### Keystone Sponsor
{% for sponsor in sponsors.keystone -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
{% endfor %}
### Gold and Silver Sponsors
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
{% endfor %}
"""
def remove_header_permalinks(content: str):
lines: list[str] = []
for line in content.split("\n"):
match = header_with_permalink_pattern.match(line)
if match:
hashes, title, *_ = match.groups()
line = f"{hashes} {title}"
lines.append(line)
return "\n".join(lines)
def generate_readme_content() -> str:
en_index = en_docs_path / "docs" / "index.md"
content = en_index.read_text("utf-8")
content = remove_header_permalinks(content) # remove permalinks from headers
match_pre = re.search(r"</style>\n\n", content)
match_start = re.search(r"<!-- sponsors -->", content)
match_end = re.search(r"<!-- /sponsors -->", content)
sponsors_data_path = en_docs_path / "data" / "sponsors.yml"
sponsors = mkdocs.utils.yaml_load(sponsors_data_path.read_text(encoding="utf-8"))
if not (match_start and match_end):
raise RuntimeError("Couldn't auto-generate sponsors section")
if not match_pre:
raise RuntimeError("Couldn't find pre section (<style>) in index.md")
frontmatter_end = match_pre.end()
pre_end = match_start.end()
post_start = match_end.start()
template = Template(index_sponsors_template)
message = template.render(sponsors=sponsors)
pre_content = content[frontmatter_end:pre_end]
post_content = content[post_start:]
new_content = pre_content + message + post_content
# Remove content between <!-- only-mkdocs --> and <!-- /only-mkdocs -->
new_content = re.sub(
r"<!-- only-mkdocs -->.*?<!-- /only-mkdocs -->",
"",
new_content,
flags=re.DOTALL,
)
return new_content
@app.command()
def generate_readme() -> None:
"""
Generate README.md content from main index.md
"""
readme_path = Path("README.md")
old_content = readme_path.read_text()
new_content = generate_readme_content()
if new_content != old_content:
print("README.md outdated from the latest index.md")
print("Updating README.md")
readme_path.write_text(new_content, encoding="utf-8")
raise typer.Exit(1)
print("README.md is up to date ✅")
@app.command()
def build_all() -> None:
"""
Build mkdocs site for en, and then build each language inside, end result is located
at directory ./site/ with each language inside.
"""
update_languages()
shutil.rmtree(site_path, ignore_errors=True)
langs = [
lang.name
for lang in get_lang_paths()
if (lang.is_dir() and lang.name in SUPPORTED_LANGS)
]
cpu_count = os.cpu_count() or 1
process_pool_size = cpu_count * 4
typer.echo(f"Using process pool size: {process_pool_size}")
with Pool(process_pool_size) as p:
p.map(build_lang, langs)
@app.command()
def update_languages() -> None:
"""
Update the mkdocs.yml file Languages section including all the available languages.
"""
old_config = get_en_config()
updated_config = get_updated_config_content()
if old_config != updated_config:
print("docs/en/mkdocs.yml outdated")
print("Updating docs/en/mkdocs.yml")
en_config_path.write_text(
yaml.dump(updated_config, sort_keys=False, width=200, allow_unicode=True),
encoding="utf-8",
)
raise typer.Exit(1)
print("docs/en/mkdocs.yml is up to date ✅")
@app.command()
def serve() -> None:
"""
A quick server to preview a built site with translations.
For development, prefer the command live (or just mkdocs serve).
This is here only to preview a site with translations already built.
Make sure you run the build-all command first.
"""
typer.echo("Warning: this is a very simple server.")
typer.echo("For development, use the command live instead.")
typer.echo("This is here only to preview a site with translations already built.")
typer.echo("Make sure you run the build-all command first.")
os.chdir("site")
server_address = ("", 8008)
server = HTTPServer(server_address, SimpleHTTPRequestHandler)
typer.echo("Serving at: http://127.0.0.1:8008")
server.serve_forever()
@app.command()
def live(
lang: str = typer.Argument(
None, callback=lang_callback, autocompletion=complete_existing_lang
),
dirty: bool = False,
) -> None:
"""
Serve with livereload a docs site for a specific language.
This only shows the actual translated files, not the placeholders created with
build-all.
Takes an optional LANG argument with the name of the language to serve, by default
en.
"""
# Enable line numbers during local development to make it easier to highlight
if lang is None:
lang = "en"
lang_path: Path = docs_path / lang
# Enable line numbers during local development to make it easier to highlight
args = ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008"]
if dirty:
args.append("--dirty")
subprocess.run(
args, env={**os.environ, "LINENUMS": "true"}, cwd=lang_path, check=True
)
def get_updated_config_content() -> dict[str, Any]:
config = get_en_config()
languages = [{"en": "/"}]
new_alternate: list[dict[str, str]] = []
# Language names sourced from https://quickref.me/iso-639-1
# Contributors may wish to update or change these, e.g. to fix capitalization.
language_names_path = Path(__file__).parent / "../docs/language_names.yml"
local_language_names: dict[str, str] = mkdocs.utils.yaml_load(
language_names_path.read_text(encoding="utf-8")
)
for lang_path in get_lang_paths():
if lang_path.name in {"en", "em"} or not lang_path.is_dir():
continue
if lang_path.name not in SUPPORTED_LANGS:
# Skip languages that are not yet ready
continue
code = lang_path.name
languages.append({code: f"/{code}/"})
for lang_dict in languages:
code = list(lang_dict.keys())[0]
url = lang_dict[code]
if code not in local_language_names:
print(
f"Missing language name for: {code}, "
"update it in docs/language_names.yml"
)
raise typer.Abort()
use_name = f"{code} - {local_language_names[code]}"
new_alternate.append({"link": url, "name": use_name})
config["extra"]["alternate"] = new_alternate
return config
@app.command()
def ensure_non_translated() -> None:
"""
Ensure there are no files in the non translatable pages.
"""
print("Ensuring no non translated pages")
lang_paths = get_lang_paths()
error_paths = []
for lang in lang_paths:
if lang.name == "en":
continue
for non_translatable in non_translated_sections:
non_translatable_path = lang / "docs" / non_translatable
if non_translatable_path.exists():
error_paths.append(non_translatable_path)
if error_paths:
print("Non-translated pages found, removing them:")
for error_path in error_paths:
print(error_path)
if error_path.is_file():
error_path.unlink()
else:
shutil.rmtree(error_path)
raise typer.Exit(1)
print("No non-translated pages found ✅")
@app.command()
def langs_json():
langs = []
for lang_path in get_lang_paths():
if lang_path.is_dir() and lang_path.name in SUPPORTED_LANGS:
langs.append(lang_path.name)
print(json.dumps(langs))
@app.command()
def generate_docs_src_versions_for_file(file_path: Path) -> None:
target_versions = ["py39", "py310"]
base_content = file_path.read_text(encoding="utf-8")
previous_content = {base_content}
for target_version in target_versions:
version_result = subprocess.run(
[
find_ruff_bin(),
"check",
"--target-version",
target_version,
"--fix",
"--unsafe-fixes",
"-",
],
input=base_content.encode("utf-8"),
capture_output=True,
)
content_target = version_result.stdout.decode("utf-8")
format_result = subprocess.run(
[find_ruff_bin(), "format", "-"],
input=content_target.encode("utf-8"),
capture_output=True,
)
content_format = format_result.stdout.decode("utf-8")
if content_format in previous_content:
continue
previous_content.add(content_format)
version_file = file_path.with_name(
file_path.name.replace(".py", f"_{target_version}.py")
)
logging.info(f"Writing to {version_file}")
version_file.write_text(content_format, encoding="utf-8")
@app.command()
def add_permalinks_page(path: Path, update_existing: bool = False):
"""
Add or update header permalinks in specific page of En docs.
"""
if not path.is_relative_to(en_docs_path / "docs"):
raise RuntimeError(f"Path must be inside {en_docs_path}")
rel_path = path.relative_to(en_docs_path / "docs")
# Skip excluded sections
if str(rel_path).startswith(non_translated_sections):
return
visible_text_extractor = VisibleTextExtractor()
updated_lines = []
in_code_block3 = False
in_code_block4 = False
permalinks = set()
with path.open("r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
# Handle codeblocks start and end
if not (in_code_block3 or in_code_block4):
if code_block4_pattern.match(line):
in_code_block4 = True
elif code_block3_pattern.match(line):
in_code_block3 = True
else:
if in_code_block4 and code_block4_pattern.match(line):
in_code_block4 = False
elif in_code_block3 and code_block3_pattern.match(line):
in_code_block3 = False
# Process Headers only outside codeblocks
if not (in_code_block3 or in_code_block4):
match = header_pattern.match(line)
if match:
hashes, title, _permalink = match.groups()
if (not _permalink) or update_existing:
slug = slugify(visible_text_extractor.extract_visible_text(title))
if slug in permalinks:
# If the slug is already used, append a number to make it unique
count = 1
original_slug = slug
while slug in permalinks:
slug = f"{original_slug}_{count}"
count += 1
permalinks.add(slug)
line = f"{hashes} {title} {{ #{slug} }}\n"
updated_lines.append(line)
with path.open("w", encoding="utf-8") as f:
f.writelines(updated_lines)
@app.command()
def add_permalinks_pages(pages: list[Path], update_existing: bool = False) -> None:
"""
Add or update header permalinks in specific pages of En docs.
"""
for md_file in pages:
add_permalinks_page(md_file, update_existing=update_existing)
@app.command()
def add_permalinks(update_existing: bool = False) -> None:
"""
Add or update header permalinks in all pages of En docs.
"""
for md_file in en_docs_path.rglob("*.md"):
add_permalinks_page(md_file, update_existing=update_existing)
if __name__ == "__main__":
app()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/mkdocs_hooks.py | scripts/mkdocs_hooks.py | from functools import lru_cache
from pathlib import Path
from typing import Any, Union
import material
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import File, Files
from mkdocs.structure.nav import Link, Navigation, Section
from mkdocs.structure.pages import Page
non_translated_sections = [
"reference/",
"release-notes.md",
"fastapi-people.md",
"external-links.md",
"newsletter.md",
"management-tasks.md",
"management.md",
]
@lru_cache
def get_missing_translation_content(docs_dir: str) -> str:
docs_dir_path = Path(docs_dir)
missing_translation_path = docs_dir_path.parent.parent / "missing-translation.md"
return missing_translation_path.read_text(encoding="utf-8")
@lru_cache
def get_mkdocs_material_langs() -> list[str]:
material_path = Path(material.__file__).parent
material_langs_path = material_path / "templates" / "partials" / "languages"
langs = [file.stem for file in material_langs_path.glob("*.html")]
return langs
class EnFile(File):
pass
def on_config(config: MkDocsConfig, **kwargs: Any) -> MkDocsConfig:
available_langs = get_mkdocs_material_langs()
dir_path = Path(config.docs_dir)
lang = dir_path.parent.name
if lang in available_langs:
config.theme["language"] = lang
if not (config.site_url or "").endswith(f"{lang}/") and lang != "en":
config.site_url = f"{config.site_url}{lang}/"
return config
def resolve_file(*, item: str, files: Files, config: MkDocsConfig) -> None:
item_path = Path(config.docs_dir) / item
if not item_path.is_file():
en_src_dir = (Path(config.docs_dir) / "../../en/docs").resolve()
potential_path = en_src_dir / item
if potential_path.is_file():
files.append(
EnFile(
path=item,
src_dir=str(en_src_dir),
dest_dir=config.site_dir,
use_directory_urls=config.use_directory_urls,
)
)
def resolve_files(*, items: list[Any], files: Files, config: MkDocsConfig) -> None:
for item in items:
if isinstance(item, str):
resolve_file(item=item, files=files, config=config)
elif isinstance(item, dict):
assert len(item) == 1
values = list(item.values())
if not values:
continue
if isinstance(values[0], str):
resolve_file(item=values[0], files=files, config=config)
elif isinstance(values[0], list):
resolve_files(items=values[0], files=files, config=config)
else:
raise ValueError(f"Unexpected value: {values}")
def on_files(files: Files, *, config: MkDocsConfig) -> Files:
resolve_files(items=config.nav or [], files=files, config=config)
if "logo" in config.theme:
resolve_file(item=config.theme["logo"], files=files, config=config)
if "favicon" in config.theme:
resolve_file(item=config.theme["favicon"], files=files, config=config)
resolve_files(items=config.extra_css, files=files, config=config)
resolve_files(items=config.extra_javascript, files=files, config=config)
return files
def generate_renamed_section_items(
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
new_children = generate_renamed_section_items(item.children, config=config)
first_child = new_children[0]
if isinstance(first_child, Page):
if first_child.file.src_path.endswith("index.md"):
# Read the source so that the title is parsed and available
first_child.read_source(config=config)
new_title = first_child.title or new_title
# Creating a new section makes it render it collapsed by default
# no idea why, so, let's just modify the existing one
# new_section = Section(title=new_title, children=new_children)
item.title = new_title.split("{ #")[0]
item.children = new_children
new_items.append(item)
else:
new_items.append(item)
return new_items
def on_nav(
nav: Navigation, *, config: MkDocsConfig, files: Files, **kwargs: Any
) -> Navigation:
new_items = generate_renamed_section_items(nav.items, config=config)
return Navigation(items=new_items, pages=nav.pages)
def on_pre_page(page: Page, *, config: MkDocsConfig, files: Files) -> Page:
return page
def on_page_markdown(
markdown: str, *, page: Page, config: MkDocsConfig, files: Files
) -> str:
# Set metadata["social"]["cards_layout_options"]["title"] to clean title (without
# permalink)
title = page.title
clean_title = title.split("{ #")[0]
if clean_title:
page.meta.setdefault("social", {})
page.meta["social"].setdefault("cards_layout_options", {})
page.meta["social"]["cards_layout_options"]["title"] = clean_title
if isinstance(page.file, EnFile):
for excluded_section in non_translated_sections:
if page.file.src_path.startswith(excluded_section):
return markdown
missing_translation_content = get_missing_translation_content(config.docs_dir)
header = ""
body = markdown
if markdown.startswith("#"):
header, _, body = markdown.partition("\n\n")
return f"{header}\n\n{missing_translation_content}\n\n{body}"
return markdown
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/deploy_docs_status.py | scripts/deploy_docs_status.py | import logging
import re
from typing import Literal
from github import Auth, Github
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
github_repository: str
github_token: SecretStr
deploy_url: str | None = None
commit_sha: str
run_id: int
state: Literal["pending", "success", "error"] = "pending"
class LinkData(BaseModel):
previous_link: str
preview_link: str
en_link: str | None = None
def main() -> None:
logging.basicConfig(level=logging.INFO)
settings = Settings()
logging.info(f"Using config: {settings.model_dump_json()}")
g = Github(auth=Auth.Token(settings.github_token.get_secret_value()))
repo = g.get_repo(settings.github_repository)
use_pr = next(
(pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None
)
if not use_pr:
logging.error(f"No PR found for hash: {settings.commit_sha}")
return
commits = list(use_pr.get_commits())
current_commit = [c for c in commits if c.sha == settings.commit_sha][0]
run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}"
if settings.state == "pending":
current_commit.create_status(
state="pending",
description="Deploying Docs",
context="deploy-docs",
target_url=run_url,
)
logging.info("No deploy URL available yet")
return
if settings.state == "error":
current_commit.create_status(
state="error",
description="Error Deploying Docs",
context="deploy-docs",
target_url=run_url,
)
logging.info("Error deploying docs")
return
assert settings.state == "success"
if not settings.deploy_url:
current_commit.create_status(
state="success",
description="No Docs Changes",
context="deploy-docs",
target_url=run_url,
)
logging.info("No docs changes found")
return
assert settings.deploy_url
current_commit.create_status(
state="success",
description="Docs Deployed",
context="deploy-docs",
target_url=run_url,
)
files = list(use_pr.get_files())
docs_files = [f for f in files if f.filename.startswith("docs/")]
deploy_url = settings.deploy_url.rstrip("/")
lang_links: dict[str, list[LinkData]] = {}
for f in docs_files:
match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename)
if not match:
continue
lang = match.group(1)
path = match.group(2)
if path.endswith("index.md"):
path = path.replace("index.md", "")
else:
path = path.replace(".md", "/")
en_path = path
if lang == "en":
use_path = en_path
else:
use_path = f"{lang}/{path}"
link = LinkData(
previous_link=f"https://fastapi.tiangolo.com/{use_path}",
preview_link=f"{deploy_url}/{use_path}",
)
if lang != "en":
link.en_link = f"https://fastapi.tiangolo.com/{en_path}"
lang_links.setdefault(lang, []).append(link)
links: list[LinkData] = []
en_links = lang_links.get("en", [])
en_links.sort(key=lambda x: x.preview_link)
links.extend(en_links)
langs = list(lang_links.keys())
langs.sort()
for lang in langs:
if lang == "en":
continue
current_lang_links = lang_links[lang]
current_lang_links.sort(key=lambda x: x.preview_link)
links.extend(current_lang_links)
header = "## 📝 Docs preview"
message = header
message += f"\n\nLast commit {settings.commit_sha} at: {deploy_url}"
if links:
message += "\n\n### Modified Pages\n\n"
for link in links:
message += f"* {link.preview_link}"
message += f" - ([before]({link.previous_link}))"
if link.en_link:
message += f" - ([English]({link.en_link}))"
message += "\n"
print(message)
issue = use_pr.as_issue()
comments = list(issue.get_comments())
for comment in comments:
if (
comment.body.startswith(header)
and comment.user.login == "github-actions[bot]"
):
comment.edit(message)
break
else:
issue.create_comment(message)
logging.info("Finished")
if __name__ == "__main__":
main()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/contributors.py | scripts/contributors.py | import logging
import secrets
import subprocess
from collections import Counter
from datetime import datetime
from pathlib import Path
from typing import Any
import httpx
import yaml
from github import Github
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings
github_graphql_url = "https://api.github.com/graphql"
prs_query = """
query Q($after: String) {
repository(name: "fastapi", owner: "fastapi") {
pullRequests(first: 100, after: $after) {
edges {
cursor
node {
number
labels(first: 100) {
nodes {
name
}
}
author {
login
avatarUrl
url
}
title
createdAt
lastEditedAt
updatedAt
state
reviews(first:100) {
nodes {
author {
login
avatarUrl
url
}
state
}
}
}
}
}
}
}
"""
class Author(BaseModel):
login: str
avatarUrl: str
url: str
class LabelNode(BaseModel):
name: str
class Labels(BaseModel):
nodes: list[LabelNode]
class ReviewNode(BaseModel):
author: Author | None = None
state: str
class Reviews(BaseModel):
nodes: list[ReviewNode]
class PullRequestNode(BaseModel):
number: int
labels: Labels
author: Author | None = None
title: str
createdAt: datetime
lastEditedAt: datetime | None = None
updatedAt: datetime | None = None
state: str
reviews: Reviews
class PullRequestEdge(BaseModel):
cursor: str
node: PullRequestNode
class PullRequests(BaseModel):
edges: list[PullRequestEdge]
class PRsRepository(BaseModel):
pullRequests: PullRequests
class PRsResponseData(BaseModel):
repository: PRsRepository
class PRsResponse(BaseModel):
data: PRsResponseData
class Settings(BaseSettings):
github_token: SecretStr
github_repository: str
httpx_timeout: int = 30
def get_graphql_response(
*,
settings: Settings,
query: str,
after: str | None = None,
) -> dict[str, Any]:
headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"}
variables = {"after": after}
response = httpx.post(
github_graphql_url,
headers=headers,
timeout=settings.httpx_timeout,
json={"query": query, "variables": variables, "operationName": "Q"},
)
if response.status_code != 200:
logging.error(f"Response was not 200, after: {after}")
logging.error(response.text)
raise RuntimeError(response.text)
data = response.json()
if "errors" in data:
logging.error(f"Errors in response, after: {after}")
logging.error(data["errors"])
logging.error(response.text)
raise RuntimeError(response.text)
return data
def get_graphql_pr_edges(
*, settings: Settings, after: str | None = None
) -> list[PullRequestEdge]:
data = get_graphql_response(settings=settings, query=prs_query, after=after)
graphql_response = PRsResponse.model_validate(data)
return graphql_response.data.repository.pullRequests.edges
def get_pr_nodes(settings: Settings) -> list[PullRequestNode]:
pr_nodes: list[PullRequestNode] = []
pr_edges = get_graphql_pr_edges(settings=settings)
while pr_edges:
for edge in pr_edges:
pr_nodes.append(edge.node)
last_edge = pr_edges[-1]
pr_edges = get_graphql_pr_edges(settings=settings, after=last_edge.cursor)
return pr_nodes
class ContributorsResults(BaseModel):
contributors: Counter[str]
translation_reviewers: Counter[str]
translators: Counter[str]
authors: dict[str, Author]
def get_contributors(pr_nodes: list[PullRequestNode]) -> ContributorsResults:
contributors = Counter[str]()
translation_reviewers = Counter[str]()
translators = Counter[str]()
authors: dict[str, Author] = {}
for pr in pr_nodes:
if pr.author:
authors[pr.author.login] = pr.author
is_lang = False
for label in pr.labels.nodes:
if label.name == "lang-all":
is_lang = True
break
for review in pr.reviews.nodes:
if review.author:
authors[review.author.login] = review.author
if is_lang:
translation_reviewers[review.author.login] += 1
if pr.state == "MERGED" and pr.author:
if is_lang:
translators[pr.author.login] += 1
else:
contributors[pr.author.login] += 1
return ContributorsResults(
contributors=contributors,
translation_reviewers=translation_reviewers,
translators=translators,
authors=authors,
)
def get_users_to_write(
*,
counter: Counter[str],
authors: dict[str, Author],
min_count: int = 2,
) -> dict[str, Any]:
users: dict[str, Any] = {}
for user, count in counter.most_common():
if count >= min_count:
author = authors[user]
users[user] = {
"login": user,
"count": count,
"avatarUrl": author.avatarUrl,
"url": author.url,
}
return users
def update_content(*, content_path: Path, new_content: Any) -> bool:
old_content = content_path.read_text(encoding="utf-8")
new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True)
if old_content == new_content:
logging.info(f"The content hasn't changed for {content_path}")
return False
content_path.write_text(new_content, encoding="utf-8")
logging.info(f"Updated {content_path}")
return True
def main() -> None:
logging.basicConfig(level=logging.INFO)
settings = Settings()
logging.info(f"Using config: {settings.model_dump_json()}")
g = Github(settings.github_token.get_secret_value())
repo = g.get_repo(settings.github_repository)
pr_nodes = get_pr_nodes(settings=settings)
contributors_results = get_contributors(pr_nodes=pr_nodes)
authors = contributors_results.authors
top_contributors = get_users_to_write(
counter=contributors_results.contributors,
authors=authors,
)
top_translators = get_users_to_write(
counter=contributors_results.translators,
authors=authors,
)
top_translations_reviewers = get_users_to_write(
counter=contributors_results.translation_reviewers,
authors=authors,
)
# For local development
# contributors_path = Path("../docs/en/data/contributors.yml")
contributors_path = Path("./docs/en/data/contributors.yml")
# translators_path = Path("../docs/en/data/translators.yml")
translators_path = Path("./docs/en/data/translators.yml")
# translation_reviewers_path = Path("../docs/en/data/translation_reviewers.yml")
translation_reviewers_path = Path("./docs/en/data/translation_reviewers.yml")
updated = [
update_content(content_path=contributors_path, new_content=top_contributors),
update_content(content_path=translators_path, new_content=top_translators),
update_content(
content_path=translation_reviewers_path,
new_content=top_translations_reviewers,
),
]
if not any(updated):
logging.info("The data hasn't changed, finishing.")
return
logging.info("Setting up GitHub Actions git user")
subprocess.run(["git", "config", "user.name", "github-actions[bot]"], check=True)
subprocess.run(
["git", "config", "user.email", "github-actions[bot]@users.noreply.github.com"],
check=True,
)
branch_name = f"fastapi-people-contributors-{secrets.token_hex(4)}"
logging.info(f"Creating a new branch {branch_name}")
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
logging.info("Adding updated file")
subprocess.run(
[
"git",
"add",
str(contributors_path),
str(translators_path),
str(translation_reviewers_path),
],
check=True,
)
logging.info("Committing updated file")
message = "👥 Update FastAPI People - Contributors and Translators"
subprocess.run(["git", "commit", "-m", message], check=True)
logging.info("Pushing branch")
subprocess.run(["git", "push", "origin", branch_name], check=True)
logging.info("Creating PR")
pr = repo.create_pull(title=message, body=message, base="master", head=branch_name)
logging.info(f"Created PR: {pr.number}")
logging.info("Finished")
if __name__ == "__main__":
main()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/topic_repos.py | scripts/topic_repos.py | import logging
import secrets
import subprocess
from pathlib import Path
import yaml
from github import Github
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
github_repository: str
github_token: SecretStr
class Repo(BaseModel):
name: str
html_url: str
stars: int
owner_login: str
owner_html_url: str
def main() -> None:
logging.basicConfig(level=logging.INFO)
settings = Settings()
logging.info(f"Using config: {settings.model_dump_json()}")
g = Github(settings.github_token.get_secret_value(), per_page=100)
r = g.get_repo(settings.github_repository)
repos = g.search_repositories(query="topic:fastapi")
repos_list = list(repos)
final_repos: list[Repo] = []
for repo in repos_list[:100]:
if repo.full_name == settings.github_repository:
continue
final_repos.append(
Repo(
name=repo.name,
html_url=repo.html_url,
stars=repo.stargazers_count,
owner_login=repo.owner.login,
owner_html_url=repo.owner.html_url,
)
)
data = [repo.model_dump() for repo in final_repos]
# Local development
# repos_path = Path("../docs/en/data/topic_repos.yml")
repos_path = Path("./docs/en/data/topic_repos.yml")
repos_old_content = repos_path.read_text(encoding="utf-8")
new_repos_content = yaml.dump(data, sort_keys=False, width=200, allow_unicode=True)
if repos_old_content == new_repos_content:
logging.info("The data hasn't changed. Finishing.")
return
repos_path.write_text(new_repos_content, encoding="utf-8")
logging.info("Setting up GitHub Actions git user")
subprocess.run(["git", "config", "user.name", "github-actions[bot]"], check=True)
subprocess.run(
["git", "config", "user.email", "github-actions[bot]@users.noreply.github.com"],
check=True,
)
branch_name = f"fastapi-topic-repos-{secrets.token_hex(4)}"
logging.info(f"Creating a new branch {branch_name}")
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
logging.info("Adding updated file")
subprocess.run(["git", "add", str(repos_path)], check=True)
logging.info("Committing updated file")
message = "👥 Update FastAPI GitHub topic repositories"
subprocess.run(["git", "commit", "-m", message], check=True)
logging.info("Pushing branch")
subprocess.run(["git", "push", "origin", branch_name], check=True)
logging.info("Creating PR")
pr = r.create_pull(title=message, body=message, base="master", head=branch_name)
logging.info(f"Created PR: {pr.number}")
logging.info("Finished")
if __name__ == "__main__":
main()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/query_param_models/image01.py | scripts/playwright/query_param_models/image01.py | import subprocess
import time
import httpx
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_role("button", name="GET /items/ Read Items").click()
page.get_by_role("button", name="Try it out").click()
page.get_by_role("heading", name="Servers").click()
# Manually add the screenshot
page.screenshot(path="docs/en/docs/img/tutorial/query-param-models/image01.png")
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["fastapi", "run", "docs_src/query_param_models/tutorial001.py"]
)
try:
for _ in range(3):
try:
response = httpx.get("http://localhost:8000/docs")
except httpx.ConnectError:
time.sleep(1)
break
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/cookie_param_models/image01.py | scripts/playwright/cookie_param_models/image01.py | import subprocess
import time
import httpx
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_role("link", name="/items/").click()
# Manually add the screenshot
page.screenshot(path="docs/en/docs/img/tutorial/cookie-param-models/image01.png")
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["fastapi", "run", "docs_src/cookie_param_models/tutorial001.py"]
)
try:
for _ in range(3):
try:
response = httpx.get("http://localhost:8000/docs")
except httpx.ConnectError:
time.sleep(1)
break
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/sql_databases/image01.py | scripts/playwright/sql_databases/image01.py | import subprocess
import time
import httpx
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_label("post /heroes/").click()
# Manually add the screenshot
page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image01.png")
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["fastapi", "run", "docs_src/sql_databases/tutorial001.py"],
)
try:
for _ in range(3):
try:
response = httpx.get("http://localhost:8000/docs")
except httpx.ConnectError:
time.sleep(1)
break
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/sql_databases/image02.py | scripts/playwright/sql_databases/image02.py | import subprocess
import time
import httpx
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_label("post /heroes/").click()
# Manually add the screenshot
page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image02.png")
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["fastapi", "run", "docs_src/sql_databases/tutorial002.py"],
)
try:
for _ in range(3):
try:
response = httpx.get("http://localhost:8000/docs")
except httpx.ConnectError:
time.sleep(1)
break
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/request_form_models/image01.py | scripts/playwright/request_form_models/image01.py | import subprocess
import time
import httpx
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_role("button", name="POST /login/ Login").click()
page.get_by_role("button", name="Try it out").click()
# Manually add the screenshot
page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png")
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["fastapi", "run", "docs_src/request_form_models/tutorial001.py"]
)
try:
for _ in range(3):
try:
response = httpx.get("http://localhost:8000/docs")
except httpx.ConnectError:
time.sleep(1)
break
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/header_param_models/image01.py | scripts/playwright/header_param_models/image01.py | import subprocess
import time
import httpx
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_role("button", name="GET /items/ Read Items").click()
page.get_by_role("button", name="Try it out").click()
# Manually add the screenshot
page.screenshot(path="docs/en/docs/img/tutorial/header-param-models/image01.png")
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["fastapi", "run", "docs_src/header_param_models/tutorial001.py"]
)
try:
for _ in range(3):
try:
response = httpx.get("http://localhost:8000/docs")
except httpx.ConnectError:
time.sleep(1)
break
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/separate_openapi_schemas/image01.py | scripts/playwright/separate_openapi_schemas/image01.py | import subprocess
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_text("POST/items/Create Item").click()
page.get_by_role("tab", name="Schema").first.click()
# Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png"
)
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"]
)
try:
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/separate_openapi_schemas/image05.py | scripts/playwright/separate_openapi_schemas/image05.py | import subprocess
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_role("button", name="Item", exact=True).click()
page.set_viewport_size({"width": 960, "height": 700})
# Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png"
)
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["uvicorn", "docs_src.separate_openapi_schemas.tutorial002:app"]
)
try:
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/separate_openapi_schemas/image02.py | scripts/playwright/separate_openapi_schemas/image02.py | import subprocess
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_text("GET/items/Read Items").click()
page.get_by_role("button", name="Try it out").click()
page.get_by_role("button", name="Execute").click()
# Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png"
)
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"]
)
try:
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/separate_openapi_schemas/image04.py | scripts/playwright/separate_openapi_schemas/image04.py | import subprocess
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_role("button", name="Item-Input").click()
page.get_by_role("button", name="Item-Output").click()
page.set_viewport_size({"width": 960, "height": 820})
# Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png"
)
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"]
)
try:
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/scripts/playwright/separate_openapi_schemas/image03.py | scripts/playwright/separate_openapi_schemas/image03.py | import subprocess
from playwright.sync_api import Playwright, sync_playwright
# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_text("GET/items/Read Items").click()
page.get_by_role("tab", name="Schema").click()
page.get_by_label("Schema").get_by_role("button", name="Expand all").click()
# Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png"
)
# ---------------------
context.close()
browser.close()
process = subprocess.Popen(
["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"]
)
try:
with sync_playwright() as playwright:
run(playwright)
finally:
process.terminate()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_annotated.py | tests/test_annotated.py | from typing import Annotated
import pytest
from fastapi import APIRouter, FastAPI, Query
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/default")
async def default(foo: Annotated[str, Query()] = "foo"):
return {"foo": foo}
@app.get("/required")
async def required(foo: Annotated[str, Query(min_length=1)]):
return {"foo": foo}
@app.get("/multiple")
async def multiple(foo: Annotated[str, object(), Query(min_length=1)]):
return {"foo": foo}
@app.get("/unrelated")
async def unrelated(foo: Annotated[str, object()]):
return {"foo": foo}
client = TestClient(app)
foo_is_missing = {
"detail": [
{
"loc": ["query", "foo"],
"msg": "Field required",
"type": "missing",
"input": None,
}
]
}
foo_is_short = {
"detail": [
{
"ctx": {"min_length": 1},
"loc": ["query", "foo"],
"msg": "String should have at least 1 character",
"type": "string_too_short",
"input": "",
}
]
}
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
("/default", 200, {"foo": "foo"}),
("/default?foo=bar", 200, {"foo": "bar"}),
("/required?foo=bar", 200, {"foo": "bar"}),
("/required", 422, foo_is_missing),
("/required?foo=", 422, foo_is_short),
("/multiple?foo=bar", 200, {"foo": "bar"}),
("/multiple", 422, foo_is_missing),
("/multiple?foo=", 422, foo_is_short),
("/unrelated?foo=bar", 200, {"foo": "bar"}),
("/unrelated", 422, foo_is_missing),
],
)
def test_get(path, expected_status, expected_response):
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_multiple_path():
app = FastAPI()
@app.get("/test1")
@app.get("/test2")
async def test(var: Annotated[str, Query()] = "bar"):
return {"foo": var}
client = TestClient(app)
response = client.get("/test1")
assert response.status_code == 200
assert response.json() == {"foo": "bar"}
response = client.get("/test1", params={"var": "baz"})
assert response.status_code == 200
assert response.json() == {"foo": "baz"}
response = client.get("/test2")
assert response.status_code == 200
assert response.json() == {"foo": "bar"}
response = client.get("/test2", params={"var": "baz"})
assert response.status_code == 200
assert response.json() == {"foo": "baz"}
def test_nested_router():
app = FastAPI()
router = APIRouter(prefix="/nested")
@router.get("/test")
async def test(var: Annotated[str, Query()] = "bar"):
return {"foo": var}
app.include_router(router)
client = TestClient(app)
response = client.get("/nested/test")
assert response.status_code == 200
assert response.json() == {"foo": "bar"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/default": {
"get": {
"summary": "Default",
"operationId": "default_default_get",
"parameters": [
{
"required": False,
"schema": {
"title": "Foo",
"type": "string",
"default": "foo",
},
"name": "foo",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/required": {
"get": {
"summary": "Required",
"operationId": "required_required_get",
"parameters": [
{
"required": True,
"schema": {
"title": "Foo",
"minLength": 1,
"type": "string",
},
"name": "foo",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/multiple": {
"get": {
"summary": "Multiple",
"operationId": "multiple_multiple_get",
"parameters": [
{
"required": True,
"schema": {
"title": "Foo",
"minLength": 1,
"type": "string",
},
"name": "foo",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/unrelated": {
"get": {
"summary": "Unrelated",
"operationId": "unrelated_unrelated_get",
"parameters": [
{
"required": True,
"schema": {"title": "Foo", "type": "string"},
"name": "foo",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
},
"components": {
"schemas": {
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_swagger_ui_init_oauth.py | tests/test_swagger_ui_init_oauth.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
swagger_ui_init_oauth = {"clientId": "the-foo-clients", "appName": "The Predendapp"}
app = FastAPI(swagger_ui_init_oauth=swagger_ui_init_oauth)
@app.get("/items/")
async def read_items():
return {"id": "foo"}
client = TestClient(app)
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, response.text
print(response.text)
assert "ui.initOAuth" in response.text
assert '"appName": "The Predendapp"' in response.text
assert '"clientId": "the-foo-clients"' in response.text
def test_response():
response = client.get("/items/")
assert response.json() == {"id": "foo"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_param_include_in_schema.py | tests/test_param_include_in_schema.py | from typing import Optional
import pytest
from fastapi import Cookie, FastAPI, Header, Path, Query
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/hidden_cookie")
async def hidden_cookie(
hidden_cookie: Optional[str] = Cookie(default=None, include_in_schema=False),
):
return {"hidden_cookie": hidden_cookie}
@app.get("/hidden_header")
async def hidden_header(
hidden_header: Optional[str] = Header(default=None, include_in_schema=False),
):
return {"hidden_header": hidden_header}
@app.get("/hidden_path/{hidden_path}")
async def hidden_path(hidden_path: str = Path(include_in_schema=False)):
return {"hidden_path": hidden_path}
@app.get("/hidden_query")
async def hidden_query(
hidden_query: Optional[str] = Query(default=None, include_in_schema=False),
):
return {"hidden_query": hidden_query}
openapi_schema = {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/hidden_cookie": {
"get": {
"summary": "Hidden Cookie",
"operationId": "hidden_cookie_hidden_cookie_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/hidden_header": {
"get": {
"summary": "Hidden Header",
"operationId": "hidden_header_hidden_header_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/hidden_path/{hidden_path}": {
"get": {
"summary": "Hidden Path",
"operationId": "hidden_path_hidden_path__hidden_path__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/hidden_query": {
"get": {
"summary": "Hidden Query",
"operationId": "hidden_query_hidden_query_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
},
"components": {
"schemas": {
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"anyOf": [{"type": "string"}, {"type": "integer"}]},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
}
},
}
def test_openapi_schema():
client = TestClient(app)
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
@pytest.mark.parametrize(
"path,cookies,expected_status,expected_response",
[
(
"/hidden_cookie",
{},
200,
{"hidden_cookie": None},
),
(
"/hidden_cookie",
{"hidden_cookie": "somevalue"},
200,
{"hidden_cookie": "somevalue"},
),
],
)
def test_hidden_cookie(path, cookies, expected_status, expected_response):
client = TestClient(app, cookies=cookies)
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
@pytest.mark.parametrize(
"path,headers,expected_status,expected_response",
[
(
"/hidden_header",
{},
200,
{"hidden_header": None},
),
(
"/hidden_header",
{"Hidden-Header": "somevalue"},
200,
{"hidden_header": "somevalue"},
),
],
)
def test_hidden_header(path, headers, expected_status, expected_response):
client = TestClient(app)
response = client.get(path, headers=headers)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_hidden_path():
client = TestClient(app)
response = client.get("/hidden_path/hidden_path")
assert response.status_code == 200
assert response.json() == {"hidden_path": "hidden_path"}
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
(
"/hidden_query",
200,
{"hidden_query": None},
),
(
"/hidden_query?hidden_query=somevalue",
200,
{"hidden_query": "somevalue"},
),
],
)
def test_hidden_query(path, expected_status, expected_response):
client = TestClient(app)
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_ambiguous_params.py | tests/test_ambiguous_params.py | from typing import Annotated
import pytest
from fastapi import Depends, FastAPI, Path
from fastapi.param_functions import Query
from fastapi.testclient import TestClient
app = FastAPI()
def test_no_annotated_defaults():
with pytest.raises(
AssertionError, match="Path parameters cannot have a default value"
):
@app.get("/items/{item_id}/")
async def get_item(item_id: Annotated[int, Path(default=1)]):
pass # pragma: nocover
with pytest.raises(
AssertionError,
match=(
"`Query` default value cannot be set in `Annotated` for 'item_id'. Set the"
" default value with `=` instead."
),
):
@app.get("/")
async def get(item_id: Annotated[int, Query(default=1)]):
pass # pragma: nocover
def test_multiple_annotations():
async def dep():
pass # pragma: nocover
@app.get("/multi-query")
async def get(foo: Annotated[int, Query(gt=2), Query(lt=10)]):
return foo
with pytest.raises(
AssertionError,
match=(
"Cannot specify `Depends` in `Annotated` and default value"
" together for 'foo'"
),
):
@app.get("/")
async def get2(foo: Annotated[int, Depends(dep)] = Depends(dep)):
pass # pragma: nocover
with pytest.raises(
AssertionError,
match=(
"Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a"
" default value together for 'foo'"
),
):
@app.get("/")
async def get3(foo: Annotated[int, Query(min_length=1)] = Depends(dep)):
pass # pragma: nocover
client = TestClient(app)
response = client.get("/multi-query", params={"foo": "5"})
assert response.status_code == 200
assert response.json() == 5
response = client.get("/multi-query", params={"foo": "123"})
assert response.status_code == 422
response = client.get("/multi-query", params={"foo": "1"})
assert response.status_code == 422
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_oauth2.py | tests/test_security_oauth2.py | import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
reusable_oauth2 = OAuth2(
flows={
"password": {
"tokenUrl": "token",
"scopes": {"read:users": "Read the users", "write:users": "Create users"},
}
}
)
class User(BaseModel):
username: str
# Here we use string annotations to test them
def get_current_user(oauth_header: "str" = Security(reusable_oauth2)):
user = User(username=oauth_header)
return user
@app.post("/login")
# Here we use string annotations to test them
def login(form_data: "OAuth2PasswordRequestFormStrict" = Depends()):
return form_data
@app.get("/users/me")
# Here we use string annotations to test them
def read_current_user(current_user: "User" = Depends(get_current_user)):
return current_user
client = TestClient(app)
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
assert response.status_code == 200, response.text
assert response.json() == {"username": "Other footokenbar"}
def test_security_oauth2_password_bearer_no_header():
response = client.get("/users/me")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_strict_login_no_data():
response = client.post("/login")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
},
]
}
def test_strict_login_no_grant_type():
response = client.post("/login", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
}
]
}
@pytest.mark.parametrize(
argnames=["grant_type"],
argvalues=[
pytest.param("incorrect", id="incorrect value"),
pytest.param("passwordblah", id="password with suffix"),
pytest.param("blahpassword", id="password with prefix"),
],
)
def test_strict_login_incorrect_grant_type(grant_type: str):
response = client.post(
"/login",
data={"username": "johndoe", "password": "secret", "grant_type": grant_type},
)
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_pattern_mismatch",
"loc": ["body", "grant_type"],
"msg": "String should match pattern '^password$'",
"input": grant_type,
"ctx": {"pattern": "^password$"},
}
]
}
def test_strict_login_correct_grant_type():
response = client.post(
"/login",
data={"username": "johndoe", "password": "secret", "grant_type": "password"},
)
assert response.status_code == 200
assert response.json() == {
"grant_type": "password",
"username": "johndoe",
"password": "secret",
"scopes": [],
"client_id": None,
"client_secret": None,
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/login": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Login",
"operationId": "login_login_post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_login_login_post"
}
}
},
"required": True,
},
}
},
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"OAuth2": []}],
}
},
},
"components": {
"schemas": {
"Body_login_login_post": {
"title": "Body_login_login_post",
"required": ["grant_type", "username", "password"],
"type": "object",
"properties": {
"grant_type": {
"title": "Grant Type",
"pattern": "^password$",
"type": "string",
},
"username": {"title": "Username", "type": "string"},
"password": {"title": "Password", "type": "string"},
"scope": {"title": "Scope", "type": "string", "default": ""},
"client_id": {
"title": "Client Id",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"client_secret": {
"title": "Client Secret",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
},
"securitySchemes": {
"OAuth2": {
"type": "oauth2",
"flows": {
"password": {
"scopes": {
"read:users": "Read the users",
"write:users": "Create users",
},
"tokenUrl": "token",
}
},
}
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_validate_response_dataclass.py | tests/test_validate_response_dataclass.py | from typing import Optional
import pytest
from fastapi import FastAPI
from fastapi.exceptions import ResponseValidationError
from fastapi.testclient import TestClient
from pydantic.dataclasses import dataclass
app = FastAPI()
@dataclass
class Item:
name: str
price: Optional[float] = None
owner_ids: Optional[list[int]] = None
@app.get("/items/invalid", response_model=Item)
def get_invalid():
return {"name": "invalid", "price": "foo"}
@app.get("/items/innerinvalid", response_model=Item)
def get_innerinvalid():
return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]}
@app.get("/items/invalidlist", response_model=list[Item])
def get_invalidlist():
return [
{"name": "foo"},
{"name": "bar", "price": "bar"},
{"name": "baz", "price": "baz"},
]
client = TestClient(app)
def test_invalid():
with pytest.raises(ResponseValidationError):
client.get("/items/invalid")
def test_double_invalid():
with pytest.raises(ResponseValidationError):
client.get("/items/innerinvalid")
def test_invalid_list():
with pytest.raises(ResponseValidationError):
client.get("/items/invalidlist")
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_model_include_exclude.py | tests/test_response_model_include_exclude.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Model1(BaseModel):
foo: str
bar: str
class Model2(BaseModel):
ref: Model1
baz: str
class Model3(BaseModel):
name: str
age: int
ref2: Model2
app = FastAPI()
@app.get(
"/simple_include",
response_model=Model2,
response_model_include={"baz": ..., "ref": {"foo"}},
)
def simple_include():
return Model2(
ref=Model1(foo="simple_include model foo", bar="simple_include model bar"),
baz="simple_include model2 baz",
)
@app.get(
"/simple_include_dict",
response_model=Model2,
response_model_include={"baz": ..., "ref": {"foo"}},
)
def simple_include_dict():
return {
"ref": {
"foo": "simple_include_dict model foo",
"bar": "simple_include_dict model bar",
},
"baz": "simple_include_dict model2 baz",
}
@app.get(
"/simple_exclude",
response_model=Model2,
response_model_exclude={"ref": {"bar"}},
)
def simple_exclude():
return Model2(
ref=Model1(foo="simple_exclude model foo", bar="simple_exclude model bar"),
baz="simple_exclude model2 baz",
)
@app.get(
"/simple_exclude_dict",
response_model=Model2,
response_model_exclude={"ref": {"bar"}},
)
def simple_exclude_dict():
return {
"ref": {
"foo": "simple_exclude_dict model foo",
"bar": "simple_exclude_dict model bar",
},
"baz": "simple_exclude_dict model2 baz",
}
@app.get(
"/mixed",
response_model=Model3,
response_model_include={"ref2", "name"},
response_model_exclude={"ref2": {"baz"}},
)
def mixed():
return Model3(
name="mixed model3 name",
age=3,
ref2=Model2(
ref=Model1(foo="mixed model foo", bar="mixed model bar"),
baz="mixed model2 baz",
),
)
@app.get(
"/mixed_dict",
response_model=Model3,
response_model_include={"ref2", "name"},
response_model_exclude={"ref2": {"baz"}},
)
def mixed_dict():
return {
"name": "mixed_dict model3 name",
"age": 3,
"ref2": {
"ref": {"foo": "mixed_dict model foo", "bar": "mixed_dict model bar"},
"baz": "mixed_dict model2 baz",
},
}
client = TestClient(app)
def test_nested_include_simple():
response = client.get("/simple_include")
assert response.status_code == 200, response.text
assert response.json() == {
"baz": "simple_include model2 baz",
"ref": {"foo": "simple_include model foo"},
}
def test_nested_include_simple_dict():
response = client.get("/simple_include_dict")
assert response.status_code == 200, response.text
assert response.json() == {
"baz": "simple_include_dict model2 baz",
"ref": {"foo": "simple_include_dict model foo"},
}
def test_nested_exclude_simple():
response = client.get("/simple_exclude")
assert response.status_code == 200, response.text
assert response.json() == {
"baz": "simple_exclude model2 baz",
"ref": {"foo": "simple_exclude model foo"},
}
def test_nested_exclude_simple_dict():
response = client.get("/simple_exclude_dict")
assert response.status_code == 200, response.text
assert response.json() == {
"baz": "simple_exclude_dict model2 baz",
"ref": {"foo": "simple_exclude_dict model foo"},
}
def test_nested_include_mixed():
response = client.get("/mixed")
assert response.status_code == 200, response.text
assert response.json() == {
"name": "mixed model3 name",
"ref2": {
"ref": {"foo": "mixed model foo", "bar": "mixed model bar"},
},
}
def test_nested_include_mixed_dict():
response = client.get("/mixed_dict")
assert response.status_code == 200, response.text
assert response.json() == {
"name": "mixed_dict model3 name",
"ref2": {
"ref": {"foo": "mixed_dict model foo", "bar": "mixed_dict model bar"},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_local_docs.py | tests/test_local_docs.py | import inspect
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
def test_strings_in_generated_swagger():
sig = inspect.signature(get_swagger_ui_html)
swagger_js_url = sig.parameters.get("swagger_js_url").default # type: ignore
swagger_css_url = sig.parameters.get("swagger_css_url").default # type: ignore
swagger_favicon_url = sig.parameters.get("swagger_favicon_url").default # type: ignore
html = get_swagger_ui_html(openapi_url="/docs", title="title")
body_content = html.body.decode()
assert swagger_js_url in body_content
assert swagger_css_url in body_content
assert swagger_favicon_url in body_content
def test_strings_in_custom_swagger():
swagger_js_url = "swagger_fake_file.js"
swagger_css_url = "swagger_fake_file.css"
swagger_favicon_url = "swagger_fake_file.png"
html = get_swagger_ui_html(
openapi_url="/docs",
title="title",
swagger_js_url=swagger_js_url,
swagger_css_url=swagger_css_url,
swagger_favicon_url=swagger_favicon_url,
)
body_content = html.body.decode()
assert swagger_js_url in body_content
assert swagger_css_url in body_content
assert swagger_favicon_url in body_content
def test_strings_in_generated_redoc():
sig = inspect.signature(get_redoc_html)
redoc_js_url = sig.parameters.get("redoc_js_url").default # type: ignore
redoc_favicon_url = sig.parameters.get("redoc_favicon_url").default # type: ignore
html = get_redoc_html(openapi_url="/docs", title="title")
body_content = html.body.decode()
assert redoc_js_url in body_content
assert redoc_favicon_url in body_content
def test_strings_in_custom_redoc():
redoc_js_url = "fake_redoc_file.js"
redoc_favicon_url = "fake_redoc_file.png"
html = get_redoc_html(
openapi_url="/docs",
title="title",
redoc_js_url=redoc_js_url,
redoc_favicon_url=redoc_favicon_url,
)
body_content = html.body.decode()
assert redoc_js_url in body_content
assert redoc_favicon_url in body_content
def test_google_fonts_in_generated_redoc():
body_with_google_fonts = get_redoc_html(
openapi_url="/docs", title="title"
).body.decode()
assert "fonts.googleapis.com" in body_with_google_fonts
body_without_google_fonts = get_redoc_html(
openapi_url="/docs", title="title", with_google_fonts=False
).body.decode()
assert "fonts.googleapis.com" not in body_without_google_fonts
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_openapi_schema_type.py | tests/test_openapi_schema_type.py | from typing import Optional, Union
import pytest
from fastapi.openapi.models import Schema, SchemaType
@pytest.mark.parametrize(
"type_value",
[
"array",
["string", "null"],
None,
],
)
def test_allowed_schema_type(
type_value: Optional[Union[SchemaType, list[SchemaType]]],
) -> None:
"""Test that Schema accepts SchemaType, List[SchemaType] and None for type field."""
schema = Schema(type=type_value)
assert schema.type == type_value
def test_invalid_type_value() -> None:
"""Test that Schema raises ValueError for invalid type values."""
with pytest.raises(ValueError, match="2 validation errors for Schema"):
Schema(type=True) # type: ignore[arg-type]
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_basic_realm.py | tests/test_security_http_basic_realm.py | from base64 import b64encode
from fastapi import FastAPI, Security
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.testclient import TestClient
app = FastAPI()
security = HTTPBasic(realm="simple")
@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredentials = Security(security)):
return {"username": credentials.username, "password": credentials.password}
client = TestClient(app)
def test_security_http_basic():
response = client.get("/users/me", auth=("john", "secret"))
assert response.status_code == 200, response.text
assert response.json() == {"username": "john", "password": "secret"}
def test_security_http_basic_no_credentials():
response = client.get("/users/me")
assert response.json() == {"detail": "Not authenticated"}
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
def test_security_http_basic_invalid_credentials():
response = client.get(
"/users/me", headers={"Authorization": "Basic notabase64token"}
)
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
assert response.json() == {"detail": "Not authenticated"}
def test_security_http_basic_non_basic_credentials():
payload = b64encode(b"johnsecret").decode("ascii")
auth_header = f"Basic {payload}"
response = client.get("/users/me", headers={"Authorization": auth_header})
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
assert response.json() == {"detail": "Not authenticated"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"HTTPBasic": []}],
}
}
},
"components": {
"securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_form_default.py | tests/test_form_default.py | from typing import Annotated, Optional
from fastapi import FastAPI, File, Form
from starlette.testclient import TestClient
app = FastAPI()
@app.post("/urlencoded")
async def post_url_encoded(age: Annotated[Optional[int], Form()] = None):
return age
@app.post("/multipart")
async def post_multi_part(
age: Annotated[Optional[int], Form()] = None,
file: Annotated[Optional[bytes], File()] = None,
):
return {"file": file, "age": age}
client = TestClient(app)
def test_form_default_url_encoded():
response = client.post("/urlencoded", data={"age": ""})
assert response.status_code == 200
assert response.text == "null"
def test_form_default_multi_part():
response = client.post("/multipart", data={"age": ""})
assert response.status_code == 200
assert response.json() == {"file": None, "age": None}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_api_key_query_description.py | tests/test_security_api_key_query_description.py | from fastapi import Depends, FastAPI, Security
from fastapi.security import APIKeyQuery
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyQuery(name="key", description="API Key Query")
class User(BaseModel):
username: str
def get_current_user(oauth_header: str = Security(api_key)):
user = User(username=oauth_header)
return user
@app.get("/users/me")
def read_current_user(current_user: User = Depends(get_current_user)):
return current_user
client = TestClient(app)
def test_security_api_key():
response = client.get("/users/me?key=secret")
assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "APIKey"
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"APIKeyQuery": []}],
}
}
},
"components": {
"securitySchemes": {
"APIKeyQuery": {
"type": "apiKey",
"name": "key",
"in": "query",
"description": "API Key Query",
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_param_class.py | tests/test_param_class.py | from typing import Optional
from fastapi import FastAPI
from fastapi.params import Param
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/items/")
def read_items(q: Optional[str] = Param(default=None)): # type: ignore
return {"q": q}
client = TestClient(app)
def test_default_param_query_none():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == {"q": None}
def test_default_param_query():
response = client.get("/items/?q=foo")
assert response.status_code == 200, response.text
assert response.json() == {"q": "foo"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_digest_description.py | tests/test_security_http_digest_description.py | from fastapi import FastAPI, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest
from fastapi.testclient import TestClient
app = FastAPI()
security = HTTPDigest(description="HTTPDigest scheme")
@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
return {"scheme": credentials.scheme, "credentials": credentials.credentials}
client = TestClient(app)
def test_security_http_digest():
response = client.get("/users/me", headers={"Authorization": "Digest foobar"})
assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Digest", "credentials": "foobar"}
def test_security_http_digest_no_credentials():
response = client.get("/users/me")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Digest"
def test_security_http_digest_incorrect_scheme_credentials():
response = client.get(
"/users/me", headers={"Authorization": "Other invalidauthorization"}
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Digest"
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"HTTPDigest": []}],
}
}
},
"components": {
"securitySchemes": {
"HTTPDigest": {
"type": "http",
"scheme": "digest",
"description": "HTTPDigest scheme",
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_empty_router.py | tests/test_empty_router.py | import pytest
from fastapi import APIRouter, FastAPI
from fastapi.exceptions import FastAPIError
from fastapi.testclient import TestClient
app = FastAPI()
router = APIRouter()
@router.get("")
def get_empty():
return ["OK"]
app.include_router(router, prefix="/prefix")
client = TestClient(app)
def test_use_empty():
with client:
response = client.get("/prefix")
assert response.status_code == 200, response.text
assert response.json() == ["OK"]
response = client.get("/prefix/")
assert response.status_code == 200, response.text
assert response.json() == ["OK"]
def test_include_empty():
# if both include and router.path are empty - it should raise exception
with pytest.raises(FastAPIError):
app.include_router(router)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_custom_swagger_ui_redirect.py | tests/test_custom_swagger_ui_redirect.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
swagger_ui_oauth2_redirect_url = "/docs/redirect"
app = FastAPI(swagger_ui_oauth2_redirect_url=swagger_ui_oauth2_redirect_url)
@app.get("/items/")
async def read_items():
return {"id": "foo"}
client = TestClient(app)
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "swagger-ui-dist" in response.text
print(client.base_url)
assert (
f"oauth2RedirectUrl: window.location.origin + '{swagger_ui_oauth2_redirect_url}'"
in response.text
)
def test_swagger_ui_oauth2_redirect():
response = client.get(swagger_ui_oauth2_redirect_url)
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "window.opener.swaggerUIRedirectOauth2" in response.text
def test_response():
response = client.get("/items/")
assert response.json() == {"id": "foo"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_http_connection_injection.py | tests/test_http_connection_injection.py | from fastapi import Depends, FastAPI
from fastapi.requests import HTTPConnection
from fastapi.testclient import TestClient
from starlette.websockets import WebSocket
app = FastAPI()
app.state.value = 42
async def extract_value_from_http_connection(conn: HTTPConnection):
return conn.app.state.value
@app.get("/http")
async def get_value_by_http(value: int = Depends(extract_value_from_http_connection)):
return value
@app.websocket("/ws")
async def get_value_by_ws(
websocket: WebSocket, value: int = Depends(extract_value_from_http_connection)
):
await websocket.accept()
await websocket.send_json(value)
await websocket.close()
client = TestClient(app)
def test_value_extracting_by_http():
response = client.get("/http")
assert response.status_code == 200
assert response.json() == 42
def test_value_extracting_by_ws():
with client.websocket_connect("/ws") as websocket:
assert websocket.receive_json() == 42
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_schema_ref_pydantic_v2.py | tests/test_schema_ref_pydantic_v2.py | from typing import Any
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, ConfigDict, Field
@pytest.fixture(name="client")
def get_client():
app = FastAPI()
class ModelWithRef(BaseModel):
ref: str = Field(validation_alias="$ref", serialization_alias="$ref")
model_config = ConfigDict(validate_by_alias=True, serialize_by_alias=True)
@app.get("/", response_model=ModelWithRef)
async def read_root() -> Any:
return {"$ref": "some-ref"}
client = TestClient(app)
return client
def test_get(client: TestClient):
response = client.get("/")
assert response.json() == {"$ref": "some-ref"}
def test_openapi_schema(client: TestClient):
response = client.get("openapi.json")
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"get": {
"summary": "Read Root",
"operationId": "read_root__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ModelWithRef"
}
}
},
}
},
}
}
},
"components": {
"schemas": {
"ModelWithRef": {
"properties": {"$ref": {"type": "string", "title": "$Ref"}},
"type": "object",
"required": ["$ref"],
"title": "ModelWithRef",
}
}
},
}
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_repeated_parameter_alias.py | tests/test_repeated_parameter_alias.py | from fastapi import FastAPI, Path, Query, status
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/{repeated_alias}")
def get_parameters_with_repeated_aliases(
path: str = Path(..., alias="repeated_alias"),
query: str = Query(..., alias="repeated_alias"),
):
return {"path": path, "query": query}
client = TestClient(app)
def test_get_parameters():
response = client.get("/test_path", params={"repeated_alias": "test_query"})
assert response.status_code == 200, response.text
assert response.json() == {"path": "test_path", "query": "test_query"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == status.HTTP_200_OK
actual_schema = response.json()
assert actual_schema == {
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {"$ref": "#/components/schemas/ValidationError"},
"title": "Detail",
"type": "array",
}
},
"title": "HTTPValidationError",
"type": "object",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"title": "Location",
"type": "array",
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
"required": ["loc", "msg", "type"],
"title": "ValidationError",
"type": "object",
},
}
},
"info": {"title": "FastAPI", "version": "0.1.0"},
"openapi": "3.1.0",
"paths": {
"/{repeated_alias}": {
"get": {
"operationId": "get_parameters_with_repeated_aliases__repeated_alias__get",
"parameters": [
{
"in": "path",
"name": "repeated_alias",
"required": True,
"schema": {"title": "Repeated Alias", "type": "string"},
},
{
"in": "query",
"name": "repeated_alias",
"required": True,
"schema": {"title": "Repeated Alias", "type": "string"},
},
],
"responses": {
"200": {
"content": {"application/json": {"schema": {}}},
"description": "Successful Response",
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error",
},
},
"summary": "Get Parameters With Repeated Aliases",
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_openapi_servers.py | tests/test_openapi_servers.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
app = FastAPI(
servers=[
{"url": "/", "description": "Default, relative server"},
{
"url": "http://staging.localhost.tiangolo.com:8000",
"description": "Staging but actually localhost still",
},
{"url": "https://prod.example.com"},
]
)
@app.get("/foo")
def foo():
return {"message": "Hello World"}
client = TestClient(app)
def test_app():
response = client.get("/foo")
assert response.status_code == 200, response.text
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"servers": [
{"url": "/", "description": "Default, relative server"},
{
"url": "http://staging.localhost.tiangolo.com:8000",
"description": "Staging but actually localhost still",
},
{"url": "https://prod.example.com"},
],
"paths": {
"/foo": {
"get": {
"summary": "Foo",
"operationId": "foo_foo_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
}
},
}
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_generic_parameterless_depends.py | tests/test_generic_parameterless_depends.py | from typing import Annotated, TypeVar
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
T = TypeVar("T")
Dep = Annotated[T, Depends()]
class A:
pass
class B:
pass
@app.get("/a")
async def a(dep: Dep[A]):
return {"cls": dep.__class__.__name__}
@app.get("/b")
async def b(dep: Dep[B]):
return {"cls": dep.__class__.__name__}
client = TestClient(app)
def test_generic_parameterless_depends():
response = client.get("/a")
assert response.status_code == 200, response.text
assert response.json() == {"cls": "A"}
response = client.get("/b")
assert response.status_code == 200, response.text
assert response.json() == {"cls": "B"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"info": {"title": "FastAPI", "version": "0.1.0"},
"openapi": "3.1.0",
"paths": {
"/a": {
"get": {
"operationId": "a_a_get",
"responses": {
"200": {
"content": {"application/json": {"schema": {}}},
"description": "Successful Response",
}
},
"summary": "A",
}
},
"/b": {
"get": {
"operationId": "b_b_get",
"responses": {
"200": {
"content": {"application/json": {"schema": {}}},
"description": "Successful Response",
}
},
"summary": "B",
}
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_union_forms.py | tests/test_union_forms.py | from typing import Annotated, Union
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class UserForm(BaseModel):
name: str
email: str
class CompanyForm(BaseModel):
company_name: str
industry: str
@app.post("/form-union/")
def post_union_form(data: Annotated[Union[UserForm, CompanyForm], Form()]):
return {"received": data}
client = TestClient(app)
def test_post_user_form():
response = client.post(
"/form-union/", data={"name": "John Doe", "email": "john@example.com"}
)
assert response.status_code == 200, response.text
assert response.json() == {
"received": {"name": "John Doe", "email": "john@example.com"}
}
def test_post_company_form():
response = client.post(
"/form-union/", data={"company_name": "Tech Corp", "industry": "Technology"}
)
assert response.status_code == 200, response.text
assert response.json() == {
"received": {"company_name": "Tech Corp", "industry": "Technology"}
}
def test_invalid_form_data():
response = client.post(
"/form-union/",
data={"name": "John", "company_name": "Tech Corp"},
)
assert response.status_code == 422, response.text
def test_empty_form():
response = client.post("/form-union/")
assert response.status_code == 422, response.text
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/form-union/": {
"post": {
"summary": "Post Union Form",
"operationId": "post_union_form_form_union__post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"anyOf": [
{"$ref": "#/components/schemas/UserForm"},
{"$ref": "#/components/schemas/CompanyForm"},
],
"title": "Data",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"CompanyForm": {
"properties": {
"company_name": {"type": "string", "title": "Company Name"},
"industry": {"type": "string", "title": "Industry"},
},
"type": "object",
"required": ["company_name", "industry"],
"title": "CompanyForm",
},
"HTTPValidationError": {
"properties": {
"detail": {
"items": {"$ref": "#/components/schemas/ValidationError"},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"UserForm": {
"properties": {
"name": {"type": "string", "title": "Name"},
"email": {"type": "string", "title": "Email"},
},
"type": "object",
"required": ["name", "email"],
"title": "UserForm",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_multi_body_errors.py | tests/test_multi_body_errors.py | from decimal import Decimal
from dirty_equals import IsOneOf
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, condecimal
app = FastAPI()
class Item(BaseModel):
name: str
age: condecimal(gt=Decimal(0.0)) # type: ignore
@app.post("/items/")
def save_item_no_body(item: list[Item]):
return {"item": item}
client = TestClient(app)
def test_put_correct_body():
response = client.post("/items/", json=[{"name": "Foo", "age": 5}])
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"item": [
{
"name": "Foo",
"age": "5",
}
]
}
)
def test_jsonable_encoder_requiring_error():
response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}])
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "greater_than",
"loc": ["body", 0, "age"],
"msg": "Input should be greater than 0",
"input": -1.0,
"ctx": {"gt": 0},
}
]
}
def test_put_incorrect_body_multiple():
response = client.post("/items/", json=[{"age": "five"}, {"age": "six"}])
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", 0, "name"],
"msg": "Field required",
"input": {"age": "five"},
},
{
"type": "decimal_parsing",
"loc": ["body", 0, "age"],
"msg": "Input should be a valid decimal",
"input": "five",
},
{
"type": "missing",
"loc": ["body", 1, "name"],
"msg": "Field required",
"input": {"age": "six"},
},
{
"type": "decimal_parsing",
"loc": ["body", 1, "age"],
"msg": "Input should be a valid decimal",
"input": "six",
},
]
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Save Item No Body",
"operationId": "save_item_no_body_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"title": "Item",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "age"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"age": {
"title": "Age",
"anyOf": [
{"exclusiveMinimum": 0.0, "type": "number"},
IsOneOf(
# pydantic < 2.12.0
{"type": "string"},
# pydantic >= 2.12.0
{
"type": "string",
"pattern": r"^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$",
},
),
],
},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_paramless.py | tests/test_dependency_paramless.py | from typing import Annotated, Union
from fastapi import FastAPI, HTTPException, Security
from fastapi.security import (
OAuth2PasswordBearer,
SecurityScopes,
)
from fastapi.testclient import TestClient
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def process_auth(
credentials: Annotated[Union[str, None], Security(oauth2_scheme)],
security_scopes: SecurityScopes,
):
# This is an incorrect way of using it, this is not checking if the scopes are
# provided by the token, only if the endpoint is requesting them, but the test
# here is just to check if FastAPI is indeed registering and passing the scopes
# correctly when using Security with parameterless dependencies.
if "a" not in security_scopes.scopes or "b" not in security_scopes.scopes:
raise HTTPException(detail="a or b not in scopes", status_code=401)
return {"token": credentials, "scopes": security_scopes.scopes}
@app.get("/get-credentials")
def get_credentials(
credentials: Annotated[dict, Security(process_auth, scopes=["a", "b"])],
):
return credentials
@app.get(
"/parameterless-with-scopes",
dependencies=[Security(process_auth, scopes=["a", "b"])],
)
def get_parameterless_with_scopes():
return {"status": "ok"}
@app.get(
"/parameterless-without-scopes",
dependencies=[Security(process_auth)],
)
def get_parameterless_without_scopes():
return {"status": "ok"}
client = TestClient(app)
def test_get_credentials():
response = client.get("/get-credentials", headers={"authorization": "Bearer token"})
assert response.status_code == 200, response.text
assert response.json() == {"token": "token", "scopes": ["a", "b"]}
def test_parameterless_with_scopes():
response = client.get(
"/parameterless-with-scopes", headers={"authorization": "Bearer token"}
)
assert response.status_code == 200, response.text
assert response.json() == {"status": "ok"}
def test_parameterless_without_scopes():
response = client.get(
"/parameterless-without-scopes", headers={"authorization": "Bearer token"}
)
assert response.status_code == 401, response.text
assert response.json() == {"detail": "a or b not in scopes"}
def test_call_get_parameterless_without_scopes_for_coverage():
assert get_parameterless_without_scopes() == {"status": "ok"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_responses_response_class.py | tests/test_additional_responses_response_class.py | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class JsonApiResponse(JSONResponse):
media_type = "application/vnd.api+json"
class Error(BaseModel):
status: str
title: str
class JsonApiError(BaseModel):
errors: list[Error]
@app.get(
"/a",
response_class=JsonApiResponse,
responses={500: {"description": "Error", "model": JsonApiError}},
)
async def a():
pass # pragma: no cover
@app.get("/b", responses={500: {"description": "Error", "model": Error}})
async def b():
pass # pragma: no cover
client = TestClient(app)
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/a": {
"get": {
"responses": {
"500": {
"description": "Error",
"content": {
"application/vnd.api+json": {
"schema": {
"$ref": "#/components/schemas/JsonApiError"
}
}
},
},
"200": {
"description": "Successful Response",
"content": {"application/vnd.api+json": {"schema": {}}},
},
},
"summary": "A",
"operationId": "a_a_get",
}
},
"/b": {
"get": {
"responses": {
"500": {
"description": "Error",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Error"}
}
},
},
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
},
"summary": "B",
"operationId": "b_b_get",
}
},
},
"components": {
"schemas": {
"Error": {
"title": "Error",
"required": ["status", "title"],
"type": "object",
"properties": {
"status": {"title": "Status", "type": "string"},
"title": {"title": "Title", "type": "string"},
},
},
"JsonApiError": {
"title": "JsonApiError",
"required": ["errors"],
"type": "object",
"properties": {
"errors": {
"title": "Errors",
"type": "array",
"items": {"$ref": "#/components/schemas/Error"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_union_body_discriminator.py | tests/test_union_body_discriminator.py | from typing import Annotated, Any, Union
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, Field
from typing_extensions import Literal
def test_discriminator_pydantic_v2() -> None:
from pydantic import Tag
app = FastAPI()
class FirstItem(BaseModel):
value: Literal["first"]
price: int
class OtherItem(BaseModel):
value: Literal["other"]
price: float
Item = Annotated[
Union[Annotated[FirstItem, Tag("first")], Annotated[OtherItem, Tag("other")]],
Field(discriminator="value"),
]
@app.post("/items/")
def save_union_body_discriminator(
item: Item, q: Annotated[str, Field(description="Query string")]
) -> dict[str, Any]:
return {"item": item}
client = TestClient(app)
response = client.post("/items/?q=first", json={"value": "first", "price": 100})
assert response.status_code == 200, response.text
assert response.json() == {"item": {"value": "first", "price": 100}}
response = client.post("/items/?q=other", json={"value": "other", "price": 100.5})
assert response.status_code == 200, response.text
assert response.json() == {"item": {"value": "other", "price": 100.5}}
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"summary": "Save Union Body Discriminator",
"operationId": "save_union_body_discriminator_items__post",
"parameters": [
{
"name": "q",
"in": "query",
"required": True,
"schema": {
"type": "string",
"description": "Query string",
"title": "Q",
},
}
],
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"oneOf": [
{"$ref": "#/components/schemas/FirstItem"},
{"$ref": "#/components/schemas/OtherItem"},
],
"discriminator": {
"propertyName": "value",
"mapping": {
"first": "#/components/schemas/FirstItem",
"other": "#/components/schemas/OtherItem",
},
},
"title": "Item",
}
}
},
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": True,
"title": "Response Save Union Body Discriminator Items Post",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"FirstItem": {
"properties": {
"value": {
"type": "string",
"const": "first",
"title": "Value",
},
"price": {"type": "integer", "title": "Price"},
},
"type": "object",
"required": ["value", "price"],
"title": "FirstItem",
},
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"OtherItem": {
"properties": {
"value": {
"type": "string",
"const": "other",
"title": "Value",
},
"price": {"type": "number", "title": "Price"},
},
"type": "object",
"required": ["value", "price"],
"title": "OtherItem",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_body_parameters_media_type.py | tests/test_request_body_parameters_media_type.py | from fastapi import Body, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
media_type = "application/vnd.api+json"
# NOTE: These are not valid JSON:API resources
# but they are fine for testing requestBody with custom media_type
class Product(BaseModel):
name: str
price: float
class Shop(BaseModel):
name: str
@app.post("/products")
async def create_product(data: Product = Body(media_type=media_type, embed=True)):
pass # pragma: no cover
@app.post("/shops")
async def create_shop(
data: Shop = Body(media_type=media_type),
included: list[Product] = Body(default=[], media_type=media_type),
):
pass # pragma: no cover
client = TestClient(app)
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/products": {
"post": {
"summary": "Create Product",
"operationId": "create_product_products_post",
"requestBody": {
"content": {
"application/vnd.api+json": {
"schema": {
"$ref": "#/components/schemas/Body_create_product_products_post"
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/shops": {
"post": {
"summary": "Create Shop",
"operationId": "create_shop_shops_post",
"requestBody": {
"content": {
"application/vnd.api+json": {
"schema": {
"$ref": "#/components/schemas/Body_create_shop_shops_post"
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
},
"components": {
"schemas": {
"Body_create_product_products_post": {
"title": "Body_create_product_products_post",
"required": ["data"],
"type": "object",
"properties": {"data": {"$ref": "#/components/schemas/Product"}},
},
"Body_create_shop_shops_post": {
"title": "Body_create_shop_shops_post",
"required": ["data"],
"type": "object",
"properties": {
"data": {"$ref": "#/components/schemas/Shop"},
"included": {
"title": "Included",
"type": "array",
"items": {"$ref": "#/components/schemas/Product"},
"default": [],
},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"Product": {
"title": "Product",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
},
},
"Shop": {
"title": "Shop",
"required": ["name"],
"type": "object",
"properties": {"name": {"title": "Name", "type": "string"}},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_duplicates.py | tests/test_dependency_duplicates.py | from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
client = TestClient(app)
class Item(BaseModel):
data: str
def duplicate_dependency(item: Item):
return item
def dependency(item2: Item):
return item2
def sub_duplicate_dependency(
item: Item, sub_item: Item = Depends(duplicate_dependency)
):
return [item, sub_item]
@app.post("/with-duplicates")
async def with_duplicates(item: Item, item2: Item = Depends(duplicate_dependency)):
return [item, item2]
@app.post("/no-duplicates")
async def no_duplicates(item: Item, item2: Item = Depends(dependency)):
return [item, item2]
@app.post("/with-duplicates-sub")
async def no_duplicates_sub(
item: Item, sub_items: list[Item] = Depends(sub_duplicate_dependency)
):
return [item, sub_items]
def test_no_duplicates_invalid():
response = client.post("/no-duplicates", json={"item": {"data": "myitem"}})
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "item2"],
"msg": "Field required",
"input": None,
}
]
}
def test_no_duplicates():
response = client.post(
"/no-duplicates",
json={"item": {"data": "myitem"}, "item2": {"data": "myitem2"}},
)
assert response.status_code == 200, response.text
assert response.json() == [{"data": "myitem"}, {"data": "myitem2"}]
def test_duplicates():
response = client.post("/with-duplicates", json={"data": "myitem"})
assert response.status_code == 200, response.text
assert response.json() == [{"data": "myitem"}, {"data": "myitem"}]
def test_sub_duplicates():
response = client.post("/with-duplicates-sub", json={"data": "myitem"})
assert response.status_code == 200, response.text
assert response.json() == [
{"data": "myitem"},
[{"data": "myitem"}, {"data": "myitem"}],
]
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/with-duplicates": {
"post": {
"summary": "With Duplicates",
"operationId": "with_duplicates_with_duplicates_post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/no-duplicates": {
"post": {
"summary": "No Duplicates",
"operationId": "no_duplicates_no_duplicates_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Body_no_duplicates_no_duplicates_post"
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/with-duplicates-sub": {
"post": {
"summary": "No Duplicates Sub",
"operationId": "no_duplicates_sub_with_duplicates_sub_post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
},
"components": {
"schemas": {
"Body_no_duplicates_no_duplicates_post": {
"title": "Body_no_duplicates_no_duplicates_post",
"required": ["item", "item2"],
"type": "object",
"properties": {
"item": {"$ref": "#/components/schemas/Item"},
"item2": {"$ref": "#/components/schemas/Item"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"Item": {
"title": "Item",
"required": ["data"],
"type": "object",
"properties": {"data": {"title": "Data", "type": "string"}},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_yield_scope_websockets.py | tests/test_dependency_yield_scope_websockets.py | from contextvars import ContextVar
from typing import Annotated, Any
import pytest
from fastapi import Depends, FastAPI, WebSocket
from fastapi.exceptions import FastAPIError
from fastapi.testclient import TestClient
global_context: ContextVar[dict[str, Any]] = ContextVar("global_context", default={}) # noqa: B039
class Session:
def __init__(self) -> None:
self.open = True
async def dep_session() -> Any:
s = Session()
yield s
s.open = False
global_state = global_context.get()
global_state["session_closed"] = True
SessionFuncDep = Annotated[Session, Depends(dep_session, scope="function")]
SessionRequestDep = Annotated[Session, Depends(dep_session, scope="request")]
SessionDefaultDep = Annotated[Session, Depends(dep_session)]
class NamedSession:
def __init__(self, name: str = "default") -> None:
self.name = name
self.open = True
def get_named_session(session: SessionRequestDep, session_b: SessionDefaultDep) -> Any:
assert session is session_b
named_session = NamedSession(name="named")
yield named_session, session_b
named_session.open = False
global_state = global_context.get()
global_state["named_session_closed"] = True
NamedSessionsDep = Annotated[tuple[NamedSession, Session], Depends(get_named_session)]
def get_named_func_session(session: SessionFuncDep) -> Any:
named_session = NamedSession(name="named")
yield named_session, session
named_session.open = False
global_state = global_context.get()
global_state["named_func_session_closed"] = True
def get_named_regular_func_session(session: SessionFuncDep) -> Any:
named_session = NamedSession(name="named")
return named_session, session
BrokenSessionsDep = Annotated[
tuple[NamedSession, Session], Depends(get_named_func_session)
]
NamedSessionsFuncDep = Annotated[
tuple[NamedSession, Session], Depends(get_named_func_session, scope="function")
]
RegularSessionsDep = Annotated[
tuple[NamedSession, Session], Depends(get_named_regular_func_session)
]
app = FastAPI()
@app.websocket("/function-scope")
async def function_scope(websocket: WebSocket, session: SessionFuncDep) -> Any:
await websocket.accept()
await websocket.send_json({"is_open": session.open})
@app.websocket("/request-scope")
async def request_scope(websocket: WebSocket, session: SessionRequestDep) -> Any:
await websocket.accept()
await websocket.send_json({"is_open": session.open})
@app.websocket("/two-scopes")
async def get_stream_session(
websocket: WebSocket,
function_session: SessionFuncDep,
request_session: SessionRequestDep,
) -> Any:
await websocket.accept()
await websocket.send_json(
{"func_is_open": function_session.open, "req_is_open": request_session.open}
)
@app.websocket("/sub")
async def get_sub(websocket: WebSocket, sessions: NamedSessionsDep) -> Any:
await websocket.accept()
await websocket.send_json(
{"named_session_open": sessions[0].open, "session_open": sessions[1].open}
)
@app.websocket("/named-function-scope")
async def get_named_function_scope(
websocket: WebSocket, sessions: NamedSessionsFuncDep
) -> Any:
await websocket.accept()
await websocket.send_json(
{"named_session_open": sessions[0].open, "session_open": sessions[1].open}
)
@app.websocket("/regular-function-scope")
async def get_regular_function_scope(
websocket: WebSocket, sessions: RegularSessionsDep
) -> Any:
await websocket.accept()
await websocket.send_json(
{"named_session_open": sessions[0].open, "session_open": sessions[1].open}
)
client = TestClient(app)
def test_function_scope() -> None:
global_context.set({})
global_state = global_context.get()
with client.websocket_connect("/function-scope") as websocket:
data = websocket.receive_json()
assert data["is_open"] is True
assert global_state["session_closed"] is True
def test_request_scope() -> None:
global_context.set({})
global_state = global_context.get()
with client.websocket_connect("/request-scope") as websocket:
data = websocket.receive_json()
assert data["is_open"] is True
assert global_state["session_closed"] is True
def test_two_scopes() -> None:
global_context.set({})
global_state = global_context.get()
with client.websocket_connect("/two-scopes") as websocket:
data = websocket.receive_json()
assert data["func_is_open"] is True
assert data["req_is_open"] is True
assert global_state["session_closed"] is True
def test_sub() -> None:
global_context.set({})
global_state = global_context.get()
with client.websocket_connect("/sub") as websocket:
data = websocket.receive_json()
assert data["named_session_open"] is True
assert data["session_open"] is True
assert global_state["session_closed"] is True
assert global_state["named_session_closed"] is True
def test_broken_scope() -> None:
with pytest.raises(
FastAPIError,
match='The dependency "get_named_func_session" has a scope of "request", it cannot depend on dependencies with scope "function"',
):
@app.websocket("/broken-scope")
async def get_broken(
websocket: WebSocket, sessions: BrokenSessionsDep
) -> Any: # pragma: no cover
pass
def test_named_function_scope() -> None:
global_context.set({})
global_state = global_context.get()
with client.websocket_connect("/named-function-scope") as websocket:
data = websocket.receive_json()
assert data["named_session_open"] is True
assert data["session_open"] is True
assert global_state["session_closed"] is True
assert global_state["named_func_session_closed"] is True
def test_regular_function_scope() -> None:
global_context.set({})
global_state = global_context.get()
with client.websocket_connect("/regular-function-scope") as websocket:
data = websocket.receive_json()
assert data["named_session_open"] is True
assert data["session_open"] is True
assert global_state["session_closed"] is True
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_arbitrary_types.py | tests/test_arbitrary_types.py | from typing import Annotated
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
@pytest.fixture(name="client")
def get_client():
from pydantic import (
BaseModel,
ConfigDict,
PlainSerializer,
TypeAdapter,
WithJsonSchema,
)
class FakeNumpyArray:
def __init__(self):
self.data = [1.0, 2.0, 3.0]
FakeNumpyArrayPydantic = Annotated[
FakeNumpyArray,
WithJsonSchema(TypeAdapter(list[float]).json_schema()),
PlainSerializer(lambda v: v.data),
]
class MyModel(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
custom_field: FakeNumpyArrayPydantic
app = FastAPI()
@app.get("/")
def test() -> MyModel:
return MyModel(custom_field=FakeNumpyArray())
client = TestClient(app)
return client
def test_get(client: TestClient):
response = client.get("/")
assert response.json() == {"custom_field": [1.0, 2.0, 3.0]}
def test_typeadapter():
# This test is only to confirm that Pydantic alone is working as expected
from pydantic import (
BaseModel,
ConfigDict,
PlainSerializer,
TypeAdapter,
WithJsonSchema,
)
class FakeNumpyArray:
def __init__(self):
self.data = [1.0, 2.0, 3.0]
FakeNumpyArrayPydantic = Annotated[
FakeNumpyArray,
WithJsonSchema(TypeAdapter(list[float]).json_schema()),
PlainSerializer(lambda v: v.data),
]
class MyModel(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
custom_field: FakeNumpyArrayPydantic
ta = TypeAdapter(MyModel)
assert ta.dump_python(MyModel(custom_field=FakeNumpyArray())) == {
"custom_field": [1.0, 2.0, 3.0]
}
assert ta.json_schema() == snapshot(
{
"properties": {
"custom_field": {
"items": {"type": "number"},
"title": "Custom Field",
"type": "array",
}
},
"required": ["custom_field"],
"title": "MyModel",
"type": "object",
}
)
def test_openapi_schema(client: TestClient):
response = client.get("openapi.json")
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"get": {
"summary": "Test",
"operationId": "test__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/MyModel"
}
}
},
}
},
}
}
},
"components": {
"schemas": {
"MyModel": {
"properties": {
"custom_field": {
"items": {"type": "number"},
"type": "array",
"title": "Custom Field",
}
},
"type": "object",
"required": ["custom_field"],
"title": "MyModel",
}
}
},
}
)
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_response_extra.py | tests/test_additional_response_extra.py | from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
router = APIRouter()
sub_router = APIRouter()
app = FastAPI()
@sub_router.get("/")
def read_item():
return {"id": "foo"}
router.include_router(sub_router, prefix="/items")
app.include_router(router)
client = TestClient(app)
def test_path_operation():
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == {"id": "foo"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Item",
"operationId": "read_item_items__get",
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_union_body.py | tests/test_union_body.py | from typing import Optional, Union
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: Optional[str] = None
class OtherItem(BaseModel):
price: int
@app.post("/items/")
def save_union_body(item: Union[OtherItem, Item]):
return {"item": item}
client = TestClient(app)
def test_post_other_item():
response = client.post("/items/", json={"price": 100})
assert response.status_code == 200, response.text
assert response.json() == {"item": {"price": 100}}
def test_post_item():
response = client.post("/items/", json={"name": "Foo"})
assert response.status_code == 200, response.text
assert response.json() == {"item": {"name": "Foo"}}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Save Union Body",
"operationId": "save_union_body_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"title": "Item",
"anyOf": [
{"$ref": "#/components/schemas/OtherItem"},
{"$ref": "#/components/schemas/Item"},
],
}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"OtherItem": {
"title": "OtherItem",
"required": ["price"],
"type": "object",
"properties": {"price": {"title": "Price", "type": "integer"}},
},
"Item": {
"title": "Item",
"type": "object",
"properties": {
"name": {
"title": "Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_no_swagger_ui_redirect.py | tests/test_no_swagger_ui_redirect.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI(swagger_ui_oauth2_redirect_url=None)
@app.get("/items/")
async def read_items():
return {"id": "foo"}
client = TestClient(app)
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "swagger-ui-dist" in response.text
print(client.base_url)
assert "oauth2RedirectUrl" not in response.text
def test_swagger_ui_no_oauth2_redirect():
response = client.get("/docs/oauth2-redirect")
assert response.status_code == 404, response.text
def test_response():
response = client.get("/items/")
assert response.json() == {"id": "foo"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_operations_signatures.py | tests/test_operations_signatures.py | import inspect
from fastapi import APIRouter, FastAPI
method_names = ["get", "put", "post", "delete", "options", "head", "patch", "trace"]
def test_signatures_consistency():
base_sig = inspect.signature(APIRouter.get)
for method_name in method_names:
router_method = getattr(APIRouter, method_name)
app_method = getattr(FastAPI, method_name)
router_sig = inspect.signature(router_method)
app_sig = inspect.signature(app_method)
param: inspect.Parameter
for key, param in base_sig.parameters.items():
router_param: inspect.Parameter = router_sig.parameters[key]
app_param: inspect.Parameter = app_sig.parameters[key]
assert param.annotation == router_param.annotation
assert param.annotation == app_param.annotation
assert param.default == router_param.default
assert param.default == app_param.default
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_callable_endpoint.py | tests/test_callable_endpoint.py | from functools import partial
from typing import Optional
from fastapi import FastAPI
from fastapi.testclient import TestClient
def main(some_arg, q: Optional[str] = None):
return {"some_arg": some_arg, "q": q}
endpoint = partial(main, "foo")
app = FastAPI()
app.get("/")(endpoint)
client = TestClient(app)
def test_partial():
response = client.get("/?q=bar")
data = response.json()
assert data == {"some_arg": "foo", "q": "bar"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_dependency_security_overrides.py | tests/test_dependency_security_overrides.py | from fastapi import Depends, FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
app = FastAPI()
def get_user(required_scopes: SecurityScopes):
return "john", required_scopes.scopes
def get_user_override(required_scopes: SecurityScopes):
return "alice", required_scopes.scopes
def get_data():
return [1, 2, 3]
def get_data_override():
return [3, 4, 5]
@app.get("/user")
def read_user(
user_data: tuple[str, list[str]] = Security(get_user, scopes=["foo", "bar"]),
data: list[int] = Depends(get_data),
):
return {"user": user_data[0], "scopes": user_data[1], "data": data}
client = TestClient(app)
def test_normal():
response = client.get("/user")
assert response.json() == {
"user": "john",
"scopes": ["foo", "bar"],
"data": [1, 2, 3],
}
def test_override_data():
app.dependency_overrides[get_data] = get_data_override
response = client.get("/user")
assert response.json() == {
"user": "john",
"scopes": ["foo", "bar"],
"data": [3, 4, 5],
}
app.dependency_overrides = {}
def test_override_security():
app.dependency_overrides[get_user] = get_user_override
response = client.get("/user")
assert response.json() == {
"user": "alice",
"scopes": ["foo", "bar"],
"data": [1, 2, 3],
}
app.dependency_overrides = {}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_path.py | tests/test_path.py | from fastapi.testclient import TestClient
from .main import app
client = TestClient(app)
def test_text_get():
response = client.get("/text")
assert response.status_code == 200, response.text
assert response.json() == "Hello World"
def test_nonexistent():
response = client.get("/nonexistent")
assert response.status_code == 404, response.text
assert response.json() == {"detail": "Not Found"}
def test_path_foobar():
response = client.get("/path/foobar")
assert response.status_code == 200
assert response.json() == "foobar"
def test_path_str_foobar():
response = client.get("/path/str/foobar")
assert response.status_code == 200
assert response.json() == "foobar"
def test_path_str_42():
response = client.get("/path/str/42")
assert response.status_code == 200
assert response.json() == "42"
def test_path_str_True():
response = client.get("/path/str/True")
assert response.status_code == 200
assert response.json() == "True"
def test_path_int_foobar():
response = client.get("/path/int/foobar")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foobar",
}
]
}
def test_path_int_True():
response = client.get("/path/int/True")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "True",
}
]
}
def test_path_int_42():
response = client.get("/path/int/42")
assert response.status_code == 200
assert response.json() == 42
def test_path_int_42_5():
response = client.get("/path/int/42.5")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "42.5",
}
]
}
def test_path_float_foobar():
response = client.get("/path/float/foobar")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "float_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "foobar",
}
]
}
def test_path_float_True():
response = client.get("/path/float/True")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "float_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "True",
}
]
}
def test_path_float_42():
response = client.get("/path/float/42")
assert response.status_code == 200
assert response.json() == 42
def test_path_float_42_5():
response = client.get("/path/float/42.5")
assert response.status_code == 200
assert response.json() == 42.5
def test_path_bool_foobar():
response = client.get("/path/bool/foobar")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "bool_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "foobar",
}
]
}
def test_path_bool_True():
response = client.get("/path/bool/True")
assert response.status_code == 200
assert response.json() is True
def test_path_bool_42():
response = client.get("/path/bool/42")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "bool_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "42",
}
]
}
def test_path_bool_42_5():
response = client.get("/path/bool/42.5")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "bool_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "42.5",
}
]
}
def test_path_bool_1():
response = client.get("/path/bool/1")
assert response.status_code == 200
assert response.json() is True
def test_path_bool_0():
response = client.get("/path/bool/0")
assert response.status_code == 200
assert response.json() is False
def test_path_bool_true():
response = client.get("/path/bool/true")
assert response.status_code == 200
assert response.json() is True
def test_path_bool_False():
response = client.get("/path/bool/False")
assert response.status_code == 200
assert response.json() is False
def test_path_bool_false():
response = client.get("/path/bool/false")
assert response.status_code == 200
assert response.json() is False
def test_path_param_foo():
response = client.get("/path/param/foo")
assert response.status_code == 200
assert response.json() == "foo"
def test_path_param_minlength_foo():
response = client.get("/path/param-minlength/foo")
assert response.status_code == 200
assert response.json() == "foo"
def test_path_param_minlength_fo():
response = client.get("/path/param-minlength/fo")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_too_short",
"loc": ["path", "item_id"],
"msg": "String should have at least 3 characters",
"input": "fo",
"ctx": {"min_length": 3},
}
]
}
def test_path_param_maxlength_foo():
response = client.get("/path/param-maxlength/foo")
assert response.status_code == 200
assert response.json() == "foo"
def test_path_param_maxlength_foobar():
response = client.get("/path/param-maxlength/foobar")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_too_long",
"loc": ["path", "item_id"],
"msg": "String should have at most 3 characters",
"input": "foobar",
"ctx": {"max_length": 3},
}
]
}
def test_path_param_min_maxlength_foo():
response = client.get("/path/param-min_maxlength/foo")
assert response.status_code == 200
assert response.json() == "foo"
def test_path_param_min_maxlength_foobar():
response = client.get("/path/param-min_maxlength/foobar")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_too_long",
"loc": ["path", "item_id"],
"msg": "String should have at most 3 characters",
"input": "foobar",
"ctx": {"max_length": 3},
}
]
}
def test_path_param_min_maxlength_f():
response = client.get("/path/param-min_maxlength/f")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_too_short",
"loc": ["path", "item_id"],
"msg": "String should have at least 2 characters",
"input": "f",
"ctx": {"min_length": 2},
}
]
}
def test_path_param_gt_42():
response = client.get("/path/param-gt/42")
assert response.status_code == 200
assert response.json() == 42
def test_path_param_gt_2():
response = client.get("/path/param-gt/2")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "greater_than",
"loc": ["path", "item_id"],
"msg": "Input should be greater than 3",
"input": "2",
"ctx": {"gt": 3.0},
}
]
}
def test_path_param_gt0_0_05():
response = client.get("/path/param-gt0/0.05")
assert response.status_code == 200
assert response.json() == 0.05
def test_path_param_gt0_0():
response = client.get("/path/param-gt0/0")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "greater_than",
"loc": ["path", "item_id"],
"msg": "Input should be greater than 0",
"input": "0",
"ctx": {"gt": 0.0},
}
]
}
def test_path_param_ge_42():
response = client.get("/path/param-ge/42")
assert response.status_code == 200
assert response.json() == 42
def test_path_param_ge_3():
response = client.get("/path/param-ge/3")
assert response.status_code == 200
assert response.json() == 3
def test_path_param_ge_2():
response = client.get("/path/param-ge/2")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "greater_than_equal",
"loc": ["path", "item_id"],
"msg": "Input should be greater than or equal to 3",
"input": "2",
"ctx": {"ge": 3.0},
}
]
}
def test_path_param_lt_42():
response = client.get("/path/param-lt/42")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than",
"loc": ["path", "item_id"],
"msg": "Input should be less than 3",
"input": "42",
"ctx": {"lt": 3.0},
}
]
}
def test_path_param_lt_2():
response = client.get("/path/param-lt/2")
assert response.status_code == 200
assert response.json() == 2
def test_path_param_lt0__1():
response = client.get("/path/param-lt0/-1")
assert response.status_code == 200
assert response.json() == -1
def test_path_param_lt0_0():
response = client.get("/path/param-lt0/0")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than",
"loc": ["path", "item_id"],
"msg": "Input should be less than 0",
"input": "0",
"ctx": {"lt": 0.0},
}
]
}
def test_path_param_le_42():
response = client.get("/path/param-le/42")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than_equal",
"loc": ["path", "item_id"],
"msg": "Input should be less than or equal to 3",
"input": "42",
"ctx": {"le": 3.0},
}
]
}
def test_path_param_le_3():
response = client.get("/path/param-le/3")
assert response.status_code == 200
assert response.json() == 3
def test_path_param_le_2():
response = client.get("/path/param-le/2")
assert response.status_code == 200
assert response.json() == 2
def test_path_param_lt_gt_2():
response = client.get("/path/param-lt-gt/2")
assert response.status_code == 200
assert response.json() == 2
def test_path_param_lt_gt_4():
response = client.get("/path/param-lt-gt/4")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than",
"loc": ["path", "item_id"],
"msg": "Input should be less than 3",
"input": "4",
"ctx": {"lt": 3.0},
}
]
}
def test_path_param_lt_gt_0():
response = client.get("/path/param-lt-gt/0")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "greater_than",
"loc": ["path", "item_id"],
"msg": "Input should be greater than 1",
"input": "0",
"ctx": {"gt": 1.0},
}
]
}
def test_path_param_le_ge_2():
response = client.get("/path/param-le-ge/2")
assert response.status_code == 200
assert response.json() == 2
def test_path_param_le_ge_1():
response = client.get("/path/param-le-ge/1")
assert response.status_code == 200
def test_path_param_le_ge_3():
response = client.get("/path/param-le-ge/3")
assert response.status_code == 200
assert response.json() == 3
def test_path_param_le_ge_4():
response = client.get("/path/param-le-ge/4")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than_equal",
"loc": ["path", "item_id"],
"msg": "Input should be less than or equal to 3",
"input": "4",
"ctx": {"le": 3.0},
}
]
}
def test_path_param_lt_int_2():
response = client.get("/path/param-lt-int/2")
assert response.status_code == 200
assert response.json() == 2
def test_path_param_lt_int_42():
response = client.get("/path/param-lt-int/42")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than",
"loc": ["path", "item_id"],
"msg": "Input should be less than 3",
"input": "42",
"ctx": {"lt": 3},
}
]
}
def test_path_param_lt_int_2_7():
response = client.get("/path/param-lt-int/2.7")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
}
]
}
def test_path_param_gt_int_42():
response = client.get("/path/param-gt-int/42")
assert response.status_code == 200
assert response.json() == 42
def test_path_param_gt_int_2():
response = client.get("/path/param-gt-int/2")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "greater_than",
"loc": ["path", "item_id"],
"msg": "Input should be greater than 3",
"input": "2",
"ctx": {"gt": 3},
}
]
}
def test_path_param_gt_int_2_7():
response = client.get("/path/param-gt-int/2.7")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
}
]
}
def test_path_param_le_int_42():
response = client.get("/path/param-le-int/42")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than_equal",
"loc": ["path", "item_id"],
"msg": "Input should be less than or equal to 3",
"input": "42",
"ctx": {"le": 3},
}
]
}
def test_path_param_le_int_3():
response = client.get("/path/param-le-int/3")
assert response.status_code == 200
assert response.json() == 3
def test_path_param_le_int_2():
response = client.get("/path/param-le-int/2")
assert response.status_code == 200
assert response.json() == 2
def test_path_param_le_int_2_7():
response = client.get("/path/param-le-int/2.7")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
}
]
}
def test_path_param_ge_int_42():
response = client.get("/path/param-ge-int/42")
assert response.status_code == 200
assert response.json() == 42
def test_path_param_ge_int_3():
response = client.get("/path/param-ge-int/3")
assert response.status_code == 200
assert response.json() == 3
def test_path_param_ge_int_2():
response = client.get("/path/param-ge-int/2")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "greater_than_equal",
"loc": ["path", "item_id"],
"msg": "Input should be greater than or equal to 3",
"input": "2",
"ctx": {"ge": 3},
}
]
}
def test_path_param_ge_int_2_7():
response = client.get("/path/param-ge-int/2.7")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
}
]
}
def test_path_param_lt_gt_int_2():
response = client.get("/path/param-lt-gt-int/2")
assert response.status_code == 200
assert response.json() == 2
def test_path_param_lt_gt_int_4():
response = client.get("/path/param-lt-gt-int/4")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than",
"loc": ["path", "item_id"],
"msg": "Input should be less than 3",
"input": "4",
"ctx": {"lt": 3},
}
]
}
def test_path_param_lt_gt_int_0():
response = client.get("/path/param-lt-gt-int/0")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "greater_than",
"loc": ["path", "item_id"],
"msg": "Input should be greater than 1",
"input": "0",
"ctx": {"gt": 1},
}
]
}
def test_path_param_lt_gt_int_2_7():
response = client.get("/path/param-lt-gt-int/2.7")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
}
]
}
def test_path_param_le_ge_int_2():
response = client.get("/path/param-le-ge-int/2")
assert response.status_code == 200
assert response.json() == 2
def test_path_param_le_ge_int_1():
response = client.get("/path/param-le-ge-int/1")
assert response.status_code == 200
assert response.json() == 1
def test_path_param_le_ge_int_3():
response = client.get("/path/param-le-ge-int/3")
assert response.status_code == 200
assert response.json() == 3
def test_path_param_le_ge_int_4():
response = client.get("/path/param-le-ge-int/4")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "less_than_equal",
"loc": ["path", "item_id"],
"msg": "Input should be less than or equal to 3",
"input": "4",
"ctx": {"le": 3},
}
]
}
def test_path_param_le_ge_int_2_7():
response = client.get("/path/param-le-ge-int/2.7")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
}
]
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_model_invalid.py | tests/test_response_model_invalid.py | import pytest
from fastapi import FastAPI
from fastapi.exceptions import FastAPIError
class NonPydanticModel:
pass
def test_invalid_response_model_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", response_model=NonPydanticModel)
def read_root():
pass # pragma: nocover
def test_invalid_response_model_sub_type_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", response_model=list[NonPydanticModel])
def read_root():
pass # pragma: nocover
def test_invalid_response_model_in_responses_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", responses={"500": {"model": NonPydanticModel}})
def read_root():
pass # pragma: nocover
def test_invalid_response_model_sub_type_in_responses_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", responses={"500": {"model": list[NonPydanticModel]}})
def read_root():
pass # pragma: nocover
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_base_description.py | tests/test_security_http_base_description.py | from fastapi import FastAPI, Security
from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase
from fastapi.testclient import TestClient
app = FastAPI()
security = HTTPBase(scheme="Other", description="Other Security Scheme")
@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
return {"scheme": credentials.scheme, "credentials": credentials.credentials}
client = TestClient(app)
def test_security_http_base():
response = client.get("/users/me", headers={"Authorization": "Other foobar"})
assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Other", "credentials": "foobar"}
def test_security_http_base_no_credentials():
response = client.get("/users/me")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Other"
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"HTTPBase": []}],
}
}
},
"components": {
"securitySchemes": {
"HTTPBase": {
"type": "http",
"scheme": "Other",
"description": "Other Security Scheme",
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_openapi_route_extensions.py | tests/test_openapi_route_extensions.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/", openapi_extra={"x-custom-extension": "value"})
def route_with_extras():
return {}
client = TestClient(app)
def test_get_route():
response = client.get("/")
assert response.status_code == 200, response.text
assert response.json() == {}
def test_openapi():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
},
"summary": "Route With Extras",
"operationId": "route_with_extras__get",
"x-custom-extension": "value",
}
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_http_bearer_optional.py | tests/test_security_http_bearer_optional.py | from typing import Optional
from fastapi import FastAPI, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.testclient import TestClient
app = FastAPI()
security = HTTPBearer(auto_error=False)
@app.get("/users/me")
def read_current_user(
credentials: Optional[HTTPAuthorizationCredentials] = Security(security),
):
if credentials is None:
return {"msg": "Create an account first"}
return {"scheme": credentials.scheme, "credentials": credentials.credentials}
client = TestClient(app)
def test_security_http_bearer():
response = client.get("/users/me", headers={"Authorization": "Bearer foobar"})
assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Bearer", "credentials": "foobar"}
def test_security_http_bearer_no_credentials():
response = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_security_http_bearer_incorrect_scheme_credentials():
response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"HTTPBearer": []}],
}
}
},
"components": {
"securitySchemes": {"HTTPBearer": {"type": "http", "scheme": "bearer"}}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_inherited_custom_class.py | tests/test_inherited_custom_class.py | import uuid
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class MyUuid:
def __init__(self, uuid_string: str):
self.uuid = uuid_string
def __str__(self):
return self.uuid
@property # type: ignore
def __class__(self):
return uuid.UUID
@property
def __dict__(self):
"""Spoof a missing __dict__ by raising TypeError, this is how
asyncpg.pgroto.pgproto.UUID behaves"""
raise TypeError("vars() argument must have __dict__ attribute")
def test_pydanticv2():
from pydantic import field_serializer
app = FastAPI()
@app.get("/fast_uuid")
def return_fast_uuid():
asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51")
assert isinstance(asyncpg_uuid, uuid.UUID)
assert type(asyncpg_uuid) is not uuid.UUID
with pytest.raises(TypeError):
vars(asyncpg_uuid)
return {"fast_uuid": asyncpg_uuid}
class SomeCustomClass(BaseModel):
model_config = {"arbitrary_types_allowed": True}
a_uuid: MyUuid
@field_serializer("a_uuid")
def serialize_a_uuid(self, v):
return str(v)
@app.get("/get_custom_class")
def return_some_user():
# Test that the fix also works for custom pydantic classes
return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01"))
client = TestClient(app)
with client:
response_simple = client.get("/fast_uuid")
response_pydantic = client.get("/get_custom_class")
assert response_simple.json() == {
"fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51"
}
assert response_pydantic.json() == {
"a_uuid": "b8799909-f914-42de-91bc-95c819218d01"
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_router_redirect_slashes.py | tests/test_router_redirect_slashes.py | from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
def test_redirect_slashes_enabled():
app = FastAPI()
router = APIRouter()
@router.get("/hello/")
def hello_page() -> str:
return "Hello, World!"
app.include_router(router)
client = TestClient(app)
response = client.get("/hello/", follow_redirects=False)
assert response.status_code == 200
response = client.get("/hello", follow_redirects=False)
assert response.status_code == 307
def test_redirect_slashes_disabled():
app = FastAPI(redirect_slashes=False)
router = APIRouter()
@router.get("/hello/")
def hello_page() -> str:
return "Hello, World!"
app.include_router(router)
client = TestClient(app)
response = client.get("/hello/", follow_redirects=False)
assert response.status_code == 200
response = client.get("/hello", follow_redirects=False)
assert response.status_code == 404
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_duplicate_models_openapi.py | tests/test_duplicate_models_openapi.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Model(BaseModel):
pass
class Model2(BaseModel):
a: Model
class Model3(BaseModel):
c: Model
d: Model2
@app.get("/", response_model=Model3)
def f():
return {"c": {}, "d": {"a": {}}}
client = TestClient(app)
def test_get_api_route():
response = client.get("/")
assert response.status_code == 200, response.text
assert response.json() == {"c": {}, "d": {"a": {}}}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"get": {
"summary": "F",
"operationId": "f__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Model3"}
}
},
}
},
}
}
},
"components": {
"schemas": {
"Model": {"title": "Model", "type": "object", "properties": {}},
"Model2": {
"title": "Model2",
"required": ["a"],
"type": "object",
"properties": {"a": {"$ref": "#/components/schemas/Model"}},
},
"Model3": {
"title": "Model3",
"required": ["c", "d"],
"type": "object",
"properties": {
"c": {"$ref": "#/components/schemas/Model"},
"d": {"$ref": "#/components/schemas/Model2"},
},
},
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_query.py | tests/test_query.py | from fastapi.testclient import TestClient
from .main import app
client = TestClient(app)
def test_query():
response = client.get("/query")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
}
]
}
def test_query_query_baz():
response = client.get("/query?query=baz")
assert response.status_code == 200
assert response.json() == "foo bar baz"
def test_query_not_declared_baz():
response = client.get("/query?not_declared=baz")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
}
]
}
def test_query_optional():
response = client.get("/query/optional")
assert response.status_code == 200
assert response.json() == "foo bar"
def test_query_optional_query_baz():
response = client.get("/query/optional?query=baz")
assert response.status_code == 200
assert response.json() == "foo bar baz"
def test_query_optional_not_declared_baz():
response = client.get("/query/optional?not_declared=baz")
assert response.status_code == 200
assert response.json() == "foo bar"
def test_query_int():
response = client.get("/query/int")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
}
]
}
def test_query_int_query_42():
response = client.get("/query/int?query=42")
assert response.status_code == 200
assert response.json() == "foo bar 42"
def test_query_int_query_42_5():
response = client.get("/query/int?query=42.5")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "42.5",
}
]
}
def test_query_int_query_baz():
response = client.get("/query/int?query=baz")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "baz",
}
]
}
def test_query_int_not_declared_baz():
response = client.get("/query/int?not_declared=baz")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
}
]
}
def test_query_int_optional():
response = client.get("/query/int/optional")
assert response.status_code == 200
assert response.json() == "foo bar"
def test_query_int_optional_query_50():
response = client.get("/query/int/optional?query=50")
assert response.status_code == 200
assert response.json() == "foo bar 50"
def test_query_int_optional_query_foo():
response = client.get("/query/int/optional?query=foo")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
}
]
}
def test_query_int_default():
response = client.get("/query/int/default")
assert response.status_code == 200
assert response.json() == "foo bar 10"
def test_query_int_default_query_50():
response = client.get("/query/int/default?query=50")
assert response.status_code == 200
assert response.json() == "foo bar 50"
def test_query_int_default_query_foo():
response = client.get("/query/int/default?query=foo")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
}
]
}
def test_query_param():
response = client.get("/query/param")
assert response.status_code == 200
assert response.json() == "foo bar"
def test_query_param_query_50():
response = client.get("/query/param?query=50")
assert response.status_code == 200
assert response.json() == "foo bar 50"
def test_query_param_required():
response = client.get("/query/param-required")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
}
]
}
def test_query_param_required_query_50():
response = client.get("/query/param-required?query=50")
assert response.status_code == 200
assert response.json() == "foo bar 50"
def test_query_param_required_int():
response = client.get("/query/param-required/int")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
}
]
}
def test_query_param_required_int_query_50():
response = client.get("/query/param-required/int?query=50")
assert response.status_code == 200
assert response.json() == "foo bar 50"
def test_query_param_required_int_query_foo():
response = client.get("/query/param-required/int?query=foo")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "int_parsing",
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
}
]
}
def test_query_frozenset_query_1_query_1_query_2():
response = client.get("/query/frozenset/?query=1&query=1&query=2")
assert response.status_code == 200
assert response.json() == "1,2"
def test_query_list():
response = client.get("/query/list/?device_ids=1&device_ids=2")
assert response.status_code == 200
assert response.json() == [1, 2]
def test_query_list_empty():
response = client.get("/query/list/")
assert response.status_code == 422
def test_query_list_default():
response = client.get("/query/list-default/?device_ids=1&device_ids=2")
assert response.status_code == 200
assert response.json() == [1, 2]
def test_query_list_default_empty():
response = client.get("/query/list-default/")
assert response.status_code == 200
assert response.json() == []
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_additional_responses_bad.py | tests/test_additional_responses_bad.py | import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/a", responses={"hello": {"description": "Not a valid additional response"}})
async def a():
pass # pragma: no cover
openapi_schema = {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/a": {
"get": {
"responses": {
# this is how one would imagine the openapi schema to be
# but since the key is not valid, openapi.utils.get_openapi will raise ValueError
"hello": {"description": "Not a valid additional response"},
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
},
"summary": "A",
"operationId": "a_a_get",
}
}
},
}
client = TestClient(app)
def test_openapi_schema():
with pytest.raises(ValueError):
client.get("/openapi.json")
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_ws_dependencies.py | tests/test_ws_dependencies.py | import json
from typing import Annotated
from fastapi import APIRouter, Depends, FastAPI, WebSocket
from fastapi.testclient import TestClient
def dependency_list() -> list[str]:
return []
DepList = Annotated[list[str], Depends(dependency_list)]
def create_dependency(name: str):
def fun(deps: DepList):
deps.append(name)
return Depends(fun)
router = APIRouter(dependencies=[create_dependency("router")])
prefix_router = APIRouter(dependencies=[create_dependency("prefix_router")])
app = FastAPI(dependencies=[create_dependency("app")])
@app.websocket("/", dependencies=[create_dependency("index")])
async def index(websocket: WebSocket, deps: DepList):
await websocket.accept()
await websocket.send_text(json.dumps(deps))
await websocket.close()
@router.websocket("/router", dependencies=[create_dependency("routerindex")])
async def routerindex(websocket: WebSocket, deps: DepList):
await websocket.accept()
await websocket.send_text(json.dumps(deps))
await websocket.close()
@prefix_router.websocket("/", dependencies=[create_dependency("routerprefixindex")])
async def routerprefixindex(websocket: WebSocket, deps: DepList):
await websocket.accept()
await websocket.send_text(json.dumps(deps))
await websocket.close()
app.include_router(router, dependencies=[create_dependency("router2")])
app.include_router(
prefix_router, prefix="/prefix", dependencies=[create_dependency("prefix_router2")]
)
def test_index():
client = TestClient(app)
with client.websocket_connect("/") as websocket:
data = json.loads(websocket.receive_text())
assert data == ["app", "index"]
def test_routerindex():
client = TestClient(app)
with client.websocket_connect("/router") as websocket:
data = json.loads(websocket.receive_text())
assert data == ["app", "router2", "router", "routerindex"]
def test_routerprefixindex():
client = TestClient(app)
with client.websocket_connect("/prefix/") as websocket:
data = json.loads(websocket.receive_text())
assert data == ["app", "prefix_router2", "prefix_router", "routerprefixindex"]
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_serialize_response_dataclass.py | tests/test_serialize_response_dataclass.py | from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@dataclass
class Item:
name: str
date: datetime
price: Optional[float] = None
owner_ids: Optional[list[int]] = None
@app.get("/items/valid", response_model=Item)
def get_valid():
return {"name": "valid", "date": datetime(2021, 7, 26), "price": 1.0}
@app.get("/items/object", response_model=Item)
def get_object():
return Item(
name="object", date=datetime(2021, 7, 26), price=1.0, owner_ids=[1, 2, 3]
)
@app.get("/items/coerce", response_model=Item)
def get_coerce():
return {"name": "coerce", "date": datetime(2021, 7, 26).isoformat(), "price": "1.0"}
@app.get("/items/validlist", response_model=list[Item])
def get_validlist():
return [
{"name": "foo", "date": datetime(2021, 7, 26)},
{"name": "bar", "date": datetime(2021, 7, 26), "price": 1.0},
{
"name": "baz",
"date": datetime(2021, 7, 26),
"price": 2.0,
"owner_ids": [1, 2, 3],
},
]
@app.get("/items/objectlist", response_model=list[Item])
def get_objectlist():
return [
Item(name="foo", date=datetime(2021, 7, 26)),
Item(name="bar", date=datetime(2021, 7, 26), price=1.0),
Item(name="baz", date=datetime(2021, 7, 26), price=2.0, owner_ids=[1, 2, 3]),
]
@app.get("/items/no-response-model/object")
def get_no_response_model_object():
return Item(
name="object", date=datetime(2021, 7, 26), price=1.0, owner_ids=[1, 2, 3]
)
@app.get("/items/no-response-model/objectlist")
def get_no_response_model_objectlist():
return [
Item(name="foo", date=datetime(2021, 7, 26)),
Item(name="bar", date=datetime(2021, 7, 26), price=1.0),
Item(name="baz", date=datetime(2021, 7, 26), price=2.0, owner_ids=[1, 2, 3]),
]
client = TestClient(app)
def test_valid():
response = client.get("/items/valid")
response.raise_for_status()
assert response.json() == {
"name": "valid",
"date": datetime(2021, 7, 26).isoformat(),
"price": 1.0,
"owner_ids": None,
}
def test_object():
response = client.get("/items/object")
response.raise_for_status()
assert response.json() == {
"name": "object",
"date": datetime(2021, 7, 26).isoformat(),
"price": 1.0,
"owner_ids": [1, 2, 3],
}
def test_coerce():
response = client.get("/items/coerce")
response.raise_for_status()
assert response.json() == {
"name": "coerce",
"date": datetime(2021, 7, 26).isoformat(),
"price": 1.0,
"owner_ids": None,
}
def test_validlist():
response = client.get("/items/validlist")
response.raise_for_status()
assert response.json() == [
{
"name": "foo",
"date": datetime(2021, 7, 26).isoformat(),
"price": None,
"owner_ids": None,
},
{
"name": "bar",
"date": datetime(2021, 7, 26).isoformat(),
"price": 1.0,
"owner_ids": None,
},
{
"name": "baz",
"date": datetime(2021, 7, 26).isoformat(),
"price": 2.0,
"owner_ids": [1, 2, 3],
},
]
def test_objectlist():
response = client.get("/items/objectlist")
response.raise_for_status()
assert response.json() == [
{
"name": "foo",
"date": datetime(2021, 7, 26).isoformat(),
"price": None,
"owner_ids": None,
},
{
"name": "bar",
"date": datetime(2021, 7, 26).isoformat(),
"price": 1.0,
"owner_ids": None,
},
{
"name": "baz",
"date": datetime(2021, 7, 26).isoformat(),
"price": 2.0,
"owner_ids": [1, 2, 3],
},
]
def test_no_response_model_object():
response = client.get("/items/no-response-model/object")
response.raise_for_status()
assert response.json() == {
"name": "object",
"date": datetime(2021, 7, 26).isoformat(),
"price": 1.0,
"owner_ids": [1, 2, 3],
}
def test_no_response_model_objectlist():
response = client.get("/items/no-response-model/objectlist")
response.raise_for_status()
assert response.json() == [
{
"name": "foo",
"date": datetime(2021, 7, 26).isoformat(),
"price": None,
"owner_ids": None,
},
{
"name": "bar",
"date": datetime(2021, 7, 26).isoformat(),
"price": 1.0,
"owner_ids": None,
},
{
"name": "baz",
"date": datetime(2021, 7, 26).isoformat(),
"price": 2.0,
"owner_ids": [1, 2, 3],
},
]
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_application.py | tests/test_application.py | import pytest
from fastapi.testclient import TestClient
from .main import app
client = TestClient(app)
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
("/api_route", 200, {"message": "Hello World"}),
("/non_decorated_route", 200, {"message": "Hello World"}),
("/nonexistent", 404, {"detail": "Not Found"}),
],
)
def test_get_path(path, expected_status, expected_response):
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_swagger_ui():
response = client.get("/docs")
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "swagger-ui-dist" in response.text
assert (
"oauth2RedirectUrl: window.location.origin + '/docs/oauth2-redirect'"
in response.text
)
def test_swagger_ui_oauth2_redirect():
response = client.get("/docs/oauth2-redirect")
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "window.opener.swaggerUIRedirectOauth2" in response.text
def test_redoc():
response = client.get("/redoc")
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "redoc@2" in response.text
def test_enum_status_code_response():
response = client.get("/enum-status-code")
assert response.status_code == 201, response.text
assert response.json() == "foo bar"
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"externalDocs": {
"description": "External API documentation.",
"url": "https://docs.example.com/api-general",
},
"paths": {
"/api_route": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Non Operation",
"operationId": "non_operation_api_route_get",
}
},
"/non_decorated_route": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Non Decorated Route",
"operationId": "non_decorated_route_non_decorated_route_get",
}
},
"/text": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Get Text",
"operationId": "get_text_text_get",
}
},
"/path/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Id",
"operationId": "get_id_path__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id"},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/str/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Str Id",
"operationId": "get_str_id_path_str__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/int/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Int Id",
"operationId": "get_int_id_path_int__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "integer"},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/float/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Float Id",
"operationId": "get_float_id_path_float__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "number"},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/bool/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Bool Id",
"operationId": "get_bool_id_path_bool__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "boolean"},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Id",
"operationId": "get_path_param_id_path_param__item_id__get",
"parameters": [
{
"name": "item_id",
"in": "path",
"required": True,
"schema": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Item Id",
},
}
],
}
},
"/path/param-minlength/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Min Length",
"operationId": "get_path_param_min_length_path_param_minlength__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"minLength": 3,
"type": "string",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-maxlength/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Max Length",
"operationId": "get_path_param_max_length_path_param_maxlength__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"maxLength": 3,
"type": "string",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-min_maxlength/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Min Max Length",
"operationId": "get_path_param_min_max_length_path_param_min_maxlength__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"maxLength": 3,
"minLength": 2,
"type": "string",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-gt/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Gt",
"operationId": "get_path_param_gt_path_param_gt__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"exclusiveMinimum": 3.0,
"type": "number",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-gt0/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Gt0",
"operationId": "get_path_param_gt0_path_param_gt0__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"exclusiveMinimum": 0.0,
"type": "number",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-ge/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Ge",
"operationId": "get_path_param_ge_path_param_ge__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"minimum": 3.0,
"type": "number",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-lt/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Lt",
"operationId": "get_path_param_lt_path_param_lt__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"exclusiveMaximum": 3.0,
"type": "number",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-lt0/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Lt0",
"operationId": "get_path_param_lt0_path_param_lt0__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"exclusiveMaximum": 0.0,
"type": "number",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-le/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Le",
"operationId": "get_path_param_le_path_param_le__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"maximum": 3.0,
"type": "number",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-lt-gt/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Lt Gt",
"operationId": "get_path_param_lt_gt_path_param_lt_gt__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"exclusiveMaximum": 3.0,
"exclusiveMinimum": 1.0,
"type": "number",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-le-ge/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Le Ge",
"operationId": "get_path_param_le_ge_path_param_le_ge__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"maximum": 3.0,
"minimum": 1.0,
"type": "number",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-lt-int/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Lt Int",
"operationId": "get_path_param_lt_int_path_param_lt_int__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"exclusiveMaximum": 3.0,
"type": "integer",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-gt-int/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Gt Int",
"operationId": "get_path_param_gt_int_path_param_gt_int__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"exclusiveMinimum": 3.0,
"type": "integer",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-le-int/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Le Int",
"operationId": "get_path_param_le_int_path_param_le_int__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"maximum": 3.0,
"type": "integer",
},
"name": "item_id",
"in": "path",
}
],
}
},
"/path/param-ge-int/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Path Param Ge Int",
"operationId": "get_path_param_ge_int_path_param_ge_int__item_id__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Item Id",
"minimum": 3.0,
"type": "integer",
},
"name": "item_id",
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | true |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_model_sub_types.py | tests/test_response_model_sub_types.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Model(BaseModel):
name: str
app = FastAPI()
@app.get("/valid1", responses={"500": {"model": int}})
def valid1():
pass
@app.get("/valid2", responses={"500": {"model": list[int]}})
def valid2():
pass
@app.get("/valid3", responses={"500": {"model": Model}})
def valid3():
pass
@app.get("/valid4", responses={"500": {"model": list[Model]}})
def valid4():
pass
client = TestClient(app)
def test_path_operations():
response = client.get("/valid1")
assert response.status_code == 200, response.text
response = client.get("/valid2")
assert response.status_code == 200, response.text
response = client.get("/valid3")
assert response.status_code == 200, response.text
response = client.get("/valid4")
assert response.status_code == 200, response.text
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/valid1": {
"get": {
"summary": "Valid1",
"operationId": "valid1_valid1_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"500": {
"description": "Internal Server Error",
"content": {
"application/json": {
"schema": {
"title": "Response 500 Valid1 Valid1 Get",
"type": "integer",
}
}
},
},
},
}
},
"/valid2": {
"get": {
"summary": "Valid2",
"operationId": "valid2_valid2_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"500": {
"description": "Internal Server Error",
"content": {
"application/json": {
"schema": {
"title": "Response 500 Valid2 Valid2 Get",
"type": "array",
"items": {"type": "integer"},
}
}
},
},
},
}
},
"/valid3": {
"get": {
"summary": "Valid3",
"operationId": "valid3_valid3_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"500": {
"description": "Internal Server Error",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Model"}
}
},
},
},
}
},
"/valid4": {
"get": {
"summary": "Valid4",
"operationId": "valid4_valid4_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"500": {
"description": "Internal Server Error",
"content": {
"application/json": {
"schema": {
"title": "Response 500 Valid4 Valid4 Get",
"type": "array",
"items": {"$ref": "#/components/schemas/Model"},
}
}
},
},
},
}
},
},
"components": {
"schemas": {
"Model": {
"title": "Model",
"required": ["name"],
"type": "object",
"properties": {"name": {"title": "Name", "type": "string"}},
}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_response_model_default_factory.py | tests/test_response_model_default_factory.py | from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class ResponseModel(BaseModel):
code: int = 200
message: str = Field(default_factory=lambda: "Successful operation.")
@app.get(
"/response_model_has_default_factory_return_dict",
response_model=ResponseModel,
)
async def response_model_has_default_factory_return_dict():
return {"code": 200}
@app.get(
"/response_model_has_default_factory_return_model",
response_model=ResponseModel,
)
async def response_model_has_default_factory_return_model():
return ResponseModel()
client = TestClient(app)
def test_response_model_has_default_factory_return_dict():
response = client.get("/response_model_has_default_factory_return_dict")
assert response.status_code == 200, response.text
assert response.json()["code"] == 200
assert response.json()["message"] == "Successful operation."
def test_response_model_has_default_factory_return_model():
response = client.get("/response_model_has_default_factory_return_model")
assert response.status_code == 200, response.text
assert response.json()["code"] == 200
assert response.json()["message"] == "Successful operation."
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_api_key_query_optional.py | tests/test_security_api_key_query_optional.py | from typing import Optional
from fastapi import Depends, FastAPI, Security
from fastapi.security import APIKeyQuery
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyQuery(name="key", auto_error=False)
class User(BaseModel):
username: str
def get_current_user(oauth_header: Optional[str] = Security(api_key)):
if oauth_header is None:
return None
user = User(username=oauth_header)
return user
@app.get("/users/me")
def read_current_user(current_user: Optional[User] = Depends(get_current_user)):
if current_user is None:
return {"msg": "Create an account first"}
return current_user
client = TestClient(app)
def test_security_api_key():
response = client.get("/users/me?key=secret")
assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"APIKeyQuery": []}],
}
}
},
"components": {
"securitySchemes": {
"APIKeyQuery": {"type": "apiKey", "name": "key", "in": "query"}
}
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_security_oauth2_optional_description.py | tests/test_security_oauth2_optional_description.py | from typing import Optional
import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
reusable_oauth2 = OAuth2(
flows={
"password": {
"tokenUrl": "token",
"scopes": {"read:users": "Read the users", "write:users": "Create users"},
}
},
description="OAuth2 security scheme",
auto_error=False,
)
class User(BaseModel):
username: str
def get_current_user(oauth_header: Optional[str] = Security(reusable_oauth2)):
if oauth_header is None:
return None
user = User(username=oauth_header)
return user
@app.post("/login")
def login(form_data: OAuth2PasswordRequestFormStrict = Depends()):
return form_data
@app.get("/users/me")
def read_users_me(current_user: Optional[User] = Depends(get_current_user)):
if current_user is None:
return {"msg": "Create an account first"}
return current_user
client = TestClient(app)
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
assert response.status_code == 200, response.text
assert response.json() == {"username": "Other footokenbar"}
def test_security_oauth2_password_bearer_no_header():
response = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_strict_login_None():
response = client.post("/login", data=None)
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
},
]
}
def test_strict_login_no_grant_type():
response = client.post("/login", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "missing",
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
}
]
}
@pytest.mark.parametrize(
argnames=["grant_type"],
argvalues=[
pytest.param("incorrect", id="incorrect value"),
pytest.param("passwordblah", id="password with suffix"),
pytest.param("blahpassword", id="password with prefix"),
],
)
def test_strict_login_incorrect_grant_type(grant_type: str):
response = client.post(
"/login",
data={"username": "johndoe", "password": "secret", "grant_type": grant_type},
)
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"type": "string_pattern_mismatch",
"loc": ["body", "grant_type"],
"msg": "String should match pattern '^password$'",
"input": grant_type,
"ctx": {"pattern": "^password$"},
}
]
}
def test_strict_login_correct_correct_grant_type():
response = client.post(
"/login",
data={"username": "johndoe", "password": "secret", "grant_type": "password"},
)
assert response.status_code == 200, response.text
assert response.json() == {
"grant_type": "password",
"username": "johndoe",
"password": "secret",
"scopes": [],
"client_id": None,
"client_secret": None,
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/login": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Login",
"operationId": "login_login_post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_login_login_post"
}
}
},
"required": True,
},
}
},
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Users Me",
"operationId": "read_users_me_users_me_get",
"security": [{"OAuth2": []}],
}
},
},
"components": {
"schemas": {
"Body_login_login_post": {
"title": "Body_login_login_post",
"required": ["grant_type", "username", "password"],
"type": "object",
"properties": {
"grant_type": {
"title": "Grant Type",
"pattern": "^password$",
"type": "string",
},
"username": {"title": "Username", "type": "string"},
"password": {"title": "Password", "type": "string"},
"scope": {"title": "Scope", "type": "string", "default": ""},
"client_id": {
"title": "Client Id",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"client_secret": {
"title": "Client Secret",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
},
"securitySchemes": {
"OAuth2": {
"type": "oauth2",
"flows": {
"password": {
"scopes": {
"read:users": "Read the users",
"write:users": "Create users",
},
"tokenUrl": "token",
}
},
"description": "OAuth2 security scheme",
}
},
},
}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_datetime_custom_encoder.py | tests/test_datetime_custom_encoder.py | from datetime import datetime, timezone
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
def test_pydanticv2():
from pydantic import field_serializer
class ModelWithDatetimeField(BaseModel):
dt_field: datetime
@field_serializer("dt_field")
def serialize_datetime(self, dt_field: datetime):
return dt_field.replace(microsecond=0, tzinfo=timezone.utc).isoformat()
app = FastAPI()
model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8))
@app.get("/model", response_model=ModelWithDatetimeField)
def get_model():
return model
client = TestClient(app)
with client:
response = client.get("/model")
assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_include_router_defaults_overrides.py | tests/test_include_router_defaults_overrides.py | import warnings
import pytest
from fastapi import APIRouter, Depends, FastAPI, Response
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
class ResponseLevel0(JSONResponse):
media_type = "application/x-level-0"
class ResponseLevel1(JSONResponse):
media_type = "application/x-level-1"
class ResponseLevel2(JSONResponse):
media_type = "application/x-level-2"
class ResponseLevel3(JSONResponse):
media_type = "application/x-level-3"
class ResponseLevel4(JSONResponse):
media_type = "application/x-level-4"
class ResponseLevel5(JSONResponse):
media_type = "application/x-level-5"
async def dep0(response: Response):
response.headers["x-level0"] = "True"
async def dep1(response: Response):
response.headers["x-level1"] = "True"
async def dep2(response: Response):
response.headers["x-level2"] = "True"
async def dep3(response: Response):
response.headers["x-level3"] = "True"
async def dep4(response: Response):
response.headers["x-level4"] = "True"
async def dep5(response: Response):
response.headers["x-level5"] = "True"
callback_router0 = APIRouter()
@callback_router0.get("/")
async def callback0(level0: str):
pass # pragma: nocover
callback_router1 = APIRouter()
@callback_router1.get("/")
async def callback1(level1: str):
pass # pragma: nocover
callback_router2 = APIRouter()
@callback_router2.get("/")
async def callback2(level2: str):
pass # pragma: nocover
callback_router3 = APIRouter()
@callback_router3.get("/")
async def callback3(level3: str):
pass # pragma: nocover
callback_router4 = APIRouter()
@callback_router4.get("/")
async def callback4(level4: str):
pass # pragma: nocover
callback_router5 = APIRouter()
@callback_router5.get("/")
async def callback5(level5: str):
pass # pragma: nocover
app = FastAPI(
dependencies=[Depends(dep0)],
responses={
400: {"description": "Client error level 0"},
500: {"description": "Server error level 0"},
},
default_response_class=ResponseLevel0,
callbacks=callback_router0.routes,
)
router2_override = APIRouter(
prefix="/level2",
tags=["level2a", "level2b"],
dependencies=[Depends(dep2)],
responses={
402: {"description": "Client error level 2"},
502: {"description": "Server error level 2"},
},
default_response_class=ResponseLevel2,
callbacks=callback_router2.routes,
deprecated=True,
)
router2_default = APIRouter()
router4_override = APIRouter(
prefix="/level4",
tags=["level4a", "level4b"],
dependencies=[Depends(dep4)],
responses={
404: {"description": "Client error level 4"},
504: {"description": "Server error level 4"},
},
default_response_class=ResponseLevel4,
callbacks=callback_router4.routes,
deprecated=True,
)
router4_default = APIRouter()
@app.get(
"/override1",
tags=["path1a", "path1b"],
responses={
401: {"description": "Client error level 1"},
501: {"description": "Server error level 1"},
},
deprecated=True,
callbacks=callback_router1.routes,
dependencies=[Depends(dep1)],
response_class=ResponseLevel1,
)
async def path1_override(level1: str):
return level1
@app.get("/default1")
async def path1_default(level1: str):
return level1
@router2_override.get(
"/override3",
tags=["path3a", "path3b"],
responses={
403: {"description": "Client error level 3"},
503: {"description": "Server error level 3"},
},
deprecated=True,
callbacks=callback_router3.routes,
dependencies=[Depends(dep3)],
response_class=ResponseLevel3,
)
async def path3_override_router2_override(level3: str):
return level3
@router2_override.get("/default3")
async def path3_default_router2_override(level3: str):
return level3
@router2_default.get(
"/override3",
tags=["path3a", "path3b"],
responses={
403: {"description": "Client error level 3"},
503: {"description": "Server error level 3"},
},
deprecated=True,
callbacks=callback_router3.routes,
dependencies=[Depends(dep3)],
response_class=ResponseLevel3,
)
async def path3_override_router2_default(level3: str):
return level3
@router2_default.get("/default3")
async def path3_default_router2_default(level3: str):
return level3
@router4_override.get(
"/override5",
tags=["path5a", "path5b"],
responses={
405: {"description": "Client error level 5"},
505: {"description": "Server error level 5"},
},
deprecated=True,
callbacks=callback_router5.routes,
dependencies=[Depends(dep5)],
response_class=ResponseLevel5,
)
async def path5_override_router4_override(level5: str):
return level5
@router4_override.get(
"/default5",
)
async def path5_default_router4_override(level5: str):
return level5
@router4_default.get(
"/override5",
tags=["path5a", "path5b"],
responses={
405: {"description": "Client error level 5"},
505: {"description": "Server error level 5"},
},
deprecated=True,
callbacks=callback_router5.routes,
dependencies=[Depends(dep5)],
response_class=ResponseLevel5,
)
async def path5_override_router4_default(level5: str):
return level5
@router4_default.get(
"/default5",
)
async def path5_default_router4_default(level5: str):
return level5
router2_override.include_router(
router4_override,
prefix="/level3",
tags=["level3a", "level3b"],
dependencies=[Depends(dep3)],
responses={
403: {"description": "Client error level 3"},
503: {"description": "Server error level 3"},
},
default_response_class=ResponseLevel3,
callbacks=callback_router3.routes,
)
router2_override.include_router(
router4_default,
prefix="/level3",
tags=["level3a", "level3b"],
dependencies=[Depends(dep3)],
responses={
403: {"description": "Client error level 3"},
503: {"description": "Server error level 3"},
},
default_response_class=ResponseLevel3,
callbacks=callback_router3.routes,
)
router2_override.include_router(router4_override)
router2_override.include_router(router4_default)
router2_default.include_router(
router4_override,
prefix="/level3",
tags=["level3a", "level3b"],
dependencies=[Depends(dep3)],
responses={
403: {"description": "Client error level 3"},
503: {"description": "Server error level 3"},
},
default_response_class=ResponseLevel3,
callbacks=callback_router3.routes,
)
router2_default.include_router(
router4_default,
prefix="/level3",
tags=["level3a", "level3b"],
dependencies=[Depends(dep3)],
responses={
403: {"description": "Client error level 3"},
503: {"description": "Server error level 3"},
},
default_response_class=ResponseLevel3,
callbacks=callback_router3.routes,
)
router2_default.include_router(router4_override)
router2_default.include_router(router4_default)
app.include_router(
router2_override,
prefix="/level1",
tags=["level1a", "level1b"],
dependencies=[Depends(dep1)],
responses={
401: {"description": "Client error level 1"},
501: {"description": "Server error level 1"},
},
default_response_class=ResponseLevel1,
callbacks=callback_router1.routes,
)
app.include_router(
router2_default,
prefix="/level1",
tags=["level1a", "level1b"],
dependencies=[Depends(dep1)],
responses={
401: {"description": "Client error level 1"},
501: {"description": "Server error level 1"},
},
default_response_class=ResponseLevel1,
callbacks=callback_router1.routes,
)
app.include_router(router2_override)
app.include_router(router2_default)
client = TestClient(app)
def test_level1_override():
response = client.get("/override1?level1=foo")
assert response.json() == "foo"
assert response.headers["content-type"] == "application/x-level-1"
assert "x-level0" in response.headers
assert "x-level1" in response.headers
assert "x-level2" not in response.headers
assert "x-level3" not in response.headers
assert "x-level4" not in response.headers
assert "x-level5" not in response.headers
def test_level1_default():
response = client.get("/default1?level1=foo")
assert response.json() == "foo"
assert response.headers["content-type"] == "application/x-level-0"
assert "x-level0" in response.headers
assert "x-level1" not in response.headers
assert "x-level2" not in response.headers
assert "x-level3" not in response.headers
assert "x-level4" not in response.headers
assert "x-level5" not in response.headers
@pytest.mark.parametrize("override1", [True, False])
@pytest.mark.parametrize("override2", [True, False])
@pytest.mark.parametrize("override3", [True, False])
def test_paths_level3(override1, override2, override3):
url = ""
content_type_level = "0"
if override1:
url += "/level1"
content_type_level = "1"
if override2:
url += "/level2"
content_type_level = "2"
if override3:
url += "/override3"
content_type_level = "3"
else:
url += "/default3"
url += "?level3=foo"
response = client.get(url)
assert response.json() == "foo"
assert (
response.headers["content-type"] == f"application/x-level-{content_type_level}"
)
assert "x-level0" in response.headers
assert not override1 or "x-level1" in response.headers
assert not override2 or "x-level2" in response.headers
assert not override3 or "x-level3" in response.headers
@pytest.mark.parametrize("override1", [True, False])
@pytest.mark.parametrize("override2", [True, False])
@pytest.mark.parametrize("override3", [True, False])
@pytest.mark.parametrize("override4", [True, False])
@pytest.mark.parametrize("override5", [True, False])
def test_paths_level5(override1, override2, override3, override4, override5):
url = ""
content_type_level = "0"
if override1:
url += "/level1"
content_type_level = "1"
if override2:
url += "/level2"
content_type_level = "2"
if override3:
url += "/level3"
content_type_level = "3"
if override4:
url += "/level4"
content_type_level = "4"
if override5:
url += "/override5"
content_type_level = "5"
else:
url += "/default5"
url += "?level5=foo"
response = client.get(url)
assert response.json() == "foo"
assert (
response.headers["content-type"] == f"application/x-level-{content_type_level}"
)
assert "x-level0" in response.headers
assert not override1 or "x-level1" in response.headers
assert not override2 or "x-level2" in response.headers
assert not override3 or "x-level3" in response.headers
assert not override4 or "x-level4" in response.headers
assert not override5 or "x-level5" in response.headers
def test_openapi():
client = TestClient(app)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
response = client.get("/openapi.json")
assert issubclass(w[-1].category, UserWarning)
assert "Duplicate Operation ID" in str(w[-1].message)
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/override1": {
"get": {
"tags": ["path1a", "path1b"],
"summary": "Path1 Override",
"operationId": "path1_override_override1_get",
"parameters": [
{
"required": True,
"schema": {"title": "Level1", "type": "string"},
"name": "level1",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/x-level-1": {"schema": {}}},
},
"400": {"description": "Client error level 0"},
"401": {"description": "Client error level 1"},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
"500": {"description": "Server error level 0"},
"501": {"description": "Server error level 1"},
},
"callbacks": {
"callback0": {
"/": {
"get": {
"summary": "Callback0",
"operationId": "callback0__get",
"parameters": [
{
"name": "level0",
"in": "query",
"required": True,
"schema": {
"title": "Level0",
"type": "string",
},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"callback1": {
"/": {
"get": {
"summary": "Callback1",
"operationId": "callback1__get",
"parameters": [
{
"name": "level1",
"in": "query",
"required": True,
"schema": {
"title": "Level1",
"type": "string",
},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
},
"deprecated": True,
}
},
"/default1": {
"get": {
"summary": "Path1 Default",
"operationId": "path1_default_default1_get",
"parameters": [
{
"required": True,
"schema": {"title": "Level1", "type": "string"},
"name": "level1",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/x-level-0": {"schema": {}}},
},
"400": {"description": "Client error level 0"},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
"500": {"description": "Server error level 0"},
},
"callbacks": {
"callback0": {
"/": {
"get": {
"summary": "Callback0",
"operationId": "callback0__get",
"parameters": [
{
"name": "level0",
"in": "query",
"required": True,
"schema": {
"title": "Level0",
"type": "string",
},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
}
},
}
},
"/level1/level2/override3": {
"get": {
"tags": [
"level1a",
"level1b",
"level2a",
"level2b",
"path3a",
"path3b",
],
"summary": "Path3 Override Router2 Override",
"operationId": "path3_override_router2_override_level1_level2_override3_get",
"parameters": [
{
"required": True,
"schema": {"title": "Level3", "type": "string"},
"name": "level3",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/x-level-3": {"schema": {}}},
},
"400": {"description": "Client error level 0"},
"401": {"description": "Client error level 1"},
"402": {"description": "Client error level 2"},
"403": {"description": "Client error level 3"},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
"500": {"description": "Server error level 0"},
"501": {"description": "Server error level 1"},
"502": {"description": "Server error level 2"},
"503": {"description": "Server error level 3"},
},
"callbacks": {
"callback0": {
"/": {
"get": {
"summary": "Callback0",
"operationId": "callback0__get",
"parameters": [
{
"name": "level0",
"in": "query",
"required": True,
"schema": {
"title": "Level0",
"type": "string",
},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"callback1": {
"/": {
"get": {
"summary": "Callback1",
"operationId": "callback1__get",
"parameters": [
{
"name": "level1",
"in": "query",
"required": True,
"schema": {
"title": "Level1",
"type": "string",
},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"callback2": {
"/": {
"get": {
"summary": "Callback2",
"operationId": "callback2__get",
"parameters": [
{
"name": "level2",
"in": "query",
"required": True,
"schema": {
"title": "Level2",
"type": "string",
},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"callback3": {
"/": {
"get": {
"summary": "Callback3",
"operationId": "callback3__get",
"parameters": [
{
"name": "level3",
"in": "query",
"required": True,
"schema": {
"title": "Level3",
"type": "string",
},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
},
"deprecated": True,
}
},
"/level1/level2/default3": {
"get": {
"tags": ["level1a", "level1b", "level2a", "level2b"],
"summary": "Path3 Default Router2 Override",
"operationId": "path3_default_router2_override_level1_level2_default3_get",
"parameters": [
{
"required": True,
"schema": {"title": "Level3", "type": "string"},
"name": "level3",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/x-level-2": {"schema": {}}},
},
"400": {"description": "Client error level 0"},
"401": {"description": "Client error level 1"},
"402": {"description": "Client error level 2"},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
"500": {"description": "Server error level 0"},
"501": {"description": "Server error level 1"},
"502": {"description": "Server error level 2"},
},
"callbacks": {
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | true |
fastapi/fastapi | https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_datastructures.py | tests/test_datastructures.py | import io
from pathlib import Path
import pytest
from fastapi import FastAPI, UploadFile
from fastapi.datastructures import Default
from fastapi.testclient import TestClient
def test_upload_file_invalid_pydantic_v2():
with pytest.raises(ValueError):
UploadFile._validate("not a Starlette UploadFile", {})
def test_default_placeholder_equals():
placeholder_1 = Default("a")
placeholder_2 = Default("a")
assert placeholder_1 == placeholder_2
assert placeholder_1.value == placeholder_2.value
def test_default_placeholder_bool():
placeholder_a = Default("a")
placeholder_b = Default("")
assert placeholder_a
assert not placeholder_b
def test_upload_file_is_closed(tmp_path: Path):
path = tmp_path / "test.txt"
path.write_bytes(b"<file content>")
app = FastAPI()
testing_file_store: list[UploadFile] = []
@app.post("/uploadfile/")
def create_upload_file(file: UploadFile):
testing_file_store.append(file)
return {"filename": file.filename}
client = TestClient(app)
with path.open("rb") as file:
response = client.post("/uploadfile/", files={"file": file})
assert response.status_code == 200, response.text
assert response.json() == {"filename": "test.txt"}
assert testing_file_store
assert testing_file_store[0].file.closed
# For UploadFile coverage, segments copied from Starlette tests
@pytest.mark.anyio
async def test_upload_file():
stream = io.BytesIO(b"data")
file = UploadFile(filename="file", file=stream, size=4)
assert await file.read() == b"data"
assert file.size == 4
await file.write(b" and more data!")
assert await file.read() == b""
assert file.size == 19
await file.seek(0)
assert await file.read() == b"data and more data!"
await file.close()
| python | MIT | f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a | 2026-01-04T14:38:15.465144Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.