Skip to content

Instantly share code, notes, and snippets.

@nguyenkims
Last active February 23, 2022 19:10
Show Gist options
  • Save nguyenkims/7b92e75f77f0d8450fd3e754cd3d7c07 to your computer and use it in GitHub Desktop.
Save nguyenkims/7b92e75f77f0d8450fd3e754cd3d7c07 to your computer and use it in GitHub Desktop.
This snippet shows how to isolate a pytest test using pytest fixture.
"""
This snippet shows how to isolate a pytest test using pytest fixture.
It requires flask, sqlalchemy, pytest, pytest-order to be installed:
> pip install flask sqlalchemy pytest pytest-order
You can run the script by
> pytest -s test_iso.py
(the "-s" is to display prints)
"""
import pytest
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
import sqlalchemy as sa
# <<<< SQLAlchemy setup >>>
# use in memory DB
DB_URI = "sqlite:///:memory:"
engine = create_engine(DB_URI)
connection = engine.connect()
Session = scoped_session(sessionmaker(bind=connection))
Base = declarative_base()
class Cat(Base):
__tablename__ = "cat"
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
name = sa.Column(sa.String(128), unique=True, nullable=False)
# create all tables
Base.metadata.create_all(engine)
# END <<<< SQLAlchemy setup >>>
# <<< Flask app setup >>>
def create_app() -> Flask:
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
@app.route("/")
def index():
cats = Session.query(Cat).all()
return {"cats": [cat.name for cat in cats]}
return app
app = create_app()
# END <<< Flask app setup >>>
@pytest.fixture
def flask_client():
"""
A test should use flask_client as argument to isolate the DB transaction
:return:
"""
transaction = connection.begin()
with app.app_context():
try:
client = app.test_client()
yield client
finally:
# roll back all commits made during a test
transaction.rollback()
Session.rollback()
Session.close()
@pytest.mark.order(1)
def test_index(flask_client):
print("start test_index")
Session.add(Cat(name="european"))
Session.add(Cat(name="egypt"))
Session.commit()
r = flask_client.get("/")
assert r.json["cats"] == ["european", "egypt"]
assert r.status_code == 200
@pytest.mark.order(2)
def test_2():
print("start test_2")
# make sure no Cat was added during test_index
assert Session.query(Cat).count() == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment