Skip to content

Commit 21c7b53

Browse files
committed
Adopted Black for code formatting
1 parent 7d6fb1b commit 21c7b53

File tree

12 files changed

+185
-113
lines changed

12 files changed

+185
-113
lines changed

.pre-commit-config.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@ repos:
2121
- id: pyupgrade
2222
args: [ "--py37-plus", "--keep-runtime-typing" ]
2323

24-
- repo: https://github.com/pre-commit/mirrors-autopep8
25-
rev: v1.6.0
24+
- repo: https://github.com/psf/black
25+
rev: 22.3.0
2626
hooks:
27-
- id: autopep8
27+
- id: black
2828

2929
- repo: https://github.com/pycqa/isort
3030
rev: 5.10.1

docs/conf.py

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,40 +4,43 @@
44
from packaging.version import parse
55

66
extensions = [
7-
'sphinx.ext.autodoc',
8-
'sphinx.ext.intersphinx',
9-
'sphinx.ext.extlinks',
10-
'sphinx_autodoc_typehints',
11-
'sphinxcontrib.asyncio'
7+
"sphinx.ext.autodoc",
8+
"sphinx.ext.intersphinx",
9+
"sphinx.ext.extlinks",
10+
"sphinx_autodoc_typehints",
11+
"sphinxcontrib.asyncio",
1212
]
1313

14-
templates_path = ['_templates']
15-
source_suffix = '.rst'
16-
master_doc = 'index'
17-
project = 'asphalt-exceptions'
18-
author = 'Alex Grönholm'
19-
copyright = '2017, ' + author
14+
templates_path = ["_templates"]
15+
source_suffix = ".rst"
16+
master_doc = "index"
17+
project = "asphalt-exceptions"
18+
author = "Alex Grönholm"
19+
copyright = "2017, " + author
2020

2121
v = parse(get_version(project))
2222
version = v.base_version
2323
release = v.public
2424

2525
language = None
2626

27-
exclude_patterns = ['_build']
28-
pygments_style = 'sphinx'
29-
highlight_language = 'python3'
27+
exclude_patterns = ["_build"]
28+
pygments_style = "sphinx"
29+
highlight_language = "python3"
3030
todo_include_todos = False
3131

32-
html_theme = 'sphinx_rtd_theme'
33-
html_static_path = ['_static']
34-
htmlhelp_basename = project.replace('-', '') + 'doc'
32+
html_theme = "sphinx_rtd_theme"
33+
html_static_path = ["_static"]
34+
htmlhelp_basename = project.replace("-", "") + "doc"
3535

3636
extlinks = {
37-
'github': (f'https://github.com/asphalt-framework/{project}/tree/{version}/%s', None)
37+
"github": (
38+
f"https://github.com/asphalt-framework/{project}/tree/{version}/%s",
39+
None,
40+
)
3841
}
3942

4043
intersphinx_mapping = {
41-
'python': ('https://docs.python.org/3/', None),
42-
'asphalt': ('https://asphalt.readthedocs.io/en/latest/', None)
44+
"python": ("https://docs.python.org/3/", None),
45+
"asphalt": ("https://asphalt.readthedocs.io/en/latest/", None),
4346
}

pyproject.toml

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,12 +65,7 @@ local_scheme = "dirty-tag"
6565
[tool.isort]
6666
src_paths = ["src"]
6767
skip_gitignore = true
68-
line_length = 99
69-
multi_line_output = 4
70-
known_first_party = ["asphalt.exceptions"]
71-
72-
[tool.autopep8]
73-
max_line_length = 99
68+
profile = "black"
7469

7570
[tool.flake8]
7671
max-line-length = 99

src/asphalt/exceptions/__init__.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,18 @@
99

1010
from asphalt.exceptions.api import ExceptionReporter, ExtrasProvider
1111

12-
__all__ = ('report_exception',)
12+
__all__ = ("report_exception",)
1313

1414
module_logger = logging.getLogger(__name__)
1515

1616

