]> arthur.barton.de Git - bup.git/blob - lib/bup/t/tmetadata.py
Don't use multiple with context clauses
[bup.git] / lib / bup / t / tmetadata.py
1
2 import errno, glob, grp, pwd, stat, tempfile, subprocess
3
4 from wvtest import *
5
6 from bup import git, metadata, vfs
7 from bup.helpers import clear_errors, detect_fakeroot, is_superuser, resolve_parent
8 from bup.xstat import utime, lutime
9 from buptest import no_lingering_errors, test_tempdir
10 import bup.helpers as helpers
11
12
13 top_dir = '../../..'
14 bup_tmp = os.path.realpath('../../../t/tmp')
15 bup_path = top_dir + '/bup'
16 start_dir = os.getcwd()
17
18
19 def ex(*cmd):
20     try:
21         cmd_str = ' '.join(cmd)
22         print >> sys.stderr, cmd_str
23         rc = subprocess.call(cmd)
24         if rc < 0:
25             print >> sys.stderr, 'terminated by signal', - rc
26             sys.exit(1)
27         elif rc > 0:
28             print >> sys.stderr, 'returned exit status', rc
29             sys.exit(1)
30     except OSError as e:
31         print >> sys.stderr, 'subprocess call failed:', e
32         sys.exit(1)
33
34
35 def setup_testfs():
36     assert(sys.platform.startswith('linux'))
37     # Set up testfs with user_xattr, etc.
38     if subprocess.call(['modprobe', 'loop']) != 0:
39         return False
40     subprocess.call(['umount', 'testfs'])
41     ex('dd', 'if=/dev/zero', 'of=testfs.img', 'bs=1M', 'count=32')
42     ex('mke2fs', '-F', '-j', '-m', '0', 'testfs.img')
43     ex('rm', '-rf', 'testfs')
44     os.mkdir('testfs')
45     ex('mount', '-o', 'loop,acl,user_xattr', 'testfs.img', 'testfs')
46     # Hide, so that tests can't create risks.
47     os.chown('testfs', 0, 0)
48     os.chmod('testfs', 0o700)
49     return True
50
51
52 def cleanup_testfs():
53     subprocess.call(['umount', 'testfs'])
54     helpers.unlink('testfs.img')
55
56
57 @wvtest
58 def test_clean_up_archive_path():
59     with no_lingering_errors():
60         cleanup = metadata._clean_up_path_for_archive
61         WVPASSEQ(cleanup('foo'), 'foo')
62         WVPASSEQ(cleanup('/foo'), 'foo')
63         WVPASSEQ(cleanup('///foo'), 'foo')
64         WVPASSEQ(cleanup('/foo/bar'), 'foo/bar')
65         WVPASSEQ(cleanup('foo/./bar'), 'foo/bar')
66         WVPASSEQ(cleanup('/foo/./bar'), 'foo/bar')
67         WVPASSEQ(cleanup('/foo/./bar/././baz'), 'foo/bar/baz')
68         WVPASSEQ(cleanup('/foo/./bar///././baz'), 'foo/bar/baz')
69         WVPASSEQ(cleanup('//./foo/./bar///././baz/.///'), 'foo/bar/baz/')
70         WVPASSEQ(cleanup('./foo/./.bar'), 'foo/.bar')
71         WVPASSEQ(cleanup('./foo/.'), 'foo')
72         WVPASSEQ(cleanup('./foo/..'), '.')
73         WVPASSEQ(cleanup('//./..//.../..//.'), '.')
74         WVPASSEQ(cleanup('//./..//..././/.'), '...')
75         WVPASSEQ(cleanup('/////.'), '.')
76         WVPASSEQ(cleanup('/../'), '.')
77         WVPASSEQ(cleanup(''), '.')
78
79
80 @wvtest
81 def test_risky_path():
82     with no_lingering_errors():
83         risky = metadata._risky_path
84         WVPASS(risky('/foo'))
85         WVPASS(risky('///foo'))
86         WVPASS(risky('/../foo'))
87         WVPASS(risky('../foo'))
88         WVPASS(risky('foo/..'))
89         WVPASS(risky('foo/../'))
90         WVPASS(risky('foo/../bar'))
91         WVFAIL(risky('foo'))
92         WVFAIL(risky('foo/'))
93         WVFAIL(risky('foo///'))
94         WVFAIL(risky('./foo'))
95         WVFAIL(risky('foo/.'))
96         WVFAIL(risky('./foo/.'))
97         WVFAIL(risky('foo/bar'))
98         WVFAIL(risky('foo/./bar'))
99
100
101 @wvtest
102 def test_clean_up_extract_path():
103     with no_lingering_errors():
104         cleanup = metadata._clean_up_extract_path
105         WVPASSEQ(cleanup('/foo'), 'foo')
106         WVPASSEQ(cleanup('///foo'), 'foo')
107         WVFAIL(cleanup('/../foo'))
108         WVFAIL(cleanup('../foo'))
109         WVFAIL(cleanup('foo/..'))
110         WVFAIL(cleanup('foo/../'))
111         WVFAIL(cleanup('foo/../bar'))
112         WVPASSEQ(cleanup('foo'), 'foo')
113         WVPASSEQ(cleanup('foo/'), 'foo/')
114         WVPASSEQ(cleanup('foo///'), 'foo///')
115         WVPASSEQ(cleanup('./foo'), './foo')
116         WVPASSEQ(cleanup('foo/.'), 'foo/.')
117         WVPASSEQ(cleanup('./foo/.'), './foo/.')
118         WVPASSEQ(cleanup('foo/bar'), 'foo/bar')
119         WVPASSEQ(cleanup('foo/./bar'), 'foo/./bar')
120         WVPASSEQ(cleanup('/'), '.')
121         WVPASSEQ(cleanup('./'), './')
122         WVPASSEQ(cleanup('///foo/bar'), 'foo/bar')
123         WVPASSEQ(cleanup('///foo/bar'), 'foo/bar')
124
125
126 @wvtest
127 def test_metadata_method():
128     with no_lingering_errors():
129         with test_tempdir('bup-tmetadata-') as tmpdir:
130             bup_dir = tmpdir + '/bup'
131             data_path = tmpdir + '/foo'
132             os.mkdir(data_path)
133             ex('touch', data_path + '/file')
134             ex('ln', '-s', 'file', data_path + '/symlink')
135             test_time1 = 13 * 1000000000
136             test_time2 = 42 * 1000000000
137             utime(data_path + '/file', (0, test_time1))
138             lutime(data_path + '/symlink', (0, 0))
139             utime(data_path, (0, test_time2))
140             ex(bup_path, '-d', bup_dir, 'init')
141             ex(bup_path, '-d', bup_dir, 'index', '-v', data_path)
142             ex(bup_path, '-d', bup_dir, 'save', '-tvvn', 'test', data_path)
143             git.check_repo_or_die(bup_dir)
144             top = vfs.RefList(None)
145             n = top.lresolve('/test/latest' + resolve_parent(data_path))
146             m = n.metadata()
147             WVPASS(m.mtime == test_time2)
148             WVPASS(len(n.subs()) == 2)
149             WVPASS(n.name == 'foo')
150             WVPASS(set([x.name for x in n.subs()]) == set(['file', 'symlink']))
151             for sub in n:
152                 if sub.name == 'file':
153                     m = sub.metadata()
154                     WVPASS(m.mtime == test_time1)
155                 elif sub.name == 'symlink':
156                     m = sub.metadata()
157                     WVPASS(m.mtime == 0)
158
159
160 def _first_err():
161     if helpers.saved_errors:
162         return str(helpers.saved_errors[0])
163     return ''
164
165
166 @wvtest
167 def test_from_path_error():
168     if is_superuser() or detect_fakeroot():
169         return
170     with no_lingering_errors():
171         with test_tempdir('bup-tmetadata-') as tmpdir:
172             path = tmpdir + '/foo'
173             os.mkdir(path)
174             m = metadata.from_path(path, archive_path=path, save_symlinks=True)
175             WVPASSEQ(m.path, path)
176             os.chmod(path, 000)
177             metadata.from_path(path, archive_path=path, save_symlinks=True)
178             if metadata.get_linux_file_attr:
179                 print >> sys.stderr, 'saved_errors:', helpers.saved_errors
180                 WVPASS(len(helpers.saved_errors) == 1)
181                 errmsg = _first_err()
182                 WVPASS(errmsg.startswith('read Linux attr'))
183                 clear_errors()
184
185
186 def _linux_attr_supported(path):
187     # Expects path to denote a regular file or a directory.
188     if not metadata.get_linux_file_attr:
189         return False
190     try:
191         metadata.get_linux_file_attr(path)
192     except OSError as e:
193         if e.errno in (errno.ENOTTY, errno.ENOSYS, errno.EOPNOTSUPP):
194             return False
195         else:
196             raise
197     return True
198
199
200 @wvtest
201 def test_apply_to_path_restricted_access():
202     if is_superuser() or detect_fakeroot():
203         return
204     if sys.platform.startswith('cygwin'):
205         return # chmod 000 isn't effective.
206     with no_lingering_errors():
207         with test_tempdir('bup-tmetadata-') as tmpdir:
208             parent = tmpdir + '/foo'
209             path = parent + '/bar'
210             os.mkdir(parent)
211             os.mkdir(path)
212             clear_errors()
213             m = metadata.from_path(path, archive_path=path, save_symlinks=True)
214             WVPASSEQ(m.path, path)
215             os.chmod(parent, 000)
216             m.apply_to_path(path)
217             print >> sys.stderr, 'saved_errors:', helpers.saved_errors
218             expected_errors = ['utime: ']
219             if m.linux_attr and _linux_attr_supported(tmpdir):
220                 expected_errors.append('Linux chattr: ')
221             if metadata.xattr and m.linux_xattr:
222                 expected_errors.append("xattr.set '")
223             WVPASS(len(helpers.saved_errors) == len(expected_errors))
224             for i in xrange(len(expected_errors)):
225                 WVPASS(str(helpers.saved_errors[i]).startswith(expected_errors[i]))
226             clear_errors()
227
228
229 @wvtest
230 def test_restore_over_existing_target():
231     with no_lingering_errors():
232         with test_tempdir('bup-tmetadata-') as tmpdir:
233             path = tmpdir + '/foo'
234             os.mkdir(path)
235             dir_m = metadata.from_path(path, archive_path=path, save_symlinks=True)
236             os.rmdir(path)
237             open(path, 'w').close()
238             file_m = metadata.from_path(path, archive_path=path, save_symlinks=True)
239             # Restore dir over file.
240             WVPASSEQ(dir_m.create_path(path, create_symlinks=True), None)
241             WVPASS(stat.S_ISDIR(os.stat(path).st_mode))
242             # Restore dir over dir.
243             WVPASSEQ(dir_m.create_path(path, create_symlinks=True), None)
244             WVPASS(stat.S_ISDIR(os.stat(path).st_mode))
245             # Restore file over dir.
246             WVPASSEQ(file_m.create_path(path, create_symlinks=True), None)
247             WVPASS(stat.S_ISREG(os.stat(path).st_mode))
248             # Restore file over file.
249             WVPASSEQ(file_m.create_path(path, create_symlinks=True), None)
250             WVPASS(stat.S_ISREG(os.stat(path).st_mode))
251             # Restore file over non-empty dir.
252             os.remove(path)
253             os.mkdir(path)
254             open(path + '/bar', 'w').close()
255             WVEXCEPT(Exception, file_m.create_path, path, create_symlinks=True)
256             # Restore dir over non-empty dir.
257             os.remove(path + '/bar')
258             os.mkdir(path + '/bar')
259             WVEXCEPT(Exception, dir_m.create_path, path, create_symlinks=True)
260
261
262 from bup.metadata import posix1e
263 if not posix1e:
264     @wvtest
265     def POSIX1E_ACL_SUPPORT_IS_MISSING():
266         pass
267
268
269 from bup.metadata import xattr
270 if xattr:
271     @wvtest
272     def test_handling_of_incorrect_existing_linux_xattrs():
273         if not is_superuser() or detect_fakeroot():
274             WVMSG('skipping test -- not superuser')
275             return
276         if not setup_testfs():
277             WVMSG('unable to load loop module; skipping dependent tests')
278             return
279         for f in glob.glob('testfs/*'):
280             ex('rm', '-rf', f)
281         path = 'testfs/foo'
282         open(path, 'w').close()
283         xattr.set(path, 'foo', 'bar', namespace=xattr.NS_USER)
284         m = metadata.from_path(path, archive_path=path, save_symlinks=True)
285         xattr.set(path, 'baz', 'bax', namespace=xattr.NS_USER)
286         m.apply_to_path(path, restore_numeric_ids=False)
287         WVPASSEQ(xattr.list(path), ['user.foo'])
288         WVPASSEQ(xattr.get(path, 'user.foo'), 'bar')
289         xattr.set(path, 'foo', 'baz', namespace=xattr.NS_USER)
290         m.apply_to_path(path, restore_numeric_ids=False)
291         WVPASSEQ(xattr.list(path), ['user.foo'])
292         WVPASSEQ(xattr.get(path, 'user.foo'), 'bar')
293         xattr.remove(path, 'foo', namespace=xattr.NS_USER)
294         m.apply_to_path(path, restore_numeric_ids=False)
295         WVPASSEQ(xattr.list(path), ['user.foo'])
296         WVPASSEQ(xattr.get(path, 'user.foo'), 'bar')
297         os.chdir(start_dir)
298         cleanup_testfs()