File: test_xattr.py

package info (click to toggle)
python-pyxattr 0.8.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 252 kB
  • sloc: ansic: 948; python: 483; makefile: 95; sh: 13
file content (494 lines) | stat: -rw-r--r-- 16,366 bytes parent folder | download
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
#
#

import sys
import tempfile
import os
import errno
import pytest
import pathlib
import platform
import io
import contextlib

import xattr
from xattr import NS_USER, XATTR_CREATE, XATTR_REPLACE

NAMESPACE = os.environ.get("NAMESPACE", NS_USER)

EMPTY_NS = bytes()

TEST_DIR = os.environ.get("TEST_DIR", ".")
TEST_IGNORE_XATTRS = os.environ.get("TEST_IGNORE_XATTRS", "")
if TEST_IGNORE_XATTRS == "":
    TEST_IGNORE_XATTRS = []
else:
    TEST_IGNORE_XATTRS = TEST_IGNORE_XATTRS.split(",")
    # The following has to be a list comprehension, not a generator, to
    # avoid weird consequences of lazy evaluation.
    TEST_IGNORE_XATTRS.extend([a.encode() for a in TEST_IGNORE_XATTRS])

USER_NN = "test"
USER_ATTR = NAMESPACE.decode() + "." + USER_NN
USER_VAL = "abc"
EMPTY_VAL = ""
LARGE_VAL = "x" * 2048
MANYOPS_COUNT = 16384

USER_NN = USER_NN.encode()
USER_VAL = USER_VAL.encode()
USER_ATTR = USER_ATTR.encode()
EMPTY_VAL = EMPTY_VAL.encode()
LARGE_VAL = LARGE_VAL.encode()

# Helper functions

def ignore_tuples(attrs):
    """Remove ignored attributes from the output of xattr.get_all."""
    return [attr for attr in attrs
            if attr[0] not in TEST_IGNORE_XATTRS]

def ignore(attrs):
    """Remove ignored attributes from the output of xattr.list"""
    return [attr for attr in attrs
            if attr not in TEST_IGNORE_XATTRS]

def lists_equal(attrs, value):
    """Helper to check list equivalence, skipping TEST_IGNORE_XATTRS."""
    assert ignore(attrs) == value

def tuples_equal(attrs, value):
    """Helper to check list equivalence, skipping TEST_IGNORE_XATTRS."""
    assert ignore_tuples(attrs) == value

# Fixtures and helpers

@pytest.fixture
def testdir():
    """per-test temp dir based in TEST_DIR"""
    with tempfile.TemporaryDirectory(dir=TEST_DIR) as dname:
        yield dname

def get_file(path):
    fh, fname = tempfile.mkstemp(".test", "xattr-", path)
    return fh, fname

@contextlib.contextmanager
def get_file_name(path):
    fh, fname = get_file(path)
    os.close(fh)
    yield fname

@contextlib.contextmanager
def get_file_fd(path):
    fd = get_file(path)[0]
    yield fd
    os.close(fd)

@contextlib.contextmanager
def get_file_object(path):
    fd = get_file(path)[0]
    with os.fdopen(fd) as f:
        yield f

@contextlib.contextmanager
def get_dir(path):
    yield tempfile.mkdtemp(".test", "xattr-", path)

def get_symlink(path, dangling=True):
    """create a symlink"""
    fh, fname = get_file(path)
    os.close(fh)
    if dangling:
        os.unlink(fname)
    sname = fname + ".symlink"
    os.symlink(fname, sname)
    return fname, sname

@contextlib.contextmanager
def get_valid_symlink(path):
    yield get_symlink(path, dangling=False)[1]

@contextlib.contextmanager
def get_dangling_symlink(path):
    yield get_symlink(path, dangling=True)[1]

@contextlib.contextmanager
def get_file_and_symlink(path):
    yield get_symlink(path, dangling=False)

