| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
|
| 5 |
import pytest |
| 6 |
import sqlalchemy as sa |
| 7 |
import sqlalchemy.orm as sa_orm |
| 8 |
from flask import Flask |
| 9 |
|
| 10 |
from flask_sqlalchemy import SQLAlchemy |
| 11 |
from flask_sqlalchemy.record_queries import get_recorded_queries |
| 12 |
|
| 13 |
|
| 14 |
@pytest.mark.usefixtures("app_ctx") |
| 15 |
def test_query_info(app: Flask) -> None: |
| 16 |
app.config["SQLALCHEMY_RECORD_QUERIES"] = True |
| 17 |
db = SQLAlchemy(app) |
| 18 |
|
| 19 |
# Copied and pasted from conftest.py |
| 20 |
if issubclass(db.Model, (sa_orm.MappedAsDataclass)): |
| 21 |
|
| 22 |
class Todo(db.Model): |
| 23 |
id: sa_orm.Mapped[int] = sa_orm.mapped_column( |
| 24 |
sa.Integer, init=False, primary_key=True |
| 25 |
) |
| 26 |
title: sa_orm.Mapped[str] = sa_orm.mapped_column( |
| 27 |
sa.String, nullable=True, default=None |
| 28 |
) |
| 29 |
|
| 30 |
elif issubclass(db.Model, (sa_orm.DeclarativeBase, sa_orm.DeclarativeBaseNoMeta)): |
| 31 |
|
| 32 |
class Todo(db.Model): # type: ignore[no-redef] |
| 33 |
id: sa_orm.Mapped[int] = sa_orm.mapped_column(sa.Integer, primary_key=True) |
| 34 |
title: sa_orm.Mapped[str] = sa_orm.mapped_column(sa.String, nullable=True) |
| 35 |
|
| 36 |
else: |
| 37 |
|
| 38 |
class Todo(db.Model): # type: ignore[no-redef] |
| 39 |
id = sa.Column(sa.Integer, primary_key=True) |
| 40 |
title = sa.Column(sa.String) |
| 41 |
|
| 42 |
db.create_all() |
| 43 |
db.session.execute(sa.select(Todo).filter(Todo.id < 5)).scalars() |
| 44 |
info = get_recorded_queries()[-1] |
| 45 |
assert info.statement is not None |
| 46 |
assert "SELECT" in info.statement |
| 47 |
assert "FROM todo" in info.statement |
| 48 |
assert info.parameters[0][0] == 5 |
| 49 |
assert info.duration == info.end_time - info.start_time |
| 50 |
assert os.path.join("tests", "test_record_queries.py:") in info.location |
| 51 |
assert "(test_query_info)" in info.location |