-
First Check
Commit to Help
Example Code# example.py
from typing import Optional
from factory.alchemy import SQLAlchemyModelFactory
from sqlmodel import Field, Session, SQLModel, create_engine, select
sqlite_url = "sqlite://"
engine = create_engine(sqlite_url)
session = Session(engine)
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
class HeroFactory(SQLAlchemyModelFactory):
class Meta:
model = Hero
sqlalchemy_session = session
name = "Superman"
secret_name = "Clark Kent"
age = 1000
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def list_heroes():
with Session(engine) as session:
statement = select(Hero)
heroes = session.exec(statement).all()
return heroes
def test_list_heroes():
create_db_and_tables()
HeroFactory(name="Batman", secret_name="Bruce Wayne", age=50)
heroes = list_heroes()
assert len(heroes) == 1 Description
This doesn't appear to work for me, and i may have misunderstood something in the way things are setup with session management (im more familiar with django, that abstracts session management away) I'm happy to move to a different library if factory boy is not well suited to this, e.g https://github.com/litestar-org/polyfactory Ive also tried various pytest fixtures e.g:
but I'm unsure on how best to set this up, any advice is appreciated Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.8 Python VersionPython 3.10.11 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I have managed to resolve this using the following structure: conftest.py
factories.py
test.py
Basically i was getting tripped up by a few things
Being able to patch the factories session in from within my pytest fixture, gives me the convenience of all data being available in the session within my pytest scope, but given that each time i interact with the db, i create a new session, i needed to commit previous changes, which factory boy was not doing by default because of Ill be leaving this discussion open for a few more days in case anyone sees it and has a cleaner pattern to follow, or spots anything fundamentally wrong with my approach. |
Beta Was this translation helpful? Give feedback.
I have managed to resolve this using the following structure:
conftest.py