@contextlib.contextmanager
def get_file_and_fobject(path):
    fh, fname = get_file(path)
    with os.fdopen(fh) as fo:
        yield fname, fo

# Wrappers that build upon existing values

def as_wrapper(call, fn, closer=None):
    @contextlib.contextmanager
    def f(path):
        with call(path) as r:
            val = fn(r)
            yield val
            if closer is not None:
                closer(val)
    return f

def as_bytes(call):
    return as_wrapper(call, lambda r: r.encode())

def as_fspath(call):
    return as_wrapper(call, pathlib.PurePath)

def as_iostream(call):
    opener = lambda f: io.open(f, "r")
    closer = lambda r: r.close()
    return as_wrapper(call, opener, closer)

NOT_BEFORE_36 = pytest.mark.xfail(condition="sys.version_info < (3,6)",
                                  strict=True)
NOT_PYPY = pytest.mark.xfail(condition="platform.python_implementation() == 'PyPy'",
                                  strict=False)

NOT_MACOSX = pytest.mark.xfail(condition="sys.platform.startswith('darwin')",
                               reason="Test not supported on MacOS",
                               strict=True)

# Note: user attributes are only allowed on files and directories, so
# we have to skip the symlinks here. See xattr(7).
ITEMS_P = [
    (get_file_name, False),
    (as_bytes(get_file_name), False),
    pytest.param((as_fspath(get_file_name), False),
                 marks=[NOT_BEFORE_36, NOT_PYPY]),
    (get_file_fd, False),
    (get_file_object, False),
    (as_iostream(get_file_name), False),
    (get_dir, False),
    (as_bytes(get_dir), False),
    pytest.param((as_fspath(get_dir), False),
                 marks=[NOT_BEFORE_36, NOT_PYPY]),
    (get_valid_symlink, False),
    (as_bytes(get_valid_symlink), False),
    pytest.param((as_fspath(get_valid_symlink), False),
                 marks=[NOT_BEFORE_36, NOT_PYPY]),
]

ITEMS_D = [
    "file name",
    "file name (bytes)",
    "file name (path)",
    "file FD",
    "file object",
    "file io stream",
    "directory",
    "directory (bytes)",
    "directory (path)",
    "file via symlink",
    "file via symlink (bytes)",
    "file via symlink (path)",
]

ALL_ITEMS_P = ITEMS_P + [
    (get_valid_symlink, True),
    (as_bytes(get_valid_symlink), True),
    (get_dangling_symlink, True),
    (as_bytes(get_dangling_symlink), True),
]

ALL_ITEMS_D = ITEMS_D + [
    "valid symlink",
    "valid symlink (bytes)",
    "dangling symlink",
    "dangling symlink (bytes)"
]

@pytest.fixture(params=ITEMS_P, ids=ITEMS_D)
def subject(testdir, request):
    with request.param[0](testdir) as value:
        yield value, request.param[1]

@pytest.fixture(params=ALL_ITEMS_P, ids=ALL_ITEMS_D)
def any_subject(testdir, request):
    with request.param[0](testdir) as value:
        yield value, request.param[1]

@pytest.fixture(params=[True, False], ids=["with namespace", "no namespace"])
def use_ns(request):
    return request.param

@pytest.fixture(params=[True, False], ids=["dangling", "valid"])
def use_dangling(request):
    return request.param

### Test functions

def test_empty_value(subject):
    item, nofollow = subject
    xattr.set(item, USER_ATTR, EMPTY_VAL, nofollow=nofollow)
    assert xattr.get(item, USER_ATTR, nofollow=nofollow) == EMPTY_VAL

def test_large_value(subject):
    item, nofollow = subject
    xattr.set(item, USER_ATTR, LARGE_VAL)
    assert xattr.get(item, USER_ATTR, nofollow=nofollow) == LARGE_VAL

@pytest.mark.parametrize(
    "gen", [ get_file_and_symlink, get_file_and_fobject ])
