Created
November 3, 2022 13:55
-
-
Save Tishka17/7b1ce06d0064167f2ca1c7ae02427eb6 to your computer and use it in GitHub Desktop.
Test with sqlalchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pytest | |
from sqlalchemy import Column, Integer, create_engine, event, String | |
from sqlalchemy.orm import declarative_base, Session | |
Base = declarative_base() | |
class Model(Base): | |
__tablename__ = "model" | |
id = Column(Integer(), primary_key=True) | |
name = Column(String(), unique=True) | |
@pytest.fixture(scope="session") | |
def engine(): | |
uri = os.getenv("DB_URI") | |
engine = create_engine(uri) | |
Base.metadata.create_all(bind=engine) | |
yield engine | |
Base.metadata.drop_all(bind=engine) | |
@pytest.fixture | |
def session(engine): | |
connection = engine.connect() | |
trans = connection.begin() | |
session = Session(bind=connection) | |
nested = connection.begin_nested() | |
@event.listens_for(session, "after_transaction_end") | |
def end_savepoint(session, transaction): | |
nonlocal nested | |
if not nested.is_active: | |
nested = connection.begin_nested() | |
yield session | |
session.expunge_all() | |
trans.rollback() | |
connection.close() | |
model = Model(id=1, name="name111") | |
@pytest.mark.parametrize("x", [1, 2]) | |
def test_x(x, session): | |
print(session) | |
print("test_x", x) | |
session.add(model) | |
session.commit() | |
session.commit() | |
assert False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment