How to initialize sanic testing?

hello everyone,

I’m trying to add unit testing to my sanic project, I followed the official docs from here Getting Started | Sanic Framework, but seems to be unreal example.

My Questions are:

  1. Is this the best way to do testing?

  2. Dependencies in server.py are not loaded when calling the module from test_1.py while testing, how can i solve it?

  3. I’m testing API, so how test_client should be given API url?

Appreciate any support.

I have my directories as the following:

  • src
    **app.py
  • tests
    **test_1.py

**app.py:**

from utils.db import DB
from utils.response import custom_response
from utils.exceptionHandler import custom_error_handler

from general.url import api as generalAPI
from user.url import api as userAPI
from syllabus.url import api as syllabusAPI

app = Sanic(__name__)

if __name__ == '__main__':
    port = int(os.getenv('PORT'))
    debug = os.getenv('DEBUG')

    app.run(port=port, auto_reload=True,
            host='0.0.0.0', debug=debug, workers=int(os.getenv('DB_WORKERS')))

test_1.py

from sanic import Sanic, response
from src.app import app as realApp

@pytest.fixture
def app():
    return realApp

@pytest.mark.asyncio
async def test_initial(app, general_url):
    request, response = await app.asgi_client.get(f"http://localhost:8050/api/v1/general/initial")
    assert False

This is fine. Personally I prefer to use an app factory because I find it makes things easier. In my tests I can control what gets loaded, and turn on/off modules. There’s a chapter on testing in my book. You can see some of the source code on testing here.