def test_free_space(self): """Unit test for free_space()""" home = os.path.expanduser("~") result = free_space(home) self.assertNotEqual(result, None) self.assert_(result > -1) self.assert_(isinstance(result, (int, long))) # compare to WMIC if 'nt' != os.name: return args = ['wmic', 'LogicalDisk', 'get', 'DeviceID,', 'FreeSpace'] from bleachbit.General import run_external (rc, stdout, stderr) = run_external(args) if rc: print 'error calling WMIC\nargs=%s\nstderr=%s' % (args, stderr) return import re for line in stdout.split('\n'): line = line.strip() if not re.match('([A-Z]):\s+(\d+)', line): continue drive, bytes_free = re.split('\s+', line) bytes_free = int(bytes_free) self.assertEqual(bytes_free, free_space(drive))
def test_free_space(self): """Unit test for free_space()""" home = expanduser('~') result = free_space(home) self.assertNotEqual(result, None) self.assertGreater(result, -1) self.assertIsInteger(result) # compare to WMIC if 'nt' != os.name: return args = ['wmic', 'LogicalDisk', 'get', 'DeviceID,', 'FreeSpace'] from bleachbit.General import run_external (rc, stdout, stderr) = run_external(args) if rc: print('error calling WMIC\nargs=%s\nstderr=%s' % (args, stderr)) return import re for line in stdout.split('\n'): line = line.strip() if not re.match('([A-Z]):\s+(\d+)', line): continue drive, bytes_free = re.split('\s+', line) print('Checking free space for %s' % drive) bytes_free = int(bytes_free) free = free_space(unicode(drive)) self.assertEqual(bytes_free, free)
def mount_filesystem(filename, mountpoint): args = ['mount', '-o', 'loop', filename, mountpoint] (rc, stdout, stderr) = run_external(args) if stderr: print(stderr) assert (rc == 0) print('mounted %s at %s', filename, mountpoint)
def mount_filesystem(filename, mountpoint): args = ['mount', '-o', 'loop', filename, mountpoint] (rc, stdout, stderr) = run_external(args) if stderr: print stderr assert(rc == 0) print 'mounted %s at %s' % (filename, mountpoint)
def test_link(self): """Unit test for links with is_link() and get_recycle_bin()""" if not common.destructive_tests('windows link'): return # make a normal directory with a file in it real_dir = os.path.join(self.tempdir, 'real_dir') os.mkdir(real_dir) self.assertExists(real_dir) self.assertEqual(False, is_link(real_dir)) canary_fn = os.path.join(real_dir, 'do_not_delete') common.touch_file(canary_fn) self.assertExists(canary_fn) self.assertEqual(False, is_link(canary_fn)) # link to the normal directory link_dir = os.path.join(self.tempdir, 'link_dir') args = ('cmd', '/c', 'mklink', '/d', link_dir, real_dir) from bleachbit.General import run_external (rc, stdout, stderr) = run_external(args) self.assertEqual(rc, 0, stderr) self.assertExists(link_dir) self.assertEqual(True, is_link(link_dir)) # put the link in the recycle bin move_to_recycle_bin(link_dir) # clear the recycle bin for f in get_recycle_bin(): FileUtilities.delete(f, shred=False) # verify the canary is still there self.assertExists(canary_fn)
def test_invalid_locale(self): """Unit test for invalid locales""" os.environ['LANG'] = 'blahfoo' # tests are run from the parent directory path = os.path.join('bleachbit', 'CLI.py') args = [sys.executable, path, '--version'] output = run_external(args) self.assertNotEqual(output[1].find('Copyright'), -1, str(output))
def test_invalid_locale(self): """Unit test for invalid locales""" old_lang = common.get_env('LANG') common.put_env('LANG', 'blahfoo') # tests are run from the parent directory args = [sys.executable, '-m', 'bleachbit.CLI', '--version'] output = run_external(args) self.assertNotEqual(output[1].find('Copyright'), -1, str(output)) common.put_env('LANG', old_lang)
def _test_link_helper(self, mklink_option, clear_recycle_bin): """Helper function for testing for links with is_link() and get_recycle_bin() It gets called four times for the combinations of the two parameters. It's called by four unit tests four accounting purposes. In other words, we don't want to count a test as skipped if part of it succeeded. mklink /j = directory junction directory junction does not require administrator privileges mklink /d=directory symbolic link requires administrator privileges """ if mklink_option == '/d': self.skipUnlessAdmin() # make a normal directory with a file in it real_dir = os.path.join(self.tempdir, 'real_dir') os.mkdir(real_dir) self.assertExists(real_dir) self.assertEqual(False, is_link(real_dir)) canary_fn = os.path.join(real_dir, 'do_not_delete') common.touch_file(canary_fn) self.assertExists(canary_fn) self.assertEqual(False, is_link(canary_fn)) # link to the normal directory link_dir = os.path.join(self.tempdir, 'link_dir') args = ('cmd', '/c', 'mklink', mklink_option, link_dir, real_dir) from bleachbit.General import run_external (rc, stdout, stderr) = run_external(args) self.assertEqual(rc, 0, stderr) self.assertExists(link_dir) self.assertEqual(True, is_link(link_dir)) if not clear_recycle_bin: os.rmdir(link_dir) self.assertNotExists(link_dir) shutil.rmtree(real_dir, True) if not common.destructive_tests('windows link'): self.skipTest('destructive tests are disabled') return # put the link in the recycle bin move_to_recycle_bin(link_dir) # clear the recycle bin for f in get_recycle_bin(): FileUtilities.delete(f, shred=False) # verify the canary is still there self.assertExists(canary_fn) # clean up shutil.rmtree(real_dir, True)
def format_filesystem(filename, mkfs_cmd): args = [] for arg in mkfs_cmd: if arg == 'filename': args.append(filename) else: args.append(arg) (rc, stdout, stderr) = run_external(args) assert (rc == 0)
def test_invalid_locale(self): """Unit test for invalid locales""" lang = os.environ['LANG'] os.environ['LANG'] = 'blahfoo' # tests are run from the parent directory args = [sys.executable, '-m', 'bleachbit.CLI', '--version'] output = run_external(args) self.assertNotEqual(output[1].find('Copyright'), -1, str(output)) os.environ['LANG'] = lang
def format_filesystem(filename, mkfs_cmd): args = [] for arg in mkfs_cmd: if arg == 'filename': args.append(filename) else: args.append(arg) (rc, stdout, stderr) = run_external(args) assert(rc == 0)
def test_delete_mount_point(self): """Unit test for deleting a mount point in use""" if not common.have_root(): self.skipTest('not enough privileges') from_dir = os.path.join(self.tempdir, 'mount_from') to_dir = os.path.join(self.tempdir, 'mount_to') os.mkdir(from_dir) os.mkdir(to_dir) args = ['mount', '--bind', from_dir, to_dir] (rc, stdout, stderr) = run_external(args) msg = 'error calling mount\nargs=%s\nstderr=%s' % (args, stderr) self.assertEqual(rc, 0, msg) delete(to_dir) args = ['umount', to_dir] (rc, stdout, stderr) = run_external(args) msg = 'error calling umount\nargs=%s\nstderr=%s' % (args, stderr) self.assertEqual(rc, 0, msg)
def test_gui_exit(self): """Unit test for --gui --exit, only for Windows""" args = [sys.executable, '-m', 'bleachbit.CLI', '--gui --exit'] output = run_external(args) opened_windows_titles = common.get_opened_windows_titles() self.assertFalse( any([ 'BleachBit' == window_title for window_title in opened_windows_titles ]))
def verify_cleanliness(filename): """Return True if the file is clean""" strings_ret = run_external(['strings', filename]) secret_count = strings_ret[1].count('secret') # filename sssshhhh_count = strings_ret[1].count('sssshhhh') # contents logger.debug('found %d sssshhhhh in image (contents) and %d secret (filename)', sssshhhh_count, secret_count) clean = ((secret_count > 0) * 1) + ((sssshhhh_count > 0) * 10) print('%s is clean: %s', filename, clean) return clean
def verify_cleanliness(filename): """Return True if the file is clean""" strings_ret = run_external(['strings', filename]) secret_count = strings_ret[1].count('secret') # filename sssshhhh_count = strings_ret[1].count('sssshhhh') # contents print 'debug: found %d sssshhhhh in image (contents) and %d secret (filename)' \ % (sssshhhh_count, secret_count) clean = ((secret_count > 0) * 1) + ((sssshhhh_count > 0) * 10) print '%s is clean: %s' % (filename, clean) return clean
def unmount_filesystem(mountpoint): time.sleep(0.5) # avoid "in use" error args = ['umount', mountpoint] attempts = 0 while True: (rc, stdout, stderr) = run_external(args) if stderr: print(stderr) if 0 == rc: break attempts += 1 time.sleep(attempts * 2) if attempts > 5: raise RuntimeError('cannot umount')
def unmount_filesystem(mountpoint): time.sleep(0.5) # avoid "in use" error args = ['umount', mountpoint] attempts = 0 while True: (rc, stdout, stderr) = run_external(args) if stderr: print stderr if 0 == rc: break attempts += 1 time.sleep(attempts * 2) if attempts > 5: raise RuntimeError('cannot umount')
def test_shred(self): """Unit test for --shred""" suffixes = ['', '.', '.txt'] dirs = ['.', None] for dir_ in dirs: for suffix in suffixes: (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-cli-shred', suffix=suffix, dir=dir_) os.close(fd) if '.' == dir_: filename = os.path.basename(filename) # not assertExists because something strange happens on Windows self.assertTrue(os.path.exists(filename)) args = [sys.executable, '-m', 'bleachbit.CLI', '--shred', filename] output = run_external(args) self.assertNotExists(filename)
def test_shred(self): """Unit test for --shred""" suffixes = ['', '.', '.txt'] dirs = ['.', None] for dir_ in dirs: for suffix in suffixes: (fd, filename) = tempfile.mkstemp( prefix='bleachbit-test-cli-shred', suffix=suffix, dir=dir_) os.close(fd) if '.' == dir_: filename = os.path.basename(filename) self.assert_(os.path.exists(filename)) path = os.path.join('bleachbit', 'CLI.py') args = [sys.executable, path, '--shred', filename] output = run_external(args, stdout=open(os.devnull, 'w')) self.assert_(not os.path.exists(filename))
def _test_preview(self, args, redirect_stdout=True, env=None): """Helper to test preview""" # Use devnull because in some cases the buffer will be too large, # and the other alternative, the screen, is not desirable. with open(os.devnull, 'w') as stdout: if not redirect_stdout: stdout = None output = run_external(args, stdout=stdout, env=env) self.assertEqual( output[0], 0, "Return code = %d, stderr='%s'" % (output[0], output[2])) pos = output[2].find('Traceback (most recent call last)') if pos > -1: print("Saw the following error when using args '%s':\n %s" % (args, output[2])) self.assertEqual(pos, -1)
def _test_preview(self, args, stdout=None, env=None): """Helper to test preview""" # Use devnull because in some cases the buffer will be too large, # and the other alternative, the screen, is not desirable. if stdout: stdout_ = None else: stdout_ = open(os.devnull, 'w') output = run_external(args, stdout=stdout_, env=env) if not stdout: stdout_.close() self.assertEqual(output[0], 0, "Return code = %d, stderr='%s'" % (output[0], output[2])) pos = output[2].find('Traceback (most recent call last)') if pos > -1: print("Saw the following error when using args '%s':\n %s" % (args, output[2])) self.assertEqual(pos, -1)
def test_wipe_sub(n_bytes, mkfs_cmd): """Test FileUtilities.wipe_path""" filename = create_disk_image(n_bytes) print('created disk image %s' % filename) # format filesystem format_filesystem(filename, mkfs_cmd) # mount mountpoint = tempfile.mkdtemp(prefix='bleachbit-wipe-mountpoint') mount_filesystem(filename, mountpoint) # baseline free disk space print('df for clean filesystem') print(run_external(['df', mountpoint])[1]) # make dirty make_dirty(mountpoint) # verify dirtiness unmount_filesystem(mountpoint) assert (verify_cleanliness(filename) == 11) mount_filesystem(filename, mountpoint) # standard delete logger.info('standard delete') delete_counter = 0 for secretfile in listdir(mountpoint): if 'secret' not in secretfile: # skip lost+found continue delete(secretfile, shred=False) delete_counter += 1 logger.debug('deleted %d files', delete_counter) # check print('df for empty, dirty filesystem') print(run_external(['df', mountpoint])[1]) # verify dirtiness unmount_filesystem(mountpoint) assert (verify_cleanliness(filename) == 11) mount_filesystem(filename, mountpoint) expected_free_space = free_space(mountpoint) # measure effectiveness of multiple wipes for i in range(1, 10): print('*' * 30) print('* pass %d *' % i) print('*' * 30) # remount if i > 1: mount_filesystem(filename, mountpoint)\ # really wipe print('wiping %s' % mountpoint) for w in wipe_path(mountpoint): pass # verify cleaning process freed all space it allocated actual_free_space = free_space(mountpoint) if not expected_free_space == actual_free_space: print('expecting %d free space but got %d' % (expected_free_space, actual_free_space)) import pdb pdb.set_trace() # unmount unmount_filesystem(mountpoint) # verify cleanliness cleanliness = verify_cleanliness(filename) assert (cleanliness < 2) # remove temporary delete(filename) delete(mountpoint)
def _test_link_helper(self, mklink_option, clear_recycle_bin): """Helper function for testing for links with is_junction() and get_recycle_bin() It gets called four times for the combinations of the two parameters. It's called by four unit tests for accounting purposes. In other words, we don't want to count a test as skipped if part of it succeeded. mklink /j = directory junction directory junction does not require administrator privileges mklink /d=directory symbolic link requires administrator privileges """ if mklink_option == '/d': self.skipUnlessAdmin() # make a normal directory with a file in it target_dir = os.path.join(self.tempdir, 'target_dir') os.mkdir(target_dir) self.assertExists(target_dir) self.assertFalse(is_junction(target_dir)) from random import randint canary_fn = os.path.join(target_dir, 'do_not_delete%d' % randint(1000, 9999)) common.touch_file(canary_fn) self.assertExists(canary_fn) self.assertFalse(is_junction(canary_fn)) # make a normal directory to hold a link container_dir = os.path.join(self.tempdir, 'container_dir') os.mkdir(container_dir) self.assertExists(container_dir) self.assertFalse(is_junction(container_dir)) # create the link link_pathname = os.path.join(container_dir, 'link') args = ('cmd', '/c', 'mklink', mklink_option, link_pathname, target_dir) from bleachbit.General import run_external (rc, stdout, stderr) = run_external(args) self.assertEqual(rc, 0, stderr) self.assertExists(link_pathname) self.assertTrue(is_junction(link_pathname)) # put the link in the recycle bin move_to_recycle_bin(container_dir) def cleanup_dirs(): shutil.rmtree(container_dir, True) self.assertNotExists(container_dir) shutil.rmtree(target_dir, True) if not clear_recycle_bin: cleanup_dirs() return # clear the recycle bin for f in get_recycle_bin(): FileUtilities.delete(f, shred=False) # verify the canary is still there self.assertExists(canary_fn) # clean up cleanup_dirs()
def test_wipe_sub(n_bytes, mkfs_cmd): """Test FileUtilities.wipe_path""" if 'nt' == os.name: print 'WARNING: test_wipe() not supported on Windows' return filename = create_disk_image(n_bytes) print 'created disk image %s' % filename # format filesystem format_filesystem(filename, mkfs_cmd) # mount mountpoint = tempfile.mkdtemp('bleachbit-wipe-mountpoint') mount_filesystem(filename, mountpoint) # baseline free disk space print 'df for clean filesystem' print run_external(['df', mountpoint])[1] # make dirty make_dirty(mountpoint) # verify dirtiness unmount_filesystem(mountpoint) assert (verify_cleanliness(filename) == 11) mount_filesystem(filename, mountpoint) # standard delete print 'info: standard delete' delete_counter = 0 for secretfile in listdir(mountpoint): if not 'secret' in secretfile: # skip lost+found continue delete(secretfile, shred=False) delete_counter += 1 print 'debug: deleted %d files' % delete_counter # check print 'df for empty, dirty filesystem' print run_external(['df', mountpoint])[1] # verify dirtiness unmount_filesystem(mountpoint) assert (verify_cleanliness(filename) == 11) mount_filesystem(filename, mountpoint) expected_free_space = free_space(mountpoint) # measure effectiveness of multiple wipes for i in range(1, 10): print '*' * 30 print '* pass %d *' % i print '*' * 30 # remount if i > 1: mount_filesystem(filename, mountpoint)\ # really wipe print 'wiping %s' % mountpoint for w in wipe_path(mountpoint): pass # verify cleaning process freed all space it allocated actual_free_space = free_space(mountpoint) if not expected_free_space == actual_free_space: print 'expecting %d free space but got %d' % \ (expected_free_space, actual_free_space) import pdb pdb.set_trace() # unmount unmount_filesystem(mountpoint) # verify cleanliness cleanliness = verify_cleanliness(filename) assert (cleanliness < 2) # remove temporary delete(filename) delete(mountpoint)
def test_wipe_sub(n_bytes, mkfs_cmd): """Test FileUtilities.wipe_path""" if 'nt' == os.name: print 'WARNING: test_wipe() not supported on Windows' return filename = create_disk_image(n_bytes) print 'created disk image %s' % filename # format filesystem format_filesystem(filename, mkfs_cmd) # mount mountpoint = tempfile.mkdtemp(prefix='bleachbit-wipe-mountpoint') mount_filesystem(filename, mountpoint) # baseline free disk space print 'df for clean filesystem' print run_external(['df', mountpoint])[1] # make dirty make_dirty(mountpoint) # verify dirtiness unmount_filesystem(mountpoint) assert(verify_cleanliness(filename) == 11) mount_filesystem(filename, mountpoint) # standard delete print 'info: standard delete' delete_counter = 0 for secretfile in listdir(mountpoint): if not 'secret' in secretfile: # skip lost+found continue delete(secretfile, shred=False) delete_counter += 1 print 'debug: deleted %d files' % delete_counter # check print 'df for empty, dirty filesystem' print run_external(['df', mountpoint])[1] # verify dirtiness unmount_filesystem(mountpoint) assert(verify_cleanliness(filename) == 11) mount_filesystem(filename, mountpoint) expected_free_space = free_space(mountpoint) # measure effectiveness of multiple wipes for i in range(1, 10): print '*' * 30 print '* pass %d *' % i print '*' * 30 # remount if i > 1: mount_filesystem(filename, mountpoint)\ # really wipe print 'wiping %s' % mountpoint for w in wipe_path(mountpoint): pass # verify cleaning process freed all space it allocated actual_free_space = free_space(mountpoint) if not expected_free_space == actual_free_space: print 'expecting %d free space but got %d' % \ (expected_free_space, actual_free_space) import pdb pdb.set_trace() # unmount unmount_filesystem(mountpoint) # verify cleanliness cleanliness = verify_cleanliness(filename) assert(cleanliness < 2) # remove temporary delete(filename) delete(mountpoint)