repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
sanic | guide/webapp/display/search/renderer.py | .py | from contextlib import contextmanager
from urllib.parse import unquote
from html5tagger import Builder, E # type: ignore
from sanic import Request
from webapp.display.search.search import Searcher
from ..base import BaseRenderer
from ..layouts.main import MainLayout
class SearchRenderer(BaseRenderer):
def ren... | 69 | 2,071 |
sanic | guide/webapp/display/search/search.py | .py | from __future__ import annotations
from collections import Counter
from pathlib import Path
from typing import ClassVar
from msgspec import Struct
from webapp.display.page import Page
class Stemmer:
STOP_WORDS: ClassVar[set[str]] = set(
"a about above after again against all am an and any are aren't as... | 177 | 6,128 |
sanic | guide/webapp/display/layouts/main.py | .py | from collections.abc import Generator
from contextlib import contextmanager
from sanic import Request
from webapp.display.layouts.elements.footer import do_footer
from webapp.display.layouts.elements.navbar import do_navbar
from webapp.display.layouts.elements.sidebar import do_sidebar
from .base import BaseLayout
... | 56 | 1,897 |
sanic | guide/webapp/display/layouts/models.py | .py | from __future__ import annotations
from msgspec import Struct, field
class MenuItem(Struct, kw_only=False, omit_defaults=True):
label: str
path: str | None = None
href: str | None = None
items: list[MenuItem] = field(default_factory=list)
class GeneralConfig(Struct, kw_only=False):
current_vers... | 15 | 329 |
sanic | guide/webapp/display/layouts/home.py | .py | from __future__ import annotations
from collections.abc import Generator
from contextlib import contextmanager
from html5tagger import Builder, E
from sanic import Request
from webapp.display.layouts.elements.footer import do_footer
from .base import BaseLayout
class HomeLayout(BaseLayout):
@contextmanager
... | 76 | 2,362 |
sanic | guide/webapp/display/layouts/base.py | .py | from __future__ import annotations
from collections.abc import Generator
from contextlib import contextmanager
from html5tagger import Builder
from sanic import Request
class BaseLayout:
def __init__(self, builder: Builder):
self.builder = builder
@contextmanager
def __call__(
self, re... | 27 | 606 |
sanic | guide/webapp/display/layouts/elements/footer.py | .py | from collections import deque
from datetime import datetime
from html5tagger import Builder, E # type: ignore
from sanic import Request
def do_footer(
builder: Builder,
request: Request,
extra_classes: str = "",
with_pagination: bool = True,
) -> None:
content = deque([_content()])
if with_... | 99 | 2,827 |
sanic | guide/webapp/display/layouts/elements/sidebar.py | .py | from html5tagger import Builder, E # type: ignore
from sanic import Request
from webapp.display.layouts.models import MenuItem
from webapp.display.text import slugify
def do_sidebar(builder: Builder, request: Request) -> None:
builder.a(class_="burger")(E.span().span().span().span())
builder.aside(*_menu_it... | 147 | 4,598 |
sanic | guide/webapp/display/layouts/elements/navbar.py | .py | from html5tagger import Builder, E # type: ignore
from sanic import Request
from webapp.display.layouts.models import MenuItem
def do_navbar(builder: Builder, request: Request) -> None:
navbar_items = [
_render_navbar_item(item, request)
for item in request.app.config.NAVBAR
]
container ... | 69 | 1,943 |
sanic | guide/webapp/display/page/renderer.py | .py | from __future__ import annotations
from contextlib import contextmanager
from html5tagger import HTML, Builder # type: ignore
from sanic import Request
from webapp.display.base import BaseRenderer
from ..layouts.base import BaseLayout
from .page import Page
class PageRenderer(BaseRenderer):
def render(self, ... | 60 | 2,007 |
sanic | guide/webapp/display/page/__init__.py | .py | from .page import Page
from .renderer import PageRenderer
__all__ = ["Page", "PageRenderer"]
| 6 | 95 |
sanic | guide/webapp/display/page/page.py | .py | from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from frontmatter import parse
from ..layouts.base import BaseLayout
from ..layouts.home import HomeLayout
from ..layouts.main import MainLayout
from ..markdown import render_markdown
from .docobject import organize_d... | 166 | 5,170 |
sanic | guide/webapp/display/page/docobject.py | .py | from __future__ import annotations
import importlib
import inspect
import pkgutil
from collections import defaultdict
from dataclasses import dataclass, field
from html import escape
from docstring_parser import Docstring, DocstringParam, DocstringRaises
from docstring_parser import parse as parse_docstring
from doc... | 414 | 13,840 |
sanic | guide/webapp/display/plugins/tabs.py | .py | from re import Match
from textwrap import dedent
from typing import Any
from mistune import HTMLRenderer
from mistune.block_parser import BlockParser
from mistune.core import BlockState
from mistune.directives import DirectivePlugin, RSTDirective
from mistune.markdown import Markdown
class Tabs(DirectivePlugin):
... | 55 | 1,562 |
sanic | guide/webapp/display/plugins/columns.py | .py | from re import Match
from textwrap import dedent
from typing import Any
from mistune import HTMLRenderer
from mistune.block_parser import BlockParser
from mistune.core import BlockState
from mistune.directives import DirectivePlugin, RSTDirective
from mistune.markdown import Markdown
class Column(DirectivePlugin):
... | 46 | 1,344 |
sanic | guide/webapp/display/plugins/span.py | .py | import re
from mistune.markdown import Markdown
def parse_inline_span(inline, m: re.Match, state):
state.append_token(
{
"type": "span",
"attrs": {"classes": m.group("classes")},
"raw": m.group("content"),
}
)
return m.end()
SPAN_PATTERN = r"{span:(?:... | 27 | 514 |
sanic | guide/webapp/display/plugins/inline_directive.py | .py | import re
from mistune.markdown import Markdown
DIRECTIVE_PATTERN = r":(?:class|func|meth|attr|exc|mod|data|const|obj|keyword|option|cmdoption|envvar):`(?P<ref>sanic\.[^`]+)`" # noqa: E501
def _parse_inline_directive(inline, m: re.Match, state):
state.append_token(
{
"type": "inline_direct... | 27 | 602 |
sanic | guide/webapp/display/plugins/hook.py | .py | from mistune.core import BlockState
from mistune.directives import DirectivePlugin, RSTDirective
from mistune.markdown import Markdown
class Hook(DirectivePlugin):
def __call__( # type: ignore
self, directive: RSTDirective, md: Markdown
) -> None:
if md.renderer.NAME == "html":
md... | 32 | 1,146 |
sanic | guide/webapp/display/plugins/notification.py | .py | from html5tagger import HTML, E
from mistune.directives import Admonition
class Notification(Admonition):
SUPPORTED_NAMES = {
"success",
"info",
"warning",
"danger",
"tip",
"new",
"note",
}
def __call__(self, directive, md):
for name in self... | 47 | 1,202 |
sanic | guide/webapp/display/plugins/mermaid.py | .py | from html import unescape
from re import Match
from textwrap import dedent
from typing import Any
from html5tagger import HTML, E
from mistune import HTMLRenderer
from mistune.block_parser import BlockParser
from mistune.core import BlockState
from mistune.directives import DirectivePlugin, RSTDirective
from mistune.m... | 41 | 1,224 |
sanic | guide/webapp/display/plugins/attrs.py | .py | from re import Match
from textwrap import dedent
from typing import Any
from html5tagger import HTML, E
from mistune.block_parser import BlockParser
from mistune.core import BlockState
from mistune.directives import DirectivePlugin
class Attributes(DirectivePlugin):
def __call__(self, directive, md):
dir... | 40 | 1,184 |
sanic | guide/webapp/endpoint/view.py | .py | from sanic import Blueprint
from .search import bp as search_bp
bp = Blueprint.group(search_bp)
| 7 | 99 |
sanic | guide/webapp/endpoint/sitemap.py | .py | from sanic import Request, Sanic, raw
def setup_sitemap(app: Sanic) -> None:
app.get("/sitemap.xml")(_sitemap)
app.before_server_start(_compile_sitemap, priority=0)
async def _compile_sitemap(app: Sanic):
pages: list[str] = [
app.url_for(
"page",
language="en",
... | 33 | 941 |
sanic | guide/webapp/endpoint/search.py | .py | # from urllib.parse import unquote
from sanic import Blueprint, Request, Sanic, html
from webapp.display.page import Page
from webapp.display.search.renderer import SearchRenderer
from webapp.display.search.search import Document, Searcher, Stemmer
bp = Blueprint("search", url_prefix="/<language>/search")
@bp.get(... | 30 | 908 |
sanic | guide/webapp/worker/reload.py | .py | from asyncio import sleep
from multiprocessing import Manager
from pathlib import Path
from queue import Empty, Queue
from typing import Any
import ujson
from sanic import Request, Sanic, Websocket
def setup_livereload(app: Sanic) -> None:
@app.main_process_start
async def main_process_start(app: Sanic):
... | 116 | 3,276 |
sanic | guide/webapp/worker/style.py | .py | # from scss.compiler import compile_string
from pygments.formatters import html
from sass import compile as compile_scss
from sanic import Sanic
from webapp.display.code_style import SanicCodeStyle
def setup_style(app: Sanic) -> None:
index = app.config.STYLE_DIR / "index.scss"
style_output = app.config.PUB... | 29 | 905 |
sanic | guide/webapp/worker/factory.py | .py | from pathlib import Path
from sanic import Request, Sanic, html, redirect
from webapp.display.layouts.models import MenuItem
from webapp.display.page import Page, PageRenderer
from webapp.endpoint.sitemap import setup_sitemap
from webapp.endpoint.view import bp
from webapp.worker.config import load_config, load_menu
f... | 111 | 3,891 |
sanic | guide/webapp/worker/config.py | .py | from pathlib import Path
from msgspec import yaml
from webapp.display.layouts.models import GeneralConfig, MenuItem
def load_menu(path: Path) -> list[MenuItem]:
loaded = yaml.decode(path.read_bytes(), type=dict[str, list[MenuItem]])
return loaded["root"]
def load_config(path: Path) -> GeneralConfig:
l... | 16 | 397 |
sanic | guide/content/en/emoji.py | .py | EMOJI = {
"1st_place_medal": "🥇",
"2nd_place_medal": "🥈",
"3rd_place_medal": "🥉",
"AB_button_(blood_type)": "🆎",
"ATM_sign": "🏧",
"A_button_(blood_type)": "🅰",
"Afghanistan": "🇦🇫",
"Albania": "🇦🇱",
"Algeria": "🇩🇿",
"American_Samoa": "🇦🇸",
"Andorra": "🇦🇩",
... | 3,905 | 169,279 |
sanic | guide/content/en/migrate.py | .py | import re
from pathlib import Path
from textwrap import indent
from emoji import EMOJI
COLUMN_PATTERN = re.compile(r"---:1\s*(.*?)\s*:--:1\s*(.*?)\s*:---", re.DOTALL)
PYTHON_HIGHLIGHT_PATTERN = re.compile(r"```python\{+.*?\}", re.DOTALL)
BASH_HIGHLIGHT_PATTERN = re.compile(r"```bash\{+.*?\}", re.DOTALL)
NOTIFICATIO... | 122 | 3,000 |
sanic | docs/conf.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Sanic documentation build configuration file, created by
# sphinx-quickstart on Sun Dec 25 18:07:21 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
import os
import sys
# Add support for auto-doc
# Ensure that sanic is pr... | 176 | 5,078 |
sanic | tests/test_pipelining.py | .py | from sanic_testing.reusable import ReusableClient
from sanic.response import json, text
def test_no_body_requests(app, port):
@app.get("/")
async def handler(request):
return json(
{
"request_id": str(request.id),
"connection_id": id(request.conn_info),
... | 101 | 2,999 |
sanic | tests/test_asgi.py | .py | import asyncio
import logging
from collections import deque, namedtuple
from unittest.mock import call
import pytest
import uvicorn
from httpx import Headers
from pytest import MonkeyPatch
from sanic import Sanic
from sanic.application.state import Mode
from sanic.asgi import Lifespan, MockTransport
from sanic.exce... | 677 | 18,191 |
sanic | tests/test_views.py | .py | import pytest
from sanic.blueprints import Blueprint
from sanic.constants import HTTP_METHODS
from sanic.request import Request
from sanic.response import HTTPResponse, text
from sanic.views import HTTPMethodView
@pytest.mark.parametrize("method", HTTP_METHODS)
def test_methods(app, method):
class DummyView(HTTP... | 225 | 5,955 |
sanic | tests/test_touchup.py | .py | import logging
import pytest
from sanic_routing.exceptions import NotFound
from sanic.signals import RESERVED_NAMESPACES
from sanic.touchup import TouchUp
def test_touchup_methods(app):
assert len(TouchUp._registry) == 9
@pytest.mark.parametrize(
"verbosity,result", ((0, False), (1, False), (2, True), (3... | 79 | 2,383 |
sanic | tests/test_late_adds.py | .py | import pytest
from sanic import Sanic, text
pytestmark = pytest.mark.xdist_group(name="process_spawning")
@pytest.fixture
def late_app(app: Sanic):
app.config.TOUCHUP = False
app.get("/")(lambda _: text(""))
return app
def test_late_route(late_app: Sanic):
@late_app.before_server_start
async ... | 58 | 1,413 |
sanic | tests/test_response.py | .py | import asyncio
import inspect
import os
import time
from collections import namedtuple
from datetime import datetime, timedelta
from email.utils import formatdate, parsedate_to_datetime
from logging import ERROR, LogRecord
from mimetypes import guess_type
from pathlib import Path
from random import choice
from typing ... | 1,005 | 33,025 |
sanic | tests/test_exceptions.py | .py | import logging
from itertools import count
import pytest
from bs4 import BeautifulSoup
from sanic import Sanic
from sanic.exceptions import (
BadRequest,
ContentRangeError,
ExpectationFailed,
Forbidden,
HeaderExpectationFailed,
InvalidUsage,
MethodNotAllowed,
MethodNotSupported,
... | 451 | 13,688 |
sanic | tests/test_static_directory.py | .py | import os
import tempfile
from pathlib import Path
import pytest
from sanic import Sanic
from sanic.handlers.directory import DirectoryHandler
pytestmark = pytest.mark.xdist_group(name="static_files")
def get_file_path(static_file_directory, file_name):
return os.path.join(static_file_directory, file_name)
... | 352 | 11,830 |
sanic | tests/test_tasks.py | .py | import asyncio
from asyncio.tasks import Task
from unittest.mock import Mock, call
import pytest
from sanic.app import Sanic
from sanic.application.state import ApplicationServerInfo, ServerStage
from sanic.response import empty
try:
from unittest.mock import AsyncMock
except ImportError:
from tests.asyncm... | 137 | 2,859 |
sanic | tests/test_bad_request.py | .py | import asyncio
from sanic import Sanic
def test_bad_request_response(app: Sanic):
lines = []
app.get("/")(lambda x: ...)
@app.listener("after_server_start")
async def _request(sanic, loop):
nonlocal lines
connect = asyncio.open_connection("127.0.0.1", 42101)
reader, writer =... | 27 | 708 |
sanic | tests/test_startup_errors.py | .py | import errno
import pytest
from sanic.exceptions import ServerError
from sanic.startup.errors import (
_handle_os_error,
_handle_server_error,
maybe_handle_startup_error,
)
def test_handle_os_error_address_in_use(caplog):
exc = OSError(errno.EADDRINUSE, "Address already in use")
result = _handle... | 81 | 2,201 |
sanic | tests/test_request_stream.py | .py | import asyncio
import pytest
from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import json, text
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
data = "abc" * 1_000_000
def test_request_stream_method_view(app):
class SimpleView(HTTPMe... | 624 | 18,128 |
sanic | tests/test_logging.py | .py | import logging
import sys
import uuid
from importlib import reload
from io import StringIO
from unittest.mock import ANY, Mock
import pytest
import sanic
from sanic import Sanic
from sanic.log import LOGGING_CONFIG_DEFAULTS, Colors, logger
from sanic.logging.formatter import (
AutoFormatter,
DebugAccessForm... | 303 | 8,424 |
sanic | tests/test_create_task.py | .py | import asyncio
from threading import Event
import pytest
from sanic.exceptions import SanicException
from sanic.response import text
def test_create_task(app):
e = Event()
async def coro():
await asyncio.sleep(0.05)
e.set()
@app.route("/early")
def not_set(request):
return... | 107 | 2,462 |
sanic | tests/asyncmock.py | .py | """
For 3.7 compat
"""
from unittest.mock import Mock
class AsyncMock(Mock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.await_count = 0
def __call__(self, *args, **kwargs):
self.call_count += 1
parent = super()
async def dummy():
... | 48 | 1,227 |
sanic | tests/test_vhosts.py | .py | import pytest
from sanic_routing.exceptions import RouteExists
from sanic import Sanic
from sanic.response import text
def test_vhosts():
app = Sanic("app")
@app.route("/", host="example.com")
async def handler1(request):
return text("You're at example.com!")
@app.route("/", host="subdomai... | 57 | 1,639 |
sanic | tests/test_versioning.py | .py | import pytest
from sanic import Blueprint, text
@pytest.fixture
def handler():
def handler(_):
return text("Done.")
return handler
def test_route(app, handler):
app.route("/", version=1)(handler)
_, response = app.test_client.get("/v1")
assert response.status == 200
def test_bp(app,... | 142 | 3,938 |
sanic | tests/test_daemon.py | .py | """Tests for daemon mode functionality."""
import os
import signal
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from sanic.cli.app import SanicCLI
from sanic.compat import OS_IS_WINDOWS
from sanic.worker.daemon import (
Daemon,
DaemonError,
PidfileInfo,
... | 1,263 | 36,364 |
sanic | tests/test_url_for_static.py | .py | import inspect
import os
import pytest
from sanic import Sanic
from sanic.blueprints import Blueprint
pytestmark = pytest.mark.xdist_group(name="static_files")
@pytest.fixture(scope="module")
def static_file_directory():
"""The static directory to serve"""
current_file = inspect.getfile(inspect.currentfra... | 491 | 16,385 |
sanic | tests/test_app.py | .py | import asyncio
import logging
import re
from collections import Counter
from inspect import isawaitable
from os import environ
from unittest.mock import Mock, patch
import pytest
import sanic
from sanic import Sanic
from sanic.compat import OS_IS_WINDOWS
from sanic.config import Config
from sanic.exceptions import ... | 675 | 18,538 |
sanic | tests/test_coffee.py | .py | import logging
from unittest.mock import patch
import pytest
from sanic.application.logo import COFFEE_LOGO, get_logo
from sanic.exceptions import SanicException
def has_sugar(value):
if value:
raise SanicException("I said no sugar please")
return False
@pytest.mark.parametrize("sugar", (True, F... | 49 | 1,178 |
sanic | tests/test_json_decoding.py | .py | from json import loads as sloads
import pytest
try:
from ujson import loads as uloads
NO_UJSON = False
DEFAULT_LOADS = uloads
except ModuleNotFoundError:
NO_UJSON = True
DEFAULT_LOADS = sloads
from sanic import Request, Sanic, json
@pytest.fixture(autouse=True)
def default_back_to_ujson():
... | 53 | 1,159 |
sanic | tests/test_request_cancel.py | .py | import asyncio
import contextlib
import pytest
from sanic.response import text
@pytest.mark.asyncio
async def test_request_cancel_when_connection_lost(app):
app.ctx.still_serving_cancelled_request = False
@app.get("/")
async def handler(request):
await asyncio.sleep(1.0)
# at this point... | 73 | 2,066 |
sanic | tests/test_config.py | .py | import logging
import os
from contextlib import contextmanager
from os import environ
from pathlib import Path
from tempfile import TemporaryDirectory
from textwrap import dedent
from unittest.mock import Mock, call
import pytest
from pytest import MonkeyPatch
from sanic import Sanic
from sanic.config import DEFAUL... | 505 | 14,176 |
sanic | tests/test_json_encoding.py | .py | import sys
from dataclasses import asdict, dataclass
from functools import partial
from json import dumps as sdumps
from string import ascii_lowercase
import pytest
try:
import ujson
from ujson import dumps as udumps
ujson_version = tuple(
map(int, ujson.__version__.strip(ascii_lowercase).spli... | 107 | 2,477 |
sanic | tests/test_multiprocessing.py | .py | import logging
import multiprocessing
import pickle
import random
import signal
import sys
from asyncio import sleep
import pytest
from sanic_testing.testing import HOST
from sanic import Blueprint, text
from sanic.compat import use_context
from sanic.log import logger
pytestmark = pytest.mark.xdist_group(name="p... | 178 | 4,916 |
sanic | tests/test_url_for.py | .py | import asyncio
import pytest
from sanic_testing.testing import SanicTestClient
from sanic.blueprints import Blueprint
def test_routes_with_host(app):
@app.route("/", name="hostindex", host="example.com")
@app.route("/path", name="hostpath", host="path.example.com")
def index(request):
pass
... | 103 | 2,748 |
sanic | tests/test_middleware.py | .py | import logging
from asyncio import CancelledError, sleep
from itertools import count
from sanic.exceptions import NotFound
from sanic.request import Request
from sanic.response import HTTPResponse, json, text
# ------------------------------------------------------------ #
# GET
# ---------------------------------... | 350 | 8,808 |
sanic | tests/test_deprecation.py | .py | import pytest
from sanic import Sanic
from sanic.log import deprecation
def test_deprecation():
message = r"\[DEPRECATION v9\.9\] hello"
with pytest.warns(DeprecationWarning, match=message):
deprecation("hello", 9.9)
@pytest.mark.parametrize(
"filter,expected",
(("default", 1), ("once", 1),... | 23 | 614 |
sanic | tests/test_server_events.py | .py | import asyncio
import signal
from contextlib import closing
from socket import socket
import pytest
from sanic_testing.testing import HOST
from sanic import Blueprint
from sanic.exceptions import BadRequest, SanicException
from .conftest import get_port
AVAILABLE_LISTENERS = [
"before_server_start",
"aft... | 275 | 7,314 |
sanic | tests/test_tls.py | .py | import logging
import os
import ssl
import subprocess
import sys
from contextlib import contextmanager
from multiprocessing import Event
from pathlib import Path
from unittest.mock import Mock, patch
from urllib.parse import urlparse
import pytest
from sanic_testing.testing import HOST, PORT, SanicTestClient
import... | 746 | 21,984 |
sanic | tests/test_routes.py | .py | import asyncio
import re
import pytest
from sanic_routing.exceptions import (
InvalidUsage,
ParameterNameConflicts,
RouteExists,
)
from sanic_testing.testing import SanicTestClient
from sanic import Blueprint, Sanic
from sanic.constants import HTTP_METHODS
from sanic.exceptions import NotFound, SanicExce... | 1,292 | 35,971 |
sanic | tests/test_blueprint_group.py | .py | import pytest
from pytest import raises
from sanic.app import Sanic
from sanic.blueprint_group import BlueprintGroup
from sanic.blueprints import Blueprint
from sanic.exceptions import BadRequest, Forbidden, SanicException, ServerError
from sanic.request import Request
from sanic.response import HTTPResponse, text
... | 392 | 11,917 |
sanic | tests/test_headers.py | .py | from unittest.mock import Mock
import pytest
from sanic import Sanic, headers, json, text
from sanic.exceptions import InvalidHeader, PayloadTooLarge
from sanic.http import Http
from sanic.request import Request
def make_request(headers) -> Request:
return Request(b"/", headers, "1.1", "GET", None, None)
@pyt... | 470 | 13,909 |
sanic | tests/test_constants.py | .py | import pytest
from sanic import Sanic, text
from sanic.application.constants import Mode, Server, ServerStage
from sanic.constants import HTTP_METHODS, HTTPMethod
@pytest.mark.parametrize("enum", (HTTPMethod, Server, Mode))
def test_string_compat(enum):
for key in enum.__members__.keys():
assert key.uppe... | 36 | 1,015 |
sanic | tests/test_prepare.py | .py | import logging
import os
from pathlib import Path
from unittest.mock import Mock
import pytest
from sanic import Sanic
from sanic.application.state import ApplicationServerInfo
@pytest.fixture(autouse=True)
def no_skip():
should_auto_reload = Sanic.should_auto_reload
Sanic.should_auto_reload = Mock(return_... | 86 | 2,063 |
sanic | tests/test_blueprint_copy.py | .py | import pytest
from sanic_routing.exceptions import RouteExists
from sanic import Blueprint, Request, Sanic
from sanic.response import text
def test_bp_copy(app: Sanic):
bp1 = Blueprint("test_bp1", version=1)
bp1.ctx.test = 1
assert hasattr(bp1.ctx, "test")
@bp1.route("/page")
def handle_request... | 154 | 4,489 |
sanic | tests/test_redirect.py | .py | from urllib.parse import quote
import pytest
from sanic.response import redirect, text
@pytest.fixture
def redirect_app(app):
@app.route("/redirect_init")
async def redirect_init(request):
return redirect("/redirect_target")
@app.route("/redirect_init_with_301")
async def redirect_init_with... | 136 | 3,651 |
sanic | tests/test_test_client_port.py | .py | from sanic_testing.testing import PORT, SanicTestClient
from sanic.response import json, text
# ------------------------------------------------------------ #
# UTF-8
# ------------------------------------------------------------ #
def test_test_client_port_none(app):
@app.get("/get")
def handler(request)... | 36 | 955 |
sanic | tests/test_custom_request.py | .py | from io import BytesIO
from sanic import Sanic
from sanic.request import Request
from sanic.response import json_dumps, text
class CustomRequest(Request):
"""Alternative implementation for loading body (non-streaming handlers)"""
async def receive_body(self):
buffer = BytesIO()
async for dat... | 47 | 1,218 |
sanic | tests/test_errorpages.py | .py | import logging
import pytest
import sanic
from sanic import Sanic
from sanic.config import Config
from sanic.errorpages import TextRenderer, exception_response, guess_mime
from sanic.exceptions import NotFound, SanicException
from sanic.handlers import ErrorHandler
from sanic.request import Request
from sanic.respon... | 576 | 17,682 |
sanic | tests/test_response_header_injection.py | .py | import pytest
from sanic.headers import format_http1_response
from sanic.response import text
from sanic.response.convenience import file
def encoded_header_values(response):
return list(response.processed_headers)
def wire(response):
return format_http1_response(response.status, response.processed_headers... | 71 | 2,010 |
sanic | tests/test_cookies.py | .py | from datetime import datetime, timedelta
from http.cookies import SimpleCookie
from unittest.mock import Mock
import pytest
from sanic import Request, Sanic
from sanic.compat import Header
from sanic.cookies import Cookie, CookieJar
from sanic.cookies.request import CookieRequestParameters, parse_cookie
from sanic.ex... | 592 | 17,853 |
sanic | tests/client.py | .py | import asyncio
from textwrap import dedent
from typing import AnyStr
class RawClient:
CRLF = b"\r\n"
def __init__(self, host: str, port: int):
self.reader = None
self.writer = None
self.host = host
self.port = port
async def connect(self):
self.reader, self.write... | 48 | 1,217 |
sanic | tests/test_handler_annotations.py | .py | from uuid import UUID
import pytest
from sanic import json
@pytest.mark.parametrize(
"idx,path,expectation",
(
(0, "/abc", "str"),
(1, "/123", "int"),
(2, "/123.5", "float"),
(3, "/8af729fe-2b94-4a95-a168-c07068568429", "UUID"),
),
)
def test_annotated_handlers(app, idx, ... | 40 | 943 |
sanic | tests/test_response_json.py | .py | import json
from functools import partial
from unittest.mock import Mock
import pytest
from sanic import Request, Sanic
from sanic.exceptions import SanicException
from sanic.response import json as json_response
from sanic.response.types import JSONResponse
JSON_BODY = {"ok": True}
json_dumps = partial(json.dumps... | 225 | 6,758 |
sanic | tests/test_blueprints.py | .py | import asyncio
import inspect
import os
import pytest
from sanic.app import Sanic
from sanic.blueprints import Blueprint
from sanic.constants import HTTP_METHODS
from sanic.exceptions import BadRequest, NotFound, SanicException, ServerError
from sanic.request import Request
from sanic.response import json, text
# -... | 1,153 | 30,164 |
sanic | tests/test_handler.py | .py | from sanic.app import Sanic
from sanic.response import empty
from sanic.signals import Event
def test_handler_operation_order(app: Sanic):
operations = []
@app.on_request
async def on_request(_):
nonlocal operations
operations.append(1)
@app.on_response
async def on_response(*_):... | 37 | 844 |
sanic | tests/test_url_building.py | .py | import string
from urllib.parse import parse_qsl, urlsplit
import pytest
from sanic_testing.testing import HOST as test_host
from sanic_testing.testing import PORT as test_port
from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.exceptions import URLBuildError
from sanic.response import text
f... | 366 | 10,404 |
sanic | tests/test_base.py | .py | import pytest
from sanic import Blueprint, Sanic
from sanic.exceptions import SanicException
@pytest.fixture
def app():
return Sanic("my_app")
@pytest.fixture
def bp(app):
return Blueprint("my_bp")
def test_app_str(app):
assert str(app) == "<Sanic my_app>"
def test_app_repr(app):
assert repr(ap... | 98 | 2,071 |
sanic | tests/skip_test_custom_protocol.py | .py | from sanic.response import text
from sanic.server import HttpProtocol
class CustomHttpProtocol(HttpProtocol):
def write_response(self, response):
if isinstance(response, str):
response = text(response)
self.transport.write(response.output(self.request.version))
self.transport.c... | 22 | 639 |
sanic | tests/test_dynamic_routes.py | .py | import pytest
from sanic_routing.exceptions import RouteExists
from sanic.response import text
@pytest.mark.parametrize(
"method,attr, expected",
[
("get", "text", "OK1 test"),
("post", "text", "OK2 test"),
("put", "text", "OK2 test"),
],
)
def test_overload_dynamic_routes(app, m... | 45 | 1,356 |
sanic | tests/test_named_routes.py | .py | #!/usr/bin/env python3
import asyncio
import pytest
from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.constants import HTTP_METHODS
from sanic.exceptions import URLBuildError
from sanic.response import text
# ------------------------------------------------------------ #
# UTF-8
# --------... | 439 | 11,794 |
sanic | tests/test_request_data.py | .py | import random
from sanic.response import json
try:
from ujson import loads
except ImportError:
from json import loads
def test_custom_context(app):
@app.middleware("request")
def store(request):
request.ctx.user = "sanic"
request.ctx.session = None
@app.route("/")
def handl... | 82 | 2,272 |
sanic | tests/test_request.py | .py | import uuid
from unittest.mock import Mock
from uuid import UUID, uuid4
import pytest
from sanic import Sanic, response
from sanic.exceptions import BadURL, SanicException
from sanic.request import Request
from sanic.server import HttpProtocol
def test_no_request_id_not_called(monkeypatch):
monkeypatch.setattr... | 339 | 8,459 |
sanic | tests/test_graceful_shutdown.py | .py | import asyncio
import logging
import pytest
from pytest import LogCaptureFixture
from sanic.response import empty
@pytest.mark.xfail(reason="This test runs fine locally, but fails on CI")
def test_no_exceptions_when_cancel_pending_request(
app, caplog: LogCaptureFixture, port
):
app.config.GRACEFUL_SHUTDOW... | 62 | 1,845 |
sanic | tests/test_server_loop.py | .py | import logging
from unittest.mock import Mock, patch
import pytest
from sanic.compat import OS_IS_WINDOWS, UVLOOP_INSTALLED
from sanic.server import loop
@pytest.mark.skipif(
not OS_IS_WINDOWS,
reason="Not testable with current client",
)
def test_raises_warning_if_os_is_windows(caplog):
with caplog.at... | 117 | 3,883 |
sanic | tests/test_http.py | .py | import json as stdjson
from collections import namedtuple
from pathlib import Path
from sys import version_info
import pytest
from sanic_testing.reusable import ReusableClient
from sanic import json, text
from sanic.app import Sanic
from tests.client import RawClient
parent_dir = Path(__file__).parent
localhost_d... | 351 | 8,383 |
sanic | tests/test_ws_handlers.py | .py | import base64
import secrets
from collections.abc import Coroutine
from typing import Any, Callable
import pytest
from websockets.client import WebSocketClientProtocol
from sanic import Request, Sanic, Websocket
MimicClientType = Callable[
[WebSocketClientProtocol], Coroutine[None, None, Any]
]
@pytest.fixt... | 176 | 5,158 |
sanic | tests/test_motd.py | .py | import logging
import os
import platform
from unittest.mock import Mock, patch
import pytest
from sanic import __version__
from sanic.application.logo import BASE_LOGO
from sanic.application.motd import MOTD, MOTDTTY
@pytest.fixture(autouse=True)
def reset():
try:
del os.environ["SANIC_MOTD_OUTPUT"]
... | 83 | 2,396 |
sanic | tests/test_cancellederror.py | .py | from asyncio import CancelledError
from sanic import Request, Sanic, json
def test_can_raise_in_handler(app: Sanic):
@app.get("/")
async def handler(request: Request):
raise CancelledError("STOP!!")
@app.exception(CancelledError)
async def handle_cancel(request: Request, exc: CancelledError)... | 18 | 506 |
sanic | tests/test_naming.py | .py | from sanic import Blueprint, Sanic, text
def factory(sanic_cls: type[Sanic], blueprint_cls: type[Blueprint]):
app = sanic_cls("Foo")
bp = blueprint_cls("Bar", url_prefix="/bar")
@app.get("/")
async def handler(request):
return text(request.name)
@bp.get("/")
async def handler(request... | 56 | 1,609 |
sanic | tests/test_timeout_logic.py | .py | import asyncio
from unittest.mock import Mock
import pytest
from sanic import Sanic
from sanic.exceptions import RequestTimeout, ServiceUnavailable
from sanic.http import Stage
from sanic.server import HttpProtocol
@pytest.fixture
def app():
return Sanic("test")
@pytest.fixture
def mock_transport():
retu... | 75 | 2,063 |
sanic | tests/test_websockets.py | .py | import re
from asyncio import Event, Queue, TimeoutError
from unittest.mock import Mock, call
import pytest
from websockets.frames import CTRL_OPCODES, DATA_OPCODES, OP_TEXT, Frame
from sanic.exceptions import ServerError
from sanic.server.websockets.frame import WebsocketFrameAssembler
try:
from unittest.moc... | 241 | 7,458 |
sanic | tests/test_signals.py | .py | import asyncio
from enum import Enum
from itertools import count
import pytest
from sanic_routing.exceptions import NotFound
from sanic import Blueprint, Sanic, empty
from sanic.exceptions import InvalidSignal, SanicException
from sanic.signals import Event
def test_add_signal(app):
def sync_signal(*_): ...
... | 773 | 18,249 |
sanic | tests/test_http_alt_svc.py | .py | import sys
from pathlib import Path
import pytest
from sanic.app import Sanic
from sanic.response import empty
from tests.client import RawClient
parent_dir = Path(__file__).parent
localhost_dir = parent_dir / "certs/localhost"
@pytest.mark.skipif(sys.version_info < (3, 9), reason="Not supported in 3.7")
def tes... | 65 | 1,383 |
sanic | tests/test_signal_handlers.py | .py | import asyncio
import os
import signal
from queue import Queue
from types import SimpleNamespace
from typing import Optional
from unittest.mock import MagicMock
import pytest
from sanic_testing.testing import HOST, PORT
from sanic import Sanic
from sanic.compat import ctrlc_workaround_for_windows
from sanic.excepti... | 180 | 5,124 |
sanic | tests/test_keep_alive_timeout.py | .py | import asyncio
import platform
from asyncio import sleep as aio_sleep
from itertools import count
from os import environ
import pytest
from sanic_testing.reusable import ReusableClient
from sanic import Sanic
from sanic.compat import OS_IS_WINDOWS
from sanic.response import text
pytestmark = pytest.mark.xdist_gro... | 260 | 8,267 |
sanic | tests/test_cli.py | .py | import json
import os
import sys
from pathlib import Path
from typing import Optional
from unittest.mock import patch
import pytest
from sanic_routing import __version__ as __routing_version__
from sanic import __version__
from sanic.__main__ import main
from sanic.cli.inspector_client import InspectorClient
from s... | 455 | 12,325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.