MCPcopy
hub / github.com/pallets-eco/flask-sqlalchemy / test_declaredattr

Function test_declaredattr

tests/test_model.py:85–138  ·  view source on GitHub ↗
(app: Flask, model_class: t.Any)

Source from the content-addressed store, hash-verified

83
84@pytest.mark.usefixtures("app_ctx")
85def test_declaredattr(app: Flask, model_class: t.Any) -> None:
86 if model_class is Model:
87
88 class IdModel(Model):
89 @sa.orm.declared_attr
90 @classmethod
91 def id(cls: type[Model]): # type: ignore[no-untyped-def]
92 for base in cls.__mro__[1:-1]:
93 if getattr(base, "__table__", None) is not None and hasattr(
94 base, "id"
95 ):
96 return sa.Column(sa.ForeignKey(base.id), primary_key=True)
97 return sa.Column(sa.Integer, primary_key=True)
98
99 db = SQLAlchemy(app, model_class=IdModel)
100
101 class User(db.Model):
102 name = db.Column(db.String)
103
104 class Employee(User):
105 title = db.Column(db.String)
106
107 else:
108
109 class Base(sa_orm.DeclarativeBase):
110 @sa_orm.declared_attr
111 @classmethod
112 def id(cls: type[sa_orm.DeclarativeBase]) -> sa_orm.Mapped[int]:
113 for base in cls.__mro__[1:-1]:
114 if getattr(base, "__table__", None) is not None and hasattr(
115 base, "id"
116 ):
117 return sa_orm.mapped_column(
118 db.ForeignKey(base.id), primary_key=True
119 )
120 return sa_orm.mapped_column(db.Integer, primary_key=True)
121
122 db = SQLAlchemy(app, model_class=Base)
123
124 class User(db.Model): # type: ignore[no-redef]
125 name: sa_orm.Mapped[str] = sa_orm.mapped_column(db.String)
126
127 class Employee(User): # type: ignore[no-redef]
128 title: sa_orm.Mapped[str] = sa_orm.mapped_column(db.String)
129
130 db.create_all()
131 db.session.add(Employee(name="Emp Loyee", title="Admin"))
132 db.session.commit()
133 user = db.session.execute(db.select(User)).scalar()
134 employee = db.session.execute(db.select(Employee)).scalar()
135 assert user is not None
136 assert employee is not None
137 assert user.id == 1
138 assert employee.id == 1
139
140
141@pytest.mark.usefixtures("app_ctx")

Callers

nothing calls this directly

Calls 3

create_allMethod · 0.95
SQLAlchemyClass · 0.90
EmployeeClass · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…