Debian Codegraph @

tests/test_client.py

raw
1 """Tests for the client module."""
2
3 from collections.abc import AsyncGenerator, AsyncIterable, Callable
4 import io
5 import os
6 from pathlib import Path
7 import re
8 import time
9 from typing import Any
10
11 import aiohttp
12 from aioresponses import CallbackResult, aioresponses
13 from multidict import CIMultiDict, CIMultiDictProxy
14 import pytest
15 import yarl
16
17 from aiowebdav2 import Client
18 from aiowebdav2.client import ClientOptions, _prune_paths
19 from aiowebdav2.exceptions import (
20 AccessDeniedError,
21 ConnectionExceptionError,
22 LocalResourceNotFoundError,
23 MethodNotSupportedError,
24 NoConnectionError,
25 NotEnoughSpaceError,
26 OptionNotValidError,
27 RemoteParentNotFoundError,
28 RemoteResourceNotFoundError,
29 ResourceLockedError,
30 ResponseErrorCodeError,
31 UnauthorizedError,
32 )
33 from aiowebdav2.models import Property, PropertyRequest, QuotaInfo
34
35 from . import load_responses, upload_stream
36
37
38 @pytest.mark.parametrize(
39 ("server_path", "response"),
40 [
41 (
42 "/",
43 load_responses("get_list.xml"),
44 ),
45 (
46 "/remote.php/webdav/",
47 load_responses("nextcloud/get_list.xml"),
48 ),
49 (
50 "/remote.php/webdav/test test/",
51 load_responses("nextcloud/get_list_with_spaces.xml"),
52 ),
53 ],
54 )
55 async def test_list_files(
56 get_client: Callable[[str], Client],
57 server_path: str,
58 response: str,
59 responses: aioresponses,
60 ) -> None:
61 """Test list files."""
62 responses.clear()
63 responses.add(
64 f"https://webdav.example.com{server_path}",
65 "PROPFIND",
66 headers={"Accept": "*/*", "Depth": "1"},
67 content_type="application/xml",
68 status=200,
69 body=response,
70 )
71
72 client = get_client(server_path)
73
74 files = await client.list_files()
75 assert len(files) == 2
76 assert files == ["/test_dir/", "/test_dir/test.txt"]
77
78
79 async def test_list_files_empty(client: Client, responses: aioresponses) -> None:
80 """Test list files with empty response."""
81 responses.clear()
82 responses.add(
83 "https://webdav.example.com",
84 "PROPFIND",
85 headers={"Accept": "*/*", "Depth": "1"},
86 content_type="application/xml",
87 status=200,
88 body=load_responses("get_list_empty.xml"),
89 )
90
91 files = await client.list_files()
92 assert not files
93
94
95 async def test_list_files_resource_not_found(
96 client: Client, responses: aioresponses
97 ) -> None:
98 """Test list files with parent not found."""
99 responses.add(
100 "https://webdav.example.com/test_dir/",
101 "PROPFIND",
102 headers={"Accept": "*/*", "Depth": "1"},
103 content_type="application/xml",
104 status=404,
105 )
106
107 with pytest.raises(RemoteResourceNotFoundError):
108 await client.list_files("/test_dir/")
109
110
111 async def test_list_files_recursive(client: Client, responses: aioresponses) -> None:
112 """Test list files recursively."""
113 responses.add(
114 "https://webdav.example.com/test_dir/",
115 "PROPFIND",
116 headers={"Accept": "*/*", "Depth": "infinity"},
117 content_type="application/xml",
118 status=200,
119 body=load_responses("get_list_recursive.xml"),
120 )
121
122 files = await client.list_files("/test_dir/", recursive=True)
123 assert len(files) == 3
124 assert files == [
125 "/test_dir/test.txt",
126 "/test_dir/test_dir2/",
127 "/test_dir/test_dir2/test.txt",
128 ]
129
130
131 async def test_list_with_infos(client: Client) -> None:
132 """Test list with infos."""
133 files = await client.list_with_infos()
134 assert len(files) == 2
135 assert files == [
136 {
137 "content_type": "httpd/unix-directory",
138 "created": "2020-04-10T21:59:43Z",
139 "etag": '"1000-5a2f6d9cf8d39"',
140 "isdir": "True",
141 "modified": "Fri, 10 Apr 2020 21:59:43 GMT",
142 "name": "",
143 "path": "/test_dir/",
144 "size": "",
145 },
146 {
147 "content_type": "text/plain",
148 "created": "2020-04-10T21:59:43Z",
149 "etag": '"29-5a2f6d9cf8d39"',
150 "isdir": "False",
151 "modified": "Fri, 10 Apr 2020 21:59:43 GMT",
152 "name": "",
153 "path": "/test_dir/test.txt",
154 "size": "41",
155 },
156 ]
157
158
159 async def test_with_properties(client: Client, responses: aioresponses) -> None:
160 """Test list with properties."""
161 responses.clear()
162 responses.add(
163 "https://webdav.example.com/",
164 "PROPFIND",
165 headers={"Accept": "*/*", "Depth": "0"},
166 content_type="application/xml",
167 status=207,
168 body=load_responses("list_with_properties.xml"),
169 )
170
171 props = await client.list_with_properties(
172 properties=[
173 PropertyRequest(namespace="test", name="aProperty"),
174 PropertyRequest(namespace="test2", name="anotherProperty"),
175 ],
176 )
177 assert props == {
178 "/test_dir/test.txt": [
179 Property(
180 name="aProperty",
181 namespace="test",
182 value="aValue",
183 ),
184 Property(
185 name="anotherProperty",
186 namespace="test2",
187 value="anotherValue",
188 ),
189 ],
190 "/test_dir/test2.txt": [
191 Property(
192 name="aProperty",
193 namespace="test",
194 value="aValue2",
195 ),
196 Property(
197 name="anotherProperty",
198 namespace="test2",
199 value="anotherValue2",
200 ),
201 ],
202 }
203
204
205 async def test_info(client: Client, responses: aioresponses) -> None:
206 """Test info."""
207 responses.add(
208 "https://webdav.example.com/test_dir/test.txt",
209 "PROPFIND",
210 headers={"Accept": "*/*", "Depth": "0"},
211 content_type="application/xml",
212 status=200,
213 body=load_responses("get_info.xml"),
214 )
215 responses.add(
216 "https://webdav.example.com/test_dir/test.txt",
217 "PROPFIND",
218 headers={"Accept": "*/*", "Depth": "0"},
219 content_type="application/xml",
220 status=200,
221 body=load_responses("is_dir_file.xml"),
222 )
223
224 info = await client.info("/test_dir/test.txt")
225 assert info == {
226 "content_type": "text/plain",
227 "created": "2017-10-18T15:16:04Z",
228 "etag": "ab0b4b7973803c03639b848682b5f38c",
229 "modified": "Wed, 18 Oct 2017 15:16:04 GMT",
230 "name": "test.txt",
231 "size": "41",
232 }
233
234
235 async def test_clean(client: Client, responses: aioresponses) -> None:
236 """Test clean."""
237 responses.add(
238 "https://webdav.example.com/test_dir/test.txt",
239 "DELETE",
240 status=204,
241 )
242
243 await client.clean("/test_dir/test.txt")
244
245
246 async def test_get_property(client: Client, responses: aioresponses) -> None:
247 """Test get property."""
248 responses.add(
249 "https://webdav.example.com/test_dir/test.txt",
250 "PROPFIND",
251 headers={"Accept": "*/*", "Depth": "0"},
252 content_type="application/xml",
253 status=200,
254 body=load_responses("get_property.xml"),
255 )
256
257 prop = await client.get_property(
258 "/test_dir/test.txt", PropertyRequest(namespace="test", name="aProperty")
259 )
260 assert prop
261 assert prop.value == "aValue"
262
263
264 async def test_set_property(client: Client, responses: aioresponses) -> None:
265 """Test set property."""
266
267 def callback(_url: str, **kwargs: dict[str, Any]) -> CallbackResult:
268 assert kwargs["headers"]["Content-Type"].strip() == "text/xml"
269 assert kwargs["headers"]["Accept"].strip() == "*/*"
270 assert kwargs["headers"]["Depth"].strip() == "0"
271 assert kwargs["data"] == (
272 b"<?xml version='1.0' encoding='UTF-8'?>\n"
273 b'<propertyupdate xmlns="DAV:"><set><prop>'
274 b'<aProperty xmlns="test">aValue</aProperty>'
275 b"</prop></set></propertyupdate>"
276 )
277
278 return CallbackResult(status=207)
279
280 responses.add(
281 "https://webdav.example.com/test_dir/test.txt",
282 "PROPPATCH",
283 headers={"Accept": "*/*"},
284 callback=callback,
285 )
286
287 await client.set_property(
288 "/test_dir/test.txt",
289 Property(namespace="test", name="aProperty", value="aValue"),
290 )
291
292
293 async def test_mkdir(client: Client, responses: aioresponses) -> None:
294 """Test mkdir."""
295 responses.add(
296 "https://webdav.example.com/test_dir/",
297 "PROPFIND",
298 status=200,
299 body=load_responses("is_dir_file.xml"),
300 )
301 responses.add(
302 "https://webdav.example.com/test_dir/test_dir2/",
303 "MKCOL",
304 headers={"Accept": "*/*"},
305 status=201,
306 )
307
308 await client.mkdir("/test_dir/test_dir2")
309
310
311 async def test_free(client: Client, responses: aioresponses) -> None:
312 """Test free."""
313 responses.clear()
314 responses.add(
315 "https://webdav.example.com",
316 "PROPFIND",
317 headers={"Accept": "*/*", "Depth": "0"},
318 content_type="application/xml",
319 status=200,
320 body=load_responses("free_space.xml"),
321 )
322
323 free = await client.free()
324 assert free == 10737417543
325
326
327 async def test_free_not_supported(client: Client, responses: aioresponses) -> None:
328 """Test free not supported."""
329 responses.clear()
330 responses.add(
331 "https://webdav.example.com",
332 "PROPFIND",
333 headers={"Accept": "*/*", "Depth": "0"},
334 content_type="application/xml",
335 status=200,
336 body=load_responses("free_space_not_supported.xml"),
337 )
338
339 with pytest.raises(MethodNotSupportedError):
340 await client.free()
341
342
343 async def test_quota(client: Client, responses: aioresponses) -> None:
344 """Test quota returns both available and used bytes."""
345 responses.clear()
346 responses.add(
347 "https://webdav.example.com",
348 "PROPFIND",
349 headers={"Accept": "*/*", "Depth": "0"},
350 content_type="application/xml",
351 status=200,
352 body=load_responses("free_space.xml"),
353 )
354
355 info = await client.quota()
356 assert info == QuotaInfo(available_bytes=10737417543, used_bytes=697)
357
358
359 async def test_quota_not_supported(client: Client, responses: aioresponses) -> None:
360 """Test quota raises when server does not support quota properties."""
361 responses.clear()
362 responses.add(
363 "https://webdav.example.com",
364 "PROPFIND",
365 headers={"Accept": "*/*", "Depth": "0"},
366 content_type="application/xml",
367 status=200,
368 body=load_responses("free_space_not_supported.xml"),
369 )
370
371 with pytest.raises(MethodNotSupportedError):
372 await client.quota()
373
374
375 async def test_quota_used_only(client: Client, responses: aioresponses) -> None:
376 """Test quota when server only provides used bytes."""
377 responses.clear()
378 responses.add(
379 "https://webdav.example.com",
380 "PROPFIND",
381 headers={"Accept": "*/*", "Depth": "0"},
382 content_type="application/xml",
383 status=200,
384 body=load_responses("quota_used_only.xml"),
385 )
386
387 info = await client.quota()
388 assert info == QuotaInfo(available_bytes=None, used_bytes=697)
389
390
391 async def test_upload_iter(client: Client, responses: aioresponses) -> None:
392 """Test upload iter."""
393
394 async def callback(_url: str, **kwargs: Any) -> CallbackResult:
395 result = bytearray()
396 async for chunk in kwargs["data"]:
397 result += chunk
398 assert result == b"Hello, world!"
399 return CallbackResult(status=201)
400
401 responses.add(
402 "https://webdav.example.com/test_dir/test.txt",
403 "PUT",
404 headers={"Accept": "*/*"},
405 callback=callback,
406 )
407
408 async def stream() -> AsyncGenerator[bytes, None]:
409 yield b"Hello, "
410 yield b"world!"
411
412 await client.upload_iter(stream(), "/test_dir/test.txt")
413
414
415 async def test_upload_iter_progress(client: Client, responses: aioresponses) -> None:
416 """Test upload iter progress."""
417
418 async def callback(_url: str, **kwargs: Any) -> CallbackResult:
419 result = bytearray()
420 async for chunk in kwargs["data"]:
421 result += chunk
422 assert result == b"Hello, world!"
423 return CallbackResult(status=201)
424
425 responses.add(
426 "https://webdav.example.com/test_dir/test.txt",
427 "PUT",
428 headers={"Accept": "*/*"},
429 callback=callback,
430 )
431
432 progress_calls: list[tuple[int, int | None]] = []
433
434 def on_progress(current: int, total: int | None) -> None:
435 progress_calls.append((current, total))
436
437 async def stream() -> AsyncGenerator[bytes, None]:
438 yield b"Hello, "
439 yield b"world!"
440
441 await client.upload_iter(
442 stream(),
443 "/test_dir/test.txt",
444 content_length=13,
445 progress=on_progress,
446 )
447 assert progress_calls == [(0, 13), (7, 13), (13, 13)]
448
449
450 async def test_upload_iter_progress_no_content_length(
451 client: Client, responses: aioresponses
452 ) -> None:
453 """Test upload iter progress without content length."""
454
455 async def callback(_url: str, **kwargs: Any) -> CallbackResult:
456 result = bytearray()
457 async for chunk in kwargs["data"]:
458 result += chunk
459 assert result == b"Hello, world!"
460 return CallbackResult(status=201)
461
462 responses.add(
463 "https://webdav.example.com/test_dir/test.txt",
464 "PUT",
465 headers={"Accept": "*/*"},
466 callback=callback,
467 )
468
469 progress_calls: list[tuple[int, int | None]] = []
470
471 def on_progress(current: int, total: int | None) -> None:
472 progress_calls.append((current, total))
473
474 async def stream() -> AsyncGenerator[bytes, None]:
475 yield b"Hello, "
476 yield b"world!"
477
478 await client.upload_iter(
479 stream(),
480 "/test_dir/test.txt",
481 progress=on_progress,
482 )
483 assert progress_calls == [(0, None), (7, None), (13, None)]
484
485
486 async def test_upload_iter_progress_unsupported_buffer(
487 client: Client, responses: aioresponses, caplog: pytest.LogCaptureFixture
488 ) -> None:
489 """Test upload iter progress logs warning for unsupported buffer."""
490 responses.add(
491 "https://webdav.example.com/test_dir/test.txt",
492 "PUT",
493 headers={"Accept": "*/*"},
494 status=201,
495 )
496
497 progress_calls: list[tuple[int, int | None]] = []
498
499 def on_progress(current: int, total: int | None) -> None:
500 progress_calls.append((current, total))
501
502 caplog.set_level("WARNING", logger="aiowebdav2.client")
503 await client.upload_iter(
504 io.BytesIO(b"Hello, world!"),
505 "/test_dir/test.txt",
506 content_length=13,
507 progress=on_progress,
508 )
509
510 assert not progress_calls
511 assert any(
512 (
513 "Progress callback is only supported for AsyncIterator buffers, "
514 "ignoring progress for BytesIO"
515 )
516 in record.getMessage()
517 for record in caplog.records
518 )
519
520
521 async def test_download_iter(client: Client, responses: aioresponses) -> None:
522 """Test download iter."""
523
524 async def callback(_url: str, **_kwargs: dict[str, Any]) -> CallbackResult:
525 return CallbackResult(status=200, body=b"Hello, world!")
526
527 responses.add(
528 "https://webdav.example.com/test_dir/test.txt",
529 "GET",
530 headers={"Accept": "*/*"},
531 callback=callback,
532 )
533 responses.add(
534 "https://webdav.example.com/test_dir/test.txt",
535 "PROPFIND",
536 headers={"Accept": "*/*", "Depth": "0"},
537 content_type="application/xml",
538 status=200,
539 body=load_responses("is_dir_file.xml"),
540 )
541
542 async for chunk in await client.download_iter("/test_dir/test.txt"):
543 assert chunk == b"Hello, world!"
544
545
546 async def test_move(client: Client, responses: aioresponses) -> None:
547 """Test move."""
548 responses.add(
549 "https://webdav.example.com/test_dir/test.txt",
550 "MOVE",
551 headers={
552 "Accept": "*/*",
553 "Destination": "https://webdav.example.com/test_dir/test2.txt",
554 },
555 status=201,
556 )
557
558 await client.move("/test_dir/test.txt", "/test_dir/test2.txt")
559
560
561 async def test_check(client: Client, responses: aioresponses) -> None:
562 """Test check."""
563 responses.add(
564 "https://webdav.example.com/test_dir/test.txt",
565 "PROPFIND",
566 headers={"Accept": "*/*", "Depth": "0"},
567 content_type="application/xml",
568 status=200,
569 body=load_responses("is_dir_file.xml"),
570 )
571
572 assert await client.check("/test_dir/test.txt")
573
574
575 async def test_copy(client: Client, responses: aioresponses) -> None:
576 """Test copy."""
577 responses.add(
578 "https://webdav.example.com/test_dir/test.txt",
579 "COPY",
580 headers={
581 "Accept": "*/*",
582 "Destination": "https://webdav.example.com/test_dir/test2.txt",
583 },
584 status=201,
585 )
586 responses.add(
587 "https://webdav.example.com/test_dir/test.txt",
588 "PROPFIND",
589 headers={"Accept": "*/*", "Depth": "0"},
590 content_type="application/xml",
591 status=200,
592 body=load_responses("is_dir_file.xml"),
593 )
594
595 await client.copy("/test_dir/test.txt", "/test_dir/test2.txt")
596
597
598 async def test_is_dir_not_supported(client: Client, responses: aioresponses) -> None:
599 """Test is_dir not supported."""
600 responses.add(
601 "https://webdav.example.com/test_dir/",
602 "PROPFIND",
603 headers={"Accept": "*/*", "Depth": "0"},
604 content_type="application/xml",
605 status=200,
606 body=load_responses("is_dir_directory_not_supported.xml"),
607 )
608
609 with pytest.raises(MethodNotSupportedError):
610 await client.is_dir("/test_dir/")
611
612
613 async def test_get_properties(client: Client, responses: aioresponses) -> None:
614 """Test get properties."""
615 responses.add(
616 "https://webdav.example.com/test_dir/test.txt",
617 "PROPFIND",
618 headers={"Accept": "*/*", "Depth": "0"},
619 content_type="application/xml",
620 status=200,
621 body=load_responses("get_property.xml"),
622 )
623
624 props = await client.get_properties(
625 "/test_dir/test.txt",
626 [
627 PropertyRequest(namespace="test", name="aProperty"),
628 PropertyRequest(namespace="test2", name="anotherProperty"),
629 ],
630 )
631 assert props == [
632 Property(
633 name="aProperty",
634 namespace="test",
635 value="aValue",
636 ),
637 Property(
638 name="anotherProperty",
639 namespace="test2",
640 value="anotherValue",
641 ),
642 ]
643
644
645 async def test_client_with_internal_session() -> None:
646 """Test client with internal session."""
647 async with Client(
648 url="https://webdav.example.com",
649 username="user",
650 password="password",
651 ) as c:
652 assert c._session is not None
653
654 assert c._session.closed
655
656
657 async def test_client_with_external_session() -> None:
658 """Test client with external session."""
659 external_session = aiohttp.ClientSession()
660 async with Client(
661 url="https://webdav.example.com",
662 username="user",
663 password="password",
664 options=ClientOptions(session=external_session),
665 ) as c:
666 assert c._session is not None
667 assert c._session is external_session
668
669 assert not c._session.closed
670
671 await external_session.close()
672 assert external_session.closed
673 assert c._session.closed
674
675
676 async def test_unauthorized(client: Client, responses: aioresponses) -> None:
677 """Test unauthorized."""
678 responses.add(
679 "https://webdav.example.com/test_dir/test.txt",
680 "PROPFIND",
681 headers={"Accept": "*/*", "Depth": "0"},
682 content_type="application/xml",
683 status=401,
684 )
685
686 with pytest.raises(
687 UnauthorizedError,
688 match=re.escape("Unauthorized access to https://webdav.example.com"),
689 ):
690 await client.info("/test_dir/test.txt")
691
692
693 async def test_access_denied(client: Client, responses: aioresponses) -> None:
694 """Test access denied."""
695 responses.add(
696 "https://webdav.example.com/test_dir/test.txt",
697 "PROPFIND",
698 headers={"Accept": "*/*", "Depth": "0"},
699 content_type="application/xml",
700 status=403,
701 )
702
703 with pytest.raises(
704 AccessDeniedError,
705 match=re.escape("Access denied to https://webdav.example.com"),
706 ):
707 await client.info("/test_dir/test.txt")
708
709
710 async def test_upload_iter_content_length(
711 client: Client, responses: aioresponses
712 ) -> None:
713 """Test upload iter with content length."""
714
715 async def callback(_url: str, **kwargs: Any) -> CallbackResult:
716 assert kwargs["headers"]["Content-Length"].strip() == "12"
717 return CallbackResult(status=201)
718
719 responses.add(
720 "https://webdav.example.com/test_dir/test.txt",
721 "PUT",
722 headers={"Accept": "*/*"},
723 callback=callback,
724 )
725
726 await client.upload_iter(upload_stream(), "/test_dir/test.txt", content_length=12)
727
728
729 async def test_upload_iter_not_enough_space(
730 client: Client, responses: aioresponses
731 ) -> None:
732 """Test upload iter with not enough space."""
733 responses.add(
734 "https://webdav.example.com/test_dir/test.txt",
735 "PUT",
736 headers={"Accept": "*/*"},
737 status=507,
738 )
739
740 with pytest.raises(NotEnoughSpaceError):
741 await client.upload_iter(
742 upload_stream(), "/test_dir/test.txt", content_length=12
743 )
744
745
746 async def test_upload_iter_on_dir_fails(
747 client: Client, responses: aioresponses
748 ) -> None:
749 """Test upload iter on a directory."""
750 responses.add(
751 "https://webdav.example.com/test_dir/",
752 "PUT",
753 headers={"Accept": "*/*"},
754 status=409,
755 )
756
757 with pytest.raises(OptionNotValidError):
758 await client.upload_iter(upload_stream(), "/test_dir/")
759
760
761 async def test_upload_iter_parent_missing(responses: aioresponses) -> None:
762 """Test upload iter on a directory."""
763 responses.add(
764 "https://webdav.example.com/test_dir/test.txt",
765 "PUT",
766 headers={"Accept": "*/*"},
767 status=409,
768 )
769 responses.add(
770 "https://webdav.example.com/test_dir/",
771 "PROPFIND",
772 headers={"Accept": "*/*"},
773 status=404,
774 )
775 responses.add(
776 "https://webdav.example.com/",
777 "PROPFIND",
778 headers={"Accept": "*/*"},
779 status=207,
780 )
781
782 async with Client(
783 url="https://webdav.example.com",
784 username="user",
785 password="password",
786 ) as client:
787 with pytest.raises(
788 RemoteParentNotFoundError,
789 match=re.escape("Remote parent for: /test_dir/test.txt not found"),
790 ):
791 await client.upload_iter(upload_stream(), "/test_dir/test.txt")
792
793
794 async def test_prune_paths_helper() -> None:
795 """Test prune paths helper."""
796 assert _prune_paths(["/root/file", "/root/dir"], "/root/") == [
797 "file",
798 "dir",
799 ]
800
801
802 async def test_get_headers_with_token() -> None:
803 """Test get headers with token."""
804 async with Client(
805 url="https://webdav.example.com",
806 username="",
807 password="",
808 options=ClientOptions(token="mytoken"),
809 ) as client:
810 headers = client.get_headers("list")
811 assert headers["Authorization"] == "Bearer mytoken"
812
813
814 async def test_execute_request_connection_error(responses: aioresponses) -> None:
815 """Test execute request connection error."""
816 responses.add(
817 "https://webdav.example.com/fail",
818 "PROPFIND",
819 exception=aiohttp.ClientConnectionError(),
820 )
821 async with Client(
822 url="https://webdav.example.com", username="u", password="p"
823 ) as client:
824 with pytest.raises(NoConnectionError):
825 await client.check("/fail")
826
827
828 async def test_execute_request_response_error(responses: aioresponses) -> None:
829 """Test execute request response error."""
830 responses.add(
831 "https://webdav.example.com/fail",
832 "PROPFIND",
833 exception=aiohttp.ClientResponseError(
834 request_info=aiohttp.RequestInfo(
835 url=yarl.URL("https://webdav.example.com/fail"),
836 method="PROPFIND",
837 headers=CIMultiDictProxy(CIMultiDict()),
838 real_url=yarl.URL("https://webdav.example.com/fail"),
839 ),
840 history=(),
841 ),
842 )
843 async with Client(
844 url="https://webdav.example.com", username="u", password="p"
845 ) as client:
846 with pytest.raises(ConnectionExceptionError):
847 await client.check("/fail")
848
849
850 async def test_execute_request_locked(responses: aioresponses) -> None:
851 """Test execute request locked."""
852 responses.add(
853 "https://webdav.example.com/locked.txt",
854 "PROPFIND",
855 status=423,
856 )
857 async with Client(
858 url="https://webdav.example.com", username="u", password="p"
859 ) as client:
860 with pytest.raises(ResourceLockedError):
861 await client.check("/locked.txt")
862
863
864 async def test_execute_request_method_not_supported(responses: aioresponses) -> None:
865 """Test execute request method not supported."""
866 responses.add(
867 "https://webdav.example.com/method.txt",
868 "PROPFIND",
869 status=405,
870 )
871 async with Client(
872 url="https://webdav.example.com", username="u", password="p"
873 ) as client:
874 with pytest.raises(MethodNotSupportedError):
875 await client.check("/method.txt")
876
877
878 async def test_execute_request_generic_error(responses: aioresponses) -> None:
879 """Test execute request generic error."""
880 responses.add(
881 "https://webdav.example.com/error.txt",
882 "PROPFIND",
883 status=418,
884 body=b"teapot",
885 )
886 async with Client(
887 url="https://webdav.example.com", username="u", password="p"
888 ) as client:
889 with pytest.raises(ResponseErrorCodeError):
890 await client.check("/error.txt")
891
892
893 async def test_list_with_infos_recursive(
894 client: Client, responses: aioresponses
895 ) -> None:
896 """Test list with infos recursive."""
897 responses.clear()
898 responses.add(
899 "https://webdav.example.com/test_dir/",
900 "PROPFIND",
901 headers={"Accept": "*/*", "Depth": "infinity"},
902 content_type="application/xml",
903 status=200,
904 body=load_responses("get_list_recursive.xml"),
905 )
906
907 files = await client.list_with_infos("/test_dir/", recursive=True)
908 assert len(files) == 3
909 assert files[0]["path"].startswith("/test_dir/")
910
911
912 async def test_list_with_properties_none(
913 client: Client, responses: aioresponses
914 ) -> None:
915 """Test list with properties none."""
916 responses.clear()
917 responses.add(
918 "https://webdav.example.com/",
919 "PROPFIND",
920 headers={"Accept": "*/*", "Depth": "1"},
921 content_type="application/xml",
922 status=207,
923 body=load_responses("list_with_properties.xml"),
924 )
925 props = await client.list_with_properties(properties=None)
926 assert "/test_dir/test.txt" in props
927
928
929 async def test_stream_with_progress_sync_and_async(
930 client: Client, responses: aioresponses
931 ) -> None:
932 """Test stream with progress sync and async."""
933 responses.add(
934 "https://webdav.example.com/test.txt",
935 "GET",
936 body=b"content",
937 headers={"content-length": "7"},
938 status=200,
939 )
940 response = await client.execute_request("download", "/test.txt")
941 output = io.BytesIO()
942 sync_calls = []
943
944 def sync_progress(current: int, total: int | None) -> None:
945 sync_calls.append((current, total))
946
947 await client._stream_with_progress(response, output.write, sync_progress)
948 assert output.getvalue() == b"content"
949 assert sync_calls[0] == (0, 7)
950
951 responses.add(
952 "https://webdav.example.com/test2.txt",
953 "GET",
954 body=b"async",
955 headers={"content-length": "5"},
956 status=200,
957 )
958 response_async = await client.execute_request("download", "/test2.txt")
959 output_async = io.BytesIO()
960 async_calls = []
961
962 async def async_progress(current: int, total: int | None) -> None:
963 async_calls.append((current, total))
964
965 await client._stream_with_progress(
966 response_async, output_async.write, async_progress
967 )
968 assert output_async.getvalue() == b"async"
969 assert async_calls[0] == (0, 5)
970
971
972 async def test_download_from_with_progress(
973 client: Client, responses: aioresponses
974 ) -> None:
975 """Test download from with progress."""
976 responses.add(
977 "https://webdav.example.com/test.txt",
978 "GET",
979 body=b"file content",
980 headers={"content-length": "12"},
981 status=200,
982 )
983 progress_calls = []
984
985 def on_progress(current: int, total: int | None) -> None:
986 progress_calls.append((current, total))
987
988 buff = io.BytesIO()
989 await client.download_from(buff, "/test.txt", progress=on_progress)
990 assert buff.getvalue() == b"file content"
991 assert progress_calls[0] == (0, 12)
992
993
994 async def test_download_dispatch_file_and_dir(
995 client: Client, responses: aioresponses, tmp_path: Any
996 ) -> None:
997 """Test download dispatch file and dir."""
998 responses.add(
999 "https://webdav.example.com/test_dir/",
1000 "PROPFIND",
1001 headers={"Accept": "*/*", "Depth": "1"},
1002 content_type="application/xml",
1003 status=200,
1004 body=load_responses("get_list.xml"),
1005 )
1006 responses.add(
1007 "https://webdav.example.com/test_dir/test.txt",
1008 "GET",
1009 body=b"file content",
1010 headers={"content-length": "12"},
1011 status=200,
1012 )
1013 responses.add(
1014 "https://webdav.example.com/test.txt",
1015 "GET",
1016 body=b"root file",
1017 headers={"content-length": "9"},
1018 status=200,
1019 )
1020
1021 local_dir = Path(tmp_path) / "download_dir"
1022 await client.download("/test_dir/", local_dir)
1023 assert ((local_dir / "test.txt").read_bytes()) == b"file content"
1024
1025 local_file = Path(tmp_path) / "test.txt"
1026 await client.download("/test.txt", local_file)
1027 assert (local_file.read_bytes()) == b"root file"
1028
1029
1030 async def test_download_directory_removes_existing(
1031 client: Client, responses: aioresponses, tmp_path: Any
1032 ) -> None:
1033 """Test download directory removes existing."""
1034 responses.add(
1035 "https://webdav.example.com/test_dir/",
1036 "PROPFIND",
1037 headers={"Accept": "*/*", "Depth": "1"},
1038 content_type="application/xml",
1039 status=200,
1040 body=load_responses("get_list.xml"),
1041 )
1042 responses.add(
1043 "https://webdav.example.com/test_dir/test.txt",
1044 "GET",
1045 body=b"file content",
1046 headers={"content-length": "12"},
1047 status=200,
1048 )
1049
1050 local_dir = Path(tmp_path) / "download_dir"
1051 local_dir.mkdir(parents=True)
1052 (local_dir / "old.txt").write_text("old")
1053
1054 await client.download_directory("/test_dir/", local_dir)
1055 assert not (local_dir / "old.txt").exists()
1056 assert (local_dir / "test.txt").exists()
1057
1058
1059 async def test_download_file_rejects_directory(client: Client, tmp_path: Any) -> None:
1060 """Test download file rejects directory."""
1061 local_dir = Path(tmp_path) / "target_dir"
1062 local_dir.mkdir(parents=True)
1063 with pytest.raises(OptionNotValidError):
1064 await client.download_file("/test.txt", local_dir)
1065
1066
1067 async def test_upload_dispatch_file_and_dir(
1068 client: Client, responses: aioresponses, tmp_path: Any
1069 ) -> None:
1070 """Test upload dispatch file and dir."""
1071 local_dir = Path(tmp_path) / "upload_dir"
1072 local_dir.mkdir(parents=True)
1073 local_file = local_dir / "test.txt"
1074 local_file.write_text("content")
1075 responses.add(
1076 "https://webdav.example.com/test_dir/",
1077 "MKCOL",
1078 headers={"Accept": "*/*", "Connection": "Keep-Alive"},
1079 status=201,
1080 )
1081
1082 def upload_callback(_url: str, **_kwargs: dict[str, Any]) -> CallbackResult:
1083 return CallbackResult(status=201)
1084
1085 responses.add(
1086 re.compile(r"https://webdav\.example\.com/test_dir/.+"),
1087 "PUT",
1088 headers={"Accept": "*/*"},
1089 callback=upload_callback,
1090 )
1091 await client.upload("/test_dir/", local_dir)
1092
1093 responses.add(
1094 "https://webdav.example.com/test.txt",
1095 "PUT",
1096 headers={"Accept": "*/*"},
1097 status=201,
1098 )
1099 await client.upload("/test.txt", local_file)
1100
1101
1102 async def test_upload_directory_validations(
1103 client: Client, responses: aioresponses, tmp_path: Any
1104 ) -> None:
1105 """Test upload directory validations."""
1106 local_dir = Path(tmp_path) / "local"
1107 with pytest.raises(LocalResourceNotFoundError):
1108 await client.upload_directory("/test_dir", local_dir)
1109
1110 local_dir.mkdir(parents=True)
1111 with pytest.raises(LocalResourceNotFoundError):
1112 await client.upload_directory("/test_dir/", local_dir / "file.txt")
1113
1114 missing_dir = Path(tmp_path) / "missing"
1115 with pytest.raises(LocalResourceNotFoundError):
1116 await client.upload_directory("/test_dir/", missing_dir)
1117
1118 responses.add(
1119 "https://webdav.example.com/test_dir/",
1120 "MKCOL",
1121 headers={"Accept": "*/*", "Connection": "Keep-Alive"},
1122 status=201,
1123 )
1124 (local_dir / "one.txt").write_text("one")
1125 responses.add(
1126 re.compile(r"https://webdav\.example\.com/test_dir/.+"),
1127 "PUT",
1128 headers={"Accept": "*/*"},
1129 status=201,
1130 )
1131 await client.upload_directory("/test_dir/", local_dir)
1132
1133
1134 async def test_upload_directory_uses_filename_not_full_path(
1135 client: Client, responses: aioresponses, tmp_path: Any
1136 ) -> None:
1137 """Test upload directory constructs remote paths from filename, not full local path."""
1138 local_dir = Path(tmp_path) / "upload_src"
1139 local_dir.mkdir(parents=True)
1140 (local_dir / "hello.txt").write_text("data")
1141
1142 responses.add(
1143 "https://webdav.example.com/dest/",
1144 "MKCOL",
1145 status=201,
1146 )
1147
1148 uploaded_urls: list[str] = []
1149
1150 def upload_callback(_url: str, **_kwargs: dict[str, Any]) -> CallbackResult:
1151 uploaded_urls.append(str(_url))
1152 return CallbackResult(status=201)
1153
1154 responses.add(
1155 re.compile(r"https://webdav\.example\.com/dest/.+"),
1156 "PUT",
1157 callback=upload_callback,
1158 )
1159
1160 await client.upload_directory("/dest/", local_dir)
1161
1162 assert len(uploaded_urls) == 1
1163 assert uploaded_urls[0] == "https://webdav.example.com/dest/hello.txt"
1164
1165
1166 async def test_upload_file_progress_and_force(
1167 responses: aioresponses, tmp_path: Any
1168 ) -> None:
1169 """Test upload file progress and force."""
1170 local_path = Path(tmp_path) / "file.txt"
1171 local_path.write_text("content")
1172
1173 responses.add(
1174 "https://webdav.example.com/test_dir/",
1175 "MKCOL",
1176 headers={"Accept": "*/*", "Connection": "Keep-Alive"},
1177 status=201,
1178 )
1179
1180 async def upload_callback(_url: str, **kwargs: dict[str, Any]) -> CallbackResult:
1181 data = kwargs.get("data")
1182 if isinstance(data, AsyncIterable):
1183 async for _chunk in data:
1184 pass
1185 return CallbackResult(status=201)
1186
1187 responses.add(
1188 "https://webdav.example.com/test_dir/file.txt",
1189 "PUT",
1190 headers={"Accept": "*/*"},
1191 callback=upload_callback,
1192 )
1193 responses.add(
1194 "https://webdav.example.com/test_dir/file.txt",
1195 "PUT",
1196 headers={"Accept": "*/*"},
1197 callback=upload_callback,
1198 )
1199
1200 progress_calls = []
1201
1202 def on_progress(current: int, total: int | None) -> None:
1203 progress_calls.append((current, total))
1204
1205 async with Client(
1206 url="https://webdav.example.com", username="u", password="p"
1207 ) as temp_client:
1208 await temp_client.upload_file(
1209 "/test_dir/file.txt", local_path, progress=on_progress, force=True
1210 )
1211 assert progress_calls[0][0] == 0
1212
1213
1214 async def test_upload_file_validations(client: Client, tmp_path: Any) -> None:
1215 """Test upload file validations."""
1216 local_missing = Path(tmp_path) / "missing.txt"
1217 with pytest.raises(LocalResourceNotFoundError):
1218 await client.upload_file("/test.txt", local_missing)
1219
1220 local_dir = Path(tmp_path) / "dir"
1221 local_dir.mkdir(parents=True)
1222 with pytest.raises(OptionNotValidError):
1223 await client.upload_file("/test.txt", local_dir)
1224
1225 local_file = Path(tmp_path) / "file.txt"
1226 local_file.write_text("content")
1227 with pytest.raises(OptionNotValidError):
1228 await client.upload_file("/test_dir/", local_file)
1229
1230
1231 async def test_copy_directory_adds_depth(
1232 client: Client, responses: aioresponses
1233 ) -> None:
1234 """Test copy directory adds depth."""
1235 responses.add(
1236 "https://webdav.example.com/test_dir/",
1237 "PROPFIND",
1238 headers={"Accept": "*/*", "Depth": "0"},
1239 content_type="application/xml",
1240 status=200,
1241 body=load_responses("is_dir_directory.xml"),
1242 )
1243
1244 def callback(_url: str, **kwargs: dict[str, Any]) -> CallbackResult:
1245 assert kwargs["headers"]["Depth"] == "2"
1246 return CallbackResult(status=201)
1247
1248 responses.add(
1249 "https://webdav.example.com/test_dir/",
1250 "COPY",
1251 headers={"Accept": "*/*"},
1252 callback=callback,
1253 )
1254 await client.copy("/test_dir/", "/test_dir_copy/", depth=2)
1255
1256
1257 async def test_lock_and_lock_client_headers(
1258 client: Client, responses: aioresponses
1259 ) -> None:
1260 """Test lock and lock client headers."""
1261 responses.add(
1262 "https://webdav.example.com/test_dir/",
1263 "LOCK",
1264 headers={"Lock-Token": "<token123>"},
1265 status=200,
1266 )
1267 responses.add(
1268 "https://webdav.example.com/test_dir/",
1269 "UNLOCK",
1270 status=204,
1271 )
1272
1273 lock_client = await client.lock("/test_dir/")
1274 headers = lock_client.get_headers("check")
1275 assert headers["Lock-Token"] == "<token123>"
1276 assert headers["If"] == "(<token123>)"
1277 await lock_client.__aexit__()
1278
1279
1280 async def test_lock_with_timeout_header(
1281 client: Client, responses: aioresponses
1282 ) -> None:
1283 """Test lock with timeout header."""
1284
1285 def callback(_url: str, **kwargs: dict[str, Any]) -> CallbackResult:
1286 assert kwargs["headers"]["Timeout"] == "Second-10"
1287 return CallbackResult(status=200, headers={"Lock-Token": "<token>"})
1288
1289 responses.add(
1290 "https://webdav.example.com/test_dir/",
1291 "LOCK",
1292 headers={"Lock-Token": "<token>"},
1293 callback=callback,
1294 )
1295 responses.add(
1296 "https://webdav.example.com/test_dir/",
1297 "UNLOCK",
1298 status=204,
1299 )
1300
1301 lock_client = await client.lock("/test_dir/", timeout=10)
1302 await lock_client.__aexit__()
1303
1304
1305 async def test_resource_factory(client: Client) -> None:
1306 """Test resource factory."""
1307 resource = client.resource("/test_dir/test.txt")
1308 assert str(resource) == "resource /test_dir/test.txt"
1309
1310
1311 async def test_is_local_more_recent(
1312 client: Client, responses: aioresponses, tmp_path: Any
1313 ) -> None:
1314 """Test is local more recent."""
1315 responses.add(
1316 "https://webdav.example.com/test_dir/test.txt",
1317 "PROPFIND",
1318 headers={"Accept": "*/*", "Depth": "1"},
1319 content_type="application/xml",
1320 status=200,
1321 body=load_responses("get_info.xml"),
1322 )
1323 local_path = Path(tmp_path) / "test.txt"
1324 local_path.write_text("content")
1325 now = time.time() + 10
1326 os.utime(str(local_path), (now, now))
1327 assert await client.is_local_more_recent(local_path, "/test_dir/test.txt")
1328
1329
1330 async def test_is_local_more_recent_error(
1331 client: Client, responses: aioresponses, tmp_path: Any
1332 ) -> None:
1333 """Test is local more recent error."""
1334 responses.add(
1335 "https://webdav.example.com/test_dir/test.txt",
1336 "PROPFIND",
1337 headers={"Accept": "*/*", "Depth": "1"},
1338 content_type="application/xml",
1339 status=200,
1340 body=load_responses("get_info.xml"),
1341 )
1342 local_path = Path(tmp_path) / "test.txt"
1343 local_path.write_text("content")
1344 local_path = Path(tmp_path) / "missing.txt"
1345 with pytest.raises(FileNotFoundError):
1346 await client.is_local_more_recent(local_path, "/test_dir/test.txt")
1347
1348
1349 async def test_push_pull_sync(
1350 client: Client, responses: aioresponses, tmp_path: Any
1351 ) -> None:
1352 """Test push pull sync."""
1353 local_dir = Path(tmp_path) / "local"
1354 local_dir.mkdir(parents=True)
1355 local_file = local_dir / "local.txt"
1356 local_file.write_text("content")
1357
1358 responses.add(
1359 "https://webdav.example.com/remote/",
1360 "PROPFIND",
1361 headers={"Accept": "*/*", "Depth": "0"},
1362 content_type="application/xml",
1363 status=200,
1364 body=load_responses("is_dir_directory.xml").replace("/test_dir/", "/remote/"),
1365 )
1366 responses.add(
1367 "https://webdav.example.com/remote/",
1368 "PROPFIND",
1369 headers={"Accept": "*/*", "Depth": "0"},
1370 content_type="application/xml",
1371 status=200,
1372 body=load_responses("is_dir_directory.xml").replace("/test_dir/", "/remote/"),
1373 )
1374 responses.add(
1375 "https://webdav.example.com/remote/",
1376 "PROPFIND",
1377 headers={"Accept": "*/*", "Depth": "0"},
1378 content_type="application/xml",
1379 status=200,
1380 body=load_responses("is_dir_directory.xml").replace("/test_dir/", "/remote/"),
1381 )
1382 list_body_sync = (
1383 '<?xml version="1.0" encoding="utf-8"?>'
1384 '<D:multistatus xmlns:D="DAV:">'
1385 "<D:response><D:href>/remote/</D:href>"
1386 "<D:propstat><D:prop><D:resourcetype><D:collection/>"
1387 "</D:resourcetype></D:prop></D:propstat></D:response>"
1388 "</D:multistatus>"
1389 )
1390 responses.add(
1391 "https://webdav.example.com/remote/",
1392 "PROPFIND",
1393 headers={"Accept": "*/*", "Depth": "1"},
1394 content_type="application/xml",
1395 status=200,
1396 body=list_body_sync,
1397 )
1398 responses.add(
1399 "https://webdav.example.com/remote/local.txt",
1400 "GET",
1401 status=200,
1402 body=b"remote",
1403 headers={"content-length": "6"},
1404 )
1405 responses.add(
1406 "https://webdav.example.com/remote/local.txt",
1407 "GET",
1408 status=200,
1409 body=b"remote",
1410 headers={"content-length": "6"},
1411 )
1412 responses.add(
1413 "https://webdav.example.com/remote/local.txt",
1414 "GET",
1415 status=200,
1416 body=b"remote",
1417 headers={"content-length": "6"},
1418 )
1419 responses.add(
1420 "https://webdav.example.com/remote/local.txt",
1421 "GET",
1422 status=200,
1423 body=b"remote",
1424 headers={"content-length": "6"},
1425 )
1426 responses.add(
1427 "https://webdav.example.com/remote/",
1428 "PROPFIND",
1429 headers={"Accept": "*/*", "Depth": "1"},
1430 content_type="application/xml",
1431 status=200,
1432 body=list_body_sync,
1433 )
1434 responses.add(
1435 "https://webdav.example.com/remote/local.txt",
1436 "PROPFIND",
1437 headers={"Accept": "*/*", "Depth": "1"},
1438 content_type="application/xml",
1439 status=200,
1440 body=load_responses("get_info.xml").replace(
1441 "/test_dir/test.txt", "/remote/local.txt"
1442 ),
1443 )
1444 responses.add(
1445 re.compile(r"https://webdav\.example\.com/remote/.+"),
1446 "PUT",
1447 headers={"Accept": "*/*"},
1448 status=201,
1449 )
1450 responses.add(
1451 "https://webdav.example.com/remote/local.txt",
1452 "GET",
1453 status=200,
1454 body=b"remote",
1455 headers={"content-length": "6"},
1456 )
1457
1458 updated = await client.push("/remote/", local_dir)
1459 assert updated
1460
1461 updated = await client.pull("/remote/", local_dir)
1462 assert updated is False
1463
1464 responses.add(
1465 "https://webdav.example.com/remote/",
1466 "PROPFIND",
1467 headers={"Accept": "*/*", "Depth": "0"},
1468 content_type="application/xml",
1469 status=200,
1470 body=load_responses("is_dir_directory.xml").replace("/test_dir/", "/remote/"),
1471 )
1472 responses.add(
1473 "https://webdav.example.com/remote/",
1474 "PROPFIND",
1475 headers={"Accept": "*/*", "Depth": "0"},
1476 content_type="application/xml",
1477 status=200,
1478 body=load_responses("is_dir_directory.xml").replace("/test_dir/", "/remote/"),
1479 )
1480 responses.add(
1481 "https://webdav.example.com/remote/",
1482 "PROPFIND",
1483 headers={"Accept": "*/*", "Depth": "1"},
1484 content_type="application/xml",
1485 status=200,
1486 body=list_body_sync,
1487 )
1488 responses.add(
1489 re.compile(r"https://webdav\.example\.com/remote/.+"),
1490 "PUT",
1491 headers={"Accept": "*/*"},
1492 status=201,
1493 )
1494 with pytest.raises(OSError, match=r".+"):
1495 await client.sync("/remote/", local_dir)
1496
1497
1498 async def test_publish_unpublish(client: Client, responses: aioresponses) -> None:
1499 """Test publish unpublish."""
1500 responses.add(
1501 "https://webdav.example.com/test.txt",
1502 "PROPPATCH",
1503 headers={"Accept": "*/*", "Depth": "0"},
1504 status=207,
1505 )
1506 responses.add(
1507 "https://webdav.example.com/test.txt",
1508 "PROPPATCH",
1509 headers={"Accept": "*/*", "Depth": "0"},
1510 status=207,
1511 )
1512
1513 await client.publish("/test.txt")
1514 await client.unpublish("/test.txt")
1515
1516
1517 async def test_download_directory_concurrent(
1518 client: Client, responses: aioresponses, tmp_path: Any
1519 ) -> None:
1520 """Test download directory with concurrency > 1 downloads all files."""
1521 responses.add(
1522 "https://webdav.example.com/test_dir/",
1523 "PROPFIND",
1524 headers={"Accept": "*/*", "Depth": "1"},
1525 content_type="application/xml",
1526 status=200,
1527 body=load_responses("get_list_multiple.xml"),
1528 )
1529 for name in ("a.txt", "b.txt", "c.txt"):
1530 responses.add(
1531 f"https://webdav.example.com/test_dir/{name}",
1532 "GET",
1533 body=f"{name} content".encode(),
1534 headers={"content-length": str(len(f"{name} content"))},
1535 status=200,
1536 )
1537
1538 local_dir = Path(tmp_path) / "concurrent_dl"
1539 await client.download_directory("/test_dir/", local_dir, concurrency=3)
1540
1541 for name in ("a.txt", "b.txt", "c.txt"):
1542 assert (local_dir / name).exists()
1543 assert (local_dir / name).read_text() == f"{name} content"
1544
1545
1546 async def test_upload_directory_concurrent(
1547 client: Client, responses: aioresponses, tmp_path: Any
1548 ) -> None:
1549 """Test upload directory with concurrency > 1 uploads all files."""
1550 local_dir = Path(tmp_path) / "concurrent_ul"
1551 local_dir.mkdir(parents=True)
1552 for name in ("a.txt", "b.txt", "c.txt"):
1553 (local_dir / name).write_text(f"{name} content")
1554
1555 responses.add(
1556 "https://webdav.example.com/test_dir/",
1557 "MKCOL",
1558 headers={"Accept": "*/*", "Connection": "Keep-Alive"},
1559 status=201,
1560 )
1561 uploaded_urls: list[str] = []
1562
1563 def upload_callback(_url: str, **_kwargs: dict[str, Any]) -> CallbackResult:
1564 uploaded_urls.append(str(_url))
1565 return CallbackResult(status=201)
1566
1567 responses.add(
1568 re.compile(r"https://webdav\.example\.com/test_dir/.+"),
1569 "PUT",
1570 headers={"Accept": "*/*"},
1571 callback=upload_callback,
1572 )
1573 # Must add enough responses for 3 files
1574 responses.add(
1575 re.compile(r"https://webdav\.example\.com/test_dir/.+"),
1576 "PUT",
1577 headers={"Accept": "*/*"},
1578 callback=upload_callback,
1579 )
1580 responses.add(
1581 re.compile(r"https://webdav\.example\.com/test_dir/.+"),
1582 "PUT",
1583 headers={"Accept": "*/*"},
1584 callback=upload_callback,
1585 )
1586
1587 await client.upload_directory("/test_dir/", local_dir, concurrency=3)
1588
1589 assert len(uploaded_urls) == 3
1590
1591
1592 async def test_download_directory_rejects_invalid_concurrency(
1593 client: Client, tmp_path: Any
1594 ) -> None:
1595 """Test download_directory rejects concurrency < 1."""
1596 local_dir = Path(tmp_path) / "dl"
1597 with pytest.raises(OptionNotValidError):
1598 await client.download_directory("/test_dir/", local_dir, concurrency=0)
1599 with pytest.raises(OptionNotValidError):
1600 await client.download_directory("/test_dir/", local_dir, concurrency=-1)
1601
1602
1603 async def test_upload_directory_rejects_invalid_concurrency(
1604 client: Client, tmp_path: Any
1605 ) -> None:
1606 """Test upload_directory rejects concurrency < 1."""
1607 local_dir = Path(tmp_path) / "ul"
1608 local_dir.mkdir(parents=True)
1609 with pytest.raises(OptionNotValidError):
1610 await client.upload_directory("/test_dir/", local_dir, concurrency=0)
1611 with pytest.raises(OptionNotValidError):
1612 await client.upload_directory("/test_dir/", local_dir, concurrency=-1)