| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import inspect |
| 4 |
import typing as t |
| 5 |
|
| 6 |
import pytest |
| 7 |
import sqlalchemy as sa |
| 8 |
import sqlalchemy.exc as sa_exc |
| 9 |
import sqlalchemy.orm as sa_orm |
| 10 |
|
| 11 |
from flask_sqlalchemy import SQLAlchemy |
| 12 |
from flask_sqlalchemy.model import camel_to_snake_case |
| 13 |
|
| 14 |
|
| 15 |
@pytest.mark.parametrize( |
| 16 |
("name", "expect"), |
| 17 |
[ |
| 18 |
("CamelCase", "camel_case"), |
| 19 |
("Snake_case", "snake_case"), |
| 20 |
("HTMLLayout", "html_layout"), |
| 21 |
("LayoutHTML", "layout_html"), |
| 22 |
("HTTP2Request", "http2_request"), |
| 23 |
("ShoppingCartSession", "shopping_cart_session"), |
| 24 |
("ABC", "abc"), |
| 25 |
("PreABC", "pre_abc"), |
| 26 |
("ABCPost", "abc_post"), |
| 27 |
("PreABCPost", "pre_abc_post"), |
| 28 |
("HTTP2RequestSession", "http2_request_session"), |
| 29 |
("UserST4", "user_st4"), |
| 30 |
( |
| 31 |
"HTTP2ClientType3EncoderParametersSSE", |
| 32 |
"http2_client_type3_encoder_parameters_sse", |
| 33 |
), |
| 34 |
( |
| 35 |
"LONGName4TestingCamelCase2snake_caseXYZ", |
| 36 |
"long_name4_testing_camel_case2snake_case_xyz", |
| 37 |
), |
| 38 |
("FooBarSSE2", "foo_bar_sse2"), |
| 39 |
("AlarmMessageSS2SignalTransformer", "alarm_message_ss2_signal_transformer"), |
| 40 |
("AstV2Node", "ast_v2_node"), |
| 41 |
("HTTPResponseCodeXYZ", "http_response_code_xyz"), |
| 42 |
("get2HTTPResponse123Code", "get2_http_response123_code"), |
| 43 |
# ("getHTTPresponseCode", "get_htt_presponse_code"), |
| 44 |
# ("__test__Method", "test___method"), |
| 45 |
], |
| 46 |
) |
| 47 |
def test_camel_to_snake_case(name: str, expect: str) -> None: |
| 48 |
assert camel_to_snake_case(name) == expect |
| 49 |
|
| 50 |
|
| 51 |
def test_name(db: SQLAlchemy) -> None: |
| 52 |
class FOOBar(db.Model): |
| 53 |
id = sa.Column(sa.Integer, primary_key=True) |
| 54 |
|
| 55 |
class BazBar(db.Model): |
| 56 |
id = sa.Column(sa.Integer, primary_key=True) |
| 57 |
|
| 58 |
class Ham(db.Model): |
| 59 |
__tablename__ = "spam" |
| 60 |
id = sa.Column(sa.Integer, primary_key=True) |
| 61 |
|
| 62 |
assert FOOBar.__tablename__ == "foo_bar" |
| 63 |
assert BazBar.__tablename__ == "baz_bar" |
| 64 |
assert Ham.__tablename__ == "spam" |
| 65 |
|
| 66 |
|
| 67 |
def test_single_name(db: SQLAlchemy) -> None: |
| 68 |
"""Single table inheritance should not set a new name.""" |
| 69 |
|
| 70 |
class Duck(db.Model): |
| 71 |
id = sa.Column(sa.Integer, primary_key=True) |
| 72 |
|
| 73 |
class Mallard(Duck): |
| 74 |
pass |
| 75 |
|
| 76 |
assert "__tablename__" not in Mallard.__dict__ |
| 77 |
assert Mallard.__tablename__ == "duck" |
| 78 |
|
| 79 |
|
| 80 |
def test_joined_name(db: SQLAlchemy) -> None: |
| 81 |
"""Model has a separate primary key; it should set a new name.""" |
| 82 |
|
| 83 |
class Duck(db.Model): |
| 84 |
id = sa.Column(sa.Integer, primary_key=True) |
| 85 |
|
| 86 |
class Donald(Duck): |
| 87 |
id = sa.Column(sa.Integer, sa.ForeignKey(Duck.id), primary_key=True) |
| 88 |
|
| 89 |
assert Donald.__tablename__ == "donald" |
| 90 |
|
| 91 |
|
| 92 |
def test_mixin_id(db: SQLAlchemy) -> None: |
| 93 |
"""Primary key provided by mixin should still allow model to set |
| 94 |
tablename. |
| 95 |
""" |
| 96 |
|
| 97 |
class Base: |
| 98 |
id = sa.Column(sa.Integer, primary_key=True) |
| 99 |
|
| 100 |
class Duck(Base, db.Model): |
| 101 |
pass |
| 102 |
|
| 103 |
assert not hasattr(Base, "__tablename__") |
| 104 |
assert Duck.__tablename__ == "duck" |
| 105 |
|
| 106 |
|
| 107 |
def test_mixin_attr(db: SQLAlchemy) -> None: |
| 108 |
"""A declared attr tablename will be used down multiple levels of |
| 109 |
inheritance. |
| 110 |
""" |
| 111 |
|
| 112 |
class Mixin: |
| 113 |
@sa_orm.declared_attr # type: ignore[arg-type] |
| 114 |
def __tablename__(cls) -> str: # noqa: B902 |
| 115 |
return cls.__name__.upper() # type: ignore[attr-defined,no-any-return] |
| 116 |
|
| 117 |
class Bird(Mixin, db.Model): |
| 118 |
id = sa.Column(sa.Integer, primary_key=True) |
| 119 |
|
| 120 |
class Duck(Bird): |
| 121 |
# object reference |
| 122 |
id = sa.Column(sa.Integer, sa.ForeignKey(Bird.id), primary_key=True) |
| 123 |
|
| 124 |
class Mallard(Duck): |
| 125 |
# string reference |
| 126 |
id = sa.Column(sa.Integer, sa.ForeignKey("DUCK.id"), primary_key=True) |
| 127 |
|
| 128 |
assert Bird.__tablename__ == "BIRD" |
| 129 |
assert Duck.__tablename__ == "DUCK" |
| 130 |
assert Mallard.__tablename__ == "MALLARD" |
| 131 |
|
| 132 |
|
| 133 |
def test_abstract_name(db: SQLAlchemy) -> None: |
| 134 |
"""Abstract model should not set a name. Subclass should set a name.""" |
| 135 |
|
| 136 |
class Base(db.Model): |
| 137 |
__abstract__ = True |
| 138 |
id = sa.Column(sa.Integer, primary_key=True) |
| 139 |
|
| 140 |
class Duck(Base): |
| 141 |
pass |
| 142 |
|
| 143 |
assert "__tablename__" not in Base.__dict__ |
| 144 |
assert Duck.__tablename__ == "duck" |
| 145 |
|
| 146 |
|
| 147 |
def test_complex_inheritance(db: SQLAlchemy) -> None: |
| 148 |
"""Joined table inheritance, but the new primary key is provided by a |
| 149 |
mixin, not directly on the class. |
| 150 |
""" |
| 151 |
|
| 152 |
class Duck(db.Model): |
| 153 |
id = sa.Column(sa.Integer, primary_key=True) |
| 154 |
|
| 155 |
class IdMixin: |
| 156 |
@sa_orm.declared_attr |
| 157 |
def id(cls): # type: ignore[no-untyped-def] # noqa: B902 |
| 158 |
return sa.Column(sa.Integer, sa.ForeignKey(Duck.id), primary_key=True) |
| 159 |
|
| 160 |
class RubberDuck(IdMixin, Duck): # type: ignore[misc] |
| 161 |
pass |
| 162 |
|
| 163 |
assert RubberDuck.__tablename__ == "rubber_duck" |
| 164 |
|
| 165 |
|
| 166 |
def test_manual_name(db: SQLAlchemy) -> None: |
| 167 |
"""Setting a manual name prevents generation for the immediate model. A |
| 168 |
name is generated for joined but not single-table inheritance. |
| 169 |
""" |
| 170 |
|
| 171 |
class Duck(db.Model): |
| 172 |
__tablename__ = "DUCK" |
| 173 |
id = sa.Column(sa.Integer, primary_key=True) |
| 174 |
type = sa.Column(sa.String) |
| 175 |
|
| 176 |
__mapper_args__ = {"polymorphic_on": type} |
| 177 |
|
| 178 |
class Daffy(Duck): |
| 179 |
id = sa.Column(sa.Integer, sa.ForeignKey(Duck.id), primary_key=True) |
| 180 |
|
| 181 |
__mapper_args__ = {"polymorphic_identity": "Tower"} # type: ignore[dict-item] |
| 182 |
|
| 183 |
class Donald(Duck): |
| 184 |
__mapper_args__ = {"polymorphic_identity": "Mouse"} # type: ignore[dict-item] |
| 185 |
|
| 186 |
assert Duck.__tablename__ == "DUCK" |
| 187 |
assert Daffy.__tablename__ == "daffy" |
| 188 |
assert "__tablename__" not in Donald.__dict__ |
| 189 |
assert Donald.__tablename__ == "DUCK" |
| 190 |
|
| 191 |
|
| 192 |
def test_primary_constraint(db: SQLAlchemy) -> None: |
| 193 |
"""Primary key will be picked up from table args.""" |
| 194 |
|
| 195 |
class Duck(db.Model): |
| 196 |
id = sa.Column(sa.Integer) |
| 197 |
|
| 198 |
__table_args__ = (sa.PrimaryKeyConstraint(id),) |
| 199 |
|
| 200 |
assert Duck.__table__ is not None |
| 201 |
assert Duck.__tablename__ == "duck" |
| 202 |
|
| 203 |
|
| 204 |
def test_no_access_to_class_property(db: SQLAlchemy) -> None: |
| 205 |
"""Ensure the implementation doesn't access class properties or declared |
| 206 |
attrs while inspecting the unmapped model. |
| 207 |
""" |
| 208 |
|
| 209 |
class class_property: |
| 210 |
def __init__(self, f: t.Callable[..., t.Any]) -> None: |
| 211 |
self.f = f |
| 212 |
|
| 213 |
def __get__(self, instance: t.Any, owner: type[t.Any]) -> t.Any: |
| 214 |
return self.f(owner) |
| 215 |
|
| 216 |
class Duck(db.Model): |
| 217 |
id = sa.Column(sa.Integer, primary_key=True) |
| 218 |
|
| 219 |
class ns: |
| 220 |
is_duck = False |
| 221 |
floats = False |
| 222 |
|
| 223 |
class Witch(Duck): |
| 224 |
@sa_orm.declared_attr # type: ignore[arg-type] |
| 225 |
def is_duck(self) -> None: |
| 226 |
# declared attrs will be accessed during mapper configuration, |
| 227 |
# but make sure they're not accessed before that |
| 228 |
info = inspect.getouterframes(inspect.currentframe())[2] |
| 229 |
assert info[3] != "_should_set_tablename" |
| 230 |
ns.is_duck = True |
| 231 |
|
| 232 |
@class_property |
| 233 |
def floats(self) -> None: |
| 234 |
ns.floats = True |
| 235 |
|
| 236 |
assert ns.is_duck |
| 237 |
assert not ns.floats |
| 238 |
|
| 239 |
|
| 240 |
def test_metadata_has_table(db: SQLAlchemy) -> None: |
| 241 |
user = db.Table("user", sa.Column("id", sa.Integer, primary_key=True)) |
| 242 |
|
| 243 |
class User(db.Model): |
| 244 |
pass |
| 245 |
|
| 246 |
assert User.__table__ is user |
| 247 |
|
| 248 |
|
| 249 |
def test_correct_error_for_no_primary_key(db: SQLAlchemy) -> None: |
| 250 |
with pytest.raises(sa_exc.ArgumentError) as info: |
| 251 |
|
| 252 |
class User(db.Model): |
| 253 |
pass |
| 254 |
|
| 255 |
assert "could not assemble any primary key" in str(info.value) |
| 256 |
|
| 257 |
|
| 258 |
def test_single_has_parent_table(db: SQLAlchemy) -> None: |
| 259 |
class Duck(db.Model): |
| 260 |
id = sa.Column(sa.Integer, primary_key=True) |
| 261 |
|
| 262 |
class Call(Duck): |
| 263 |
pass |
| 264 |
|
| 265 |
assert Call.__table__ is Duck.__table__ |
| 266 |
assert "__table__" not in Call.__dict__ |