asanypath 2.6.1__tar.gz → 2.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. {asanypath-2.6.1 → asanypath-2.7.0}/.github/workflows/publish.yml +3 -3
  2. {asanypath-2.6.1 → asanypath-2.7.0}/.github/workflows/unittests.yml +1 -1
  3. {asanypath-2.6.1 → asanypath-2.7.0}/PKG-INFO +24 -4
  4. {asanypath-2.6.1 → asanypath-2.7.0}/README.md +22 -2
  5. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/_version.py +2 -2
  6. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/asanypath.pyi +1 -0
  7. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/cloud.py +102 -60
  8. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/common.py +3 -2
  9. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/local.py +2 -1
  10. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/sync.py +13 -1
  11. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_cloudpathmixin.py +293 -0
  12. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_scandir.py +5 -2
  13. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_sync.py +64 -1
  14. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_syncpath.py +38 -0
  15. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_upload.py +8 -2
  16. {asanypath-2.6.1 → asanypath-2.7.0}/.copilot/skills/async-python-lib/SKILL.md +0 -0
  17. {asanypath-2.6.1 → asanypath-2.7.0}/.copilot/skills/gitguro/SKILL.md +0 -0
  18. {asanypath-2.6.1 → asanypath-2.7.0}/.github/CODEOWNERS +0 -0
  19. {asanypath-2.6.1 → asanypath-2.7.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  20. {asanypath-2.6.1 → asanypath-2.7.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  21. {asanypath-2.6.1 → asanypath-2.7.0}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  22. {asanypath-2.6.1 → asanypath-2.7.0}/.github/dependabot.yml +0 -0
  23. {asanypath-2.6.1 → asanypath-2.7.0}/.gitignore +0 -0
  24. {asanypath-2.6.1 → asanypath-2.7.0}/.pre-commit-config.yaml +0 -0
  25. {asanypath-2.6.1 → asanypath-2.7.0}/CODE_OF_CONDUCT.md +0 -0
  26. {asanypath-2.6.1 → asanypath-2.7.0}/CONTRIBUTING.md +0 -0
  27. {asanypath-2.6.1 → asanypath-2.7.0}/LICENSE +0 -0
  28. {asanypath-2.6.1 → asanypath-2.7.0}/asanypath.png +0 -0
  29. {asanypath-2.6.1 → asanypath-2.7.0}/compose.yml +0 -0
  30. {asanypath-2.6.1 → asanypath-2.7.0}/hatch_build.py +0 -0
  31. {asanypath-2.6.1 → asanypath-2.7.0}/pyproject.toml +0 -0
  32. {asanypath-2.6.1 → asanypath-2.7.0}/scripts/bench.py +0 -0
  33. {asanypath-2.6.1 → asanypath-2.7.0}/scripts/bench_rmtree.py +0 -0
  34. {asanypath-2.6.1 → asanypath-2.7.0}/scripts/bench_upload.py +0 -0
  35. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/__init__.py +0 -0
  36. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/__init__.pyi +0 -0
  37. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/_backend_opts.py +0 -0
  38. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/_credstore.py +0 -0
  39. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/_prompt.py +0 -0
  40. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/_resume.py +0 -0
  41. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/_transfer.py +0 -0
  42. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/artifactory.py +0 -0
  43. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/asanypath.py +0 -0
  44. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/azure.py +0 -0
  45. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/batcher.py +0 -0
  46. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/cache.py +0 -0
  47. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/cli.py +0 -0
  48. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/click.py +0 -0
  49. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/exceptions.py +0 -0
  50. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/ftp.py +0 -0
  51. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/gcs.py +0 -0
  52. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/http.py +0 -0
  53. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/options.py +0 -0
  54. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/py.typed +0 -0
  55. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/s3.py +0 -0
  56. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/ssh.py +0 -0
  57. {asanypath-2.6.1 → asanypath-2.7.0}/src/asanypath/unsupported.py +0 -0
  58. {asanypath-2.6.1 → asanypath-2.7.0}/tests/__init__.py +0 -0
  59. {asanypath-2.6.1 → asanypath-2.7.0}/tests/conftest.py +0 -0
  60. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_artifactory.py +0 -0
  61. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_asanypath.py +0 -0
  62. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_auth_errors.py +0 -0
  63. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_azure.py +0 -0
  64. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_backend_options.py +0 -0
  65. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_batcher.py +0 -0
  66. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_cache.py +0 -0
  67. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_cli.py +0 -0
  68. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_click.py +0 -0
  69. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_commonpathmixin.py +0 -0
  70. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_credstore.py +0 -0
  71. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_endpoints.py +0 -0
  72. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_ftp.py +0 -0
  73. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_gcs.py +0 -0
  74. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_http.py +0 -0
  75. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_http_auth.py +0 -0
  76. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_isolation.py +0 -0
  77. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_local.py +0 -0
  78. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_options.py +0 -0
  79. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_py_typed.py +0 -0
  80. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_resume.py +0 -0
  81. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_s3.py +0 -0
  82. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_ssh.py +0 -0
  83. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_ssh_hostkeys.py +0 -0
  84. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_transport_hardening.py +0 -0
  85. {asanypath-2.6.1 → asanypath-2.7.0}/tests/test_unsupported_path.py +0 -0
@@ -44,7 +44,7 @@ jobs:
44
44
  - os: macos-15-intel
45
45
  target: x86_64
46
46
  manylinux: off
47
- - os: macos-14
47
+ - os: macos-15
48
48
  target: aarch64
49
49
  manylinux: off
50
50
  - os: windows-latest
@@ -116,7 +116,7 @@ jobs:
116
116
  rm rust/Cargo.toml.bak
117
117
 
118
118
  - name: Set up uv
119
- uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
119
+ uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
120
120
  with:
121
121
  enable-cache: false
122
122
 
@@ -142,7 +142,7 @@ jobs:
142
142
  persist-credentials: false
143
143
 
144
144
  - name: Set up uv
145
- uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
145
+ uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
146
146
  with:
147
147
  enable-cache: false
148
148
 
@@ -44,7 +44,7 @@ jobs:
44
44
  python-version: ${{ matrix.python-version }}
45
45
 
46
46
  - name: Set up uv
47
- uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
47
+ uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
48
48
 
49
49
  - name: Ruff checks
50
50
  run: uvx ruff check src tests && uvx ruff format --check src tests
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: asanypath
3
- Version: 2.6.1
3
+ Version: 2.7.0
4
4
  Summary: Async pathlib for local and cloud storage
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -20,7 +20,7 @@ Classifier: Programming Language :: Python :: 3.15
20
20
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
21
  Requires-Python: >=3.10
22
22
  Requires-Dist: anyio>=4
23
- Requires-Dist: asanypath-native~=2.6.1
23
+ Requires-Dist: asanypath-native~=2.7.0
24
24
  Requires-Dist: msgspec>=0.22.0
25
25
  Requires-Dist: yarl>=1.2
26
26
  Provides-Extra: all
@@ -197,13 +197,28 @@ report those errors rather than claiming the file does not exist.
197
197
  # Copy a single file (cross-backend supported)
198
198
  await src.copy(dst)
199
199
 
200
- # Copy entire directory tree
200
+ # Copy entire directory tree (cloud sources copy files concurrently)
201
201
  await src.copy(dst, recursive=True)
202
202
 
203
+ # Tune recursive cloud-copy concurrency, or use 1 for sequential copying
204
+ await src.copy(dst, recursive=True, concurrency=16)
205
+
203
206
  # Remove directory and all its contents
204
207
  await path.rmdir(recursive=True)
205
208
  ```
206
209
 
210
+ Recursive copies from S3, GCS, Azure, Artifactory and HTTP/HTTPS reuse
211
+ directory-listing metadata where available instead of probing each entry's
212
+ type. The default file concurrency is `min(12, os.cpu_count() or 1)`. A bounded
213
+ queue feeds the file workers, so a large tree does not create one task per
214
+ file. `concurrency=1` restores sequential file copying. Local, SSH and FTP
215
+ source backends are unchanged.
216
+ Progress callbacks remain serialized with cumulative byte totals, but files
217
+ may finish in any order. If a listing, transfer or callback fails, outstanding
218
+ workers are cancelled and awaited before the error is raised and `on_done`
219
+ is called. Some files may already have been copied (or moved); recursive
220
+ copies are not transactional.
221
+
207
222
  On S3, GCS and Azure a recursive delete lists the prefix once at every depth
208
223
  and deletes each key below it, directory marker objects included, in bulk: S3
209
224
  with one `DeleteObjects` request per 1,000 keys, GCS with JSON batch requests
@@ -271,7 +286,12 @@ for child in p.parent.iterdir(): # yields synchronously
271
286
  ```
272
287
 
273
288
  Local paths (`file://` or bare `/path`) bypass the proxy entirely and use
274
- `pathlib.Path` directly — zero threading overhead.
289
+ `SyncPath`, a wrapper around `pathlib.Path` — zero threading overhead.
290
+ These local path objects can be pickled and passed to spawned multiprocessing
291
+ workers.
292
+
293
+ Cloud paths share a background event loop per process. After `fork`, the child
294
+ resets the inherited runner and starts its own loop lazily on the next sync call.
275
295
 
276
296
  ### Large uploads stream automatically
277
297
 
@@ -140,13 +140,28 @@ report those errors rather than claiming the file does not exist.
140
140
  # Copy a single file (cross-backend supported)
141
141
  await src.copy(dst)
142
142
 
143
- # Copy entire directory tree
143
+ # Copy entire directory tree (cloud sources copy files concurrently)
144
144
  await src.copy(dst, recursive=True)
145
145
 
146
+ # Tune recursive cloud-copy concurrency, or use 1 for sequential copying
147
+ await src.copy(dst, recursive=True, concurrency=16)
148
+
146
149
  # Remove directory and all its contents
147
150
  await path.rmdir(recursive=True)
148
151
  ```
149
152
 
153
+ Recursive copies from S3, GCS, Azure, Artifactory and HTTP/HTTPS reuse
154
+ directory-listing metadata where available instead of probing each entry's
155
+ type. The default file concurrency is `min(12, os.cpu_count() or 1)`. A bounded
156
+ queue feeds the file workers, so a large tree does not create one task per
157
+ file. `concurrency=1` restores sequential file copying. Local, SSH and FTP
158
+ source backends are unchanged.
159
+ Progress callbacks remain serialized with cumulative byte totals, but files
160
+ may finish in any order. If a listing, transfer or callback fails, outstanding
161
+ workers are cancelled and awaited before the error is raised and `on_done`
162
+ is called. Some files may already have been copied (or moved); recursive
163
+ copies are not transactional.
164
+
150
165
  On S3, GCS and Azure a recursive delete lists the prefix once at every depth
151
166
  and deletes each key below it, directory marker objects included, in bulk: S3
152
167
  with one `DeleteObjects` request per 1,000 keys, GCS with JSON batch requests
@@ -214,7 +229,12 @@ for child in p.parent.iterdir(): # yields synchronously
214
229
  ```
215
230
 
216
231
  Local paths (`file://` or bare `/path`) bypass the proxy entirely and use
217
- `pathlib.Path` directly — zero threading overhead.
232
+ `SyncPath`, a wrapper around `pathlib.Path` — zero threading overhead.
233
+ These local path objects can be pickled and passed to spawned multiprocessing
234
+ workers.
235
+
236
+ Cloud paths share a background event loop per process. After `fork`, the child
237
+ resets the inherited runner and starts its own loop lazily on the next sync call.
218
238
 
219
239
  ### Large uploads stream automatically
220
240
 
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '2.6.1'
22
- __version_tuple__ = version_tuple = (2, 6, 1)
21
+ __version__ = version = '2.7.0'
22
+ __version_tuple__ = version_tuple = (2, 7, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -136,6 +136,7 @@ class AsAnyPath(AsAnyPurePath):
136
136
  dst: PathPart,
137
137
  *,
138
138
  recursive: bool = False,
139
+ concurrency: int = ...,
139
140
  remove_src: bool = False,
140
141
  force: bool = False,
141
142
  atomic: bool = False,
@@ -988,6 +988,7 @@ class CloudPathMixin(CommonPurePathMixin):
988
988
  dst,
989
989
  *,
990
990
  recursive: bool = False,
991
+ concurrency: int = min(12, os.cpu_count() or 1),
991
992
  remove_src: bool = False,
992
993
  force: bool = False,
993
994
  atomic: bool = False,
@@ -1000,13 +1001,18 @@ class CloudPathMixin(CommonPurePathMixin):
1000
1001
  """Copy this path to *dst*.
1001
1002
 
1002
1003
  *dst* can be any path type (cross-backend supported).
1003
- With ``recursive=True``, copies entire directory tree.
1004
+ With ``recursive=True``, copies entire directory tree with up to
1005
+ ``concurrency`` file transfers in flight (default: CPU count, capped at
1006
+ 12, or 1 if unknown; pass 1 for sequential).
1007
+ Progress callbacks are serialized, but files may finish in any order.
1004
1008
  With ``remove_src=True``, deletes source after copy (move semantics).
1005
1009
  Returns the destination path.
1006
1010
  """
1007
1011
  from asanypath import AsAnyPath
1008
1012
 
1009
1013
  _validate_chunk_size(chunk_size)
1014
+ if isinstance(concurrency, bool) or not isinstance(concurrency, int) or concurrency < 1:
1015
+ raise ValueError("concurrency must be a positive integer")
1010
1016
  dst = dst if has_async_transfer_api(dst) else AsAnyPath(str(dst))
1011
1017
  same_native = self._can_server_side_copy(dst)
1012
1018
  if atomic and getattr(dst, "protocol", None) != "file" and not same_native:
@@ -1027,15 +1033,17 @@ class CloudPathMixin(CommonPurePathMixin):
1027
1033
  )
1028
1034
  transferred = 0
1029
1035
  error: BaseException | None = None
1036
+ progress_lock = asyncio.Lock()
1030
1037
 
1031
1038
  async def _emit_progress(delta: int) -> None:
1032
1039
  nonlocal transferred
1033
1040
  if on_progress is None or delta <= 0: # pragma: no cover
1034
1041
  return
1035
- transferred += delta
1036
- maybe = on_progress(delta, transferred, self, dst)
1037
- if inspect.isawaitable(maybe): # pragma: no cover
1038
- await maybe
1042
+ async with progress_lock:
1043
+ transferred += delta
1044
+ maybe = on_progress(delta, transferred, self, dst)
1045
+ if inspect.isawaitable(maybe): # pragma: no cover
1046
+ await maybe
1039
1047
 
1040
1048
  async def _emit_done() -> None:
1041
1049
  if on_done is None: # pragma: no cover
@@ -1044,66 +1052,101 @@ class CloudPathMixin(CommonPurePathMixin):
1044
1052
  if inspect.isawaitable(maybe): # pragma: no cover
1045
1053
  await maybe
1046
1054
 
1047
- async def _copy_recursive(src_node: Self, dst_node: Self) -> None:
1048
- if await src_node.is_dir():
1049
- await dst_node.mkdir(parents=True, exist_ok=True)
1050
- async for child in src_node.iterdir():
1051
- await _copy_recursive(child, dst_node / child.name)
1052
- else:
1055
+ async def _copy_leaf(src_node: Self, dst_node: Any) -> None:
1056
+ if getattr(dst_node, "protocol", None) == "file":
1057
+ # copy_from owns destination checks, atomic writes and source removal.
1058
+ await dst_node.copy_from(
1059
+ src_node,
1060
+ remove_src=remove_src,
1061
+ force=force,
1062
+ atomic=atomic,
1063
+ chunk_size=chunk_size,
1064
+ on_progress=lambda delta, transferred, _src, _dst: _emit_progress(delta),
1065
+ )
1066
+ return
1053
1067
 
1054
- async def _copy_leaf() -> int:
1055
- if not needs_copy:
1056
- return 0
1057
- if src_node._can_server_side_copy(dst_node):
1058
- return await src_node._server_side_copy(
1059
- dst_node,
1060
- want_size=on_progress is not None,
1061
- destination_backend_options=destination_backend_options,
1062
- )
1063
- if getattr(dst_node, "protocol", None) == "file":
1064
- await dst_node.copy_from(
1065
- src_node,
1066
- force=force,
1067
- atomic=atomic,
1068
- chunk_size=chunk_size,
1069
- on_progress=lambda delta, transferred, _src, _dst: _emit_progress(
1070
- delta
1071
- ),
1072
- )
1073
- return 0
1074
- await dst_node.parent.mkdir(parents=True, exist_ok=True)
1075
- return await src_node._copy_to_remote(
1068
+ async def _copy_file() -> int:
1069
+ if not needs_copy:
1070
+ return 0
1071
+ if src_node._can_server_side_copy(dst_node):
1072
+ return await src_node._server_side_copy(
1076
1073
  dst_node,
1077
- chunk_size=chunk_size,
1078
- backend_options=destination_backend_options,
1074
+ want_size=on_progress is not None,
1075
+ destination_backend_options=destination_backend_options,
1079
1076
  )
1080
-
1081
- needs_copy, same_path, destination_exists = await async_destination_state(
1082
- src_node, dst_node
1077
+ await dst_node.parent.mkdir(parents=True, exist_ok=True)
1078
+ return await src_node._copy_to_remote(
1079
+ dst_node,
1080
+ chunk_size=chunk_size,
1081
+ backend_options=destination_backend_options,
1083
1082
  )
1084
- if not needs_copy:
1085
- if same_path:
1086
- return
1087
- elif destination_exists and not force:
1088
- require_force(force, dst_node)
1089
1083
 
1090
- await run_transfer_async(
1091
- src=src_node,
1092
- dst=dst_node,
1093
- copy_fn=_copy_leaf,
1094
- remove_fn=src_node.unlink,
1095
- remove_src=remove_src and not same_path,
1096
- on_progress=lambda delta, transferred, _src, _dst: _emit_progress(delta),
1097
- on_done=None,
1098
- )
1084
+ needs_copy, same_path, destination_exists = await async_destination_state(
1085
+ src_node, dst_node
1086
+ )
1087
+ if not needs_copy:
1088
+ if same_path:
1089
+ return
1090
+ elif destination_exists and not force:
1091
+ require_force(force, dst_node)
1092
+
1093
+ await run_transfer_async(
1094
+ src=src_node,
1095
+ dst=dst_node,
1096
+ copy_fn=_copy_file,
1097
+ remove_fn=src_node.unlink,
1098
+ remove_src=remove_src and not same_path,
1099
+ on_progress=lambda delta, transferred, _src, _dst: _emit_progress(delta),
1100
+ on_done=None,
1101
+ )
1102
+
1103
+ async def _copy_tree() -> None:
1104
+ queue: asyncio.Queue[tuple[Self, Any] | None] = asyncio.Queue(maxsize=concurrency)
1105
+
1106
+ async def produce(src_node: Self, dst_node: Any) -> None:
1107
+ await dst_node.mkdir(parents=True, exist_ok=True)
1108
+ async for entry in src_node.scandir():
1109
+ target = dst_node / entry.path.name
1110
+ is_dir = entry.is_dir
1111
+ if is_dir is None:
1112
+ is_dir = await entry.path.is_dir()
1113
+ if is_dir:
1114
+ await produce(entry.path, target)
1115
+ elif concurrency == 1:
1116
+ await _copy_leaf(entry.path, target)
1117
+ else:
1118
+ await queue.put((entry.path, target))
1119
+
1120
+ if concurrency == 1:
1121
+ await produce(self, dst)
1122
+ return
1123
+
1124
+ async def producer() -> None:
1125
+ await produce(self, dst)
1126
+ for _ in range(concurrency):
1127
+ await queue.put(None)
1128
+
1129
+ async def worker() -> None:
1130
+ while (item := await queue.get()) is not None:
1131
+ await _copy_leaf(*item)
1132
+
1133
+ tasks = [asyncio.create_task(producer())]
1134
+ tasks.extend(asyncio.create_task(worker()) for _ in range(concurrency))
1135
+ try:
1136
+ await asyncio.gather(*tasks)
1137
+ finally:
1138
+ for task in tasks:
1139
+ task.cancel()
1140
+ await asyncio.gather(*tasks, return_exceptions=True)
1099
1141
 
1100
1142
  try:
1101
- if recursive and await self.is_dir():
1143
+ is_directory = await self.is_dir()
1144
+ if recursive and is_directory:
1102
1145
  same_path = str(self) == str(dst)
1103
- await _copy_recursive(self, dst)
1146
+ await _copy_tree()
1104
1147
  if remove_src and not same_path:
1105
1148
  await self.rmdir()
1106
- elif await self.is_dir():
1149
+ elif is_directory:
1107
1150
  raise IsADirectoryError(21, f"Is a directory: '{self}' (use recursive=True)")
1108
1151
  else:
1109
1152
 
@@ -1206,17 +1249,16 @@ class CloudPathMixin(CommonPurePathMixin):
1206
1249
  directory prefixes need no per-entry probes.
1207
1250
  ``follow_symlinks`` is accepted for API parity; cloud objects have no symlinks.
1208
1251
  """
1252
+ dirs: list[Self] = []
1253
+ files: list[Self] = []
1209
1254
  try:
1210
- entries = [entry async for entry in self.scandir()]
1255
+ async for entry in self.scandir():
1256
+ (dirs if entry.is_dir else files).append(entry.path)
1211
1257
  except OSError as e:
1212
1258
  if on_error is not None:
1213
1259
  on_error(e)
1214
1260
  return
1215
1261
  raise
1216
- dirs: list[Self] = []
1217
- files: list[Self] = []
1218
- for entry in entries:
1219
- (dirs if entry.is_dir else files).append(entry.path)
1220
1262
  if top_down:
1221
1263
  yield self, [d.name for d in dirs], [f.name for f in files]
1222
1264
  for d in dirs:
@@ -14,12 +14,13 @@ from datetime import datetime
14
14
  from email.utils import parsedate_to_datetime
15
15
  from os import PathLike, getenv, sep
16
16
  from pathlib import Path, PurePath, PurePosixPath
17
- from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar
17
+ from typing import TYPE_CHECKING, Any, TypeVar
18
18
  from urllib.parse import urlsplit
19
19
 
20
20
  if TYPE_CHECKING:
21
21
  from typing import Self
22
22
 
23
+ import msgspec
23
24
  from anyio import Path as AioPath
24
25
  from yarl import URL
25
26
 
@@ -34,7 +35,7 @@ OS_SEP = sep
34
35
  _FILL_CONCURRENCY = 32
35
36
 
36
37
 
37
- class DirEntry(NamedTuple):
38
+ class DirEntry(msgspec.Struct, frozen=True):
38
39
  """One directory listing entry with the metadata the backend reported.
39
40
 
40
41
  ``None`` means the field is unknown: the listing did not include it and
@@ -201,7 +201,8 @@ class SyncPath(CommonPurePathMixin):
201
201
  return str(self._path)
202
202
 
203
203
  def __getattr__(self, name):
204
- return getattr(self._path, name)
204
+ # Pickle probes __setstate__ before restoring _path.
205
+ return getattr(object.__getattribute__(self, "_path"), name)
205
206
 
206
207
  def iterdir(self) -> Generator[S]:
207
208
  for entry in self._path.iterdir():
@@ -23,6 +23,7 @@ from __future__ import annotations
23
23
 
24
24
  import asyncio
25
25
  import inspect
26
+ import os
26
27
  import threading
27
28
  from abc import ABC
28
29
  from collections.abc import AsyncIterator
@@ -74,6 +75,15 @@ class _SyncRunner:
74
75
  return
75
76
 
76
77
 
78
+ def _reset_after_fork() -> None:
79
+ _SyncRunner._instance = None
80
+ _SyncRunner._lock = threading.Lock()
81
+
82
+
83
+ if hasattr(os, "register_at_fork"):
84
+ os.register_at_fork(after_in_child=_reset_after_fork)
85
+
86
+
77
87
  class _SyncProxy:
78
88
  """Transparent sync proxy around an async path instance."""
79
89
 
@@ -155,12 +165,14 @@ class _SyncProxy:
155
165
  if inspect.isasyncgenfunction(attr): # pragma: no cover
156
166
 
157
167
  def _sync_iter_method(*args, **kwargs): # pragma: no cover
168
+ from msgspec.structs import replace
169
+
158
170
  from asanypath.common import DirEntry
159
171
 
160
172
  async_it = attr(*args, **kwargs)
161
173
  for item in _SyncRunner.get().iter(async_it): # pragma: no cover
162
174
  if isinstance(item, DirEntry):
163
- yield item._replace(path=_wrap(item.path))
175
+ yield replace(item, path=_wrap(item.path))
164
176
  else:
165
177
  yield _wrap(item) if _is_path(item) else item
166
178
 
@@ -5,6 +5,7 @@
5
5
  # https://opensource.org/licenses/MIT.
6
6
 
7
7
  import asyncio
8
+ import os
8
9
  from os.path import expanduser
9
10
  from types import SimpleNamespace
10
11
  from unittest.mock import AsyncMock, patch
@@ -756,6 +757,298 @@ class TestCopyCallbacks:
756
757
  assert done_calls == [(7, True, None)]
757
758
 
758
759
 
760
+ class TestRecursiveCopy:
761
+ @pytest.fixture
762
+ def tree(self, monkeypatch):
763
+ src = _make_s3().parent
764
+ files = [src / f"file{i}.txt" for i in range(12)]
765
+ subdir = src / "sub"
766
+ files.append(subdir / "nested.txt")
767
+ listings = {
768
+ str(src): [
769
+ *((str(path), False, 7, None) for path in files[:-1]),
770
+ (str(subdir), True, None, None),
771
+ (str(src / "empty"), True, None, None),
772
+ ],
773
+ str(subdir): [(str(files[-1]), False, 7, None)],
774
+ str(src / "empty"): [],
775
+ }
776
+
777
+ async def fetch_listing(path):
778
+ return listings[str(path)]
779
+
780
+ async def is_dir(path):
781
+ assert path == src, "Listed entries should not need directory probes"
782
+ return True
783
+
784
+ monkeypatch.setattr(S3Path, "_fetch_listing", fetch_listing)
785
+ monkeypatch.setattr(S3Path, "is_dir", is_dir)
786
+ return src, files
787
+
788
+ @pytest.mark.parametrize("concurrency", [None, 1, 3])
789
+ async def test_bounded_copy_reuses_listing_and_checks_destination_once(
790
+ self, tree, tmp_path, monkeypatch, concurrency
791
+ ):
792
+ from asanypath.local import AsyncPath
793
+
794
+ src, files = tree
795
+ active = peak = 0
796
+ reads = []
797
+ probes = []
798
+ original_is_file = AsyncPath.is_file
799
+
800
+ async def is_file(path):
801
+ probes.append(str(path))
802
+ return await original_is_file(path)
803
+
804
+ async def read_bytes(path):
805
+ nonlocal active, peak
806
+ active += 1
807
+ peak = max(peak, active)
808
+ try:
809
+ await asyncio.sleep(0.001)
810
+ reads.append(path)
811
+ return b"payload"
812
+ finally:
813
+ active -= 1
814
+
815
+ monkeypatch.setattr(S3Path, "read_bytes", read_bytes)
816
+ monkeypatch.setattr(AsyncPath, "is_file", is_file)
817
+ progress = []
818
+ done = []
819
+
820
+ async def on_progress(delta, total, source, destination):
821
+ assert source is src
822
+ assert str(destination) == str(tmp_path)
823
+ progress.append((delta, total))
824
+ await asyncio.sleep(0)
825
+ assert progress[-1] == (delta, total), "Progress callbacks must not overlap"
826
+
827
+ def on_done(source, destination, total, ok, error):
828
+ done.append((total, ok, error))
829
+
830
+ kwargs = {} if concurrency is None else {"concurrency": concurrency}
831
+ result = await src.copy(
832
+ tmp_path,
833
+ recursive=True,
834
+ chunk_size=0,
835
+ on_progress=on_progress,
836
+ on_done=on_done,
837
+ **kwargs,
838
+ )
839
+
840
+ assert str(result) == str(tmp_path)
841
+ assert peak == (min(12, os.cpu_count() or 1) if concurrency is None else concurrency)
842
+ assert set(reads) == set(files)
843
+ if concurrency == 1:
844
+ assert reads == files
845
+ assert len(probes) == len(files)
846
+ assert len(set(probes)) == len(files)
847
+ assert (tmp_path / "empty").is_dir()
848
+ for path in files:
849
+ assert (tmp_path / path.relative_to(src)).read_bytes() == b"payload"
850
+ assert progress == [(7, 7 * i) for i in range(1, len(files) + 1)]
851
+ assert done == [(7 * len(files), True, None)]
852
+
853
+ @pytest.mark.parametrize("cancel", [False, True])
854
+ async def test_failure_or_cancellation_joins_workers(self, tree, tmp_path, monkeypatch, cancel):
855
+ src, _ = tree
856
+ started = asyncio.Event()
857
+ blocked = asyncio.Event()
858
+ active = 0
859
+ finished = []
860
+ yielded = []
861
+ done = []
862
+ failure = OSError("read failed")
863
+ original_scandir = S3Path.scandir
864
+
865
+ async def scandir(path):
866
+ async for entry in original_scandir(path):
867
+ yielded.append(entry.path)
868
+ yield entry
869
+
870
+ async def read_bytes(path):
871
+ nonlocal active
872
+ active += 1
873
+ if active == 3:
874
+ started.set()
875
+ try:
876
+ await started.wait()
877
+ if path.name == "file0.txt" and not cancel:
878
+ raise failure
879
+ await blocked.wait()
880
+ return b"payload"
881
+ finally:
882
+ active -= 1
883
+ finished.append(path)
884
+
885
+ monkeypatch.setattr(S3Path, "read_bytes", read_bytes)
886
+ monkeypatch.setattr(S3Path, "scandir", scandir)
887
+ unlink = AsyncMock()
888
+ monkeypatch.setattr(S3Path, "unlink", unlink)
889
+ rmdir = AsyncMock()
890
+ monkeypatch.setattr(S3Path, "rmdir", rmdir)
891
+
892
+ task = asyncio.create_task(
893
+ src.copy(
894
+ tmp_path,
895
+ recursive=True,
896
+ concurrency=3,
897
+ chunk_size=0,
898
+ atomic=True,
899
+ remove_src=True,
900
+ on_done=lambda *args: done.append(args),
901
+ )
902
+ )
903
+ await asyncio.wait_for(started.wait(), timeout=2)
904
+ if cancel:
905
+ task.cancel()
906
+ with pytest.raises(asyncio.CancelledError if cancel else OSError) as exc:
907
+ await asyncio.wait_for(task, timeout=2)
908
+
909
+ assert active == 0
910
+ assert len(finished) == 3
911
+ assert len(yielded) <= 7 # Three active, three queued, one waiting for queue space.
912
+ assert not list(tmp_path.rglob(".*.tmp-*"))
913
+ assert len(done) == 1
914
+ assert done[0][3] is False
915
+ if cancel:
916
+ assert isinstance(done[0][4], asyncio.CancelledError)
917
+ else:
918
+ assert done[0][4] is exc.value
919
+ assert exc.value is failure
920
+ unlink.assert_not_awaited()
921
+ rmdir.assert_not_awaited()
922
+
923
+ @pytest.mark.parametrize("force, identical", [(False, False), (False, True), (True, False)])
924
+ async def test_existing_destination_and_move(
925
+ self, tree, tmp_path, monkeypatch, force, identical
926
+ ):
927
+ src, files = tree
928
+ for path in files:
929
+ destination = tmp_path / path.relative_to(src)
930
+ destination.parent.mkdir(parents=True, exist_ok=True)
931
+ destination.write_bytes(b"payload" if identical else b"old")
932
+ monkeypatch.setattr(S3Path, "read_bytes", AsyncMock(return_value=b"payload"))
933
+ monkeypatch.setattr(S3Path, "checksums", AsyncMock(return_value={}))
934
+ unlink = AsyncMock()
935
+ monkeypatch.setattr(S3Path, "unlink", unlink)
936
+ rmdir = AsyncMock()
937
+ monkeypatch.setattr(S3Path, "rmdir", rmdir)
938
+
939
+ if not force and not identical:
940
+ with pytest.raises(FileExistsError):
941
+ await src.copy(tmp_path, recursive=True, remove_src=True, chunk_size=0)
942
+ unlink.assert_not_awaited()
943
+ rmdir.assert_not_awaited()
944
+ else:
945
+ await src.copy(tmp_path, recursive=True, force=force, remove_src=True, chunk_size=0)
946
+ assert unlink.await_count == len(files)
947
+ rmdir.assert_awaited_once()
948
+ for path in files:
949
+ assert (tmp_path / path.relative_to(src)).read_bytes() == b"payload"
950
+
951
+ @pytest.mark.parametrize("concurrency", [0, -1, 1.5, True])
952
+ async def test_invalid_concurrency(self, concurrency, tmp_path):
953
+ with pytest.raises(ValueError, match="concurrency"):
954
+ await _make_s3().copy(tmp_path, recursive=True, concurrency=concurrency)
955
+
956
+ @pytest.mark.parametrize("server_side", [False, True])
957
+ async def test_remote_destination_preserves_options_and_move(
958
+ self, tree, monkeypatch, server_side
959
+ ):
960
+ src, files = tree
961
+ dst = src._spawn("s3://bucket/target" if server_side else "s3://other/target")
962
+ options = BackendOptions(headers={"x-amz-meta-source": "test"})
963
+ monkeypatch.setattr(S3Path, "mkdir", AsyncMock())
964
+ monkeypatch.setattr(S3Path, "is_file", AsyncMock(return_value=False))
965
+ unlink = AsyncMock()
966
+ monkeypatch.setattr(S3Path, "unlink", unlink)
967
+ rmdir = AsyncMock()
968
+ monkeypatch.setattr(S3Path, "rmdir", rmdir)
969
+ copies = []
970
+
971
+ async def copy(path, target, **kwargs):
972
+ copies.append((path, target, kwargs))
973
+ await asyncio.sleep(0)
974
+ return 7
975
+
976
+ monkeypatch.setattr(S3Path, "_server_side_copy" if server_side else "_copy_to_remote", copy)
977
+ assert (
978
+ await src.copy(
979
+ dst, recursive=True, remove_src=True, destination_backend_options=options
980
+ )
981
+ is dst
982
+ )
983
+
984
+ assert {path for path, _, _ in copies} == set(files)
985
+ for path, target, kwargs in copies:
986
+ assert str(target) == str(dst / path.relative_to(src))
987
+ assert kwargs == (
988
+ {"want_size": False, "destination_backend_options": options}
989
+ if server_side
990
+ else {"chunk_size": None, "backend_options": options}
991
+ )
992
+ assert unlink.await_count == len(files)
993
+ rmdir.assert_awaited_once()
994
+
995
+ @pytest.mark.parametrize("origin", ["listing", "callback"])
996
+ async def test_listing_or_callback_error_cancels_active_copies(
997
+ self, tree, tmp_path, monkeypatch, origin
998
+ ):
999
+ src, _ = tree
1000
+ started = asyncio.Event()
1001
+ blocked = asyncio.Event()
1002
+ active = 0
1003
+ done = []
1004
+ failure = OSError(f"{origin} failed")
1005
+ original_fetch = S3Path._fetch_listing
1006
+
1007
+ async def fetch_listing(path):
1008
+ if path.name == "sub":
1009
+ await started.wait()
1010
+ raise failure
1011
+ rows = await original_fetch(path)
1012
+ return [*rows[:3], rows[-2]] if path == src else rows
1013
+
1014
+ async def read_bytes(path):
1015
+ nonlocal active
1016
+ active += 1
1017
+ if active == 3:
1018
+ started.set()
1019
+ try:
1020
+ await started.wait()
1021
+ if origin == "callback" and path.name == "file0.txt":
1022
+ return b"payload"
1023
+ await blocked.wait()
1024
+ finally:
1025
+ active -= 1
1026
+
1027
+ def progress(*args):
1028
+ raise failure
1029
+
1030
+ if origin == "listing":
1031
+ # Reach the subdirectory listing while file transfers are blocked.
1032
+ monkeypatch.setattr(S3Path, "_fetch_listing", fetch_listing)
1033
+ monkeypatch.setattr(S3Path, "read_bytes", read_bytes)
1034
+ with pytest.raises(OSError) as exc:
1035
+ await asyncio.wait_for(
1036
+ src.copy(
1037
+ tmp_path,
1038
+ recursive=True,
1039
+ concurrency=3,
1040
+ chunk_size=0,
1041
+ on_progress=progress if origin == "callback" else None,
1042
+ on_done=lambda *args: done.append(args),
1043
+ ),
1044
+ timeout=2,
1045
+ )
1046
+ assert exc.value is failure
1047
+ assert active == 0
1048
+ assert len(done) == 1
1049
+ assert done[0][3:] == (False, failure)
1050
+
1051
+
759
1052
  class TestRenameReplaceCallbacks:
760
1053
  async def test_rename_callbacks_called(self):
761
1054
  src = _make_s3()
@@ -45,11 +45,14 @@ def test_parse_listing_mtime(text, expected):
45
45
  async def test_local_scandir(tree):
46
46
  entries = {e.path.name: e async for e in AsyncPath(tree).scandir(stat=True)}
47
47
  assert isinstance(entries["f.txt"].path, AsyncPath)
48
- assert entries["f.txt"][1:3] == (False, 3)
48
+ assert entries["f.txt"].is_dir is False
49
+ assert entries["f.txt"].size == 3
49
50
  assert entries["f.txt"].mtime is not None
50
51
  assert entries["sub"].is_dir is True
51
52
  # A dangling symlink is listed as a non-directory without metadata.
52
- assert entries["broken"][1:] == (False, None, None)
53
+ assert entries["broken"].is_dir is False
54
+ assert entries["broken"].size is None
55
+ assert entries["broken"].mtime is None
53
56
 
54
57
 
55
58
  async def test_local_scandir_without_stat(tree):
@@ -8,11 +8,13 @@
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
+ import multiprocessing
12
+
11
13
  import pytest
12
14
 
13
15
  from asanypath.exceptions import UnsupportedProtocolError
14
16
  from asanypath.local import SyncPath
15
- from asanypath.sync import AsAnyPath, _SyncProxy
17
+ from asanypath.sync import AsAnyPath, _SyncProxy, _SyncRunner
16
18
  from asanypath.unsupported import UnsupportedProtocolPath
17
19
 
18
20
 
@@ -171,6 +173,67 @@ class TestSyncProxy:
171
173
  for child in p.iterdir():
172
174
  assert isinstance(child, _SyncProxy)
173
175
 
176
+ def test_scandir_wraps_paths_without_mutating_entries(self, monkeypatch):
177
+ from asanypath import DirEntry, S3Path
178
+
179
+ root = S3Path("s3://bucket")
180
+ original = [
181
+ DirEntry(root / "file.txt", False, 3, 7.0),
182
+ DirEntry(root / "sub", True),
183
+ ]
184
+
185
+ async def scandir(self, *, stat=False):
186
+ for entry in original:
187
+ yield entry
188
+
189
+ monkeypatch.setattr(S3Path, "scandir", scandir)
190
+ entries = list(AsAnyPath("s3://bucket").scandir(stat=True))
191
+
192
+ assert len(entries) == len(original)
193
+ for entry, source in zip(entries, original):
194
+ assert isinstance(entry, DirEntry)
195
+ assert isinstance(entry.path, _SyncProxy)
196
+ assert str(entry.path) == str(source.path)
197
+ assert (entry.is_dir, entry.size, entry.mtime) == (
198
+ source.is_dir,
199
+ source.size,
200
+ source.mtime,
201
+ )
202
+ assert isinstance(source.path, S3Path)
203
+ assert entry is not source
204
+
205
+ @pytest.mark.skipif(
206
+ "fork" not in multiprocessing.get_all_start_methods(), reason="requires fork"
207
+ )
208
+ @pytest.mark.parametrize("operation", ["read_bytes", "iterdir"])
209
+ def test_sync_after_fork(self, mock_s3, operation):
210
+ p = AsAnyPath("s3://bucket")
211
+ assert p.read_bytes() == b"mock data"
212
+ runner = _SyncRunner.get()
213
+
214
+ def check_child():
215
+ if operation == "read_bytes":
216
+ assert p.read_bytes() == b"mock data"
217
+ else:
218
+ assert [child.name for child in p.iterdir()] == ["a.txt", "b.txt"]
219
+ assert _SyncRunner.get() is not runner
220
+
221
+ process = multiprocessing.get_context("fork").Process(target=check_child)
222
+ with _SyncRunner._lock:
223
+ process.start()
224
+ try:
225
+ process.join(timeout=5)
226
+ assert not process.is_alive(), "forked child hung using the sync runner"
227
+ assert process.exitcode == 0
228
+ finally:
229
+ if process.is_alive():
230
+ process.terminate()
231
+ process.join(timeout=5)
232
+ process.close()
233
+
234
+ assert _SyncRunner.get() is runner
235
+ assert p.read_bytes() == b"mock data"
236
+
174
237
 
175
238
  class TestSyncUnsupportedProtocol:
176
239
  def test_unknown_protocol_returns_placeholder(self):
@@ -4,6 +4,9 @@
4
4
  # license that can be found in the LICENSE file or at
5
5
  # https://opensource.org/licenses/MIT.
6
6
 
7
+ import copy
8
+ import multiprocessing
9
+ import pickle
7
10
  from pathlib import Path
8
11
 
9
12
  import pytest
@@ -16,6 +19,10 @@ from tests.conftest import classtest_factory
16
19
  testbase = classtest_factory("_TestSyncPath", SyncPath)
17
20
 
18
21
 
22
+ def _echo_path(path):
23
+ return path
24
+
25
+
19
26
  class TestSyncPath(testbase):
20
27
  __test__ = True
21
28
 
@@ -48,6 +55,37 @@ class TestSyncPath(testbase):
48
55
  def test___str__(self, p):
49
56
  assert str(p) == "testdir/nested/file.txt"
50
57
 
58
+ @pytest.mark.parametrize("protocol", range(pickle.HIGHEST_PROTOCOL + 1))
59
+ def test_pickle_roundtrip(self, tmp, protocol):
60
+ path = tmp / "file.txt"
61
+ path.write_text("payload")
62
+
63
+ restored = pickle.loads(pickle.dumps(path, protocol=protocol))
64
+
65
+ assert isinstance(restored, SyncPath)
66
+ assert restored == path
67
+ assert restored.read_text() == "payload"
68
+
69
+ @pytest.mark.parametrize("clone", [copy.copy, copy.deepcopy], ids=["shallow", "deep"])
70
+ def test_copy_roundtrip(self, p, clone):
71
+ restored = clone(p)
72
+
73
+ assert isinstance(restored, SyncPath)
74
+ assert restored is not p
75
+ assert restored == p
76
+ assert restored.__dict__ == p.__dict__
77
+
78
+ def test_spawn_pool_roundtrip(self, tmp):
79
+ path = tmp / "file.txt"
80
+ path.write_text("payload")
81
+
82
+ with multiprocessing.get_context("spawn").Pool(1) as pool:
83
+ restored = pool.apply_async(_echo_path, (path,)).get(timeout=10)
84
+
85
+ assert isinstance(restored, SyncPath)
86
+ assert restored == path
87
+ assert restored.read_text() == "payload"
88
+
51
89
  def test___truediv__(self, p):
52
90
  result = p / "sub"
53
91
  assert result == SyncPath("testdir/nested/file.txt/sub")
@@ -13,6 +13,7 @@ import pytest
13
13
 
14
14
  from asanypath import TransferBudget
15
15
  from asanypath._transfer import iter_transfer_chunks, upload_parts
16
+ from asanypath.common import DirEntry
16
17
  from tests.test_azure import _make_azure_path
17
18
  from tests.test_gcs import _make_gcs_path
18
19
  from tests.test_s3 import _make_s3path
@@ -534,6 +535,11 @@ async def test_cross_backend_copy_uses_spooled_upload(recursive, monkeypatch):
534
535
 
535
536
  monkeypatch.setattr("asanypath.cloud.SPOOL_MAX_SIZE", 4)
536
537
  monkeypatch.setattr(S3Path, "is_dir", AsyncMock(return_value=False))
538
+ monkeypatch.setattr(
539
+ S3Path,
540
+ "_fetch_listing",
541
+ AsyncMock(side_effect=AssertionError("Unexpected listing request")),
542
+ )
537
543
  monkeypatch.setattr(source, "iter_bytes", lambda _: chunks())
538
544
  monkeypatch.setattr(type(destination), "exists", AsyncMock(return_value=False))
539
545
  monkeypatch.setattr(type(destination), "_upload_buffer", upload)
@@ -548,10 +554,10 @@ async def test_cross_backend_copy_uses_spooled_upload(recursive, monkeypatch):
548
554
  monkeypatch.setattr(child, "iter_bytes", lambda _: chunks())
549
555
 
550
556
  async def children():
551
- yield child
557
+ yield DirEntry(child, is_dir=False)
552
558
 
553
559
  monkeypatch.setattr(source, "is_dir", AsyncMock(return_value=True))
554
- monkeypatch.setattr(source, "iterdir", children)
560
+ monkeypatch.setattr(source, "scandir", children)
555
561
  with TransferBudget(min_range_size=8):
556
562
  await source.copy(
557
563
  destination, recursive=recursive, chunk_size=4, destination_backend_options=options
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes