|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import typing as t |
| 4 | + |
| 5 | +import pytest |
| 6 | +import sqlalchemy as sa |
| 7 | +from flask import Flask |
| 8 | +from werkzeug.exceptions import NotFound |
| 9 | + |
| 10 | +from flask_sqlalchemy import SQLAlchemy |
| 11 | + |
| 12 | + |
| 13 | +@pytest.mark.usefixtures("app_ctx") |
| 14 | +def test_view_get_or_404(db: SQLAlchemy, Todo: t.Any) -> None: |
| 15 | + item = Todo() |
| 16 | + db.session.add(item) |
| 17 | + db.session.commit() |
| 18 | + assert db.get_or_404(Todo, 1) is item |
| 19 | + with pytest.raises(NotFound): |
| 20 | + assert db.get_or_404(Todo, 2) |
| 21 | + |
| 22 | + |
| 23 | +@pytest.mark.usefixtures("app_ctx") |
| 24 | +def test_first_or_404(db: SQLAlchemy, Todo: t.Any) -> None: |
| 25 | + db.session.add(Todo(title="a")) |
| 26 | + db.session.commit() |
| 27 | + result = db.first_or_404(db.select(Todo).filter_by(title="a")) |
| 28 | + assert result.title == "a" |
| 29 | + |
| 30 | + with pytest.raises(NotFound): |
| 31 | + db.first_or_404(db.select(Todo).filter_by(title="b")) |
| 32 | + |
| 33 | + |
| 34 | +@pytest.mark.usefixtures("app_ctx") |
| 35 | +def test_view_one_or_404(db: SQLAlchemy, Todo: t.Any) -> None: |
| 36 | + db.session.add(Todo(title="a")) |
| 37 | + db.session.add(Todo(title="b")) |
| 38 | + db.session.add(Todo(title="b")) |
| 39 | + db.session.commit() |
| 40 | + result = db.one_or_404(db.select(Todo).filter_by(title="a")) |
| 41 | + assert result.title == "a" |
| 42 | + |
| 43 | + with pytest.raises(NotFound): |
| 44 | + # MultipleResultsFound |
| 45 | + db.one_or_404(db.select(Todo).filter_by(title="b")) |
| 46 | + |
| 47 | + with pytest.raises(NotFound): |
| 48 | + # NoResultFound |
| 49 | + db.one_or_404(db.select(Todo).filter_by(title="c")) |
| 50 | + |
| 51 | + |
| 52 | +@pytest.mark.usefixtures("app_ctx") |
| 53 | +def test_paginate(db: SQLAlchemy, Todo: t.Any) -> None: |
| 54 | + db.session.add_all(Todo() for _ in range(150)) |
| 55 | + db.session.commit() |
| 56 | + p = db.paginate(db.select(Todo)) |
| 57 | + assert p.total == 150 |
| 58 | + assert len(p.items) == 20 |
| 59 | + p2 = p.next() |
| 60 | + assert p2.page == 2 |
| 61 | + assert p2.total == 150 |
| 62 | + |
| 63 | + |
| 64 | +# This test creates its own inline model so that it can use that as the type |
| 65 | +@pytest.mark.usefixtures("app_ctx") |
| 66 | +def test_view_get_or_404_typed(db: SQLAlchemy, app: Flask) -> None: |
| 67 | + class Quiz(db.Model): |
| 68 | + id = sa.Column(sa.Integer, primary_key=True) |
| 69 | + topic = sa.Column(sa.String) |
| 70 | + |
| 71 | + db.create_all() |
| 72 | + |
| 73 | + item: Quiz = Quiz() |
| 74 | + db.session.add(item) |
| 75 | + db.session.commit() |
| 76 | + result: Quiz = db.get_or_404(Quiz, 1) |
| 77 | + assert result is item |
| 78 | + with pytest.raises(NotFound): |
| 79 | + assert db.get_or_404(Quiz, 2) |
| 80 | + db.drop_all() |
0 commit comments