1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
|
"""Tests for the Flask extension."""
from __future__ import annotations
from collections.abc import Generator, Sequence
from pathlib import Path
from typing import cast
import pytest
from flask import Flask, Response
from msgspec import Struct
from pydantic import BaseModel
from sqlalchemy import String, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from advanced_alchemy import base, mixins
from advanced_alchemy._listeners import is_async_context
from advanced_alchemy.exceptions import ImproperConfigurationError
from advanced_alchemy.extensions.flask import (
AdvancedAlchemy,
FlaskServiceMixin,
SQLAlchemyAsyncConfig,
SQLAlchemySyncConfig,
)
from advanced_alchemy.repository import SQLAlchemyAsyncRepository, SQLAlchemySyncRepository
from advanced_alchemy.service import SQLAlchemyAsyncRepositoryService, SQLAlchemySyncRepositoryService
metadata = base.metadata_registry.get("flask_testing")
class NewBigIntBase(mixins.BigIntPrimaryKey, base.CommonTableAttributes, DeclarativeBase):
"""Base model with a big integer primary key."""
__metadata__ = metadata
class User(NewBigIntBase):
"""Test user model."""
__tablename__ = "users_testing"
name: Mapped[str] = mapped_column(String(50))
class UserSchema(Struct):
"""Test user pydantic model."""
name: str
class UserPydantic(BaseModel):
"""Test user pydantic model."""
name: str
class UserService(SQLAlchemySyncRepositoryService[User], FlaskServiceMixin):
"""Test user service."""
class Repo(SQLAlchemySyncRepository[User]):
model_type = User
repository_type = Repo
class AsyncUserService(SQLAlchemyAsyncRepositoryService[User], FlaskServiceMixin):
"""Test user service."""
class Repo(SQLAlchemyAsyncRepository[User]):
model_type = User
repository_type = Repo
@pytest.fixture(scope="session")
def tmp_path_session(tmp_path_factory: pytest.TempPathFactory) -> Path:
return cast("Path", tmp_path_factory.mktemp("test_extensions_flask"))
@pytest.fixture(scope="session")
def setup_database(tmp_path_session: Path) -> Generator[Path, None, None]:
# Create a new database for each test
db_path = tmp_path_session / "test.db"
config = SQLAlchemySyncConfig(connection_string=f"sqlite:///{db_path}", metadata=metadata)
engine = config.get_engine()
User._sa_registry.metadata.create_all(engine) # pyright: ignore[reportPrivateUsage]
with config.get_session() as session:
assert isinstance(session, Session)
table_exists = session.execute(text("SELECT COUNT(*) FROM users_testing")).scalar_one()
assert table_exists >= 0
yield db_path
def test_sync_extension_init(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
config = SQLAlchemySyncConfig(connection_string=f"sqlite:///{setup_database}", metadata=metadata)
extension = AdvancedAlchemy(config, app)
assert "advanced_alchemy" in app.extensions
assert isinstance(extension, AdvancedAlchemy)
session = extension.get_sync_session()
assert is_async_context() is False
assert isinstance(session, Session)
def test_sync_extension_init_with_app(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
config = SQLAlchemySyncConfig(connection_string=f"sqlite:///{setup_database}", metadata=metadata)
extension = AdvancedAlchemy(config, app)
assert "advanced_alchemy" in app.extensions
assert isinstance(extension, AdvancedAlchemy)
session = extension.get_sync_session()
assert is_async_context() is False
assert isinstance(session, Session)
def test_sync_extension_multiple_init(setup_database: Path) -> None:
app = Flask(__name__)
with (
app.app_context(),
pytest.raises(ImproperConfigurationError, match="Advanced Alchemy extension is already registered"),
):
config = SQLAlchemySyncConfig(connection_string=f"sqlite:///{setup_database}", metadata=metadata)
extension = AdvancedAlchemy(config, app)
extension.init_app(app)
def test_async_extension_init(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
config = SQLAlchemyAsyncConfig(
bind_key="async", connection_string=f"sqlite+aiosqlite:///{setup_database}", metadata=metadata
)
extension = AdvancedAlchemy(config, app)
assert "advanced_alchemy" in app.extensions
session = extension.get_session("async")
assert isinstance(session, AsyncSession)
assert is_async_context() is True
extension.portal_provider.stop()
def test_async_extension_init_single_config_no_bind_key(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
config = SQLAlchemyAsyncConfig(connection_string=f"sqlite+aiosqlite:///{setup_database}", metadata=metadata)
extension = AdvancedAlchemy(config, app)
assert "advanced_alchemy" in app.extensions
session = extension.get_session()
assert isinstance(session, AsyncSession)
extension.portal_provider.stop()
def test_async_extension_init_with_app(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
config = SQLAlchemyAsyncConfig(
bind_key="async", connection_string=f"sqlite+aiosqlite:///{setup_database}", metadata=metadata
)
extension = AdvancedAlchemy(config, app)
assert "advanced_alchemy" in app.extensions
session = extension.get_session("async")
assert isinstance(session, AsyncSession)
extension.portal_provider.stop()
def test_async_extension_multiple_init(setup_database: Path) -> None:
app = Flask(__name__)
with (
app.app_context(),
pytest.raises(ImproperConfigurationError, match="Advanced Alchemy extension is already registered"),
):
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", bind_key="async", metadata=metadata
)
extension = AdvancedAlchemy(config, app)
extension.init_app(app)
def test_sync_and_async_extension_init(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
extension = AdvancedAlchemy(
[
SQLAlchemySyncConfig(connection_string=f"sqlite:///{setup_database}"),
SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", bind_key="async", metadata=metadata
),
],
app,
)
assert "advanced_alchemy" in app.extensions
session = extension.get_session()
assert isinstance(session, Session)
def test_multiple_binds(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
extension = AdvancedAlchemy(
[
SQLAlchemySyncConfig(
connection_string=f"sqlite:///{setup_database}", bind_key="db1", metadata=metadata
),
SQLAlchemySyncConfig(
connection_string=f"sqlite:///{setup_database}", bind_key="db2", metadata=metadata
),
],
app,
)
session = extension.get_session("db1")
assert isinstance(session, Session)
session = extension.get_session("db2")
assert isinstance(session, Session)
def test_multiple_binds_async(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
configs: Sequence[SQLAlchemyAsyncConfig] = [
SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", bind_key="db1", metadata=metadata
),
SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", bind_key="db2", metadata=metadata
),
]
extension = AdvancedAlchemy(configs, app)
session = extension.get_session("db1")
assert isinstance(session, AsyncSession)
session = extension.get_session("db2")
assert isinstance(session, AsyncSession)
extension.portal_provider.stop()
def test_mixed_binds(setup_database: Path) -> None:
app = Flask(__name__)
with app.app_context():
configs: Sequence[SQLAlchemyAsyncConfig | SQLAlchemySyncConfig] = [
SQLAlchemySyncConfig(connection_string=f"sqlite:///{setup_database}", bind_key="sync", metadata=metadata),
SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", bind_key="async", metadata=metadata
),
]
extension = AdvancedAlchemy(configs, app)
session = extension.get_session("sync")
assert isinstance(session, Session)
session.close()
session = extension.get_session("async")
assert isinstance(session, AsyncSession)
extension.portal_provider.portal.call(session.close)
extension.portal_provider.stop()
def test_sync_autocommit(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemySyncConfig(
connection_string=f"sqlite:///{setup_database}", commit_mode="autocommit", metadata=metadata
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[dict[str, str], int]:
session = extension.get_session()
assert isinstance(session, Session)
user = User(name="test")
session.add(user)
return {"status": "success"}, 200
# Test successful response (should commit)
response = client.post("/test")
assert response.status_code == 200
# Verify the data was committed
session = extension.get_session()
assert isinstance(session, Session)
result = session.execute(select(User).where(User.name == "test"))
assert result.scalar_one().name == "test"
def test_sync_autocommit_include_redirect(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemySyncConfig(
connection_string=f"sqlite:///{setup_database}",
commit_mode="autocommit_include_redirect",
metadata=metadata,
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[str, int, dict[str, str]]:
session = extension.get_session()
assert isinstance(session, Session)
session.add(User(name="test_redirect"))
return "", 302, {"Location": "/redirected"}
# Test redirect response (should commit with autocommit_include_redirect)
response = client.post("/test")
assert response.status_code == 302
# Verify the data was committed
session = extension.get_session()
assert isinstance(session, Session)
result = session.execute(select(User).where(User.name == "test_redirect"))
assert result.scalar_one().name == "test_redirect"
def test_sync_no_autocommit_on_error(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemySyncConfig(
connection_string=f"sqlite:///{setup_database}", commit_mode="autocommit", metadata=metadata
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[dict[str, str], int]:
session = extension.get_session()
assert isinstance(session, Session)
user = User(name="test_error")
session.add(user)
return {"error": "test error"}, 500
# Test error response (should not commit)
response = client.post("/test")
assert response.status_code == 500
# Verify the data was not committed
session = extension.get_session()
assert isinstance(session, Session)
result = session.execute(select(User).where(User.name == "test_error"))
assert result.first() is None
def test_async_autocommit(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", commit_mode="autocommit", metadata=metadata
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[dict[str, str], int]:
session = extension.get_session()
assert isinstance(session, AsyncSession)
session.add(User(name="test_async"))
return {"status": "success"}, 200
# Test successful response (should commit)
response = client.post("/test")
assert response.status_code == 200
# Verify the data was committed
session = extension.get_session()
assert isinstance(session, AsyncSession)
result = extension.portal_provider.portal.call(session.execute, select(User).where(User.name == "test_async"))
assert result.scalar_one().name == "test_async"
extension.portal_provider.stop()
def test_async_autocommit_include_redirect(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}",
commit_mode="autocommit_include_redirect",
metadata=metadata,
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[str, int, dict[str, str]]:
session = extension.get_session()
assert isinstance(session, AsyncSession)
user = User(name="test_async_redirect") # type: ignore
session.add(user)
return "", 302, {"Location": "/redirected"}
# Test redirect response (should commit with autocommit_include_redirect)
response = client.post("/test")
assert response.status_code == 302
session = extension.get_session()
assert isinstance(session, AsyncSession)
result = extension.portal_provider.portal.call(
session.execute, select(User).where(User.name == "test_async_redirect")
)
assert result.scalar_one().name == "test_async_redirect"
extension.portal_provider.stop()
def test_async_no_autocommit_on_error(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", commit_mode="autocommit", metadata=metadata
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[dict[str, str], int]:
session = extension.get_session()
assert isinstance(session, AsyncSession)
user = User(name="test_async_error") # type: ignore
session.add(user)
return {"error": "test async error"}, 500
# Test error response (should not commit)
response = client.post("/test")
assert response.status_code == 500
session = extension.get_session()
assert isinstance(session, AsyncSession)
async def get_user() -> User | None:
result = await session.execute(select(User).where(User.name == "test_async_error"))
return result.scalar_one_or_none()
# Verify the data was not committed
user = extension.portal_provider.portal.call(get_user)
assert user is None
extension.portal_provider.stop()
def test_async_portal_cleanup(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", commit_mode="manual", metadata=metadata
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[dict[str, str], int]:
session = extension.get_session()
assert isinstance(session, AsyncSession)
user = User(name="test_async_cleanup") # type: ignore
session.add(user)
return {"status": "success"}, 200
# Test successful response (should not commit since we're using MANUAL mode)
response = client.post("/test")
assert response.status_code == 200
session = extension.get_session()
assert isinstance(session, AsyncSession)
# Verify the data was not committed (MANUAL mode)
result = extension.portal_provider.portal.call(
session.execute, select(User).where(User.name == "test_async_cleanup")
)
assert result.first() is None
extension.portal_provider.stop()
def test_async_portal_explicit_stop(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}",
metadata=metadata,
commit_mode="manual",
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[dict[str, str], int]:
session = extension.get_session()
assert isinstance(session, AsyncSession)
user = User(name="test_async_explicit_stop") # type: ignore
session.add(user)
return {"status": "success"}, 200
# Test successful response (should not commit since we're using MANUAL mode)
response = client.post("/test")
assert response.status_code == 200
with app.app_context():
session = extension.get_session()
assert isinstance(session, AsyncSession)
# Verify the data was not committed (MANUAL mode)
result = extension.portal_provider.portal.call(
session.scalar, select(User).where(User.name == "test_async_explicit_stop")
)
assert result is None
extension.portal_provider.stop()
def test_async_portal_explicit_stop_with_commit(setup_database: Path) -> None:
app = Flask(__name__)
@app.route("/test", methods=["POST"])
def test_route() -> tuple[dict[str, str], int]:
session = extension.get_session()
assert isinstance(session, AsyncSession)
async def create_user() -> None:
user = User(name="test_async_explicit_stop_with_commit") # type: ignore
session.add(user)
await session.commit() # type: ignore
extension.portal_provider.portal.call(create_user)
return {"status": "success"}, 200
with app.test_client() as client:
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}",
metadata=metadata,
commit_mode="manual",
)
extension = AdvancedAlchemy(config, app)
# Test successful response
response = client.post("/test")
assert response.status_code == 200
# Verify in a new session
session = extension.get_session()
assert isinstance(session, AsyncSession)
async def get_user() -> User | None:
async with session:
result = await session.execute(select(User).where(User.name == "test_async_explicit_stop_with_commit"))
return result.scalar_one_or_none()
user = extension.portal_provider.portal.call(get_user)
assert isinstance(user, User)
assert user.name == "test_async_explicit_stop_with_commit"
extension.portal_provider.stop()
def test_sync_service_jsonify_msgspec(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemySyncConfig(
connection_string=f"sqlite:///{setup_database}", metadata=metadata, commit_mode="autocommit"
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> Response:
service = UserService(extension.get_sync_session())
user = service.create({"name": "service_test"})
return service.jsonify(service.to_schema(user, schema_type=UserSchema))
# Test successful response (should commit)
response = client.post("/test")
assert response.status_code == 200
# Verify the data was committed
session = extension.get_session()
assert isinstance(session, Session)
result = session.execute(select(User).where(User.name == "service_test"))
assert result.scalar_one().name == "service_test"
def test_async_service_jsonify_msgspec(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", metadata=metadata, commit_mode="autocommit"
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> Response:
service = AsyncUserService(extension.get_async_session())
user = extension.portal_provider.portal.call(service.create, {"name": "async_service_test"})
return service.jsonify(service.to_schema(user, schema_type=UserSchema))
# Test successful response (should commit)
response = client.post("/test")
assert response.status_code == 200
# Verify the data was committed
session = extension.get_session()
assert isinstance(session, AsyncSession)
result = extension.portal_provider.portal.call(
session.scalar, select(User).where(User.name == "async_service_test")
)
assert result
assert result.name == "async_service_test"
extension.portal_provider.stop()
def test_sync_service_jsonify_pydantic(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemySyncConfig(
connection_string=f"sqlite:///{setup_database}", metadata=metadata, commit_mode="autocommit"
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> Response:
service = UserService(extension.get_sync_session())
user = service.create({"name": "test_sync_service_jsonify_pydantic"})
return service.jsonify(service.to_schema(user, schema_type=UserPydantic))
# Test successful response (should commit)
response = client.post("/test")
assert response.status_code == 200
# Verify the data was committed
session = extension.get_session()
assert isinstance(session, Session)
result = session.execute(select(User).where(User.name == "test_sync_service_jsonify_pydantic"))
assert result.scalar_one().name == "test_sync_service_jsonify_pydantic"
def test_async_service_jsonify_pydantic(setup_database: Path) -> None:
app = Flask(__name__)
with app.test_client() as client:
config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{setup_database}", metadata=metadata, commit_mode="autocommit"
)
extension = AdvancedAlchemy(config, app)
@app.route("/test", methods=["POST"])
def test_route() -> Response:
service = AsyncUserService(extension.get_async_session())
user = extension.portal_provider.portal.call(
service.create, {"name": "test_async_service_jsonify_pydantic"}
)
return service.jsonify(service.to_schema(user, schema_type=UserPydantic))
# Test successful response (should commit)
response = client.post("/test")
assert response.status_code == 200
# Verify the data was committed
session = extension.get_session()
assert isinstance(session, AsyncSession)
result = extension.portal_provider.portal.call(
session.scalar, select(User).where(User.name == "test_async_service_jsonify_pydantic")
)
assert result
assert result.name == "test_async_service_jsonify_pydantic"
extension.portal_provider.stop()
|