Skip to content

Commit

Permalink
Move import for patch tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Jun 19, 2022
2 parents 037b286 + 684c638 commit eef949d
Show file tree
Hide file tree
Showing 39 changed files with 573 additions and 251 deletions.
2 changes: 0 additions & 2 deletions .black.toml

This file was deleted.

6 changes: 3 additions & 3 deletions Makefile
Expand Up @@ -66,15 +66,15 @@ ifdef include_tests
isort -rc sanic tests
else
$(info Sorting Imports)
isort -rc sanic tests --profile=black
isort -rc sanic tests
endif
endif

black:
black --config ./.black.toml sanic tests
black sanic tests

isort:
isort sanic tests --profile=black
isort sanic tests

pretty: black isort

Expand Down
2 changes: 1 addition & 1 deletion README.rst
Expand Up @@ -114,7 +114,7 @@ Hello World Example
from sanic import Sanic
from sanic.response import json
app = Sanic("My Hello, world app")
app = Sanic("my-hello-world-app")
@app.route('/')
async def test(request):
Expand Down
15 changes: 15 additions & 0 deletions pyproject.toml
@@ -1,3 +1,18 @@
[build-system]
requires = ["setuptools<60.0", "wheel"]
build-backend = "setuptools.build_meta"

[tool.black]
line-length = 79

