FactoryBoy / factory_boy

A test fixtures replacement for Python
https://factoryboy.readthedocs.io/
MIT License
3.48k stars 392 forks source link

JSON field data is not persisted correctly for SQLAlchemy JSON fields #1024

Open aalvrz opened 1 year ago

aalvrz commented 1 year ago

Description

Not sure if this is a Factory Boy bug or SQLAlchemy bug.

When trying to persist more complex dictionaries within a JSON field/column of a SQLAlchemy model, the data is only partially persisted.

Model / Factory code
# SQLAlchemy Model
from sqlalchemy import JSON

class Model:
    data = JSON()
import factory

# Factory
class ModelFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        model = Model
        sqlalchemy_session = Session
        sqlalchemy_session_persistence = "commit"
The issue

Set a more complex dictionary for the data JSON field when generating objects with the factory:

# Include the code that provoked the bug, including as full a stack-trace as possible

obj = ModelFactory(
  data={
    "apples": [
      {
        "apple_id": 1,
        "apple_color": "red",
      }
    ]
  }
)

The object is created, but the data field is persisted as:

{"apples": []}

Notes

SQLAlchemy==1.4.46
factory-boy==3.1.0
fdemmer commented 1 year ago

Your SQLAlchemy code is incomplete; it is not enough to define a class with some attribute. SQLAlchemy uses declarative mapping. You also need to create a session instance and and not just provide the Session class to SQLAlchemyModelFactory.

I suggest trying the the code example in the factory-boy docs first; you could add a JSON column to that: https://factoryboy.readthedocs.io/en/stable/orms.html#sqlalchemy