I have a util class as below that creates database engine. I would like to keep this as is and use engine from this in unit tests.
database/database_util.py:
import os
from sqlalchemy import create_engine
db_uri = os.getenv("DATABASE_URL", default="")
engine = create_engine(db_uri, echo=False, future=True)
Here is a unit test I have:
tests/test.py:
import os
from unittest import mock
from sqlalchemy import delete, select
k = mock.patch.dict(os.environ, {"DATABASE_URL": "sqlite:///tests/database_for_tests.db"})
k.start()
from database.database_util import engine # noqa: E402
def test_existing_user_not_opted_out():
with engine.connect() as conn:
with conn.begin():
assert conn.execute("SELECT * FROM User..").length() == 2
k.stop()
Here I am first doing mocking of DATABASE_URL and then doing import of engine but this shows error E402: Module level import not at top of file
Is there a way to move import to top of the file and at the same time change the DATABASE_URL used by database_util.py file.