[tool.isort]
atomic = true
default_section = "THIRDPARTY"
include_trailing_comma = true
known_first_party = "sanic"
known_third_party = "pytest"
line_length = 79
lines_after_imports = 2
lines_between_types = 1
multi_line_output = 3
profile = "black"
15 changes: 8 additions & 7 deletions sanic/app.py
Expand Up @@ -58,7 +58,7 @@
from sanic.compat import OS_IS_WINDOWS, enable_windows_color_support
from sanic.config import SANIC_PREFIX, Config
from sanic.exceptions import (
InvalidUsage,
BadRequest,
SanicException,
ServerError,
URLBuildError,
Expand Down Expand Up @@ -97,7 +97,7 @@
from sanic_ext import Extend # type: ignore
from sanic_ext.extensions.base import Extension # type: ignore
except ImportError:
Extend = TypeVar("Extend") # type: ignore
Extend = TypeVar("Extend", Type) # type: ignore


if OS_IS_WINDOWS: # no cov
Expand Down Expand Up @@ -281,7 +281,7 @@ def register_listener(
valid = ", ".join(
map(lambda x: x.lower(), ListenerEvent.__members__.keys())
)
raise InvalidUsage(f"Invalid event: {event}. Use one of: {valid}")
raise BadRequest(f"Invalid event: {event}. Use one of: {valid}")

if "." in _event:
self.signal(_event.value)(
Expand Down Expand Up @@ -992,10 +992,10 @@ async def _websocket_handler(
cancelled = False
try:
await fut
except Exception as e:
self.error_handler.log(request, e)
except (CancelledError, ConnectionClosed):
cancelled = True
except Exception as e:
self.error_handler.log(request, e)
finally:
self.websocket_tasks.remove(fut)
if cancelled:
Expand Down Expand Up @@ -1573,8 +1573,9 @@ async def _server_event(
"shutdown",
):
raise SanicException(f"Invalid server event: {event}")
if self.state.verbosity >= 1:
logger.debug(f"Triggering server events: {event}")
logger.debug(
f"Triggering server events: {event}", extra={"verbosity": 1}
)
reverse = concern == "shutdown"
if loop is None:
loop = self.loop
Expand Down
4 changes: 3 additions & 1 deletion sanic/application/logo.py
Expand Up @@ -3,6 +3,8 @@

from os import environ

from sanic.compat import is_atty


BASE_LOGO = """
Expand Down Expand Up @@ -44,7 +46,7 @@
def get_logo(full=False, coffee=False):
logo = (
(FULL_COLOR_LOGO if full else (COFFEE_LOGO if coffee else COLOR_LOGO))
if sys.stdout.isatty()
if is_atty()
else BASE_LOGO
)

Expand Down
5 changes: 2 additions & 3 deletions sanic/application/motd.py
@@ -1,11 +1,10 @@
import sys

from abc import ABC, abstractmethod
from shutil import get_terminal_size
from textwrap import indent, wrap
from typing import Dict, Optional

from sanic import __version__
from sanic.compat import is_atty
from sanic.log import logger


Expand Down Expand Up @@ -36,7 +35,7 @@ def output(
data: Dict[str, str],
extra: Dict[str, str],
) -> None:
motd_class = MOTDTTY if sys.stdout.isatty() else MOTDBasic
motd_class = MOTDTTY if is_atty() else MOTDBasic
motd_class(logo, serve_location, data, extra).display()


Expand Down
5 changes: 4 additions & 1 deletion sanic/application/state.py
Expand Up @@ -9,7 +9,7 @@
from ssl import SSLContext
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union

from sanic.log import logger
from sanic.log import VerbosityFilter, logger
from sanic.server.async_server import AsyncioServer


Expand Down Expand Up @@ -91,6 +91,9 @@ def set_mode(self, value: Union[str, Mode]):
if getattr(self.app, "configure_logging", False) and self.app.debug:
logger.setLevel(logging.DEBUG)

def set_verbosity(self, value: int):
VerbosityFilter.verbosity = value

@property
def is_debug(self):
return self.mode is Mode.DEBUG
Expand Down
50 changes: 29 additions & 21 deletions sanic/asgi.py
Expand Up @@ -25,27 +25,28 @@ class Lifespan:
def __init__(self, asgi_app: ASGIApp) -> None:
self.asgi_app = asgi_app

if self.asgi_app.sanic_app.state.verbosity > 0:
if (
"server.init.before"
in self.asgi_app.sanic_app.signal_router.name_index
):
logger.debug(
'You have set a listener for "before_server_start" '
"in ASGI mode. "
"It will be executed as early as possible, but not before "
"the ASGI server is started."
)
if (
"server.shutdown.after"
in self.asgi_app.sanic_app.signal_router.name_index
):
logger.debug(
'You have set a listener for "after_server_stop" '
"in ASGI mode. "
"It will be executed as late as possible, but not after "
"the ASGI server is stopped."
)
if (
"server.init.before"
in self.asgi_app.sanic_app.signal_router.name_index
):
logger.debug(
'You have set a listener for "before_server_start" '
"in ASGI mode. "
"It will be executed as early as possible, but not before "
"the ASGI server is started.",
extra={"verbosity": 1},
)
if (
"server.shutdown.after"
in self.asgi_app.sanic_app.signal_router.name_index
):
logger.debug(
'You have set a listener for "after_server_stop" '
"in ASGI mode. "
"It will be executed as late as possible, but not after "
"the ASGI server is stopped.",
extra={"verbosity": 1},
)

async def startup(self) -> None:
"""
Expand Down Expand Up @@ -163,6 +164,13 @@ async def create(
instance.request_body = True
instance.request.conn_info = ConnInfo(instance.transport)

await sanic_app.dispatch(
"http.lifecycle.request",
inline=True,
context={"request": instance.request},
fail_not_found=False,
)

return instance

async def read(self) -> Optional[bytes]:
Expand Down
9 changes: 6 additions & 3 deletions sanic/compat.py
@@ -1,8 +1,7 @@
import asyncio
import os
import signal

from sys import argv
import sys

from multidict import CIMultiDict # type: ignore

Expand Down Expand Up @@ -47,7 +46,7 @@ def get_all(self, key: str):
return self.getall(key, default=[])


use_trio = argv[0].endswith("hypercorn") and "trio" in argv
use_trio = sys.argv[0].endswith("hypercorn") and "trio" in sys.argv

if use_trio: # pragma: no cover
import trio # type: ignore
Expand Down Expand Up @@ -89,3 +88,7 @@ def ctrlc_handler(sig, frame):
die = False
signal.signal(signal.SIGINT, ctrlc_handler)
app.add_task(stay_active)


def is_atty():
return sys.stdout and sys.stdout.isatty()
4 changes: 2 additions & 2 deletions sanic/errorpages.py
Expand Up @@ -19,7 +19,7 @@
from functools import partial
from traceback import extract_tb

from sanic.exceptions import InvalidUsage, SanicException
from sanic.exceptions import BadRequest, SanicException
from sanic.helpers import STATUS_CODES
from sanic.request import Request
from sanic.response import HTTPResponse, html, json, text
Expand Down Expand Up @@ -506,7 +506,7 @@ def exception_response(
# $ curl localhost:8000 -d '{"foo": "bar"}'
# And provide them with JSONRenderer
renderer = JSONRenderer if request.json else base
except InvalidUsage:
except BadRequest:
renderer = base
else:
renderer = RENDERERS_BY_CONFIG.get(render_format, renderer)
Expand Down
28 changes: 20 additions & 8 deletions sanic/exceptions.py
Expand Up @@ -42,7 +42,7 @@ class NotFound(SanicException):
quiet = True


class InvalidUsage(SanicException):
class BadRequest(SanicException):
"""
**Status**: 400 Bad Request
"""
Expand All @@ -51,11 +51,14 @@ class InvalidUsage(SanicException):
quiet = True


class BadURL(InvalidUsage):
InvalidUsage = BadRequest


class BadURL(BadRequest):
...


class MethodNotSupported(SanicException):
class MethodNotAllowed(SanicException):
"""
**Status**: 405 Method Not Allowed
"""
Expand All @@ -68,6 +71,9 @@ def __init__(self, message, method, allowed_methods):
self.headers = {"Allow": ", ".join(allowed_methods)}


MethodNotSupported = MethodNotAllowed


class ServerError(SanicException):
"""
**Status**: 500 Internal Server Error
Expand Down Expand Up @@ -129,19 +135,19 @@ class PayloadTooLarge(SanicException):
quiet = True


class HeaderNotFound(InvalidUsage):
class HeaderNotFound(BadRequest):
"""
**Status**: 400 Bad Request
"""


class InvalidHeader(InvalidUsage):
class InvalidHeader(BadRequest):
"""
**Status**: 400 Bad Request
"""


class ContentRangeError(SanicException):
class RangeNotSatisfiable(SanicException):
"""
**Status**: 416 Range Not Satisfiable
"""
Expand All @@ -154,7 +160,10 @@ def __init__(self, message, content_range):
self.headers = {"Content-Range": f"bytes */{content_range.total}"}


class HeaderExpectationFailed(SanicException):
ContentRangeError = RangeNotSatisfiable


class ExpectationFailed(SanicException):
"""
**Status**: 417 Expectation Failed
"""
Expand All @@ -163,6 +172,9 @@ class HeaderExpectationFailed(SanicException):
quiet = True


HeaderExpectationFailed = ExpectationFailed


class Forbidden(SanicException):
"""
**Status**: 403 Forbidden
Expand All @@ -172,7 +184,7 @@ class Forbidden(SanicException):
quiet = True


class InvalidRangeType(ContentRangeError):
class InvalidRangeType(RangeNotSatisfiable):
"""
**Status**: 416 Range Not Satisfiable
"""
Expand Down

0 comments on commit eef949d

Please sign in to comment.