Repository navigation
Expand file tree
/
Copy pathtest_pathroot.py
More file actions
553 lines (403 loc) · 14.9 KB
/
Copy pathtest_pathroot.py
File metadata and controls
553 lines (403 loc) · 14.9 KB
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
"""Unit tests for pathroot."""
import logging
import os
import pathlib
from contextlib import contextmanager
from pathlib import Path
import pytest
import pathroot
LOG = logging.getLogger(__name__)
# Dictionary of test files to create in root_folder.
# Keys should be Path objects, and values should be None
# for directories, or a bytes object for contents.
TEST_FILES = {
Path("d1"): None,
Path("d1/f1.txt"): b"First file",
Path("d2"): None,
Path("d2/f2.txt"): b"Second file",
}
# region Fixtures
@pytest.fixture
def root_folder(tmp_path) -> Path: # type: ignore
"""Self cleaning test folder, populated by TEST_FILES."""
for p, c in TEST_FILES.items():
p = tmp_path / p
if c is None:
p.mkdir(exist_ok=True, parents=True)
LOG.info("** Created dir %s", p)
else:
p.parent.mkdir(exist_ok=True, parents=True)
p.write_bytes(c)
LOG.info("** Create file %s", p)
LOG.info("** Returning %s", tmp_path)
yield tmp_path
for p in sorted(tmp_path.rglob("*"), reverse=True):
if p.is_symlink() or p.is_file():
p.unlink()
LOG.info("** Unlinking %s", p)
elif p.is_dir():
p.rmdir()
LOG.info("** Removing dir %s", p)
@contextmanager
def fix_os_name(v: str):
"""Context manager for replacing pathroot.OS_NAME temporarily.
Args:
v: Value to set OS_NAME to.
"""
old_val = pathroot.OS_NAME
pathroot.OS_NAME = v # ty:ignore[invalid-assignment]
LOG.info("** Set OS_NAME to %r", v)
try:
yield
finally:
pathroot.OS_NAME = old_val
LOG.info("** Set OS_NAME back to %r", old_val)
@pytest.fixture
def _force_nt():
"""Force the OS name to nt (for Windows)."""
with fix_os_name("nt"):
yield
@pytest.fixture
def _force_posix():
"""Force the OS name to darwin (for POSIX)."""
with fix_os_name("darwin"):
yield
# endregion
# region Tests - Init Behavior
def test_safe_root_accepts_str_bytes_and_pathlike(tmp_path):
"""safe_root accepts str, bytes, and os.PathLike values."""
# Arrange
root = tmp_path
class MyPathLike:
def __fspath__(self) -> str:
return str(root)
# Act
pr_str = pathroot.PathRoot(root, safe_root=str(root))
pr_bytes = pathroot.PathRoot(root, safe_root=str(root).encode("utf-8"))
pr_pathlike = pathroot.PathRoot(root, safe_root=MyPathLike())
# Assert
expected = Path(root).resolve()
assert pr_str.safe_root == expected
assert pr_bytes.safe_root == expected
assert pr_pathlike.safe_root == expected
def test_safe_root_kwarg_precedence(tmp_path):
"""`safe_root` kwarg takes precedence over a PathRoot positional arg."""
# Arrange
parent = pathroot.PathRoot(tmp_path / "parent")
override = tmp_path / "override"
override.mkdir()
# Act
child = pathroot.PathRoot(parent, "child", safe_root=override)
# Assert
assert child.safe_root == override.resolve()
def test_default_safe_root_when_not_provided(tmp_path):
"""Default `safe_root` is the instance's resolved path when not provided."""
# Arrange
instance_path = tmp_path / "mysub"
# Act
pr = pathroot.PathRoot(instance_path)
# Assert
assert pr.safe_root == instance_path.resolve()
def test_construct_from_bytes_and_str_segments(tmp_path):
"""Constructing from a str path creates a `PathRoot` and sets `safe_root`."""
# Arrange
root = tmp_path
# Act
pr_from_str = pathroot.PathRoot(str(root))
# Assert
assert isinstance(pr_from_str, pathroot.PathRoot)
assert pr_from_str.safe_root == root.resolve()
def test_safe_root_resolves_symlink(tmp_path):
"""`safe_root` resolves symlinks by default."""
# Arrange
real = tmp_path / "real"
real.mkdir()
link = tmp_path / "link"
link.symlink_to(real)
# Act
pr = pathroot.PathRoot(link)
# Assert
assert pr.safe_root == real.resolve()
# endregion
# region Tests - OS-Specific Construction
@pytest.mark.usefixtures("_force_nt")
def test_new_windows(root_folder):
"""Test that PathRoot on Windows returns a WindowsPathRoot instance."""
# Arrange (OS_NAME is set to "nt" by _force_nt fixture)
# Act
r = pathroot.PathRoot(root_folder)
# Assert
assert type(r) is pathroot.WindowsPathRoot
@pytest.mark.usefixtures("_force_posix")
def test_new_posix(root_folder):
"""Test that PathRoot on POSIX OS returns a PosixPathRoot instance."""
# Arrange (OS_NAME is set to "darwin" by _force_posix fixture)
# Act
r = pathroot.PathRoot(root_folder)
# Assert
assert type(r) is pathroot.PosixPathRoot
@pytest.mark.usefixtures("_force_nt")
def test_windows_operations_preserve_type(root_folder):
"""Non-mutating path operations on a WindowsPathRoot return WindowsPathRoot instances.
rename/replace are not exercised here because WindowsPath formats paths with
backslashes, causing OS-level failures on non-Windows systems.
"""
# Arrange
r = pathroot.PathRoot(root_folder)
assert type(r) is pathroot.WindowsPathRoot
# Act / Assert
assert type(r / "d1") is pathroot.WindowsPathRoot
assert type(r.joinpath("d1")) is pathroot.WindowsPathRoot
assert type(r.with_segments(root_folder, "d1")) is pathroot.WindowsPathRoot
@pytest.mark.usefixtures("_force_posix")
def test_posix_operations_preserve_type(root_folder):
"""Path operations on a PosixPathRoot return PosixPathRoot instances."""
# Arrange
r = pathroot.PathRoot(root_folder)
assert type(r) is pathroot.PosixPathRoot
# Act / Assert - non-mutating operations
assert type(r / "d1") is pathroot.PosixPathRoot
assert type(r.joinpath("d1")) is pathroot.PosixPathRoot
assert type(r.with_segments(root_folder, "d1")) is pathroot.PosixPathRoot
# Act / Assert - rename
d1 = r / "d1"
assert type(d1.rename(root_folder / "d3")) is pathroot.PosixPathRoot
# Act / Assert - replace
d2 = r / "d2"
assert type(d2.replace(root_folder / "d4")) is pathroot.PosixPathRoot
# endregion
# region Tests - Construction and Safe Root
def test_safe_root_is_immutable(tmp_path):
"""Assigning to `safe_root` should raise an AttributeError."""
# Arrange
pr = pathroot.PathRoot(tmp_path)
# Act and Assert
with pytest.raises(AttributeError):
pr.safe_root = tmp_path / "other"
# endregion
# region Tests - Path Operations (Success Cases)
def test_joinpath_works(root_folder):
"""Test joinpath with path inside root works and returns PathRoot."""
# Arrange
r = pathroot.PathRoot(root_folder)
# Act
p1 = r.joinpath("foo/bar.txt")
# Assert
assert isinstance(p1, pathroot.PathRoot)
assert p1.safe_root == r.safe_root
def test_divide_works(root_folder):
"""Test divide operator inside root works and returns PathRoot."""
# Arrange
r = pathroot.PathRoot(root_folder)
# Act
p1 = r / "foo" / "bar.txt"
# Assert
assert isinstance(p1, pathroot.PathRoot)
assert p1.safe_root == r.safe_root
def test_with_segments_works(root_folder):
"""Test with_segments inside root works and returns PathRoot."""
# Arrange
r = pathroot.PathRoot(root_folder)
# Act
p1 = r.with_segments(root_folder, "foo/bar.txt")
# Assert
assert isinstance(p1, pathroot.PathRoot)
assert p1.safe_root == r.safe_root
def test_rename_works(root_folder):
"""Test rename works and returns PathRoot with same safe_root."""
# Arrange
p1 = pathroot.PathRoot(root_folder) / "d1"
# Act
p2 = p1.rename(root_folder / "d3")
# Assert
assert isinstance(p2, pathroot.PathRoot)
assert p2.safe_root == p1.safe_root
def test_replace_works(root_folder):
"""Test replace works and returns PathRoot with same safe_root."""
# Arrange
p1 = pathroot.PathRoot(root_folder) / "d1"
# Act
p2 = p1.replace(root_folder / "d3")
# Assert
assert isinstance(p2, pathroot.PathRoot)
assert p2.safe_root == p1.safe_root
def test_safe_root_inherits_from_pathroot_argument(tmp_path):
"""Test that new PathRoot inherits safe_root from PathRoot arg."""
# Arrange
parent = pathroot.PathRoot(tmp_path)
# Act
child = pathroot.PathRoot(parent, "subdir")
# Assert
assert child.safe_root == parent.safe_root
assert isinstance(child, pathroot.PathRoot)
def test_rename_accepts_bytes_target_and_moves_file(tmp_path):
"""Test rename accepts bytes target and moves file inside root."""
# Arrange
root = tmp_path
src = root / "a.txt"
dst = root / "b.txt"
content = b"hello"
src.write_bytes(content)
pr_file = pathroot.PathRoot(root) / "a.txt"
target_bytes = str(dst).encode("utf-8")
# Act
new_path = pr_file.rename(target_bytes)
# Assert
assert isinstance(new_path, pathroot.PathRoot)
assert new_path.exists()
assert dst.read_bytes() == content
# endregion
# region Tests - PathOutsideRootError
def test_joinpath_errors(root_folder):
"""Test joinpath raises PathOutsideRootError for paths outside root."""
# Arrange
r = pathroot.PathRoot(root_folder)
# Act and Assert
with pytest.raises(pathroot.PathOutsideRootError):
r.joinpath("..", "..", "etc")
def test_divide_errors(root_folder):
"""Test divide operator raises PathOutsideRootError for outside paths."""
# Arrange
r = pathroot.PathRoot(root_folder)
# Act and Assert
with pytest.raises(pathroot.PathOutsideRootError):
r / ".." / ".." / "etc"
def test_with_segments_errors(root_folder):
"""Test with_segments raises PathOutsideRootError for outside paths."""
# Arrange
r = pathroot.PathRoot(root_folder)
# Act and Assert
with pytest.raises(pathroot.PathOutsideRootError):
r.with_segments(root_folder, "..", "..", "etc")
def test_rename_errors(root_folder):
"""Test rename raises PathOutsideRootError for outside paths."""
# Arrange
r = pathroot.PathRoot(root_folder)
# Act and Assert
with pytest.raises(pathroot.PathOutsideRootError):
r.rename(root_folder / ".." / ".." / "etc")
def test_replace_errors(root_folder):
"""Test replace raises PathOutsideRootError for outside paths."""
# Arrange
r = pathroot.PathRoot(root_folder)
# Act and Assert
with pytest.raises(pathroot.PathOutsideRootError):
r.replace(root_folder / ".." / ".." / "etc")
def test_pathoutsiderooterror_str_contains_paths(tmp_path):
"""Test PathOutsideRootError string contains path and safe root."""
# Arrange
root = tmp_path
pr = pathroot.PathRoot(root)
# Act and Assert
with pytest.raises(pathroot.PathOutsideRootError) as excinfo:
pr.joinpath("..", "..", "outside")
# Assert
err = excinfo.value
s = str(err)
assert "is outside of" in s
assert str(err.path.resolve()) in s
assert str(err.root) in s
def test_symlink_to_raises_for_outside_target(tmp_path):
"""Test symlink_to raises PathOutsideRootError for outside target."""
# Arrange
root = tmp_path
pr = pathroot.PathRoot(root)
outside = root / ".." / "etc"
# Act and Assert
with pytest.raises(pathroot.PathOutsideRootError):
pr.symlink_to(outside)
def test_hardlink_to_raises_for_outside_target(tmp_path):
"""Test hardlink_to raises PathOutsideRootError for outside target."""
# Arrange
root = tmp_path
pr = pathroot.PathRoot(root)
outside = root / ".." / "etc"
# Act and Assert
with pytest.raises(pathroot.PathOutsideRootError):
pr.hardlink_to(outside)
# endregion
# region Tests - Link Methods (Success Cases)
def test_symlink_to_accepts_bytes_target_and_preserves_safe_root(monkeypatch, tmp_path):
"""Test symlink_to accepts bytes and passes PathRoot to super."""
# Arrange
root = tmp_path
(root / "target.txt").write_bytes(b"x")
pr_link = pathroot.PathRoot(root) / "link"
target_bytes = str(root / "target.txt").encode("utf-8")
recorded = {}
def fake_symlink_to(self, target, target_is_directory=False):
recorded["self"] = self
recorded["target"] = target
recorded["target_is_directory"] = target_is_directory
return None
monkeypatch.setattr(pathlib.Path, "symlink_to", fake_symlink_to, raising=True)
# Act
pr_link.symlink_to(target_bytes, target_is_directory=False)
# Assert
assert "target" in recorded
target_passed = recorded["target"]
assert isinstance(target_passed, pathroot.PathRoot)
assert target_passed.safe_root == pr_link.safe_root
def test_hardlink_to_accepts_bytes_target_and_calls_super(monkeypatch, tmp_path):
"""Test hardlink_to accepts bytes and passes PathRoot to super."""
# Arrange
root = tmp_path
(root / "target.txt").write_bytes(b"x")
pr_link = pathroot.PathRoot(root) / "linkfile"
target_bytes = str(root / "target.txt").encode("utf-8")
recorded = {}
def fake_hardlink_to(self, target):
recorded["self"] = self
recorded["target"] = target
return None
monkeypatch.setattr(pathlib.Path, "hardlink_to", fake_hardlink_to, raising=False)
# Act
pr_link.hardlink_to(target_bytes)
# Assert
assert "target" in recorded
target_passed = recorded["target"]
assert isinstance(target_passed, pathroot.PathRoot)
assert target_passed.safe_root == pr_link.safe_root
# endregion
# region Tests - Actual Link Creation (Edge Cases)
def test_symlink_to_creates_link_for_inside_target(tmp_path):
"""Test that symlink_to actually creates a link when target is inside root."""
# Arrange
root = tmp_path
target = root / "inside.txt"
target.write_bytes(b"inside")
link = pathroot.PathRoot(root) / "mylink"
# Act
link.symlink_to(target)
# Assert
assert link.exists()
assert link.is_symlink()
# reading via the symlink should give the same bytes
assert (root / "mylink").read_bytes() == b"inside"
def test_symlink_to_rejects_actual_outside_target(tmp_path):
"""Test that symlink_to raises when target is an actual file outside the root."""
# Arrange
root = tmp_path
outside_dir = tmp_path.parent / (tmp_path.name + "_outside")
outside_dir.mkdir(exist_ok=True)
outside_file = outside_dir / "outside.txt"
outside_file.write_bytes(b"outside")
pr = pathroot.PathRoot(root)
link = pr / "badlink"
# Act / Assert
with pytest.raises(pathroot.PathOutsideRootError):
link.symlink_to(outside_file)
def test_hardlink_to_rejects_actual_outside_target(tmp_path):
"""Test that hardlink_to raises when target is an actual file outside the root."""
# Arrange
root = tmp_path
outside_dir = tmp_path.parent / (tmp_path.name + "_outside_hl")
outside_dir.mkdir(exist_ok=True)
outside_file = outside_dir / "outside_hl.txt"
outside_file.write_bytes(b"outside-hl")
pr = pathroot.PathRoot(root)
link = pr / "badhardlink"
# Act / Assert
with pytest.raises(pathroot.PathOutsideRootError):
link.hardlink_to(outside_file)
# endregion