Debian Codegraph @

testing/_py/test_local.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import contextlib
5 import multiprocessing
6 import os
7 import sys
8 import time
9 from unittest import mock
10 import warnings
11
12 from py.path import local
13
14 from py import error
15
16 import pytest
17
18
19 @contextlib.contextmanager
20 def ignore_encoding_warning():
21 with warnings.catch_warnings():
22 warnings.simplefilter("ignore", EncodingWarning)
23 yield
24
25
26 class CommonFSTests:
27 def test_constructor_equality(self, path1):
28 p = path1.__class__(path1)
29 assert p == path1
30
31 def test_eq_nonstring(self, path1):
32 p1 = path1.join("sampledir")
33 p2 = path1.join("sampledir")
34 assert p1 == p2
35
36 def test_new_identical(self, path1):
37 assert path1 == path1.new()
38
39 def test_join(self, path1):
40 p = path1.join("sampledir")
41 strp = str(p)
42 assert strp.endswith("sampledir")
43 assert strp.startswith(str(path1))
44
45 def test_join_normalized(self, path1):
46 newpath = path1.join(path1.sep + "sampledir")
47 strp = str(newpath)
48 assert strp.endswith("sampledir")
49 assert strp.startswith(str(path1))
50 newpath = path1.join((path1.sep * 2) + "sampledir")
51 strp = str(newpath)
52 assert strp.endswith("sampledir")
53 assert strp.startswith(str(path1))
54
55 def test_join_noargs(self, path1):
56 newpath = path1.join()
57 assert path1 == newpath
58
59 def test_add_something(self, path1):
60 p = path1.join("sample")
61 p = p + "dir"
62 assert p.check()
63 assert p.exists()
64 assert p.isdir()
65 assert not p.isfile()
66
67 def test_parts(self, path1):
68 newpath = path1.join("sampledir", "otherfile")
69 par = newpath.parts()[-3:]
70 assert par == [path1, path1.join("sampledir"), newpath]
71
72 revpar = newpath.parts(reverse=True)[:3]
73 assert revpar == [newpath, path1.join("sampledir"), path1]
74
75 def test_common(self, path1):
76 other = path1.join("sampledir")
77 x = other.common(path1)
78 assert x == path1
79
80 # def test_parents_nonexisting_file(self, path1):
81 # newpath = path1 / 'dirnoexist' / 'nonexisting file'
82 # par = list(newpath.parents())
83 # assert par[:2] == [path1 / 'dirnoexist', path1]
84
85 def test_basename_checks(self, path1):
86 newpath = path1.join("sampledir")
87 assert newpath.check(basename="sampledir")
88 assert newpath.check(notbasename="xyz")
89 assert newpath.basename == "sampledir"
90
91 def test_basename(self, path1):
92 newpath = path1.join("sampledir")
93 assert newpath.check(basename="sampledir")
94 assert newpath.basename, "sampledir"
95
96 def test_dirname(self, path1):
97 newpath = path1.join("sampledir")
98 assert newpath.dirname == str(path1)
99
100 def test_dirpath(self, path1):
101 newpath = path1.join("sampledir")
102 assert newpath.dirpath() == path1
103
104 def test_dirpath_with_args(self, path1):
105 newpath = path1.join("sampledir")
106 assert newpath.dirpath("x") == path1.join("x")
107
108 def test_newbasename(self, path1):
109 newpath = path1.join("samplefile")
110 newbase = newpath.new(basename="samplefile2")
111 assert newbase.basename == "samplefile2"
112 assert newbase.dirpath() == newpath.dirpath()
113
114 def test_not_exists(self, path1):
115 assert not path1.join("does_not_exist").check()
116 assert path1.join("does_not_exist").check(exists=0)
117
118 def test_exists(self, path1):
119 assert path1.join("samplefile").check()
120 assert path1.join("samplefile").check(exists=1)
121 assert path1.join("samplefile").exists()
122 assert path1.join("samplefile").isfile()
123 assert not path1.join("samplefile").isdir()
124
125 def test_dir(self, path1):
126 # print repr(path1.join("sampledir"))
127 assert path1.join("sampledir").check(dir=1)
128 assert path1.join("samplefile").check(notdir=1)
129 assert not path1.join("samplefile").check(dir=1)
130 assert path1.join("samplefile").exists()
131 assert not path1.join("samplefile").isdir()
132 assert path1.join("samplefile").isfile()
133
134 def test_fnmatch_file(self, path1):
135 assert path1.join("samplefile").check(fnmatch="s*e")
136 assert path1.join("samplefile").fnmatch("s*e")
137 assert not path1.join("samplefile").fnmatch("s*x")
138 assert not path1.join("samplefile").check(fnmatch="s*x")
139
140 # def test_fnmatch_dir(self, path1):
141
142 # pattern = path1.sep.join(['s*file'])
143 # sfile = path1.join("samplefile")
144 # assert sfile.check(fnmatch=pattern)
145
146 def test_relto(self, path1):
147 p = path1.join("sampledir", "otherfile")
148 assert p.relto(path1) == p.sep.join(["sampledir", "otherfile"])
149 assert p.check(relto=path1)
150 assert path1.check(notrelto=p)
151 assert not path1.check(relto=p)
152
153 def test_bestrelpath(self, path1):
154 curdir = path1
155 sep = curdir.sep
156 s = curdir.bestrelpath(curdir)
157 assert s == "."
158 s = curdir.bestrelpath(curdir.join("hello", "world"))
159 assert s == "hello" + sep + "world"
160
161 s = curdir.bestrelpath(curdir.dirpath().join("sister"))
162 assert s == ".." + sep + "sister"
163 assert curdir.bestrelpath(curdir.dirpath()) == ".."
164
165 assert curdir.bestrelpath("hello") == "hello"
166
167 def test_relto_not_relative(self, path1):
168 l1 = path1.join("bcde")
169 l2 = path1.join("b")
170 assert not l1.relto(l2)
171 assert not l2.relto(l1)
172
173 def test_listdir(self, path1):
174 p = path1.listdir()
175 assert path1.join("sampledir") in p
176 assert path1.join("samplefile") in p
177 with pytest.raises(error.ENOTDIR):
178 path1.join("samplefile").listdir()
179
180 def test_listdir_fnmatchstring(self, path1):
181 p = path1.listdir("s*dir")
182 assert len(p)
183 assert p[0], path1.join("sampledir")
184
185 def test_listdir_filter(self, path1):
186 p = path1.listdir(lambda x: x.check(dir=1))
187 assert path1.join("sampledir") in p
188 assert path1.join("samplefile") not in p
189
190 def test_listdir_sorted(self, path1):
191 p = path1.listdir(lambda x: x.check(basestarts="sample"), sort=True)
192 assert path1.join("sampledir") == p[0]
193 assert path1.join("samplefile") == p[1]
194 assert path1.join("samplepickle") == p[2]
195
196 def test_visit_nofilter(self, path1):
197 lst = []
198 for i in path1.visit():
199 lst.append(i.relto(path1))
200 assert "sampledir" in lst
201 assert path1.sep.join(["sampledir", "otherfile"]) in lst
202
203 def test_visit_norecurse(self, path1):
204 lst = []
205 for i in path1.visit(None, lambda x: x.basename != "sampledir"):
206 lst.append(i.relto(path1))
207 assert "sampledir" in lst
208 assert path1.sep.join(["sampledir", "otherfile"]) not in lst
209
210 def test_visit_filterfunc_is_string(self, path1):
211 lst = []
212 for i in path1.visit("*dir"):
213 lst.append(i.relto(path1))
214 assert len(lst), 2 # noqa: PLC1802,RUF040
215 assert "sampledir" in lst
216 assert "otherdir" in lst
217
218 def test_visit_ignore(self, path1):
219 p = path1.join("nonexisting")
220 assert list(p.visit(ignore=error.ENOENT)) == []
221
222 def test_visit_endswith(self, path1):
223 p = []
224 for i in path1.visit(lambda x: x.check(endswith="file")):
225 p.append(i.relto(path1))
226 assert path1.sep.join(["sampledir", "otherfile"]) in p
227 assert "samplefile" in p
228
229 def test_cmp(self, path1):
230 path1 = path1.join("samplefile")
231 path2 = path1.join("samplefile2")
232 assert (path1 < path2) == ("samplefile" < "samplefile2")
233 assert not (path1 < path1)
234
235 def test_simple_read(self, path1):
236 with ignore_encoding_warning():
237 x = path1.join("samplefile").read("r")
238 assert x == "samplefile\n"
239
240 def test_join_div_operator(self, path1):
241 newpath = path1 / "/sampledir" / "/test//"
242 newpath2 = path1.join("sampledir", "test")
243 assert newpath == newpath2
244
245 def test_ext(self, path1):
246 newpath = path1.join("sampledir.ext")
247 assert newpath.ext == ".ext"
248 newpath = path1.join("sampledir")
249 assert not newpath.ext
250
251 def test_purebasename(self, path1):
252 newpath = path1.join("samplefile.py")
253 assert newpath.purebasename == "samplefile"
254
255 def test_multiple_parts(self, path1):
256 newpath = path1.join("samplefile.py")
257 dirname, purebasename, basename, ext = newpath._getbyspec(
258 "dirname,purebasename,basename,ext"
259 )
260 assert str(path1).endswith(dirname) # be careful with win32 'drive'
261 assert purebasename == "samplefile"
262 assert basename == "samplefile.py"
263 assert ext == ".py"
264
265 def test_dotted_name_ext(self, path1):
266 newpath = path1.join("a.b.c")
267 ext = newpath.ext
268 assert ext == ".c"
269 assert newpath.ext == ".c"
270
271 def test_newext(self, path1):
272 newpath = path1.join("samplefile.py")
273 newext = newpath.new(ext=".txt")
274 assert newext.basename == "samplefile.txt"
275 assert newext.purebasename == "samplefile"
276
277 def test_readlines(self, path1):
278 fn = path1.join("samplefile")
279 with ignore_encoding_warning():
280 contents = fn.readlines()
281 assert contents == ["samplefile\n"]
282
283 def test_readlines_nocr(self, path1):
284 fn = path1.join("samplefile")
285 with ignore_encoding_warning():
286 contents = fn.readlines(cr=0)
287 assert contents == ["samplefile", ""]
288
289 def test_file(self, path1):
290 assert path1.join("samplefile").check(file=1)
291
292 def test_not_file(self, path1):
293 assert not path1.join("sampledir").check(file=1)
294 assert path1.join("sampledir").check(file=0)
295
296 def test_non_existent(self, path1):
297 assert path1.join("sampledir.nothere").check(dir=0)
298 assert path1.join("sampledir.nothere").check(file=0)
299 assert path1.join("sampledir.nothere").check(notfile=1)
300 assert path1.join("sampledir.nothere").check(notdir=1)
301 assert path1.join("sampledir.nothere").check(notexists=1)
302 assert not path1.join("sampledir.nothere").check(notfile=0)
303
304 # pattern = path1.sep.join(['s*file'])
305 # sfile = path1.join("samplefile")
306 # assert sfile.check(fnmatch=pattern)
307
308 def test_size(self, path1):
309 url = path1.join("samplefile")
310 assert url.size() > len("samplefile")
311
312 def test_mtime(self, path1):
313 url = path1.join("samplefile")
314 assert url.mtime() > 0
315
316 def test_relto_wrong_type(self, path1):
317 with pytest.raises(TypeError):
318 path1.relto(42)
319
320 def test_load(self, path1):
321 p = path1.join("samplepickle")
322 obj = p.load()
323 assert type(obj) is dict
324 assert obj.get("answer", None) == 42
325
326 def test_visit_filesonly(self, path1):
327 p = []
328 for i in path1.visit(lambda x: x.check(file=1)):
329 p.append(i.relto(path1))
330 assert "sampledir" not in p
331 assert path1.sep.join(["sampledir", "otherfile"]) in p
332
333 def test_visit_nodotfiles(self, path1):
334 p = []
335 for i in path1.visit(lambda x: x.check(dotfile=0)):
336 p.append(i.relto(path1))
337 assert "sampledir" in p
338 assert path1.sep.join(["sampledir", "otherfile"]) in p
339 assert ".dotfile" not in p
340
341 def test_visit_breadthfirst(self, path1):
342 lst = []
343 for i in path1.visit(bf=True):
344 lst.append(i.relto(path1))
345 for i, p in enumerate(lst):
346 if path1.sep in p:
347 for j in range(i, len(lst)):
348 assert path1.sep in lst[j]
349 break
350 else:
351 pytest.fail("huh")
352
353 def test_visit_sort(self, path1):
354 lst = []
355 for i in path1.visit(bf=True, sort=True):
356 lst.append(i.relto(path1))
357 for i, p in enumerate(lst):
358 if path1.sep in p:
359 break
360 assert lst[:i] == sorted(lst[:i])
361 assert lst[i:] == sorted(lst[i:])
362
363 def test_endswith(self, path1):
364 def chk(p):
365 return p.check(endswith="pickle")
366
367 assert not chk(path1)
368 assert not chk(path1.join("samplefile"))
369 assert chk(path1.join("somepickle"))
370
371 def test_copy_file(self, path1):
372 otherdir = path1.join("otherdir")
373 initpy = otherdir.join("__init__.py")
374 copied = otherdir.join("copied")
375 initpy.copy(copied)
376 try:
377 assert copied.check()
378 s1 = initpy.read_text(encoding="utf-8")
379 s2 = copied.read_text(encoding="utf-8")
380 assert s1 == s2
381 finally:
382 if copied.check():
383 copied.remove()
384
385 def test_copy_dir(self, path1):
386 otherdir = path1.join("otherdir")
387 copied = path1.join("newdir")
388 try:
389 otherdir.copy(copied)
390 assert copied.check(dir=1)
391 assert copied.join("__init__.py").check(file=1)
392 s1 = otherdir.join("__init__.py").read_text(encoding="utf-8")
393 s2 = copied.join("__init__.py").read_text(encoding="utf-8")
394 assert s1 == s2
395 finally:
396 if copied.check(dir=1):
397 copied.remove(rec=1)
398
399 def test_remove_file(self, path1):
400 d = path1.ensure("todeleted")
401 assert d.check()
402 d.remove()
403 assert not d.check()
404
405 def test_remove_dir_recursive_by_default(self, path1):
406 d = path1.ensure("to", "be", "deleted")
407 assert d.check()
408 p = path1.join("to")
409 p.remove()
410 assert not p.check()
411
412 def test_ensure_dir(self, path1):
413 b = path1.ensure_dir("001", "002")
414 assert b.basename == "002"
415 assert b.isdir()
416
417 def test_mkdir_and_remove(self, path1):
418 tmpdir = path1
419 with pytest.raises(error.EEXIST):
420 tmpdir.mkdir("sampledir")
421 new = tmpdir.join("mktest1")
422 new.mkdir()
423 assert new.check(dir=1)
424 new.remove()
425
426 new = tmpdir.mkdir("mktest")
427 assert new.check(dir=1)
428 new.remove()
429 assert tmpdir.join("mktest") == new
430
431 def test_move_file(self, path1):
432 p = path1.join("samplefile")
433 newp = p.dirpath("moved_samplefile")
434 p.move(newp)
435 try:
436 assert newp.check(file=1)
437 assert not p.check()
438 finally:
439 dp = newp.dirpath()
440 if hasattr(dp, "revert"):
441 dp.revert()
442 else:
443 newp.move(p)
444 assert p.check()
445
446 def test_move_dir(self, path1):
447 source = path1.join("sampledir")
448 dest = path1.join("moveddir")
449 source.move(dest)
450 assert dest.check(dir=1)
451 assert dest.join("otherfile").check(file=1)
452 assert not source.join("sampledir").check()
453
454 def test_fspath_protocol_match_strpath(self, path1):
455 assert path1.__fspath__() == path1.strpath
456
457 def test_fspath_func_match_strpath(self, path1):
458 from os import fspath
459
460 assert fspath(path1) == path1.strpath
461
462 def test_fspath_open(self, path1):
463 f = path1.join("samplefile")
464 stream = open(f, encoding="utf-8")
465 stream.close()
466
467 def test_fspath_fsencode(self, path1):
468 from os import fsencode
469
470 assert fsencode(path1) == fsencode(path1.strpath)
471
472
473 def setuptestfs(path):
474 if path.join("samplefile").check():
475 return
476 # print "setting up test fs for", repr(path)
477 samplefile = path.ensure("samplefile")
478 samplefile.write_text("samplefile\n", encoding="utf-8")
479
480 execfile = path.ensure("execfile")
481 execfile.write_text("x=42", encoding="utf-8")
482
483 execfilepy = path.ensure("execfile.py")
484 execfilepy.write_text("x=42", encoding="utf-8")
485
486 d = {1: 2, "hello": "world", "answer": 42}
487 path.ensure("samplepickle").dump(d)
488
489 sampledir = path.ensure("sampledir", dir=1)
490 sampledir.ensure("otherfile")
491
492 otherdir = path.ensure("otherdir", dir=1)
493 otherdir.ensure("__init__.py")
494
495 module_a = otherdir.ensure("a.py")
496 module_a.write_text("from .b import stuff as result\n", encoding="utf-8")
497 module_b = otherdir.ensure("b.py")
498 module_b.write_text('stuff="got it"\n', encoding="utf-8")
499 module_c = otherdir.ensure("c.py")
500 module_c.write_text(
501 """import py;
502 import otherdir.a
503 value = otherdir.a.result
504 """,
505 encoding="utf-8",
506 )
507 module_d = otherdir.ensure("d.py")
508 module_d.write_text(
509 """import py;
510 from otherdir import a
511 value2 = a.result
512 """,
513 encoding="utf-8",
514 )
515
516
517 win32only = pytest.mark.skipif(
518 "not (sys.platform == 'win32' or getattr(os, '_name', None) == 'nt')"
519 )
520 skiponwin32 = pytest.mark.skipif(
521 "sys.platform == 'win32' or getattr(os, '_name', None) == 'nt'"
522 )
523
524 ATIME_RESOLUTION = 0.01
525
526
527 @pytest.fixture(scope="session")
528 def path1(tmpdir_factory):
529 path = tmpdir_factory.mktemp("path")
530 setuptestfs(path)
531 yield path
532 assert path.join("samplefile").check()
533
534
535 @pytest.fixture
536 def fake_fspath_obj(request):
537 class FakeFSPathClass:
538 def __init__(self, path):
539 self._path = path
540
541 def __fspath__(self):
542 return self._path
543
544 return FakeFSPathClass(os.path.join("this", "is", "a", "fake", "path"))
545
546
547 def batch_make_numbered_dirs(rootdir, repeats):
548 for i in range(repeats):
549 dir_ = local.make_numbered_dir(prefix="repro-", rootdir=rootdir)
550 file_ = dir_.join("foo")
551 file_.write_text(f"{i}", encoding="utf-8")
552 actual = int(file_.read_text(encoding="utf-8"))
553 assert actual == i, (
554 f"int(file_.read_text(encoding='utf-8')) is {actual} instead of {i}"
555 )
556 dir_.join(".lock").remove(ignore_errors=True)
557 return True
558
559
560 class TestLocalPath(CommonFSTests):
561 def test_join_normpath(self, tmpdir):
562 assert tmpdir.join(".") == tmpdir
563 p = tmpdir.join(f"../{tmpdir.basename}")
564 assert p == tmpdir
565 p = tmpdir.join(f"..//{tmpdir.basename}/")
566 assert p == tmpdir
567
568 @skiponwin32
569 def test_dirpath_abs_no_abs(self, tmpdir):
570 p = tmpdir.join("foo")
571 assert p.dirpath("/bar") == tmpdir.join("bar")
572 assert tmpdir.dirpath("/bar", abs=True) == local("/bar")
573
574 def test_gethash(self, tmpdir):
575 from hashlib import md5
576 from hashlib import sha1 as sha
577
578 fn = tmpdir.join("testhashfile")
579 data = b"hello"
580 fn.write(data, mode="wb")
581 assert fn.computehash("md5") == md5(data).hexdigest()
582 assert fn.computehash("sha1") == sha(data).hexdigest()
583 with pytest.raises(ValueError):
584 fn.computehash("asdasd")
585
586 def test_remove_removes_readonly_file(self, tmpdir):
587 readonly_file = tmpdir.join("readonly").ensure()
588 readonly_file.chmod(0)
589 readonly_file.remove()
590 assert not readonly_file.check(exists=1)
591
592 def test_remove_removes_readonly_dir(self, tmpdir):
593 readonly_dir = tmpdir.join("readonlydir").ensure(dir=1)
594 readonly_dir.chmod(int("500", 8))
595 readonly_dir.remove()
596 assert not readonly_dir.check(exists=1)
597
598 def test_remove_removes_dir_and_readonly_file(self, tmpdir):
599 readonly_dir = tmpdir.join("readonlydir").ensure(dir=1)
600 readonly_file = readonly_dir.join("readonlyfile").ensure()
601 readonly_file.chmod(0)
602 readonly_dir.remove()
603 assert not readonly_dir.check(exists=1)
604
605 def test_remove_routes_ignore_errors(self, tmpdir, monkeypatch):
606 lst = []
607 monkeypatch.setattr("shutil.rmtree", lambda *args, **kwargs: lst.append(kwargs))
608 tmpdir.remove()
609 assert not lst[0]["ignore_errors"]
610 for val in (True, False):
611 lst[:] = []
612 tmpdir.remove(ignore_errors=val)
613 assert lst[0]["ignore_errors"] == val
614
615 def test_initialize_curdir(self):
616 assert str(local()) == os.getcwd()
617
618 @skiponwin32
619 def test_chdir_gone(self, path1):
620 p = path1.ensure("dir_to_be_removed", dir=1)
621 p.chdir()
622 p.remove()
623 with pytest.raises(error.ENOENT):
624 local()
625 assert path1.chdir() is None
626 assert os.getcwd() == str(path1)
627
628 with pytest.raises(error.ENOENT):
629 with p.as_cwd():
630 raise NotImplementedError
631
632 @skiponwin32
633 def test_chdir_gone_in_as_cwd(self, path1):
634 p = path1.ensure("dir_to_be_removed", dir=1)
635 p.chdir()
636 p.remove()
637
638 with path1.as_cwd() as old:
639 assert old is None
640
641 def test_as_cwd(self, path1):
642 dir = path1.ensure("subdir", dir=1)
643 old = local()
644 with dir.as_cwd() as x:
645 assert x == old
646 assert local() == dir
647 assert os.getcwd() == str(old)
648
649 def test_as_cwd_exception(self, path1):
650 old = local()
651 dir = path1.ensure("subdir", dir=1)
652 with pytest.raises(ValueError):
653 with dir.as_cwd():
654 raise ValueError()
655 assert old == local()
656
657 def test_initialize_reldir(self, path1):
658 with path1.as_cwd():
659 p = local("samplefile")
660 assert p.check()
661
662 def test_tilde_expansion(self, monkeypatch, tmpdir):
663 monkeypatch.setenv("HOME", str(tmpdir))
664 p = local("~", expanduser=True)
665 assert p == os.path.expanduser("~")
666
667 @pytest.mark.skipif(
668 not sys.platform.startswith("win32"), reason="case-insensitive only on windows"
669 )
670 def test_eq_hash_are_case_insensitive_on_windows(self):
671 a = local("/some/path")
672 b = local("/some/PATH")
673 assert a == b
674 assert hash(a) == hash(b)
675 assert a in {b}
676 assert a in {b: "b"}
677
678 def test_eq_with_strings(self, path1):
679 path1 = path1.join("sampledir")
680 path2 = str(path1)
681 assert path1 == path2
682 assert path2 == path1
683 path3 = path1.join("samplefile")
684 assert path3 != path2
685 assert path2 != path3
686
687 def test_eq_with_none(self, path1):
688 assert path1 != None # noqa: E711
689
690 def test_eq_non_ascii_unicode(self, path1):
691 path2 = path1.join("temp")
692 path3 = path1.join("ação")
693 path4 = path1.join("ディレクトリ")
694
695 assert path2 != path3
696 assert path2 != path4
697 assert path4 != path3
698
699 def test_gt_with_strings(self, path1):
700 path2 = path1.join("sampledir")
701 path3 = str(path1.join("ttt"))
702 assert path3 > path2
703 assert path2 < path3
704 assert path2 < "ttt"
705 assert "ttt" > path2
706 path4 = path1.join("aaa")
707 lst = [path2, path4, path3]
708 assert sorted(lst) == [path4, path2, path3]
709
710 def test_open_and_ensure(self, path1):
711 p = path1.join("sub1", "sub2", "file")
712 with p.open("w", ensure=1, encoding="utf-8") as f:
713 f.write("hello")
714 assert p.read_text(encoding="utf-8") == "hello"
715
716 def test_write_and_ensure(self, path1):
717 p = path1.join("sub1", "sub2", "file")
718 p.write_text("hello", ensure=1, encoding="utf-8")
719 assert p.read_text(encoding="utf-8") == "hello"
720
721 @pytest.mark.parametrize("bin", (False, True))
722 def test_dump(self, tmpdir, bin):
723 path = tmpdir.join(f"dumpfile{int(bin)}")
724 try:
725 d = {"answer": 42}
726 path.dump(d, bin=bin)
727 f = path.open("rb+")
728 import pickle
729
730 dnew = pickle.load(f)
731 assert d == dnew
732 finally:
733 f.close()
734
735 def test_setmtime(self):
736 import tempfile
737
738 fd, name = tempfile.mkstemp()
739 os.close(fd)
740 try:
741 # Do not use _pytest.timing here, as we do not want time mocking to affect this test.
742 mtime = int(time.time()) - 100
743 path = local(name)
744 assert path.mtime() != mtime
745 path.setmtime(mtime)
746 assert path.mtime() == mtime
747 path.setmtime()
748 assert path.mtime() != mtime
749 finally:
750 os.remove(name)
751
752 def test_normpath(self, path1):
753 new1 = path1.join("/otherdir")
754 new2 = path1.join("otherdir")
755 assert str(new1) == str(new2)
756
757 def test_mkdtemp_creation(self):
758 d = local.mkdtemp()
759 try:
760 assert d.check(dir=1)
761 finally:
762 d.remove(rec=1)
763
764 def test_tmproot(self):
765 d = local.mkdtemp()
766 tmproot = local.get_temproot()
767 try:
768 assert d.check(dir=1)
769 assert d.dirpath() == tmproot
770 finally:
771 d.remove(rec=1)
772
773 def test_chdir(self, tmpdir):
774 old = local()
775 try:
776 res = tmpdir.chdir()
777 assert str(res) == str(old)
778 assert os.getcwd() == str(tmpdir)
779 finally:
780 old.chdir()
781
782 def test_ensure_filepath_withdir(self, tmpdir):
783 newfile = tmpdir.join("test1", "test")
784 newfile.ensure()
785 assert newfile.check(file=1)
786 newfile.write_text("42", encoding="utf-8")
787 newfile.ensure()
788 s = newfile.read_text(encoding="utf-8")
789 assert s == "42"
790
791 def test_ensure_filepath_withoutdir(self, tmpdir):
792 newfile = tmpdir.join("test1file")
793 t = newfile.ensure()
794 assert t == newfile
795 assert newfile.check(file=1)
796
797 def test_ensure_dirpath(self, tmpdir):
798 newfile = tmpdir.join("test1", "testfile")
799 t = newfile.ensure(dir=1)
800 assert t == newfile
801 assert newfile.check(dir=1)
802
803 def test_ensure_non_ascii_unicode(self, tmpdir):
804 newfile = tmpdir.join("ação", "ディレクトリ")
805 t = newfile.ensure(dir=1)
806 assert t == newfile
807 assert newfile.check(dir=1)
808
809 @pytest.mark.xfail(run=False, reason="unreliable est for long filenames")
810 def test_long_filenames(self, tmpdir):
811 if sys.platform == "win32":
812 pytest.skip("win32: work around needed for path length limit")
813 # see http://codespeak.net/pipermail/py-dev/2008q2/000922.html
814
815 # testing paths > 260 chars (which is Windows' limitation, but
816 # depending on how the paths are used), but > 4096 (which is the
817 # Linux' limitation) - the behaviour of paths with names > 4096 chars
818 # is undetermined
819 newfilename = "/test" * 60 # type:ignore[unreachable,unused-ignore]
820 l1 = tmpdir.join(newfilename)
821 l1.ensure(file=True)
822 l1.write_text("foo", encoding="utf-8")
823 l2 = tmpdir.join(newfilename)
824 assert l2.read_text(encoding="utf-8") == "foo"
825
826 def test_visit_depth_first(self, tmpdir):
827 tmpdir.ensure("a", "1")
828 tmpdir.ensure("b", "2")
829 p3 = tmpdir.ensure("breadth")
830 lst = list(tmpdir.visit(lambda x: x.check(file=1)))
831 assert len(lst) == 3
832 # check that breadth comes last
833 assert lst[2] == p3
834
835 def test_visit_rec_fnmatch(self, tmpdir):
836 p1 = tmpdir.ensure("a", "123")
837 tmpdir.ensure(".b", "345")
838 lst = list(tmpdir.visit("???", rec="[!.]*"))
839 assert len(lst) == 1
840 # check that breadth comes last
841 assert lst[0] == p1
842
843 def test_fnmatch_file_abspath(self, tmpdir):
844 b = tmpdir.join("a", "b")
845 assert b.fnmatch(os.sep.join("ab"))
846 pattern = os.sep.join([str(tmpdir), "*", "b"])
847 assert b.fnmatch(pattern)
848
849 def test_sysfind(self):
850 name = (sys.platform == "win32" and "cmd") or "test"
851 x = local.sysfind(name)
852 assert x.check(file=1)
853 assert local.sysfind("jaksdkasldqwe") is None
854 assert local.sysfind(name, paths=[]) is None
855 x2 = local.sysfind(name, paths=[x.dirpath()])
856 assert x2 == x
857
858 def test_fspath_protocol_other_class(self, fake_fspath_obj):
859 # py.path is always absolute
860 py_path = local(fake_fspath_obj)
861 str_path = fake_fspath_obj.__fspath__()
862 assert py_path.check(endswith=str_path)
863 assert py_path.join(fake_fspath_obj).strpath == os.path.join(
864 py_path.strpath, str_path
865 )
866
867 @pytest.mark.xfail(
868 reason="#11603", raises=(error.EEXIST, error.ENOENT), strict=False
869 )
870 def test_make_numbered_dir_multiprocess_safe(self, tmpdir):
871 # https://github.com/pytest-dev/py/issues/30
872 with multiprocessing.Pool() as pool:
873 results = [
874 pool.apply_async(batch_make_numbered_dirs, [tmpdir, 100])
875 for _ in range(20)
876 ]
877 for r in results:
878 assert r.get()
879
880
881 class TestExecutionOnWindows:
882 pytestmark = win32only
883
884 def test_sysfind_bat_exe_before(self, tmpdir, monkeypatch):
885 monkeypatch.setenv("PATH", str(tmpdir), prepend=os.pathsep)
886 tmpdir.ensure("hello")
887 h = tmpdir.ensure("hello.bat")
888 x = local.sysfind("hello")
889 assert x == h
890
891
892 class TestExecution:
893 pytestmark = skiponwin32
894
895 def test_sysfind_no_permission_ignored(self, monkeypatch, tmpdir):
896 noperm = tmpdir.ensure("noperm", dir=True)
897 monkeypatch.setenv("PATH", str(noperm), prepend=":")
898 noperm.chmod(0)
899 try:
900 assert local.sysfind("jaksdkasldqwe") is None
901 finally:
902 noperm.chmod(0o644)
903
904 def test_sysfind_absolute(self):
905 x = local.sysfind("test")
906 assert x.check(file=1)
907 y = local.sysfind(str(x))
908 assert y.check(file=1)
909 assert y == x
910
911 def test_sysfind_multiple(self, tmpdir, monkeypatch):
912 monkeypatch.setenv(
913 "PATH", "{}:{}".format(tmpdir.ensure("a"), tmpdir.join("b")), prepend=":"
914 )
915 tmpdir.ensure("b", "a")
916 x = local.sysfind("a", checker=lambda x: x.dirpath().basename == "b")
917 assert x.basename == "a"
918 assert x.dirpath().basename == "b"
919 assert local.sysfind("a", checker=lambda x: None) is None
920
921 def test_sysexec(self):
922 x = local.sysfind("ls")
923 out = x.sysexec("-a")
924 for x in local().listdir():
925 assert out.find(x.basename) != -1
926
927 def test_sysexec_failing(self):
928 try:
929 from py._process.cmdexec import ExecutionFailed # py library
930 except ImportError:
931 ExecutionFailed = RuntimeError # py vendored
932 x = local.sysfind("false")
933 with pytest.raises(ExecutionFailed):
934 x.sysexec("aksjdkasjd")
935
936 def test_make_numbered_dir(self, tmpdir):
937 tmpdir.ensure("base.not_an_int", dir=1)
938 for i in range(10):
939 numdir = local.make_numbered_dir(
940 prefix="base.", rootdir=tmpdir, keep=2, lock_timeout=0
941 )
942 assert numdir.check()
943 assert numdir.basename == f"base.{i}"
944 if i >= 1:
945 assert numdir.new(ext=str(i - 1)).check()
946 if i >= 2:
947 assert numdir.new(ext=str(i - 2)).check()
948 if i >= 3:
949 assert not numdir.new(ext=str(i - 3)).check()
950
951 def test_make_numbered_dir_case(self, tmpdir):
952 """make_numbered_dir does not make assumptions on the underlying
953 filesystem based on the platform and will assume it _could_ be case
954 insensitive.
955
956 See issues:
957 - https://github.com/pytest-dev/pytest/issues/708
958 - https://github.com/pytest-dev/pytest/issues/3451
959 """
960 d1 = local.make_numbered_dir(
961 prefix="CAse.",
962 rootdir=tmpdir,
963 keep=2,
964 lock_timeout=0,
965 )
966 d2 = local.make_numbered_dir(
967 prefix="caSE.",
968 rootdir=tmpdir,
969 keep=2,
970 lock_timeout=0,
971 )
972 assert str(d1).lower() != str(d2).lower()
973 assert str(d2).endswith(".1")
974
975 def test_make_numbered_dir_NotImplemented_Error(self, tmpdir, monkeypatch):
976 def notimpl(x, y):
977 raise NotImplementedError(42)
978
979 monkeypatch.setattr(os, "symlink", notimpl)
980 x = tmpdir.make_numbered_dir(rootdir=tmpdir, lock_timeout=0)
981 assert x.relto(tmpdir)
982 assert x.check()
983
984 def test_locked_make_numbered_dir(self, tmpdir):
985 for i in range(10):
986 numdir = local.make_numbered_dir(prefix="base2.", rootdir=tmpdir, keep=2)
987 assert numdir.check()
988 assert numdir.basename == f"base2.{i}"
989 for j in range(i):
990 assert numdir.new(ext=str(j)).check()
991
992 def test_error_preservation(self, path1):
993 with pytest.raises(EnvironmentError):
994 path1.join("qwoeqiwe").mtime()
995 with pytest.raises(EnvironmentError):
996 path1.join("qwoeqiwe").read()
997
998 # def test_parentdirmatch(self):
999 # local.parentdirmatch('std', startmodule=__name__)
1000 #
1001
1002
1003 class TestImport:
1004 @pytest.fixture(autouse=True)
1005 def preserve_sys(self):
1006 with mock.patch.dict(sys.modules):
1007 with mock.patch.object(sys, "path", list(sys.path)):
1008 yield
1009
1010 def test_pyimport(self, path1):
1011 obj = path1.join("execfile.py").pyimport()
1012 assert obj.x == 42
1013 assert obj.__name__ == "execfile"
1014
1015 def test_pyimport_renamed_dir_creates_mismatch(self, tmpdir, monkeypatch):
1016 p = tmpdir.ensure("a", "test_x123.py")
1017 p.pyimport()
1018 tmpdir.join("a").move(tmpdir.join("b"))
1019 with pytest.raises(tmpdir.ImportMismatchError):
1020 tmpdir.join("b", "test_x123.py").pyimport()
1021
1022 # Errors can be ignored.
1023 monkeypatch.setenv("PY_IGNORE_IMPORTMISMATCH", "1")
1024 tmpdir.join("b", "test_x123.py").pyimport()
1025
1026 # PY_IGNORE_IMPORTMISMATCH=0 does not ignore error.
1027 monkeypatch.setenv("PY_IGNORE_IMPORTMISMATCH", "0")
1028 with pytest.raises(tmpdir.ImportMismatchError):
1029 tmpdir.join("b", "test_x123.py").pyimport()
1030
1031 def test_pyimport_messy_name(self, tmpdir):
1032 # http://bitbucket.org/hpk42/py-trunk/issue/129
1033 path = tmpdir.ensure("foo__init__.py")
1034 path.pyimport()
1035
1036 def test_pyimport_dir(self, tmpdir):
1037 p = tmpdir.join("hello_123")
1038 p_init = p.ensure("__init__.py")
1039 m = p.pyimport()
1040 assert m.__name__ == "hello_123"
1041 m = p_init.pyimport()
1042 assert m.__name__ == "hello_123"
1043
1044 def test_pyimport_execfile_different_name(self, path1):
1045 obj = path1.join("execfile.py").pyimport(modname="0x.y.z")
1046 assert obj.x == 42
1047 assert obj.__name__ == "0x.y.z"
1048
1049 def test_pyimport_a(self, path1):
1050 otherdir = path1.join("otherdir")
1051 mod = otherdir.join("a.py").pyimport()
1052 assert mod.result == "got it"
1053 assert mod.__name__ == "otherdir.a"
1054
1055 def test_pyimport_b(self, path1):
1056 otherdir = path1.join("otherdir")
1057 mod = otherdir.join("b.py").pyimport()
1058 assert mod.stuff == "got it"
1059 assert mod.__name__ == "otherdir.b"
1060
1061 def test_pyimport_c(self, path1):
1062 otherdir = path1.join("otherdir")
1063 mod = otherdir.join("c.py").pyimport()
1064 assert mod.value == "got it"
1065
1066 def test_pyimport_d(self, path1):
1067 otherdir = path1.join("otherdir")
1068 mod = otherdir.join("d.py").pyimport()
1069 assert mod.value2 == "got it"
1070
1071 def test_pyimport_and_import(self, tmpdir):
1072 tmpdir.ensure("xxxpackage", "__init__.py")
1073 mod1path = tmpdir.ensure("xxxpackage", "module1.py")
1074 mod1 = mod1path.pyimport()
1075 assert mod1.__name__ == "xxxpackage.module1"
1076 from xxxpackage import module1
1077
1078 assert module1 is mod1
1079
1080 def test_pyimport_check_filepath_consistency(self, monkeypatch, tmpdir):
1081 name = "pointsback123"
1082 ModuleType = type(os)
1083 p = tmpdir.ensure(name + ".py")
1084 with monkeypatch.context() as mp:
1085 for ending in (".pyc", "$py.class", ".pyo"):
1086 mod = ModuleType(name)
1087 pseudopath = tmpdir.ensure(name + ending)
1088 mod.__file__ = str(pseudopath)
1089 mp.setitem(sys.modules, name, mod)
1090 newmod = p.pyimport()
1091 assert mod == newmod
1092 mod = ModuleType(name)
1093 pseudopath = tmpdir.ensure(name + "123.py")
1094 mod.__file__ = str(pseudopath)
1095 monkeypatch.setitem(sys.modules, name, mod)
1096 with pytest.raises(pseudopath.ImportMismatchError) as excinfo:
1097 p.pyimport()
1098 modname, modfile, orig = excinfo.value.args
1099 assert modname == name
1100 assert modfile == pseudopath
1101 assert orig == p
1102 assert issubclass(pseudopath.ImportMismatchError, ImportError)
1103
1104 def test_issue131_pyimport_on__init__(self, tmpdir):
1105 # __init__.py files may be namespace packages, and thus the
1106 # __file__ of an imported module may not be ourselves
1107 # see issue
1108 p1 = tmpdir.ensure("proja", "__init__.py")
1109 p2 = tmpdir.ensure("sub", "proja", "__init__.py")
1110 m1 = p1.pyimport()
1111 m2 = p2.pyimport()
1112 assert m1 == m2
1113
1114 def test_ensuresyspath_append(self, tmpdir):
1115 root1 = tmpdir.mkdir("root1")
1116 file1 = root1.ensure("x123.py")
1117 assert str(root1) not in sys.path
1118 file1.pyimport(ensuresyspath="append")
1119 assert str(root1) == sys.path[-1]
1120 assert str(root1) not in sys.path[:-1]
1121
1122
1123 class TestImportlibImport:
1124 OPTS = {"ensuresyspath": "importlib"}
1125
1126 def test_pyimport(self, path1):
1127 obj = path1.join("execfile.py").pyimport(**self.OPTS)
1128 assert obj.x == 42
1129 assert obj.__name__ == "execfile"
1130
1131 def test_pyimport_dir_fails(self, tmpdir):
1132 p = tmpdir.join("hello_123")
1133 p.ensure("__init__.py")
1134 with pytest.raises(ImportError):
1135 p.pyimport(**self.OPTS)
1136
1137 def test_pyimport_execfile_different_name(self, path1):
1138 obj = path1.join("execfile.py").pyimport(modname="0x.y.z", **self.OPTS)
1139 assert obj.x == 42
1140 assert obj.__name__ == "0x.y.z"
1141
1142 def test_pyimport_relative_import_fails(self, path1):
1143 otherdir = path1.join("otherdir")
1144 with pytest.raises(ImportError):
1145 otherdir.join("a.py").pyimport(**self.OPTS)
1146
1147 def test_pyimport_doesnt_use_sys_modules(self, tmpdir):
1148 p = tmpdir.ensure("file738jsk.py")
1149 mod = p.pyimport(**self.OPTS)
1150 assert mod.__name__ == "file738jsk"
1151 assert "file738jsk" not in sys.modules
1152
1153
1154 def test_pypkgdir(tmpdir):
1155 pkg = tmpdir.ensure("pkg1", dir=1)
1156 pkg.ensure("__init__.py")
1157 pkg.ensure("subdir/__init__.py")
1158 assert pkg.pypkgpath() == pkg
1159 assert pkg.join("subdir", "__init__.py").pypkgpath() == pkg
1160
1161
1162 def test_pypkgdir_unimportable(tmpdir):
1163 pkg = tmpdir.ensure("pkg1-1", dir=1) # unimportable
1164 pkg.ensure("__init__.py")
1165 subdir = pkg.ensure("subdir/__init__.py").dirpath()
1166 assert subdir.pypkgpath() == subdir
1167 assert subdir.ensure("xyz.py").pypkgpath() == subdir
1168 assert not pkg.pypkgpath()
1169
1170
1171 def test_isimportable():
1172 try:
1173 from py.path import isimportable # py vendored version
1174 except ImportError:
1175 from py._path.local import isimportable # py library
1176
1177 assert not isimportable("")
1178 assert isimportable("x")
1179 assert isimportable("x1")
1180 assert isimportable("x_1")
1181 assert isimportable("_")
1182 assert isimportable("_1")
1183 assert not isimportable("x-1")
1184 assert not isimportable("x:1")
1185
1186
1187 def test_homedir_from_HOME(monkeypatch):
1188 path = os.getcwd()
1189 monkeypatch.setenv("HOME", path)
1190 assert local._gethomedir() == local(path)
1191
1192
1193 def test_homedir_not_exists(monkeypatch):
1194 monkeypatch.delenv("HOME", raising=False)
1195 monkeypatch.delenv("HOMEDRIVE", raising=False)
1196 homedir = local._gethomedir()
1197 assert homedir is None
1198
1199
1200 def test_samefile(tmpdir):
1201 assert tmpdir.samefile(tmpdir)
1202 p = tmpdir.ensure("hello")
1203 assert p.samefile(p)
1204 with p.dirpath().as_cwd():
1205 assert p.samefile(p.basename)
1206 if sys.platform == "win32":
1207 p1 = p.__class__(str(p).lower())
1208 p2 = p.__class__(str(p).upper())
1209 assert p1.samefile(p2)
1210
1211
1212 @pytest.mark.skipif(not hasattr(os, "symlink"), reason="os.symlink not available")
1213 def test_samefile_symlink(tmpdir):
1214 p1 = tmpdir.ensure("foo.txt")
1215 p2 = tmpdir.join("linked.txt")
1216 try:
1217 os.symlink(str(p1), str(p2))
1218 except (OSError, NotImplementedError) as e:
1219 # on Windows this might fail if the user doesn't have special symlink permissions
1220 # pypy3 on Windows doesn't implement os.symlink and raises NotImplementedError
1221 pytest.skip(str(e.args[0]))
1222
1223 assert p1.samefile(p2)
1224
1225
1226 def test_listdir_single_arg(tmpdir):
1227 tmpdir.ensure("hello")
1228 assert tmpdir.listdir("hello")[0].basename == "hello"
1229
1230
1231 def test_mkdtemp_rootdir(tmpdir):
1232 dtmp = local.mkdtemp(rootdir=tmpdir)
1233 assert tmpdir.listdir() == [dtmp]
1234
1235
1236 class TestWINLocalPath:
1237 pytestmark = win32only
1238
1239 def test_owner_group_not_implemented(self, path1):
1240 with pytest.raises(NotImplementedError):
1241 _ = path1.stat().owner
1242 with pytest.raises(NotImplementedError):
1243 _ = path1.stat().group
1244
1245 def test_chmod_simple_int(self, path1):
1246 mode = path1.stat().mode
1247 # Ensure that we actually change the mode to something different.
1248 path1.chmod((mode == 0 and 1) or 0)
1249 try:
1250 print(path1.stat().mode)
1251 print(mode)
1252 assert path1.stat().mode != mode
1253 finally:
1254 path1.chmod(mode)
1255 assert path1.stat().mode == mode
1256
1257 def test_path_comparison_lowercase_mixed(self, path1):
1258 t1 = path1.join("a_path")
1259 t2 = path1.join("A_path")
1260 assert t1 == t1
1261 assert t1 == t2
1262
1263 def test_relto_with_mixed_case(self, path1):
1264 t1 = path1.join("a_path", "fiLe")
1265 t2 = path1.join("A_path")
1266 assert t1.relto(t2) == "fiLe"
1267
1268 def test_allow_unix_style_paths(self, path1):
1269 t1 = path1.join("a_path")
1270 assert t1 == str(path1) + "\\a_path"
1271 t1 = path1.join("a_path/")
1272 assert t1 == str(path1) + "\\a_path"
1273 t1 = path1.join("dir/a_path")
1274 assert t1 == str(path1) + "\\dir\\a_path"
1275
1276 def test_sysfind_in_currentdir(self, path1):
1277 cmd = local.sysfind("cmd")
1278 root = cmd.new(dirname="", basename="") # c:\ in most installations
1279 with root.as_cwd():
1280 x = local.sysfind(cmd.relto(root))
1281 assert x.check(file=1)
1282
1283 def test_fnmatch_file_abspath_posix_pattern_on_win32(self, tmpdir):
1284 # path-matching patterns might contain a posix path separator '/'
1285 # Test that we can match that pattern on windows.
1286 import posixpath
1287
1288 b = tmpdir.join("a", "b")
1289 assert b.fnmatch(posixpath.sep.join("ab"))
1290 pattern = posixpath.sep.join([str(tmpdir), "*", "b"])
1291 assert b.fnmatch(pattern)
1292
1293
1294 class TestPOSIXLocalPath:
1295 pytestmark = skiponwin32
1296
1297 def test_hardlink(self, tmpdir):
1298 linkpath = tmpdir.join("test")
1299 filepath = tmpdir.join("file")
1300 filepath.write_text("Hello", encoding="utf-8")
1301 nlink = filepath.stat().nlink
1302 linkpath.mklinkto(filepath)
1303 assert filepath.stat().nlink == nlink + 1
1304
1305 def test_symlink_are_identical(self, tmpdir):
1306 filepath = tmpdir.join("file")
1307 filepath.write_text("Hello", encoding="utf-8")
1308 linkpath = tmpdir.join("test")
1309 linkpath.mksymlinkto(filepath)
1310 assert linkpath.readlink() == str(filepath)
1311
1312 def test_symlink_isfile(self, tmpdir):
1313 linkpath = tmpdir.join("test")
1314 filepath = tmpdir.join("file")
1315 filepath.write_text("", encoding="utf-8")
1316 linkpath.mksymlinkto(filepath)
1317 assert linkpath.check(file=1)
1318 assert not linkpath.check(link=0, file=1)
1319 assert linkpath.islink()
1320
1321 def test_symlink_relative(self, tmpdir):
1322 linkpath = tmpdir.join("test")
1323 filepath = tmpdir.join("file")
1324 filepath.write_text("Hello", encoding="utf-8")
1325 linkpath.mksymlinkto(filepath, absolute=False)
1326 assert linkpath.readlink() == "file"
1327 assert filepath.read_text(encoding="utf-8") == linkpath.read_text(
1328 encoding="utf-8"
1329 )
1330
1331 def test_symlink_not_existing(self, tmpdir):
1332 linkpath = tmpdir.join("testnotexisting")
1333 assert not linkpath.check(link=1)
1334 assert linkpath.check(link=0)
1335
1336 def test_relto_with_root(self, path1, tmpdir):
1337 y = path1.join("x").relto(local("/"))
1338 assert y[0] == str(path1)[1]
1339
1340 def test_visit_recursive_symlink(self, tmpdir):
1341 linkpath = tmpdir.join("test")
1342 linkpath.mksymlinkto(tmpdir)
1343 visitor = tmpdir.visit(None, lambda x: x.check(link=0))
1344 assert list(visitor) == [linkpath]
1345
1346 def test_symlink_isdir(self, tmpdir):
1347 linkpath = tmpdir.join("test")
1348 linkpath.mksymlinkto(tmpdir)
1349 assert linkpath.check(dir=1)
1350 assert not linkpath.check(link=0, dir=1)
1351
1352 def test_symlink_remove(self, tmpdir):
1353 linkpath = tmpdir.join("test")
1354 linkpath.mksymlinkto(linkpath) # point to itself
1355 assert linkpath.check(link=1)
1356 linkpath.remove()
1357 assert not linkpath.check()
1358
1359 def test_realpath_file(self, tmpdir):
1360 linkpath = tmpdir.join("test")
1361 filepath = tmpdir.join("file")
1362 filepath.write_text("", encoding="utf-8")
1363 linkpath.mksymlinkto(filepath)
1364 realpath = linkpath.realpath()
1365 assert realpath.basename == "file"
1366
1367 def test_owner(self, path1, tmpdir):
1368 from grp import getgrgid # type:ignore[attr-defined,unused-ignore]
1369 from pwd import getpwuid # type:ignore[attr-defined,unused-ignore]
1370
1371 stat = path1.stat()
1372 assert stat.path == path1
1373
1374 uid = stat.uid
1375 gid = stat.gid
1376 owner = getpwuid(uid)[0]
1377 group = getgrgid(gid)[0]
1378
1379 assert uid == stat.uid
1380 assert owner == stat.owner
1381 assert gid == stat.gid
1382 assert group == stat.group
1383
1384 def test_stat_helpers(self, tmpdir, monkeypatch):
1385 path1 = tmpdir.ensure("file")
1386 stat1 = path1.stat()
1387 stat2 = tmpdir.stat()
1388 assert stat1.isfile()
1389 assert stat2.isdir()
1390 assert not stat1.islink()
1391 assert not stat2.islink()
1392
1393 def test_stat_non_raising(self, tmpdir):
1394 path1 = tmpdir.join("file")
1395 with pytest.raises(error.ENOENT):
1396 path1.stat()
1397 res = path1.stat(raising=False)
1398 assert res is None
1399
1400 def test_atime(self, tmpdir):
1401 import time
1402
1403 path = tmpdir.ensure("samplefile")
1404 # Do not use _pytest.timing here, as we do not want time mocking to affect this test.
1405 now = time.time()
1406 atime1 = path.atime()
1407 # we could wait here but timer resolution is very
1408 # system dependent
1409 path.read_binary()
1410 time.sleep(ATIME_RESOLUTION)
1411 atime2 = path.atime()
1412 time.sleep(ATIME_RESOLUTION)
1413 duration = time.time() - now
1414 assert (atime2 - atime1) <= duration
1415
1416 def test_commondir(self, path1):
1417 # XXX This is here in local until we find a way to implement this
1418 # using the subversion command line api.
1419 p1 = path1.join("something")
1420 p2 = path1.join("otherthing")
1421 assert p1.common(p2) == path1
1422 assert p2.common(p1) == path1
1423
1424 def test_commondir_nocommon(self, path1):
1425 # XXX This is here in local until we find a way to implement this
1426 # using the subversion command line api.
1427 p1 = path1.join("something")
1428 p2 = local(path1.sep + "blabla")
1429 assert p1.common(p2) == "/"
1430
1431 def test_join_to_root(self, path1):
1432 root = path1.parts()[0]
1433 assert len(str(root)) == 1
1434 assert str(root.join("a")) == "/a"
1435
1436 def test_join_root_to_root_with_no_abs(self, path1):
1437 nroot = path1.join("/")
1438 assert str(path1) == str(nroot)
1439 assert path1 == nroot
1440
1441 def test_chmod_simple_int(self, path1):
1442 mode = path1.stat().mode
1443 path1.chmod(int(mode / 2))
1444 try:
1445 assert path1.stat().mode != mode
1446 finally:
1447 path1.chmod(mode)
1448 assert path1.stat().mode == mode
1449
1450 def test_chmod_rec_int(self, path1):
1451 # XXX fragile test
1452 def recfilter(x):
1453 return x.check(dotfile=0, link=0)
1454
1455 oldmodes = {}
1456 for x in path1.visit(rec=recfilter):
1457 oldmodes[x] = x.stat().mode
1458 path1.chmod(int("772", 8), rec=recfilter)
1459 try:
1460 for x in path1.visit(rec=recfilter):
1461 assert x.stat().mode & int("777", 8) == int("772", 8)
1462 finally:
1463 for x, y in oldmodes.items():
1464 x.chmod(y)
1465
1466 def test_copy_archiving(self, tmpdir):
1467 unicode_fn = "something-\342\200\223.txt"
1468 f = tmpdir.ensure("a", unicode_fn)
1469 a = f.dirpath()
1470 oldmode = f.stat().mode
1471 newmode = oldmode ^ 1
1472 f.chmod(newmode)
1473 b = tmpdir.join("b")
1474 a.copy(b, mode=True)
1475 assert b.join(f.basename).stat().mode == newmode
1476
1477 def test_copy_stat_file(self, tmpdir):
1478 src = tmpdir.ensure("src")
1479 dst = tmpdir.join("dst")
1480 # a small delay before the copy
1481 time.sleep(ATIME_RESOLUTION)
1482 src.copy(dst, stat=True)
1483 oldstat = src.stat()
1484 newstat = dst.stat()
1485 assert oldstat.mode == newstat.mode
1486 assert (dst.atime() - src.atime()) < ATIME_RESOLUTION
1487 assert (dst.mtime() - src.mtime()) < ATIME_RESOLUTION
1488
1489 def test_copy_stat_dir(self, tmpdir):
1490 test_files = ["a", "b", "c"]
1491 src = tmpdir.join("src")
1492 for f in test_files:
1493 src.join(f).write_text(f, ensure=True, encoding="utf-8")
1494 dst = tmpdir.join("dst")
1495 # a small delay before the copy
1496 time.sleep(ATIME_RESOLUTION)
1497 src.copy(dst, stat=True)
1498 for f in test_files:
1499 oldstat = src.join(f).stat()
1500 newstat = dst.join(f).stat()
1501 assert (newstat.atime - oldstat.atime) < ATIME_RESOLUTION
1502 assert (newstat.mtime - oldstat.mtime) < ATIME_RESOLUTION
1503 assert oldstat.mode == newstat.mode
1504
1505 def test_chown_identity(self, path1):
1506 owner = path1.stat().owner
1507 group = path1.stat().group
1508 path1.chown(owner, group)
1509
1510 def test_chown_dangling_link(self, path1):
1511 owner = path1.stat().owner
1512 group = path1.stat().group
1513 x = path1.join("hello")
1514 x.mksymlinkto("qlwkejqwlek")
1515 try:
1516 path1.chown(owner, group, rec=1)
1517 finally:
1518 x.remove(rec=0)
1519
1520 def test_chown_identity_rec_mayfail(self, path1):
1521 owner = path1.stat().owner
1522 group = path1.stat().group
1523 path1.chown(owner, group)
1524
1525
1526 class TestUnicode:
1527 def test_join_ensure(self, tmpdir, monkeypatch):
1528 if "LANG" not in os.environ:
1529 pytest.skip("cannot run test without locale")
1530 x = local(tmpdir.strpath)
1531 part = "hällo"
1532 y = x.ensure(part)
1533 assert x.join(part) == y
1534
1535 def test_listdir(self, tmpdir):
1536 if "LANG" not in os.environ:
1537 pytest.skip("cannot run test without locale")
1538 x = local(tmpdir.strpath)
1539 part = "hällo"
1540 y = x.ensure(part)
1541 assert x.listdir(part)[0] == y
1542
1543 @pytest.mark.xfail(reason="changing read/write might break existing usages")
1544 def test_read_write(self, tmpdir):
1545 x = tmpdir.join("hello")
1546 part = "hällo"
1547 with ignore_encoding_warning():
1548 x.write(part)
1549 assert x.read() == part
1550 x.write(part.encode(sys.getdefaultencoding()))
1551 assert x.read() == part.encode(sys.getdefaultencoding())
1552
1553
1554 class TestBinaryAndTextMethods:
1555 def test_read_binwrite(self, tmpdir):
1556 x = tmpdir.join("hello")
1557 part = "hällo"
1558 part_utf8 = part.encode("utf8")
1559 x.write_binary(part_utf8)
1560 assert x.read_binary() == part_utf8
1561 s = x.read_text(encoding="utf8")
1562 assert s == part
1563 assert isinstance(s, str)
1564
1565 def test_read_textwrite(self, tmpdir):
1566 x = tmpdir.join("hello")
1567 part = "hällo"
1568 part_utf8 = part.encode("utf8")
1569 x.write_text(part, encoding="utf8")
1570 assert x.read_binary() == part_utf8
1571 assert x.read_text(encoding="utf8") == part
1572
1573 def test_default_encoding(self, tmpdir):
1574 x = tmpdir.join("hello")
1575 # Can't use UTF8 as the default encoding (ASCII) doesn't support it
1576 part = "hello"
1577 x.write_text(part, "ascii")
1578 s = x.read_text("ascii")
1579 assert s == part
1580 assert type(s) is type(part)