Giter Site home page Giter Site logo

klen / asgi-tools Goto Github PK

View Code? Open in Web Editor NEW
33.0 33.0 1.0 7.84 MB

Tools to build ASGI apps

License: MIT License

Makefile 0.85% Python 85.21% Cython 13.93%
asgi asgi-middleware asgi-toolkit async async-await asyncio curio networking python trio

asgi-tools's Introduction

Hi there, I'm Kirill ๐Ÿ‘‹

  • ๐Ÿ”ญ Iโ€™m currently working on Muffin ecosystem
  • ๐ŸŒฑ Iโ€™m currently learning Rust
  • ๐Ÿ’ฌ Ask me about anything here
  • ๐Ÿ“ซ How to reach me: [email protected]
Anurag's github stats

asgi-tools's People

Contributors

dependabot[bot] avatar klen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

arpitjain799

asgi-tools's Issues

ASGITestClient task not successfully waited before closing connection

Still found one more issue which this time is related to asyncio task not fully finished.

Example code to reproduce the problem, note the artifical asyncio.sleep, which is simulated to trigger the problem condition. Note that I had to comment out pytest.raises as if it's defined the problem condition is not triggered.

import asyncio

import pytest

from asgi_tools import App, ResponseWebSocket, ASGIConnectionClosed
from asgi_tools.tests import ASGITestClient


@pytest.fixture
def app():
    app = App(debug=True)

    @app.route('/')
    async def index(request):
        return 'OK'

    return app


@pytest.fixture(scope="session")
def Client():
    return ASGITestClient


@pytest.mark.asyncio
async def test_websocket(app, Client):

    @app.route('/websocket')
    async def websocket(request):
        assert request.subprotocols == ['ship', 'done']
        async with ResponseWebSocket(request) as ws:
            msg = await ws.receive()
            assert msg == 'ping'
            await ws.send('pong')
            await asyncio.sleep(1)  # simulate executing some logic after sending response

    async with Client(app).websocket(
            '/websocket', headers={'sec-websocket-protocol': 'ship,done'}) as ws:
        await ws.send('ping')
        msg = await ws.receive()
        assert msg == 'pong'

        # with pytest.raises(ASGIConnectionClosed):
        #     await ws.receive()

Task was destroyed but it is pending!
task: <Task pending name='Task-2' coro=<App.call() done, defined at ...asgi_tools/app.py:196> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x1097c9070>()]>>

One possible fix for this is to wait in aio_spawn until task truly has finished. There might be alternative (and more proper) ways to fix this as well.

#...asgi_tools/_compat.py
@asynccontextmanager
async def aio_spawn(fn: t.Callable[..., t.Awaitable], *args, **kwargs):
    """Spawn a given coroutine."""
    if trio and current_async_library() == 'trio':
        async with trio.open_nursery() as tasks:
            tasks.start_soon(fn, *args, **kwargs)
            yield tasks

    elif curio and current_async_library() == 'curio':
        task = await curio.spawn(fn, *args, **kwargs)
        yield task
        await task.join()

    else:
        task = create_task(fn(*args, **kwargs))
        yield task
        while not task.done():  #  Wait until task is truly finished
            await asyncio.sleep(0.02)

ASGITestClient websocket connection scope missing "subprotocols"

ASGITestClient build_scope is missing "subprotocols".

https://asgi.readthedocs.io/en/latest/specs/www.html#websocket-connection-scope
...
subprotocols (Iterable[Unicode string]) โ€“ Subprotocols the client advertised. Optional; if missing defaults to empty list.

Also, test client websocket example in the documentation is incorrect (it's missing websocket-context manager). In my case that would be something like this. For example code, the headers are not that important.

async def test_app(app):
    client = ASGITestClient(app)
    headers = {"Sec-WebSocket-Protocol": "ocpp1.6, ocpp2.0.1"}
    async with client.websocket(path="/123", headers=headers) as ws:
        await ws.send("ping")
        msg = await ws.receive()
        assert msg == "pong"

Anyway, nice library.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.