def test_mixed_access(testdir, gen):
    """test mixed access to file"""
    with gen(testdir) as (a, b):
        # Check empty
        lists_equal(xattr.list(a), [])
        lists_equal(xattr.listxattr(b), [])

        # Check value
        xattr.set(a, USER_ATTR, USER_VAL)
        for i in [a, b]:
            # Deprecated functions
            lists_equal(xattr.listxattr(i), [USER_ATTR])
            assert xattr.getxattr(i, USER_ATTR) == USER_VAL
            tuples_equal(xattr.get_all(i), [(USER_ATTR, USER_VAL)])
            # Current functions
            lists_equal(xattr.list(i), [USER_ATTR])
            assert xattr.list(i, namespace=NAMESPACE) == [USER_NN]
            assert xattr.get(i, USER_ATTR) == USER_VAL
            assert xattr.get(i, USER_NN, namespace=NAMESPACE) == USER_VAL
            tuples_equal(xattr.get_all(i),
                         [(USER_ATTR, USER_VAL)])
            assert xattr.get_all(i, namespace=NAMESPACE) == \
                [(USER_NN, USER_VAL)]

        # Overwrite
        xattr.set(b, USER_ATTR, LARGE_VAL, flags=xattr.XATTR_REPLACE)
        assert xattr.get(a, USER_ATTR) == LARGE_VAL
        assert xattr.getxattr(a, USER_ATTR) == LARGE_VAL
        xattr.removexattr(b, USER_ATTR)
        assert xattr.get_all(a, namespace=NAMESPACE) == []
        assert xattr.get_all(b, namespace=NAMESPACE) == []

def test_replace_on_missing(subject, use_ns):
    item = subject[0]
    lists_equal(xattr.list(item), [])
    with pytest.raises(EnvironmentError):
        if use_ns:
            xattr.set(item, USER_NN, USER_VAL, flags=XATTR_REPLACE,
                      namespace=NAMESPACE)
        else:
            xattr.set(item, USER_ATTR, USER_VAL, flags=XATTR_REPLACE)

def test_create_on_existing(subject, use_ns):
    item = subject[0]
    lists_equal(xattr.list(item), [])
    if use_ns:
        xattr.set(item, USER_NN, USER_VAL,
                  namespace=NAMESPACE)
    else:
        xattr.set(item, USER_ATTR, USER_VAL)
    with pytest.raises(EnvironmentError):
        if use_ns:
            xattr.set(item, USER_NN, USER_VAL,
                      flags=XATTR_CREATE, namespace=NAMESPACE)
        else:
            xattr.set(item, USER_ATTR, USER_VAL, flags=XATTR_CREATE)

def test_remove_on_missing(any_subject, use_ns):
    item, nofollow = any_subject
    lists_equal(xattr.list(item, nofollow=nofollow), [])
    with pytest.raises(EnvironmentError):
        if use_ns:
            xattr.remove(item, USER_NN, namespace=NAMESPACE,
                         nofollow=nofollow)
        else:
            xattr.remove(item, USER_ATTR, nofollow=nofollow)

def test_set_get_remove(subject, use_ns):
    item = subject[0]
    lists_equal(xattr.list(item), [])
    if use_ns:
        xattr.set(item, USER_NN, USER_VAL,
                  namespace=NAMESPACE)
    else:
        xattr.set(item, USER_ATTR, USER_VAL)
    if use_ns:
        assert xattr.list(item, namespace=NAMESPACE) == [USER_NN]
    else:
        lists_equal(xattr.list(item), [USER_ATTR])
        lists_equal(xattr.list(item, namespace=EMPTY_NS),
                    [USER_ATTR])
    if use_ns:
        assert xattr.get(item, USER_NN, namespace=NAMESPACE) == USER_VAL
    else:
        assert xattr.get(item, USER_ATTR) == USER_VAL
    if use_ns:
        assert xattr.get_all(item, namespace=NAMESPACE) == \
            [(USER_NN, USER_VAL)]
    else:
        tuples_equal(xattr.get_all(item),
                     [(USER_ATTR, USER_VAL)])
    if use_ns:
        xattr.remove(item, USER_NN, namespace=NAMESPACE)
    else:
        xattr.remove(item, USER_ATTR)
    lists_equal(xattr.list(item), [])
    tuples_equal(xattr.get_all(item), [])

