|
2 | 2 | from unittest.mock import patch |
3 | 3 |
|
4 | 4 | import pytest |
| 5 | +from sqlalchemy import inspect |
5 | 6 | from sqlmodel import Session |
6 | 7 |
|
7 | 8 | from kayman.crud.event import create_events, read_events, update_events |
8 | | -from kayman.schemas.event import EventType, EventUpdate |
| 9 | +from kayman.schemas.event import Event, EventType, EventUpdate |
9 | 10 | from kayman.tests.factories import ( |
10 | 11 | CategoryFactory, |
11 | 12 | EventEntryFactory, |
12 | 13 | EventFactory, |
| 14 | + TransactionFactory, |
13 | 15 | ) |
14 | 16 |
|
15 | 17 |
|
@@ -87,6 +89,36 @@ def test_read_events_by_ids(session: Session): |
87 | 89 | assert {event.id for event in multiple} == {event_1.id, event_2.id} |
88 | 90 |
|
89 | 91 |
|
| 92 | +def test_read_events_details_ordered_by_index( |
| 93 | + session: Session, # noqa: ARG001 (binds factory session) |
| 94 | + session_2: Session, |
| 95 | +): |
| 96 | + event = EventFactory() |
| 97 | + for index in (2, 0, 1): |
| 98 | + EventEntryFactory(event=event, index=index) |
| 99 | + TransactionFactory(event=event, index=index) |
| 100 | + |
| 101 | + events = read_events(session_2, event_ids=[event.id]) |
| 102 | + |
| 103 | + assert len(events) == 1 |
| 104 | + assert len(events[0].entries) == 3 |
| 105 | + assert [entry.index for entry in events[0].entries] == [0, 1, 2] |
| 106 | + assert len(events[0].transactions) == 3 |
| 107 | + assert [transaction.index for transaction in events[0].transactions] == [0, 1, 2] |
| 108 | + |
| 109 | + # The assertions above cannot fail on SQLite: it answers both lazy loads |
| 110 | + # from the (event_id, index) unique index, so rows come back in index order |
| 111 | + # even without an ORDER BY. Assert the relationships are configured to sort, |
| 112 | + # which is what actually holds on Postgres. |
| 113 | + relationships = inspect(Event).relationships |
| 114 | + assert [str(column) for column in relationships["entries"].order_by] == [ |
| 115 | + "event_entry.index" |
| 116 | + ] |
| 117 | + assert [str(column) for column in relationships["transactions"].order_by] == [ |
| 118 | + "transaction.index" |
| 119 | + ] |
| 120 | + |
| 121 | + |
90 | 122 | def test_read_events_all(session: Session): |
91 | 123 | for _ in range(10): |
92 | 124 | EventFactory() |
|
0 commit comments