4 """Unittests for the posix1e module"""
6 # Copyright (C) 2002-2009, 2012, 2014, 2015 Iustin Pop <iustin@k1024.org>
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
40 TEST_DIR = os.environ.get("TEST_DIR", ".")
42 BASIC_ACL_TEXT = "u::rw,g::r,o::-"
44 # Permset permission information
46 posix1e.ACL_READ: ("read", posix1e.Permset.read),
47 posix1e.ACL_WRITE: ("write", posix1e.Permset.write),
48 posix1e.ACL_EXECUTE: ("execute", posix1e.Permset.execute),
52 (posix1e.ACL_USER, "user"),
53 (posix1e.ACL_GROUP, "group"),
54 (posix1e.ACL_USER_OBJ, "user object"),
55 (posix1e.ACL_GROUP_OBJ, "group object"),
56 (posix1e.ACL_MASK, "mask"),
57 (posix1e.ACL_OTHER, "other"),
60 ALL_TAG_VALUES = [i[0] for i in ALL_TAGS]
61 ALL_TAG_DESCS = [i[1] for i in ALL_TAGS]
63 # Fixtures and helpers
65 def ignore_ioerror(errnum, fn, *args, **kwargs):
66 """Call a function while ignoring some IOErrors.
68 This is needed as some OSes (e.g. FreeBSD) return failure (EINVAL)
69 when doing certain operations on an invalid ACL.
75 err = sys.exc_info()[1]
76 if err.errno == errnum:
82 """per-test temp dir based in TEST_DIR"""
83 with tempfile.TemporaryDirectory(dir=TEST_DIR) as dname:
87 fh, fname = tempfile.mkstemp(".test", "xattr-", path)
90 @contextlib.contextmanager
91 def get_file_name(path):
92 fh, fname = get_file(path)
96 @contextlib.contextmanager
97 def get_file_fd(path):
98 fd = get_file(path)[0]
102 @contextlib.contextmanager
103 def get_file_object(path):
104 fd = get_file(path)[0]
105 with os.fdopen(fd) as f:
108 @contextlib.contextmanager
110 yield tempfile.mkdtemp(".test", "xattr-", path)
112 def get_symlink(path, dangling=True):
113 """create a symlink"""
114 fh, fname = get_file(path)
118 sname = fname + ".symlink"
119 os.symlink(fname, sname)
122 @contextlib.contextmanager
123 def get_valid_symlink(path):
124 yield get_symlink(path, dangling=False)[1]
126 @contextlib.contextmanager
127 def get_dangling_symlink(path):
128 yield get_symlink(path, dangling=True)[1]
130 @contextlib.contextmanager
131 def get_file_and_symlink(path):
132 yield get_symlink(path, dangling=False)
134 @contextlib.contextmanager
135 def get_file_and_fobject(path):
136 fh, fname = get_file(path)
137 with os.fdopen(fh) as fo:
140 # Wrappers that build upon existing values
142 def as_wrapper(call, fn, closer=None):
143 @contextlib.contextmanager
145 with call(path) as r:
148 if closer is not None:
153 return as_wrapper(call, lambda r: r.encode())
156 return as_wrapper(call, pathlib.PurePath)
158 def as_iostream(call):
159 opener = lambda f: io.open(f, "r")
160 closer = lambda r: r.close()
161 return as_wrapper(call, opener, closer)
163 NOT_BEFORE_36 = pytest.mark.xfail(condition="sys.version_info < (3,6)",
165 NOT_PYPY = pytest.mark.xfail(condition="platform.python_implementation() == 'PyPy'",
168 require_acl_from_mode = pytest.mark.skipif("not HAS_ACL_FROM_MODE")
169 require_acl_check = pytest.mark.skipif("not HAS_ACL_CHECK")
170 require_acl_entry = pytest.mark.skipif("not HAS_ACL_ENTRY")
171 require_extended_check = pytest.mark.skipif("not HAS_EXTENDED_CHECK")
172 require_equiv_mode = pytest.mark.skipif("not HAS_EQUIV_MODE")
174 # Note: ACLs are valid only for files/directories, not symbolic links
175 # themselves, so we only create valid symlinks.
178 as_bytes(get_file_name),
179 pytest.param(as_fspath(get_file_name),
180 marks=[NOT_BEFORE_36, NOT_PYPY]),
183 pytest.param(as_fspath(get_dir),
184 marks=[NOT_BEFORE_36, NOT_PYPY]),
186 as_bytes(get_valid_symlink),
187 pytest.param(as_fspath(get_valid_symlink),
188 marks=[NOT_BEFORE_36, NOT_PYPY]),
199 "file via symlink (bytes)",
200 "file via symlink (path)",
206 as_iostream(get_file_name),
215 ALL_P = FILE_P + FD_P
216 ALL_D = FILE_D + FD_D
218 @pytest.fixture(params=FILE_P, ids=FILE_D)
219 def file_subject(testdir, request):
220 with request.param(testdir) as value:
223 @pytest.fixture(params=FD_P, ids=FD_D)
224 def fd_subject(testdir, request):
225 with request.param(testdir) as value:
228 @pytest.fixture(params=ALL_P, ids=ALL_D)
229 def subject(testdir, request):
230 with request.param(testdir) as value:
235 """Load/create tests"""
236 def test_from_file(self, testdir):
237 """Test loading ACLs from a file"""
238 _, fname = get_file(testdir)
239 acl1 = posix1e.ACL(file=fname)
242 def test_from_dir(self, testdir):
243 """Test loading ACLs from a directory"""
244 with get_dir(testdir) as dname:
245 acl1 = posix1e.ACL(file=dname)
246 acl2 = posix1e.ACL(filedef=dname)
248 # default ACLs might or might not be valid; missing ones are
249 # not valid, so we don't test acl2 for validity
251 def test_from_fd(self, testdir):
252 """Test loading ACLs from a file descriptor"""
253 fd, _ = get_file(testdir)
254 acl1 = posix1e.ACL(fd=fd)
257 def test_from_empty_invalid(self):
258 """Test creating an empty ACL"""
260 assert not acl1.valid()
262 def test_from_text(self):
263 """Test creating an ACL from text"""
264 acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
267 def test_from_acl(self):
268 """Test creating an ACL from an existing ACL"""
270 acl2 = posix1e.ACL(acl=acl1)
273 def test_invalid_creation_params(self, testdir):
274 """Test that creating an ACL from multiple objects fails"""
275 fd, _ = get_file(testdir)
276 with pytest.raises(ValueError):
277 posix1e.ACL(text=BASIC_ACL_TEXT, fd=fd)
279 def test_invalid_value_creation(self):
280 """Test that creating an ACL from wrong specification fails"""
281 with pytest.raises(EnvironmentError):
282 posix1e.ACL(text="foobar")
283 with pytest.raises(TypeError):
284 posix1e.ACL(foo="bar")
286 def test_double_init(self):
287 acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
289 acl1.__init__(text=BASIC_ACL_TEXT)
292 class TestAclExtensions:
293 """ACL extensions checks"""
295 @require_acl_from_mode
296 def test_from_mode(self):
297 """Test loading ACLs from an octal mode"""
298 acl1 = posix1e.ACL(mode=0o644)
302 def test_acl_check(self):
303 """Test the acl_check method"""
304 acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
305 assert not acl1.check()
309 @require_extended_check
310 def test_extended(self, testdir):
311 """Test the acl_extended function"""
312 fd, fname = get_file(testdir)
313 basic_acl = posix1e.ACL(text=BASIC_ACL_TEXT)
314 basic_acl.applyto(fd)
315 for item in fd, fname:
316 assert not has_extended(item)
317 enhanced_acl = posix1e.ACL(text="u::rw,g::-,o::-,u:root:rw,mask::r")
318 assert enhanced_acl.valid()
319 enhanced_acl.applyto(fd)
320 for item in fd, fname:
321 assert has_extended(item)
323 @require_extended_check
324 def test_extended_arg_handling(self):
325 with pytest.raises(TypeError):
327 with pytest.raises(TypeError):
328 has_extended(object())
331 def test_equiv_mode(self):
332 """Test the equiv_mode function"""
333 if HAS_ACL_FROM_MODE:
334 for mode in 0o644, 0o755:
335 acl = posix1e.ACL(mode=mode)
336 assert acl.equiv_mode() == mode
337 acl = posix1e.ACL(text="u::rw,g::r,o::r")
338 assert acl.equiv_mode() == 0o644
339 acl = posix1e.ACL(text="u::rx,g::-,o::-")
340 assert acl.equiv_mode() == 0o500
343 def test_to_any_text(self):
344 acl = posix1e.ACL(text=BASIC_ACL_TEXT)
346 acl.to_any_text(options=posix1e.TEXT_ABBREVIATE)
347 assert b"user::" in acl.to_any_text()
350 def test_to_any_text_wrong_args(self):
351 acl = posix1e.ACL(text=BASIC_ACL_TEXT)
352 with pytest.raises(TypeError):
353 acl.to_any_text(foo="bar")
357 def test_rich_compare(self):
358 acl1 = posix1e.ACL(text="u::rw,g::r,o::r")
359 acl2 = posix1e.ACL(acl=acl1)
360 acl3 = posix1e.ACL(text="u::rw,g::rw,o::r")
363 with pytest.raises(TypeError):
365 with pytest.raises(TypeError):
368 assert not (acl1 == 1)
369 with pytest.raises(TypeError):
372 def test_apply_to_with_wrong_object(self):
373 acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
375 with pytest.raises(TypeError):
376 acl1.applyto(object())
377 with pytest.raises(TypeError):
378 acl1.applyto(object(), object())
381 def test_acl_iterator(self):
382 acl = posix1e.ACL(text=BASIC_ACL_TEXT)
384 assert entry.parent is acl
390 def test_delete_default(self, testdir):
391 """Test removing the default ACL"""
392 with get_dir(testdir) as dname:
393 posix1e.delete_default(dname)
396 def test_delete_default_wrong_arg(self):
397 with pytest.raises(TypeError):
398 posix1e.delete_default(object())
400 def test_reapply(self, testdir):
401 """Test re-applying an ACL"""
402 fd, fname = get_file(testdir)
403 acl1 = posix1e.ACL(fd=fd)
406 with get_dir(testdir) as dname:
407 acl2 = posix1e.ACL(file=fname)
413 class TestModification:
414 """ACL modification tests"""
416 def checkRef(self, obj):
417 """Checks if a given obj has a 'sane' refcount"""
418 if platform.python_implementation() == "PyPy":
420 ref_cnt = sys.getrefcount(obj)
421 # FIXME: hardcoded value for the max ref count... but I've
422 # seen it overflow on bad reference counting, so it's better
424 if ref_cnt < 2 or ref_cnt > 1024:
425 pytest.fail("Wrong reference count, expected 2-1024 and got %d" %
429 """Test str() of an ACL."""
430 acl = posix1e.ACL(text=BASIC_ACL_TEXT)
432 self.checkRef(str_acl)
434 def test_append(self):
435 """Test append a new Entry to the ACL"""
438 e.tag_type = posix1e.ACL_OTHER
439 ignore_ioerror(errno.EINVAL, acl.calc_mask)
441 self.checkRef(str_format)
443 ignore_ioerror(errno.EINVAL, acl.calc_mask)
444 assert not acl.valid()
446 def test_wrong_append(self):
447 """Test append a new Entry to the ACL based on wrong object type"""
449 with pytest.raises(TypeError):
452 def test_entry_creation(self):
454 e = posix1e.Entry(acl)
455 ignore_ioerror(errno.EINVAL, acl.calc_mask)
457 self.checkRef(str_format)
459 def test_entry_failed_creation(self):
460 # Checks for partial initialisation and deletion on error
462 with pytest.raises(TypeError):
463 posix1e.Entry(object())
465 def test_delete(self):
466 """Test delete Entry from the ACL"""
469 e.tag_type = posix1e.ACL_OTHER
470 ignore_ioerror(errno.EINVAL, acl.calc_mask)
472 ignore_ioerror(errno.EINVAL, acl.calc_mask)
474 def test_double_delete(self):
475 """Test delete Entry from the ACL"""
476 # This is not entirely valid/correct, since the entry object
477 # itself is invalid after the first deletion, so we're
478 # actually testing deleting an invalid object, not a
479 # non-existing entry...
482 e.tag_type = posix1e.ACL_OTHER
483 ignore_ioerror(errno.EINVAL, acl.calc_mask)
485 ignore_ioerror(errno.EINVAL, acl.calc_mask)
486 with pytest.raises(EnvironmentError):
489 # This currently fails as this deletion seems to be accepted :/
490 @pytest.mark.xfail(reason="Entry deletion is unreliable")
491 def testDeleteInvalidEntry(self):
492 """Test delete foreign Entry from the ACL"""
496 e.tag_type = posix1e.ACL_OTHER
497 ignore_ioerror(errno.EINVAL, acl1.calc_mask)
498 with pytest.raises(EnvironmentError):
501 def test_delete_invalid_object(self):
502 """Test delete a non-Entry from the ACL"""
504 with pytest.raises(TypeError):
505 acl.delete_entry(object())
507 def test_double_entries(self):
508 """Test double entries"""
509 acl = posix1e.ACL(text=BASIC_ACL_TEXT)
511 for tag_type in (posix1e.ACL_USER_OBJ, posix1e.ACL_GROUP_OBJ,
514 e.tag_type = tag_type
516 assert not acl.valid(), ("ACL containing duplicate entries"
517 " should not be valid")
520 def test_multiple_good_entries(self):
521 """Test multiple valid entries"""
522 acl = posix1e.ACL(text=BASIC_ACL_TEXT)
524 for tag_type in (posix1e.ACL_USER,
526 for obj_id in range(5):
528 e.tag_type = tag_type
532 assert acl.valid(), ("ACL should be able to hold multiple"
533 " user/group entries")
535 def test_multiple_bad_entries(self):
536 """Test multiple invalid entries"""
537 for tag_type in (posix1e.ACL_USER,
539 acl = posix1e.ACL(text=BASIC_ACL_TEXT)
542 e1.tag_type = tag_type
546 assert acl.valid(), ("ACL should be able to add a"
549 e2.tag_type = tag_type
552 ignore_ioerror(errno.EINVAL, acl.calc_mask)
553 assert not acl.valid(), ("ACL should not validate when"
554 " containing two duplicate entries")
556 # FreeBSD trips over itself here and can't delete the
557 # entry, even though it still exists.
558 ignore_ioerror(errno.EINVAL, acl.delete_entry, e2)
563 e1.tag_type = ACL_USER
569 e2.tag_type = ACL_GROUP
576 assert e1.tag_type == e2.tag_type
578 def test_copy_wrong_arg(self):
581 with pytest.raises(TypeError):
584 def test_set_permset(self):
587 e1.tag_type = ACL_USER
593 e2.tag_type = ACL_GROUP
599 assert e2.permset.write
600 assert e2.tag_type == ACL_GROUP
602 def test_set_permset_wrong_arg(self):
605 with pytest.raises(TypeError):
608 def test_permset_creation(self):
613 #self.assertEqual(p1, p2)
615 def test_permset_creation_wrong_arg(self):
616 with pytest.raises(TypeError):
619 def test_permset(self):
620 """Test permissions"""
626 self.checkRef(str_ps)
627 for perm in PERMSETS:
629 txt = PERMSETS[perm][0]
630 self.checkRef(str_ps)
631 assert not ps.test(perm), ("Empty permission set should not"
632 " have permission '%s'" % txt)
634 assert ps.test(perm), ("Permission '%s' should exist"
635 " after addition" % txt)
637 self.checkRef(str_ps)
639 assert not ps.test(perm), ("Permission '%s' should not exist"
640 " after deletion" % txt)
642 def test_permset_via_accessors(self):
643 """Test permissions"""
649 self.checkRef(str_ps)
651 return PERMSETS[perm][1].__get__(ps)
652 def setter(parm, value):
653 return PERMSETS[perm][1].__set__(ps, value)
654 for perm in PERMSETS:
656 self.checkRef(str_ps)
657 txt = PERMSETS[perm][0]
658 assert not getter(perm), ("Empty permission set should not"
659 " have permission '%s'" % txt)
661 assert ps.test(perm), ("Permission '%s' should exist"
662 " after addition" % txt)
663 assert getter(perm), ("Permission '%s' should exist"
664 " after addition" % txt)
666 self.checkRef(str_ps)
668 assert not ps.test(perm), ("Permission '%s' should not exist"
669 " after deletion" % txt)
670 assert not getter(perm), ("Permission '%s' should not exist"
671 " after deletion" % txt)
673 def test_permset_invalid_type(self):
678 with pytest.raises(TypeError):
680 with pytest.raises(TypeError):
682 with pytest.raises(TypeError):
684 with pytest.raises(ValueError):
687 def test_qualifier_values(self):
688 """Tests qualifier correct store/retrieval"""
691 # work around deprecation warnings
692 for tag in [posix1e.ACL_USER, posix1e.ACL_GROUP]:
696 if tag == posix1e.ACL_USER:
697 regex = re.compile("user with uid %d" % qualifier)
699 regex = re.compile("group with gid %d" % qualifier)
701 e.qualifier = qualifier
702 except OverflowError:
703 # reached overflow condition, break
705 assert e.qualifier == qualifier
706 assert regex.search(str(e)) is not None
709 def test_qualifier_overflow(self):
710 """Tests qualifier overflow handling"""
713 qualifier = sys.maxsize * 2
714 for tag in [posix1e.ACL_USER, posix1e.ACL_GROUP]:
716 with pytest.raises(OverflowError):
717 e.qualifier = qualifier
719 def test_negative_qualifier(self):
720 """Tests negative qualifier handling"""
721 # Note: this presumes that uid_t/gid_t in C are unsigned...
724 for tag in [posix1e.ACL_USER, posix1e.ACL_GROUP]:
726 for qualifier in [-10, -5, -1]:
727 with pytest.raises(OverflowError):
728 e.qualifier = qualifier
730 def test_invalid_qualifier(self):
731 """Tests invalid qualifier handling"""
734 with pytest.raises(TypeError):
735 e.qualifier = object()
736 with pytest.raises((TypeError, AttributeError)):
739 def test_qualifier_on_wrong_tag(self):
740 """Tests qualifier setting on wrong tag"""
743 e.tag_type = posix1e.ACL_OTHER
744 with pytest.raises(TypeError):
746 with pytest.raises(TypeError):
749 @pytest.mark.parametrize("tag", ALL_TAG_VALUES, ids=ALL_TAG_DESCS)
750 def test_tag_types(self, tag):
751 """Tests tag type correct set/get"""
755 assert e.tag_type == tag
756 # check we can show all tag types without breaking
759 @pytest.mark.parametrize("src_tag", ALL_TAG_VALUES, ids=ALL_TAG_DESCS)
760 @pytest.mark.parametrize("dst_tag", ALL_TAG_VALUES, ids=ALL_TAG_DESCS)
761 def test_tag_overwrite(self, src_tag, dst_tag):
762 """Tests tag type correct set/get"""
766 assert e.tag_type == src_tag
769 assert e.tag_type == dst_tag
772 def test_invalid_tags(self):
773 """Tests tag type incorrect set/get"""
776 with pytest.raises(TypeError):
777 e.tag_type = object()
778 e.tag_type = posix1e.ACL_USER_OBJ
779 # For some reason, PyPy raises AttributeError. Strange...
780 with pytest.raises((TypeError, AttributeError)):
783 def test_tag_wrong_overwrite(self):
786 e.tag_type = posix1e.ACL_USER_OBJ
787 tag = max(ALL_TAG_VALUES) + 1
788 with pytest.raises(EnvironmentError):
790 # Check tag is still valid.
791 assert e.tag_type == posix1e.ACL_USER_OBJ
793 if __name__ == "__main__":