def test_replace_on_missing_deprecated(subject):
    item = subject[0]
    lists_equal(xattr.listxattr(item), [])
    with pytest.raises(EnvironmentError):
        xattr.setxattr(item, USER_ATTR, USER_VAL, XATTR_REPLACE)

def test_create_on_existing_deprecated(subject):
    item = subject[0]
    lists_equal(xattr.listxattr(item), [])
    xattr.setxattr(item, USER_ATTR, USER_VAL, 0)
    with pytest.raises(EnvironmentError):
        xattr.setxattr(item, USER_ATTR, USER_VAL, XATTR_CREATE)

def test_remove_on_missing_deprecated(any_subject):
    """check deprecated list, set, get operations against an item"""
    item, nofollow = any_subject
    lists_equal(xattr.listxattr(item, nofollow), [])
    with pytest.raises(EnvironmentError):
        xattr.removexattr(item, USER_ATTR)

def test_set_get_remove_deprecated(subject):
    """check deprecated list, set, get operations against an item"""
    item = subject[0]
    lists_equal(xattr.listxattr(item), [])
    xattr.setxattr(item, USER_ATTR, USER_VAL, 0)
    lists_equal(xattr.listxattr(item), [USER_ATTR])
    assert xattr.getxattr(item, USER_ATTR) == USER_VAL
    tuples_equal(xattr.get_all(item), [(USER_ATTR, USER_VAL)])
    xattr.removexattr(item, USER_ATTR)
    lists_equal(xattr.listxattr(item), [])
    tuples_equal(xattr.get_all(item), [])

def test_many_ops(subject):
    """test many ops"""
    item = subject[0]
    xattr.set(item, USER_ATTR, USER_VAL)
    VL = [USER_ATTR]
    VN = [USER_NN]
    for i in range(MANYOPS_COUNT):
        lists_equal(xattr.list(item), VL)
        lists_equal(xattr.list(item, namespace=EMPTY_NS), VL)
        assert xattr.list(item, namespace=NAMESPACE) == VN
    for i in range(MANYOPS_COUNT):
        assert xattr.get(item, USER_ATTR) == USER_VAL
        assert xattr.get(item, USER_NN, namespace=NAMESPACE) == USER_VAL
    for i in range(MANYOPS_COUNT):
        tuples_equal(xattr.get_all(item),
                     [(USER_ATTR, USER_VAL)])
        assert xattr.get_all(item, namespace=NAMESPACE) == \
            [(USER_NN, USER_VAL)]

def test_many_ops_deprecated(subject):
    """test many ops (deprecated functions)"""
    item = subject[0]
    xattr.setxattr(item, USER_ATTR, USER_VAL)
    VL = [USER_ATTR]
    for i in range(MANYOPS_COUNT):
        lists_equal(xattr.listxattr(item), VL)
    for i in range(MANYOPS_COUNT):
        assert xattr.getxattr(item, USER_ATTR) == USER_VAL
    for i in range(MANYOPS_COUNT):
        tuples_equal(xattr.get_all(item),
                     [(USER_ATTR, USER_VAL)])

def test_no_attributes_deprecated(any_subject):
    """test no attributes (deprecated functions)"""
    item, nofollow = any_subject
    lists_equal(xattr.listxattr(item, True), [])
    tuples_equal(xattr.get_all(item, True), [])
    with pytest.raises(EnvironmentError):
        xattr.getxattr(item, USER_ATTR, True)

