Devin
Devin

Reputation: 911

Mock SQLAlchemy database URI with pytest

I have a Flask app that is create via the app factory method:

appname/__init__.py

from flask import Flask

def create_app():
    app = Flask(__name__)

    with app.app_context():
        from appname.db import db_session

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()

    return app

if __name__ == "__main__":
    app = create_app()
    app.run(port=5050)

The URI for my database is stored in an environment variable and created using standard SQLAlchemy boilerplate:

appname/db.py

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import os

engine = create_engine(os.environ.get('DATABASE_URI'), echo=True)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    Base.metadata.create_all(bind=engine)

This setup works fine for developing, but I can't figure out how to set the DATABASE_URI variable for pytest. Right now I have to specify it along with the pytest command:

DATABASE_URI='postgresql://me@localhost/appname' pipenv run pytest

While this works, I have to imagine there's a better way to predefine the environment for my test suite. What's the best-practices way to set these environment variables?

Upvotes: 0

Views: 2937

Answers (1)

Devin
Devin

Reputation: 911

This seems to work:

test/conftest.py

import pytest
from _pytest import monkeypatch
from appname import create_app


@pytest.fixture
def client():
    mp = monkeypatch.MonkeyPatch()
    mp.setenv('DATABASE_URI', 'postgresql://me@localhost/appname')
    app = create_app()
    client = app.test_client()

    yield client

Upvotes: 2

Related Questions