17-
def report_exception(ctx: Context, message: str, exception: BaseException = None, *,
18-
logger: logging.Logger | str | bool = True) -> None:
17+
def report_exception(
18+
ctx: Context,
19+
message: str,
20+
exception: BaseException = None,
21+
*,
22+
logger: logging.Logger | str | bool = True,
23+
) -> None:
1924
"""
2025
Report an exception to all exception reporters in the given context (and optionally log it too)
2126
@@ -31,8 +36,10 @@ def report_exception(ctx: Context, message: str, exception: BaseException = None
3136
if not exception:
3237
exception = sys.exc_info()[1]
3338
if not exception:
34-
raise ValueError('missing "exception" parameter and no current exception present in '
35-
'sys.exc_info()')
39+
raise ValueError(
40+
'missing "exception" parameter and no current exception present in '
41+
"sys.exc_info()"
42+
)
3643

3744
actual_logger: logging.Logger | None
3845
if isinstance(logger, bool):
@@ -43,7 +50,7 @@ def report_exception(ctx: Context, message: str, exception: BaseException = None
4350
if module and module.__spec__:
4451
actual_logger = logging.getLogger(module.__spec__.name)
4552
else: # pragma: no cover
46-
actual_logger = logging.getLogger(frame.f_globals['__name__'])
53+
actual_logger = logging.getLogger(frame.f_globals["__name__"])
4754
else:
4855
actual_logger = None
4956
elif isinstance(logger, str):
@@ -61,14 +68,18 @@ def report_exception(ctx: Context, message: str, exception: BaseException = None
6168
try:
6269
new_extra = provider.get_extras(ctx, reporter)
6370
except Exception:
64-
module_logger.exception('error retrieving exception extras for %s from %s',
65-
qualified_name(reporter), qualified_name(provider))
71+
module_logger.exception(
72+
"error retrieving exception extras for %s from %s",
73+
qualified_name(reporter),
74+
qualified_name(provider),
75+
)
6676
else:
6777
if isinstance(new_extra, dict):
6878
extra = merge_config(extra, new_extra)
6979

7080
try:
7181
reporter.report_exception(ctx, exception, message, extra)
7282
except Exception:
73-
module_logger.exception('error calling exception reporter (%s)',
74-
qualified_name(reporter))
83+
module_logger.exception(
84+
"error calling exception reporter (%s)", qualified_name(reporter)
85+
)

src/asphalt/exceptions/api.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,13 @@ class ExceptionReporter(metaclass=ABCMeta):
1515
"""
1616

1717
@abstractmethod
18-
def report_exception(self, ctx: Context, exception: BaseException, message: str,
19-
extra: dict[str, Any]) -> None:
18+
def report_exception(
19+
self,
20+
ctx: Context,
21+
exception: BaseException,
22+
message: str,
23+
extra: dict[str, Any],
24+
) -> None:
2025
"""
2126
Report the given exception to an external service.
2227
@@ -43,7 +48,9 @@ class ExtrasProvider(metaclass=ABCMeta):
4348
"""
4449

4550
@abstractmethod
46-
def get_extras(self, ctx: Context, reporter: ExceptionReporter) -> dict[str, Any] | None:
51+
def get_extras(
52+
self, ctx: Context, reporter: ExceptionReporter
53+
) -> dict[str, Any] | None:
4754
"""
4855
Return context specific extras for the given exception reporter backend.
4956

src/asphalt/exceptions/component.py

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,26 @@
66
from typing import Any, AsyncIterator, Dict, Optional
77

88
from asphalt.core import (
9-
Component, Context, PluginContainer, context_teardown, merge_config, qualified_name)
9+
Component,
10+
Context,
11+
PluginContainer,
12+
context_teardown,
13+
merge_config,
14+
qualified_name,
15+
)
1016
from typeguard import check_argument_types
1117

1218
from asphalt.exceptions import report_exception
1319
from asphalt.exceptions.api import ExceptionReporter
1420

15-
reporter_backends = PluginContainer('asphalt.exceptions.reporters', ExceptionReporter)
21+
reporter_backends = PluginContainer("asphalt.exceptions.reporters", ExceptionReporter)
1622
logger = logging.getLogger(__name__)
1723

1824

19-
def default_exception_handler(loop: AbstractEventLoop, context: dict[str, Any], *,
20-
ctx: Context) -> None:
21-
report_exception(ctx, context['message'], context['exception'])
25+
def default_exception_handler(
26+
loop: AbstractEventLoop, context: dict[str, Any], *, ctx: Context
27+
) -> None:
28+
report_exception(ctx, context["message"], context["exception"])
2229

2330

2431
class ExceptionReporterComponent(Component):
@@ -52,17 +59,21 @@ class ExceptionReporterComponent(Component):
5259
:param default_args: default values for constructor keyword arguments
5360
"""
5461

55-
def __init__(self, reporters: Dict[str, Optional[Dict[str, Any]]] = None,
56-
install_default_handler: bool = True, **default_args) -> None:
62+
def __init__(
63+
self,
64+
reporters: Dict[str, Optional[Dict[str, Any]]] = None,
65+
install_default_handler: bool = True,
66+
**default_args,
67+
) -> None:
5768
assert check_argument_types()
5869
self.install_default_handler = install_default_handler
5970
if not reporters:
60-
reporters = {'default': default_args}
71+
reporters = {"default": default_args}
6172