def test_no_attributes(any_subject):
    """test no attributes"""
    item, nofollow = any_subject
    lists_equal(xattr.list(item, nofollow=nofollow), [])
    assert xattr.list(item, nofollow=nofollow,
                      namespace=NAMESPACE) == []
    tuples_equal(xattr.get_all(item, nofollow=nofollow), [])
    assert xattr.get_all(item, nofollow=nofollow,
                         namespace=NAMESPACE) == []
    with pytest.raises(EnvironmentError):
        xattr.get(item, USER_NN, nofollow=nofollow,
                  namespace=NAMESPACE)

def test_binary_payload_deprecated(subject):
    """test binary values (deprecated functions)"""
    item = subject[0]
    BINVAL = b"abc\0def"
    xattr.setxattr(item, USER_ATTR, BINVAL)
    lists_equal(xattr.listxattr(item), [USER_ATTR])
    assert xattr.getxattr(item, USER_ATTR) == BINVAL
    tuples_equal(xattr.get_all(item), [(USER_ATTR, BINVAL)])
    xattr.removexattr(item, USER_ATTR)

def test_binary_payload(subject):
    """test binary values"""
    item = subject[0]
    BINVAL = b"abc\0def"
    xattr.set(item, USER_ATTR, BINVAL)
    lists_equal(xattr.list(item), [USER_ATTR])
    assert xattr.list(item, namespace=NAMESPACE) == [USER_NN]
    assert xattr.get(item, USER_ATTR) == BINVAL
    assert xattr.get(item, USER_NN, namespace=NAMESPACE) == BINVAL
    tuples_equal(xattr.get_all(item), [(USER_ATTR, BINVAL)])
    assert xattr.get_all(item, namespace=NAMESPACE) == [(USER_NN, BINVAL)]
    xattr.remove(item, USER_ATTR)

@NOT_MACOSX
def test_symlinks_user_fail(testdir, use_dangling):
    _, sname = get_symlink(testdir, dangling=use_dangling)
    with pytest.raises(IOError):
        xattr.set(sname, USER_ATTR, USER_VAL, nofollow=True)
    with pytest.raises(IOError):
        xattr.set(sname, USER_NN, USER_VAL, namespace=NAMESPACE,
                  nofollow=True)
    with pytest.raises(IOError):
        xattr.setxattr(sname, USER_ATTR, USER_VAL, XATTR_CREATE, True)

@pytest.mark.parametrize(
    "call, args", [(xattr.get, [USER_ATTR]),
                   (xattr.list, []),
                   (xattr.remove, [USER_ATTR]),
                   (xattr.get, [USER_ATTR]),
                   (xattr.set, [USER_ATTR, USER_VAL])])
def test_none_namespace(testdir, call, args):
    # Don't want to use subject, since that would prevent xfail test
    # on path objects (due to hiding the exception here).
    f = get_file_name(testdir)
    with pytest.raises(TypeError):
        call(f, *args, namespace=None)
    fd = get_file_fd(testdir)
    with pytest.raises(TypeError):
        call(fd, *args, namespace=None)

@pytest.mark.parametrize(
    "call",
    [xattr.get, xattr.list, xattr.listxattr,
     xattr.remove, xattr.removexattr,
     xattr.set, xattr.setxattr,
     xattr.get, xattr.getxattr])
def test_wrong_call(call):
    with pytest.raises(TypeError):
        call()

@pytest.mark.parametrize(
    "call, args", [(xattr.get, [USER_ATTR]),
                   (xattr.listxattr, []),
                   (xattr.list, []),
                   (xattr.remove, [USER_ATTR]),
                   (xattr.removexattr, [USER_ATTR]),
                   (xattr.get, [USER_ATTR]),
                   (xattr.getxattr, [USER_ATTR]),
                   (xattr.set, [USER_ATTR, USER_VAL]),
                   (xattr.setxattr, [USER_ATTR, USER_VAL])])
def test_wrong_argument_type(call, args):
    with pytest.raises(TypeError):
        call(object(), *args)