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
|
from __future__ import annotations
import contextlib
import inspect
import json
import operator
import pickle
import re
import time
import warnings
from typing import TYPE_CHECKING, Any, Literal, get_args
import numpy as np
import pytest
from numcodecs import Blosc
import zarr
import zarr.api.asynchronous
import zarr.api.synchronous
import zarr.storage
from zarr import Array, AsyncArray, AsyncGroup, Group
from zarr.abc.store import Store
from zarr.core import sync_group
from zarr.core._info import GroupInfo
from zarr.core.buffer import default_buffer_prototype
from zarr.core.config import config as zarr_config
from zarr.core.dtype.common import unpack_dtype_json
from zarr.core.dtype.npy.int import UInt8
from zarr.core.group import (
ConsolidatedMetadata,
GroupMetadata,
ImplicitGroupMarker,
_build_metadata_v3,
_get_roots,
_parse_hierarchy_dict,
create_hierarchy,
create_nodes,
create_rooted_hierarchy,
get_node,
)
from zarr.core.metadata.v3 import ArrayV3Metadata
from zarr.core.sync import _collect_aiterator, sync
from zarr.errors import (
ContainsArrayError,
ContainsGroupError,
MetadataValidationError,
ZarrDeprecationWarning,
ZarrUserWarning,
)
from zarr.storage import LocalStore, MemoryStore, StorePath, ZipStore
from zarr.storage._common import make_store_path
from zarr.storage._utils import _join_paths, normalize_path
from zarr.testing.store import LatencyStore
from .conftest import meta_from_array, parse_store
if TYPE_CHECKING:
from collections.abc import Callable
from _pytest.compat import LEGACY_PATH
from zarr.core.buffer.core import Buffer
from zarr.core.common import JSON, ZarrFormat
@pytest.fixture(params=["local", "memory", "zip"])
async def store(request: pytest.FixtureRequest, tmpdir: LEGACY_PATH) -> Store:
result = await parse_store(request.param, str(tmpdir))
if not isinstance(result, Store):
raise TypeError("Wrong store class returned by test fixture! got " + result + " instead")
return result
@pytest.fixture(params=[True, False])
def overwrite(request: pytest.FixtureRequest) -> bool:
result = request.param
if not isinstance(result, bool):
raise TypeError("Wrong type returned by test fixture.")
return result
def test_group_init(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test that initializing a group from an asyncgroup works.
"""
agroup = sync(AsyncGroup.from_store(store=store, zarr_format=zarr_format))
group = Group(agroup)
assert group._async_group == agroup
async def test_create_creates_parents(store: Store, zarr_format: ZarrFormat) -> None:
# prepare a root node, with some data set
await zarr.api.asynchronous.open_group(
store=store, path="a", zarr_format=zarr_format, attributes={"key": "value"}
)
objs = {x async for x in store.list()}
if zarr_format == 2:
assert objs == {".zgroup", ".zattrs", "a/.zgroup", "a/.zattrs"}
else:
assert objs == {"zarr.json", "a/zarr.json"}
# test that root group node was created
root = await zarr.api.asynchronous.open_group(
store=store,
)
agroup = await root.getitem("a")
assert agroup.attrs == {"key": "value"}
# create a child node with a couple intermediates
await zarr.api.asynchronous.open_group(store=store, path="a/b/c/d", zarr_format=zarr_format)
parts = ["a", "a/b", "a/b/c"]
if zarr_format == 2:
files = [".zattrs", ".zgroup"]
else:
files = ["zarr.json"]
expected = [f"{part}/{file}" for file in files for part in parts]
if zarr_format == 2:
expected.extend([".zgroup", ".zattrs", "a/b/c/d/.zgroup", "a/b/c/d/.zattrs"])
else:
expected.extend(["zarr.json", "a/b/c/d/zarr.json"])
expected = sorted(expected)
result = sorted([x async for x in store.list_prefix("")])
assert result == expected
paths = ["a", "a/b", "a/b/c"]
for path in paths:
g = await zarr.api.asynchronous.open_group(store=store, path=path)
assert isinstance(g, AsyncGroup)
if path == "a":
# ensure we didn't overwrite the root attributes
assert g.attrs == {"key": "value"}
else:
assert g.attrs == {}
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("root_name", ["", "/", "a", "/a"])
@pytest.mark.parametrize("branch_name", ["foo", "/foo", "foo/bar", "/foo/bar"])
def test_group_name_properties(
store: Store, zarr_format: ZarrFormat, root_name: str, branch_name: str
) -> None:
"""
Test that the path, name, and basename attributes of a group and its subgroups are consistent
"""
root = Group.from_store(store=StorePath(store=store, path=root_name), zarr_format=zarr_format)
assert root.path == normalize_path(root_name)
assert root.name == "/" + root.path
assert root.basename == root.path
branch = root.create_group(branch_name)
if root.path == "":
assert branch.path == normalize_path(branch_name)
else:
assert branch.path == "/".join([root.path, normalize_path(branch_name)])
assert branch.name == "/" + branch.path
assert branch.basename == branch_name.split("/")[-1]
@pytest.mark.parametrize("consolidated_metadata", [True, False])
def test_group_members(store: Store, zarr_format: ZarrFormat, consolidated_metadata: bool) -> None:
"""
Test that `Group.members` returns correct values, i.e. the arrays and groups
(explicit and implicit) contained in that group.
"""
# group/
# subgroup/
# subsubgroup/
# subsubsubgroup
# subarray
path = "group"
group = Group.from_store(
store=store,
zarr_format=zarr_format,
)
members_expected: dict[str, Array | Group] = {}
members_expected["subgroup"] = group.create_group("subgroup")
# make a sub-sub-subgroup, to ensure that the children calculation doesn't go
# too deep in the hierarchy
subsubgroup = members_expected["subgroup"].create_group("subsubgroup")
subsubsubgroup = subsubgroup.create_group("subsubsubgroup")
members_expected["subarray"] = group.create_array(
"subarray", shape=(100,), dtype="uint8", chunks=(10,), overwrite=True
)
# add an extra object to the domain of the group.
# the list of children should ignore this object.
sync(
store.set(
f"{path}/extra_object-1",
default_buffer_prototype().buffer.from_bytes(b"000000"),
)
)
# add an extra object under a directory-like prefix in the domain of the group.
# this creates a directory with a random key in it
# this should not show up as a member
sync(
store.set(
f"{path}/extra_directory/extra_object-2",
default_buffer_prototype().buffer.from_bytes(b"000000"),
)
)
# this warning shows up when extra objects show up in the hierarchy
warn_context = pytest.warns(
ZarrUserWarning,
match=r"(?:Object at .* is not recognized as a component of a Zarr hierarchy.)|(?:Consolidated metadata is currently not part in the Zarr format 3 specification.)",
)
if consolidated_metadata:
if isinstance(store, ZipStore):
with warn_context:
with pytest.warns(UserWarning, match="Duplicate name: "):
zarr.consolidate_metadata(store=store, zarr_format=zarr_format)
else:
with warn_context:
zarr.consolidate_metadata(store=store, zarr_format=zarr_format)
# now that we've consolidated the store, we shouldn't get the warnings from the unrecognized objects anymore
# we use a nullcontext to handle these cases
warn_context = contextlib.nullcontext()
group = zarr.open_consolidated(store=store, zarr_format=zarr_format)
with warn_context:
members_observed = group.members()
# members are not guaranteed to be ordered, so sort before comparing
assert sorted(dict(members_observed)) == sorted(members_expected)
# partial
with warn_context:
members_observed = group.members(max_depth=1)
members_expected["subgroup/subsubgroup"] = subsubgroup
# members are not guaranteed to be ordered, so sort before comparing
assert sorted(dict(members_observed)) == sorted(members_expected)
# total
with warn_context:
members_observed = group.members(max_depth=None)
members_expected["subgroup/subsubgroup/subsubsubgroup"] = subsubsubgroup
# members are not guaranteed to be ordered, so sort before comparing
assert sorted(dict(members_observed)) == sorted(members_expected)
with pytest.raises(ValueError, match="max_depth"):
members_observed = group.members(max_depth=-1)
def test_group(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test basic Group routines.
"""
store_path = StorePath(store)
agroup = AsyncGroup(metadata=GroupMetadata(zarr_format=zarr_format), store_path=store_path)
group = Group(agroup)
assert agroup.metadata is group.metadata
assert agroup.store_path == group.store_path == store_path
# create two groups
foo = group.create_group("foo")
bar = foo.create_group("bar", attributes={"baz": "qux"})
# create an array from the "bar" group
data = np.arange(0, 4 * 4, dtype="uint16").reshape((4, 4))
arr = bar.create_array("baz", shape=data.shape, dtype=data.dtype, chunks=(2, 2), overwrite=True)
arr[:] = data
# check the array
assert arr == bar["baz"]
assert arr.shape == data.shape
assert arr.dtype == data.dtype
# TODO: update this once the array api settles down
assert arr.chunks == (2, 2)
bar2 = foo["bar"]
assert dict(bar2.attrs) == {"baz": "qux"}
# update a group's attributes
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
bar2.attrs.update({"name": "bar"})
else:
bar2.attrs.update({"name": "bar"})
# bar.attrs was modified in-place
assert dict(bar2.attrs) == {"baz": "qux", "name": "bar"}
# and the attrs were modified in the store
bar3 = foo["bar"]
assert dict(bar3.attrs) == {"baz": "qux", "name": "bar"}
def test_group_create(store: Store, overwrite: bool, zarr_format: ZarrFormat) -> None:
"""
Test that `Group.from_store` works as expected.
"""
attributes = {"foo": 100}
group = Group.from_store(
store, attributes=attributes, zarr_format=zarr_format, overwrite=overwrite
)
assert group.attrs == attributes
if not overwrite:
with pytest.raises(ContainsGroupError):
_ = Group.from_store(store, overwrite=overwrite, zarr_format=zarr_format)
def test_group_open(store: Store, zarr_format: ZarrFormat, overwrite: bool) -> None:
"""
Test the `Group.open` method.
"""
spath = StorePath(store)
# attempt to open a group that does not exist
with pytest.raises(FileNotFoundError):
Group.open(store)
# create the group
attrs = {"path": "foo"}
group_created = Group.from_store(
store, attributes=attrs, zarr_format=zarr_format, overwrite=overwrite
)
assert group_created.attrs == attrs
assert group_created.metadata.zarr_format == zarr_format
assert group_created.store_path == spath
# attempt to create a new group in place, to test overwrite
new_attrs = {"path": "bar"}
if not overwrite:
with pytest.raises(ContainsGroupError):
Group.from_store(store, attributes=attrs, zarr_format=zarr_format, overwrite=overwrite)
else:
if not store.supports_deletes:
pytest.skip(
"Store does not support deletes but `overwrite` is True, requiring deletes to override a group"
)
group_created_again = Group.from_store(
store, attributes=new_attrs, zarr_format=zarr_format, overwrite=overwrite
)
assert group_created_again.attrs == new_attrs
assert group_created_again.metadata.zarr_format == zarr_format
assert group_created_again.store_path == spath
@pytest.mark.parametrize("consolidated", [True, False])
def test_group_getitem(store: Store, zarr_format: ZarrFormat, consolidated: bool) -> None:
"""
Test the `Group.__getitem__` method.
"""
group = Group.from_store(store, zarr_format=zarr_format)
subgroup = group.create_group(name="subgroup")
subarray = group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8")
subsubarray = subgroup.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8")
if consolidated:
if zarr_format == 3:
with pytest.warns( # noqa: PT031
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
group = zarr.api.synchronous.consolidate_metadata(
store=store, zarr_format=zarr_format
)
else:
group = zarr.api.synchronous.consolidate_metadata(
store=store, zarr_format=zarr_format
)
else:
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
group = zarr.api.synchronous.consolidate_metadata(
store=store, zarr_format=zarr_format
)
else:
group = zarr.api.synchronous.consolidate_metadata(
store=store, zarr_format=zarr_format
)
# we're going to assume that `group.metadata` is correct, and reuse that to focus
# on indexing in this test. Other tests verify the correctness of group.metadata
object.__setattr__(
subgroup.metadata,
"consolidated_metadata",
ConsolidatedMetadata(
metadata={"subarray": group.metadata.consolidated_metadata.metadata["subarray"]}
),
)
assert group["subgroup"] == subgroup
assert group["subarray"] == subarray
assert group["subgroup"]["subarray"] == subsubarray
assert group["subgroup/subarray"] == subsubarray
with pytest.raises(KeyError):
group["nope"]
with pytest.raises(KeyError, match="subarray/subsubarray"):
group["subarray/subsubarray"]
# Now test the mixed case
if consolidated:
object.__setattr__(
group.metadata.consolidated_metadata.metadata["subgroup"],
"consolidated_metadata",
None,
)
# test the implementation directly
with pytest.raises(KeyError):
group._async_group._getitem_consolidated(
group.store_path, "subgroup/subarray", prefix="/"
)
with pytest.raises(KeyError):
# We've chosen to trust the consolidated metadata, which doesn't
# contain this array
group["subgroup/subarray"]
with pytest.raises(KeyError, match="subarray/subsubarray"):
group["subarray/subsubarray"]
def test_group_get_with_default(store: Store, zarr_format: ZarrFormat) -> None:
group = Group.from_store(store, zarr_format=zarr_format)
# default behavior
result = group.get("subgroup")
assert result is None
# custom default
result = group.get("subgroup", 8)
assert result == 8
# now with a group
subgroup = group.require_group("subgroup")
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
subgroup.attrs["foo"] = "bar"
else:
subgroup.attrs["foo"] = "bar"
result = group.get("subgroup", 8)
assert result.attrs["foo"] == "bar"
@pytest.mark.parametrize("consolidated", [True, False])
def test_group_delitem(store: Store, zarr_format: ZarrFormat, consolidated: bool) -> None:
"""
Test the `Group.__delitem__` method.
"""
if not store.supports_deletes:
pytest.skip("store does not support deletes")
group = Group.from_store(store, zarr_format=zarr_format)
subgroup = group.create_group(name="subgroup")
subarray = group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8")
if consolidated:
if zarr_format == 3:
with pytest.warns( # noqa: PT031
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
group = zarr.api.synchronous.consolidate_metadata(
store=store, zarr_format=zarr_format
)
else:
group = zarr.api.synchronous.consolidate_metadata(
store=store, zarr_format=zarr_format
)
else:
group = zarr.api.synchronous.consolidate_metadata(store=store, zarr_format=zarr_format)
object.__setattr__(
subgroup.metadata, "consolidated_metadata", ConsolidatedMetadata(metadata={})
)
assert group["subgroup"] == subgroup
assert group["subarray"] == subarray
del group["subgroup"]
with pytest.raises(KeyError):
group["subgroup"]
del group["subarray"]
with pytest.raises(KeyError):
group["subarray"]
def test_group_iter(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test the `Group.__iter__` method.
"""
group = Group.from_store(store, zarr_format=zarr_format)
assert list(group) == []
def test_group_len(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test the `Group.__len__` method.
"""
group = Group.from_store(store, zarr_format=zarr_format)
assert len(group) == 0
def test_group_setitem(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test the `Group.__setitem__` method.
"""
group = Group.from_store(store, zarr_format=zarr_format)
arr = np.ones((2, 4))
group["key"] = arr
assert list(group.array_keys()) == ["key"]
assert group["key"].shape == (2, 4)
np.testing.assert_array_equal(group["key"][:], arr)
if store.supports_deletes:
key = "key"
else:
# overwriting with another array requires deletes
# for stores that don't support this, we just use a new key
key = "key2"
# overwrite with another array
arr = np.zeros((3, 5))
group[key] = arr
assert key in list(group.array_keys())
assert group[key].shape == (3, 5)
np.testing.assert_array_equal(group[key], arr)
def test_group_contains(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test the `Group.__contains__` method
"""
group = Group.from_store(store, zarr_format=zarr_format)
assert "foo" not in group
_ = group.create_group(name="foo")
assert "foo" in group
@pytest.mark.parametrize("consolidate", [True, False])
def test_group_child_iterators(store: Store, zarr_format: ZarrFormat, consolidate: bool):
group = Group.from_store(store, zarr_format=zarr_format)
expected_group_keys = ["g0", "g1"]
expected_group_values = [group.create_group(name=name) for name in expected_group_keys]
expected_groups = list(zip(expected_group_keys, expected_group_values, strict=False))
fill_value = 3
dtype = UInt8()
expected_group_values[0].create_group("subgroup")
expected_group_values[0].create_array(
"subarray", shape=(1,), dtype=dtype, fill_value=fill_value
)
expected_array_keys = ["a0", "a1"]
expected_array_values = [
group.create_array(name=name, shape=(1,), dtype=dtype, fill_value=fill_value)
for name in expected_array_keys
]
expected_arrays = list(zip(expected_array_keys, expected_array_values, strict=False))
if consolidate:
if zarr_format == 3:
with pytest.warns( # noqa: PT031
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
group = zarr.consolidate_metadata(store)
else:
group = zarr.consolidate_metadata(store)
else:
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
group = zarr.consolidate_metadata(store)
else:
group = zarr.consolidate_metadata(store)
if zarr_format == 2:
metadata = {
"subarray": {
"attributes": {},
"dtype": unpack_dtype_json(dtype.to_json(zarr_format=zarr_format)),
"fill_value": fill_value,
"shape": (1,),
"chunks": (1,),
"order": "C",
"filters": None,
"compressor": Blosc(),
"zarr_format": zarr_format,
},
"subgroup": {
"attributes": {},
"consolidated_metadata": {
"metadata": {},
"kind": "inline",
"must_understand": False,
},
"node_type": "group",
"zarr_format": zarr_format,
},
}
else:
metadata = {
"subarray": {
"attributes": {},
"chunk_grid": {
"configuration": {"chunk_shape": (1,)},
"name": "regular",
},
"chunk_key_encoding": {
"configuration": {"separator": "/"},
"name": "default",
},
"codecs": (
{"configuration": {"endian": "little"}, "name": "bytes"},
{"configuration": {}, "name": "zstd"},
),
"data_type": unpack_dtype_json(dtype.to_json(zarr_format=zarr_format)),
"fill_value": fill_value,
"node_type": "array",
"shape": (1,),
"zarr_format": zarr_format,
},
"subgroup": {
"attributes": {},
"consolidated_metadata": {
"metadata": {},
"kind": "inline",
"must_understand": False,
},
"node_type": "group",
"zarr_format": zarr_format,
},
}
object.__setattr__(
expected_group_values[0].metadata,
"consolidated_metadata",
ConsolidatedMetadata.from_dict(
{
"kind": "inline",
"metadata": metadata,
"must_understand": False,
}
),
)
object.__setattr__(
expected_group_values[1].metadata,
"consolidated_metadata",
ConsolidatedMetadata(metadata={}),
)
result = sorted(group.groups(), key=operator.itemgetter(0))
assert result == expected_groups
assert sorted(group.groups(), key=operator.itemgetter(0)) == expected_groups
assert sorted(group.group_keys()) == expected_group_keys
assert sorted(group.group_values(), key=lambda x: x.name) == expected_group_values
assert sorted(group.arrays(), key=operator.itemgetter(0)) == expected_arrays
assert sorted(group.array_keys()) == expected_array_keys
assert sorted(group.array_values(), key=lambda x: x.name) == expected_array_values
def test_group_update_attributes(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test the behavior of `Group.update_attributes`
"""
attrs = {"foo": 100}
group = Group.from_store(store, zarr_format=zarr_format, attributes=attrs)
assert group.attrs == attrs
new_attrs = {"bar": 100}
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
new_group = group.update_attributes(new_attrs)
else:
new_group = group.update_attributes(new_attrs)
updated_attrs = attrs.copy()
updated_attrs.update(new_attrs)
assert new_group.attrs == updated_attrs
async def test_group_update_attributes_async(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test the behavior of `Group.update_attributes_async`
"""
attrs = {"foo": 100}
group = Group.from_store(store, zarr_format=zarr_format, attributes=attrs)
assert group.attrs == attrs
new_attrs = {"bar": 100}
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name: "):
new_group = await group.update_attributes_async(new_attrs)
else:
new_group = await group.update_attributes_async(new_attrs)
assert new_group.attrs == new_attrs
@pytest.mark.parametrize("method", ["create_array", "array"])
@pytest.mark.parametrize("name", ["a", "/a"])
def test_group_create_array(
store: Store,
zarr_format: ZarrFormat,
overwrite: bool,
method: Literal["create_array", "array"],
name: str,
) -> None:
"""
Test `Group.from_store`
"""
group = Group.from_store(store, zarr_format=zarr_format)
shape = (10, 10)
dtype = "uint8"
data = np.arange(np.prod(shape)).reshape(shape).astype(dtype)
if method == "create_array":
array = group.create_array(name=name, shape=shape, dtype=dtype)
array[:] = data
elif method == "array":
with pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."):
with pytest.warns(
ZarrUserWarning,
match="The `compressor` argument is deprecated. Use `compressors` instead.",
):
array = group.array(name=name, data=data, shape=shape, dtype=dtype)
else:
raise AssertionError
if not overwrite:
if method == "create_array":
with pytest.raises(ContainsArrayError): # noqa: PT012
a = group.create_array(name=name, shape=shape, dtype=dtype)
a[:] = data
elif method == "array":
with pytest.raises(ContainsArrayError): # noqa: PT012
with pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."):
with pytest.warns(
ZarrUserWarning,
match="The `compressor` argument is deprecated. Use `compressors` instead.",
):
a = group.array(name=name, shape=shape, dtype=dtype)
a[:] = data
assert array.path == normalize_path(name)
assert array.name == "/" + array.path
assert array.shape == shape
assert array.dtype == np.dtype(dtype)
assert np.array_equal(array[:], data)
@pytest.mark.parametrize("method", ["create_array", "create_group"])
def test_create_with_parent_array(store: Store, zarr_format: ZarrFormat, method: str):
"""Test that groups/arrays cannot be created under a parent array."""
# create a group with a child array
group = Group.from_store(store, zarr_format=zarr_format)
group.create_array(name="arr_1", shape=(10, 10), dtype="uint8")
error_msg = r"A parent of .* is an array - only groups may have child nodes."
if method == "create_array":
with pytest.raises(ValueError, match=error_msg):
group.create_array("arr_1/group_1/group_2/arr_2", shape=(10, 10), dtype="uint8")
else:
with pytest.raises(ValueError, match=error_msg):
group.create_group("arr_1/group_1/group_2/group_3")
LikeMethodName = Literal["zeros_like", "ones_like", "empty_like", "full_like"]
@pytest.mark.parametrize("method_name", get_args(LikeMethodName))
@pytest.mark.parametrize("out_shape", ["keep", (10, 10)])
@pytest.mark.parametrize("out_chunks", ["keep", (10, 10)])
@pytest.mark.parametrize("out_dtype", ["keep", "int8"])
def test_group_array_like_creation(
zarr_format: ZarrFormat,
method_name: LikeMethodName,
out_shape: Literal["keep"] | tuple[int, ...],
out_chunks: Literal["keep"] | tuple[int, ...],
out_dtype: str,
) -> None:
"""
Test Group.{zeros_like, ones_like, empty_like, full_like}, ensuring that we can override the
shape, chunks, and dtype of the array-like object provided to these functions with
appropriate keyword arguments
"""
ref_arr = zarr.ones(store={}, shape=(11, 12), dtype="uint8", chunks=(11, 12))
group = Group.from_store({}, zarr_format=zarr_format)
kwargs = {}
if method_name == "full_like":
expect_fill = 4
kwargs["fill_value"] = expect_fill
meth = group.full_like
elif method_name == "zeros_like":
expect_fill = 0
meth = group.zeros_like
elif method_name == "ones_like":
expect_fill = 1
meth = group.ones_like
elif method_name == "empty_like":
expect_fill = ref_arr.fill_value
meth = group.empty_like
else:
raise AssertionError
if out_shape != "keep":
kwargs["shape"] = out_shape
expect_shape = out_shape
else:
expect_shape = ref_arr.shape
if out_chunks != "keep":
kwargs["chunks"] = out_chunks
expect_chunks = out_chunks
else:
expect_chunks = ref_arr.chunks
if out_dtype != "keep":
kwargs["dtype"] = out_dtype
expect_dtype = out_dtype
else:
expect_dtype = ref_arr.dtype
new_arr = meth(name="foo", data=ref_arr, **kwargs)
assert new_arr.shape == expect_shape
assert new_arr.chunks == expect_chunks
assert new_arr.dtype == expect_dtype
assert np.all(new_arr[:] == expect_fill)
def test_group_array_creation(
store: Store,
zarr_format: ZarrFormat,
):
group = Group.from_store(store, zarr_format=zarr_format)
shape = (10, 10)
empty_array = group.empty(name="empty", shape=shape)
assert isinstance(empty_array, Array)
assert empty_array.fill_value == 0
assert empty_array.shape == shape
assert empty_array.store_path.store == store
assert empty_array.store_path.path == "empty"
empty_like_array = group.empty_like(name="empty_like", data=empty_array)
assert isinstance(empty_like_array, Array)
assert empty_like_array.fill_value == 0
assert empty_like_array.shape == shape
assert empty_like_array.store_path.store == store
empty_array_bool = group.empty(name="empty_bool", shape=shape, dtype=np.dtype("bool"))
assert isinstance(empty_array_bool, Array)
assert not empty_array_bool.fill_value
assert empty_array_bool.shape == shape
assert empty_array_bool.store_path.store == store
empty_like_array_bool = group.empty_like(name="empty_like_bool", data=empty_array_bool)
assert isinstance(empty_like_array_bool, Array)
assert not empty_like_array_bool.fill_value
assert empty_like_array_bool.shape == shape
assert empty_like_array_bool.store_path.store == store
zeros_array = group.zeros(name="zeros", shape=shape)
assert isinstance(zeros_array, Array)
assert zeros_array.fill_value == 0
assert zeros_array.shape == shape
assert zeros_array.store_path.store == store
zeros_like_array = group.zeros_like(name="zeros_like", data=zeros_array)
assert isinstance(zeros_like_array, Array)
assert zeros_like_array.fill_value == 0
assert zeros_like_array.shape == shape
assert zeros_like_array.store_path.store == store
ones_array = group.ones(name="ones", shape=shape)
assert isinstance(ones_array, Array)
assert ones_array.fill_value == 1
assert ones_array.shape == shape
assert ones_array.store_path.store == store
ones_like_array = group.ones_like(name="ones_like", data=ones_array)
assert isinstance(ones_like_array, Array)
assert ones_like_array.fill_value == 1
assert ones_like_array.shape == shape
assert ones_like_array.store_path.store == store
full_array = group.full(name="full", shape=shape, fill_value=42)
assert isinstance(full_array, Array)
assert full_array.fill_value == 42
assert full_array.shape == shape
assert full_array.store_path.store == store
full_like_array = group.full_like(name="full_like", data=full_array, fill_value=43)
assert isinstance(full_like_array, Array)
assert full_like_array.fill_value == 43
assert full_like_array.shape == shape
assert full_like_array.store_path.store == store
@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
@pytest.mark.parametrize("overwrite", [True, False])
@pytest.mark.parametrize("extant_node", ["array", "group"])
def test_group_creation_existing_node(
store: Store,
zarr_format: ZarrFormat,
overwrite: bool,
extant_node: Literal["array", "group"],
) -> None:
"""
Check that an existing array or group is handled as expected during group creation.
"""
spath = StorePath(store)
group = Group.from_store(spath, zarr_format=zarr_format)
expected_exception: type[ContainsArrayError | ContainsGroupError]
attributes: dict[str, JSON] = {"old": True}
if extant_node == "array":
expected_exception = ContainsArrayError
_ = group.create_array("extant", shape=(10,), dtype="uint8", attributes=attributes)
elif extant_node == "group":
expected_exception = ContainsGroupError
_ = group.create_group("extant", attributes=attributes)
else:
raise AssertionError
new_attributes = {"new": True}
if overwrite:
if not store.supports_deletes:
pytest.skip("store does not support deletes but overwrite is True")
node_new = Group.from_store(
spath / "extant",
attributes=new_attributes,
zarr_format=zarr_format,
overwrite=overwrite,
)
assert node_new.attrs == new_attributes
else:
with pytest.raises(expected_exception):
node_new = Group.from_store(
spath / "extant",
attributes=new_attributes,
zarr_format=zarr_format,
overwrite=overwrite,
)
async def test_asyncgroup_create(
store: Store,
overwrite: bool,
zarr_format: ZarrFormat,
) -> None:
"""
Test that `AsyncGroup.from_store` works as expected.
"""
spath = StorePath(store=store)
attributes = {"foo": 100}
agroup = await AsyncGroup.from_store(
store,
attributes=attributes,
overwrite=overwrite,
zarr_format=zarr_format,
)
assert agroup.metadata == GroupMetadata(zarr_format=zarr_format, attributes=attributes)
assert agroup.store_path == await make_store_path(store)
if not overwrite:
with pytest.raises(ContainsGroupError):
agroup = await AsyncGroup.from_store(
spath,
attributes=attributes,
overwrite=overwrite,
zarr_format=zarr_format,
)
# create an array at our target path
collision_name = "foo"
_ = await zarr.api.asynchronous.create_array(
spath / collision_name, shape=(10,), dtype="uint8", zarr_format=zarr_format
)
with pytest.raises(ContainsArrayError):
_ = await AsyncGroup.from_store(
StorePath(store=store) / collision_name,
attributes=attributes,
overwrite=overwrite,
zarr_format=zarr_format,
)
async def test_asyncgroup_attrs(store: Store, zarr_format: ZarrFormat) -> None:
attributes = {"foo": 100}
agroup = await AsyncGroup.from_store(store, zarr_format=zarr_format, attributes=attributes)
assert agroup.attrs == agroup.metadata.attributes == attributes
async def test_asyncgroup_open(
store: Store,
zarr_format: ZarrFormat,
) -> None:
"""
Create an `AsyncGroup`, then ensure that we can open it using `AsyncGroup.open`
"""
attributes = {"foo": 100}
group_w = await AsyncGroup.from_store(
store=store,
attributes=attributes,
overwrite=False,
zarr_format=zarr_format,
)
group_r = await AsyncGroup.open(store=store, zarr_format=zarr_format)
assert group_w.attrs == group_w.attrs == attributes
assert group_w == group_r
async def test_asyncgroup_open_wrong_format(
store: Store,
zarr_format: ZarrFormat,
) -> None:
_ = await AsyncGroup.from_store(store=store, overwrite=False, zarr_format=zarr_format)
zarr_format_wrong: ZarrFormat
# try opening with the wrong zarr format
if zarr_format == 3:
zarr_format_wrong = 2
elif zarr_format == 2:
zarr_format_wrong = 3
else:
raise AssertionError
with pytest.raises(FileNotFoundError):
await AsyncGroup.open(store=store, zarr_format=zarr_format_wrong)
# todo: replace the dict[str, Any] type with something a bit more specific
# should this be async?
@pytest.mark.parametrize(
"data",
[
{"zarr_format": 3, "node_type": "group", "attributes": {"foo": 100}},
{"zarr_format": 2, "attributes": {"foo": 100}},
],
)
def test_asyncgroup_from_dict(store: Store, data: dict[str, Any]) -> None:
"""
Test that we can create an AsyncGroup from a dict
"""
path = "test"
store_path = StorePath(store=store, path=path)
group = AsyncGroup.from_dict(store_path, data=data)
assert group.metadata.zarr_format == data["zarr_format"]
assert group.metadata.attributes == data["attributes"]
# todo: replace this with a declarative API where we model a full hierarchy
async def test_asyncgroup_getitem(store: Store, zarr_format: ZarrFormat) -> None:
"""
Create an `AsyncGroup`, then create members of that group, and ensure that we can access those
members via the `AsyncGroup.getitem` method.
"""
agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
array_name = "sub_array"
sub_array = await agroup.create_array(name=array_name, shape=(10,), dtype="uint8", chunks=(2,))
assert await agroup.getitem(array_name) == sub_array
sub_group_path = "sub_group"
sub_group = await agroup.create_group(sub_group_path, attributes={"foo": 100})
assert await agroup.getitem(sub_group_path) == sub_group
# check that asking for a nonexistent key raises KeyError
with pytest.raises(KeyError):
await agroup.getitem("foo")
async def test_asyncgroup_delitem(store: Store, zarr_format: ZarrFormat) -> None:
if not store.supports_deletes:
pytest.skip("store does not support deletes")
agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
array_name = "sub_array"
_ = await agroup.create_array(
name=array_name,
shape=(10,),
dtype="uint8",
chunks=(2,),
attributes={"foo": 100},
)
await agroup.delitem(array_name)
# todo: clean up the code duplication here
if zarr_format == 2:
assert not await agroup.store_path.store.exists(array_name + "/" + ".zarray")
assert not await agroup.store_path.store.exists(array_name + "/" + ".zattrs")
elif zarr_format == 3:
assert not await agroup.store_path.store.exists(array_name + "/" + "zarr.json")
else:
raise AssertionError
sub_group_path = "sub_group"
_ = await agroup.create_group(sub_group_path, attributes={"foo": 100})
await agroup.delitem(sub_group_path)
if zarr_format == 2:
assert not await agroup.store_path.store.exists(array_name + "/" + ".zgroup")
assert not await agroup.store_path.store.exists(array_name + "/" + ".zattrs")
elif zarr_format == 3:
assert not await agroup.store_path.store.exists(array_name + "/" + "zarr.json")
else:
raise AssertionError
@pytest.mark.parametrize("name", ["a", "/a"])
async def test_asyncgroup_create_group(
store: Store,
name: str,
zarr_format: ZarrFormat,
) -> None:
agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
attributes = {"foo": 999}
subgroup = await agroup.create_group(name=name, attributes=attributes)
assert isinstance(subgroup, AsyncGroup)
assert subgroup.path == normalize_path(name)
assert subgroup.name == "/" + subgroup.path
assert subgroup.attrs == attributes
assert subgroup.store_path.path == subgroup.path
assert subgroup.store_path.store == store
assert subgroup.metadata.zarr_format == zarr_format
async def test_asyncgroup_create_array(
store: Store, zarr_format: ZarrFormat, overwrite: bool
) -> None:
"""
Test that the AsyncGroup.create_array method works correctly. We ensure that array properties
specified in create_array are present on the resulting array.
"""
agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
if not overwrite:
with pytest.raises(ContainsGroupError):
agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
shape = (10,)
dtype = "uint8"
chunk_shape = (4,)
attributes: dict[str, JSON] = {"foo": 100}
sub_node_path = "sub_array"
subnode = await agroup.create_array(
name=sub_node_path,
shape=shape,
dtype=dtype,
chunks=chunk_shape,
attributes=attributes,
)
assert isinstance(subnode, AsyncArray)
assert subnode.attrs == attributes
assert subnode.store_path.path == sub_node_path
assert subnode.store_path.store == store
assert subnode.shape == shape
assert subnode.dtype == dtype
# todo: fix the type annotation of array.metadata.chunk_grid so that we get some autocomplete
# here.
assert subnode.metadata.chunk_grid.chunk_shape == chunk_shape
assert subnode.metadata.zarr_format == zarr_format
async def test_asyncgroup_update_attributes(store: Store, zarr_format: ZarrFormat) -> None:
"""
Test that the AsyncGroup.update_attributes method works correctly.
"""
attributes_old = {"foo": 10}
attributes_new = {"baz": "new"}
agroup = await AsyncGroup.from_store(
store=store, zarr_format=zarr_format, attributes=attributes_old
)
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name"):
agroup_new_attributes = await agroup.update_attributes(attributes_new)
else:
agroup_new_attributes = await agroup.update_attributes(attributes_new)
attributes_updated = attributes_old.copy()
attributes_updated.update(attributes_new)
assert agroup_new_attributes.attrs == attributes_updated
@pytest.mark.parametrize("store", ["local"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
async def test_serializable_async_group(store: LocalStore, zarr_format: ZarrFormat) -> None:
expected = await AsyncGroup.from_store(
store=store, attributes={"foo": 999}, zarr_format=zarr_format
)
p = pickle.dumps(expected)
actual = pickle.loads(p)
assert actual == expected
@pytest.mark.parametrize("store", ["local"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
def test_serializable_sync_group(store: LocalStore, zarr_format: ZarrFormat) -> None:
expected = Group.from_store(store=store, attributes={"foo": 999}, zarr_format=zarr_format)
p = pickle.dumps(expected)
actual = pickle.loads(p)
assert actual == expected
@pytest.mark.parametrize("consolidated_metadata", [True, False])
async def test_group_members_async(store: Store, consolidated_metadata: bool) -> None:
group = await AsyncGroup.from_store(
store=store,
)
a0 = await group.create_array("a0", shape=(1,), dtype="uint8")
g0 = await group.create_group("g0")
a1 = await g0.create_array("a1", shape=(1,), dtype="uint8")
g1 = await g0.create_group("g1")
a2 = await g1.create_array("a2", shape=(1,), dtype="uint8")
g2 = await g1.create_group("g2")
# immediate children
children = sorted([x async for x in group.members()], key=operator.itemgetter(0))
assert children == [
("a0", a0),
("g0", g0),
]
nmembers = await group.nmembers()
assert nmembers == 2
# partial
children = sorted([x async for x in group.members(max_depth=1)], key=operator.itemgetter(0))
expected = [
("a0", a0),
("g0", g0),
("g0/a1", a1),
("g0/g1", g1),
]
assert children == expected
nmembers = await group.nmembers(max_depth=1)
assert nmembers == 4
# all children
all_children = sorted(
[x async for x in group.members(max_depth=None)], key=operator.itemgetter(0)
)
expected = [
("a0", a0),
("g0", g0),
("g0/a1", a1),
("g0/g1", g1),
("g0/g1/a2", a2),
("g0/g1/g2", g2),
]
assert all_children == expected
if consolidated_metadata:
with pytest.warns( # noqa: PT031
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name"):
await zarr.api.asynchronous.consolidate_metadata(store=store)
else:
await zarr.api.asynchronous.consolidate_metadata(store=store)
group = await zarr.api.asynchronous.open_group(store=store)
nmembers = await group.nmembers(max_depth=None)
assert nmembers == 6
with pytest.raises(ValueError, match="max_depth"):
[x async for x in group.members(max_depth=-1)]
if consolidated_metadata:
# test for mixed known and unknown metadata.
# For now, we trust the consolidated metadata.
object.__setattr__(
group.metadata.consolidated_metadata.metadata["g0"].consolidated_metadata.metadata[
"g1"
],
"consolidated_metadata",
None,
)
# test depth=0
nmembers = await group.nmembers(max_depth=0)
assert nmembers == 2
# test depth=1
nmembers = await group.nmembers(max_depth=1)
assert nmembers == 4
# test depth=None
all_children = sorted(
[x async for x in group.members(max_depth=None)], key=operator.itemgetter(0)
)
assert len(all_children) == 4
nmembers = await group.nmembers(max_depth=None)
assert nmembers == 4
# test depth<0
with pytest.raises(ValueError, match="max_depth"):
await group.nmembers(max_depth=-1)
async def test_require_group(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None:
root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
# create foo group
_ = await root.create_group("foo", attributes={"foo": 100})
# test that we can get the group using require_group
foo_group = await root.require_group("foo")
assert foo_group.attrs == {"foo": 100}
# test that we can get the group using require_group and overwrite=True
if store.supports_deletes:
foo_group = await root.require_group("foo", overwrite=True)
assert foo_group.attrs == {}
_ = await foo_group.create_array(
"bar", shape=(10,), dtype="uint8", chunks=(2,), attributes={"foo": 100}
)
# test that overwriting a group w/ children fails
# TODO: figure out why ensure_no_existing_node is not catching the foo.bar array
#
# with pytest.raises(ContainsArrayError):
# await root.require_group("foo", overwrite=True)
# test that requiring a group where an array is fails
with pytest.raises(TypeError):
await foo_group.require_group("bar")
async def test_require_groups(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None:
root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
# create foo group
_ = await root.create_group("foo", attributes={"foo": 100})
# create bar group
_ = await root.create_group("bar", attributes={"bar": 200})
foo_group, bar_group = await root.require_groups("foo", "bar")
assert foo_group.attrs == {"foo": 100}
assert bar_group.attrs == {"bar": 200}
# get a mix of existing and new groups
foo_group, spam_group = await root.require_groups("foo", "spam")
assert foo_group.attrs == {"foo": 100}
assert spam_group.attrs == {}
# no names
no_group = await root.require_groups()
assert no_group == ()
def test_create_dataset_with_data(store: Store, zarr_format: ZarrFormat) -> None:
"""Check that deprecated create_dataset method allows input data.
See https://github.com/zarr-developers/zarr-python/issues/2631.
"""
root = Group.from_store(store=store, zarr_format=zarr_format)
arr = np.random.random((5, 5))
with pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."):
data = root.create_dataset("random", data=arr, shape=arr.shape)
np.testing.assert_array_equal(np.asarray(data), arr)
async def test_create_dataset(store: Store, zarr_format: ZarrFormat) -> None:
root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
with pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."):
foo = await root.create_dataset("foo", shape=(10,), dtype="uint8")
assert foo.shape == (10,)
with (
pytest.raises(ContainsArrayError),
pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."),
):
await root.create_dataset("foo", shape=(100,), dtype="int8")
_ = await root.create_group("bar")
with (
pytest.raises(ContainsGroupError),
pytest.warns(ZarrDeprecationWarning, match=r"Group\.create_array instead\."),
):
await root.create_dataset("bar", shape=(100,), dtype="int8")
async def test_require_array(store: Store, zarr_format: ZarrFormat) -> None:
root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format)
foo1 = await root.require_array("foo", shape=(10,), dtype="i8", attributes={"foo": 101})
assert foo1.attrs == {"foo": 101}
foo2 = await root.require_array("foo", shape=(10,), dtype="i8")
assert foo2.attrs == {"foo": 101}
# exact = False
_ = await root.require_array("foo", shape=10, dtype="f8")
# errors w/ exact True
with pytest.raises(TypeError, match="Incompatible dtype"):
await root.require_array("foo", shape=(10,), dtype="f8", exact=True)
with pytest.raises(TypeError, match="Incompatible shape"):
await root.require_array("foo", shape=(100, 100), dtype="i8")
with pytest.raises(TypeError, match="Incompatible dtype"):
await root.require_array("foo", shape=(10,), dtype="f4")
_ = await root.create_group("bar")
with pytest.raises(TypeError, match="Incompatible object"):
await root.require_array("bar", shape=(10,), dtype="int8")
@pytest.mark.parametrize("consolidate", [True, False])
async def test_members_name(store: Store, consolidate: bool, zarr_format: ZarrFormat):
group = Group.from_store(store=store, zarr_format=zarr_format)
a = group.create_group(name="a")
a.create_array("array", shape=(1,), dtype="uint8")
b = a.create_group(name="b")
b.create_array("array", shape=(1,), dtype="uint8")
if consolidate:
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name"): # noqa: PT031
if zarr_format == 3:
with pytest.warns(
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
group = zarr.api.synchronous.consolidate_metadata(store)
else:
group = zarr.api.synchronous.consolidate_metadata(store)
else:
if zarr_format == 3:
with pytest.warns(
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
group = zarr.api.synchronous.consolidate_metadata(store)
else:
group = zarr.api.synchronous.consolidate_metadata(store)
result = group["a"]["b"]
assert result.name == "/a/b"
paths = sorted(x.name for _, x in group.members(max_depth=None))
expected = ["/a", "/a/array", "/a/b", "/a/b/array"]
assert paths == expected
# regression test for https://github.com/zarr-developers/zarr-python/pull/2356
g = zarr.open_group(store, use_consolidated=False)
with warnings.catch_warnings():
warnings.simplefilter("error")
assert list(g)
async def test_open_mutable_mapping():
group = await zarr.api.asynchronous.open_group(
store={},
)
assert isinstance(group.store_path.store, MemoryStore)
def test_open_mutable_mapping_sync():
group = zarr.open_group(
store={},
)
assert isinstance(group.store_path.store, MemoryStore)
async def test_open_ambiguous_node():
zarr_json_bytes = default_buffer_prototype().buffer.from_bytes(
json.dumps({"zarr_format": 3, "node_type": "group"}).encode("utf-8")
)
zgroup_bytes = default_buffer_prototype().buffer.from_bytes(
json.dumps({"zarr_format": 2}).encode("utf-8")
)
store: dict[str, Buffer] = {"zarr.json": zarr_json_bytes, ".zgroup": zgroup_bytes}
with pytest.warns(
ZarrUserWarning,
match=r"Both zarr\.json \(Zarr format 3\) and \.zgroup \(Zarr format 2\) metadata objects exist at",
):
await AsyncGroup.open(store, zarr_format=None)
class TestConsolidated:
async def test_group_getitem_consolidated(self, store: Store) -> None:
root = await AsyncGroup.from_store(store=store)
# Set up the test structure with
# /
# g0/ # group /g0
# g1/ # group /g0/g1
# g2/ # group /g0/g1/g2
# x1/ # group /x0
# x2/ # group /x0/x1
# x3/ # group /x0/x1/x2
g0 = await root.create_group("g0")
g1 = await g0.create_group("g1")
await g1.create_group("g2")
x0 = await root.create_group("x0")
x1 = await x0.create_group("x1")
await x1.create_group("x2")
with pytest.warns( # noqa: PT031
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name"):
await zarr.api.asynchronous.consolidate_metadata(store)
else:
await zarr.api.asynchronous.consolidate_metadata(store)
# On disk, we've consolidated all the metadata in the root zarr.json
group = await zarr.api.asynchronous.open(store=store)
rg0 = await group.getitem("g0")
expected = ConsolidatedMetadata(
metadata={
"g1": GroupMetadata(
attributes={},
zarr_format=3,
consolidated_metadata=ConsolidatedMetadata(
metadata={
"g2": GroupMetadata(
attributes={},
zarr_format=3,
consolidated_metadata=ConsolidatedMetadata(metadata={}),
)
}
),
),
}
)
assert rg0.metadata.consolidated_metadata == expected
rg1 = await rg0.getitem("g1")
assert rg1.metadata.consolidated_metadata == expected.metadata["g1"].consolidated_metadata
rg2 = await rg1.getitem("g2")
assert rg2.metadata.consolidated_metadata == ConsolidatedMetadata(metadata={})
async def test_group_delitem_consolidated(self, store: Store) -> None:
if isinstance(store, ZipStore):
raise pytest.skip("Not implemented")
root = await AsyncGroup.from_store(store=store)
# Set up the test structure with
# /
# g0/ # group /g0
# g1/ # group /g0/g1
# g2/ # group /g0/g1/g2
# data # array
# x1/ # group /x0
# x2/ # group /x0/x1
# x3/ # group /x0/x1/x2
# data # array
g0 = await root.create_group("g0")
g1 = await g0.create_group("g1")
g2 = await g1.create_group("g2")
await g2.create_array("data", shape=(1,), dtype="uint8")
x0 = await root.create_group("x0")
x1 = await x0.create_group("x1")
x2 = await x1.create_group("x2")
await x2.create_array("data", shape=(1,), dtype="uint8")
with pytest.warns( # noqa: PT031
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
if isinstance(store, ZipStore):
with pytest.warns(UserWarning, match="Duplicate name"):
await zarr.api.asynchronous.consolidate_metadata(store)
else:
await zarr.api.asynchronous.consolidate_metadata(store)
group = await zarr.api.asynchronous.open_consolidated(store=store)
assert len(group.metadata.consolidated_metadata.metadata) == 2
assert "g0" in group.metadata.consolidated_metadata.metadata
await group.delitem("g0")
assert len(group.metadata.consolidated_metadata.metadata) == 1
assert "g0" not in group.metadata.consolidated_metadata.metadata
def test_open_consolidated_raises(self, store: Store) -> None:
if isinstance(store, ZipStore):
raise pytest.skip("Not implemented")
root = Group.from_store(store=store)
# fine to be missing by default
zarr.open_group(store=store)
with pytest.raises(ValueError, match="Consolidated metadata requested."):
zarr.open_group(store=store, use_consolidated=True)
# Now create consolidated metadata...
root.create_group("g0")
with pytest.warns(
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
zarr.consolidate_metadata(store)
# and explicitly ignore it.
group = zarr.open_group(store=store, use_consolidated=False)
assert group.metadata.consolidated_metadata is None
async def test_open_consolidated_raises_async(self, store: Store) -> None:
if isinstance(store, ZipStore):
raise pytest.skip("Not implemented")
root = await AsyncGroup.from_store(store=store)
# fine to be missing by default
await zarr.api.asynchronous.open_group(store=store)
with pytest.raises(ValueError, match="Consolidated metadata requested."):
await zarr.api.asynchronous.open_group(store=store, use_consolidated=True)
# Now create consolidated metadata...
await root.create_group("g0")
with pytest.warns(
ZarrUserWarning,
match="Consolidated metadata is currently not part in the Zarr format 3 specification.",
):
await zarr.api.asynchronous.consolidate_metadata(store)
# and explicitly ignore it.
group = await zarr.api.asynchronous.open_group(store=store, use_consolidated=False)
assert group.metadata.consolidated_metadata is None
class TestGroupMetadata:
def test_from_dict_extra_fields(self):
data = {
"attributes": {"key": "value"},
"_nczarr_superblock": {"version": "2.0.0"},
"zarr_format": 2,
}
result = GroupMetadata.from_dict(data)
expected = GroupMetadata(attributes={"key": "value"}, zarr_format=2)
assert result == expected
class TestInfo:
def test_info(self):
store = zarr.storage.MemoryStore()
A = zarr.group(store=store, path="A")
B = A.create_group(name="B")
B.create_array(name="x", shape=(1,), dtype="uint8")
B.create_array(name="y", shape=(2,), dtype="uint8")
result = A.info
expected = GroupInfo(
_name="A",
_read_only=False,
_store_type="MemoryStore",
_zarr_format=3,
)
assert result == expected
result = A.info_complete()
expected = GroupInfo(
_name="A",
_read_only=False,
_store_type="MemoryStore",
_zarr_format=3,
_count_members=3,
_count_arrays=2,
_count_groups=1,
)
assert result == expected
def test_update_attrs() -> None:
# regression test for https://github.com/zarr-developers/zarr-python/issues/2328
root = Group.from_store(
MemoryStore(),
)
root.attrs["foo"] = "bar"
assert root.attrs["foo"] == "bar"
@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"])
def test_delitem_removes_children(store: Store, zarr_format: ZarrFormat) -> None:
# https://github.com/zarr-developers/zarr-python/issues/2191
g1 = zarr.group(store=store, zarr_format=zarr_format)
g1.create_group("0")
g1.create_group("0/0")
arr = g1.create_array("0/0/0", shape=(1,), dtype="uint8")
arr[:] = 1
del g1["0"]
with pytest.raises(KeyError):
g1["0/0"]
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_create_nodes(
impl: Literal["async", "sync"], store: Store, zarr_format: ZarrFormat
) -> None:
"""
Ensure that ``create_nodes`` can create a zarr hierarchy from a model of that
hierarchy in dict form. Note that this creates an incomplete Zarr hierarchy.
"""
node_spec = {
"group": GroupMetadata(attributes={"foo": 10}),
"group/array_0": meta_from_array(np.arange(3), zarr_format=zarr_format),
"group/array_1": meta_from_array(np.arange(4), zarr_format=zarr_format),
"group/subgroup/array_0": meta_from_array(np.arange(4), zarr_format=zarr_format),
"group/subgroup/array_1": meta_from_array(np.arange(5), zarr_format=zarr_format),
}
if impl == "sync":
observed_nodes = dict(sync_group.create_nodes(store=store, nodes=node_spec))
elif impl == "async":
observed_nodes = dict(await _collect_aiterator(create_nodes(store=store, nodes=node_spec)))
else:
raise ValueError(f"Invalid impl: {impl}")
assert node_spec == {k: v.metadata for k, v in observed_nodes.items()}
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_create_nodes_concurrency_limit(store: MemoryStore) -> None:
"""
Test that the execution time of create_nodes can be constrained by the async concurrency
configuration setting.
"""
set_latency = 0.02
num_groups = 10
groups = {str(idx): GroupMetadata() for idx in range(num_groups)}
latency_store = LatencyStore(store, set_latency=set_latency)
# check how long it takes to iterate over the groups
# if create_nodes is sensitive to IO latency,
# this should take (num_groups * get_latency) seconds
# otherwise, it should take only marginally more than get_latency seconds
with zarr_config.set({"async.concurrency": 1}):
start = time.time()
_ = tuple(sync_group.create_nodes(store=latency_store, nodes=groups))
elapsed = time.time() - start
assert elapsed > num_groups * set_latency
@pytest.mark.parametrize(
("a_func", "b_func"),
[
(zarr.core.group.AsyncGroup.create_array, zarr.core.group.Group.create_array),
(zarr.core.group.AsyncGroup.create_hierarchy, zarr.core.group.Group.create_hierarchy),
(zarr.core.group.create_hierarchy, zarr.core.sync_group.create_hierarchy),
(zarr.core.group.create_nodes, zarr.core.sync_group.create_nodes),
(zarr.core.group.create_rooted_hierarchy, zarr.core.sync_group.create_rooted_hierarchy),
(zarr.core.group.get_node, zarr.core.sync_group.get_node),
],
)
def test_consistent_signatures(
a_func: Callable[[object], object], b_func: Callable[[object], object]
) -> None:
"""
Ensure that pairs of functions have consistent signatures
"""
base_sig = inspect.signature(a_func)
test_sig = inspect.signature(b_func)
wrong: dict[str, list[object]] = {
"missing_from_test": [],
"missing_from_base": [],
"wrong_type": [],
}
for key, value in base_sig.parameters.items():
if key not in test_sig.parameters:
wrong["missing_from_test"].append((key, value))
for key, value in test_sig.parameters.items():
if key not in base_sig.parameters:
wrong["missing_from_base"].append((key, value))
if base_sig.parameters[key] != value:
wrong["wrong_type"].append({key: {"test": value, "base": base_sig.parameters[key]}})
assert wrong["missing_from_base"] == []
assert wrong["missing_from_test"] == []
assert wrong["wrong_type"] == []
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("overwrite", [True, False])
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_create_hierarchy(
impl: Literal["async", "sync"], store: Store, overwrite: bool, zarr_format: ZarrFormat
) -> None:
"""
Test that ``create_hierarchy`` can create a complete Zarr hierarchy, even if the input describes
an incomplete one.
"""
hierarchy_spec = {
"group": GroupMetadata(attributes={"path": "group"}, zarr_format=zarr_format),
"group/array_0": meta_from_array(
np.arange(3), attributes={"path": "group/array_0"}, zarr_format=zarr_format
),
"group/subgroup/array_0": meta_from_array(
np.arange(4), attributes={"path": "group/subgroup/array_0"}, zarr_format=zarr_format
),
}
pre_existing_nodes = {
"group/extra": GroupMetadata(zarr_format=zarr_format, attributes={"path": "group/extra"}),
"": GroupMetadata(zarr_format=zarr_format, attributes={"name": "root"}),
}
# we expect create_hierarchy to insert a group that was missing from the hierarchy spec
expected_meta = hierarchy_spec | {"group/subgroup": GroupMetadata(zarr_format=zarr_format)}
# initialize the group with some nodes
_ = dict(sync_group.create_nodes(store=store, nodes=pre_existing_nodes))
if impl == "sync":
created = dict(
sync_group.create_hierarchy(store=store, nodes=hierarchy_spec, overwrite=overwrite)
)
elif impl == "async":
created = {
k: v
async for k, v in create_hierarchy(
store=store, nodes=hierarchy_spec, overwrite=overwrite
)
}
else:
raise ValueError(f"Invalid impl: {impl}")
if not overwrite:
extra_group = sync_group.get_node(store=store, path="group/extra", zarr_format=zarr_format)
assert extra_group.metadata.attributes == {"path": "group/extra"}
else:
with pytest.raises(FileNotFoundError):
await get_node(store=store, path="group/extra", zarr_format=zarr_format)
assert expected_meta == {k: v.metadata for k, v in created.items()}
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("extant_node", ["array", "group"])
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_create_hierarchy_existing_nodes(
impl: Literal["async", "sync"],
store: Store,
extant_node: Literal["array", "group"],
zarr_format: ZarrFormat,
) -> None:
"""
Test that create_hierarchy with overwrite = False will not overwrite an existing array or group,
and raises an exception instead.
"""
extant_node_path = "node"
if extant_node == "array":
extant_metadata = meta_from_array(
np.zeros(4), zarr_format=zarr_format, attributes={"extant": True}
)
new_metadata = meta_from_array(np.zeros(4), zarr_format=zarr_format)
err_cls = ContainsArrayError
else:
extant_metadata = GroupMetadata(zarr_format=zarr_format, attributes={"extant": True})
new_metadata = GroupMetadata(zarr_format=zarr_format)
err_cls = ContainsGroupError
# write the extant metadata
tuple(sync_group.create_nodes(store=store, nodes={extant_node_path: extant_metadata}))
msg = f"{extant_node} exists in store {store!r} at path {extant_node_path!r}."
# ensure that we cannot invoke create_hierarchy with overwrite=False here
if impl == "sync":
with pytest.raises(err_cls, match=re.escape(msg)):
tuple(
sync_group.create_hierarchy(
store=store, nodes={"node": new_metadata}, overwrite=False
)
)
elif impl == "async":
with pytest.raises(err_cls, match=re.escape(msg)):
tuple(
[
x
async for x in create_hierarchy(
store=store, nodes={"node": new_metadata}, overwrite=False
)
]
)
else:
raise ValueError(f"Invalid impl: {impl}")
# ensure that the extant metadata was not overwritten
assert (
await get_node(store=store, path=extant_node_path, zarr_format=zarr_format)
).metadata.attributes == {"extant": True}
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("overwrite", [True, False])
@pytest.mark.parametrize("group_path", ["", "foo"])
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_group_create_hierarchy(
store: Store,
zarr_format: ZarrFormat,
overwrite: bool,
group_path: str,
impl: Literal["async", "sync"],
) -> None:
"""
Test that the Group.create_hierarchy method creates specified nodes and returns them in a dict.
Also test that off-target nodes are not deleted, and that the root group is not deleted
"""
root_attrs = {"root": True}
g = sync_group.create_rooted_hierarchy(
store=store,
nodes={group_path: GroupMetadata(zarr_format=zarr_format, attributes=root_attrs)},
)
node_spec = {
"a": GroupMetadata(zarr_format=zarr_format, attributes={"name": "a"}),
"a/b": GroupMetadata(zarr_format=zarr_format, attributes={"name": "a/b"}),
"a/b/c": meta_from_array(
np.zeros(5), zarr_format=zarr_format, attributes={"name": "a/b/c"}
),
}
# This node should be kept if overwrite is True
extant_spec = {"b": GroupMetadata(zarr_format=zarr_format, attributes={"name": "b"})}
if impl == "async":
extant_created = dict(
await _collect_aiterator(g._async_group.create_hierarchy(extant_spec, overwrite=False))
)
nodes_created = dict(
await _collect_aiterator(
g._async_group.create_hierarchy(node_spec, overwrite=overwrite)
)
)
elif impl == "sync":
extant_created = dict(g.create_hierarchy(extant_spec, overwrite=False))
nodes_created = dict(g.create_hierarchy(node_spec, overwrite=overwrite))
all_members = dict(g.members(max_depth=None))
for k, v in node_spec.items():
assert all_members[k].metadata == v == nodes_created[k].metadata
# if overwrite is True, the extant nodes should be erased
for k, v in extant_spec.items():
if overwrite:
assert k in all_members
else:
assert all_members[k].metadata == v == extant_created[k].metadata
# ensure that we left the root group as-is
assert (
sync_group.get_node(store=store, path=group_path, zarr_format=zarr_format).attrs.asdict()
== root_attrs
)
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("overwrite", [True, False])
def test_group_create_hierarchy_no_root(
store: Store, zarr_format: ZarrFormat, overwrite: bool
) -> None:
"""
Test that the Group.create_hierarchy method will error if the dict provided contains a root.
"""
g = Group.from_store(store, zarr_format=zarr_format)
tree = {
"": GroupMetadata(zarr_format=zarr_format, attributes={"name": "a"}),
}
with pytest.raises(
ValueError, match="It is an error to use this method to create a root node. "
):
_ = dict(g.create_hierarchy(tree, overwrite=overwrite))
class TestParseHierarchyDict:
"""
Tests for the function that parses dicts of str : Metadata pairs, ensuring that the output models a
valid Zarr hierarchy
"""
@staticmethod
def test_normed_keys() -> None:
"""
Test that keys get normalized properly
"""
nodes = {
"a": GroupMetadata(),
"/b": GroupMetadata(),
"": GroupMetadata(),
"/a//c////": GroupMetadata(),
}
observed = _parse_hierarchy_dict(data=nodes)
expected = {normalize_path(k): v for k, v in nodes.items()}
assert observed == expected
@staticmethod
def test_empty() -> None:
"""
Test that an empty dict passes through
"""
assert _parse_hierarchy_dict(data={}) == {}
@staticmethod
def test_implicit_groups() -> None:
"""
Test that implicit groups were added as needed.
"""
requested = {"a/b/c": GroupMetadata()}
expected = requested | {
"": ImplicitGroupMarker(),
"a": ImplicitGroupMarker(),
"a/b": ImplicitGroupMarker(),
}
observed = _parse_hierarchy_dict(data=requested)
assert observed == expected
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_group_create_hierarchy_invalid_mixed_zarr_format(
store: Store, zarr_format: ZarrFormat
) -> None:
"""
Test that ``Group.create_hierarchy`` will raise an error if the zarr_format of the nodes is
different from the parent group.
"""
other_format = 2 if zarr_format == 3 else 3
g = Group.from_store(store, zarr_format=other_format)
tree = {
"a": GroupMetadata(zarr_format=zarr_format, attributes={"name": "a"}),
"a/b": meta_from_array(np.zeros(5), zarr_format=zarr_format, attributes={"name": "a/c"}),
}
msg = "The zarr_format of the nodes must be the same as the parent group."
with pytest.raises(ValueError, match=msg):
_ = tuple(g.create_hierarchy(tree))
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("defect", ["array/array", "array/group"])
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_create_hierarchy_invalid_nested(
impl: Literal["async", "sync"], store: Store, defect: tuple[str, str], zarr_format: ZarrFormat
) -> None:
"""
Test that create_hierarchy will not create a Zarr array that contains a Zarr group
or Zarr array.
"""
if defect == "array/array":
hierarchy_spec = {
"array_0": meta_from_array(np.arange(3), zarr_format=zarr_format),
"array_0/subarray": meta_from_array(np.arange(4), zarr_format=zarr_format),
}
elif defect == "array/group":
hierarchy_spec = {
"array_0": meta_from_array(np.arange(3), zarr_format=zarr_format),
"array_0/subgroup": GroupMetadata(attributes={"foo": 10}, zarr_format=zarr_format),
}
msg = "Only Zarr groups can contain other nodes."
if impl == "sync":
with pytest.raises(ValueError, match=msg):
tuple(sync_group.create_hierarchy(store=store, nodes=hierarchy_spec))
elif impl == "async":
with pytest.raises(ValueError, match=msg):
await _collect_aiterator(create_hierarchy(store=store, nodes=hierarchy_spec))
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_create_hierarchy_invalid_mixed_format(
impl: Literal["async", "sync"], store: Store
) -> None:
"""
Test that create_hierarchy will not create a Zarr group that contains a both Zarr v2 and
Zarr v3 nodes.
"""
msg = (
"Got data with both Zarr v2 and Zarr v3 nodes, which is invalid. "
"The following keys map to Zarr v2 nodes: ['v2']. "
"The following keys map to Zarr v3 nodes: ['v3']."
"Ensure that all nodes have the same Zarr format."
)
nodes = {
"v2": GroupMetadata(zarr_format=2),
"v3": GroupMetadata(zarr_format=3),
}
if impl == "sync":
with pytest.raises(ValueError, match=re.escape(msg)):
tuple(
sync_group.create_hierarchy(
store=store,
nodes=nodes,
)
)
elif impl == "async":
with pytest.raises(ValueError, match=re.escape(msg)):
await _collect_aiterator(
create_hierarchy(
store=store,
nodes=nodes,
)
)
else:
raise ValueError(f"Invalid impl: {impl}")
@pytest.mark.parametrize("store", ["memory", "local"], indirect=True)
@pytest.mark.parametrize("zarr_format", [2, 3])
@pytest.mark.parametrize("root_key", ["", "root"])
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_create_rooted_hierarchy_group(
impl: Literal["async", "sync"], store: Store, zarr_format, root_key: str
) -> None:
"""
Test that the _create_rooted_hierarchy can create a group.
"""
root_meta = {root_key: GroupMetadata(zarr_format=zarr_format, attributes={"path": root_key})}
group_names = ["a", "a/b"]
array_names = ["a/b/c", "a/b/d"]
# just to ensure that we don't use the same name twice in tests
assert set(group_names) & set(array_names) == set()
groups_expected_meta = {
_join_paths([root_key, node_name]): GroupMetadata(
zarr_format=zarr_format, attributes={"path": node_name}
)
for node_name in group_names
}
arrays_expected_meta = {
_join_paths([root_key, node_name]): meta_from_array(np.zeros(4), zarr_format=zarr_format)
for node_name in array_names
}
nodes_create = root_meta | groups_expected_meta | arrays_expected_meta
if impl == "sync":
g = sync_group.create_rooted_hierarchy(store=store, nodes=nodes_create)
assert isinstance(g, Group)
members = g.members(max_depth=None)
elif impl == "async":
g = await create_rooted_hierarchy(store=store, nodes=nodes_create)
assert isinstance(g, AsyncGroup)
members = await _collect_aiterator(g.members(max_depth=None))
else:
raise ValueError(f"Unknown implementation: {impl}")
assert g.metadata.attributes == {"path": root_key}
members_observed_meta = {k: v.metadata for k, v in members}
members_expected_meta_relative = {
k.removeprefix(root_key).lstrip("/"): v
for k, v in (groups_expected_meta | arrays_expected_meta).items()
}
assert members_observed_meta == members_expected_meta_relative
@pytest.mark.parametrize("store", ["memory", "local"], indirect=True)
@pytest.mark.parametrize("zarr_format", [2, 3])
@pytest.mark.parametrize("root_key", ["", "root"])
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_create_rooted_hierarchy_array(
impl: Literal["async", "sync"], store: Store, zarr_format, root_key: str
) -> None:
"""
Test that _create_rooted_hierarchy can create an array.
"""
root_meta = {
root_key: meta_from_array(
np.arange(3), zarr_format=zarr_format, attributes={"path": root_key}
)
}
nodes_create = root_meta
if impl == "sync":
a = sync_group.create_rooted_hierarchy(store=store, nodes=nodes_create, overwrite=True)
assert isinstance(a, Array)
elif impl == "async":
a = await create_rooted_hierarchy(store=store, nodes=nodes_create, overwrite=True)
assert isinstance(a, AsyncArray)
else:
raise ValueError(f"Invalid impl: {impl}")
assert a.metadata.attributes == {"path": root_key}
@pytest.mark.parametrize("impl", ["async", "sync"])
async def test_create_rooted_hierarchy_invalid(impl: Literal["async", "sync"]) -> None:
"""
Ensure _create_rooted_hierarchy will raise a ValueError if the input does not contain
a root node.
"""
zarr_format = 3
nodes = {
"a": GroupMetadata(zarr_format=zarr_format),
"b": GroupMetadata(zarr_format=zarr_format),
}
msg = "The input does not specify a root node. "
if impl == "sync":
with pytest.raises(ValueError, match=msg):
sync_group.create_rooted_hierarchy(store=store, nodes=nodes)
elif impl == "async":
with pytest.raises(ValueError, match=msg):
await create_rooted_hierarchy(store=store, nodes=nodes)
else:
raise ValueError(f"Invalid impl: {impl}")
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_group_members_performance(store: Store) -> None:
"""
Test that the execution time of Group.members is less than the number of members times the
latency for accessing each member.
"""
get_latency = 0.1
# use the input store to create some groups
group_create = zarr.group(store=store)
num_groups = 10
# Create some groups
for i in range(num_groups):
group_create.create_group(f"group{i}")
latency_store = LatencyStore(store, get_latency=get_latency)
# create a group with some latency on get operations
group_read = zarr.group(store=latency_store)
# check how long it takes to iterate over the groups
# if .members is sensitive to IO latency,
# this should take (num_groups * get_latency) seconds
# otherwise, it should take only marginally more than get_latency seconds
start = time.time()
_ = group_read.members()
elapsed = time.time() - start
assert elapsed < (num_groups * get_latency)
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_group_members_concurrency_limit(store: MemoryStore) -> None:
"""
Test that the execution time of Group.members can be constrained by the async concurrency
configuration setting.
"""
get_latency = 0.02
# use the input store to create some groups
group_create = zarr.group(store=store)
num_groups = 10
# Create some groups
for i in range(num_groups):
group_create.create_group(f"group{i}")
latency_store = LatencyStore(store, get_latency=get_latency)
# create a group with some latency on get operations
group_read = zarr.group(store=latency_store)
# check how long it takes to iterate over the groups
# if .members is sensitive to IO latency,
# this should take (num_groups * get_latency) seconds
# otherwise, it should take only marginally more than get_latency seconds
with zarr_config.set({"async.concurrency": 1}):
start = time.time()
_ = group_read.members()
elapsed = time.time() - start
assert elapsed > num_groups * get_latency
@pytest.mark.parametrize("option", ["array", "group", "invalid"])
def test_build_metadata_v3(option: Literal["array", "group", "invalid"]) -> None:
"""
Test that _build_metadata_v3 returns the correct metadata for a v3 array or group
"""
match option:
case "array":
metadata_dict = meta_from_array(np.arange(10), zarr_format=3).to_dict()
assert _build_metadata_v3(metadata_dict) == ArrayV3Metadata.from_dict(metadata_dict)
case "group":
metadata_dict = GroupMetadata(attributes={"foo": 10}, zarr_format=3).to_dict()
assert _build_metadata_v3(metadata_dict) == GroupMetadata.from_dict(metadata_dict)
case "invalid":
metadata_dict = GroupMetadata(zarr_format=3).to_dict()
metadata_dict.pop("node_type")
# TODO: fix the error message
msg = "Required key 'node_type' is missing from the provided metadata document."
with pytest.raises(MetadataValidationError, match=msg):
_build_metadata_v3(metadata_dict)
@pytest.mark.parametrize("roots", [("",), ("a", "b")])
def test_get_roots(roots: tuple[str, ...]):
root_nodes = {k: GroupMetadata(attributes={"name": k}) for k in roots}
child_nodes = {
_join_paths([k, "foo"]): GroupMetadata(attributes={"name": _join_paths([k, "foo"])})
for k in roots
}
data = root_nodes | child_nodes
assert set(_get_roots(data)) == set(roots)
def test_open_array_as_group():
z = zarr.create_array(shape=(40, 50), chunks=(10, 10), dtype="f8", store={})
with pytest.raises(ContainsArrayError):
zarr.open_group(z.store)
|