'Using pytest with FastAPI + Tortoise : tortoise.exceptions.DBConnectionError: Can't establish connection to database

I have two postgres databases, one for prod and another for testing in "DATABASE_URI" and "TESTDATABASE_URI" respectively. The app seems to working perfectly, whether I use either of the databases ( in testing, none of them seem to work ). Pytest shows this error ( I have pytest and pytest-asyncio installed )

tortoise.exceptions.DBConnectionError: Can't establish connection to database d8jup7ghj3oqu2
  • tests/conftest.py
import asyncio
from os import environ

import pytest
from app.core.init_app import get_app_list
from tortoise.contrib.test import finalizer, initializer



@pytest.fixture(scope="session", autouse=True)
def init_tests():
  initializer(modules=get_app_list(), db_url=environ["TESTDATABASE_URI"])
  yield
  finalizer()


@pytest.fixture(scope="session")
def event_loop():
  return asyncio.get_event_loop()
  • app/main.py
from fastapi import FastAPI

from .core.exceptions import SettingNotFound
from .core.init_app import configure_logging, init_middlewares, register_db, register_exceptions, register_routers

try:
  from .settings.config import settings
except ImportError:
  raise SettingNotFound('Can not import settings. Create settings file from template.config.py')


app = FastAPI(
  title=settings.APP_TITLE,
  description=settings.APP_DESCRIPTION,
  version=settings.VERSION,
  debug=True
)


@app.get("/")
def index():
  return "Hello"


configure_logging()
init_middlewares(app)
register_db(app)
register_exceptions(app)
register_routers(app)

Thank you for your time, do ask me for more info if needed



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source