File size: 84,967 Bytes
d086025 | 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 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 | diff --git a/dysql/test/__init__.py b/dysql/test/__init__.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/__init__.py
@@ -0,0 +1,55 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from unittest.mock import Mock
+
+from dysql import set_default_connection_parameters, databases
+
+
+def setup_mock_engine(mock_create_engine):
+ """
+ build up the basics of a mock engine for the database
+ :return: mocked engine for use and manipulation in testing
+ """
+ mock_engine = Mock()
+ mock_engine.connect().execution_options().__enter__ = Mock()
+ mock_engine.connect().execution_options().__exit__ = Mock()
+ set_default_connection_parameters("fake", "user", "password", "test")
+
+ # Clear out the databases before attempting to mock anything
+ databases.DatabaseContainerSingleton().clear()
+ mock_create_engine.return_value = mock_engine
+ return mock_engine
+
+
+def verify_query_params(mock_engine, expected_query, expected_args):
+ verify_query(mock_engine, expected_query)
+ verify_query_args(mock_engine, expected_args)
+
+
+def verify_query(mock_engine, expected_query):
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ execute_call.assert_called()
+
+ query = execute_call.call_args[0][0].text
+ assert query == expected_query
+
+
+def verify_query_args(mock_engine, expected_args):
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ query_args = execute_call.call_args[0][1]
+
+ assert query_args
+ for expected_key in expected_args:
+ expected_value = expected_args[expected_key]
+ assert query_args.get(expected_key)
+ assert expected_value == query_args[expected_key]
diff --git a/dysql/test/conftest.py b/dysql/test/conftest.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/conftest.py
@@ -0,0 +1,19 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from unittest.mock import patch
+import pytest
+
+
+@pytest.fixture(name="mock_create_engine")
+def mock_create_engine_fixture():
+ create_mock = patch("dysql.databases.sqlalchemy.create_engine")
+ try:
+ yield create_mock.start()
+ finally:
+ create_mock.stop()
diff --git a/dysql/test/test_annotations.py b/dysql/test/test_annotations.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_annotations.py
@@ -0,0 +1,68 @@
+"""
+Copyright 2023 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from typing import List, Union
+
+import pytest
+from pydantic import BaseModel, ValidationError
+
+from dysql.annotations import FromCSVToList
+
+
+class StrCSVModel(BaseModel):
+ values: FromCSVToList[List[str]]
+
+
+class IntCSVModel(BaseModel):
+ values: FromCSVToList[List[int]]
+
+
+class NullableStrCSVModel(BaseModel):
+ values: FromCSVToList[Union[List[str], None]]
+
+
+class NullableIntCSVModel(BaseModel):
+ values: FromCSVToList[Union[List[int], None]]
+
+
+@pytest.mark.parametrize(
+ "cls, values, expected",
+ [
+ (StrCSVModel, "1,2,3", ["1", "2", "3"]),
+ (StrCSVModel, "a,b", ["a", "b"]),
+ (StrCSVModel, "a", ["a"]),
+ (NullableStrCSVModel, "", None),
+ (NullableStrCSVModel, None, None),
+ (StrCSVModel, ["a", "b"], ["a", "b"]),
+ (StrCSVModel, ["a", "b", "c"], ["a", "b", "c"]),
+ (IntCSVModel, "1,2,3", [1, 2, 3]),
+ (IntCSVModel, "1", [1]),
+ (NullableIntCSVModel, "", None),
+ (NullableIntCSVModel, None, None),
+ (IntCSVModel, ["1", "2", "3"], [1, 2, 3]),
+ (IntCSVModel, ["1", "2", "3", 4, 5], [1, 2, 3, 4, 5]),
+ ],
+)
+def test_from_csv_to_list(cls, values, expected):
+ assert expected == cls(values=values).values
+
+
+@pytest.mark.parametrize(
+ "cls, values",
+ [
+ (StrCSVModel, ""),
+ (StrCSVModel, None),
+ (IntCSVModel, "a,b,c"),
+ (IntCSVModel, ""),
+ (IntCSVModel, None),
+ (IntCSVModel, ["a", "b", "c"]),
+ ],
+)
+def test_from_csv_to_list_invalid(cls, values):
+ with pytest.raises(ValidationError):
+ cls(values=values)
diff --git a/dysql/test/test_database_initialization.py b/dysql/test/test_database_initialization.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_database_initialization.py
@@ -0,0 +1,240 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from unittest import mock
+
+import pytest
+
+import dysql.connections
+from dysql import (
+ sqlquery,
+ DBNotPreparedError,
+ set_default_connection_parameters,
+ QueryData,
+ set_database_init_hook,
+)
+from dysql.test import setup_mock_engine
+
+
+"""
+These tests reflect what can happen when dealing with a config passing in a value that may not
+have been set. There are some parameters that are absolutely necessary, if they aren't set we
+want to make sure we are warning the user in different ways.
+"""
+
+
+@sqlquery()
+def query():
+ """
+ This is used to call the code that would initialize the database on the first time.
+ If there were any failures this is where we would expect to see them.
+ """
+ return QueryData("SELECT * FROM table")
+
+
+@pytest.fixture(autouse=True, name="mock_engine")
+def fixture_mock_engine(mock_create_engine):
+ dysql.databases.DatabaseContainerSingleton().clear()
+ dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY.clear()
+
+ # Reset the database before the test
+ dysql.databases.reset_current_database()
+
+ yield setup_mock_engine(mock_create_engine)
+
+ # Reset database after the test as well
+ dysql.databases.reset_current_database()
+
+
+@pytest.fixture(autouse=True)
+def fixture_reset_init_hook():
+ yield
+ if hasattr(dysql.databases.Database, "hook_method"):
+ delattr(dysql.databases.Database, "hook_method")
+
+
+def test_nothing_set():
+ dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY.clear()
+ with pytest.raises(DBNotPreparedError) as error:
+ query()
+ assert (
+ str(error.value)
+ == "Unable to connect to a database, set_default_connection_parameters must first be called"
+ )
+
+
+@pytest.mark.parametrize(
+ "host, user, password, database, failed_field",
+ [
+ (None, "u", "p", "d", "host"),
+ ("", "u", "p", "d", "host"),
+ ("h", None, "p", "d", "user"),
+ ("h", "", "p", "d", "user"),
+ ("h", "u", None, "d", "password"),
+ ("h", "u", "", "d", "password"),
+ ("h", "u", "p", None, "database"),
+ ("h", "u", "p", "", "database"),
+ ],
+)
+def test_fields_required(host, user, password, database, failed_field):
+ with pytest.raises(DBNotPreparedError) as error:
+ set_default_connection_parameters(host, user, password, database)
+ assert (
+ str(error.value)
+ == f'Database parameter "{failed_field}" is not set or empty and is required'
+ )
+
+
+def test_minimal_credentials(mock_engine):
+ set_default_connection_parameters("h", "u", "p", "d")
+
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+
+def test_init_hook(mock_engine):
+ init_hook = mock.MagicMock()
+ set_database_init_hook(init_hook)
+ set_default_connection_parameters("h", "u", "p", "d")
+ dysql.databases.set_current_database("d")
+
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+ init_hook.assert_called_once_with("d", mock_engine)
+
+
+def test_init_hook_multiple_databases(mock_engine):
+ init_hook = mock.MagicMock()
+ set_database_init_hook(init_hook)
+ set_default_connection_parameters("h1", "u1", "p1", "d1")
+ set_default_connection_parameters("h2", "u2", "p2", "d2")
+
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+ dysql.databases.set_current_database("d1")
+ query()
+ assert init_hook.call_args_list == [
+ mock.call("test", mock_engine),
+ mock.call("d1", mock_engine),
+ ]
+ dysql.databases.set_current_database("d2")
+ query()
+ assert init_hook.call_args_list == [
+ mock.call("test", mock_engine),
+ mock.call("d1", mock_engine),
+ mock.call("d2", mock_engine),
+ ]
+
+
+def test_current_database_default(mock_engine, mock_create_engine):
+ db_container = dysql.databases.DatabaseContainerSingleton()
+ assert len(db_container) == 0
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+ # Only one database is initialized
+ assert len(db_container) == 1
+ assert "test" in db_container
+ assert db_container.current_database.database == "test"
+ mock_create_engine.assert_called_once_with(
+ "mysql+mysqlconnector://user:password@fake:3306/test?charset=utf8",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ )
+
+
+def test_different_charset_collation(mock_engine, mock_create_engine):
+ db_container = dysql.databases.DatabaseContainerSingleton()
+ set_default_connection_parameters(
+ "host",
+ "user",
+ "password",
+ "database",
+ charset="other",
+ collation="other_collation",
+ )
+ assert len(db_container) == 0
+ dysql.databases.set_current_database("database")
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+ # Only one database is initialized
+ mock_create_engine.assert_called_once_with(
+ "mysql+mysqlconnector://user:password@host:3306/database?charset=other&collation=other_collation",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ )
+
+
+def test_is_set_current_database_supported():
+ # This test only asserts that true is always returned since this method is deprecated
+ assert dysql.databases.is_set_current_database_supported()
+
+
+def test_current_database_set(mock_engine, mock_create_engine):
+ db_container = dysql.databases.DatabaseContainerSingleton()
+ set_default_connection_parameters("h1", "u1", "p1", "d1", database_key="db1")
+ dysql.databases.set_current_database("db1")
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+ assert len(db_container) == 1
+ assert "db1" in db_container
+ assert db_container.current_database.database == "db1"
+ mock_create_engine.assert_called_once_with(
+ "mysql+mysqlconnector://u1:p1@h1:3306/d1?charset=utf8",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ )
+
+
+def test_current_database_cached(mock_engine, mock_create_engine):
+ db_container = dysql.databases.DatabaseContainerSingleton()
+ mock_engine.connect().execution_options().execute.return_value = []
+ query()
+
+ assert len(db_container) == 1
+ assert "test" in db_container
+ assert db_container.current_database.database == "test"
+
+ set_default_connection_parameters("h1", "u1", "p1", "db1")
+ dysql.databases.set_current_database("db1")
+ query()
+ assert len(db_container) == 2
+ assert "test" in db_container
+ assert db_container.current_database.database == "db1"
+
+ # Set back to default
+ dysql.databases.reset_current_database()
+ query()
+ assert len(db_container) == 2
+ assert db_container.current_database.database == "test"
+
+ assert mock_create_engine.call_count == 2
+ assert mock_create_engine.call_args_list == [
+ mock.call(
+ "mysql+mysqlconnector://user:password@fake:3306/test?charset=utf8",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ ),
+ mock.call(
+ "mysql+mysqlconnector://u1:p1@h1:3306/db1?charset=utf8",
+ echo=False,
+ pool_pre_ping=True,
+ pool_recycle=3600,
+ pool_size=10,
+ ),
+ ]
diff --git a/dysql/test/test_mappers.py b/dysql/test/test_mappers.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_mappers.py
@@ -0,0 +1,227 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+
+from dysql import (
+ RecordCombiningMapper,
+ SingleRowMapper,
+ SingleColumnMapper,
+ SingleRowAndColumnMapper,
+ CountMapper,
+ KeyValueMapper,
+)
+from dysql.mappers import MapperError
+
+
+class TestMappers:
+ """
+ Test Mappers
+ """
+
+ @staticmethod
+ def _unwrap_results(results):
+ return [r.raw() for r in results]
+
+ def test_record_combining(self):
+ mapper = RecordCombiningMapper()
+ assert len(mapper.map_records([])) == 0
+ assert self._unwrap_results(mapper.map_records([{"a": 1, "b": 2}])) == [
+ {"a": 1, "b": 2}
+ ]
+ assert self._unwrap_results(
+ mapper.map_records(
+ [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ )
+ ) == [
+ {"id": 1, "a": 1, "b": 2, "c": 3},
+ {"id": 2, "a": 1, "b": 2},
+ ]
+
+ @staticmethod
+ def test_record_combining_no_record_mapper():
+ mapper = RecordCombiningMapper(record_mapper=None)
+ assert len(mapper.map_records([])) == 0
+ assert mapper.map_records([{"a": 1, "b": 2}]) == [{"a": 1, "b": 2}]
+ assert mapper.map_records(
+ [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ ) == [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+
+ @staticmethod
+ def test_single_row():
+ mapper = SingleRowMapper()
+ assert mapper.map_records([]) is None
+ assert mapper.map_records([{"a": 1, "b": 2}]).raw() == {"a": 1, "b": 2}
+ assert mapper.map_records(
+ [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ ).raw() == {"id": 1, "a": 1, "b": 2}
+
+ @staticmethod
+ def test_single_row_no_record_mapper():
+ mapper = SingleRowMapper(record_mapper=None)
+ assert mapper.map_records([]) is None
+ assert mapper.map_records([{"a": 1, "b": 2}]) == {"a": 1, "b": 2}
+ assert mapper.map_records(
+ [
+ {"id": 1, "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ ) == {"id": 1, "a": 1, "b": 2}
+
+ @staticmethod
+ def test_single_column():
+ mapper = SingleColumnMapper()
+ assert len(mapper.map_records([])) == 0
+ assert mapper.map_records([{"a": 1, "b": 2}]) == [1]
+ assert mapper.map_records(
+ [
+ {"id": "myid1", "a": 1, "b": 2},
+ {"id": "myid2", "a": 1, "b": 2},
+ {"id": "myid3", "c": 3},
+ ]
+ ) == ["myid1", "myid2", "myid3"]
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ "mapper",
+ [
+ SingleRowAndColumnMapper(),
+ # Alias for the other one
+ CountMapper(),
+ ],
+ )
+ def test_single_column_and_row(mapper):
+ assert mapper.map_records([]) is None
+ assert mapper.map_records([{"a": 1, "b": 2}]) == 1
+ assert (
+ mapper.map_records(
+ [
+ {"id": "myid", "a": 1, "b": 2},
+ {"id": 2, "a": 1, "b": 2},
+ {"id": 1, "c": 3},
+ ]
+ )
+ == "myid"
+ )
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ "mapper, expected",
+ [
+ (KeyValueMapper(), {"a": 4, "b": 7}),
+ (KeyValueMapper(key_column="column_named_something"), {"a": 4, "b": 7}),
+ (KeyValueMapper(value_column="column_with_some_value"), {"a": 4, "b": 7}),
+ (
+ KeyValueMapper(has_multiple_values_per_key=True),
+ {"a": [1, 2, 3, 4], "b": [3, 4, 5, 6, 7]},
+ ),
+ (
+ KeyValueMapper(
+ key_column="column_named_something",
+ has_multiple_values_per_key=True,
+ ),
+ {"a": [1, 2, 3, 4], "b": [3, 4, 5, 6, 7]},
+ ),
+ (
+ KeyValueMapper(
+ key_column="column_with_some_value",
+ value_column="column_named_something",
+ has_multiple_values_per_key=True,
+ ),
+ {
+ 1: ["a"],
+ 2: ["a"],
+ 3: ["a", "b"],
+ 4: ["a", "b"],
+ 5: ["b"],
+ 6: ["b"],
+ 7: ["b"],
+ },
+ ),
+ (
+ KeyValueMapper(
+ key_column="column_with_some_value",
+ value_column="column_named_something",
+ ),
+ {1: "a", 2: "a", 3: "b", 4: "b", 5: "b", 6: "b", 7: "b"},
+ ),
+ ],
+ )
+ def test_key_mapper_key_has_multiple(mapper, expected):
+ result = mapper.map_records(
+ [
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["a", 1]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["a", 2]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["a", 3]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["a", 4]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 3]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 4]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 5]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 6]
+ ),
+ HelperRow(
+ ("column_named_something", "column_with_some_value"), ["b", 7]
+ ),
+ ]
+ )
+ assert len(result) == len(expected)
+ assert result == expected
+
+ @staticmethod
+ def test_key_mapper_key_value_same():
+ with pytest.raises(
+ MapperError, match="key and value columns cannot be the same"
+ ):
+ KeyValueMapper(key_column="same", value_column="same")
+
+
+class HelperRow: # pylint: disable=too-few-public-methods
+ """
+ Helper class does the most basic functionality we see when accessing records passed in
+ """
+
+ def __init__(self, fields, values):
+ self.fields = fields
+ self.values = values
+
+ def __getitem__(self, key):
+ if isinstance(key, int):
+ return self.values[key]
+ return self.values[self.fields.index(key)]
diff --git a/dysql/test/test_mariadbmap_tojson.py b/dysql/test/test_mariadbmap_tojson.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_mariadbmap_tojson.py
@@ -0,0 +1,47 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import json
+import pytest
+
+from dysql import DbMapResult
+
+
+@pytest.mark.parametrize(
+ "name, expected_json, mariadb_map",
+ [
+ (
+ "basic",
+ '{"id": 1, "name": "test"}',
+ DbMapResult(id=1, name="test"),
+ ),
+ (
+ "basic_with_list",
+ '{"id": 1, "name": "test", "my_list": ["a", "b", "c"]}',
+ DbMapResult(id=1, name="test", my_list=["a", "b", "c"]),
+ ),
+ (
+ "inner_map",
+ '{"id": 1, "inner_map": {"id": 2, "name": "inner_test"}}',
+ DbMapResult(id=1, inner_map=DbMapResult(id=2, name="inner_test")),
+ ),
+ (
+ "inner_list_of_maps",
+ '{"id": 1, "inner_map_list": [{"id": 2, "name": "inner_test_2"}, {"id": 3, "name": "inner_test_3"}]}',
+ DbMapResult(
+ id=1,
+ inner_map_list=[
+ DbMapResult(id=2, name="inner_test_2"),
+ DbMapResult(id=3, name="inner_test_3"),
+ ],
+ ),
+ ),
+ ],
+)
+def test_raw_json_format(name, expected_json, mariadb_map):
+ assert json.dumps(mariadb_map.raw()) == expected_json, "error with " + name
diff --git a/dysql/test/test_pydantic_mappers.py b/dysql/test/test_pydantic_mappers.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_pydantic_mappers.py
@@ -0,0 +1,291 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import json
+from typing import Any, Dict, List, Set, Optional
+import pytest
+
+from pydantic import ValidationError
+
+from dysql import (
+ RecordCombiningMapper,
+ SingleRowMapper,
+)
+from dysql.pydantic_mappers import DbMapResultModel
+
+
+class ConversionDbModel(DbMapResultModel):
+ id: int
+ field_str: str
+ field_int: int
+ field_bool: bool
+
+
+class CombiningDbModel(DbMapResultModel):
+ _list_fields: Set[str] = {"list1"}
+ _set_fields: Set[str] = {"set1"}
+ _dict_key_fields: Dict[str, str] = {"key1": "dict1", "key2": "dict2"}
+ _dict_value_mappings: Dict[str, str] = {"dict1": "val1", "dict2": "val2"}
+
+ id: int = None
+ list1: List[str]
+ set1: Set[str] = set()
+ dict1: Dict[str, Any] = {}
+ dict2: Dict[str, int] = {}
+
+
+class DefaultListCombiningDbModel(CombiningDbModel):
+ list1: List[str] = []
+
+
+class ListWithStringsModel(DbMapResultModel):
+ _csv_list_fields: Set[str] = {"list1", "list2"}
+
+ id: int
+ list1: Optional[List[str]] = None
+ list2: List[int] = [] # help test empty list gets filled
+
+
+class JsonModel(DbMapResultModel):
+ _json_fields: Set[str] = {"json1", "json2"}
+
+ id: int
+ json1: dict
+ json2: Optional[dict] = None
+
+
+class MultiKeyModel(DbMapResultModel):
+ @classmethod
+ def get_key_columns(cls):
+ return ["a", "b"]
+
+ _list_fields = {"c"}
+ a: int
+ b: str
+ c: List[str]
+
+
+def _unwrap_results(results):
+ return [r.raw() for r in results]
+
+
+def test_field_conversion():
+ mapper = SingleRowMapper(record_mapper=ConversionDbModel)
+ assert mapper.map_records(
+ [
+ {"id": 1, "field_str": "str1", "field_int": 1, "field_bool": 1},
+ ]
+ ).raw() == {"id": 1, "field_str": "str1", "field_int": 1, "field_bool": True}
+
+
+def test_complex_object_record_combining():
+ mapper = RecordCombiningMapper(record_mapper=CombiningDbModel)
+ assert len(mapper.map_records([])) == 0
+ assert _unwrap_results(
+ mapper.map_records(
+ [
+ {
+ "id": 1,
+ "list1": "val1",
+ "set1": "val2",
+ "key1": "k1",
+ "val1": "v1",
+ "key2": "k3",
+ "val2": 3,
+ },
+ {"id": 2, "list1": "val1"},
+ {
+ "id": 1,
+ "list1": "val3",
+ "set1": "val4",
+ "key1": "k2",
+ "val1": "v2",
+ "key2": "k4",
+ "val2": 4,
+ },
+ ]
+ )
+ ) == [
+ {
+ "id": 1,
+ "list1": ["val1", "val3"],
+ "set1": {"val2", "val4"},
+ "dict1": {"k1": "v1", "k2": "v2"},
+ "dict2": {"k3": 3, "k4": 4},
+ },
+ {
+ "id": 2,
+ "list1": ["val1"],
+ "set1": set(),
+ "dict1": {},
+ "dict2": {},
+ },
+ ]
+
+
+def test_record_combining_multi_column_id():
+ mapper = RecordCombiningMapper(MultiKeyModel)
+ assert len(mapper.map_records([])) == 0
+ assert _unwrap_results(
+ mapper.map_records(
+ [
+ {"a": 1, "b": "test", "c": "one"},
+ {"a": 1, "b": "test", "c": "two"},
+ {"a": 1, "b": "test", "c": "three"},
+ {"a": 2, "b": "test", "c": "one"},
+ {"a": 2, "b": "test", "c": "two"},
+ {"a": 1, "b": "othertest", "c": "one"},
+ ]
+ )
+ ) == [
+ {"a": 1, "b": "test", "c": ["one", "two", "three"]},
+ {"a": 2, "b": "test", "c": ["one", "two"]},
+ {"a": 1, "b": "othertest", "c": ["one"]},
+ ]
+
+
+def test_complex_object_with_null_values():
+ mapper = SingleRowMapper(record_mapper=DefaultListCombiningDbModel)
+ assert mapper.map_records(
+ [
+ {"id": 1},
+ ]
+ ).raw() == {
+ "id": 1,
+ "list1": [],
+ "set1": set(),
+ "dict1": {},
+ "dict2": {},
+ }
+
+
+def test_csv_list_field():
+ mapper = SingleRowMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [{"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"}]
+ ).raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]}
+
+
+def test_csv_list_field_single_value():
+ mapper = SingleRowMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records([{"id": 1, "list1": "a", "list2": "1"}]).raw() == {
+ "id": 1,
+ "list1": ["a"],
+ "list2": [1],
+ }
+
+
+def test_csv_list_field_empty_string():
+ mapper = SingleRowMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records([{"id": 1, "list1": "", "list2": ""}]).raw() == {
+ "id": 1,
+ "list1": None,
+ "list2": [],
+ }
+
+
+def test_csv_list_field_extends():
+ mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [
+ {"id": 1, "list1": "a,b", "list2": "1,2"},
+ {"id": 1, "list1": "c,d", "list2": "3,4"},
+ ]
+ )[0].raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]}
+
+
+def test_csv_list_field_multiple_records_duplicates():
+ mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [
+ {"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"},
+ {"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"},
+ ]
+ )[0].raw() == {
+ "id": 1,
+ "list1": ["a", "b", "c", "d", "a", "b", "c", "d"],
+ "list2": [1, 2, 3, 4, 1, 2, 3, 4],
+ }
+
+
+def test_csv_list_field_none_in_first_record():
+ mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [
+ {"id": 1, "list1": "a,b,c,d", "list2": None},
+ {"id": 1, "list1": "e,f,g", "list2": "1,2,3,4"},
+ ]
+ )[0].raw() == {
+ "id": 1,
+ "list1": ["a", "b", "c", "d", "e", "f", "g"],
+ "list2": [1, 2, 3, 4],
+ }
+
+
+def test_csv_list_field_without_mapping_ignored():
+ mapper = SingleRowMapper(record_mapper=ListWithStringsModel)
+ assert mapper.map_records(
+ [{"id": 1, "list1": "a,b, c,d", "list2": "1,2,3,4", "list3": "x,y,z"}]
+ ).raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]}
+
+
+def test_csv_list_field_invalid_type():
+ mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel)
+ with pytest.raises(ValidationError, match="1 validation error for list"):
+ mapper.map_records(
+ [
+ {"id": 1, "list1": "a,b", "list2": "1,2"},
+ {"id": 1, "list1": "c,d", "list2": "3,a"},
+ ]
+ )
+
+
+def test_json_field():
+ mapper = SingleRowMapper(record_mapper=JsonModel)
+ assert mapper.map_records(
+ [
+ {
+ "id": 1,
+ "json1": json.dumps(
+ {"a": 1, "b": 2, "c": {"x": 10, "y": 9, "z": {"deep": "value"}}}
+ ),
+ }
+ ]
+ ).model_dump() == {
+ "id": 1,
+ "json1": {"a": 1, "b": 2, "c": {"x": 10, "y": 9, "z": {"deep": "value"}}},
+ "json2": None,
+ }
+
+
+@pytest.mark.parametrize(
+ "json1, json2",
+ [
+ ('{ "json": value', None),
+ ('{ "json": value', '{ "json": value }'),
+ ('{ "json": value }', '{ "json": value'),
+ (None, '{ "json": value'),
+ ],
+)
+def test_invalid_json(json1, json2):
+ with pytest.raises(ValidationError, match="Invalid JSON"):
+ mapper = SingleRowMapper(record_mapper=JsonModel)
+ mapper.map_records([{"id": 1, "json1": json1, "json2": json2}])
+
+
+def test_json_none():
+ mapper = SingleRowMapper(record_mapper=JsonModel)
+ assert mapper.map_records(
+ [{"id": 1, "json1": '{ "first": "value" }', "json2": None}]
+ ).model_dump() == {
+ "id": 1,
+ "json1": {
+ "first": "value",
+ },
+ "json2": None,
+ }
diff --git a/dysql/test/test_sql_decorator.py b/dysql/test/test_sql_decorator.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_sql_decorator.py
@@ -0,0 +1,399 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+
+from dysql import (
+ sqlupdate,
+ sqlquery,
+ DbMapResult,
+ CountMapper,
+ SingleRowMapper,
+ QueryData,
+ QueryDataError,
+)
+from dysql.test import setup_mock_engine
+
+
+class TestSqlSelectDecorator:
+ """
+ Test Sql Select Decorator
+ """
+
+ @staticmethod
+ @pytest.fixture
+ def mock_results():
+ return [
+ {
+ "id": 1,
+ "name": "jack",
+ "email": "jack@adobe.com",
+ "hobbies": ["golf", "bikes", "coding"],
+ },
+ {
+ "id": 2,
+ "name": "flora",
+ "email": "flora@adobe.com",
+ "hobbies": ["golf", "coding"],
+ },
+ {
+ "id": 3,
+ "name": "Terrence",
+ "email": "terrence@adobe.com",
+ "hobbies": ["coding", "watching tv", "hot dog eating contest"],
+ },
+ ]
+
+ @staticmethod
+ @pytest.fixture
+ def mock_engine(mock_results, mock_create_engine):
+ mock_engine = setup_mock_engine(mock_create_engine)
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results
+ return mock_engine
+
+ @staticmethod
+ def test_non_query_data_fails(mock_create_engine):
+ # This argument forces the fixture setup
+ _ = mock_create_engine
+
+ @sqlquery()
+ def select_with_string():
+ return "SELECT"
+
+ with pytest.raises(QueryDataError):
+ select_with_string()
+
+ def test_map_not_specified(self, mock_results, mock_engine):
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results
+ assert isinstance(list(self._select_all())[0], DbMapResult)
+
+ def test_single(self, mock_results, mock_engine):
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results
+ result = self._select_single()
+ assert isinstance(result, DbMapResult)
+
+ def test_count(self, mock_engine):
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = [
+ {"count": 2},
+ {"count": 3},
+ ]
+ assert self._select_count() == 2
+
+ def test_execute_no_params(self, mock_engine):
+ self._select_all()
+ mock_engine.connect.return_value.execution_options.return_value.execute.assert_called()
+ call_args = mock_engine.connect.return_value.execution_options.return_value.execute.call_args
+ assert call_args[0][0].text == "SELECT * FROM my_table"
+ assert call_args[0][1] == {}
+
+ def test_execute_params(self, mock_engine):
+ self._select_filtered(3)
+ mock_engine.connect.return_value.execution_options.return_value.execute.assert_called()
+
+ call_args = mock_engine.connect.return_value.execution_options.return_value.execute.call_args
+ assert call_args[0][0].text == "SELECT * FROM my_table WHERE id=:id"
+ assert call_args[0][1] == {"id": 3}
+
+ def test_list_results_map(self, mock_results, mock_engine):
+ mock_engine.connect.return_value.execution_options.return_value.execute.return_value = [
+ mock_results[2]
+ ]
+ results = self._select_filtered(3)
+
+ assert len(results) == 1
+ assert len(list(results)[0].hobbies) == 3
+
+ def test_isolation_default(self, mock_engine):
+ mock_connect = mock_engine.connect.return_value.execution_options
+ self._select_all()
+ mock_connect.assert_called_with(isolation_level="READ_COMMITTED")
+
+ def test_isolation_default_read_uncommited(self, mock_engine):
+ mock_connect = mock_engine.connect.return_value.execution_options
+ self._select_uncommitted()
+ mock_connect.assert_called_with(isolation_level="READ_UNCOMMITTED")
+ mock_connect.return_value.execute.assert_called()
+
+ @staticmethod
+ @sqlquery()
+ def _select_all():
+ """
+ method is static just to help show you can use static methods if
+ you don't want to instantiate an instance of the class
+ """
+ return QueryData("SELECT * FROM my_table")
+
+ @staticmethod
+ @sqlquery(mapper=SingleRowMapper())
+ def _select_single():
+ return QueryData("SELECT * FROM my_table")
+
+ @staticmethod
+ @sqlquery(mapper=CountMapper)
+ def _select_count():
+ return QueryData("SELECT COUNT(*) FROM my_table")
+
+ @staticmethod
+ @sqlquery()
+ def _select_filtered(_id):
+ return QueryData(
+ "SELECT * FROM my_table WHERE id=:id", query_params={"id": _id}
+ )
+
+ @staticmethod
+ @sqlquery(isolation_level="READ_UNCOMMITTED")
+ def _select_uncommitted():
+ return QueryData("SELECT * FROM uncommitted")
+
+
+class TestSqlUpdateDecorator:
+ """
+ Test Sql Update Decorator
+ """
+
+ @staticmethod
+ @pytest.fixture
+ def mock_engine(mock_create_engine):
+ return setup_mock_engine(mock_create_engine)
+
+ @staticmethod
+ @pytest.fixture
+ def mock_connect(mock_engine):
+ return mock_engine.connect.return_value.execution_options
+
+ def test_isolation_default(self, mock_connect):
+ self._update_something({"id": 1, "value": "test"})
+ mock_connect.assert_called_with(isolation_level="READ_COMMITTED")
+
+ def test_isolation_default_read_uncommited(self, mock_connect):
+ self._update_something_uncommited_isolation({"id": 1, "value": "test"})
+ mock_connect.assert_called_with(isolation_level="READ_UNCOMMITTED")
+ mock_connect.return_value.begin.assert_called()
+ mock_connect.return_value.begin.return_value.commit.assert_called()
+ mock_connect.return_value.__exit__.assert_called()
+
+ def test_transaction(self, mock_connect):
+ self._update_something({"id": 1, "value": "test"})
+ mock_connect().begin.assert_called()
+ mock_connect().begin.return_value.commit.assert_called()
+ mock_connect().__exit__.assert_called()
+
+ def test_transaction_fails(self, mock_connect):
+ mock_connect().execute.side_effect = Exception("error")
+ with pytest.raises(Exception):
+ self._update_something({"id": 1, "value": "test"})
+ mock_connect().begin.return_value.commit.assert_not_called()
+ mock_connect().begin.return_value.rollback.assert_called()
+ mock_connect().__exit__.assert_called()
+
+ def test_execute_passes_values(self, mock_engine):
+ values = {"id": 1, "value": "test"}
+ self._update_something(values)
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ execute_call.assert_called()
+
+ execute_call_args = execute_call.call_args[0]
+ assert execute_call_args[0].text == "INSERT something"
+ assert values == execute_call_args[1]
+
+ def test_execute_query_values_none(self, mock_engine):
+ self._update_something(None)
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ execute_call.assert_called()
+
+ self._expect_args_list(execute_call.call_args_list[0], "INSERT something")
+
+ def test_execute_query_values_not_given(self, mock_engine):
+ # pylint: disable=unused-argument
+ self._update_something_no_params()
+
+ def test_execute_multi_yield(self, mock_connect):
+ expected_values = [
+ {"id": 1, "value": "test 1"},
+ {"id": 2, "value": "test 2"},
+ {"id": 3, "value": "test 3"},
+ ]
+ self._update_something_multi_yield(expected_values)
+
+ execute_call = mock_connect().execute
+ assert execute_call.call_count == 3
+
+ for call_args in execute_call.call_args_list:
+ self._expect_args_list(call_args, "INSERT something")
+
+ def test_execute_fails_list_if_multi_false(self):
+ expected_values = [
+ {"id": 1, "value": "test 1"},
+ {"id": 2, "value": "test 2"},
+ {"id": 3, "value": "test 3"},
+ ]
+ with pytest.raises(Exception):
+ self._update_list_when_multi_false(expected_values)
+
+ def test_execute_multi_yield_and_lists(self, mock_engine):
+ expected_values = [
+ {"id": 1, "value": "test 1"},
+ {"id": 2, "value": "test 2"},
+ {"id": 3, "value": "test 3"},
+ ]
+ other_expected_values = [
+ {"id": 5, "value": "test 5"},
+ {"id": 6, "value": "test 6"},
+ {"id": 7, "value": "test 7"},
+ ]
+ self._update_yield_with_lists(expected_values, other_expected_values)
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ assert execute_call.call_count == 2
+
+ self._expect_args_list(
+ execute_call.call_args_list[0],
+ "INSERT some VALUES ( :values__in_0_0, :values__in_0_1 ), ( :values__in_1_0, :values__in_1_1 ), "
+ "( :values__in_2_0, :values__in_2_1 ) ",
+ )
+ self._expect_args_list(
+ execute_call.call_args_list[1],
+ "INSERT some more VALUES ( :values__other_0_0, :values__other_0_1 ), "
+ "( :values__other_1_0, :values__other_1_1 ), ( :values__other_2_0, :values__other_2_1 ) ",
+ )
+
+ def test_execute_multi_yield_and_lists_some_no_params(self, mock_engine):
+ expected_values = [
+ {"id": 1, "value": "test 1"},
+ {"id": 2, "value": "test 2"},
+ {"id": 3, "value": "test 3"},
+ ]
+ self._update_yield_with_lists_some_no_params(expected_values)
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ assert execute_call.call_count == 4
+
+ self._expect_args_list(
+ execute_call.call_args_list[0],
+ "INSERT some VALUES ( :values__in_0_0, :values__in_0_1 ), ( :values__in_1_0, :values__in_1_1 ), "
+ "( :values__in_2_0, :values__in_2_1 ) ",
+ )
+ self._expect_args_list(execute_call.call_args_list[1], "UPDATE some more")
+ self._expect_args_list(execute_call.call_args_list[2], "UPDATE some more")
+ self._expect_args_list(execute_call.call_args_list[3], "DELETE some more")
+
+ def test_set_foreign_key_checks_default(self, mock_engine):
+ self._update_something_no_params()
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ assert execute_call.call_count == 1
+
+ def test_set_foreign_key_checks_true(self, mock_engine):
+ self._update_without_foreign_key_checks()
+
+ execute_call = (
+ mock_engine.connect.return_value.execution_options.return_value.execute
+ )
+ assert execute_call.call_count == 4
+ assert execute_call.call_args_list[0][0][0].text == "SET FOREIGN_KEY_CHECKS=0"
+ assert execute_call.call_args_list[-1][0][0].text == "SET FOREIGN_KEY_CHECKS=1"
+
+ @staticmethod
+ def _expect_args_list(call_args, expected_query):
+ assert expected_query == call_args[0][0].text
+
+ @staticmethod
+ @sqlupdate(disable_foreign_key_checks=True)
+ def _update_without_foreign_key_checks():
+ yield QueryData("INSERT B_RELIES_ON_A")
+ yield QueryData("INSERT A")
+
+ @staticmethod
+ @sqlupdate()
+ def _update_something(values):
+ return QueryData("INSERT something", query_params=values)
+
+ @staticmethod
+ @sqlupdate(isolation_level="READ_UNCOMMITTED")
+ def _update_something_uncommited_isolation(values):
+ return QueryData(f"INSERT WITH uncommitted {values}")
+
+ @staticmethod
+ @sqlupdate()
+ def _update_something_no_params():
+ return QueryData("INSERT something")
+
+ @staticmethod
+ @sqlupdate()
+ def _update_something_multi_yield(multiple_values):
+ for values in multiple_values:
+ yield QueryData("INSERT something", query_params=values)
+
+ @staticmethod
+ @sqlupdate()
+ def _update_something_return_list(multiple_values):
+ return QueryData("INSERT something", query_params=multiple_values)
+
+ @staticmethod
+ @sqlupdate()
+ def _update_list_when_multi_false(multiple_values):
+ return "INSERT something", multiple_values
+
+ @staticmethod
+ @sqlupdate()
+ def _update_yield_with_lists(multiple_values, other_values):
+ """
+ method is static just to help show you can use static methods if
+ you don't want to instantiate an instance of the class
+
+ NOTE:
+ """
+ yield QueryData(
+ "INSERT some {values__in}",
+ template_params=_get_template_params("values__in", multiple_values),
+ )
+ yield QueryData(
+ "INSERT some more {values__other}",
+ template_params=_get_template_params("values__other", other_values),
+ )
+
+ @staticmethod
+ @sqlupdate()
+ def _update_yield_with_lists_some_no_params(multiple_values):
+ """
+ method is static just to help show you can use static methods if
+ you don't want to instantiate an instance of the class
+ """
+ yield QueryData(
+ "INSERT some {values__in}",
+ template_params=_get_template_params("values__in", multiple_values),
+ )
+ yield QueryData("UPDATE some more")
+ yield QueryData("UPDATE some more")
+ yield QueryData("DELETE some more")
+
+
+def _get_template_params(key, values):
+ """
+ template parameters is handled here as an example of what you might end up
+ doing. usually data coming in is going to be a list
+
+ :param key: the template key we want to use to build our template with
+ :param values: the list of objects or mariadbmaps,
+ :return: a keyed list of tuples or mariadbmaps
+ """
+ if isinstance(values[0], DbMapResult):
+ return {key: values}
+ return {key: [(v["id"], v["value"]) for v in values]}
diff --git a/dysql/test/test_sql_exists_decorator.py b/dysql/test/test_sql_exists_decorator.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_sql_exists_decorator.py
@@ -0,0 +1,165 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from unittest.mock import Mock
+
+import pytest
+
+from dysql import sqlexists, QueryData
+from dysql.test import setup_mock_engine
+
+
+TRUE_QUERY = "SELECT 1 from table"
+TRUE_QUERY_PARAMS = "SELECT 1 from table where key=:key"
+FALSE_QUERY = "SELECT 1 from false_table "
+FALSE_QUERY_PARAMS = "SELECT 1 from table where key=:key"
+TRUE_PARAMS = {"key": 123}
+FALSE_PARAMS = {"key": 456}
+SELECT_EXISTS_QUERY = "SELECT 1 WHERE EXISTS ( {} )"
+SELECT_EXISTS_NO_WHERE_QUERY = "SELECT EXISTS ( {} )"
+EXISTS_QUERIES = {
+ "true": SELECT_EXISTS_QUERY.format(TRUE_QUERY),
+ "false": SELECT_EXISTS_QUERY.format(FALSE_QUERY),
+ "true_params": SELECT_EXISTS_QUERY.format(TRUE_QUERY_PARAMS),
+ "false_params": SELECT_EXISTS_QUERY.format(FALSE_QUERY_PARAMS),
+ "true_no_where": SELECT_EXISTS_NO_WHERE_QUERY.format(TRUE_QUERY),
+ "false_no_where": SELECT_EXISTS_NO_WHERE_QUERY.format(FALSE_QUERY),
+}
+
+
+@pytest.fixture(autouse=True)
+def mock_engine_fixture(mock_create_engine):
+ mock_engine = setup_mock_engine(mock_create_engine)
+ mock_engine.connect.return_value.execution_options.return_value.execute.side_effect = _check_query_and_return_result
+ mock_engine.connect().execution_options().__enter__ = Mock()
+ mock_engine.connect().execution_options().__exit__ = Mock()
+
+
+def test_exists_true():
+ assert _exists_true()
+
+
+def test_exists_false():
+ assert not _exists_false()
+
+
+def test_exists_true_params():
+ assert _exists_true_params()
+
+
+def test_exists_false_params():
+ assert not _exists_false_params()
+
+
+def test_exists_query_contains_with_exists_true():
+ """
+ this helps to test that if someone adds an exists statement, we don't add the exists
+ exists(exists()) will always give a 'true' result
+ """
+ # should match against the same query, should still match
+ assert _exists_specified("true")
+
+
+def test_exists_query_contains_with_exists_false():
+ """
+ this helps to test that if someone adds an exists statement, we don't add the exists
+ exists(exists()) will always give a 'true' result
+ """
+ # should match against the same query, should still match
+ assert not _exists_specified("false")
+
+
+def test_exists_without_where_true():
+ """
+ this helps avoid an issue discovered when using the 'utf8' charset, some queries with the exists
+ query would fail to decode the '0' returned with a query as just `SELECT EXISTS` but work as expected
+ when using `SELECT 1 WHERE EXISTS`
+ """
+ assert _select_exists_no_where_true()
+
+
+def test_exists_witohut_where_false():
+ """
+ this helps avoid an issue discovered when using the 'utf8' charset, some queries with the exists
+ query would fail to decode the '0' returned with a query as just `SELECT EXISTS` but work as expected
+ when using `SELECT 1 WHERE EXISTS`
+ """
+ assert not _select_exists_no_where_false()
+
+
+def test_exists_query_starts_with_exists_handles_whitespace():
+ """
+ this helps to test that if someone adds an exists statement, we don't add the exists
+ exists(exists()) will always give a 'true' result
+ """
+ # should trim the whitespace and match appropiately
+ assert _exists_whitespace()
+
+
+@sqlexists()
+def _select_exists_no_where_false():
+ return QueryData(EXISTS_QUERIES["false_no_where"])
+
+
+@sqlexists()
+def _select_exists_no_where_true():
+ return QueryData(EXISTS_QUERIES["true_no_where"])
+
+
+@sqlexists()
+def _exists_specified(key):
+ return QueryData(EXISTS_QUERIES[key])
+
+
+@sqlexists()
+def _exists_true():
+ return QueryData(TRUE_QUERY)
+
+
+@sqlexists()
+def _exists_false():
+ return QueryData(FALSE_QUERY)
+
+
+@sqlexists()
+def _exists_true_params():
+ return QueryData(TRUE_QUERY, TRUE_PARAMS)
+
+
+@sqlexists()
+def _exists_false_params():
+ return QueryData(FALSE_QUERY, FALSE_PARAMS)
+
+
+@sqlexists()
+def _exists_whitespace():
+ return QueryData(
+ """
+ """
+ + TRUE_QUERY
+ )
+
+
+def _check_query_and_return_result(query, params):
+ """
+ check that the query matches our expectations
+ and then set the return value for the scalar call.
+ scalar() returns either 1 or 0, 1 for true, 0 for false
+ """
+ assert query.text in list(EXISTS_QUERIES.values())
+ scalar_mock = Mock()
+ # default mock responses to true, then we only handle setting false responses
+ scalar_mock.scalar.return_value = 1
+ if query.text == EXISTS_QUERIES["true_params"]:
+ assert params.get("key") == 123
+ if query.text == EXISTS_QUERIES["false_params"]:
+ assert params.get("key") == 456
+ scalar_mock.scalar.return_value = 0
+ elif query.text == EXISTS_QUERIES["false"]:
+ scalar_mock.scalar.return_value = 0
+ return scalar_mock
diff --git a/dysql/test/test_sql_in_list_templates.py b/dysql/test/test_sql_in_list_templates.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_sql_in_list_templates.py
@@ -0,0 +1,289 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+# pylint: disable=too-many-public-methods
+import pytest
+
+import dysql
+from dysql import QueryData, sqlquery
+from dysql.test import (
+ verify_query,
+ verify_query_args,
+ verify_query_params,
+ setup_mock_engine,
+)
+
+
+@pytest.fixture(name="mock_engine", autouse=True)
+def mock_engine_fixture(mock_create_engine):
+ mock_engine = setup_mock_engine(mock_create_engine)
+ mock_engine.connect().execution_options().execute.side_effect = lambda x, y: []
+ return mock_engine
+
+
+def test_list_in_numbers(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a}",
+ template_params={"in__column_a": [1, 2, 3, 4]},
+ )
+ verify_query_params(
+ mock_engine,
+ "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1, :in__column_a_2, :in__column_a_3 ) ",
+ {
+ "in__column_a_0": 1,
+ "in__column_a_1": 2,
+ "in__column_a_2": 3,
+ "in__column_a_3": 4,
+ },
+ )
+
+
+def test_list_in__strings(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a}",
+ template_params={"in__column_a": ["a", "b", "c", "d"]},
+ )
+ verify_query_params(
+ mock_engine,
+ "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1, :in__column_a_2, :in__column_a_3 ) ",
+ {
+ "in__column_a_0": "a",
+ "in__column_a_1": "b",
+ "in__column_a_2": "c",
+ "in__column_a_3": "d",
+ },
+ )
+
+
+def test_list_not_in_numbers(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {not_in__column_b}",
+ template_params={"not_in__column_b": [1, 2, 3, 4]},
+ )
+ verify_query_params(
+ mock_engine,
+ "SELECT * FROM table WHERE column_b NOT IN ( :not_in__column_b_0, :not_in__column_b_1, "
+ ":not_in__column_b_2, :not_in__column_b_3 ) ",
+ {
+ "not_in__column_b_0": 1,
+ "not_in__column_b_1": 2,
+ "not_in__column_b_2": 3,
+ "not_in__column_b_3": 4,
+ },
+ )
+
+
+def test_list_not_in_strings(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {not_in__column_b}",
+ template_params={"not_in__column_b": ["a", "b", "c", "d"]},
+ )
+ verify_query_params(
+ mock_engine,
+ "SELECT * FROM table WHERE column_b NOT IN ( :not_in__column_b_0, :not_in__column_b_1, "
+ ":not_in__column_b_2, :not_in__column_b_3 ) ",
+ {
+ "not_in__column_b_0": "a",
+ "not_in__column_b_1": "b",
+ "not_in__column_b_2": "c",
+ "not_in__column_b_3": "d",
+ },
+ )
+
+
+def test_list_in_handles_empty(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a}", template_params={"in__column_a": []}
+ )
+ verify_query(mock_engine, "SELECT * FROM table WHERE 1 <> 1 ")
+
+
+def test_list_in_handles_no_param():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['in__column_a']"
+ ):
+ _query("SELECT * FROM table WHERE {in__column_a}")
+
+
+def test_list_in_multiple_lists(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a} OR {in__column_b}",
+ template_params={"in__column_a": ["first", "second"], "in__column_b": [1, 2]},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1 ) "
+ "OR column_b IN ( :in__column_b_0, :in__column_b_1 ) ",
+ )
+
+
+def test_list_in_multiple_lists_one_empty(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a} OR {in__column_b}",
+ template_params={"in__column_a": ["first", "second"], "in__column_b": []},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1 ) OR 1 <> 1 ",
+ )
+
+
+def test_list_in_multiple_lists_one_missing():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['in__column_a']"
+ ):
+ _query(
+ "SELECT * FROM table WHERE {in__column_a} OR {in__column_b} ",
+ template_params={"in__column_b": [1, 2]},
+ )
+
+
+def test_list_in_multiple_lists_all_missing():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['in__column_a','in__column_b']"
+ ):
+ _query("SELECT * FROM table WHERE {in__column_a} OR {in__column_b} ")
+
+
+def test_list_not_in_handles_empty(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {not_in__column_b}",
+ template_params={"not_in__column_b": []},
+ )
+ verify_query(mock_engine, "SELECT * FROM table WHERE 1 = 1 ")
+
+
+def test_list_not_in_handles_no_param():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['not_in__column_b']"
+ ):
+ _query("SELECT * FROM table WHERE {not_in__column_b} ")
+
+
+def test_list_gives_template_space_before(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE{in__space}", template_params={"in__space": [9, 8]}
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) ",
+ )
+
+
+def test_list_gives_template_space_after(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__space}AND other_condition = 1",
+ template_params={"in__space": [9, 8]},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) AND other_condition = 1",
+ )
+
+
+def test_list_gives_template_space_before_and_after(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE{in__space}AND other_condition = 1",
+ template_params={"in__space": [9, 8]},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) AND other_condition = 1",
+ )
+
+
+def test_in_contains_whitespace(mock_engine):
+ _query("{in__column_one}", template_params={"in__column_one": [1, 2]})
+ verify_query(
+ mock_engine, " column_one IN ( :in__column_one_0, :in__column_one_1 ) "
+ )
+
+
+def test_template_handles_table_qualifier(mock_engine):
+ """
+ when the table is specified with a dot separator, we need to split the table out of the
+ keyword and the keyword passed in should be passed in without the keyword
+
+ {in__table.column} -> {table}.{in__column} -> table.column IN (:in__column_0, :in__column_1)
+ :return:
+ """
+ _query(
+ "SELECT * FROM table WHERE {in__table.column}",
+ template_params={"in__table.column": [1, 2]},
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE table.column IN ( :in__table_column_0, :in__table_column_1 ) ",
+ )
+ verify_query_args(mock_engine, {"in__table_column_0": 1, "in__table_column_1": 2})
+
+
+def test_template_handles_multiple_table_qualifier(mock_engine):
+ _query(
+ "SELECT * FROM table WHERE {in__table.column} AND {not_in__other_column}",
+ template_params={
+ "in__table.column": [1, 2],
+ "not_in__other_column": ["a", "b"],
+ },
+ )
+ verify_query(
+ mock_engine,
+ "SELECT * FROM table WHERE table.column IN ( :in__table_column_0, :in__table_column_1 ) "
+ "AND other_column NOT IN ( :not_in__other_column_0, :not_in__other_column_1 ) ",
+ )
+ verify_query_args(
+ mock_engine,
+ {
+ "in__table_column_0": 1,
+ "in__table_column_1": 2,
+ "not_in__other_column_0": "a",
+ "not_in__other_column_1": "b",
+ },
+ )
+
+
+def test_empty_in_contains_whitespace(mock_engine):
+ _query("{in__column_one}", template_params={"in__column_one": []})
+ verify_query(mock_engine, " 1 <> 1 ")
+
+
+def test_multiple_templates_same_column_diff_table(mock_engine):
+ template_params = {
+ "in__table.status": ["on", "off", "waiting"],
+ "in__other_table.status": ["success", "partial_success"],
+ }
+ expected_params_from_template = {
+ "in__table_status_0": "on",
+ "in__table_status_1": "off",
+ "in__table_status_2": "waiting",
+ "in__other_table_status_0": "success",
+ "in__other_table_status_1": "partial_success",
+ }
+
+ # writing each of these queries out to help see what we expect compared to
+ # the query we actually sent
+ _query(
+ "SELECT * FROM table WHERE {in__table.status} AND {in__other_table.status}",
+ template_params=template_params,
+ )
+ expected_query = (
+ "SELECT * FROM table WHERE table.status IN ( :in__table_status_0, :in__table_status_1, "
+ ":in__table_status_2 ) AND other_table.status IN ( :in__other_table_status_0, "
+ ":in__other_table_status_1 ) "
+ )
+
+ connection = mock_engine.connect.return_value.execution_options.return_value
+ execute_call = connection.execute
+ execute_call.assert_called_once()
+ assert execute_call.call_args[0][0].text == expected_query
+ assert execute_call.call_args[0][1] == expected_params_from_template
+
+
+@sqlquery()
+def _query(query, query_params=None, template_params=None):
+ return QueryData(query, query_params=query_params, template_params=template_params)
diff --git a/dysql/test/test_sql_insert_templates.py b/dysql/test/test_sql_insert_templates.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_sql_insert_templates.py
@@ -0,0 +1,174 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+
+import dysql
+from dysql import QueryData, sqlupdate, QueryDataError
+from dysql.test import (
+ verify_query,
+ verify_query_args,
+ setup_mock_engine,
+)
+
+
+@pytest.fixture(name="mock_engine", autouse=True)
+def mock_engine_fixture(mock_create_engine):
+ initial_id = 0
+
+ def handle_execute(query=None, args=None):
+ nonlocal initial_id
+ if "INSERT INTO get_last(name)" in query.text:
+ initial_id += 1
+ if "SELECT LAST_INSERT_ID()" == query.text:
+ return type("Result", (), {"scalar": lambda: initial_id})
+ return []
+
+ mock_engine = setup_mock_engine(mock_create_engine)
+ execute_mock = mock_engine.connect().execution_options().execute
+ execute_mock.side_effect = handle_execute
+ return mock_engine
+
+
+def test_insert_non_query_data_fails():
+ @sqlupdate()
+ def select_with_string():
+ return "INSERT"
+
+ with pytest.raises(QueryDataError):
+ select_with_string()
+
+
+def test_insert_single_column(mock_engine):
+ insert_into_single_value(["Tom", "Jerry"])
+ verify_query(
+ mock_engine,
+ "INSERT INTO table(name) VALUES ( :values__name_col_0 ), ( :values__name_col_1 ) ",
+ )
+
+
+def test_insert_single_column_single_value(mock_engine):
+ insert_into_single_value("Tom")
+ verify_query(mock_engine, "INSERT INTO table(name) VALUES ( :values__name_col_0 ) ")
+
+
+def test_insert_single_value_empty():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['values_name_col']"
+ ):
+ insert_into_single_value([])
+
+
+def test_insert_single_value_no_key():
+ with pytest.raises(
+ dysql.query_utils.ListTemplateException, match="['values_name_col']"
+ ):
+ insert_into_single_value(None)
+
+
+def test_insert_multiple_values(mock_engine):
+ insert_into_multiple_values(
+ [
+ {"name": "Tom", "email": "tom@adobe.com"},
+ {"name": "Jerry", "email": "jerry@adobe.com"},
+ ]
+ )
+ verify_query(
+ mock_engine,
+ "INSERT INTO table(name, email) VALUES ( :values__users_0_0, :values__users_0_1 ), "
+ "( :values__users_1_0, :values__users_1_1 ) ",
+ )
+ verify_query_args(
+ mock_engine,
+ {
+ "values__users_0_0": "Tom",
+ "values__users_0_1": "tom@adobe.com",
+ "values__users_1_0": "Jerry",
+ "values__users_1_1": "jerry@adobe.com",
+ },
+ )
+
+
+@pytest.mark.parametrize(
+ "args",
+ [
+ ([("bob", "bob@email.com")]),
+ ([("bob", "bob@email.com"), ("tom", "tom@email.com")]),
+ None,
+ (),
+ ],
+)
+def test_insert_with_callback(args):
+ def callback(items):
+ assert items == args
+
+ @sqlupdate(on_success=callback)
+ def insert(items):
+ yield QueryData(f"INSERT INTO table(name, email) {items}")
+
+ insert(args)
+
+
+def test_insert_with_callack_not_called(mock_engine):
+ def callback():
+ assert False
+
+ @sqlupdate(on_success=callback)
+ def insert():
+ yield QueryData("INSERT INTO table(name, email)")
+
+ mock_engine.connect().execution_options.return_value.execute.side_effect = (
+ Exception()
+ )
+ with pytest.raises(Exception):
+ insert()
+
+
+@sqlupdate()
+def insert_into_multiple_values(users):
+ yield QueryData(
+ "INSERT INTO table(name, email) {values__users}",
+ template_params={"values__users": [(d["name"], d["email"]) for d in users]},
+ )
+
+
+@sqlupdate()
+def insert_into_single_value(names):
+ template_params = {}
+ if names is not None:
+ template_params = {"values__name_col": names}
+
+ return QueryData(
+ "INSERT INTO table(name) {values__name_col}", template_params=template_params
+ )
+
+
+def test_last_insert_id():
+ @sqlupdate()
+ def insert(get_last_insert_id=None):
+ yield QueryData("INSERT INTO get_last(name) VALUES ('Tom')")
+ assert get_last_insert_id
+ assert get_last_insert_id() == 1
+ yield QueryData("INSERT INTO get_last(name) VALUES ('Jerry')")
+ assert get_last_insert_id() == 2
+
+ insert()
+
+
+def test_last_insert_id_removed_before_callback():
+ def callback(**kwargs):
+ assert "get_last_insert_id" not in kwargs
+
+ @sqlupdate()
+ def insert(get_last_insert_id=None):
+ assert get_last_insert_id
+ yield QueryData("INSERT INTO get_last(name) VALUES ('Tom')")
+ yield QueryData("INSERT INTO get_last(name) VALUES ('Jerry')")
+ assert get_last_insert_id() == 2
+
+ insert()
diff --git a/dysql/test/test_template_generators.py b/dysql/test/test_template_generators.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_template_generators.py
@@ -0,0 +1,222 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+
+from dysql.query_utils import TemplateGenerators, ListTemplateException
+
+
+class TestTemplatesGenerators:
+ """
+ Test we get templates back from Templates
+ """
+
+ number_values = [1, 2, 3, 4]
+ string_values = ["1", "2", "3", "4"]
+ set_values = {1, 2, 3, 4}
+ insert_values = [("ironman", 1), ("batman", 2)]
+ tuple_values = [(1, 2), (3, 4)]
+ query = "column_a IN ( :column_a_0, :column_a_1, :column_a_2, :column_a_3 )"
+
+ query_with_list_of_tuples = (
+ "(column_a, column_b) IN (( :column_acolumn_b_0_0, :column_acolumn_b_0_1 ), "
+ "( :column_acolumn_b_1_0, :column_acolumn_b_1_1 ))"
+ )
+ not_query_with_list_of_tuples = (
+ "(column_a, column_b) NOT IN (( :column_acolumn_b_0_0, :column_acolumn_b_0_1 ), "
+ "( :column_acolumn_b_1_0, :column_acolumn_b_1_1 ))"
+ )
+ query_with_table = "table.column_a IN ( :table_column_a_0, :table_column_a_1, :table_column_a_2, :table_column_a_3 )"
+ not_query = "column_a NOT IN ( :column_a_0, :column_a_1, :column_a_2, :column_a_3 )"
+ not_query_with_table = "table.column_a NOT IN ( :table_column_a_0, :table_column_a_1, :table_column_a_2, :table_column_a_3 )"
+
+ test_query_data = (
+ "template_function, column_name,column_values,expected_query",
+ [
+ (TemplateGenerators.in_column, "column_a", number_values, query),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ number_values,
+ query_with_table,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ set_values,
+ query_with_table,
+ ),
+ (TemplateGenerators.in_column, "column_a", string_values, query),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ string_values,
+ query_with_table,
+ ),
+ (TemplateGenerators.in_column, "column_a", [], "1 <> 1"),
+ (
+ TemplateGenerators.in_multi_column,
+ "(column_a, column_b)",
+ tuple_values,
+ query_with_list_of_tuples,
+ ),
+ (
+ TemplateGenerators.not_in_multi_column,
+ "(column_a, column_b)",
+ tuple_values,
+ not_query_with_list_of_tuples,
+ ),
+ (TemplateGenerators.not_in_column, "column_a", number_values, not_query),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ number_values,
+ not_query_with_table,
+ ),
+ (TemplateGenerators.not_in_column, "column_a", string_values, not_query),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ string_values,
+ not_query_with_table,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ set_values,
+ not_query_with_table,
+ ),
+ (TemplateGenerators.not_in_column, "column_a", [], "1 = 1"),
+ (
+ TemplateGenerators.values,
+ "someid",
+ insert_values,
+ "VALUES ( :someid_0_0, :someid_0_1 ), ( :someid_1_0, :someid_1_1 )",
+ ),
+ ],
+ )
+
+ parameter_numbers = {
+ "column_a_0": number_values[0],
+ "column_a_1": number_values[1],
+ "column_a_2": number_values[2],
+ "column_a_3": number_values[3],
+ }
+ with_table_parameter_numbers = {
+ "table_column_a_0": number_values[0],
+ "table_column_a_1": number_values[1],
+ "table_column_a_2": number_values[2],
+ "table_column_a_3": number_values[3],
+ }
+ parameter_strings = {
+ "column_a_0": string_values[0],
+ "column_a_1": string_values[1],
+ "column_a_2": string_values[2],
+ "column_a_3": string_values[3],
+ }
+ with_table_parameter_strings = {
+ "table_column_a_0": string_values[0],
+ "table_column_a_1": string_values[1],
+ "table_column_a_2": string_values[2],
+ "table_column_a_3": string_values[3],
+ }
+ test_params_data = (
+ "template_function, column_name,column_values,expected_params",
+ [
+ (
+ TemplateGenerators.in_column,
+ "column_a",
+ number_values,
+ parameter_numbers,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "column_a",
+ set_values,
+ parameter_numbers,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ number_values,
+ with_table_parameter_numbers,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "column_a",
+ string_values,
+ parameter_strings,
+ ),
+ (
+ TemplateGenerators.in_column,
+ "table.column_a",
+ string_values,
+ with_table_parameter_strings,
+ ),
+ (TemplateGenerators.in_column, "column_a", [], None),
+ (
+ TemplateGenerators.not_in_column,
+ "column_a",
+ number_values,
+ parameter_numbers,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ number_values,
+ with_table_parameter_numbers,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "column_a",
+ string_values,
+ parameter_strings,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "column_a",
+ set_values,
+ parameter_numbers,
+ ),
+ (
+ TemplateGenerators.not_in_column,
+ "table.column_a",
+ string_values,
+ with_table_parameter_strings,
+ ),
+ (TemplateGenerators.not_in_column, "column_a", [], None),
+ (
+ TemplateGenerators.values,
+ "someid",
+ insert_values,
+ {
+ "someid_0_0": insert_values[0][0],
+ "someid_0_1": insert_values[0][1],
+ "someid_1_0": insert_values[1][0],
+ "someid_1_1": insert_values[1][1],
+ },
+ ),
+ ],
+ )
+
+ @staticmethod
+ @pytest.mark.parametrize(*test_query_data)
+ def test_query(template_function, column_name, column_values, expected_query):
+ query, _ = template_function(column_name, column_values)
+ assert query == expected_query
+
+ @staticmethod
+ @pytest.mark.parametrize(*test_params_data)
+ def test_params(template_function, column_name, column_values, expected_params):
+ _, params = template_function(column_name, column_values)
+ assert params == expected_params
+
+ @staticmethod
+ def test_insert_none():
+ with pytest.raises(ListTemplateException):
+ TemplateGenerators.values("someid", None)
diff --git a/dysql/test/test_test_managers.py b/dysql/test/test_test_managers.py
new file mode 100644
--- /dev/null
+++ b/dysql/test/test_test_managers.py
@@ -0,0 +1,76 @@
+"""
+Copyright 2026 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import pytest
+from unittest.mock import patch
+
+from dysql.test_managers import MariaDbTestManager
+
+
+class TestMariaDbTestManager:
+ """
+ Tests for MariaDbTestManager
+ """
+
+ @patch.object(MariaDbTestManager, "_run")
+ def test_create_test_db_without_schema(self, mock_run):
+ """Test that _create_test_db works without a schema_db_name"""
+ manager = MariaDbTestManager(db_name="test_db")
+ manager._create_test_db()
+
+ # Should have called _run twice (DROP and CREATE)
+ assert mock_run.call_count == 2
+
+ # Verify DROP command
+ drop_call = mock_run.call_args_list[0]
+ assert "DROP DATABASE IF EXISTS test_db" in drop_call[0][0]
+
+ # Verify CREATE command
+ create_call = mock_run.call_args_list[1]
+ assert "CREATE DATABASE IF NOT EXISTS test_db" in create_call[0][0]
+
+ @patch.object(MariaDbTestManager, "_run")
+ @pytest.mark.parametrize("command", ["--no-data", "--routines", "source_db"])
+ def test_create_test_includes_commands(self, mock_run, command):
+ """Test that _create_test_db includes --routines flag when copying schema"""
+ manager = MariaDbTestManager(db_name="test_db", schema_db_name="source_db")
+ manager._create_test_db()
+
+ # Should have called _run three times (DROP, CREATE, and mysqldump)
+ assert mock_run.call_count == 3
+
+ # Verify mysqldump command includes command
+ mysqldump_call = mock_run.call_args_list[2]
+ mysqldump_command = mysqldump_call[0][0]
+
+ assert "mariadb-dump" in mysqldump_command
+ assert command in mysqldump_command
+
+ @patch.object(MariaDbTestManager, "_run")
+ def test_create_test_db_mysqldump_command_format(self, mock_run):
+ """Test the exact format of the mysqldump command"""
+ manager = MariaDbTestManager(db_name="test_db", schema_db_name="source_db")
+ manager._create_test_db()
+
+ mysqldump_call = mock_run.call_args_list[2]
+ mysqldump_command = mysqldump_call[0][0]
+
+ # Verify the command has the correct structure
+ # mysqldump --no-data --routines -p{password} {schema_db_name} -h{host} | mariadb ...
+ assert "| mariadb" in mysqldump_command
+ assert "test_db" in mysqldump_command
+
+ @patch.object(MariaDbTestManager, "_run")
+ def test_tear_down_test_db(self, mock_run):
+ """Test that _tear_down_test_db drops the database"""
+ manager = MariaDbTestManager(db_name="test_db")
+ manager._tear_down_test_db()
+
+ assert mock_run.call_count == 1
+ drop_call = mock_run.call_args_list[0]
+ assert "DROP DATABASE IF EXISTS test_db" in drop_call[0][0]
diff --git a/dysql/test_managers.py b/dysql/test_managers.py
new file mode 100644
--- /dev/null
+++ b/dysql/test_managers.py
@@ -0,0 +1,236 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+import abc
+import logging
+import os
+import subprocess
+from time import sleep
+from typing import Optional
+
+from .connections import sqlquery
+from .databases import (
+ is_set_current_database_supported,
+ set_current_database,
+ set_default_connection_parameters,
+)
+from .mappers import CountMapper
+from .query_utils import QueryData
+
+LOGGER = logging.getLogger(__name__)
+
+
+class DbTestManagerBase(abc.ABC):
+ """
+ Base class for all test managers. See individual implementations for usage details.
+ """
+
+ # pylint: disable=too-many-instance-attributes
+
+ def __init__(
+ self,
+ host: str,
+ username: str,
+ password: str,
+ db_name: str,
+ schema_db_name: Optional[str],
+ docker_container: Optional[str] = None,
+ keep_db: bool = False,
+ **connection_defaults,
+ ): # pylint: disable=too-many-arguments
+ """
+ Constructor, any unknown kwargs are passed directly to set_default_connection_parameters.
+
+ :param host: the host to access the test database
+ :param username: the username to access the test database
+ :param password: the password to access the test database
+ :param db_name: the name of the test database
+ :param schema_db_name: the name of the DB to duplicate schema from (using mariadb-dump)
+ :param docker_container: the name of the docker container where the database is running (if in docker)
+ :param keep_db: This prevents teardown from removing the created database after running tests
+ which can be helpful in debugging
+ """
+ self.host = host
+ self.username = username
+ self.password = password
+ self.db_name = db_name
+ self.schema_db_name = schema_db_name
+ self.docker_container = docker_container
+ self.keep_db = keep_db
+ self.connection_defaults = connection_defaults
+ self.in_docker = self._is_running_in_docker()
+
+ @staticmethod
+ def _is_running_in_docker():
+ if os.path.exists("/.dockerenv"):
+ return True
+
+ if os.path.exists("/proc/1/cgroup"):
+ with open("/proc/1/cgroup", "rt", encoding="utf8") as fobj:
+ contents = fobj.read()
+ for marker in ("docker", "kubepod", "lxc"):
+ if marker in contents:
+ return True
+ return False
+
+ def __enter__(self):
+ LOGGER.debug(f"Setting up database : {self.db_name}")
+ # Set the host based on whether we are in buildrunner or not (to test locally)
+
+ self._create_test_db()
+ set_default_connection_parameters(
+ self.host,
+ self.username,
+ self.password,
+ self.db_name,
+ **self.connection_defaults,
+ )
+
+ # Set the database if supported by the python runtime
+ if is_set_current_database_supported():
+ set_current_database(self.db_name)
+
+ if self.schema_db_name:
+ self._wait_for_tables_exist()
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if not self.keep_db:
+ LOGGER.debug(f"Tearing down database : {self.db_name}")
+ self._tear_down_test_db()
+
+ @abc.abstractmethod
+ def _create_test_db(self) -> None:
+ """
+ Must be overridden in implementing classes. Creates the test database from the self.schema_db_name
+ database (if present) or an empty database desired.
+ """
+
+ @abc.abstractmethod
+ def _get_tables_count(self, db_name: str) -> int:
+ """
+ Must be overridden in implementing classes. Retrieves the current table count for the database.
+ :param db_name: the database to retrieve the count for
+ :return: the number of tables present in the database
+ """
+
+ @abc.abstractmethod
+ def _tear_down_test_db(self) -> None:
+ """
+ Must be overridden in implementing classes. Tears down the test database.
+ """
+
+ def _wait_for_tables_exist(self) -> None:
+ """
+ Waits for the tables to exist in the new test database.
+ """
+ tables_exist = False
+ expected_count = self._get_tables_count(self.schema_db_name)
+ while not tables_exist:
+ sleep(0.25)
+ LOGGER.debug("Tables are still not ready")
+ actual_count = self._get_tables_count(self.db_name)
+ tables_exist = expected_count == actual_count
+
+ def _run(self, command: str) -> subprocess.CompletedProcess:
+ """
+ Runs a command, wrapping the command in docker commands if necessary.
+ :param command: the command to run
+ :return: the completed process information
+ """
+ if not self.in_docker:
+ command = f"docker exec {self.docker_container} bash -c '{command}'"
+
+ try:
+ LOGGER.debug(f"Executing : '{command}'")
+ completed_process = subprocess.run(
+ command, shell=True, timeout=30, check=True, capture_output=True
+ )
+ LOGGER.debug(f"Executed : {completed_process.stdout}")
+
+ return completed_process
+ except subprocess.CalledProcessError:
+ LOGGER.exception(f"Error handling command : {command}")
+ raise
+
+
+class MariaDbTestManager(DbTestManagerBase):
+ """
+ May be used in testing to copy and create a database and schema. This class works specifically with
+ Maria/MySQL databases.
+
+ Example:
+
+ @pytest.fixture(scope='module', autouse=True)
+ def setup_db(self):
+ # Pass in the database name and any optional params
+ with MariaDbTestManager(f'testdb_{self.__class__.__name__.lower()}'):
+ yield
+ """
+
+ # pylint: disable=too-few-public-methods
+
+ def __init__(
+ self,
+ db_name: str,
+ schema_db_name: Optional[str] = None,
+ echo_queries: bool = False,
+ keep_db: bool = False,
+ pool_size=3,
+ charset="utf8",
+ ): # pylint: disable=too-many-arguments
+ """
+ :param db_name: the name you want for your test database
+ :param schema_db_name: the name of the DB to duplicate schema from (using mariadb-dump)
+ :param echo_queries: True if you want to see queries
+ :param keep_db: This prevents teardown from removing the created DB after running tests
+ which can be helpful in debugging
+ :param charset: This allows you to override the default charset if you need something besides utf8
+ """
+ super().__init__(
+ os.getenv("MARIA_HOST", "localhost"),
+ os.getenv("MARIA_USERNAME", "root"),
+ os.getenv("MARIA_PASSWORD", "password"),
+ db_name,
+ schema_db_name,
+ port=3306,
+ echo_queries=echo_queries,
+ pool_size=pool_size,
+ docker_container=os.getenv("MARIA_CONTAINER_NAME", "mariadb"),
+ keep_db=keep_db,
+ charset=charset,
+ )
+
+ def _create_test_db(self) -> None:
+ self._run(
+ f'mariadb -p{self.password} -h{self.host} -N -e "DROP DATABASE IF EXISTS {self.db_name}"'
+ )
+ self._run(
+ f'mariadb -p{self.password} -h{self.host} -s -N -e "CREATE DATABASE IF NOT EXISTS {self.db_name}"'
+ )
+ if self.schema_db_name:
+ self._run(
+ f"mariadb-dump --no-data --routines -p{self.password} {self.schema_db_name} -h{self.host} "
+ f"| mariadb -p{self.password} {self.db_name} -h{self.host}"
+ )
+
+ def _tear_down_test_db(self) -> None:
+ self._run(
+ f'echo "DROP DATABASE IF EXISTS {self.db_name} " | mariadb -p{self.password} -h{self.host}'
+ )
+
+ @sqlquery(mapper=CountMapper())
+ def _get_tables_count(self, db_name: str) -> int:
+ # pylint: disable=unused-argument
+ return QueryData(
+ """
+ SELECT count(1)
+ FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA=:db_name
+ """,
+ query_params={"db_name": db_name},
+ )
|