Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jan 18, 2024
1 parent 81b1a9e commit 647bdcb
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 42 deletions.
5 changes: 1 addition & 4 deletions src/asphalt/core/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@

__all__ = ("Component", "ContainerComponent", "CLIApplicationComponent")

import sys
from abc import ABCMeta, abstractmethod
from asyncio import Future
from collections import OrderedDict
from contextlib import AsyncExitStack
from traceback import print_exception
from typing import Any
from warnings import warn

from anyio import create_task_group, create_memory_object_stream
from anyio import create_memory_object_stream, create_task_group
from anyio.abc import TaskGroup

from .context import Context
Expand Down Expand Up @@ -187,7 +185,6 @@ async def run(exit_code):
self._exit_code = receive_stream
self.task_group.start_soon(run, send_stream)


async def exit_code(self) -> int:
return await self._exit_code.receive()

Expand Down
5 changes: 2 additions & 3 deletions src/asphalt/core/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@

import asyncio
import sys
from asyncio.events import AbstractEventLoop
from logging import INFO, Logger, basicConfig, getLogger, shutdown
from logging import INFO, basicConfig, getLogger, shutdown
from logging.config import dictConfig
from traceback import print_exception
from typing import Any, cast

from anyio import create_task_group, fail_after
from anyio import fail_after

from .component import CLIApplicationComponent, Component, component_types
from .context import Context, _current_context
Expand Down
8 changes: 4 additions & 4 deletions tests/test_concurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async def special_executor(context: Context) -> ThreadPoolExecutor:

@pytest.mark.parametrize("use_resource_name", [False, True], ids=["instance", "resource_name"])
@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_executor_special(
context: Context, use_resource_name: bool, special_executor: ThreadPoolExecutor
) -> None:
Expand All @@ -40,7 +40,7 @@ def check_thread(ctx: Context) -> None:


@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_executor_default(event_loop: AbstractEventLoop, context: Context) -> None:
@executor
def check_thread(ctx: Context) -> None:
Expand All @@ -52,7 +52,7 @@ def check_thread(ctx: Context) -> None:


@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_executor_worker_thread(
event_loop: AbstractEventLoop,
context: Context,
Expand All @@ -77,7 +77,7 @@ def runs_in_default_worker(ctx: Context) -> str:


@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_executor_missing_context(event_loop: AbstractEventLoop, context: Context) -> None:
@executor("special")
def runs_in_default_worker() -> None:
Expand Down
50 changes: 26 additions & 24 deletions tests/test_context.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from __future__ import annotations

import asyncio
import sys
from collections.abc import Callable
from concurrent.futures import Executor, ThreadPoolExecutor
from inspect import isawaitable
from itertools import count
from threading import Thread, current_thread
from typing import AsyncGenerator, AsyncIterator, Dict, NoReturn, Optional, Tuple, Union
from typing import AsyncIterator, Dict, NoReturn, Optional, Tuple, Union
from unittest.mock import patch

import pytest
Expand Down Expand Up @@ -192,12 +191,14 @@ async def test_async_contextmanager_exception(self, event_loop, context):

@pytest.mark.parametrize("types", [int, (int,), ()], ids=["type", "tuple", "empty"])
@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource(self, context, event_loop, types):
"""Test that a resource is properly added in the context and listeners are notified."""
async with create_task_group() as tg:

async def add_resource():
context.add_resource(6, "foo", None, types)

tg.start_soon(add_resource)
event = await context.resource_added.wait_event()

Expand All @@ -207,7 +208,7 @@ async def add_resource():
assert context.get_resource(int, "foo") == 6

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_name_conflict(self, context: Context) -> None:
"""Test that adding a resource won't replace any existing resources."""
context.add_resource(5, "foo")
Expand All @@ -223,7 +224,7 @@ async def test_add_resource_none_value(self, context: Context) -> None:
exc.match('"value" must not be None')

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_context_attr(self, context: Context) -> None:
"""Test that when resources are added, they are also set as properties of the context."""
with pytest.deprecated_call():
Expand All @@ -245,7 +246,7 @@ def test_add_resource_context_attr_conflict(self, context: Context) -> None:
assert context.get_resource(int) is None

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_type_conflict(self, context: Context) -> None:
context.add_resource(5)
with pytest.raises(ResourceConflict) as exc:
Expand All @@ -265,7 +266,7 @@ async def test_add_resource_bad_name(self, context, name):
)

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_parametrized_generic_type(self, context: Context) -> None:
resource = {"a": 1}
resource_type = Dict[str, int]
Expand All @@ -277,7 +278,7 @@ async def test_add_resource_parametrized_generic_type(self, context: Context) ->
assert context.get_resource(dict) is None

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_factory(self, context: Context) -> None:
"""Test that resources factory callbacks are only called once for each context."""

