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 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
|
"""Unit tests for the SQLAlchemy Repository implementation."""
from __future__ import annotations
import datetime
import decimal
from collections.abc import AsyncGenerator, Collection, Generator
from typing import TYPE_CHECKING, Any, Union, cast
from unittest.mock import AsyncMock, MagicMock, PropertyMock
from uuid import uuid4
import pytest
from msgspec import Struct
from pydantic import BaseModel
from pytest_lazy_fixtures import lf
from sqlalchemy import Integer, String
from sqlalchemy.exc import InvalidRequestError, SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import InstrumentedAttribute, Mapped, Session, mapped_column
from sqlalchemy.sql.selectable import ForUpdateArg
from sqlalchemy.types import TypeEngine
from advanced_alchemy import base
from advanced_alchemy.exceptions import IntegrityError, RepositoryError, wrap_sqlalchemy_exception
from advanced_alchemy.filters import (
BeforeAfter,
CollectionFilter,
LimitOffset,
NotInCollectionFilter,
OnBeforeAfter,
)
from advanced_alchemy.repository import (
SQLAlchemyAsyncRepository,
SQLAlchemySyncRepository,
)
from advanced_alchemy.repository._util import column_has_defaults, model_from_dict
from advanced_alchemy.service.typing import (
is_msgspec_struct,
is_pydantic_model,
is_schema,
is_schema_or_dict,
is_schema_or_dict_with_field,
is_schema_or_dict_without_field,
is_schema_with_field,
is_schema_without_field,
)
from tests.helpers import maybe_async
if TYPE_CHECKING:
from _pytest.fixtures import FixtureRequest
from pytest import MonkeyPatch
from pytest_mock import MockerFixture
AnyMock = Union[MagicMock, AsyncMock]
class UUIDModel(base.UUIDAuditBase):
"""Inheriting from UUIDAuditBase gives the model 'created_at' and 'updated_at'
columns.
"""
class BigIntModel(base.BigIntAuditBase):
"""Inheriting from BigIntAuditBase gives the model 'created_at' and 'updated_at'
columns.
"""
@pytest.fixture()
async def async_mock_repo() -> AsyncGenerator[SQLAlchemyAsyncRepository[MagicMock], None]:
"""SQLAlchemy repository with a mock model type."""
class Repo(SQLAlchemyAsyncRepository[MagicMock]):
"""Repo with mocked out stuff."""
model_type = MagicMock(__name__="MagicMock") # pyright:ignore[reportGeneralTypeIssues,reportAssignmentType]
session = AsyncMock(spec=AsyncSession, bind=MagicMock())
yield Repo(session=session, statement=MagicMock())
@pytest.fixture()
def sync_mock_repo() -> Generator[SQLAlchemySyncRepository[MagicMock], None, None]:
"""SQLAlchemy repository with a mock model type."""
class Repo(SQLAlchemySyncRepository[MagicMock]):
"""Repo with mocked out stuff."""
model_type = MagicMock(__name__="MagicMock") # pyright:ignore[reportGeneralTypeIssues,reportAssignmentType]
yield Repo(session=MagicMock(spec=Session, bind=MagicMock()), statement=MagicMock())
@pytest.fixture(params=[lf("sync_mock_repo"), lf("async_mock_repo")])
def mock_repo(request: FixtureRequest) -> Generator[SQLAlchemyAsyncRepository[MagicMock], None, None]:
yield cast(SQLAlchemyAsyncRepository[Any], request.param)
@pytest.fixture()
def mock_session_scalars( # pyright: ignore[reportUnknownParameterType]
mock_repo: SQLAlchemyAsyncRepository[MagicMock], mocker: MockerFixture
) -> Generator[AnyMock, None, None]:
yield mocker.patch.object(mock_repo.session, "scalars")
@pytest.fixture()
def mock_session_execute( # pyright: ignore[reportUnknownParameterType]
mock_repo: SQLAlchemyAsyncRepository[MagicMock], mocker: MockerFixture
) -> Generator[AnyMock, None, None]:
yield mocker.patch.object(mock_repo.session, "scalars")
@pytest.fixture()
def mock_repo_list( # pyright: ignore[reportUnknownParameterType]
mock_repo: SQLAlchemyAsyncRepository[MagicMock], mocker: MockerFixture
) -> Generator[AnyMock, None, None]:
yield mocker.patch.object(mock_repo, "list")
@pytest.fixture()
def mock_repo_execute( # pyright: ignore[reportUnknownParameterType]
mock_repo: SQLAlchemyAsyncRepository[MagicMock], mocker: MockerFixture
) -> Generator[AnyMock, None, None]:
yield mocker.patch.object(mock_repo, "_execute")
@pytest.fixture()
def mock_repo_attach_to_session( # pyright: ignore[reportUnknownParameterType]
mock_repo: SQLAlchemyAsyncRepository[MagicMock], mocker: MockerFixture
) -> Generator[AnyMock, None, None]:
yield mocker.patch.object(mock_repo, "_attach_to_session")
@pytest.fixture()
def mock_repo_count( # pyright: ignore[reportUnknownParameterType]
mock_repo: SQLAlchemyAsyncRepository[MagicMock], mocker: MockerFixture
) -> Generator[AnyMock, None, None]:
yield mocker.patch.object(mock_repo, "count")
def test_sqlalchemy_tablename() -> None:
"""Test the snake case conversion for table names."""
class BigModel(base.UUIDAuditBase):
"""Inheriting from UUIDAuditBase gives the model 'created_at' and 'updated_at'
columns.
"""
class TESTModel(base.UUIDAuditBase):
"""Inheriting from UUIDAuditBase gives the model 'created_at' and 'updated_at'
columns.
"""
class OtherBigIntModel(base.BigIntAuditBase):
"""Inheriting from BigIntAuditBase gives the model 'created_at' and 'updated_at'
columns.
"""
assert BigModel.__tablename__ == "big_model"
assert TESTModel.__tablename__ == "test_model"
assert OtherBigIntModel.__tablename__ == "other_big_int_model"
def test_sqlalchemy_sentinel(monkeypatch: MonkeyPatch) -> None:
"""Test the sqlalchemy sentinel column only exists on `UUIDPrimaryKey` models."""
class AnotherModel(base.UUIDAuditBase):
"""Inheriting from UUIDAuditBase gives the model 'created_at' and 'updated_at'
columns.
"""
the_extra_col: Mapped[str] = mapped_column(String(length=100), nullable=True) # pyright: ignore
class TheTestModel(base.UUIDBase):
"""Inheriting from DeclarativeBase gives the model 'id' columns."""
the_extra_col: Mapped[str] = mapped_column(String(length=100), nullable=True) # pyright: ignore
class TheBigIntModel(base.BigIntBase):
"""Inheriting from DeclarativeBase gives the model 'id' columns."""
the_extra_col: Mapped[str] = mapped_column(String(length=100), nullable=True) # pyright: ignore
unloaded_cols = {"the_extra_col"}
sa_instance_mock = MagicMock(unloaded=unloaded_cols)
assert isinstance(AnotherModel._sentinel, InstrumentedAttribute) # pyright: ignore
assert isinstance(TheTestModel._sentinel, InstrumentedAttribute) # pyright: ignore
assert not hasattr(TheBigIntModel, "_sentinel")
model1, model2, model3 = AnotherModel(), TheTestModel(), TheBigIntModel()
monkeypatch.setattr(model1, "_sa_instance_state", sa_instance_mock)
monkeypatch.setattr(model2, "_sa_instance_state", sa_instance_mock)
monkeypatch.setattr(model3, "_sa_instance_state", sa_instance_mock)
assert "created_at" not in model1.to_dict(exclude={"created_at"})
assert "the_extra_col" not in model1.to_dict(exclude={"created_at"})
assert "sa_orm_sentinel" not in model1.to_dict()
assert "sa_orm_sentinel" not in model2.to_dict()
assert "sa_orm_sentinel" not in model3.to_dict()
assert "_sentinel" not in model1.to_dict()
assert "_sentinel" not in model2.to_dict()
assert "_sentinel" not in model3.to_dict()
assert "the_extra_col" not in model1.to_dict()
def test_wrap_sqlalchemy_integrity_error() -> None:
"""Test to ensure we wrap IntegrityError."""
with pytest.raises(IntegrityError), wrap_sqlalchemy_exception():
raise IntegrityError(None, None, Exception())
def test_wrap_sqlalchemy_generic_error() -> None:
"""Test to ensure we wrap generic SQLAlchemy exceptions."""
with pytest.raises(RepositoryError), wrap_sqlalchemy_exception():
raise SQLAlchemyError
async def test_sqlalchemy_repo_add(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test expected method calls for add operation."""
mock_instance = MagicMock()
instance = await maybe_async(mock_repo.add(mock_instance))
assert instance is mock_instance
mock_repo.session.add.assert_called_once_with(mock_instance) # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.flush.assert_called_once() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.refresh.assert_called_once_with( # pyright: ignore[reportFunctionMemberAccess]
instance=mock_instance,
attribute_names=None,
with_for_update=None,
)
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_add_many(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mocker: MockerFixture,
request: FixtureRequest,
) -> None:
"""Test expected method calls for add many operation."""
mock_instances = [MagicMock(), MagicMock(), MagicMock()]
monkeypatch.setattr(mock_repo, "model_type", UUIDModel)
mocker.patch.object(mock_repo.session, "scalars", return_value=mock_instances)
instances = await maybe_async(mock_repo.add_many(mock_instances))
assert len(instances) == 3
for row in instances:
assert row.id is not None
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_update_many(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mocker: MockerFixture,
) -> None:
"""Test expected method calls for update many operation."""
mock_instances = [MagicMock(), MagicMock(), MagicMock()]
monkeypatch.setattr(mock_repo, "model_type", UUIDModel)
mocker.patch.object(mock_repo.session, "scalars", return_value=mock_instances)
instances = await maybe_async(mock_repo.update_many(mock_instances))
assert len(instances) == 3
for row in instances:
assert row.id is not None
mock_repo.session.flush.assert_called_once() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_upsert_many(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mocker: MockerFixture,
) -> None:
"""Test expected method calls for update many operation."""
mock_instances = [MagicMock(), MagicMock(), MagicMock()]
monkeypatch.setattr(mock_repo, "model_type", UUIDModel)
mocker.patch.object(mock_repo.session, "scalars", return_value=mock_instances)
mocker.patch.object(mock_repo, "list", return_value=mock_instances)
mocker.patch.object(mock_repo, "add_many", return_value=mock_instances)
mocker.patch.object(mock_repo, "update_many", return_value=mock_instances)
instances = await maybe_async(mock_repo.upsert_many(mock_instances))
assert len(instances) == 3
for row in instances:
assert row.id is not None
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_delete(mock_repo: SQLAlchemyAsyncRepository[Any], mocker: MockerFixture) -> None:
"""Test expected method calls for delete operation."""
mock_instance = MagicMock()
mocker.patch.object(mock_repo, "get", return_value=mock_instance)
instance = await maybe_async(mock_repo.delete("instance-id"))
assert instance is mock_instance
mock_repo.session.delete.assert_called_once_with(mock_instance) # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.flush.assert_called_once() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_delete_many_uuid(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_session_scalars: AnyMock,
mock_session_execute: AnyMock,
mock_repo_list: AnyMock,
) -> None:
"""Test expected method calls for delete operation."""
mock_instances = [MagicMock(), MagicMock(id=uuid4())]
mock_session_scalars.return_value = mock_instances
mock_session_execute.return_value = mock_instances
mock_repo_list.return_value = mock_instances
monkeypatch.setattr(mock_repo, "model_type", UUIDModel)
monkeypatch.setattr(mock_repo.session.bind.dialect, "insertmanyvalues_max_parameters", 2)
added_instances = await maybe_async(mock_repo.add_many(mock_instances))
instances = await maybe_async(mock_repo.delete_many([obj.id for obj in added_instances]))
assert len(instances) == len(mock_instances)
mock_repo.session.flush.assert_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_delete_many_bigint(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_session_scalars: AnyMock,
mock_session_execute: AnyMock,
mock_repo_list: AnyMock,
testrun_uid: str,
) -> None:
"""Test expected method calls for delete operation."""
mock_instances = [MagicMock(), MagicMock(id=uuid4())]
mock_session_scalars.return_value = mock_instances
mock_session_execute.return_value = mock_instances
mock_repo_list.return_value = mock_instances
monkeypatch.setattr(mock_repo, "model_type", BigIntModel)
monkeypatch.setattr(mock_repo.session.bind.dialect, "insertmanyvalues_max_parameters", 2)
added_instances = await maybe_async(mock_repo.add_many(mock_instances))
instances = await maybe_async(mock_repo.delete_many([obj.id for obj in added_instances]))
assert len(instances) == len(mock_instances)
mock_repo.session.flush.assert_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_get_member(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
) -> None:
"""Test expected method calls for member get operation."""
mock_instance = MagicMock()
mock_repo_execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=mock_instance))
instance = await maybe_async(mock_repo.get("instance-id"))
assert instance is mock_instance
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_get_with_for_update(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
"""Ensure FOR UPDATE options are applied when requested."""
statement = MagicMock()
statement.options.return_value = statement
statement.execution_options.return_value = statement
statement.with_for_update.return_value = statement
mock_repo.statement = statement
mocker.patch.object(mock_repo, "_get_loader_options", return_value=([], False))
mocker.patch.object(mock_repo, "_get_base_stmt", return_value=statement)
mocker.patch.object(mock_repo, "_apply_filters", return_value=statement)
mocker.patch.object(mock_repo, "_filter_select_by_kwargs", return_value=statement)
execute_result = MagicMock()
execute_result.scalar_one_or_none.return_value = MagicMock()
execute = mocker.patch.object(mock_repo, "_execute", return_value=execute_result)
instance = await maybe_async(mock_repo.get("instance-id", with_for_update=True))
assert instance is execute_result.scalar_one_or_none.return_value
statement.with_for_update.assert_called_once_with()
execute.assert_called_once_with(statement, uniquify=False)
async def test_sqlalchemy_repo_get_with_for_update_dict(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
statement = MagicMock()
statement.options.return_value = statement
statement.execution_options.return_value = statement
statement.with_for_update.return_value = statement
mock_repo.statement = statement
mocker.patch.object(mock_repo, "_get_loader_options", return_value=([], False))
mocker.patch.object(mock_repo, "_get_base_stmt", return_value=statement)
mocker.patch.object(mock_repo, "_apply_filters", return_value=statement)
mocker.patch.object(mock_repo, "_filter_select_by_kwargs", return_value=statement)
execute_result = MagicMock()
execute_result.scalar_one_or_none.return_value = MagicMock()
mocker.patch.object(mock_repo, "_execute", return_value=execute_result)
await maybe_async(
mock_repo.get(
"instance-id",
with_for_update={"nowait": True, "read": False},
)
)
statement.with_for_update.assert_called_once_with(nowait=True, read=False)
async def test_sqlalchemy_repo_get_with_for_update_arg(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
statement = MagicMock()
statement.options.return_value = statement
statement.execution_options.return_value = statement
statement.with_for_update.return_value = statement
mock_repo.statement = statement
mocker.patch.object(mock_repo, "_get_loader_options", return_value=([], False))
mocker.patch.object(mock_repo, "_get_base_stmt", return_value=statement)
mocker.patch.object(mock_repo, "_apply_filters", return_value=statement)
mocker.patch.object(mock_repo, "_filter_select_by_kwargs", return_value=statement)
execute_result = MagicMock()
execute_result.scalar_one_or_none.return_value = MagicMock()
mocker.patch.object(mock_repo, "_execute", return_value=execute_result)
await maybe_async(
mock_repo.get(
"instance-id",
with_for_update=ForUpdateArg(nowait=True, key_share=True),
)
)
statement.with_for_update.assert_called_once_with(nowait=True, read=False, skip_locked=False, key_share=True)
async def test_sqlalchemy_repo_get_one_member(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
) -> None:
"""Test expected method calls for member get one operation."""
mock_instance = MagicMock()
mock_repo_execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=mock_instance))
instance = await maybe_async(mock_repo.get_one(id="instance-id"))
assert instance is mock_instance
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_get_or_upsert_member_existing(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mock_repo_attach_to_session: AnyMock,
) -> None:
"""Test expected method calls for member get or create operation (existing)."""
mock_instance = MagicMock()
mock_repo_execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=mock_instance))
mock_repo_attach_to_session.return_value = mock_instance
instance, created = await maybe_async(mock_repo.get_or_upsert(id="instance-id", upsert=False))
assert instance is mock_instance
assert created is False
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.merge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.refresh.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_get_or_upsert_member_existing_upsert(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mock_repo_attach_to_session: AnyMock,
) -> None:
"""Test expected method calls for member get or create operation (existing)."""
mock_instance = MagicMock()
mock_repo_execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=mock_instance))
mock_repo_attach_to_session.return_value = mock_instance
instance, created = await maybe_async(
mock_repo.get_or_upsert(id="instance-id", upsert=True, an_extra_attribute="yep"),
)
assert instance is mock_instance
assert created is False
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo._attach_to_session.assert_called_once() # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
mock_repo.session.flush.assert_called_once() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.refresh.assert_called_once_with( # pyright: ignore[reportFunctionMemberAccess]
instance=mock_instance,
attribute_names=None,
with_for_update=None,
)
async def test_sqlalchemy_repo_get_or_upsert_member_existing_no_upsert(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
) -> None:
"""Test expected method calls for member get or create operation (existing)."""
mock_instance = MagicMock()
mock_repo_execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=mock_instance))
instance, created = await maybe_async(
mock_repo.get_or_upsert(id="instance-id", upsert=False, an_extra_attribute="yep"),
)
assert instance is mock_instance
assert created is False
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.add.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.refresh.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_get_or_upsert_member_created(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
) -> None:
"""Test expected method calls for member get or create operation (created)."""
mock_repo_execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=None))
instance, created = await maybe_async(mock_repo.get_or_upsert(id="new-id"))
assert instance is not None
assert created is True
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.add.assert_called_once_with(instance) # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.refresh.assert_called_once_with(instance=instance, attribute_names=None, with_for_update=None) # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_get_one_or_none_member(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
) -> None:
"""Test expected method calls for member get one or none operation (found)."""
mock_instance = MagicMock()
mock_repo_execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=mock_instance))
instance = await maybe_async(mock_repo.get_one_or_none(id="instance-id"))
assert instance is mock_instance
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_get_one_or_none_not_found(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
) -> None:
"""Test expected method calls for member get one or none operation (Not found)."""
mock_repo_execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=None))
instance = await maybe_async(mock_repo.get_one_or_none(id="instance-id"))
assert instance is None
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_list(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
) -> None:
"""Test expected method calls for list operation."""
mock_instances = [MagicMock(), MagicMock()]
mock_repo_execute.return_value = MagicMock(scalars=MagicMock(return_value=mock_instances))
instances = await maybe_async(mock_repo.list())
assert instances == mock_instances
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_list_and_count(mock_repo: SQLAlchemyAsyncRepository[Any], mocker: MockerFixture) -> None:
"""Test expected method calls for list operation."""
mock_instances = [MagicMock(), MagicMock()]
mock_count = len(mock_instances)
mocker.patch.object(mock_repo, "_list_and_count_window", return_value=(mock_instances, mock_count))
instances, instance_count = await maybe_async(mock_repo.list_and_count())
assert instances == mock_instances
assert instance_count == mock_count
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_list_and_count_basic(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
"""Test expected method calls for list operation."""
mock_instances = [MagicMock(), MagicMock()]
mock_count = len(mock_instances)
mocker.patch.object(mock_repo, "_list_and_count_basic", return_value=(mock_instances, mock_count))
instances, instance_count = await maybe_async(mock_repo.list_and_count(count_with_window_function=False))
assert instances == mock_instances
assert instance_count == mock_count
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_exists(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mock_repo_count: AnyMock,
) -> None:
"""Test expected method calls for exists operation."""
mock_repo_count.return_value = 1
exists = await maybe_async(mock_repo.exists(id="my-id"))
assert exists
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_exists_with_filter(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mock_repo_count: AnyMock,
) -> None:
"""Test expected method calls for exists operation. with filter argument"""
limit_filter = LimitOffset(limit=1, offset=0)
mock_repo_count.return_value = 1
exists = await maybe_async(mock_repo.exists(limit_filter, id="my-id"))
assert exists
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_count(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mock_repo_count: AnyMock,
) -> None:
"""Test expected method calls for list operation."""
mock_repo_count.return_value = 1
count = await maybe_async(mock_repo.count())
assert count == 1
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
async def test_sqlalchemy_repo_list_with_pagination(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mocker: MockerFixture,
) -> None:
"""Test list operation with pagination."""
statement = MagicMock()
mock_repo_execute.return_value = MagicMock()
mocker.patch.object(LimitOffset, "append_to_statement", return_value=statement)
mock_repo_execute.return_value = MagicMock()
await maybe_async(mock_repo.list(LimitOffset(2, 3)))
mock_repo._execute.assert_called_with(statement, uniquify=False) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
async def test_sqlalchemy_repo_list_with_before_after_filter(
mock_repo: SQLAlchemyAsyncRepository[Any],
mock_repo_execute: AnyMock,
mocker: MockerFixture,
) -> None:
"""Test list operation with BeforeAfter filter."""
statement = MagicMock()
mocker.patch.object(mock_repo.model_type.updated_at, "__lt__", return_value="lt")
mocker.patch.object(mock_repo.model_type.updated_at, "__gt__", return_value="gt")
mocker.patch.object(BeforeAfter, "append_to_statement", return_value=statement)
mock_repo_execute.return_value = MagicMock()
await maybe_async(mock_repo.list(BeforeAfter("updated_at", datetime.datetime.max, datetime.datetime.min)))
mock_repo._execute.assert_called_with(statement, uniquify=False) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
async def test_sqlalchemy_repo_list_with_on_before_after_filter(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mocker: MockerFixture,
) -> None:
"""Test list operation with BeforeAfter filter."""
statement = MagicMock()
mocker.patch.object(mock_repo.model_type.updated_at, "__le__", return_value="le")
mocker.patch.object(mock_repo.model_type.updated_at, "__ge__", return_value="ge")
mocker.patch.object(OnBeforeAfter, "append_to_statement", return_value=statement)
mock_repo_execute.return_value = MagicMock()
await maybe_async(mock_repo.list(OnBeforeAfter("updated_at", datetime.datetime.max, datetime.datetime.min)))
mock_repo._execute.assert_called_with(statement, uniquify=False) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
async def test_sqlalchemy_repo_list_with_collection_filter(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mocker: MockerFixture,
) -> None:
"""Test behavior of list operation given CollectionFilter."""
field_name = "id"
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement # pyright: ignore[reportFunctionMemberAccess]
mocker.patch.object(CollectionFilter, "append_to_statement", return_value=mock_repo.statement)
values = [1, 2, 3]
await maybe_async(mock_repo.list(CollectionFilter(field_name, values)))
mock_repo._execute.assert_called_with(mock_repo.statement, uniquify=False) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
async def test_sqlalchemy_repo_list_with_null_collection_filter(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mocker: MockerFixture,
) -> None:
"""Test behavior of list operation given CollectionFilter."""
field_name = "id"
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement # pyright: ignore[reportFunctionMemberAccess]
monkeypatch.setattr(
CollectionFilter,
"append_to_statement",
MagicMock(return_value=mock_repo.statement),
)
await maybe_async(mock_repo.list(CollectionFilter(field_name, None))) # pyright: ignore[reportFunctionMemberAccess,reportUnknownArgumentType]
mock_repo._execute.assert_called_with(mock_repo.statement, uniquify=False) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
async def test_sqlalchemy_repo_empty_list_with_collection_filter(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mocker: MockerFixture,
) -> None:
"""Test behavior of list operation given CollectionFilter."""
field_name = "id"
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement # pyright: ignore[reportFunctionMemberAccess]
values: Collection[Any] = []
await maybe_async(mock_repo.list(CollectionFilter(field_name, values)))
monkeypatch.setattr(
CollectionFilter,
"append_to_statement",
MagicMock(return_value=mock_repo.statement),
)
await maybe_async(mock_repo.list(CollectionFilter(field_name, values)))
mock_repo._execute.assert_called_with(mock_repo.statement, uniquify=False) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
async def test_sqlalchemy_repo_list_with_not_in_collection_filter(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mocker: MockerFixture,
) -> None:
"""Test behavior of list operation given CollectionFilter."""
field_name = "id"
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement # pyright: ignore[reportFunctionMemberAccess]
monkeypatch.setattr(
NotInCollectionFilter,
"append_to_statement",
MagicMock(return_value=mock_repo.statement),
)
values = [1, 2, 3]
await maybe_async(mock_repo.list(NotInCollectionFilter(field_name, values)))
mock_repo._execute.assert_called_with(mock_repo.statement, uniquify=False) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
async def test_sqlalchemy_repo_list_with_null_not_in_collection_filter(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mock_repo_execute: AnyMock,
mocker: MockerFixture,
) -> None:
"""Test behavior of list operation given CollectionFilter."""
field_name = "id"
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement # pyright: ignore[reportFunctionMemberAccess]
monkeypatch.setattr(
NotInCollectionFilter,
"append_to_statement",
MagicMock(return_value=mock_repo.statement),
)
await maybe_async(mock_repo.list(NotInCollectionFilter[str](field_name, None))) # pyright: ignore[reportFunctionMemberAccess]
mock_repo._execute.assert_called_with(mock_repo.statement, uniquify=False) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
async def test_sqlalchemy_repo_unknown_filter_type_raises(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test that repo raises exception if list receives unknown filter type."""
with pytest.raises(RepositoryError):
await maybe_async(mock_repo.list("not a filter")) # type: ignore
async def test_sqlalchemy_repo_update(
mock_repo: SQLAlchemyAsyncRepository[Any],
monkeypatch: MonkeyPatch,
mocker: MockerFixture,
) -> None:
"""Test the sequence of repo calls for update operation."""
id_ = 3
mock_instance = MagicMock()
existing_instance = MagicMock()
mocker.patch.object(mock_repo, "get_id_attribute_value", return_value=id_)
mocker.patch.object(mock_repo, "get", return_value=existing_instance)
mock_repo.session.merge.return_value = existing_instance # pyright: ignore[reportFunctionMemberAccess]
instance = await maybe_async(mock_repo.update(mock_instance))
assert instance is existing_instance
mock_repo.session.merge.assert_called_once_with(existing_instance, load=True) # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.flush.assert_called_once() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.refresh.assert_called_once_with( # pyright: ignore[reportFunctionMemberAccess]
instance=existing_instance,
attribute_names=None,
with_for_update=None,
)
async def test_sqlalchemy_repo_upsert(mock_repo: SQLAlchemyAsyncRepository[Any], mocker: MockerFixture) -> None:
"""Test the sequence of repo calls for upsert operation."""
mock_instance = MagicMock()
mock_repo.session.merge.return_value = mock_instance # pyright: ignore[reportFunctionMemberAccess]
instance = await maybe_async(mock_repo.upsert(mock_instance))
mocker.patch.object(mock_repo, "exists", return_value=True)
mocker.patch.object(mock_repo, "count", return_value=1)
assert instance is mock_instance
mock_repo.session.flush.assert_called_once() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.expunge.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.commit.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
mock_repo.session.refresh.assert_called_once_with( # pyright: ignore[reportFunctionMemberAccess]
instance=mock_instance,
attribute_names=None,
with_for_update=None,
)
async def test_attach_to_session_unexpected_strategy_raises_valueerror(
mock_repo: SQLAlchemyAsyncRepository[Any],
) -> None:
"""Test to hit the error condition in SQLAlchemy._attach_to_session()."""
with pytest.raises(ValueError):
await maybe_async(mock_repo._attach_to_session(MagicMock(), strategy="t-rex")) # type:ignore[arg-type]
async def test_execute(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Simple test of the abstraction over `AsyncSession.execute()`"""
_ = await maybe_async(mock_repo._execute(mock_repo.statement)) # pyright: ignore[reportFunctionMemberAccess,reportPrivateUsage]
mock_repo.session.execute.assert_called_once_with(mock_repo.statement) # pyright: ignore[reportFunctionMemberAccess]
async def test_filter_in_collection_noop_if_collection_empty(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Ensures we don't filter on an empty collection."""
statement = MagicMock()
filter = CollectionFilter(field_name="id", values=[]) # type:ignore[var-annotated]
statement = filter.append_to_statement(statement, MagicMock()) # type:ignore[assignment]
mock_repo.statement.where.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
@pytest.mark.parametrize(
("before", "after"),
[
(datetime.datetime.max, datetime.datetime.min),
(None, datetime.datetime.min),
(datetime.datetime.max, None),
],
)
async def test_filter_on_datetime_field(
before: datetime.datetime,
after: datetime.datetime,
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
monkeypatch: MonkeyPatch,
) -> None:
"""Test through branches of _filter_on_datetime_field()"""
field_mock = MagicMock(return_value=before or after)
statement = MagicMock()
field_mock.__gt__ = field_mock.__lt__ = lambda self, other: True # pyright: ignore[reportFunctionMemberAccess,reportUnknownLambdaType]
monkeypatch.setattr(
BeforeAfter,
"append_to_statement",
MagicMock(return_value=mock_repo.statement),
)
filter = BeforeAfter(field_name="updated_at", before=before, after=after)
statement = filter.append_to_statement(statement, MagicMock(return_value=before or after)) # type:ignore[assignment]
mock_repo.model_type.updated_at = field_mock
mock_repo.statement.where.assert_not_called() # pyright: ignore[reportFunctionMemberAccess]
# Type compatibility test fixtures and classes
class MockComplexType:
"""Mock complex type that would have DBAPI serialization issues."""
def __init__(self, value: Any):
self.value = value
class MockPostgreSQLRange:
"""Mock PostgreSQL Range type."""
def __init__(self, lower: Any, upper: Any):
self.lower = lower
self.upper = upper
class MockTypeWithoutPythonType(TypeEngine[Any]):
"""Mock SQLAlchemy type that doesn't implement python_type."""
def __init__(self) -> None:
super().__init__()
@property
def python_type(self) -> type[Any]:
raise NotImplementedError("This type doesn't have a python_type")
async def test_type_must_use_in_empty_list(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test that empty list returns False."""
result = mock_repo._type_must_use_in_instead_of_any([])
assert result is False
async def test_type_must_use_in_standard_python_types(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test that standard Python types can use ANY() operator."""
# Test integers
result = mock_repo._type_must_use_in_instead_of_any([1, 2, 3])
assert result is False
# Test strings
result = mock_repo._type_must_use_in_instead_of_any(["a", "b", "c"])
assert result is False
# Test booleans
result = mock_repo._type_must_use_in_instead_of_any([True, False])
assert result is False
# Test floats
result = mock_repo._type_must_use_in_instead_of_any([1.1, 2.2])
assert result is False
# Test bytes
result = mock_repo._type_must_use_in_instead_of_any([b"test", b"data"])
assert result is False
async def test_type_must_use_in_safe_datetime_decimal_types(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test that datetime and decimal types can use ANY() operator."""
# Test datetime.date
result = mock_repo._type_must_use_in_instead_of_any([datetime.date(2024, 1, 1)])
assert result is False
# Test datetime.datetime
result = mock_repo._type_must_use_in_instead_of_any([datetime.datetime.now()])
assert result is False
# Test datetime.time
result = mock_repo._type_must_use_in_instead_of_any([datetime.time(12, 30)])
assert result is False
# Test datetime.timedelta
result = mock_repo._type_must_use_in_instead_of_any([datetime.timedelta(days=1)])
assert result is False
# Test decimal.Decimal
result = mock_repo._type_must_use_in_instead_of_any([decimal.Decimal("10.5")])
assert result is False
async def test_type_must_use_in_complex_types(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test that complex types must use IN() operator."""
# Test mock PostgreSQL Range
ranges = [MockPostgreSQLRange(1, 10), MockPostgreSQLRange(20, 30)]
result = mock_repo._type_must_use_in_instead_of_any(ranges)
assert result is True
# Test custom complex type
complex_types = [MockComplexType("test")]
result = mock_repo._type_must_use_in_instead_of_any(complex_types)
assert result is True
async def test_type_must_use_in_mixed_types_with_complex(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test that mixed types containing complex types use IN() operator."""
mixed_values = [1, "test", MockComplexType("complex")]
result = mock_repo._type_must_use_in_instead_of_any(mixed_values)
assert result is True
async def test_type_must_use_in_none_values_ignored(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test that None values are properly ignored."""
values_with_none = [1, None, 3]
result = mock_repo._type_must_use_in_instead_of_any(values_with_none)
assert result is False
# Test only None values
only_none = [None, None]
result = mock_repo._type_must_use_in_instead_of_any(only_none)
assert result is False
async def test_type_must_use_in_sqlalchemy_type_matching(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test SQLAlchemy type introspection with matching types."""
# Test Integer type with integer values
int_type = Integer()
result = mock_repo._type_must_use_in_instead_of_any([1, 2, 3], int_type)
assert result is False
# Test String type with string values
str_type = String()
result = mock_repo._type_must_use_in_instead_of_any(["a", "b"], str_type)
assert result is False
async def test_type_must_use_in_sqlalchemy_type_mismatched(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test SQLAlchemy type introspection with mismatched types."""
# Test Integer type with string values (mismatch)
int_type = Integer()
result = mock_repo._type_must_use_in_instead_of_any(["not_an_int"], int_type)
assert result is True
# Test String type with integer values (mismatch)
str_type = String()
result = mock_repo._type_must_use_in_instead_of_any([123], str_type)
assert result is True
async def test_type_must_use_in_sqlalchemy_type_without_python_type(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test SQLAlchemy type that doesn't implement python_type."""
mock_type: MockTypeWithoutPythonType = MockTypeWithoutPythonType()
result = mock_repo._type_must_use_in_instead_of_any([1, 2, 3], mock_type)
assert result is True # Should use IN() for safety
async def test_type_must_use_in_sqlalchemy_type_with_none_python_type(
mock_repo: SQLAlchemyAsyncRepository[Any],
) -> None:
"""Test SQLAlchemy type that has None as python_type."""
mock_type = MagicMock()
mock_type.python_type = None
# Should fall back to Python type checking
result = mock_repo._type_must_use_in_instead_of_any([1, 2, 3], mock_type)
assert result is False # Standard integers should use ANY()
result = mock_repo._type_must_use_in_instead_of_any([MockComplexType("test")], mock_type)
assert result is True # Complex types should use IN()
async def test_type_must_use_in_missing_python_type_attribute(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test fallback when python_type attribute is missing from type."""
# Create a mock that doesn't have python_type attribute at all
mock_type = type("MockType", (), {})() # Empty object with no attributes
result = mock_repo._type_must_use_in_instead_of_any([1, 2, 3], mock_type)
assert result is False # Should fall back to Python type checking for safe types
class MyModel(BaseModel):
name: str
age: int
class MyStruct(Struct):
name: str
age: int
def test_is_pydantic_model() -> None:
pydantic_model = MyModel(name="Pydantic John", age=30)
msgspec_struct = MyStruct(name="Msgspec Joe", age=30)
old_dict = {"name": "Old Greg", "age": 30}
int_value = 1
assert is_pydantic_model(pydantic_model)
assert not is_pydantic_model(msgspec_struct)
assert not is_pydantic_model(old_dict)
assert not is_pydantic_model(int_value)
def test_is_msgspec_struct() -> None:
pydantic_model = MyModel(name="Pydantic John", age=30)
msgspec_struct = MyStruct(name="Msgspec Joe", age=30)
old_dict = {"name": "Old Greg", "age": 30}
assert not is_msgspec_struct(pydantic_model)
assert is_msgspec_struct(msgspec_struct)
assert not is_msgspec_struct(old_dict)
def test_is_schema() -> None:
pydantic_model = MyModel(name="Pydantic John", age=30)
msgspec_struct = MyStruct(name="Msgspec Joe", age=30)
old_dict = {"name": "Old Greg", "age": 30}
int_value = 1
assert is_schema(pydantic_model)
assert is_schema(msgspec_struct)
assert not is_schema(old_dict)
assert not is_schema(int_value)
assert is_schema_with_field(pydantic_model, "name")
assert not is_schema_with_field(msgspec_struct, "name2")
assert is_schema_without_field(pydantic_model, "name2")
assert not is_schema_without_field(msgspec_struct, "name")
def test_is_schema_or_dict() -> None:
pydantic_model = MyModel(name="Pydantic John", age=30)
msgspec_struct = MyStruct(name="Msgspec Joe", age=30)
old_dict = {"name": "Old Greg", "age": 30}
int_value = 1
assert is_schema_or_dict(pydantic_model)
assert is_schema_or_dict(msgspec_struct)
assert is_schema_or_dict(old_dict)
assert not is_schema_or_dict(int_value)
assert is_schema_or_dict_with_field(pydantic_model, "name")
assert not is_schema_or_dict_with_field(msgspec_struct, "name2")
assert is_schema_or_dict_without_field(pydantic_model, "name2")
assert not is_schema_or_dict_without_field(msgspec_struct, "name")
# Tests for new methods added in id-attribute-update branch
def test_async_type_must_use_in_empty_values(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test that empty values return False."""
assert mock_repo._type_must_use_in_instead_of_any([]) is False
def test_sync_type_must_use_in_empty_values(sync_mock_repo: SQLAlchemySyncRepository[Any]) -> None:
"""Test that empty values return False."""
assert sync_mock_repo._type_must_use_in_instead_of_any([]) is False
def test_async_safe_types_with_field_type(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test safe types with valid field type."""
# Mock field type with python_type
mock_field_type = MagicMock()
mock_field_type.python_type = str
values = ["test", "another_string"]
result = mock_repo._type_must_use_in_instead_of_any(values, mock_field_type)
assert result is False
def test_sync_type_mismatch_with_field_type(sync_mock_repo: SQLAlchemySyncRepository[Any]) -> None:
"""Test type mismatch triggers IN() usage."""
# Mock field type expecting strings
mock_field_type = MagicMock()
mock_field_type.python_type = str
# Pass integers when expecting strings
values = [1, 2, 3]
result = sync_mock_repo._type_must_use_in_instead_of_any(values, mock_field_type)
assert result is True
def test_async_field_type_none_python_type(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test behavior when field_type.python_type is None."""
mock_field_type = MagicMock()
mock_field_type.python_type = None
values = [{"complex": "object"}] # Non-safe type
result = mock_repo._type_must_use_in_instead_of_any(values, mock_field_type)
assert result is True # Should use fallback logic
def test_sync_field_type_no_python_type_attr(sync_mock_repo: SQLAlchemySyncRepository[Any]) -> None:
"""Test behavior when field_type has no python_type attribute."""
# Create object without python_type attribute
mock_field_type = object()
values = [{"complex": "object"}] # Non-safe type
result = sync_mock_repo._type_must_use_in_instead_of_any(values, mock_field_type)
assert result is True # Should use fallback logic for non-safe types
def test_async_no_field_type_safe_values(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test safe values without field type information."""
# Test all safe types
safe_values = [
42,
3.14,
"string",
True,
b"bytes",
decimal.Decimal("10.5"),
datetime.date.today(),
datetime.datetime.now(),
datetime.time(12, 30),
datetime.timedelta(days=1),
]
result = mock_repo._type_must_use_in_instead_of_any(safe_values)
assert result is False
def test_sync_no_field_type_unsafe_values(sync_mock_repo: SQLAlchemySyncRepository[Any]) -> None:
"""Test unsafe values without field type information."""
# Test unsafe types (complex objects)
unsafe_values = [{"key": "value"}, [1, 2, 3], {"nested": {"data": True}}]
result = sync_mock_repo._type_must_use_in_instead_of_any(unsafe_values)
assert result is True
def test_async_mixed_safe_unsafe_values(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test mixed safe and unsafe values."""
# Mix safe and unsafe types
mixed_values = ["string", 42, {"unsafe": "dict"}]
result = mock_repo._type_must_use_in_instead_of_any(mixed_values)
assert result is True
def test_sync_none_values_handling(sync_mock_repo: SQLAlchemySyncRepository[Any]) -> None:
"""Test handling of None values."""
# None values should be ignored in type checking
values_with_none = [None, "string", None, 42]
result = sync_mock_repo._type_must_use_in_instead_of_any(values_with_none)
assert result is False
def test_async_empty_values(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test empty list returns empty list."""
result = mock_repo._get_unique_values([])
assert result == []
def test_sync_hashable_values(sync_mock_repo: SQLAlchemySyncRepository[Any]) -> None:
"""Test hashable values deduplication."""
values = [1, 2, 1, 3, 2, 4]
result = sync_mock_repo._get_unique_values(values)
assert result == [1, 2, 3, 4]
def test_async_string_values(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test string deduplication."""
values = ["a", "b", "a", "c", "b"]
result = mock_repo._get_unique_values(values)
assert result == ["a", "b", "c"]
def test_sync_unhashable_values(sync_mock_repo: SQLAlchemySyncRepository[Any]) -> None:
"""Test unhashable values (dicts) deduplication."""
values = [
{"key": "value1"},
{"key": "value2"},
{"key": "value1"}, # duplicate
{"key": "value3"},
]
result = sync_mock_repo._get_unique_values(values)
expected = [{"key": "value1"}, {"key": "value2"}, {"key": "value3"}]
assert result == expected
def test_async_mixed_types(mock_repo: SQLAlchemyAsyncRepository[Any]) -> None:
"""Test mixed hashable and unhashable types."""
# Mix strings and dicts to trigger TypeError in set operations
values = ["string", {"dict": "value"}, "string", {"other": "dict"}]
result = mock_repo._get_unique_values(values)
expected = ["string", {"dict": "value"}, {"other": "dict"}]
assert result == expected
def test_sync_preserves_order(sync_mock_repo: SQLAlchemySyncRepository[Any]) -> None:
"""Test that order is preserved in deduplication."""
values = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
result = sync_mock_repo._get_unique_values(values)
assert result == [3, 1, 4, 5, 9, 2, 6]
def test_column_with_python_default() -> None:
"""Test column with Python-side default."""
mock_column = MagicMock()
mock_column.default = "default_value"
mock_column.server_default = None
mock_column.onupdate = None
mock_column.server_onupdate = None
assert column_has_defaults(mock_column) is True
def test_column_with_server_default() -> None:
"""Test column with server-side default."""
mock_column = MagicMock()
mock_column.default = None
mock_column.server_default = "DEFAULT VALUE"
mock_column.onupdate = None
mock_column.server_onupdate = None
assert column_has_defaults(mock_column) is True
def test_column_with_python_onupdate() -> None:
"""Test column with Python-side onupdate."""
mock_column = MagicMock()
mock_column.default = None
mock_column.server_default = None
mock_column.onupdate = "update_function"
mock_column.server_onupdate = None
assert column_has_defaults(mock_column) is True
def test_column_with_server_onupdate() -> None:
"""Test column with server-side onupdate."""
mock_column = MagicMock()
mock_column.default = None
mock_column.server_default = None
mock_column.onupdate = None
mock_column.server_onupdate = "UPDATE_FUNCTION"
assert column_has_defaults(mock_column) is True
def test_column_with_no_defaults() -> None:
"""Test column with no defaults."""
mock_column = MagicMock()
mock_column.default = None
mock_column.server_default = None
mock_column.onupdate = None
mock_column.server_onupdate = None
assert column_has_defaults(mock_column) is False
def test_column_with_false_default() -> None:
"""Test column where default is False (falsy but not None)."""
mock_column = MagicMock()
mock_column.default = False # Falsy but not None
mock_column.server_default = None
mock_column.onupdate = None
mock_column.server_onupdate = None
assert column_has_defaults(mock_column) is True
def test_column_with_zero_default() -> None:
"""Test column where default is 0 (falsy but not None)."""
mock_column = MagicMock()
mock_column.default = 0 # Falsy but not None
mock_column.server_default = None
mock_column.onupdate = None
mock_column.server_onupdate = None
assert column_has_defaults(mock_column) is True
def test_column_with_empty_string_default() -> None:
"""Test column where default is empty string (falsy but not None)."""
mock_column = MagicMock()
mock_column.default = "" # Falsy but not None
mock_column.server_default = None
mock_column.onupdate = None
mock_column.server_onupdate = None
assert column_has_defaults(mock_column) is True
def test_column_property_label_object() -> None:
"""Test column_property Label objects return False for column_has_defaults."""
from sqlalchemy.sql.elements import Label
# Create a Label object similar to what column_property creates
mock_label = MagicMock(spec=Label)
# Label objects don't have default/onupdate attributes, but if they did,
# they would raise AttributeError when accessed
assert column_has_defaults(mock_label) is False
def test_column_property_with_real_label() -> None:
"""Test column_has_defaults with an actual Label object from SQLAlchemy."""
from sqlalchemy import literal_column
from sqlalchemy.sql.elements import Label
# Create a real Label object like column_property would create
label_obj = literal_column("test_value").label("test_column") # type: ignore[var-annotated]
assert isinstance(label_obj, Label)
# This should return False and not raise AttributeError
assert column_has_defaults(label_obj) is False
def test_column_object_without_default_attributes() -> None:
"""Test column_has_defaults with object missing some attributes."""
# Create an object that only has some of the expected attributes
class PartialColumn:
def __init__(self) -> None:
self.default = "test_default"
# Missing server_default, onupdate, server_onupdate attributes
partial_column = PartialColumn()
# Should return True based on the default attribute, even though others are missing
assert column_has_defaults(partial_column) is True
def test_column_object_with_no_default_attributes() -> None:
"""Test column_has_defaults with object missing all attributes."""
# Create an object that has none of the expected attributes
class MinimalColumn:
def __init__(self) -> None:
self.name = "test_column"
minimal_column = MinimalColumn()
# Should return False since no default attributes are present
assert column_has_defaults(minimal_column) is False
def test_model_from_dict_includes_relationship_attributes() -> None:
"""Test that model_from_dict includes relationship attributes from __mapper__.attrs.keys()."""
from tests.fixtures.uuid.models import UUIDAuthor
# Verify that attrs.keys() includes relationships while columns.keys() doesn't
columns_keys = list(UUIDAuthor.__mapper__.columns.keys())
attrs_keys = list(UUIDAuthor.__mapper__.attrs.keys())
assert "books" not in columns_keys, "books relationship should NOT be in columns.keys()"
assert "books" in attrs_keys, "books relationship should be in attrs.keys()"
# Tests for write_only relationship handling in update method (issue #524)
async def test_update_skips_write_only_relationships(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
"""Test that update method skips write_only relationships without error."""
id_ = 3
mock_instance = MagicMock()
existing_instance = MagicMock()
# Mock the mapper and relationship
mock_mapper = MagicMock()
mock_relationship = MagicMock()
mock_relationship.key = "items"
mock_relationship.lazy = "write_only"
mock_relationship.viewonly = False
mock_mapper.mapper.columns = []
mock_mapper.mapper.relationships = [mock_relationship]
# Mock the data object to have the write_only relationship attribute
mock_instance.items = MagicMock() # This would be a WriteOnlyCollection in reality
mocker.patch.object(mock_repo, "get_id_attribute_value", return_value=id_)
mocker.patch.object(mock_repo, "get", return_value=existing_instance)
mocker.patch("advanced_alchemy.repository._async.inspect", return_value=mock_mapper)
mock_repo.session.merge.return_value = existing_instance # pyright: ignore[reportFunctionMemberAccess]
# This should not raise an error even though items is a write_only relationship
instance = await maybe_async(mock_repo.update(mock_instance))
# Verify the relationship was not processed (no merge attempted for relationships)
mock_repo.session.merge.assert_called_once_with(existing_instance, load=True) # pyright: ignore[reportFunctionMemberAccess]
assert instance is existing_instance
async def test_update_skips_dynamic_relationships(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
"""Test that update method skips dynamic relationships without error."""
id_ = 3
mock_instance = MagicMock()
existing_instance = MagicMock()
# Mock the mapper and relationship
mock_mapper = MagicMock()
mock_relationship = MagicMock()
mock_relationship.key = "items"
mock_relationship.lazy = "dynamic"
mock_relationship.viewonly = False
mock_mapper.mapper.columns = []
mock_mapper.mapper.relationships = [mock_relationship]
# Mock the data object to have the dynamic relationship attribute
mock_instance.items = MagicMock() # This would be an AppenderQuery in reality
mocker.patch.object(mock_repo, "get_id_attribute_value", return_value=id_)
mocker.patch.object(mock_repo, "get", return_value=existing_instance)
mocker.patch("advanced_alchemy.repository._async.inspect", return_value=mock_mapper)
mock_repo.session.merge.return_value = existing_instance # pyright: ignore[reportFunctionMemberAccess]
# This should not raise an error even though items is a dynamic relationship
instance = await maybe_async(mock_repo.update(mock_instance))
# Verify the relationship was not processed (no merge attempted for relationships)
mock_repo.session.merge.assert_called_once_with(existing_instance, load=True) # pyright: ignore[reportFunctionMemberAccess]
assert instance is existing_instance
async def test_update_skips_viewonly_relationships(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
"""Test that update method skips viewonly relationships without error."""
id_ = 3
mock_instance = MagicMock()
existing_instance = MagicMock()
# Mock the mapper and relationship
mock_mapper = MagicMock()
mock_relationship = MagicMock()
mock_relationship.key = "readonly_items"
mock_relationship.lazy = "select" # Normal lazy loading
mock_relationship.viewonly = True # But marked as view-only
mock_mapper.mapper.columns = []
mock_mapper.mapper.relationships = [mock_relationship]
# Mock the data object to have the viewonly relationship attribute
mock_instance.readonly_items = [MagicMock()]
mocker.patch.object(mock_repo, "get_id_attribute_value", return_value=id_)
mocker.patch.object(mock_repo, "get", return_value=existing_instance)
mocker.patch("advanced_alchemy.repository._async.inspect", return_value=mock_mapper)
mock_repo.session.merge.return_value = existing_instance # pyright: ignore[reportFunctionMemberAccess]
# This should not raise an error even though readonly_items is viewonly
instance = await maybe_async(mock_repo.update(mock_instance))
# Verify the relationship was not processed (no merge attempted for relationships)
mock_repo.session.merge.assert_called_once_with(existing_instance, load=True) # pyright: ignore[reportFunctionMemberAccess]
assert instance is existing_instance
async def test_update_skips_raise_lazy_relationships(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
"""Test that update method skips raise lazy strategy relationships without error."""
id_ = 3
mock_instance = MagicMock()
existing_instance = MagicMock()
# Mock the mapper and relationship
mock_mapper = MagicMock()
mock_relationship = MagicMock()
mock_relationship.key = "items"
mock_relationship.lazy = "raise"
mock_relationship.viewonly = False
mock_mapper.mapper.columns = []
mock_mapper.mapper.relationships = [mock_relationship]
# Mock the data object to raise an error when accessing the relationship
type(mock_instance).items = PropertyMock(side_effect=InvalidRequestError)
mocker.patch.object(mock_repo, "get_id_attribute_value", return_value=id_)
mocker.patch.object(mock_repo, "get", return_value=existing_instance)
mocker.patch("advanced_alchemy.repository._sync.inspect", return_value=mock_mapper)
mocker.patch("advanced_alchemy.repository._async.inspect", return_value=mock_mapper)
mock_repo.session.merge.return_value = existing_instance # pyright: ignore[reportFunctionMemberAccess]
# This should not raise an error even though items has lazy="raise"
instance = await maybe_async(mock_repo.update(mock_instance))
# Verify the relationship was not processed (no merge attempted for relationships)
mock_repo.session.merge.assert_called_once_with(existing_instance, load=True) # pyright: ignore[reportFunctionMemberAccess]
assert instance is existing_instance
async def test_update_processes_normal_relationships(
mock_repo: SQLAlchemyAsyncRepository[Any],
mocker: MockerFixture,
) -> None:
"""Test that update method still processes normal relationships correctly."""
id_ = 3
mock_instance = MagicMock()
existing_instance = MagicMock()
related_item = MagicMock()
merged_related_item = MagicMock()
# Mock the mapper and relationship
mock_mapper = MagicMock()
mock_relationship = MagicMock()
mock_relationship.key = "items"
mock_relationship.lazy = "select" # Normal lazy loading
mock_relationship.viewonly = False
mock_mapper.mapper.columns = []
mock_mapper.mapper.relationships = [mock_relationship]
# Mock the data object to have a normal relationship with items
mock_instance.items = [related_item]
mocker.patch.object(mock_repo, "get_id_attribute_value", return_value=id_)
mocker.patch.object(mock_repo, "get", return_value=existing_instance)
mocker.patch("advanced_alchemy.repository._async.inspect", return_value=mock_mapper)
# Mock session.merge to return different objects for main instance vs related items
async def mock_merge(obj: Any, load: bool = True) -> Any:
if obj is existing_instance:
return existing_instance
if obj is related_item:
return merged_related_item
return obj
mock_repo.session.merge.side_effect = mock_merge
# This should process the normal relationship correctly
instance = await maybe_async(mock_repo.update(mock_instance))
# Verify the relationship was processed - at minimum the main instance should be merged
assert mock_repo.session.merge.call_count >= 1 # At least the main instance
# The main point is that normal relationships don't cause errors
assert instance is existing_instance
def test_model_from_dict_backward_compatibility() -> None:
"""Test that model_from_dict maintains backward compatibility with column-only data."""
from tests.fixtures.uuid.models import UUIDAuthor
author_data = {"name": "Compatible Author", "string_field": "compatibility test"}
author = model_from_dict(UUIDAuthor, **author_data)
assert author.name == "Compatible Author"
assert author.string_field == "compatibility test"
def test_model_from_dict_ignores_unknown_attributes() -> None:
"""Test that model_from_dict still ignores unknown attributes."""
from tests.fixtures.uuid.models import UUIDAuthor
author_data = {"name": "Test Author", "unknown_attribute": "should be ignored", "another_unknown": 12345}
author = model_from_dict(UUIDAuthor, **author_data)
assert author.name == "Test Author"
assert not hasattr(author, "unknown_attribute")
assert not hasattr(author, "another_unknown")
def test_model_from_dict_empty_relationship() -> None:
"""Test that model_from_dict handles empty relationship lists."""
from tests.fixtures.uuid.models import UUIDAuthor
author_data = {
"name": "Author Without Books",
"books": [], # Empty relationship
}
author = model_from_dict(UUIDAuthor, **author_data)
assert author.name == "Author Without Books"
assert hasattr(author, "books")
assert author.books == []
def test_update_many_data_conversion_handles_mixed_types() -> None:
"""Test that update_many properly handles mixed input types (regression test).
This verifies the fix for the type handling bug in update_many where
the old logic would fail with AttributeError when mixing model instances
and dictionaries.
"""
from tests.fixtures.uuid.models import UUIDAuthor
# Simulate the data conversion logic from the fixed code
model_type = UUIDAuthor
# Create a mock model instance
mock_author = UUIDAuthor(name="Test Author")
# Mix of model instances and dictionaries (the problematic case)
mixed_data = [
mock_author, # Model instance with to_dict() method
{"id": "dict-id", "name": "Dict Author"}, # Plain dictionary
]
# This is the fixed logic from repository/_async.py and _sync.py
data_to_update = []
for v in mixed_data:
if isinstance(v, model_type):
data_to_update.append(v.to_dict())
else:
data_to_update.append(v) # type: ignore[arg-type]
# Verify no AttributeError was raised and data is properly converted
assert len(data_to_update) == 2
assert isinstance(data_to_update[0], dict) # Model converted to dict
assert isinstance(data_to_update[1], dict) # Dict passed through
assert data_to_update[0]["name"] == "Test Author"
assert data_to_update[1]["name"] == "Dict Author"
def test_compare_values_handles_numpy_arrays() -> None:
"""Test that compare_values properly handles numpy arrays.
This is a regression test for the issue where comparing numpy arrays
(like pgvector's Vector type) would raise:
ValueError: The truth value of an array with more than one element is ambiguous
"""
from advanced_alchemy.repository._util import compare_values
# Test with regular values (should work as before)
assert compare_values("same", "same") is True
assert compare_values("different", "other") is False
assert compare_values(None, None) is True
assert compare_values(None, "value") is False
assert compare_values("value", None) is False
# Test with mock numpy arrays (when numpy is not installed)
class MockNumpyArray:
"""Mock numpy array for testing when numpy is not available."""
def __init__(self, data: list[float]) -> None:
self.data = data
self.dtype = "float64" # Required for is_numpy_array detection
def __array__(self) -> list[float]:
"""Required for is_numpy_array detection."""
return self.data
def __eq__(self, other: object) -> list[bool]: # type: ignore[override]
"""Simulate numpy's element-wise comparison that causes the issue."""
if isinstance(other, MockNumpyArray):
return [a == b for a, b in zip(self.data, other.data)]
return [False] * len(self.data)
# Create mock arrays
array1 = MockNumpyArray([1.0, 2.0, 3.0])
array2 = MockNumpyArray([1.0, 2.0, 3.0]) # Same data
array3 = MockNumpyArray([4.0, 5.0, 6.0]) # Different data
# Test array comparisons (these would previously raise ValueError)
result_same = compare_values(array1, array2)
result_different = compare_values(array1, array3)
result_mixed = compare_values(array1, "not_an_array")
# The important thing is that no ValueError is raised
assert isinstance(result_same, bool) # Should not raise ValueError
assert isinstance(result_different, bool) # Should not raise ValueError
assert isinstance(result_mixed, bool) # Should not raise ValueError
# The specific results depend on whether numpy is installed:
# - With numpy: MockNumpyArray is not detected as numpy array, falls back to __eq__
# - Without numpy: stub functions are used which return False for safety
# Either way, no ValueError should be raised
# Test with values that would cause comparison errors
class ProblematicValue:
def __eq__(self, other: object) -> None: # type: ignore[override]
raise TypeError("Cannot compare")
problematic = ProblematicValue()
# Should handle comparison errors gracefully
assert compare_values(problematic, "other") is False
assert compare_values("other", problematic) is False
def test_compare_values_with_real_numpy_arrays() -> None:
"""Test compare_values with actual numpy arrays when numpy is installed.
This test covers the real numpy code paths that were missing from coverage.
"""
# This test will only run if numpy is actually installed
try:
import numpy as np
except ImportError:
pytest.skip("numpy not available")
from advanced_alchemy.repository._util import compare_values
# Test equal arrays
arr1 = np.array([1.0, 2.0, 3.0])
arr2 = np.array([1.0, 2.0, 3.0])
assert compare_values(arr1, arr2) is True
# Test different arrays
arr3 = np.array([4.0, 5.0, 6.0])
assert compare_values(arr1, arr3) is False
# Test different shapes
arr4 = np.array([[1.0, 2.0], [3.0, 4.0]])
assert compare_values(arr1, arr4) is False
# Test array vs non-array
assert compare_values(arr1, [1.0, 2.0, 3.0]) is False
assert compare_values(arr1, "not an array") is False
# Test empty arrays
empty1 = np.array([])
empty2 = np.array([])
assert compare_values(empty1, empty2) is True
# Test different dtypes but same values
int_arr = np.array([1, 2, 3])
float_arr = np.array([1.0, 2.0, 3.0])
assert compare_values(int_arr, float_arr) is True # numpy considers these equal
# Test NaN handling
nan_arr1 = np.array([1.0, np.nan, 3.0])
nan_arr2 = np.array([1.0, np.nan, 3.0])
# numpy considers NaN != NaN, so arrays with NaN won't be equal
assert compare_values(nan_arr1, nan_arr2) is False
def test_compare_values_covers_all_branches() -> None:
"""Test compare_values to ensure all code branches are covered."""
from advanced_alchemy.repository._util import compare_values
# Test standard equality that returns non-bool (should not happen with normal types)
class WeirdComparison:
def __eq__(self, other: object) -> str: # type: ignore[override]
return "weird"
weird = WeirdComparison()
# This tests the bool() conversion in the standard comparison path
result = compare_values(weird, weird)
assert isinstance(result, bool) # Should convert "weird" to True
assert result is True
def test_repository_update_methods_with_numpy_arrays() -> None:
"""Test that repository update methods work correctly with numpy array fields.
This integration test covers the actual repository comparison paths
that were missing from coverage.
"""
# This test will only run if numpy is actually installed
try:
import numpy as np
except ImportError:
pytest.skip("numpy not available")
from advanced_alchemy.repository._util import compare_values
# Test data with numpy arrays
arr1 = np.array([1.0, 2.0, 3.0])
arr2 = np.array([1.0, 2.0, 3.0]) # Same as arr1
arr3 = np.array([4.0, 5.0, 6.0]) # Different from arr1
# These operations would previously fail with ValueError
# Now they should work correctly by using our safe comparison
# Test 1: Arrays with same data should be considered equal
assert arr1 is not arr2 # Different objects
# But compare_values should see them as equal
assert compare_values(arr1, arr2) is True
# Test 2: Arrays with different data should be considered different
assert compare_values(arr1, arr3) is False
# Test 3: Test with None values (common edge case)
assert compare_values(None, None) is True
assert compare_values(arr1, None) is False
assert compare_values(None, arr1) is False
# Test 4: Array vs non-array should be False
assert compare_values(arr1, [1.0, 2.0, 3.0]) is False
assert compare_values(arr1, "not an array") is False
# Test 5: Test different shapes
arr_2d = np.array([[1.0, 2.0], [3.0, 4.0]])
assert compare_values(arr1, arr_2d) is False
# Test 6: Test empty arrays
empty1 = np.array([])
empty2 = np.array([])
assert compare_values(empty1, empty2) is True
# Test 7: Test with complex numbers (edge case)
complex1 = np.array([1 + 2j, 3 + 4j])
complex2 = np.array([1 + 2j, 3 + 4j])
complex3 = np.array([1 + 2j, 5 + 6j])
assert compare_values(complex1, complex2) is True
assert compare_values(complex1, complex3) is False
def test_was_attribute_set_with_explicitly_set_attributes() -> None:
"""Test was_attribute_set correctly identifies explicitly set attributes."""
from sqlalchemy import inspect
from advanced_alchemy.repository._util import was_attribute_set
# Create an instance with explicitly set attributes
instance = UUIDModel()
instance.id = uuid4() # Explicitly set id
# Get the mapper/inspector
mapper = inspect(instance)
# Explicitly set attributes should return True
assert was_attribute_set(instance, mapper, "id") is True
def test_was_attribute_set_with_uninitialized_attributes() -> None:
"""Test was_attribute_set correctly identifies uninitialized attributes."""
from sqlalchemy import inspect
from advanced_alchemy.repository._util import was_attribute_set
# Use the existing UUIDModel which has created_at and updated_at audit fields
# Create an instance - created_at and updated_at won't be in instance dict yet
instance = UUIDModel()
# Get the mapper/inspector
mapper = inspect(instance)
# Uninitialized audit attributes should return False
# They exist on the model but haven't been explicitly set
assert was_attribute_set(instance, mapper, "created_at") is False
assert was_attribute_set(instance, mapper, "updated_at") is False
def test_was_attribute_set_with_modified_attributes() -> None:
"""Test was_attribute_set detects attributes with modification history."""
from sqlalchemy import inspect
from advanced_alchemy.repository._util import was_attribute_set
# Create an instance and explicitly set attributes
instance = UUIDModel()
instance.id = uuid4() # Explicitly set id
# Also test setting a datetime attribute
now = datetime.datetime.now(datetime.timezone.utc)
instance.created_at = now # Explicitly modify created_at
# Get the mapper/inspector
mapper = inspect(instance)
# Modified attributes should return True
assert was_attribute_set(instance, mapper, "id") is True
assert was_attribute_set(instance, mapper, "created_at") is True
def test_was_attribute_set_with_nonexistent_attribute() -> None:
"""Test was_attribute_set handles nonexistent attributes gracefully."""
from sqlalchemy import inspect
from advanced_alchemy.repository._util import was_attribute_set
# Create an instance
instance = UUIDModel()
# Get the mapper/inspector
mapper = inspect(instance)
# Nonexistent attribute should return False (attr_state is None)
assert was_attribute_set(instance, mapper, "nonexistent_field") is False
|