pythonsanic

How to call the sanic asyncio rest endpoint internally for testing purpose


Here is a simple example of sanic

from sanic import Sanic
from sanic import response as res

app = Sanic(__name__)


@app.route("/")
async def test(req):
    return res.text("I\'m a teapot", status=418)


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8000)

Now, this will open port 8000, where I have send request. Instead of that, can I call the test(req) internally in the same python code, something like:

from sanic import Sanic
from sanic import response as res

## generating some data
req = generate_data()

app = Sanic(__name__)


@app.route("/")
async def test(req):
    return res.text("I\'m a teapot", status=418)


if __name__ == '__main__':
    app.call(test(req))   ????????????????
    #app.run(host="0.0.0.0", port=8000)

For testing, can I do something like app.call(test(req)), such that the same 'req' data generated can be passed to the sanic api without any HTTP overhead?


Solution

  • The answer is in the docs.

    There are two test clients built in. The sync version stands up the application and does submit http requests. The async version avoids that leveraging ASGI to reach inside and execute the handler. Sounds like that is the one that you want.

    request, response = await app.asgi_client.put('/')