Expand All @@ -294,7 +295,7 @@ def factory(ctx):
assert context.__dict__["foo"] == 1

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_factory_parametrized_generic_type(self, context: Context) -> None:
resource = {"a": 1}
resource_type = Dict[str, int]
Expand Down Expand Up @@ -334,7 +335,7 @@ async def test_add_resource_factory_empty_types(self, context: Context) -> None:
exc.match("no resource types were specified")

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_factory_context_attr_conflict(self, context: Context) -> None:
with pytest.deprecated_call():
context.add_resource_factory(lambda ctx: None, str, context_attr="foo")
Expand All @@ -347,7 +348,7 @@ async def test_add_resource_factory_context_attr_conflict(self, context: Context
)

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_factory_type_conflict(self, context: Context) -> None:
context.add_resource_factory(lambda ctx: None, (str, int))
with pytest.raises(ResourceConflict) as exc:
Expand All @@ -356,7 +357,7 @@ async def test_add_resource_factory_type_conflict(self, context: Context) -> Non
exc.match("this context already contains a resource factory for the type int")

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_factory_no_inherit(self, context: Context) -> None:
"""
Test that a subcontext gets its own version of a factory-generated resource even if a
Expand All @@ -371,7 +372,7 @@ async def test_add_resource_factory_no_inherit(self, context: Context) -> None:
assert subcontext.foo == id(subcontext)

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_return_type_single(self, context: Context) -> None:
def factory(ctx: Context) -> str:
return "foo"
Expand All @@ -381,7 +382,7 @@ def factory(ctx: Context) -> str:
assert context.require_resource(str) == "foo"

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_return_type_union(self, context: Context) -> None:
def factory(ctx: Context) -> Union[int, float]: # noqa: UP007
return 5
Expand All @@ -393,7 +394,7 @@ def factory(ctx: Context) -> Union[int, float]: # noqa: UP007

@pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires Python 3.10+")
@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_return_type_uniontype(self, context: Context) -> None:
def factory(ctx: Context) -> int | float:
return 5
Expand All @@ -404,7 +405,7 @@ def factory(ctx: Context) -> int | float:
assert context.require_resource(float) == 5

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_add_resource_return_type_optional(self, context: Context) -> None:
def factory(ctx: Context) -> Optional[str]: # noqa: UP007
return "foo"
Expand Down Expand Up @@ -452,7 +453,7 @@ def test_require_resource_not_found(self, context: Context) -> None:
assert exc.value.name == "foo"

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_request_resource_parent_add(self, context, event_loop):
"""
Test that adding a resource to the parent context will satisfy a resource request in a
Expand All @@ -461,6 +462,7 @@ async def test_request_resource_parent_add(self, context, event_loop):
"""
async with create_task_group() as tg:
async with context, Context() as child_context:

async def add_resource():
context.add_resource(6)

Expand Down Expand Up @@ -812,7 +814,7 @@ def test_explicit_parent_deprecation() -> None:
# async def generator() -> AsyncGenerator:
# async with Context():
# yield
#
#
# gen = generator()
# await event_loop.create_task(gen.asend(None))
# async with Context() as ctx:
Expand All @@ -821,15 +823,15 @@ def test_explicit_parent_deprecation() -> None:
# await event_loop.create_task(gen.asend(None))
# except StopAsyncIteration:
# pass
#
#
# assert current_context() is ctx
#
#
# pytest.raises(NoCurrentContext, current_context)


class TestDependencyInjection:
@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_static_resources(self) -> None:
@inject
async def injected(
Expand All @@ -847,7 +849,7 @@ async def injected(
assert baz == "baz_test"

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_sync_injection(self) -> None:
@inject
def injected(
Expand Down Expand Up @@ -876,7 +878,7 @@ async def injected(foo: int, bar: str = resource(), *, baz=resource("alt")) -> N
)

@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_missing_resource(self) -> None:
@inject
async def injected(foo: int, bar: str = resource()) -> None:
Expand Down Expand Up @@ -910,7 +912,7 @@ async def injected(foo: int, bar: str = resource()) -> None:
],
)
@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_inject_optional_resource_async(self, annotation: type, sync: bool) -> None:
if sync:

Expand Down
20 changes: 13 additions & 7 deletions tests/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import asyncio
import logging
import sys
from asyncio import AbstractEventLoop
from concurrent.futures import ThreadPoolExecutor
from typing import NoReturn
from unittest.mock import patch

Expand All @@ -15,7 +13,7 @@

from asphalt.core.component import CLIApplicationComponent, Component
from asphalt.core.context import Context
from asphalt.core.runner import run_application #, sigterm_handler
from asphalt.core.runner import run_application # , sigterm_handler


class ShutdownComponent(Component):
Expand All @@ -35,21 +33,29 @@ async def start(self, ctx: Context) -> None:
ctx.add_teardown_callback(self.teardown_callback, pass_exception=True)

if self.method == "stop":

async def stop():
self.task_group.cancel_scope.cancel

self.task_group.start_soon(stop)
elif self.method == "exit":

async def exit():
await sleep(0.1)
sys.exit()

self.task_group.start_soon(exit)
elif self.method == "keyboard":

async def keyboard():
self.press_ctrl_c()

self.task_group.start_soon(keyboard)
elif self.method == "sigterm":

async def sigterm():
sigterm_handler(logging.getLogger(__name__), ctx.loop)

self.task_group.start_soon(sigterm)
elif self.method == "exception":
raise RuntimeError("this should crash the application")
Expand Down Expand Up @@ -90,7 +96,7 @@ async def test_run_logging_config(logging_config) -> None:


@pytest.mark.anyio
@pytest.mark.parametrize('anyio_backend', ['asyncio'])
@pytest.mark.parametrize("anyio_backend", ["asyncio"])
async def test_uvloop_policy(caplog: LogCaptureFixture) -> None:
"""Test that the runner switches to a different event loop policy when instructed to."""
pytest.importorskip("uvloop", reason="uvloop not installed")
Expand Down Expand Up @@ -137,12 +143,12 @@ async def test_run_callbacks(caplog: LogCaptureFixture) -> None:
# """
# Test that when Ctrl+C is pressed during event_loop.run_forever(), run_application() exits
# cleanly.
#
#
# """
# caplog.set_level(logging.INFO)
# component = ShutdownComponent(method=method)
# await run_application(component)
#
#
# records = [record for record in caplog.records if record.name == "asphalt.core.runner"]
# assert len(records) == 5
# assert records[0].message == "Running in development mode"
Expand All @@ -166,7 +172,7 @@ async def test_run_start_exception(caplog: LogCaptureFixture) -> None:

assert str(component.exception) == "this should crash the application"
records = [record for record in caplog.records if record.name == "asphalt.core.runner"]
#assert len(records) == 5
# assert len(records) == 5
assert records[0].message == "Running in development mode"
assert records[1].message == "Starting application"
assert records[2].message == "Error during application startup"
Expand Down

0 comments on commit 647bdcb

Please sign in to comment.