Debian Codegraph @

test/gvfs-test

raw ◀ ▶
2 Debian patches touch this file
1 #!/usr/bin/env python3
2
3 __author__ = 'Martin Pitt <[email protected]>'
4 __copyright__ = '(C) 2012 Canonical Ltd.'
5 __license__ = 'LGPL v2 or later'
6
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General
18 # Public License along with this library; if not, write to the
19 # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 # Boston, MA 02110-1301, USA.
21
22 import os
23 import os.path
24 import sys
25 import unittest
26 import subprocess
27 import tempfile
28 import tarfile
29 import zipfile
30 import time
31 import shutil
32 import fcntl
33 import re
34 import locale
35 import socket
36 from glob import glob
37
38 from gi.repository import GLib, Gio
39
40 os.environ['GIO_USE_VFS'] = 'gvfs'
41
42 try:
43 import gi
44 gi.require_version('UMockdev', '1.0')
45 from gi.repository import UMockdev
46 have_umockdev = shutil.which('umockdev-wrapper') != None
47 # needs >= 0.2.10
48 have_umockdev = have_umockdev and hasattr(UMockdev.Testbed, 'add_from_file')
49 except (ValueError, ImportError):
50 have_umockdev = False
51
52 # umockdev environment for gphoto/MTP tests
53 umockdev_testbed = None
54
55 smbd_path = shutil.which('smbd')
56
57 def find_alternative(cmds):
58 '''Find command in cmds array and return the found alternative'''
59
60 for cmd in cmds:
61 if shutil.which(cmd) != None:
62 return cmd
63
64 in_testbed = os.path.exists('/home/gvfs_sandbox_marker')
65 samba_running = subprocess.call(['pidof', 'smbd'], stdout=subprocess.PIPE) == 0
66 httpd_cmd = find_alternative(['apache2', 'httpd', 'apachectl'])
67 have_httpd = httpd_cmd is not None
68 sshd_path = shutil.which('sshd')
69 twistd_path = find_alternative(['twistd-3', 'twistd3'])
70
71 local_ip = subprocess.check_output("ip -4 addr | sed -nr '/127\.0\.0/ n; "
72 "/inet / { s/^.*inet ([0-9.]+).*$/\\1/; p; q }'"
73 "| tr -d '\n'",
74 shell=True, universal_newlines=True)
75
76 SMB_USER_PORT = 1445
77
78 # when running in the build tree, check whether Dav backend is enabled
79 have_dav_backend = True
80 if 'GVFS_MOUNTABLE_DIR' in os.environ:
81 have_dav_backend = os.path.exists(os.path.join(os.environ['GVFS_MOUNTABLE_DIR'], 'dav.localmount'))
82
83 my_dir = os.path.dirname(os.path.abspath(__file__))
84
85 # we need this flag to check if we can test error messages
86 locale.setlocale(locale.LC_ALL, '')
87 lc = locale.getlocale(locale.LC_MESSAGES)[0]
88 english_messages = not lc or lc.startswith('en_')
89
90 # http://sg.danny.cz/sg/sdebug26.html
91 PTYPE_DISK = 0
92 PTYPE_CDROM = 5
93
94 # local D-BUS daemon
95 dbus_daemon = None
96
97
98 class GvfsTestCase(unittest.TestCase):
99 '''Gvfs tests base class.
100
101 Provide some utility functions and a temporary work dir.
102 '''
103 def setUp(self):
104 self.workdir = tempfile.mkdtemp()
105
106 def tearDown(self):
107 shutil.rmtree(self.workdir)
108 if umockdev_testbed:
109 umockdev_testbed.clear()
110
111 def run(self, result=None):
112 '''Show dbus daemon output on failed tests'''
113
114 if result:
115 orig_err_fail = len(result.errors) + len(result.failures)
116 super().run(result)
117 # always read the logs, so that we only get the ones relevant to this
118 # particular test case
119 dbus_out = dbus_daemon.stdout.read()
120 dbus_err = dbus_daemon.stderr.read()
121 if result and len(result.errors) + len(result.failures) > orig_err_fail:
122 print('\n----- dbus stdout -----\n%s\n----- dbus stderr -----\n%s\n' %
123 (dbus_out and dbus_out.decode('UTF-8') or '',
124 dbus_err and dbus_err.decode('UTF-8') or ''))
125
126 def program_code_out_err(self, argv):
127 '''Return (exitcode, stdout, stderr) from a program call.'''
128
129 prog = subprocess.Popen(argv, stdout=subprocess.PIPE,
130 stderr=subprocess.PIPE, universal_newlines=True)
131 (out, err) = prog.communicate()
132 return (prog.returncode, out, err)
133
134 def program_out_err(self, argv):
135 '''Return (stdout, stderr) from a program call.'''
136
137 (code, out, err) = self.program_code_out_err(argv)
138 self.assertEqual(code, 0, err)
139 return (out, err)
140
141 def program_out_success(self, argv):
142 '''Return stdout from a successful program call.'''
143
144 (out, err) = self.program_out_err(argv)
145 self.assertEqual(err, '', err)
146 return out
147
148 @classmethod
149 def root_command(klass, command):
150 '''Run a shell command string as root.
151
152 This only works when running under gvfs-testbed.
153
154 Return (code, stdout, stderr).
155 '''
156 assert in_testbed, 'root_command() only works under gvfs-testbed'
157
158 rootsh = subprocess.Popen(['./rootsh', '-p'], stdin=subprocess.PIPE,
159 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
160 # set reasonable path that includes /sbin
161 rootsh.stdin.write(b'export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n')
162
163 (out, err) = rootsh.communicate(command.encode('UTF-8'))
164 return (rootsh.returncode, out.decode('UTF-8'), err.decode('UTF-8'))
165
166 @classmethod
167 def root_command_success(klass, command):
168 '''root_command() for commands that should succeed without errors.'''
169
170 (code, out, err) = klass.root_command(command)
171 if code != 0:
172 raise SystemError('command "%s" failed with code %i:\n%s' % (command, code, err))
173 if err:
174 raise SystemError('command "%s" produced error:\n%s' % (command, err))
175
176 def unmount(self, uri):
177 self.program_out_success(['gio', 'mount', '-u', uri])
178
•179 timeout = 10
180 while timeout > 0:
181 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
182 if not re.search('Mount.*' + uri, out):
183 break
184 timeout -= 1
185 time.sleep(1)
186 else:
187 self.fail('gio mount -u %s failed' % uri)
188
189 @classmethod
190 def quote(klass, path):
191 '''Quote a path for GIO URLs'''
192
193 return path.replace('%', '%25').replace('/', '%2F').replace(':', '%3A')
194
195 def wait_for_gvfs_mount_user_prompt(self, popen):
196 '''Wait for a gio mount Popen process to show an User auth prompt'''
197
198 empty_timeout = 50
199
200 # set stdout to nonblocking
201 flags = fcntl.fcntl(popen.stdout, fcntl.F_GETFL)
202 fcntl.fcntl(popen.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
203 while True:
204 r = popen.stdout.read(1000)
205 # print(' wait_for_gvfs_mount_user_prompt: got "%s"' % str(r))
206 if r and (b'User' in r or b'Domain' in r):
207 break
208
209 self.assertGreater(empty_timeout, 0,
210 'timed out waiting for auth prompt')
211 empty_timeout -= 1
212 time.sleep(0.1)
213
214 # restore flags
215 fcntl.fcntl(popen.stdout, fcntl.F_SETFL, flags)
216
217 def wait_for_question(self, popen):
218 '''Wait for a gio mount Popen process to show an question prompt'''
219
220 empty_timeout = 50
221
222 # set stdout to nonblocking
223 flags = fcntl.fcntl(popen.stdout, fcntl.F_GETFL)
224 fcntl.fcntl(popen.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
225 while True:
226 r = popen.stdout.read(1000)
227 if r and (b'Choice' in r):
228 break
229
230 self.assertGreater(empty_timeout, 0,
231 'timed out waiting for question prompt')
232 empty_timeout -= 1
233 time.sleep(0.1)
234
235 # restore flags
236 fcntl.fcntl(popen.stdout, fcntl.F_SETFL, flags)
237
238 def mount_api(self, gfile, mount_op=None):
239 '''Mount a Gio.File using the Gio API
240
241 This times out after 30 seconds.
242
243 Return True on success or a GLib.GError object from the mount call.
244 '''
245 self.cb_result = None
246
247 def mount_done(obj, result, main_loop):
248 ml.quit()
249 try:
250 success = obj.mount_enclosing_volume_finish(result)
251 self.cb_result = (obj, success)
252 except GLib.GError as e:
253 self.cb_result = (obj, e)
254
255 ml = GLib.MainLoop()
256 gfile.mount_enclosing_volume(Gio.MountMountFlags.NONE, mount_op, None, mount_done, ml)
257 # ensure we are timing out
258 GLib.timeout_add_seconds(30, lambda data: ml.quit(), None)
259 ml.run()
260
261 self.assertNotEqual(self.cb_result, None, 'operation timed out')
262 self.assertEqual(self.cb_result[0], gfile)
263 return self.cb_result[1]
264
265 def unmount_api(self, gfile):
266 '''Umount a mounted Gio.File using the Gio API
267
•268 This times out after 10 seconds.
269 '''
270 self.cb_result = None
271
272 def unmount_done(obj, result, main_loop):
273 success = obj.unmount_with_operation_finish(result)
274 self.cb_result = (obj, success)
275 main_loop.quit()
276
277 mount = gfile.find_enclosing_mount(None)
278 self.assertNotEqual(mount, None)
279
280 ml = GLib.MainLoop()
281
282 mount.unmount_with_operation(Gio.MountUnmountFlags.NONE, None, None,
283 unmount_done, ml)
284 # ensure we are timing out
•285 GLib.timeout_add_seconds(10, lambda data: ml.quit(), None)
286 ml.run()
287
288 self.assertNotEqual(self.cb_result, None, 'operation timed out')
289 self.assertEqual(self.cb_result[0], mount)
290 self.assertTrue(self.cb_result[1])
291
292 def make_mountop(self, user=None, password=None):
293 '''Create a Gio.MountOperation from given credentials
294 (anonymous is requested if credentials aren't given)
295
296 On the first ask_password signal this sends the password, and aborts
297 the second request (for tests that use wrong credentials).
298 '''
299 def pwd_cb(op, message, default_user, default_domain, flags, data):
300 # first call: send correct result
301 if op.get_username() or op.get_anonymous():
302 op.reply(Gio.MountOperationResult.HANDLED)
303
304 # subsequent calls: abort
305 op.set_username('')
306 mo.set_anonymous(False)
307 op.reply(Gio.MountOperationResult.ABORTED)
308
309 mo = Gio.MountOperation.new()
310 if user is None and password is None:
311 mo.set_anonymous(True)
312 else:
313 mo.set_username(user)
314 mo.set_password(password)
315 mo.connect('ask_password', pwd_cb, None)
316 return mo
317
318
319 class ArchiveMounter(GvfsTestCase):
320 def add_files(self, add_fn):
321 '''Add test files to an archive'''
322
323 p = os.path.join(self.workdir, 'hello.txt')
324 with open(p, 'w') as f:
325 f.write('hello\n')
326 add_fn(p, 'hello.txt')
327
328 p = os.path.join(self.workdir, 'bye.txt')
329 with open(p, 'w') as f:
330 f.write('bye\n')
331 add_fn(p, 'stuff/bye.txt')
332
333 def test_tar(self):
334 '''archive:// for tar'''
335
336 tar_path = os.path.join(self.workdir, 'stuff.tar')
337 tf = tarfile.open(tar_path, 'w')
338 self.add_files(tf.add)
339 tf.close()
340
341 self.do_test_for_archive(tar_path)
342
343 def test_tar_gz(self):
344 '''archive:// for tar.gz'''
345
346 tar_path = os.path.join(self.workdir, 'stuff.tar.gz')
347 tf = tarfile.open(tar_path, 'w:gz')
348 self.add_files(tf.add)
349 tf.close()
350
351 self.do_test_for_archive(tar_path)
352
353 def test_tar_bz2(self):
354 '''archive:// for tar.bz2'''
355
356 tar_path = os.path.join(self.workdir, 'stuff.tar.bz2')
357 tf = tarfile.open(tar_path, 'w:bz2')
358 self.add_files(tf.add)
359 tf.close()
360
361 self.do_test_for_archive(tar_path)
362
363 def test_zip(self):
364 '''archive:// for .zip'''
365
366 zip_path = os.path.join(self.workdir, 'stuff.zip')
367 zf = zipfile.ZipFile(zip_path, 'w')
368 self.add_files(zf.write)
369 zf.close()
370
371 self.do_test_for_archive(zip_path)
372
373 def test_iso_rr(self):
374 '''archive:// for RockRidge .iso'''
375
376 iso = os.path.join(self.workdir, 'bogus-cd.iso')
377 with open(iso, 'wb') as f:
378 subprocess.check_call(['bzip2', '-cd', os.path.join(my_dir, 'files', 'bogus-cd.iso.bz2')],
379 stdout=f)
380 self.do_test_for_archive(iso)
381
382 def test_iso_joliet(self):
383 '''archive:// for Joliet .iso'''
384
385 iso = os.path.join(self.workdir, 'joliet.iso')
386 with open(iso, 'wb') as f:
387 subprocess.check_call(['bzip2', '-cd', os.path.join(my_dir, 'files', 'joliet.iso.bz2')],
388 stdout=f)
389 self.do_test_for_archive(iso)
390
391 def do_test_for_archive(self, path):
392 # mount it; yes, gvfs expects double quoting
393 uri = 'archive://' + self.quote(self.quote('file://' + path))
394 subprocess.check_call(['gio', 'mount', uri])
395
396 # appears in gio mount list
397 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
398 try:
399 self.assertTrue('Mount(0)' in out, out)
400 self.assertTrue('%s -> %s' % (os.path.basename(path), uri) in out, out)
401
402 # check gio info
403 out = self.program_out_success(['gio', 'info', uri])
404 self.assertTrue('standard::content-type: inode/directory' in out, out)
405 self.assertTrue('access::can-read: TRUE' in out, out)
406
407 # check gio cat
408 out = self.program_out_success(['gio', 'cat', uri + '/hello.txt'])
409 self.assertEqual(out, 'hello\n')
410 out = self.program_out_success(['gio', 'cat', uri + '/stuff/bye.txt'])
411 self.assertEqual(out, 'bye\n')
412 finally:
413 self.unmount(uri)
414
415 def test_api(self):
416 '''archive:// with Gio API'''
417
418 tar_path = os.path.join(self.workdir, 'stuff.tar')
419 tf = tarfile.open(tar_path, 'w')
420 tf.add(__file__, 'gvfs-test.py')
421 tf.close()
422 uri = 'archive://' + self.quote(self.quote('file://' + tar_path))
423
424 gfile = Gio.File.new_for_uri(uri)
425
426 # not mounted yet, should fail
427 self.assertRaises(GLib.GError, gfile.query_info, '*', 0, None)
428
429 self.assertEqual(self.mount_api(gfile), True)
430 try:
431 info = gfile.query_info('*', 0, None)
432 self.assertEqual(info.get_content_type(), 'inode/directory')
433 self.assertEqual(info.get_file_type(), Gio.FileType.DIRECTORY)
434 self.assertTrue('stuff.tar' in info.get_display_name(),
435 info.get_display_name())
436 self.assertEqual(info.get_attribute_boolean('access::can-read'), True)
437 finally:
438 self.unmount_api(gfile)
439
440
441 @unittest.skipUnless(sshd_path != None, 'sshd not installed')
442 @unittest.skipUnless(os.getenv('XDG_RUNTIME_DIR'), 'No $XDG_RUNTIME_DIR available')
443 @unittest.skipUnless(os.path.exists(os.path.expanduser('~/.ssh/id_rsa')), 'This test needs an existing ~/.ssh/id_rsa')
444 class Sftp(GvfsTestCase):
445 def setUp(self):
446 '''Run ssh server'''
447
448 super().setUp()
449
450 # find sftp-server
451 for dir in ['/usr/local/lib/openssh',
452 '/usr/lib/openssh',
453 '/usr/local/libexec/openssh',
454 '/usr/libexec/openssh',
455 '/usr/lib/misc', '/usr/lib64/misc']:
456 sftp_server = os.path.join(dir, 'sftp-server')
457 if os.path.exists(sftp_server):
458 break
459 else:
460 self.fail('Cannot locate OpenSSH sftp-server program, please update tests for your distribution')
461
462 # look for authorized_keys in a temporary dir, to avoid having to mess
463 # with the actual user files when not calling this through gvfs-testbed
464 # (unfortunately ssh doesn't consider $HOME); NB we cannot use
465 # self.workdir as ssh refuses files in /tmp.
466 self.authorized_keys = os.path.join(os.environ['XDG_RUNTIME_DIR'],
467 'gvfs_test_authorized_keys')
468
469 # generate sshd configuration; note that we must ensure that the
470 # private key is not world-readable, so we need to copy it
471 shutil.copy(os.path.join(my_dir, 'files', 'ssh_host_rsa_key'), self.workdir)
472 os.chmod(os.path.join(self.workdir, 'ssh_host_rsa_key'), 0o600)
473 shutil.copy(os.path.join(my_dir, 'files', 'ssh_host_rsa_key.pub'), self.workdir)
474 self.sshd_config = os.path.join(self.workdir, 'sshd_config')
475 with open(self.sshd_config, 'w') as f:
476 f.write('''Port 22222
477 HostKey %(workdir)s/ssh_host_rsa_key
478 UsePrivilegeSeparation no
479 AuthorizedKeysFile %(authorized_keys)s
480 UsePam no
481 PasswordAuthentication no
482 Subsystem sftp %(sftp_server)s
483 ''' % {'workdir': self.workdir, 'sftp_server': sftp_server, 'authorized_keys': self.authorized_keys})
484
485 self.sshd = subprocess.Popen([sshd_path, '-Dde', '-f', self.sshd_config],
486 universal_newlines=True,
487 stderr=subprocess.PIPE)
488
489 def tearDown(self):
490 os.unlink(self.authorized_keys)
491 if self.sshd.returncode is None:
492 self.sshd.terminate()
493 self.sshd.wait()
494 super().tearDown()
495
496 def run(self, result=None):
497 '''Show sshd log output on failed tests'''
498
499 if result:
500 orig_err_fail = len(result.errors) + len(result.failures)
501 super().run(result)
502 if result and len(result.errors) + len(result.failures) > orig_err_fail and hasattr(self, 'sshd'):
503 print('\n----- sshd log -----\n%s\n------\n' % self.sshd.stderr.read())
504
505 def test_rsa(self):
506 '''sftp://localhost with RSA authentication'''
507
508 # accept our key for localhost logins
509 shutil.copy(os.path.expanduser('~/.ssh/id_rsa.pub'), self.authorized_keys)
510
511 # mount it
512 uri = 'sftp://localhost:22222'
513 subprocess.check_call(['gio', 'mount', uri])
514
515 self.do_mount_check(uri)
516
517 # if we are in the testbed, then ssh defaults to
518 # "StrictHostKeyChecking ask", and a connection attempt should fail;
519 # otherwise this is client-configurable behaviour which cannot be
520 # temporarily overridden
521 @unittest.skipUnless(in_testbed, 'not running under gvfs-testbed')
522 @unittest.skipUnless(local_ip, 'not having any non-localhost IP')
523 def test_unknown_host(self):
524 '''sftp:// with RSA authentication for unknown host'''
525
526 # accept our key for localhost logins
527 shutil.copy(os.path.expanduser('~/.ssh/id_rsa.pub'), self.authorized_keys)
528
529 # try to mount it; should fail as it's an unknown host
530 uri = 'sftp://%s:22222' % local_ip
531 (code, out, err) = self.program_code_out_err(['gio', 'mount', uri])
532
533 self.assertNotEqual(code, 0)
534 # there is nothing in our testbed which would show or answer the
535 # dialog
536 if english_messages:
537 self.assertTrue('Login dialog cancelled' in err, err)
538
539 def do_mount_check(self, uri):
540 # appears in gio mount list
541 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
542 try:
543 self.assertRegex(out, 'Mount\(\d+\):.*localhost -> %s' % uri)
544
545 # check gio info
546 out = self.program_out_success(['gio', 'info', uri])
547 self.assertRegex(out, 'display name: / .* localhost')
548 self.assertTrue('type: directory' in out, out)
549 self.assertTrue('access::can-read: TRUE' in out, out)
550
551 # check gio list
552 out = self.program_out_success(['gio', 'list', uri + '/home'])
553 self.assertTrue('%s\n' % os.environ['USER'] in out, out)
554
555 # check gio cat
556 out = self.program_out_success(['gio', 'cat', uri + '/etc/passwd'])
557 self.assertTrue('root:' in out, out)
558 finally:
559 self.unmount(uri)
560
561
562 @unittest.skipUnless(twistd_path != None, 'Twisted twistd not installed')
563 class Ftp(GvfsTestCase):
564 def setUp(self):
565 '''Launch FTP server'''
566
567 super().setUp()
568 with open(os.path.join(self.workdir, 'myfile.txt'), 'w') as f:
569 f.write('hello world\n')
570 os.mkdir(os.path.join(self.workdir, 'mydir'))
571 secret_path = os.path.join(self.workdir, 'mydir', 'onlyme.txt')
572 with open(secret_path, 'w') as f:
573 f.write('secret\n')
574 os.chmod(secret_path, 0o600)
575
576 self.ftpd = subprocess.Popen([twistd_path, '-n', 'ftp', '-p', '2121',
577 '-r', self.workdir,
578 '--auth', 'memory:testuser:pwd1'],
579 stdout=subprocess.PIPE)
580 # wait until server is started up
581 s = socket.socket()
582 for timeout in range(50):
583 try:
584 s.connect(('127.0.0.1', 2121))
585 s.close()
586 break
587 except ConnectionRefusedError:
588 time.sleep(0.3)
589 pass
590 else:
591 self.fail('timed out waiting for test FTP server')
592
593 def tearDown(self):
594 '''Shut down FTP server'''
595
596 self.ftpd.terminate()
597 self.ftpd.wait()
598 super().tearDown()
599
600 def test_anonymous_cli_user(self):
601 '''ftp:// anonymous (CLI with user)'''
602
603 uri = 'ftp://anonymous@localhost:2121'
604 subprocess.check_call(['gio', 'mount', uri])
605
606 self.do_mount_check_cli(uri, True)
607
608 def test_anonymous_cli_option(self):
609 '''ftp:// anonymous (CLI with option)'''
610
611 uri = 'ftp://localhost:2121'
612 subprocess.check_call(['gio', 'mount', '-a', uri])
613
614 self.do_mount_check_cli(uri, True)
615
616 def test_authenticated_cli(self):
617 '''ftp:// authenticated (CLI)'''
618
619 uri = 'ftp://localhost:2121'
620 mount = subprocess.Popen(['gio', 'mount', uri],
621 stdin=subprocess.PIPE,
622 stdout=subprocess.PIPE,
623 stderr=subprocess.PIPE)
624
625 # wrong user name
626 self.wait_for_gvfs_mount_user_prompt(mount)
627 mount.stdin.write(b'eve\nh4ck\n')
628 mount.stdin.flush()
629
630 # wrong password name
631 self.wait_for_gvfs_mount_user_prompt(mount)
632 mount.stdin.write(b'testuser\nh4ck\n')
633 mount.stdin.flush()
634
635 # correct credentials
636 self.wait_for_gvfs_mount_user_prompt(mount)
637 (out, err) = mount.communicate(b'testuser\npwd1\n')
638 self.assertEqual(mount.returncode, 0)
639 self.assertEqual(err, b'')
640
641 # in test bed, there is nothing interesting in /home/testuser/, and
642 # without the test bed we do not know what's in the folder, so skip
643 # gio list check
644 self.do_mount_check_cli(uri, False)
645
646 def do_mount_check_cli(self, uri, check_contents):
647 # appears in gio mount list
648 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
649 try:
650 self.assertRegex(out, 'Mount\(\d+\):.* -> ftp://([a-z0-9]+@)?localhost:2121')
651
652 # check gio info
653 out = self.program_out_success(['gio', 'info', uri])
654 self.assertRegex(out, 'display name: / .* localhost', out)
655 self.assertTrue('type: directory' in out, out)
656
657 # check gio list
658 if check_contents:
659 out = self.program_out_success(['gio', 'list', uri])
660 self.assertEqual(set(out.split()), set(['myfile.txt', 'mydir']))
661 out = self.program_out_success(['gio', 'list', uri + '/mydir'])
662 self.assertEqual(out, 'onlyme.txt\n')
663
664 # check gio cat
665 out = self.program_out_success(['gio', 'cat', uri + '/myfile.txt'])
666 self.assertEqual(out, 'hello world\n')
667 finally:
668 self.unmount(uri)
669
670 def test_anonymous_api_user(self):
671 '''ftp:// anonymous (API with user)'''
672
673 uri = 'ftp://anonymous@localhost:2121'
674 gfile = Gio.File.new_for_uri(uri)
675 self.assertEqual(self.mount_api(gfile), True)
676 try:
677 self.do_mount_check_api(gfile, True)
678 finally:
679 self.unmount_api(gfile)
680
681 def test_anonymous_api_flag(self):
682 '''ftp:// anonymous (API with flag)'''
683
684 uri = 'ftp://localhost:2121'
685 gfile = Gio.File.new_for_uri(uri)
686 self.assertEqual(self.mount_api(gfile, self.make_mountop()), True)
687 try:
688 self.do_mount_check_api(gfile, True)
689 finally:
690 self.unmount_api(gfile)
691
692 def test_authenticated_api(self):
693 '''ftp:// authenticated (API)'''
694
695 uri = 'ftp://localhost:2121'
696 gfile = Gio.File.new_for_uri(uri)
697
698 # no password supplied
699 res = self.mount_api(gfile)
700 self.assertTrue(isinstance(res, GLib.GError), res)
701
702 # wrong username
703 res = self.mount_api(gfile, self.make_mountop('eve', 'h4ck'))
704 self.assertTrue(isinstance(res, GLib.GError))
705
706 # wrong password
707 res = self.mount_api(gfile, self.make_mountop('testuser', 'h4ck'))
708 self.assertTrue(isinstance(res, GLib.GError))
709
710 # correct credentials
711 res = self.mount_api(gfile, self.make_mountop('testuser', 'pwd1'))
712 self.assertEqual(res, True)
713 try:
714 self.do_mount_check_api(gfile, False)
715 finally:
716 self.unmount_api(gfile)
717
718 def do_mount_check_api(self, gfile, check_contents):
719 info = gfile.query_info('*', 0, None)
720 self.assertEqual(info.get_content_type(), 'inode/directory')
721 self.assertEqual(info.get_file_type(), Gio.FileType.DIRECTORY)
722 self.assertTrue('localhost' in info.get_display_name(),
723 info.get_display_name())
724 # FIXME: this is actually supposed to be true!
725 # self.assertEqual(info.get_attribute_boolean('access::can-read'), True)
726
727 if check_contents:
728 # check available files
729 enum = gfile.enumerate_children('*', Gio.FileQueryInfoFlags.NONE, None)
730 files = set()
731 while True:
732 info = enum.next_file(None)
733 if info is None:
734 break
735 files.add(info.get_name())
736 self.assertEqual(files, set(['myfile.txt', 'mydir']))
737
738 gfile_myfile = Gio.File.new_for_uri(gfile.get_uri() + '/myfile.txt')
739 (success, contents, etags) = gfile_myfile.load_contents(None)
740 self.assertTrue(success)
741 self.assertEqual(contents, b'hello world\n')
742
743
744 @unittest.skipUnless(smbd_path != None, 'Samba smbd not installed')
745 class Smb(GvfsTestCase):
746 def setUp(self):
747 '''start local smbd as user if we are not in test bed'''
748 super().setUp()
749
750 # create a few test files
751 if in_testbed:
752 pubdir = os.path.expanduser('~/public')
753 privdir = os.path.expanduser('~/private')
754 else:
755 pubdir = os.path.join(self.workdir, 'public')
756 privdir = os.path.join(self.workdir, 'private')
757 if not os.path.exists(pubdir):
758 # only run this once
759 os.mkdir(pubdir)
760 os.makedirs(os.path.join(privdir, 'mydir'))
761 with open(os.path.join(pubdir, 'myfile.txt'), 'w') as f:
762 f.write('hello world\n')
763 secret_path = os.path.join(privdir, 'mydir', 'onlyme.txt')
764 with open(secret_path, 'w') as f:
765 f.write('secret\n')
766 os.chmod(secret_path, 0o600)
767
768 if in_testbed:
769 return
770
771 # smbpasswd file with password "foo"
772 smbpasswd = os.path.join(self.workdir, 'smbpasswd')
773 with open(smbpasswd, 'w') as f:
774 f.write(os.environ['USER'])
775 f.write(':2:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:AC8E657F83DF82BEEA5D43BDAF7800CC:[U ]:LCT-507C14C7:\n')
776
777 # create local samba configuration
778 smbdir = os.path.join(self.workdir, 'samba')
779 os.mkdir(smbdir, 0o755)
780 smbconf = os.path.join(self.workdir, 'smb.conf')
781 with open(smbconf, 'w') as f:
782 f.write('''[global]
783 workgroup = TESTGROUP
784 interfaces = lo 127.0.0.0/8
785 smb ports = %(port)d
786 log level = 2
787 map to guest = Bad User
788 passdb backend = smbpasswd
789 smb passwd file = %(workdir)s/smbpasswd
790 lock directory = %(workdir)s/samba
791 state directory = %(workdir)s/samba
792 cache directory = %(workdir)s/samba
793 pid directory = %(workdir)s/samba
794 private dir = %(workdir)s/samba
795 ncalrpc dir = %(workdir)s/samba
796
797 [public]
798 path = %(workdir)s/public
799 guest ok = yes
800
801 [private]
802 path = %(workdir)s/private
803 read only = no
804 ''' % {'workdir': self.workdir,
805 'port': SMB_USER_PORT})
806
807 # start smbd
808 self.smbd = subprocess.Popen([smbd_path, '-FS', '-s', smbconf],
809 universal_newlines=True,
810 stdout=subprocess.PIPE)
811
812 timeout = 50
813 while timeout > 0:
814 (out, err) = self.program_out_err(['ss', '-ltn'])
815 if (':%d ' % SMB_USER_PORT) in out:
816 break
817 timeout -= 1
818 time.sleep(0.1)
819 else:
820 self.smbd.terminate()
821 self.smbd.wait()
822 self.fail('starting smbd failed')
823
824 def tearDown(self):
825 # stop smbd
826 if hasattr(self, 'smbd') and self.smbd.returncode is None:
827 self.smbd.terminate()
828 self.smbd.wait()
829 super().tearDown()
830
831 def run(self, result=None):
832 '''Show smbd log output on failed tests'''
833
834 if result:
835 orig_err_fail = len(result.errors) + len(result.failures)
836 super().run(result)
837 if hasattr(self, 'smbd'):
838 if result and len(result.errors) + len(result.failures) > orig_err_fail:
839 print('\n----- smbd log -----\n%s\n------\n' % self.smbd.stdout.read())
840
841 def test_anonymous(self):
842 '''smb:// anonymous'''
843
844 if in_testbed:
845 uri = 'smb://%s/public' % (os.uname()[1])
846 else:
847 uri = 'smb://%s:%d/public' % (os.uname()[1], SMB_USER_PORT)
848
849 # ensure that this does not ask for any credentials
850 mount = subprocess.Popen(['gio', 'mount', '-a', uri])
851 timeout = 50
852 while timeout > 0:
853 time.sleep(0.1)
854 timeout -= 1
855 if mount.poll() is not None:
856 self.assertEqual(mount.returncode, 0, 'gio mount -a %s failed' % uri)
857 break
858 else:
859 mount.terminate()
860 self.fail('timed out waiting for gio mount -a %s' % uri)
861 mount.wait()
862
863 self.do_mount_check(uri, False)
864
865 def test_authenticated(self):
866 '''smb:// authenticated'''
867
868 if in_testbed:
869 uri = 'smb://%s@%s/private' % (os.environ['USER'], os.uname()[1])
870 else:
871 uri = 'smb://%s@%s:%d/private' % (os.environ['USER'], os.uname()[1], SMB_USER_PORT)
872
873 mount = subprocess.Popen(['gio', 'mount', uri],
874 stdin=subprocess.PIPE,
875 stdout=subprocess.PIPE,
876 stderr=subprocess.PIPE)
877
878 # correct credentials
879 self.wait_for_gvfs_mount_user_prompt(mount)
880 # default domain, password
881 (out, err) = mount.communicate(b'\nfoo\n')
882 self.assertEqual(mount.returncode, 0, err)
883 # self.assertEqual(err, b'') # we get some warnings
884
885 self.do_mount_check(uri, True)
886
887 def do_mount_check(self, uri, writable):
888 sharename = uri.split('/')[-1]
889
890 # appears in gio mount list
891 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
892 try:
893 self.assertRegex(out, 'Mount\(0\): %s .* smb://.*/%s' % (sharename, sharename))
894
895 # check gio info
896 out = self.program_out_success(['gio', 'info', uri])
897 self.assertTrue('display name: ' + sharename in out, out)
898 self.assertTrue('type: directory' in out, out)
899
900 # check gio list and gio cat
901 out = self.program_out_success(['gio', 'list', uri])
902 if sharename == 'public':
903 self.assertEqual(out, 'myfile.txt\n')
904
905 out = self.program_out_success(['gio', 'cat', uri + '/myfile.txt'])
906 self.assertEqual(out, 'hello world\n')
907 else:
908 self.assertEqual(out, 'mydir\n')
909 self.assertEqual(self.program_out_success(['gio', 'list', uri + '/mydir']),
910 'onlyme.txt\n')
911
912 out = self.program_out_success(['gio', 'cat', uri + '/mydir/onlyme.txt'])
913 self.assertEqual(out, 'secret\n')
914
915 if writable:
916 # should be writable
917 self.program_out_success(['gio', 'copy', '/etc/passwd', uri + '/newfile.txt'])
918 out = self.program_out_success(['gio', 'cat', uri + '/newfile.txt'])
919 with open('/etc/passwd') as f:
920 self.assertEqual(out, f.read())
921 else:
922 # should not be writable
923 (code, out, err) = self.program_code_out_err(
924 ['gio', 'copy', '/etc/passwd', uri + '/newfile.txt'])
925 self.assertNotEqual(code, 0)
926 self.assertEqual(out, '')
927 self.assertNotEqual(err, '')
928 finally:
929 self.unmount(uri)
930
931
932 @unittest.skipUnless(in_testbed, 'not running under gvfs-testbed')
933 @unittest.skipIf(os.path.exists('/sys/module/scsi_debug'), 'scsi_debug is already loaded')
934 class Drive(GvfsTestCase):
935 @classmethod
936 def setUpClass(klass):
937 '''Load scsi_debug'''
938
939 klass.root_command_success('modprobe scsi_debug add_host=0 dev_size_mb=64')
940
941 @classmethod
942 def tearDownClass(klass):
943 # remove scsi_debug; might need a few tries while being busy
944 timeout = 10
945 while timeout > 0:
946 (code, out, err) = klass.root_command('rmmod -v scsi_debug')
947 if code == 0:
948 break
949 if 'in use' in err:
950 time.sleep(0.2)
951 else:
952 break
953 if code != 0:
954 raise SystemError('cannot rmmod scsi_debug: ' + err)
955
956 @classmethod
957 def get_devices(klass):
958 '''Return current set of device names from scsi_debug'''
959
960 devs = []
961 for dir in glob('/sys/bus/pseudo/drivers/scsi_debug/adapter*/host*/target*/*:*/block'):
962 try:
963 devs += os.listdir(dir)
964 except OSError:
965 # TOCTOU, might change underneath us
966 pass
967 return set(devs)
968
969 @classmethod
970 def create_host(klass, ptype):
971 '''Create a new SCSI host.
972
973 Return device name.
974 '''
975 orig_devs = klass.get_devices()
976 klass.root_command_success('echo %i > /sys/bus/pseudo/drivers/scsi_debug/ptype' % ptype)
977 klass.root_command_success('echo 1 > /sys/bus/pseudo/drivers/scsi_debug/add_host')
978
979 timeout = 1000
980 while timeout >= 0:
981 devs = klass.get_devices()
982 if devs - orig_devs:
983 break
984 time.sleep(0.2)
985 timeout -= 1
986 else:
987 raise SystemError('timed out waiting for new device')
988
989 new_devs = devs - orig_devs
990 assert len(new_devs) == 1
991 return new_devs.pop()
992
993 @classmethod
994 def remove_device(klass, device):
995 '''Remove given device name.'''
996
997 klass.root_command_success('echo 1 > /sys/block/%s/device/delete' % device)
998
999 def load_image(self, fname):
1000 '''Install a test image on the scsi_debug drive
1001
1002 This must be a bzip2'ed file in test/files/.
1003 '''
1004 # we cannot write to a scsi_debug CD drive, so write it into it in hard
1005 # disk mode
1006 dev = self.create_host(PTYPE_DISK)
1007 self.root_command('udevadm wait -t10 --settle /dev/%s' % dev)
1008
1009 # put test.iso onto disk
1010 img = os.path.join(my_dir, 'files', fname)
1011 self.root_command_success('bzip2 -cd %s > /dev/%s; sync' % (img, dev))
1012
1013 # leave the actual device creation to the individual tests; all devices
1014 # created henceforth will default to the image contents
1015 self.remove_device(dev)
1016
1017 while dev in self.get_devices():
1018 time.sleep(0.2)
1019
1020 # flush volume monitor output
1021 ctx = GLib.MainContext().default()
1022 while ctx.iteration(False):
1023 pass
1024
1025 # Let a few seconds the gio monitor settle and detect the removal.
1026 for _ in range(20):
1027 out = self.monitor.stdout.read()
1028 if out and b"Drive disconnected" in out:
1029 break
1030 time.sleep(0.2)
1031
1032 def setUp(self):
1033 super().setUp()
1034
1035 self.mock_polkit = None
1036
1037 # do not use the mocked /sys for these tests, but the real one
1038 # (GvfsTestCase.tearDown() puts it back via .clear())
1039 if umockdev_testbed:
1040 umockdev_testbed.disable()
1041
1042 self.monitor = subprocess.Popen(['gio', 'mount', '-oi'],
1043 stdout=subprocess.PIPE)
1044 # set monitor stdout to non-blocking
1045 fl = fcntl.fcntl(self.monitor.stdout, fcntl.F_GETFL)
1046 fcntl.fcntl(self.monitor.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)
1047
1048 # wait until monitor is ready
1049 while 'Monitoring events' not in self.get_monitor_output():
1050 time.sleep(0.1)
1051
1052 def tearDown(self):
1053 for dev in self.get_devices():
1054 self.remove_device(dev)
1055
1056 self.monitor.terminate()
1057 self.monitor.wait()
1058 self.stop_polkit()
1059
1060 super().tearDown()
1061
1062 def test_cdrom(self):
1063 '''drive mount: cdrom'''
1064
1065 self.load_image('bogus-cd.iso.bz2')
1066 dev = self.create_host(PTYPE_CDROM)
1067
1068 # check that gvfs monitor picks up the new drive
1069 out = self.get_monitor_output()
1070 self.assertRegex(out, 'Drive connected:')
1071 self.assertRegex(out, '\[drive-optical\]')
1072 self.assertRegex(out, '\[media-optical-cd\]')
1073 self.assertRegex(out, 'unix-device:.*/dev/%s' % dev)
1074 self.assertRegex(out, 'has_media=1')
1075
1076 self.assertRegex(out, 'Volume added:\s+.*bogus-cd')
1077 self.assertRegex(out, "label:\s+'bogus-cd")
1078 self.assertRegex(out, 'can_mount=1')
1079 self.assertRegex(out, 'should_automount=1')
1080 self.assertRegex(out, 'themed icons:.*media-optical')
1081
1082 # tell polkit to do allow removable (but not internal) storage
1083 self.start_polkit(['org.freedesktop.udisks2.filesystem-mount',
1084 'org.freedesktop.udisks2.filesystem-mount-other-seat'])
1085
1086 # now mounting should succeed
1087 (out, err) = self.program_out_err(['gio', 'mount', '-d', '/dev/' + dev])
1088
1089 # should appear as Mount
1090 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
1091 self.assertEqual(err.strip(), '')
1092 match = re.search('Mount\(\d+\): bogus-cd -> (file://.*/media/.*/bogus-cd)', out)
1093 self.assertTrue(match, 'no Mount found in gio mount -li output:\n' + out)
1094
1095 # unmount it again
1096 self.unmount(match.group(1))
1097
1098 def test_cdrom_api(self):
1099 '''drive mount: cdrom with Gio API'''
1100
1101 self.load_image('bogus-cd.iso.bz2')
1102
1103 self.start_polkit(['org.freedesktop.udisks2.filesystem-mount',
1104 'org.freedesktop.udisks2.filesystem-mount-other-seat'])
1105
1106 self.bogus_volume = None
1107
1108 # add CD and wait for it to appear in the monitor
1109 def volume_added(vm, v, main_loop):
1110 if v.get_name() == 'bogus-cd':
1111 self.bogus_volume = v
1112 main_loop.quit()
1113
1114 vm = Gio.VolumeMonitor.get()
1115 ml = GLib.MainLoop()
1116 vm.connect('volume-added', volume_added, ml)
1117
1118 dev = self.create_host(PTYPE_CDROM)
1119 timeout_id = GLib.timeout_add_seconds(5, lambda data: ml.quit(), None)
1120 ml.run()
1121 self.assertNotEqual(self.bogus_volume, None,
1122 'timed out waiting for bogus-cd volume')
1123 ml.get_context().find_source_by_id(timeout_id).destroy()
1124
1125 # check properties
1126 ids = self.bogus_volume.enumerate_identifiers()
1127 self.assertTrue('unix-device' in ids, ids)
1128 self.assertTrue('label' in ids, ids)
1129 self.assertEqual(self.bogus_volume.get_identifier('unix-device'), '/dev/' + dev)
1130 self.assertEqual(self.bogus_volume.get_identifier('label'), 'bogus-cd')
1131
1132 self.assertEqual(self.bogus_volume.get_mount(), None)
1133
1134 # mount it
1135 self.cb_result = None
1136
1137 def mount_done(obj, result, main_loop):
1138 main_loop.quit()
1139 try:
1140 success = obj.mount_finish(result)
1141 self.cb_result = (obj, success)
1142 except GLib.GError as e:
1143 self.cb_result = (obj, e)
1144 self.bogus_volume.mount(Gio.MountMountFlags.NONE, None, None, mount_done, ml)
1145
1146 timeout_id = GLib.timeout_add_seconds(5, lambda data: ml.quit(), None)
1147 ml.run()
1148 self.assertNotEqual(self.cb_result, None,
1149 'timed out waiting for bogus-cd mount')
1150 ml.get_context().find_source_by_id(timeout_id).destroy()
1151
1152 self.assertEqual(self.cb_result[1], True)
1153 self.assertEqual(self.cb_result[0], self.bogus_volume)
1154
1155 # get Mount object
1156 mount = self.bogus_volume.get_mount()
1157 self.assertNotEqual(mount, None)
1158 self.assertEqual(mount.get_name(), 'bogus-cd')
1159 p = mount.get_root().get_path()
1160 self.assertTrue(os.path.isdir(p), p)
1161 self.assertTrue(os.path.isfile(os.path.join(p, 'hello.txt')))
1162 self.assertTrue('/media/' in p, p)
1163 self.assertEqual(mount.get_volume(), self.bogus_volume)
1164
1165 # unmount
1166 self.cb_result = None
1167
1168 def unmount_done(obj, result, main_loop):
1169 main_loop.quit()
1170 try:
1171 success = obj.unmount_with_operation_finish(result)
1172 self.cb_result = (obj, success)
1173 except GLib.GError as e:
1174 self.cb_result = (obj, e)
1175
1176 mount.unmount_with_operation(Gio.MountUnmountFlags.NONE, None, None, unmount_done, ml)
1177 timeout_id = GLib.timeout_add_seconds(5, lambda data: ml.quit(), None)
1178 ml.run()
1179 self.assertEqual(self.cb_result[1], True)
1180 self.assertEqual(self.bogus_volume.get_mount(), None)
1181
1182 def test_system_partition(self):
1183 '''drive mount: system partition'''
1184
1185 self.load_image('vfat.img.bz2')
1186 dev = self.create_host(PTYPE_DISK)
1187
1188 # check that gvfs monitor picks up the new drive
1189 out = self.get_monitor_output()
1190 self.assertRegex(out, 'Drive connected:')
1191 self.assertRegex(out, '\[drive-harddisk\]')
1192 self.assertRegex(out, 'unix-device:.*/dev/%s' % dev)
1193 self.assertRegex(out, 'has_media=1')
1194
1195 self.assertRegex(out, 'Volume added:\s+.*testvfat')
1196 self.assertRegex(out, "label:\s+'testvfat")
1197 self.assertRegex(out, 'should_automount=0')
1198 self.assertRegex(out, 'themed icons:.*harddisk')
1199
1200 # should fail with only allowing the user to mount removable storage
1201 self.start_polkit(['org.freedesktop.udisks2.filesystem-mount'])
1202 (code, out, err) = self.program_code_out_err(['gio', 'mount', '-d', '/dev/' + dev])
1203 self.assertNotEqual(code, 0)
1204 self.assertRegex(err, 'Not authorized')
1205
1206 # should succeed with allowing the user to mount system storage
1207 self.start_polkit(['org.freedesktop.udisks2.filesystem-mount-system'])
1208 (out, err) = self.program_out_err(['gio', 'mount', '-d', '/dev/' + dev])
1209
1210 # should appear as Mount
1211 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
1212 self.assertEqual(err.strip(), '')
1213 match = re.search('Mount\(\d+\): testvfat -> (file://.*/media/.*/testvfat)', out)
1214 self.assertTrue(match, 'no Mount found in gio mount -li output:\n' + out)
1215
1216 # unmount it again
1217 self.unmount(match.group(1))
1218
1219 def test_system_partition_api(self):
1220 '''drive mount: system partition with Gio API'''
1221
1222 self.load_image('vfat.img.bz2')
1223
1224 self.start_polkit(['org.freedesktop.udisks2.filesystem-mount-system'])
1225
1226 self.volume = None
1227
1228 # add partition and wait for it to appear in the monitor
1229 def volume_added(vm, v, main_loop):
1230 if v.get_name() == 'testvfat':
1231 self.volume = v
1232 main_loop.quit()
1233
1234 vm = Gio.VolumeMonitor.get()
1235 ml = GLib.MainLoop()
1236 vm.connect('volume-added', volume_added, ml)
1237
1238 dev = self.create_host(PTYPE_DISK)
1239 timeout_id = GLib.timeout_add_seconds(5, lambda data: ml.quit(), None)
1240 ml.run()
1241 self.assertNotEqual(self.volume, None,
1242 'timed out waiting for volume')
1243 ml.get_context().find_source_by_id(timeout_id).destroy()
1244
1245 # check properties
1246 ids = self.volume.enumerate_identifiers()
1247 self.assertTrue('unix-device' in ids, ids)
1248 self.assertTrue('label' in ids, ids)
1249 self.assertTrue('uuid' in ids, ids)
1250 self.assertEqual(self.volume.get_identifier('unix-device'), '/dev/' + dev)
1251 self.assertEqual(self.volume.get_identifier('label'), 'testvfat')
1252 self.assertEqual(self.volume.get_identifier('uuid'), 'F3C1-6301')
1253
1254 def test_media_player(self):
1255 '''drive mount: media player'''
1256
1257 self.load_image('bogus-cd.iso.bz2')
1258
1259 def cleanup():
1260 rootsh = subprocess.Popen(['./rootsh', '-p'], stdin=subprocess.PIPE)
1261 rootsh.communicate(b'''rm /run/udev/rules.d/40-scsi_debug-fake-mediaplayer.rules
1262 pkill --signal HUP udevd || pkill --signal HUP systemd-udevd
1263 ''')
1264
1265 # create udev rule to turn it into a music player
1266 self.addCleanup(cleanup)
1267 rootsh = subprocess.Popen(['./rootsh', '-p'], stdin=subprocess.PIPE)
1268 rootsh.communicate(b'''export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
1269 mkdir -p /run/udev/rules.d
1270 echo 'SUBSYSTEM=="block", ATTRS{model}=="scsi_debug*", ENV{ID_MEDIA_PLAYER}="MockTune"' > /run/udev/rules.d/40-scsi_debug-fake-mediaplayer.rules
1271 sync
1272 pkill --signal HUP udevd || pkill --signal HUP systemd-udevd
1273 ''')
1274
1275 dev = self.create_host(PTYPE_DISK)
1276
1277 # check that gvfs monitor picks up the new volume
1278 out = self.get_monitor_output()
1279 self.assertRegex(out, 'Volume added:\s+.*bogus-cd')
1280 self.assertRegex(out, "label:\s+'bogus-cd")
1281 self.assertTrue('should_automount=0' in out, out)
1282 self.assertRegex(out, 'themed icons:.*harddisk')
1283
1284 # mount it
1285 self.start_polkit(['org.freedesktop.udisks2.filesystem-mount-system'])
1286 (out, err) = self.program_out_err(['gio', 'mount', '-d', '/dev/' + dev])
1287
1288 # should appear as Mount
1289 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
1290 self.assertEqual(err.strip(), '')
1291 match = re.search('Mount\(\d+\): bogus-cd -> (file://.*/media/.*/bogus-cd)', out)
1292 self.assertTrue(match, 'no Mount found in gio mount -li output:\n' + out)
1293
1294 # should have media player content
1295 self.assertRegex(out, 'x_content_types:.*x-content/audio-player')
1296
1297 # unmount it again
1298 self.unmount(match.group(1))
1299
1300 def get_monitor_output(self):
1301 '''Wait for gvfs monitor to output something, and return it'''
1302
1303 empty_timeout = 50
1304 while True:
1305 out = self.monitor.stdout.read()
1306 if out:
1307 break
1308 else:
1309 empty_timeout -= 1
1310 self.assertGreater(empty_timeout, 0,
1311 'timed out waiting for monitor output')
1312
1313 time.sleep(0.1)
1314
1315 # wait a bit more to see whether we catch some stragglers
1316 time.sleep(0.7)
1317 out2 = self.monitor.stdout.read()
1318 if out2:
1319 out += out2
1320
1321 return out.decode()
1322
1323 def start_polkit(self, actions):
1324 '''Start mock polkit with list of allowed actions.'''
1325
1326 self.stop_polkit()
1327 self.mock_polkit = subprocess.Popen(['./rootsh', '-p'],
1328 stdin=subprocess.PIPE)
1329 self.mock_polkit.stdin.write(('set -e\n/home/test_polkitd.py -r -a %s\n'
1330 % ','.join(actions)).encode('ASCII'))
1331 self.mock_polkit.stdin.flush()
1332
1333 # wait until it started up
1334 if actions:
1335 timeout = 50
1336 while timeout > 0:
1337 try:
1338 out = subprocess.check_output(['pkcheck', '--action-id', actions[0], '--process', '1'],
1339 stderr=subprocess.PIPE)
1340 if b'test=test' in out:
1341 break
1342 except subprocess.CalledProcessError:
1343 pass
1344
1345 time.sleep(0.1)
1346 timeout -= 1
1347 else:
1348 self.fail('timed out waiting for test_polkitd.py')
1349 else:
1350 # we can only cross fingers here, as we do not have an action to verify
1351 time.sleep(0.5)
1352
1353 self.assertEqual(self.mock_polkit.poll(), None,
1354 'mock polkitd unexpectedly terminated')
1355
1356 def stop_polkit(self):
1357 '''Stop mock polkit, if it is running.'''
1358
1359 if self.mock_polkit:
1360 # for some reason, terminating the shell doesn't terminate the
1361 # polkitd running in it, so kill that separately.
1362 # The apparently redundant [] is to stop pkill from
1363 # killing itself or its sudo parent.
1364 self.root_command('pkill -e -f "/home/test_polkitd[.]py"')
1365 self.mock_polkit.terminate()
1366 self.mock_polkit.wait()
1367 self.mock_polkit = None
1368
1369
1370 @unittest.skipUnless(have_httpd, 'Apache httpd not installed')
1371 @unittest.skipUnless(have_dav_backend, 'Dav backend not enabled')
1372 class Dav(GvfsTestCase):
1373 '''Test WebDAV backend'''
1374
1375 @classmethod
1376 def setUpClass(klass):
1377 '''Set up Apache httpd sandbox'''
1378
1379 klass.mod_dir = klass.get_httpd_module_dir()
1380 klass.httpd_sandbox = tempfile.mkdtemp()
1381
1382 klass.public_dir = os.path.join(klass.httpd_sandbox, 'public')
1383 os.mkdir(klass.public_dir)
1384 with open(os.path.join(klass.public_dir, 'hello.txt'), 'w') as f:
1385 f.write('hi\n')
1386
1387 klass.secret_dir = os.path.join(klass.httpd_sandbox, 'secret')
1388 os.mkdir(klass.secret_dir)
1389 with open(os.path.join(klass.secret_dir, 'restricted.txt'), 'w') as f:
1390 f.write('dont tell anyone\n')
1391
1392 # test:s3kr1t
1393 with open(os.path.join(klass.httpd_sandbox, 'htpasswd'), 'w') as f:
1394 f.write('test:$apr1$t0B4mfkT$Tr8ip333/ZR/7xrRBuxjI.\n')
1395
1396 # some distros have some extra modules which we need to load
1397 modules = ''
1398 for m in ['authn_core', 'authz_core', 'authz_user', 'auth_basic',
1399 'authn_file', 'mpm_prefork', 'unixd', 'dav', 'dav_fs', 'ssl']:
1400 if os.path.exists(os.path.join(klass.mod_dir, 'mod_%s.so' % m)):
1401 modules += 'LoadModule %s_module %s/mod_%s.so\n' % (m, klass.mod_dir, m)
1402
1403 with open(os.path.join(klass.httpd_sandbox, 'apache2.conf'), 'w') as f:
1404 f.write('''Listen localhost:8088
1405 Listen localhost:4443
1406 %(modules)s
1407
1408 DocumentRoot .
1409 ServerName localhost
1410 PidFile apache.pid
1411 LogLevel debug
1412 ErrorLog error_log
1413 DAVLockDB DAVLock
1414
1415 <VirtualHost localhost:4443>
1416 SSLEngine on
1417 SSLCertificateFile %(mydir)s/files/testcert.pem
1418 SSLCertificateKeyFile %(mydir)s/files/testcert.pem
1419 </VirtualHost>
1420
1421 <Directory %(root)s/public>
1422 Dav On
1423 </Directory>
1424
1425 <Directory %(root)s/secret>
1426 Dav On
1427 AuthType Basic
1428 AuthName DAV
1429 AuthUserFile htpasswd
1430 Require valid-user
1431 </Directory>
1432 ''' % {'mod_dir': klass.mod_dir, 'root': klass.httpd_sandbox, 'modules': modules, 'mydir': my_dir})
1433
1434 # start server
1435 try:
1436 subprocess.check_call([httpd_cmd, '-d', klass.httpd_sandbox, '-f', 'apache2.conf', '-k', 'start'])
1437 except subprocess.CalledProcessError:
1438 error_log = os.path.join(klass.httpd_sandbox, 'error_log')
1439 if os.path.exists(error_log):
1440 with open(error_log) as f:
1441 print('---- apache http error log ----\n%s\n---------\n' % f.read())
1442 raise
1443
1444 @classmethod
1445 def tearDownClass(klass):
1446 '''Stop httpd server and remove sandbox'''
1447
1448 subprocess.call([httpd_cmd, '-d', klass.httpd_sandbox, '-f', 'apache2.conf', '-k', 'stop'])
1449 shutil.rmtree(klass.httpd_sandbox)
1450
1451 @classmethod
1452 def get_httpd_module_dir(klass):
1453 '''Return module directory for Apache httpd.
1454
1455 Unfortunately this is highly distro/platform specific, so try to
1456 determine it from apxs2 or apachectl/apache2.
1457 '''
1458 # if we have apxs2 installed, use this
1459 try:
1460 apxs2 = subprocess.Popen(['apxs2', '-q', 'LIBEXECDIR'],
1461 stdout=subprocess.PIPE,
1462 stderr=subprocess.PIPE,
1463 universal_newlines=True)
1464 out = apxs2.communicate()[0].strip()
1465 assert apxs2.returncode == 0, 'apxs2 -V failed'
1466 return out
1467 except OSError:
1468 # Look for apxs instead
1469 try:
1470 apxs2 = subprocess.Popen(['apxs', '-q', 'LIBEXECDIR'],
1471 stdout=subprocess.PIPE,
1472 stderr=subprocess.PIPE,
1473 universal_newlines=True)
1474 out = apxs2.communicate()[0].strip()
1475 assert apxs2.returncode == 0, 'apxs2 -V failed'
1476 return out
1477 except OSError:
1478 print('[no apxs2, falling back]')
1479 pass
1480
1481 # fall back to looking for modules in HTTPD_ROOT/modules/
1482 ctl = subprocess.Popen([httpd_cmd, '-V'],
1483 stdout=subprocess.PIPE,
1484 universal_newlines=True)
1485 out = ctl.communicate()[0]
1486 assert ctl.returncode == 0, httpd_cmd + ' -V failed'
1487 m = re.search('\sHTTPD_ROOT="([^"]+)"\s', out)
1488 assert m, httpd_cmd + ' -V does not show HTTPD_ROOT'
1489 mod_dir = os.path.join(m.group(1), 'modules')
1490 assert os.path.isdir(mod_dir), \
1491 '%s does not exist, cannot determine httpd module path' % mod_dir
1492 return mod_dir
1493
1494 def test_http_noauth(self):
1495 '''dav://localhost without credentials'''
1496
1497 uri = 'dav://localhost:8088/public'
1498 subprocess.check_call(['gio', 'mount', uri])
1499 self.do_mount_check(uri, 'hello.txt', 'hi\n')
1500
1501 def test_https_noauth(self):
1502 '''davs://localhost without credentials'''
1503
1504 uri = 'davs://localhost:4443/public'
1505 mount = subprocess.Popen(['gio', 'mount', uri],
1506 stdin=subprocess.PIPE,
1507 stdout=subprocess.PIPE,
1508 stderr=subprocess.PIPE)
1509
1510 # confirm unknown certificate
1511 self.wait_for_question (mount);
1512 mount.stdin.write(b'1\n')
1513 mount.stdin.flush()
1514
1515 self.do_mount_check(uri, 'hello.txt', 'hi\n')
1516
1517 def test_http_auth(self):
1518 '''dav://localhost with credentials'''
1519
1520 uri = 'dav://localhost:8088/secret'
1521
1522 mount = subprocess.Popen(['gio', 'mount', uri],
1523 stdin=subprocess.PIPE,
1524 stdout=subprocess.PIPE,
1525 stderr=subprocess.PIPE)
1526
1527 # wrong password
1528 self.wait_for_gvfs_mount_user_prompt(mount)
1529 mount.stdin.write(b'test\nh4ck\n')
1530 mount.stdin.flush()
1531
1532 # correct password
1533 (out, err) = mount.communicate(b's3kr1t\n')
1534 self.assertEqual(mount.returncode, 0)
1535 self.assertEqual(err, b'')
1536
1537 self.do_mount_check(uri, 'restricted.txt', 'dont tell anyone\n')
1538
1539 def test_https_auth(self):
1540 '''davs://localhost with credentials'''
1541
1542 uri = 'davs://localhost:4443/secret'
1543
1544 mount = subprocess.Popen(['gio', 'mount', uri],
1545 stdin=subprocess.PIPE,
1546 stdout=subprocess.PIPE,
1547 stderr=subprocess.PIPE)
1548
1549 # confirm unknown certificate
1550 self.wait_for_question (mount);
1551 mount.stdin.write(b'1\n')
1552 mount.stdin.flush()
1553
1554 # wrong password
1555 self.wait_for_gvfs_mount_user_prompt(mount)
1556 mount.stdin.write(b'test\nh4ck\n')
1557 mount.stdin.flush()
1558
1559 # correct password
1560 (out, err) = mount.communicate(b's3kr1t\n')
1561 self.assertEqual(mount.returncode, 0)
1562 self.assertEqual(err, b'')
1563
1564 self.do_mount_check(uri, 'restricted.txt', 'dont tell anyone\n')
1565
1566 def do_mount_check(self, uri, testfile, content):
1567 # appears in gio mount list
1568 (out, err) = self.program_out_err(['gio', 'mount', '-li'])
1569 try:
1570 self.assertRegex(out, 'Mount\(\d+\):.* -> davs?://([a-z0-9]+@)?localhost')
1571
1572 # check gio info
1573 out = self.program_out_success(['gio', 'info', uri])
1574 self.assertRegex(out, 'id::filesystem: dav')
1575 self.assertTrue('type: directory' in out, out)
1576
1577 # check gio list
1578 out = self.program_out_success(['gio', 'list', uri])
1579 self.assertEqual(out.strip(), testfile)
1580
1581 # check gio cat
1582 out = self.program_out_success(['gio', 'cat', uri + '/' + testfile])
1583 self.assertEqual(out, content)
1584
1585 # create a new file
1586 self.program_out_success(['gio', 'copy', uri + '/' + testfile, uri + '/foo'])
1587 out = self.program_out_success(['gio', 'cat', uri + '/foo'])
1588 self.assertEqual(out, content)
1589
1590 # remove it again
1591 self.program_out_success(['gio', 'remove', uri + '/foo'])
1592 out = self.program_out_success(['gio', 'list', uri])
1593 self.assertFalse('foo' in out.split(), out)
1594 finally:
1595 self.unmount(uri)
1596
1597
1598 class Trash(GvfsTestCase):
1599 def setUp(self):
1600 super().setUp()
1601
1602 self.gfile_trash = Gio.File.new_for_uri('trash://')
1603
1604 # double-check that we are really running with a temporary
1605 # $XDG_DATA_HOME and that gvfs respects it, or under gvfs-testbed
1606 self.assertEqual(self.files_in_trash(), set())
1607
1608 self.my_file = None
1609
1610 def tearDown(self):
1611 if self.my_file:
1612 if os.path.exists(self.my_file):
1613 os.unlink(self.my_file)
1614
1615 # clean up the trash, for predictable test cases
1616 for f in self.files_in_trash():
1617 # print('cleaning up trash:///' + f)
1618 subprocess.call(['gio', 'remove', 'trash:///' + f])
1619
1620 super().tearDown()
1621
1622 def files_in_trash(self):
1623 files = set()
1624 time.sleep(0.3)
1625 enum = self.gfile_trash.enumerate_children('*', Gio.FileQueryInfoFlags.NONE, None)
1626 while True:
1627 info = enum.next_file(None)
1628 if info is None:
1629 break
1630 files.add(info.get_name())
1631 return files
1632
1633 def test_file_in_home_cli(self):
1634 '''trash:// deletion, attributes, restoring for a file in $HOME (CLI)'''
1635
1636 # create test file
1637 self.my_file = os.path.expanduser('~/hello_gvfs_tests.txt')
1638 with open(self.my_file, 'w') as f:
1639 f.write('hello world\n')
1640
1641 # trash it
1642 del_time = time.time()
1643 subprocess.check_call(['gio', 'trash', self.my_file])
1644 # should now be gone
1645 self.assertFalse(os.path.exists(self.my_file))
1646 # and be in the trash
1647 self.assertEqual(self.files_in_trash(), set(['hello_gvfs_tests.txt']))
1648
1649 out = self.program_out_success(['gio', 'info', 'trash:///hello_gvfs_tests.txt'])
1650
1651 # has proper original path
1652 self.assertTrue('trash::orig-path: ' + self.my_file in out, out)
1653
1654 # has proper deletion time
1655 m = re.search('trash::deletion-date: (.*)\n', out)
1656 self.assertNotEqual(m, None)
1657 recorded_time = time.mktime(time.strptime(m.group(1), '%Y-%m-%dT%H:%M:%S'))
1658 self.assertLess(abs(recorded_time - del_time), 2.0)
1659
1660 # is saved in home trash, not by-device trash
1661 data_home = os.environ.get('XDG_DATA_HOME', os.path.expanduser('~/.local/share'))
1662 self.assertTrue('standard::target-uri: file://' + data_home in out, out)
1663
1664 def test_file_in_home_api(self):
1665 '''trash:// deletion, attributes, restoring for a file in $HOME (API)'''
1666
1667 # create test file
1668 self.my_file = os.path.expanduser('~/hello_gvfs_tests.txt')
1669 with open(self.my_file, 'w') as f:
1670 f.write('hello world\n')
1671 gfile = Gio.File.new_for_path(self.my_file)
1672
1673 self.assertTrue(gfile.trash(None))
1674 # should now be gone
1675 self.assertFalse(os.path.exists(self.my_file))
1676 # and be in the trash
1677 self.assertEqual(self.files_in_trash(), set(['hello_gvfs_tests.txt']))
1678
1679 def test_deletion_with_same_path(self):
1680 '''trash:// deletion of two files with the same path'''
1681
1682 # create test file
1683 self.my_file = os.path.expanduser('~/hello_gvfs_tests.txt')
1684 with open(self.my_file, 'w') as f:
1685 f.write('hello world\n')
1686 gfile = Gio.File.new_for_path(self.my_file)
1687 self.assertTrue(gfile.trash(None))
1688 self.assertFalse(os.path.exists(self.my_file))
1689
1690 # and re-create/re-trash it again
1691 self.my_file = os.path.expanduser('~/hello_gvfs_tests.txt')
1692 with open(self.my_file, 'w') as f:
1693 f.write('bye bye\n')
1694 gfile = Gio.File.new_for_path(self.my_file)
1695 self.assertTrue(gfile.trash(None))
1696 self.assertFalse(os.path.exists(self.my_file))
1697
1698 # should have two trash entries now with tame original path
1699 enum = self.gfile_trash.enumerate_children('*', Gio.FileQueryInfoFlags.NONE, None)
1700 count = 0
1701 while True:
1702 info = enum.next_file(None)
1703 if info is None:
1704 break
1705 count += 1
1706 self.assertEqual(info.get_attribute_byte_string('trash::orig-path'), self.my_file)
1707 self.assertEqual(count, 2)
1708
1709 def test_file_in_system(self):
1710 '''trash:// deletion for system location
1711
1712 This either should work if /tmp/ is a partition on its own writable to
1713 the user (such as a tmpfs), or fail gracefully without deleting the
1714 file.
1715 '''
1716 # create test file
1717 self.my_file = os.path.join(self.workdir, 'hello_gvfs_tests.txt')
1718 with open(self.my_file, 'w') as f:
1719 f.write('hello world\n')
1720
1721 # try to trash it
1722 trash = subprocess.Popen(['gio', 'trash', self.my_file], stderr=subprocess.PIPE)
1723 trash.communicate()
1724
1725 if trash.returncode == 0:
1726 self.assertFalse(os.path.exists(self.my_file))
1727 if os.stat('/tmp').st_dev == os.stat(os.environ['XDG_DATA_HOME']).st_dev:
1728 self.assertTrue(os.path.exists(os.path.join(os.environ['XDG_DATA_HOME'],
1729 'Trash/files/hello_gvfs_tests.txt')))
1730 else:
1731 self.assertTrue(os.path.exists('/tmp/.Trash-%i/files/hello_gvfs_tests.txt'
1732 % os.getuid()))
1733 else:
1734 # file should still be there
1735 self.assertTrue(os.path.exists(self.my_file))
1736
1737
•1738 #@unittest.skipUnless(have_umockdev,
1739 # 'umockdev not installed; get it from https://launchpad.net/umockdev')
1740 @unittest.skip("umockdev/ioctl recording is currently known to have issue and not to be reworked")
1741 class GPhoto(GvfsTestCase):
1742 def test_mount_api(self):
1743 '''gphoto2:// mount with Gio API'''
1744
1745 self.add_powershot()
1746
1747 uri = 'gphoto2://[usb:001,015]'
1748 gfile_mount = Gio.File.new_for_uri(uri)
1749
1750 self.assertEqual(self.mount_api(gfile_mount), True)
1751 try:
1752 # check top-level directory
1753 info = gfile_mount.query_info('*', 0, None)
1754 self.assertEqual(info.get_content_type(), 'inode/directory')
1755 self.assertEqual(info.get_file_type(), Gio.FileType.DIRECTORY)
1756 self.assertIn('camera', info.get_display_name().lower())
1757 self.assertEqual(info.get_attribute_boolean('access::can-read'), True)
1758
1759 # check a photo
1760 gfile = Gio.File.new_for_uri(uri + '/DCIM/100CANON/IMG_0001.JPG')
1761 # FIXME: The first call always fails (only with umockdev)
1762 try:
1763 info = gfile.query_info('*', 0, None)
1764 except GLib.GError:
1765 info = gfile.query_info('*', 0, None)
1766
1767 self.assertEqual(info.get_content_type(), 'image/jpeg')
1768 self.assertEqual(info.get_file_type(), Gio.FileType.REGULAR)
1769 # we don't care about capitalization
1770 self.assertEqual(info.get_display_name().lower(), 'img_0001.jpg')
1771 self.assertEqual(info.get_attribute_boolean('access::can-read'), True)
1772 self.assertEqual(info.get_attribute_boolean('access::can-write'), True)
1773
1774 # open photo
1775 stream = gfile.read(None)
1776 block = stream.read_bytes(20, None)
1777 self.assertIn(b'JFIF\x00', block.get_data())
1778 stream.close(None)
1779
1780 # nonexisting file
1781 gfile = Gio.File.new_for_uri(uri + '/DCIM/100CANON/IMG_9999.JPG')
1782 self.assertRaises(GLib.GError, gfile.query_info, '*', 0, None)
1783 finally:
1784 self.unmount_api(gfile_mount)
1785
1786 def add_powershot(self):
1787 '''Add PowerShot device and ioctls to umockdev testbed'''
1788
1789 with open(os.path.join(my_dir, 'files', 'powershot.umockdev')) as f:
1790 umockdev_testbed.add_from_string(f.read())
1791 umockdev_testbed.load_ioctl('/dev/bus/usb/001/015',
1792 os.path.join(my_dir, 'files', 'powershot.ioctl'))
1793
1794 # signal our monitor about the addition
1795 # umockdev_testbed.uevent('/sys/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.5/1-1.5.2/1-1.5.2.3', 'add');
1796
1797
1798 def start_dbus():
1799 '''Run a local D-BUS daemon under temporary XDG directories
1800
1801 This also runs the D-BUS daemon under umockdev-wrapper (if available), so
1802 that it will see fake umockdev devices.
1803
1804 Return temporary XDG home directory.
1805 '''
1806 global dbus_daemon
1807
1808 # use temporary config/data/runtime directories; NB that these need to be
1809 # in g_get_home_dir(), otherwise you can't trash files as this doesn't work
1810 # across fs boundaries
1811 # if/once https://bugzilla.gnome.org/show_bug.cgi?id=142568 gets fixed, we
1812 # can put it into a proper temp dir again
1813 temp_home = tempfile.mkdtemp(prefix='gvfs_test', dir=GLib.get_home_dir())
1814 os.environ['XDG_CONFIG_HOME'] = os.path.join(temp_home, 'config')
1815 os.environ['XDG_DATA_HOME'] = os.path.join(temp_home, 'data')
1816
1817 if os.path.exists('session.conf'):
1818 dbus_conf = 'session.conf'
1819 else:
1820 # for out-of-tree builds
1821 dbus_conf = os.path.join(os.path.dirname(__file__), 'session.conf')
1822 env = os.environ.copy()
1823 env['G_MESSAGES_DEBUG'] = 'all'
1824 env['GVFS_DEBUG'] = 'all'
1825 env['GVFS_SMB_DEBUG'] = '10'
1826 env['GVFS_HTTP_DEBUG'] = 'all'
1827 if not in_testbed:
1828 env['LIBSMB_PROG'] = "nc localhost %d" % SMB_USER_PORT
1829 # run local D-BUS; if we run this in a built tree, use our config to pick
1830 # up the built services, otherwise the standard session one
1831 if os.path.exists(dbus_conf):
1832 # Prevent test failures caused by attempts to spawn monitors which are
1833 # not available in our custom servicedir.
1834 env['GVFS_MONITOR_DIR'] = os.path.dirname(dbus_conf)
1835
1836 argv = ['dbus-daemon', '--config-file', dbus_conf, '--print-address=1']
1837 else:
1838 argv = ['dbus-daemon', '--session', '--print-address=1']
1839 if umockdev_testbed:
1840 argv.insert(0, 'umockdev-wrapper')
1841 # Python doesn't catch the setenv() from UMockdev.Testbed.new()
1842 env['UMOCKDEV_DIR'] = umockdev_testbed.get_root_dir()
1843 dbus_daemon = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
1844 addr = dbus_daemon.stdout.readline().decode()
1845 os.environ['DBUS_SESSION_BUS_ADDRESS'] = addr
1846
1847 # set dbus output to nonblocking
1848 flags = fcntl.fcntl(dbus_daemon.stdout, fcntl.F_GETFL)
1849 fcntl.fcntl(dbus_daemon.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
1850 flags = fcntl.fcntl(dbus_daemon.stderr, fcntl.F_GETFL)
1851 fcntl.fcntl(dbus_daemon.stderr, fcntl.F_SETFL, flags | os.O_NONBLOCK)
1852
1853 # set maximal size for pipes to avoid hangs when too many debug info is printed
1854 F_SETPIPE_SZ = 1031
1855 pipe_max_size = int(open('/proc/sys/fs/pipe-max-size', 'r').read())
1856 fcntl.fcntl(dbus_daemon.stdout, F_SETPIPE_SZ, pipe_max_size)
1857 fcntl.fcntl(dbus_daemon.stderr, F_SETPIPE_SZ, pipe_max_size)
1858
1859 return temp_home
1860
1861
1862 if __name__ == '__main__':
1863 # do not break tests due to translations
1864 try:
1865 del os.environ['LANGUAGE']
1866 except KeyError:
1867 pass
1868 os.environ['LC_ALL'] = 'C'
1869
1870 # we need to create the umockdev testbed before launching D-BUS, so
1871 # that all spawned gvfs daemons see it
1872 if have_umockdev:
1873 umockdev_testbed = UMockdev.Testbed.new()
1874
1875 temp_home = start_dbus()
1876 try:
1877 unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
1878 finally:
1879 dbus_daemon.terminate()
1880 dbus_daemon.wait()
1881 # it might take a while until the child processes terminate and
1882 # release usage of the home dir, so try several times
1883 timeout = 20
1884 while timeout > 0:
1885 try:
1886 shutil.rmtree(temp_home)
1887 break
1888 except OSError as e:
1889 timeout -= 1
1890 time.sleep(0.1)
1891 if timeout <= 0:
1892 raise