6273
self.reporters: list[tuple] = []
6374
for resource_name, config in reporters.items():
6475
merged_config = merge_config(default_args, config or {})
65-
type_ = merged_config.pop('backend', resource_name)
76+
type_ = merged_config.pop("backend", resource_name)
6677
serializer = reporter_backends.create_object(type_, **merged_config)
6778
self.reporters.append((resource_name, serializer))
6879

@@ -71,15 +82,18 @@ async def start(self, ctx: Context) -> AsyncIterator[None]:
7182
for resource_name, reporter in self.reporters:
7283
types = [ExceptionReporter, type(reporter)]
7384
ctx.add_resource(reporter, resource_name, types=types)
74-
logger.info('Configured exception reporter (%s; class=%s)', resource_name,
75-
qualified_name(reporter))
85+
logger.info(
86+
"Configured exception reporter (%s; class=%s)",
87+
resource_name,
88+
qualified_name(reporter),
89+
)
7690

7791
if self.install_default_handler:
7892
handler = partial(default_exception_handler, ctx=ctx)
7993
ctx.loop.set_exception_handler(handler)
80-
logger.info('Installed default event loop exception handler')
94+
logger.info("Installed default event loop exception handler")
8195

8296
yield
8397

8498
ctx.loop.set_exception_handler(None)
85-
logger.info('Uninstalled default event loop exception handler')
99+
logger.info("Uninstalled default event loop exception handler")

src/asphalt/exceptions/reporters/raygun.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ class RaygunExceptionReporter(ExceptionReporter):
2828
def __init__(self, api_key: str, **config) -> None:
2929
self.client = RaygunSender(api_key, config)
3030

31-
def report_exception(self, ctx: Context, exception: BaseException, message: str,
32-
extra: dict[str, Any]) -> None:
31+
def report_exception(
32+
self,
33+
ctx: Context,
34+
exception: BaseException,
35+
message: str,
36+
extra: dict[str, Any],
37+
) -> None:
3338
self.client.send_exception(exception, **extra)

src/asphalt/exceptions/reporters/sentry.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,20 @@ class SentryExceptionReporter(ExceptionReporter):
3636
"""
3737

3838
def __init__(self, **client_args) -> None:
39-
client_args.setdefault('environment', 'development' if __debug__ else 'production')
40-
client_args.setdefault('transport', AioHttpTransport)
41-
client_args.setdefault('enable_breadcrumbs', False)
42-
client_args.setdefault('install_logging_hook', False)
39+
client_args.setdefault(
40+
"environment", "development" if __debug__ else "production"
41+
)
42+
client_args.setdefault("transport", AioHttpTransport)
43+
client_args.setdefault("enable_breadcrumbs", False)
44+
client_args.setdefault("install_logging_hook", False)
4345
self.client = Client(**client_args)
4446

45-
def report_exception(self, ctx: Context, exception: BaseException, message: str,
46-
extra: dict[str, Any]) -> None:
47+
def report_exception(
48+
self,
49+
ctx: Context,
50+
exception: BaseException,
51+
message: str,
52+
extra: dict[str, Any],
53+
) -> None:
4754
exc_info = type(exception), exception, exception.__traceback__
4855
self.client.captureException(exc_info, message=message, **extra)

tests/reporters/test_raygun.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ async def test_raygun():
1515
except ZeroDivisionError as exc:
1616
exception = exc
1717

18-
reporter = RaygunExceptionReporter('abvcgrdg234')
19-
with patch.object(reporter.client, '_post') as post:
20-
reporter.report_exception(Context(), exception, 'test exception', {})
18+
reporter = RaygunExceptionReporter("abvcgrdg234")
19+
with patch.object(reporter.client, "_post") as post:
20+
reporter.report_exception(Context(), exception, "test exception", {})
2121

2222
await asyncio.sleep(0.1)
2323
assert post.call_count == 1

tests/reporters/test_sentry.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ async def test_sentry():
1515
except ZeroDivisionError as exc:
1616
exception = exc
1717

18-
reporter = SentryExceptionReporter(dsn='http://username:[email protected]/000000')
19-
with patch.object(reporter.client, 'send') as send:
20-
reporter.report_exception(Context(), exception, 'test exception', {})
18+
reporter = SentryExceptionReporter(dsn="http://username:[email protected]/000000")
19+
with patch.object(reporter.client, "send") as send:
20+
reporter.report_exception(Context(), exception, "test exception", {})
2121

2222
await asyncio.sleep(0.1)
2323
assert send.call_count == 1

0 commit comments

Comments
 (0)