Example of a Sanic architecture with tests needed

Hi guys,

can someone provide a working example of a Sanic app including tests? The user guide (Getting Started | Sanic Framework) assigns the @pytest.fixture within the test script itself. Yet, obviously, my real app is not coded in the test script. My architecture looks like this:

-server.py
-tests.py

server.py:

...
app = Sanic("my_app")
...
app.run(host='0.0.0.0', port=3030, access_log=False, debug=False)

tests.py:

import pytest
from sanic import Sanic, response

from server import app 

def test_ping(app):
    request, response = app.test_client.get("/ping")

    assert request.method.lower() == "get"
    assert response.body == "pong"
    assert response.status == 200

I start the tests with pytest tests.py. Nothing happens. If I CTRL+C out, it says fixture ‘app’ not found. How can I connect both scripts?

from sanic import Sanic
from sanic import request, response


app = Sanic(__name__)

@app.get('/ping')
async def ping(request) -> response:
    return response.text("pong")
import pytest
from sanic import Sanic, response

from server import app as sanic_app

@pytest.fixture
def app():
    return sanic_app

def test_ping(app):
    request, response = app.test_client.get("/ping")

    assert request.method.lower() == "get"
    assert response.body == b"pong"
    assert response.status == 200
$ pdm run pytest ./test_server.py -v
================================ test session starts =================================
platform darwin -- Python 3.10.2, pytest-7.1.2, pluggy-1.0.0 -- /opt/homebrew/Cellar/pdm/1.14.0/libexec/bin/python3.10
cachedir: .pytest_cache
rootdir: /Users/ssadowski/projects/sanic-pytest
plugins: anyio-3.5.0
collected 1 item

test_server.py::test_ping PASSED                                               [100%]

================================= 1 passed in 0.14s ==================================

I do use pdm, but it shouldn’t make any difference if you’re using virtualenv, pipenv, or poetry

Oh, that was easy. Thanks a lot.

You can also see a sample operational project here:

From inside the ./application dir:

pytest tests