From ebefcbbc66d5579bdd3d0980690f26bb5330b79f Mon Sep 17 00:00:00 2001 From: Tristan Stenner Date: Sun, 5 Feb 2017 14:54:02 +0100 Subject: [PATCH 1/4] Use custom TestCase-class --- tests/TestAction.py | 2 +- tests/TestCLI.py | 11 +--- tests/TestCleaner.py | 9 +--- tests/TestCleanerML.py | 10 +--- tests/TestCommand.py | 11 +--- tests/TestCommon.py | 11 +--- tests/TestDeepScan.py | 11 +--- tests/TestDiagnostic.py | 14 +---- tests/TestFileUtilities.py | 19 ++----- tests/TestGeneral.py | 10 +--- tests/TestMemory.py | 11 +--- tests/TestOptions.py | 12 +---- tests/TestRecognizeCleanerML.py | 12 +---- tests/TestSpecial.py | 11 +--- tests/TestUnix.py | 10 +--- tests/TestUpdate.py | 11 +--- tests/TestWinapp.py | 10 +--- tests/TestWindows.py | 13 +---- tests/TestWorker.py | 10 +--- tests/common.py | 95 +++++++++++++++++++++++---------- 20 files changed, 91 insertions(+), 212 deletions(-) diff --git a/tests/TestAction.py b/tests/TestAction.py index dc6b2fac4..d982dec02 100644 --- a/tests/TestAction.py +++ b/tests/TestAction.py @@ -90,7 +90,7 @@ def dir_is_empty(dirname): return not os.listdir(dirname) -class ActionTestCase(unittest.TestCase, common.AssertFile): +class ActionTestCase(common.BleachbitTestCase): """Test cases for Action""" diff --git a/tests/TestCLI.py b/tests/TestCLI.py index 4955cf68e..9ff23e709 100644 --- a/tests/TestCLI.py +++ b/tests/TestCLI.py @@ -37,8 +37,7 @@ import unittest - -class CLITestCase(unittest.TestCase): +class CLITestCase(common.BleachbitTestCase): """Test case for module CLI""" @@ -170,11 +169,3 @@ def test_shred(self): args = [sys.executable, '-m', 'bleachbit.CLI', '--shred', filename] output = run_external(args, stdout=open(os.devnull, 'w')) self.assert_(not os.path.exists(filename)) - - -def suite(): - return unittest.makeSuite(CLITestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestCleaner.py b/tests/TestCleaner.py index 41d93be6c..aca4191d2 100644 --- a/tests/TestCleaner.py +++ b/tests/TestCleaner.py @@ -63,7 +63,7 @@ def actions_to_cleaner(action_strs): return cleaner -class CleanerTestCase(unittest.TestCase, common.AssertFile): +class CleanerTestCase(common.BleachbitTestCase): def test_add_action(self): """Unit test for Cleaner.add_action()""" @@ -234,10 +234,3 @@ def test_whitelist(self): for test in tests: self.assertEqual( backends['system'].whitelisted(test[0]), test[1], test[0]) - - -def suite(): - return unittest.makeSuite(CleanerTestCase) - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestCleanerML.py b/tests/TestCleanerML.py index da881e408..106e93a90 100644 --- a/tests/TestCleanerML.py +++ b/tests/TestCleanerML.py @@ -31,7 +31,7 @@ import unittest -class CleanerMLTestCase(unittest.TestCase, common.AssertFile): +class CleanerMLTestCase(common.BleachbitTestCase): """Test cases for CleanerML""" @@ -98,11 +98,3 @@ def test_load_cleaners(self): def test_pot_fragment(self): """Unit test for pot_fragment()""" self.assert_(isinstance(pot_fragment("Foo", 'bar.xml'), str)) - - -def suite(): - return unittest.makeSuite(CleanerMLTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestCommand.py b/tests/TestCommand.py index 823330e45..262ee83ee 100644 --- a/tests/TestCommand.py +++ b/tests/TestCommand.py @@ -29,10 +29,9 @@ from bleachbit.Command import * import tempfile -import unittest -class CommandTestCase(unittest.TestCase): +class CommandTestCase(common.BleachbitTestCase): """Test case for Command""" @@ -80,11 +79,3 @@ def test_Function(self): def test_Shred(self): """Unit test for Shred""" self.test_Delete(Shred) - - -def suite(): - return unittest.makeSuite(CommandTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestCommon.py b/tests/TestCommon.py index 6e950a9d3..f1c548564 100644 --- a/tests/TestCommon.py +++ b/tests/TestCommon.py @@ -28,11 +28,9 @@ import bleachbit import os -import tempfile -import unittest -class CommonTestCase(unittest.TestCase, common.AssertFile): +class CommonTestCase(common.BleachbitTestCase): """Test case for Common.""" @@ -78,10 +76,3 @@ def test_expanduser(self): # A relative path (without a reference to the home directory) # should not be expanded. self.assertEqual(bleachbit.expanduser('common'), 'common') - -def suite(): - return unittest.makeSuite(CommonTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestDeepScan.py b/tests/TestDeepScan.py index 9a1e9b1a4..bd7347cb8 100644 --- a/tests/TestDeepScan.py +++ b/tests/TestDeepScan.py @@ -32,10 +32,9 @@ import os import shutil import tempfile -import unittest -class DeepScanTestCase(unittest.TestCase): +class DeepScanTestCase(common.BleachbitTestCase): """Test Case for module DeepScan""" @@ -153,11 +152,3 @@ def test_normalized_walk_darwin(self): ] mock_walk.return_value = expected self.assertEqual(list(normalized_walk('.')), expected) - - -def suite(): - return unittest.makeSuite(DeepScanTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestDiagnostic.py b/tests/TestDiagnostic.py index 9cdc51df1..c029f8127 100644 --- a/tests/TestDiagnostic.py +++ b/tests/TestDiagnostic.py @@ -29,22 +29,12 @@ from tests import common from bleachbit.Diagnostic import diagnostic_info -import unittest - -class DiagnosticTestCase(unittest.TestCase): +class DiagnosticTestCase(common.BleachbitTestCase): """Test Case for module Diagnostic""" def test_diagnostic_info(self): """Test diagnostic_info""" # at least it does not crash ret = diagnostic_info() - self.assert_(isinstance(ret, (str, unicode))) - - -def suite(): - return unittest.makeSuite(DiagnosticTestCase) - - -if __name__ == '__main__': - unittest.main() + self.assertIsString(ret, (str, unicode)) diff --git a/tests/TestFileUtilities.py b/tests/TestFileUtilities.py index 34e55fb02..88ed1434c 100644 --- a/tests/TestFileUtilities.py +++ b/tests/TestFileUtilities.py @@ -36,9 +36,6 @@ import unittest - - - def test_ini_helper(self, execute): """Used to test .ini cleaning in TestAction and in TestFileUtilities""" @@ -116,8 +113,7 @@ def load_js(js_fn): self.assert_(not os.path.exists(filename)) -class FileUtilitiesTestCase(unittest.TestCase, common.AssertFile): - +class FileUtilitiesTestCase(common.BleachbitTestCase): """Test case for module FileUtilities""" def test_bytes_to_human(self): @@ -521,11 +517,10 @@ def test_free_space(self): def test_getsize(self): """Unit test for method getsize()""" - dirname = tempfile.mkdtemp(prefix='bleachbit-test-getsize') + dirname = tempfile.mkdtemp(prefix='bleachbit-test-getsize', dir=self.tempdir) def test_getsize_helper(fname): - filename = os.path.join(dirname, fname) - common.write_file(filename, "abcdefghij" * 12345) + filename = self.write_file(os.path.join(dirname, fname), "abcdefghij" * 12345) if 'nt' == os.name: self.assertEqual(getsize(filename), 10 * 12345) @@ -938,11 +933,3 @@ def test_open_files_lsof(self): self.assertEqual(list(open_files_lsof(lambda: 'n/bar/foo\nn/foo/bar\nnoise' )), ['/bar/foo', '/foo/bar']) - - -def suite(): - return unittest.makeSuite(FileUtilitiesTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestGeneral.py b/tests/TestGeneral.py index 0ec912aaa..fbd7fbb59 100644 --- a/tests/TestGeneral.py +++ b/tests/TestGeneral.py @@ -32,7 +32,7 @@ import unittest -class GeneralTestCase(unittest.TestCase): +class GeneralTestCase(common.BleachbitTestCase): """Test case for module General""" @@ -168,11 +168,3 @@ def test_run_external_clean_env(self): def test_sudo_mode(self): """Unit test for sudo_mode""" self.assert_(isinstance(sudo_mode(), bool)) - - -def suite(): - return unittest.makeSuite(GeneralTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestMemory.py b/tests/TestMemory.py index 2da6325e7..22cca029e 100644 --- a/tests/TestMemory.py +++ b/tests/TestMemory.py @@ -27,14 +27,13 @@ from tests import common from bleachbit.Memory import * - import unittest import sys running_linux = sys.platform.startswith('linux') -class MemoryTestCase(unittest.TestCase): +class MemoryTestCase(common.BleachbitTestCase): """Test case for module Memory""" @unittest.skipUnless(running_linux, 'not running linux') @@ -143,11 +142,3 @@ def test_swap_off_swap_on(self): self.skipTest('not enough privileges') devices = disable_swap_linux() enable_swap_linux() - - -def suite(): - return unittest.makeSuite(MemoryTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestOptions.py b/tests/TestOptions.py index 19668fd8a..e3a11dec9 100644 --- a/tests/TestOptions.py +++ b/tests/TestOptions.py @@ -24,14 +24,14 @@ from __future__ import absolute_import, print_function +from tests import common import bleachbit.Options from bleachbit import NoOptionError import os -import unittest -class OptionsTestCase(unittest.TestCase): +class OptionsTestCase(common.BleachbitTestCase): """Test case for class Options""" @@ -160,11 +160,3 @@ def test_abbreviations(self): # clean up del o - - -def suite(): - return unittest.makeSuite(OptionsTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestRecognizeCleanerML.py b/tests/TestRecognizeCleanerML.py index 7fad4b765..927ec1643 100644 --- a/tests/TestRecognizeCleanerML.py +++ b/tests/TestRecognizeCleanerML.py @@ -24,12 +24,11 @@ from __future__ import absolute_import, print_function +from tests import common from bleachbit.RecognizeCleanerML import hashdigest -import unittest - -class RecognizeCleanerMLTestCase(unittest.TestCase): +class RecognizeCleanerMLTestCase(common.BleachbitTestCase): """Test case for RecognizeCleanerML""" @@ -39,10 +38,3 @@ def test_hash(self): self.assertEqual(len(digest), 128) self.assertEqual(digest[1:10], '6382c203e') - -def suite(): - return unittest.makeSuite(RecognizeCleanerMLTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestSpecial.py b/tests/TestSpecial.py index 0fc06e6f7..4ca1ffaeb 100644 --- a/tests/TestSpecial.py +++ b/tests/TestSpecial.py @@ -34,7 +34,6 @@ import shutil import sqlite3 import tempfile -import unittest chrome_bookmarks = """ @@ -187,7 +186,7 @@ def assertTableIsEmpty(self, path, table): raise AssertionError('Table is not empty: %s ' % table) -class SpecialTestCase(unittest.TestCase, SpecialAssertions): +class SpecialTestCase(common.BleachbitTestCase, SpecialAssertions): """Test case for module Special""" @@ -383,11 +382,3 @@ def test_get_sqlite_int(self): ver = Special.get_sqlite_int( filename, 'select value from meta where key="version"') self.assertEqual(ver, [20]) - - -def suite(): - return unittest.makeSuite(SpecialTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestUnix.py b/tests/TestUnix.py index f5f2a61fc..704d24963 100644 --- a/tests/TestUnix.py +++ b/tests/TestUnix.py @@ -35,7 +35,7 @@ @unittest.skipIf('win32' == sys.platform, 'skipping unix tests on windows') -class UnixTestCase(unittest.TestCase): +class UnixTestCase(common.BleachbitTestCase): """Test case for module Unix""" @@ -243,11 +243,3 @@ def test_yum_clean(self): bytes_freed = yum_clean() self.assert_(isinstance(bytes_freed, (int, long))) bleachbit.logger.debug('yum bytes cleaned %d', bytes_freed) - - -def suite(): - return unittest.makeSuite(UnixTestCase) - - -if __name__ == '__main__' and 'posix' == os.name: - unittest.main() diff --git a/tests/TestUpdate.py b/tests/TestUpdate.py index dc80a8da5..ac2ea53aa 100644 --- a/tests/TestUpdate.py +++ b/tests/TestUpdate.py @@ -33,10 +33,9 @@ import os import os.path -import unittest -class UpdateTestCase(unittest.TestCase): +class UpdateTestCase(common.BleachbitTestCase): """Test case for module Update""" @@ -157,11 +156,3 @@ def test_environment(self): import socket self.assertTrue(hasattr(socket, 'ssl')) import _ssl - - -def suite(): - return unittest.makeSuite(UpdateTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestWinapp.py b/tests/TestWinapp.py index 7819f4dc3..f02884fd2 100644 --- a/tests/TestWinapp.py +++ b/tests/TestWinapp.py @@ -69,7 +69,7 @@ def get_winapp2(): @unittest.skipUnless('win32' == sys.platform, 'not running on windows') -class WinappTestCase(unittest.TestCase, common.AssertFile): +class WinappTestCase(common.BleachbitTestCase): """Test cases for Winapp""" @@ -404,11 +404,3 @@ def test_section2option(self): ('A - B (C)', 'a_b_c')) for test in tests: self.assertEqual(section2option(test[0]), test[1]) - - -def suite(): - return unittest.makeSuite(WinappTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/TestWindows.py b/tests/TestWindows.py index 18706eabf..20593d3ce 100644 --- a/tests/TestWindows.py +++ b/tests/TestWindows.py @@ -59,7 +59,7 @@ def put_files_into_recycle_bin(): @unittest.skipUnless('win32' == sys.platform, 'not running on windows') -class WindowsTestCase(unittest.TestCase, common.AssertFile): +class WindowsTestCase(common.BleachbitTestCase): """Test case for module Windows""" @@ -254,8 +254,7 @@ def test_file_wipe(self): logger.debug('file_wipe(%s)', longname) def _write_file(longname, contents): - common.write_file(longname, contents) - self.assertExists(longname) + self.write_file(longname, contents) return longname import win32api shortname = extended_path_undo( @@ -365,11 +364,3 @@ def test_shell_change_notify(self): """Unit test for shell_change_notify""" ret = shell_change_notify() self.assertEqual(ret, 0) - - -def suite(): - return unittest.makeSuite(WindowsTestCase) - - -if __name__ == '__main__' and sys.platform == 'win32': - unittest.main() diff --git a/tests/TestWorker.py b/tests/TestWorker.py index b03a398c3..364cda6ce 100644 --- a/tests/TestWorker.py +++ b/tests/TestWorker.py @@ -194,7 +194,7 @@ def get_commands(self): yield Command.Delete(self.pathname) -class WorkerTestCase(unittest.TestCase): +class WorkerTestCase(common.BleachbitTestCase): """Test case for module Worker""" @@ -337,11 +337,3 @@ def test_multiple_options(self): self.assertEqual(worker.total_special, 0) self.assertEqual(worker.total_errors, 0) self.assertEqual(worker.total_deleted, 2) - - -def suite(): - return unittest.makeSuite(WorkerTestCase) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/common.py b/tests/common.py index 1c71f603c..fdcc1ecbe 100644 --- a/tests/common.py +++ b/tests/common.py @@ -26,24 +26,48 @@ from bleachbit.FileUtilities import extended_path +import unittest +import shutil import tempfile import os +import os.path -class AssertFile: +class BleachbitTestCase(unittest.TestCase): + """TestCase class with several convenience methods and asserts""" - def getTestPath(self, path): - if 'nt' == os.name: - return extended_path(os.path.normpath(path)) - return path + @classmethod + def setUpClass(cls): + """Create a temporary directory for the testcase""" + cls.tempdir = tempfile.mkdtemp(prefix=cls.__name__) + print(cls.tempdir) + @classmethod + def tearDownClass(cls): + """remove the temporary directory""" + shutil.rmtree(cls.tempdir) + + # + # type asserts + # + def assertIsInteger(self, obj, msg=''): + self.assertIsInstance(obj, (int, long), msg) + + def assertIsString(self, obj, msg=''): + self.assertIsInstance(obj, (unicode, str), msg) + + def assertIsBytes(self, obj, msg=''): + self.assertIsInstance(obj, bytes, msg) + + # + # file asserts + # def assertExists(self, path, msg='', func=os.path.exists): """File, directory, or any path exists""" from bleachbit import expandvars path = expandvars(path) - if not func(self.getTestPath(path)): - raise AssertionError( - 'The file %s should exist, but it does not. %s' % (path, msg)) + if not func(getTestPath(path)): + raise AssertionError('The file %s should exist, but it does not. %s' % (path, msg)) def assertLExists(self, path, msg=''): self.assertExists(path, msg, os.path.lexists) @@ -52,9 +76,8 @@ def assertNotLExists(self, path, msg=''): self.assertNotExists(path, msg, os.path.lexists) def assertNotExists(self, path, msg='', func=os.path.exists): - if func(self.getTestPath(path)): - raise AssertionError( - 'The file %s should not exist, but it does. %s' % (path, msg)) + if func(getTestPath(path)): + raise AssertionError('The file %s should not exist, but it does. %s' % (path, msg)) def assertCondExists(self, cond, path, msg=''): if cond: @@ -62,6 +85,25 @@ def assertCondExists(self, cond, path, msg=''): else: self.assertNotExists(path, msg) + # + # file creation functions + # + def write_file(self, filename, contents=''): + """Create a temporary file, optionally writing contents to it""" + if not os.path.isabs(filename): + filename = os.path.join(self.tempdir, filename) + filename = extended_path(filename) + with open(filename, 'w') as f: + f.write(contents) + assert (os.path.exists(filename)) + return filename + + +def getTestPath(path): + if 'nt' == os.name: + return extended_path(os.path.normpath(path)) + return path + def destructive_tests(title): """Return true if allowed to run destructive tests. If false print notice.""" @@ -73,42 +115,37 @@ def destructive_tests(title): def touch_file(filename): """Create an empty file""" - write_file(filename, '') + with open(filename, "w") as f: + pass + import os.path + assert(os.path.exists(filename)) def validate_result(self, result, really_delete=False): """Validate the command returned valid results""" - self.assert_(isinstance(result, dict), "result is a %s" % type(result)) + self.assertIsInstance(result, dict, "result is a %s" % type(result)) # label - self.assert_(isinstance(result['label'], (str, unicode))) - self.assert_(len(result['label'].strip()) > 0) + self.assertIsString(result['label']) + self.assertGreater(len(result['label'].strip()), 0) # n_* - self.assert_(isinstance(result['n_deleted'], (int, long))) - self.assert_(result['n_deleted'] >= 0) - self.assert_(result['n_deleted'] <= 1) + self.assertIsInteger(result['n_deleted']) + self.assertGreaterEqual(result['n_deleted'], 0) + self.assertLessEqual(result['n_deleted'], 1) self.assertEqual(result['n_special'] + result['n_deleted'], 1) # size - self.assert_(isinstance(result['size'], (int, long, type(None))), - "size is %s" % str(result['size'])) + self.assertIsInstance(result['size'], (int, long, type(None),), "size is %s" % str(result['size'])) # path filename = result['path'] if not filename: # the process action, for example, does not have a filename return from bleachbit import encoding - self.assert_(isinstance(filename, (str, unicode, type(None))), + self.assertIsInstance(filename, (str, unicode, type(None)), "Filename is invalid: '%s' (type %s)" % (filename, type(filename))) - if isinstance(filename, (str, unicode)) and \ - not filename[0:2] == 'HK': + if isinstance(filename, (str, unicode)) and not filename[0:2] == 'HK': if really_delete: self.assertNotLExists(filename) else: self.assertLExists(filename) -def write_file(filename, contents): - """Write contents to file""" - with open(extended_path(filename), 'w') as f: - f.write(contents) - import os.path - assert(os.path.exists(extended_path(filename))) From 77726c3963c664637e527b1cddc176321f22f7ae Mon Sep 17 00:00:00 2001 From: Tristan Stenner Date: Sun, 5 Feb 2017 16:08:02 +0100 Subject: [PATCH 2/4] Convert `assert_`s --- tests/TestAction.py | 43 ++++++------- tests/TestCLI.py | 32 +++++----- tests/TestCleaner.py | 40 ++++++------ tests/TestCleanerML.py | 6 +- tests/TestCommand.py | 22 +++---- tests/TestCommon.py | 8 +-- tests/TestDeepScan.py | 25 +++----- tests/TestDiagnostic.py | 3 +- tests/TestFileUtilities.py | 123 +++++++++++++++++++------------------ tests/TestGeneral.py | 20 +++--- tests/TestMemory.py | 31 +++++----- tests/TestOptions.py | 11 ++-- tests/TestSpecial.py | 22 +++---- tests/TestUnix.py | 25 ++++---- tests/TestUpdate.py | 8 +-- tests/TestWorker.py | 15 ++--- tests/common.py | 3 + 17 files changed, 208 insertions(+), 229 deletions(-) diff --git a/tests/TestAction.py b/tests/TestAction.py index d982dec02..b7cb8dbba 100644 --- a/tests/TestAction.py +++ b/tests/TestAction.py @@ -107,8 +107,7 @@ def _test_action_str(self, action_str): provider = actionplugin(action_node) self.assertNotEqual(provider, None) for cmd in provider.get_commands(): - self.assert_( - isinstance(cmd, (Command.Delete, Command.Ini, Command.Json, Command.Function))) + self.assertIsInstance(cmd, (Command.Delete, Command.Ini, Command.Json, Command.Function)) if 'process' != command: # process does not have a filename self.assertLExists(filename) @@ -131,8 +130,7 @@ def _test_action_str(self, action_str): else: raise RuntimeError("Unknown command '%s'" % command) if 'walk.all' == search: - self.assert_(dir_is_empty(filename), - 'directory not empty after walk.all: %s' % filename) + self.assertTrue(dir_is_empty(filename), 'directory not empty after walk.all: %s' % filename) def test_delete(self): """Unit test for class Delete""" @@ -233,49 +231,48 @@ def test_regex(self): # should match three files using no regexes action_str = u'' results = _action_str_to_results(action_str) - self.assert_(3 == len(results)) + self.assertEqual(len(results), 3) # should match second file using positive regex action_str = u'' results = _action_str_to_results(action_str) - self.assert_(1 == len(results)) + self.assertEqual(len(results), 1) self.assertEqual(results[0]['path'], '/tmp/foo2') # On Windows should be case insensitive action_str = u'' results = _action_str_to_results(action_str) if 'nt' == os.name: - self.assert_(1 == len(results)) + self.assertEqual(len(results), 1) self.assertEqual(results[0]['path'], '/tmp/foo2') else: - self.assert_(0 == len(results)) + self.assertEqual(len(results), 0) # should match second file using negative regex action_str = u'' results = _action_str_to_results(action_str) - self.assert_(1 == len(results)) + self.assertEqual(len(results), 1) self.assertEqual(results[0]['path'], '/tmp/foo2') # should match second file using both regexes action_str = u'' results = _action_str_to_results(action_str) - self.assert_(1 == len(results)) + self.assertEqual(len(results), 1) self.assertEqual(results[0]['path'], '/tmp/foo2') # should match nothing using positive regex action_str = u'' results = _action_str_to_results(action_str) - self.assert_(0 == len(results)) + self.assertEqual(len(results), 0) # should match nothing using negative regex action_str = u'' results = _action_str_to_results(action_str) - self.assert_(0 == len(results)) + self.assertEqual(len(results), 0) # should give an error action_str = u'' - self.assertRaises( - RuntimeError, lambda: _action_str_to_results(action_str)) + self.assertRaises(RuntimeError, lambda: _action_str_to_results(action_str)) # clean up glob.iglob = _iglob @@ -291,18 +288,18 @@ def test_wholeregex(self): # should match three files using no regexes action_str = u'' results = _action_str_to_results(action_str) - self.assert_(3 == len(results)) + self.assertEqual(len(results), 3) # should match two files using wholeregex action_str = u'' results = _action_str_to_results(action_str) - self.assert_(2 == len(results)) + self.assertEqual(len(results), 2) self.assertEqual(results[0]['path'], '/tmp/foo1') # should match third file using nwholeregex action_str = u'' results = _action_str_to_results(action_str) - self.assert_(1 == len(results)) + self.assertEqual(len(results), 1) self.assertEqual(results[0]['path'], '/tmp/bar1') # clean up @@ -362,19 +359,17 @@ def test_walk_all(self): def test_walk_files(self): """Unit test for walk.files""" - if 'posix' == os.name: - path = '/var' - elif 'nt' == os.name: - path = '$WINDIR\\system32' - action_str = u'' % path + paths = {'posix': '/var', 'nt': '$WINDIR\\system32'} + + action_str = u'' % paths[os.name] results = 0 for cmd in _action_str_to_commands(action_str): result = cmd.execute(False).next() common.validate_result(self, result) path = result['path'] - self.assert_(not os.path.isdir(path), "%s is a directory" % path) + self.assertFalse(os.path.isdir(path), "%s is a directory" % path) results += 1 - self.assert_(results > 0) + self.assertGreater(results, 0) def suite(): diff --git a/tests/TestCLI.py b/tests/TestCLI.py index 9ff23e709..40eed39a3 100644 --- a/tests/TestCLI.py +++ b/tests/TestCLI.py @@ -76,12 +76,7 @@ def test_args_to_operations(self): def test_cleaners_list(self): """Unit test for cleaners_list()""" for cleaner in cleaners_list(): - self.assert_( - isinstance( - cleaner, - str) or isinstance( - cleaner, - unicode)) + self.assertIsString(cleaner) @unittest.skipUnless('posix' == os.name, 'skipping on non-Unix') def test_encoding(self): @@ -90,7 +85,8 @@ def test_encoding(self): (fd, filename) = tempfile.mkstemp( prefix='bleachbit-test-cli-encoding-\xe4\xf6\xfc~', dir='/tmp') os.close(fd) - self.assert_(os.path.exists(filename)) + # not assertExists because it doesn't cope with invalid encodings + self.assertTrue(os.path.exists(filename)) env = copy.deepcopy(os.environ) env['LANG'] = 'en_US' # not UTF-8 @@ -101,7 +97,7 @@ def test_encoding(self): self._test_preview(args, stdout=True, env=env) os.remove(filename) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) def test_invalid_locale(self): """Unit test for invalid locales""" @@ -141,18 +137,17 @@ def test_delete(self): deleted_paths = [] def dummy_delete(path, shred=False): - self.assert_(os.path.exists(path)) + self.assertExists(path) deleted_paths.append(os.path.normcase(path)) FileUtilities.delete = dummy_delete FileUtilities.delete(filename) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) operations = args_to_operations(['system.tmp'], False) preview_or_clean(operations, True) FileUtilities.delete = save_delete - self.assert_(filename in deleted_paths, - "%s not found deleted" % filename) + self.assertIn(filename, deleted_paths, "%s not found deleted" % filename) os.remove(filename) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) def test_shred(self): """Unit test for --shred""" @@ -160,12 +155,13 @@ def test_shred(self): dirs = ['.', None] for dir_ in dirs: for suffix in suffixes: - (fd, filename) = tempfile.mkstemp( - prefix='bleachbit-test-cli-shred', suffix=suffix, dir=dir_) + (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)) + # 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, stdout=open(os.devnull, 'w')) - self.assert_(not os.path.exists(filename)) + output = run_external(args) + self.assertNotExists(filename) + diff --git a/tests/TestCleaner.py b/tests/TestCleaner.py index aca4191d2..0172acef6 100644 --- a/tests/TestCleaner.py +++ b/tests/TestCleaner.py @@ -88,7 +88,7 @@ def test_add_action(self): self.actions.append( '') - self.assert_(len(self.actions) > 0) + self.assertGreater(len(self.actions), 0) for action_str in self.actions: cleaner = action_to_cleaner(action_str) @@ -97,22 +97,21 @@ def test_add_action(self): for result in cmd.execute(False): self.assertEqual(result['n_deleted'], 1) pathname = result['path'] - self.assert_(os.path.lexists(pathname), - "Does not exist: '%s'" % pathname) + self.assertLExists(pathname, "Does not exist: '%s'" % pathname) count += 1 common.validate_result(self, result) - self.assert_(count > 0, "No files found for %s" % action_str) + self.assertGreater(count, 0, "No files found for %s" % action_str) # should yield nothing cleaner.add_option('option2', 'name2', 'description2') for cmd in cleaner.get_commands('option2'): print(cmd) - self.assert_(False, 'option2 should yield nothing') + raise AssertionError('option2 should yield nothing') # should fail self.assertRaises(RuntimeError, cleaner.get_commands('option3').next) def test_auto_hide(self): for key in sorted(backends): - self.assert_(isinstance(backends[key].auto_hide(), bool)) + self.assertIsInstance(backends[key].auto_hide(), bool) def test_create_simple_cleaner(self): """Unit test for method create_simple_cleaner""" @@ -123,8 +122,8 @@ def test_create_simple_cleaner(self): # test Cyrillic for https://bugs.launchpad.net/bleachbit/+bug/1541808 filename2 = os.path.join(dirname, u'чистый') common.touch_file(filename2) - self.assert_(os.path.exists(filename1)) - self.assert_(os.path.exists(filename2)) + self.assertExists(filename1) + self.assertExists(filename2) cleaner = create_simple_cleaner([filename1, filename2, dirname]) for cmd in cleaner.get_commands('files'): # preview @@ -134,28 +133,27 @@ def test_create_simple_cleaner(self): for result in cmd.execute(True): pass - self.assert_(not os.path.exists(filename1)) - self.assert_(not os.path.exists(filename2)) - self.assert_(not os.path.exists(dirname)) + self.assertNotExists(filename1) + self.assertNotExists(filename2) + self.assertNotExists(dirname) def test_get_name(self): for key in sorted(backends): - self.assert_(isinstance(backends[key].get_name(), (str, unicode))) + self.assertIsString(backends[key].get_name()) def test_get_description(self): for key in sorted(backends): - self.assert_(isinstance(key, (str, unicode))) - self.assert_(isinstance(backends[key], Cleaner)) + self.assertIsString(key) + self.assertIsInstance(backends[key], Cleaner) desc = backends[key].get_description() - self.assert_(isinstance(desc, (str, unicode, type(None))), - "description for '%s' is '%s'" % (key, desc)) + if desc is not None: + self.assertIsString(desc, "description for '%s' is '%s'" % (key, desc)) def test_get_options(self): for key in sorted(backends): for (test_id, name) in backends[key].get_options(): - self.assert_(isinstance(test_id, (str, unicode)), - '%s.%s is not a string' % (key, test_id)) - self.assert_(isinstance(name, (str, unicode))) + self.assertIsString(test_id, '%s.%s is not a string' % (key, test_id)) + self.assertIsString(name) def test_get_commands(self): for key in sorted(backends): @@ -180,7 +178,7 @@ def get_files(option_id): trash_paths = get_files('trash') tmp_paths = get_files('tmp') for tmp_path in tmp_paths: - self.assert_(tmp_path not in trash_paths) + self.assertNotIn(tmp_path, trash_paths) def test_no_files_exist(self): """Verify only existing files are returned""" @@ -200,7 +198,7 @@ def test_no_files_exist(self): break msg = "Expected no files to be deleted but got '%s'" % str( result) - self.assert_(not isinstance(cmd, Command.Delete), msg) + self.assertNotIsInstance(cmd, Command.Delete, msg) common.validate_result(self, result) glob.iglob = _iglob os.path.exists = _exists diff --git a/tests/TestCleanerML.py b/tests/TestCleanerML.py index 106e93a90..4184c90e1 100644 --- a/tests/TestCleanerML.py +++ b/tests/TestCleanerML.py @@ -41,8 +41,8 @@ def test_CleanerML(self): os.chdir('tests') xmlcleaner = CleanerML("../doc/example_cleaner.xml") - self.assert_(isinstance(xmlcleaner, CleanerML)) - self.assert_(isinstance(xmlcleaner.cleaner, Cleaner.Cleaner)) + self.assertIsInstance(xmlcleaner, CleanerML) + self.assertIsInstance(xmlcleaner.cleaner, Cleaner.Cleaner) def run_all(really_delete): for (option_id, __name) in xmlcleaner.cleaner.get_options(): @@ -97,4 +97,4 @@ def test_load_cleaners(self): def test_pot_fragment(self): """Unit test for pot_fragment()""" - self.assert_(isinstance(pot_fragment("Foo", 'bar.xml'), str)) + self.assertIsString(pot_fragment("Foo", 'bar.xml')) diff --git a/tests/TestCommand.py b/tests/TestCommand.py index 262ee83ee..9f5e98047 100644 --- a/tests/TestCommand.py +++ b/tests/TestCommand.py @@ -41,20 +41,20 @@ def test_Delete(self, cls=Delete): os.write(fd, "foo") os.close(fd) cmd = cls(path) - self.assert_(os.path.exists(path)) + self.assertExists(path) # preview ret = cmd.execute(really_delete=False).next() s = str(cmd) - self.assert_(ret['size'] > 0) + self.assertGreater(ret['size'], 0) self.assertEqual(ret['path'], path) - self.assert_(os.path.exists(path)) + self.assertExists(path) # delete ret = cmd.execute(really_delete=True).next() - self.assert_(ret['size'] > 0) + self.assertGreater(ret['size'], 0) self.assertEqual(ret['path'], path) - self.assert_(not os.path.exists(path)) + self.assertNotExists(path) def test_Function(self): """Unit test for Function""" @@ -62,19 +62,19 @@ def test_Function(self): os.write(fd, "foo") os.close(fd) cmd = Function(path, FileUtilities.delete, 'bar') - self.assert_(os.path.exists(path)) - self.assert_(os.path.getsize(path) > 0) + self.assertExists(path) + self.assertGreater(os.path.getsize(path), 0) # preview ret = cmd.execute(False).next() - self.assert_(os.path.exists(path)) - self.assert_(os.path.getsize(path) > 0) + self.assertExists(path) + self.assertGreater(os.path.getsize(path), 0) # delete ret = cmd.execute(True).next() - self.assert_(ret['size'] > 0, 'Size is %d' % ret['size']) + self.assertGreater(ret['size'], 0) self.assertEqual(ret['path'], path) - self.assert_(not os.path.exists(path)) + self.assertNotExists(path) def test_Shred(self): """Unit test for Shred""" diff --git a/tests/TestCommon.py b/tests/TestCommon.py index f1c548564..3e275f302 100644 --- a/tests/TestCommon.py +++ b/tests/TestCommon.py @@ -37,7 +37,7 @@ class CommonTestCase(common.BleachbitTestCase): def test_expandvars(self): """Unit test for expandvars.""" var = bleachbit.expandvars('$HOME') - self.assertIsInstance(var, unicode) + self.assertIsUnicodeString(var) def test_environment(self): """Test for important environment variables""" @@ -58,10 +58,10 @@ def test_expanduser(self): """Unit test for expanduser.""" # Return Unicode when given str. var = bleachbit.expanduser('~') - self.assertIsInstance(var, unicode) + self.assertIsUnicodeString(var) # Return Unicode when given Unicode. var = bleachbit.expanduser(u'~') - self.assertIsInstance(var, unicode) + self.assertIsUnicodeString(var) # Blank input should give blank output. self.assertEqual(bleachbit.expanduser(''), u'') # An absolute path should not be altered. @@ -72,7 +72,7 @@ def test_expanduser(self): self.assertExists(abs_dir) self.assertEqual(bleachbit.expanduser(abs_dir), abs_dir) # Path with tilde should be expanded - self.assertTrue(os.path.normpath(bleachbit.expanduser('~')), os.path.normpath(os.path.expanduser('~'))) + self.assertEqual(os.path.normpath(bleachbit.expanduser('~')), os.path.normpath(os.path.expanduser('~'))) # A relative path (without a reference to the home directory) # should not be expanded. self.assertEqual(bleachbit.expanduser('common'), 'common') diff --git a/tests/TestDeepScan.py b/tests/TestDeepScan.py index bd7347cb8..da0befede 100644 --- a/tests/TestDeepScan.py +++ b/tests/TestDeepScan.py @@ -42,7 +42,7 @@ def _test_encoding(self, fn): """Test encoding""" tempd = tempfile.mkdtemp(prefix='bleachbit-test-deepscan') - self.assert_(os.path.exists(tempd)) + self.assertExists(tempd) fullpath = os.path.join(tempd, fn) common.touch_file(fullpath) @@ -58,16 +58,13 @@ def _test_encoding(self, fn): self.assert_(found, "Did not find '%s'" % fullpath) os.unlink(fullpath) - self.assert_(not os.path.exists(fullpath)) + self.assertNotExists(fullpath) os.rmdir(tempd) - self.assert_(not os.path.exists(tempd)) + self.assertNotExists(tempd) def test_encoding(self): """Test encoding""" - tests = ('äöüßÄÖÜ', - "עִבְרִית") - - for test in tests: + for test in ('äöüßÄÖÜ', "עִבְרִית"): self._test_encoding(test) def test_DeepScan(self): @@ -83,10 +80,8 @@ def test_DeepScan(self): if True == ret: # it's yielding control to the GTK idle loop continue - self.assert_(isinstance(ret, (str, unicode)), - "Expecting string but got '%s' (%s)" % - (ret, str(type(ret)))) - self.assert_(os.path.lexists(ret)) + self.assertIsString(ret, "Expecting string but got '%s' (%s)" % (ret, str(type(ret)))) + self.assertLExists(ret) def test_delete(self): """Delete files in a test environment""" @@ -103,9 +98,9 @@ def test_delete(self): open(f_del2, 'w').close() # sanity check - self.assert_(os.path.exists(f_del1)) - self.assert_(os.path.exists(f_keep)) - self.assert_(os.path.exists(f_del2)) + self.assertExists(f_del1) + self.assertExists(f_keep) + self.assertExists(f_del2) # run deep scan astr = '' % base @@ -124,7 +119,7 @@ def test_delete(self): # validate results self.assertFalse(os.path.exists(f_del1)) - self.assert_(os.path.exists(f_keep)) + self.assertExists(f_keep) self.assertFalse(os.path.exists(f_del2)) # clean up diff --git a/tests/TestDiagnostic.py b/tests/TestDiagnostic.py index c029f8127..20029b29c 100644 --- a/tests/TestDiagnostic.py +++ b/tests/TestDiagnostic.py @@ -23,7 +23,6 @@ Test case for module Diagnostic """ - from __future__ import absolute_import, print_function from tests import common @@ -37,4 +36,4 @@ def test_diagnostic_info(self): """Test diagnostic_info""" # at least it does not crash ret = diagnostic_info() - self.assertIsString(ret, (str, unicode)) + self.assertIsString(ret) diff --git a/tests/TestFileUtilities.py b/tests/TestFileUtilities.py index 88ed1434c..4d013f134 100644 --- a/tests/TestFileUtilities.py +++ b/tests/TestFileUtilities.py @@ -46,7 +46,7 @@ def test_ini_helper(self, execute): os.write( fd, 'list=C:\\Users\\me\\Videos\\movie.mpg,C:\\Users\\me\\movie2.mpg\n\n') os.close(fd) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) size = os.path.getsize(filename) self.assertEqual(77, size) @@ -68,33 +68,30 @@ def test_ini_helper(self, execute): # clean up delete(filename) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) def test_json_helper(self, execute): """Used to test JSON cleaning in TestAction and in TestFileUtilities""" def load_js(js_fn): - js_fd = open(js_fn, 'r') - return json.load(js_fd) + with open(js_fn, 'r') as js_fd: + return json.load(js_fd) # create test file (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-json') os.write(fd, '{ "deleteme" : 1, "spareme" : { "deletemetoo" : 1 } }') os.close(fd) - self.assert_(os.path.exists(filename)) - self.assertEqual(load_js(filename), { - 'deleteme': 1, 'spareme': {'deletemetoo': 1}}) + self.assertExists(filename) + self.assertEqual(load_js(filename), {'deleteme': 1, 'spareme': {'deletemetoo': 1}}) # invalid key execute(filename, 'doesnotexist') - self.assertEqual(load_js(filename), { - 'deleteme': 1, 'spareme': {'deletemetoo': 1}}) + self.assertEqual(load_js(filename), {'deleteme': 1, 'spareme': {'deletemetoo': 1}}) # invalid key execute(filename, 'deleteme/doesnotexist') - self.assertEqual(load_js(filename), { - 'deleteme': 1, 'spareme': {'deletemetoo': 1}}) + self.assertEqual(load_js(filename), {'deleteme': 1, 'spareme': {'deletemetoo': 1}}) # valid key execute(filename, 'deleteme') @@ -110,7 +107,7 @@ def load_js(js_fn): # clean up delete(filename) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) class FileUtilitiesTestCase(common.BleachbitTestCase): @@ -161,9 +158,8 @@ def test_bytes_to_human(self): human = bytes_to_human(bytes1) bytes2 = human_to_bytes(human) error = abs(float(bytes2 - bytes1) / bytes1) - self.assert_(abs(error) < 0.01, - "%d (%s) is %.2f%% different than %d" % - (bytes1, human, error * 100, bytes2)) + self.assertLess(abs(error), 0.01, "%d (%s) is %.2f%% different than %d" % + (bytes1, human, error * 100, bytes2)) # test localization if hasattr(locale, 'format_string'): @@ -205,7 +201,7 @@ def test_children_in_directory(self): for filename in children_in_directory(dirname, True): self.assertEqual(filename, subdirname) for filename in children_in_directory(dirname, False): - self.assert_(False) + raise AssertionError('Found a file that shouldn\'t have been found: ' + filename) os.rmdir(subdirname) os.rmdir(dirname) @@ -278,16 +274,16 @@ def delete_helper(self, shred): bytes_written = os.write(fd, "top secret") self.assertEqual(bytes_written, 10) os.close(fd) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) delete(filename, shred) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) # delete an empty directory dirname = tempfile.mkdtemp( prefix='bleachbit-test-delete-dir' + test[0], suffix=test[1]) - self.assert_(os.path.exists(dirname)) + self.assertExists(dirname) delete(dirname, shred) - self.assert_(not os.path.exists(dirname)) + self.assertNotExists(dirname) def symlink_helper(link_fn): if 'nt' == os.name: @@ -301,21 +297,21 @@ def symlink_helper(link_fn): os.close(fd) # make symlink - self.assert_(os.path.exists(srcname)) + self.assertExists(srcname) linkname = tempfile.mktemp('bblink') - self.assert_(not os.path.exists(linkname)) + self.assertNotExists(linkname) link_fn(srcname, linkname) - self.assert_(os.path.exists(linkname)) - self.assert_(os.path.lexists(linkname)) + self.assertExists(linkname) + self.assertLExists(linkname) # delete symlink delete(linkname, shred) - self.assert_(os.path.exists(srcname)) - self.assert_(not os.path.lexists(linkname)) + self.assertExists(srcname) + self.assertNotLExists(linkname) # delete regular file delete(srcname, shred) - self.assert_(not os.path.exists(srcname)) + self.assertNotExists(srcname) # # test broken symlink @@ -323,20 +319,20 @@ def symlink_helper(link_fn): (fd, srcname) = tempfile.mkstemp( prefix='bleachbit-test-delete-sym') os.close(fd) - self.assert_(os.path.lexists(srcname)) + self.assertLExists(srcname) link_fn(srcname, linkname) - self.assert_(os.path.lexists(linkname)) - self.assert_(os.path.exists(linkname)) + self.assertLExists(linkname) + self.assertExists(linkname) # delete regular file first delete(srcname, shred) - self.assert_(not os.path.exists(srcname)) + self.assertNotExists(srcname)) self.assertLExists(linkname) # clean up delete(linkname, shred) - self.assert_(not os.path.exists(linkname)) - self.assert_(not os.path.lexists(linkname)) + self.assertNotExists(linkname) + self.assertNotLExists(linkname) if 'nt' == os.name and platform.uname()[3][0:3] > '5.1': # Windows XP = 5.1 @@ -361,7 +357,7 @@ def win_symlink(src, linkname): os.close(fd) os.chmod(filename, 0o444) delete(filename, shred) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) # test symlink symlink_helper(os.symlink) @@ -370,15 +366,15 @@ def win_symlink(src, linkname): args = ["mkfifo", filename] ret = subprocess.call(args) self.assertEqual(ret, 0) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) delete(filename, shred) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) # test directory path = tempfile.mkdtemp(prefix='bleachbit-test-delete-dir') - self.assert_(os.path.exists(path)) + self.assertExists(path) delete(path, shred) - self.assert_(not os.path.exists(path)) + self.assertNotExists(path) @unittest.skipIf('nt' != os.name, 'skipping on non-Windows') def test_delete_locked(self): @@ -458,7 +454,7 @@ def test_expand_glob_join(self): def test_expandvars(self): """Unit test for expandvars().""" expanded = expandvars('$HOME') - self.assertTrue(isinstance(expanded, unicode)) + self.assertIsUnicodeString(expanded) def test_extended_path(self): """Unit test for extended_path() and extended_path_undo()""" @@ -492,8 +488,8 @@ def test_free_space(self): home = expanduser('~') result = free_space(home) self.assertNotEqual(result, None) - self.assert_(result > -1) - self.assert_(isinstance(result, (int, long))) + self.assertGreater(result, -1) + self.assertIsInteger(result) # compare to WMIC if 'nt' != os.name: @@ -546,7 +542,7 @@ def test_getsize_helper(fname): print(output, du_size, du_bytes) self.assertEqual(getsize(filename), du_bytes) delete(filename) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) # create regular file test_getsize_helper('bleachbit-test-regular') @@ -575,8 +571,7 @@ def test_getsize_helper(fname): if os.path.lexists(linkname): delete(linkname) os.symlink(filename, linkname) - self.assert_(getsize(linkname) < 8192, "Symlink size is %d" % - getsize(filename)) + self.assertLess(getsize(linkname), 8192, "Symlink size is %d" % getsize(filename)) delete(filename) if 'darwin' == sys.platform: @@ -595,7 +590,7 @@ def test_getsizedir(self): path = '/bin' if 'nt' == os.name: path = 'c:\\windows\\system32' - self.assert_(getsizedir(path) > 0) + self.assertGreater(getsizedir(path), 0) def test_globex(self): """Unit test for method globex()""" @@ -808,17 +803,17 @@ def test_wipe_contents(self): def wipe_name_helper(self, filename): """Helper for test_wipe_name()""" - self.assert_(os.path.exists(filename)) + self.assertExists(filename) # test newname = wipe_name(filename) - self.assert_(len(filename) > len(newname)) - self.assert_(not os.path.exists(filename)) - self.assert_(os.path.exists(newname)) + self.assertGreater(len(filename), len(newname)) + self.assertNotExists(filename) + self.assertExists(newname) # clean os.remove(newname) - self.assert_(not os.path.exists(newname)) + self.assertNotExists(newname) def test_wipe_name(self): """Unit test for wipe_name()""" @@ -839,31 +834,31 @@ def test_wipe_name(self): # http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maxpath dir0len = 100 dir1len = 5 - filelen = 10 + filelen = 10 dir0 = tempfile.mkdtemp(prefix="0" * dir0len) - self.assert_(os.path.exists(dir0)) + self.assertExists(dir0) dir1 = tempfile.mkdtemp(prefix="1" * dir1len, dir=dir0) - self.assert_(os.path.exists(dir1)) + self.assertExists(dir1) (handle, filename) = tempfile.mkstemp( dir=dir1, prefix="2" * filelen) os.close(handle) self.wipe_name_helper(filename) - self.assert_(os.path.exists(dir0)) - self.assert_(os.path.exists(dir1)) + self.assertExists(dir0) + self.assertExists(dir1) # wipe a directory name dir1new = wipe_name(dir1) - self.assert_(len(dir1) > len(dir1new)) - self.assert_(not os.path.exists(dir1)) - self.assert_(os.path.exists(dir1new)) + self.assertGreater(len(dir1), len(dir1new)) + self.assertNotExists(dir1) + self.assertExists(dir1new) os.rmdir(dir1new) # wipe the directory os.rmdir(dir0) - self.assert_(not os.path.exists(dir0)) + self.assertNotExists(dir0) def test_wipe_path(self): """Unit test for wipe_path()""" @@ -895,7 +890,7 @@ def number_generator(): conn.executemany( 'insert into numbers (number) values ( ? ) ', number_generator()) conn.commit() - self.assert_(empty_size < getsize(path)) + self.assertLess(empty_size, getsize(path)) conn.execute('delete from numbers') conn.commit() conn.close() @@ -933,3 +928,11 @@ def test_open_files_lsof(self): self.assertEqual(list(open_files_lsof(lambda: 'n/bar/foo\nn/foo/bar\nnoise' )), ['/bar/foo', '/foo/bar']) + + +def suite(): + return unittest.makeSuite(FileUtilitiesTestCase) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/TestGeneral.py b/tests/TestGeneral.py index fbd7fbb59..47ca86a83 100644 --- a/tests/TestGeneral.py +++ b/tests/TestGeneral.py @@ -22,7 +22,6 @@ Test case for module General """ - from __future__ import absolute_import, print_function from bleachbit.General import * @@ -52,19 +51,18 @@ def test_getrealuid(self): self.assertRaises(RuntimeError, getrealuid) return uid = getrealuid() - self.assert_(isinstance(uid, int)) - self.assert_(0 <= uid <= 65535) + self.assertIsInstance(uid, int) + self.assertTrue(0 <= uid <= 65535) if sudo_mode(): - self.assert_(uid > 0) + self.assertGreater(uid, 0) logger.debug("os.getenv('LOGNAME') = %s", os.getenv('LOGNAME')) logger.debug("os.getenv('SUDO_UID') = %s", os.getenv('SUDO_UID')) logger.debug('os.geteuid() = %d', os.geteuid()) - logger.debug('os.getuid() = %d', str(os.getuid())) + logger.debug('os.getuid() = %d', os.getuid()) try: logger.debug('os.login() = %s', os.getlogin()) except: - traceback.print_exc() - logger.debug('os.login() raised exception') + logger.exception('os.login() raised exception') def test_makedirs(self): """Unit test for makedirs""" @@ -73,7 +71,7 @@ def cleanup(dir): return os.rmdir(dir) os.rmdir(os.path.dirname(dir)) - self.assert_(not os.path.lexists(dir)) + self.assertNotLExists(dir) if 'nt' == os.name: dir = 'c:\\temp\\bleachbit-test-makedirs\\a' @@ -82,10 +80,10 @@ def cleanup(dir): cleanup(dir) # directory does not exist makedirs(dir) - self.assert_(os.path.lexists(dir)) + self.assertLExists(dir) # directory already exists makedirs(dir) - self.assert_(os.path.lexists(dir)) + self.assertLExists(dir) # clean up cleanup(dir) @@ -167,4 +165,4 @@ def test_run_external_clean_env(self): @unittest.skipUnless('posix' == os.name, 'skipping on platforms without sudo') def test_sudo_mode(self): """Unit test for sudo_mode""" - self.assert_(isinstance(sudo_mode(), bool)) + self.assertIsInstance(sudo_mode(), bool) diff --git a/tests/TestMemory.py b/tests/TestMemory.py index 22cca029e..0951f3032 100644 --- a/tests/TestMemory.py +++ b/tests/TestMemory.py @@ -40,11 +40,9 @@ class MemoryTestCase(common.BleachbitTestCase): def test_get_proc_swaps(self): """Test for method get_proc_swaps""" ret = get_proc_swaps() - self.assert_(isinstance(ret, str)) - self.assert_(len(ret) > 10) + self.assertGreater(len(ret), 10) if not re.search('Filename\s+Type\s+Size', ret): - raise RuntimeError( - "Unexpected first line in swap summary '%s'" % ret) + raise RuntimeError("Unexpected first line in swap summary '%s'" % ret) @unittest.skipUnless(running_linux, 'not running linux') def test_make_self_oom_target_linux(self): @@ -63,9 +61,8 @@ def test_make_self_oom_target_linux(self): def test_count_linux_swap(self): """Test for method count_linux_swap""" n_swaps = count_swap_linux() - self.assert_(isinstance(n_swaps, (int, long))) - self.assert_(n_swaps >= 0) - self.assert_(n_swaps < 10) + self.assertIsInteger(n_swaps) + self.assertTrue(0 <= n_swaps < 10) def test_physical_free_darwin(self): self.assertEqual(physical_free_darwin(lambda: @@ -93,29 +90,29 @@ def test_physical_free_darwin(self): Swapins: 19424481. Swapouts: 20258188. """), 3427905536) - self.assertRaises( - RuntimeError, physical_free_darwin, lambda: "Invalid header") + self.assertRaises(RuntimeError, physical_free_darwin, lambda: "Invalid header") def test_physical_free(self): """Test for method physical_free""" ret = physical_free() - self.assert_(isinstance(ret, (int, long)), - 'physical_free() returns variable type %s' % type(ret)) - self.assert_(physical_free() > 0) + self.assertIsInteger(ret, 'physical_free() returns variable type %s' % type(ret)) + self.assertGreater(physical_free(), 0) report_free() @unittest.skipUnless(running_linux, 'not running linux') def test_get_swap_size_linux(self): """Test for get_swap_size_linux()""" - swapdev = open('/proc/swaps').read().split('\n')[1].split(' ')[0] + with open('/proc/swaps') as f: + swapdev = f.read().split('\n')[1].split(' ')[0] if 0 == len(swapdev): print('no active swap device detected') return size = get_swap_size_linux(swapdev) - self.assert_(isinstance(size, (int, long))) - self.assert_(size > 1024 ** 2) + self.assertIsInteger(size) + self.assertGreater(size, 1024 ** 2) logger.debug("size of swap '%s': %d B (%d MB)", swapdev, size, size / (1024 ** 2)) - proc_swaps = open('/proc/swaps').read() + with open('/proc/swaps') as f: + proc_swaps = f.read() size2 = get_swap_size_linux(swapdev, proc_swaps) self.assertEqual(size, size2) @@ -140,5 +137,5 @@ def test_swap_off_swap_on(self): """Test for disabling and enabling swap""" if not General.sudo_mode() or os.getuid() > 0: self.skipTest('not enough privileges') - devices = disable_swap_linux() + disable_swap_linux() enable_swap_linux() diff --git a/tests/TestOptions.py b/tests/TestOptions.py index e3a11dec9..3349fc646 100644 --- a/tests/TestOptions.py +++ b/tests/TestOptions.py @@ -21,7 +21,6 @@ """ Test case for module Options """ - from __future__ import absolute_import, print_function from tests import common @@ -65,25 +64,25 @@ def test_Options(self): self.assertEqual(list_values, o.get_list("list_test")) # whitelist - self.assert_(type(o.get_whitelist_paths() is list)) + self.assertIsInstance(o.get_whitelist_paths(), list) whitelist = [('file', '/home/foo'), ('folder', '/home')] old_whitelist = o.get_whitelist_paths() o.config.remove_section('whitelist/paths') - self.assert_(type(o.get_whitelist_paths() is list)) + self.assertIsInstance(o.get_whitelist_paths(), list) self.assertEqual(o.get_whitelist_paths(), []) o.set_whitelist_paths(whitelist) - self.assert_(type(o.get_whitelist_paths() is list)) + self.assertIsInstance(o.get_whitelist_paths(), list) self.assertEqual(set(whitelist), set(o.get_whitelist_paths())) o.set_whitelist_paths(old_whitelist) self.assertEqual(set(old_whitelist), set(o.get_whitelist_paths())) # these should always be set for bkey in bleachbit.Options.boolean_keys: - self.assert_(isinstance(o.get(bkey), bool)) + self.assertIsInstance(o.get(bkey), bool) # language value = o.get_language('en') - self.assert_(isinstance(value, bool)) + self.assertIsInstance(value, bool) o.set_language('en', True) self.assertTrue(o.get_language('en')) o.set_language('en', False) diff --git a/tests/TestSpecial.py b/tests/TestSpecial.py index 4ca1ffaeb..59f5332ca 100644 --- a/tests/TestSpecial.py +++ b/tests/TestSpecial.py @@ -225,15 +225,14 @@ def sqlite_clean_helper( self, sql, fn, clean_func, check_func=None, setup_func=None): """Helper for cleaning special SQLite cleaning""" - self.assertFalse( - sql and fn, "sql and fn are mutually exclusive ways to create the data") + self.assertFalse(sql and fn, "sql and fn are mutually exclusive ways to create the data") if fn: filename = os.path.normpath(os.path.join(self.dir_base, fn)) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) # create sqlite file - if sql: + elif sql: # create test file tmpdir = tempfile.mkdtemp(prefix='bleachbit-test-sqlite') (fd, filename) = tempfile.mkstemp(dir=tmpdir) @@ -244,11 +243,12 @@ def sqlite_clean_helper( setup_func(filename) # before SQL creation executed, cleaning should fail - self.assertRaises(sqlite3.DatabaseError, - clean_func, filename) + self.assertRaises(sqlite3.DatabaseError, clean_func, filename) # create FileUtilities.execute_sqlite3(filename, sql) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) + else: + raise RuntimeError('neither fn nor sql supplied') # clean the file old_shred = options.get('shred') @@ -259,7 +259,7 @@ def sqlite_clean_helper( self.assertTrue(options.get('shred')) options.set('shred', old_shred, commit=False) clean_func(filename) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) # check if check_func: @@ -267,7 +267,7 @@ def sqlite_clean_helper( # tear down FileUtilities.delete(filename) - self.assert_(not os.path.exists(filename)) + self.assertNotExists(filename) def test_delete_chrome_autofill(self): """Unit test for delete_chrome_autofill""" @@ -362,7 +362,7 @@ def test_get_chrome_bookmark_urls(self): os.write(fd, chrome_bookmarks) os.close(fd) - self.assert_(os.path.exists(path)) + self.assertExists(path) urls = Special.get_chrome_bookmark_urls(path) self.assertEqual( urls, [u'https://www.bleachbit.org/', u'http://www.slashdot.org/']) @@ -377,7 +377,7 @@ def test_get_sqlite_int(self): (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-sqlite') os.close(fd) FileUtilities.execute_sqlite3(filename, sql) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) # run the test ver = Special.get_sqlite_int( filename, 'select value from meta where key="version"') diff --git a/tests/TestUnix.py b/tests/TestUnix.py index 704d24963..34a625ef6 100644 --- a/tests/TestUnix.py +++ b/tests/TestUnix.py @@ -50,9 +50,9 @@ def test_apt(self): self.assertRaises(RuntimeError, apt_autoremove) else: bytes_freed = apt_autoclean() - self.assert_(isinstance(bytes_freed, (int, long))) + self.assertIsInteger(bytes_freed) bytes_freed = apt_autoremove() - self.assert_(isinstance(bytes_freed, (int, long))) + self.assertIsInteger(bytes_freed) def test_is_broken_xdg_desktop(self): """Unit test for is_broken_xdg_desktop()""" @@ -66,7 +66,7 @@ def test_is_broken_xdg_desktop(self): for dirname in menu_dirs: for filename in [fn for fn in FileUtilities.children_in_directory(dirname, False) if fn.endswith('.desktop')]: - self.assert_(type(is_broken_xdg_desktop(filename) is bool)) + self.assertIsInstance(is_broken_xdg_desktop(filename), bool) def test_is_running_darwin(self): def run_ps(): @@ -114,10 +114,10 @@ def test_locale_regex(self): regex = re.compile('^' + Locales.localepattern + '$') for test in tests: m = regex.match(test[0]) - self.assert_(m is not None, 'expected positive match for ' + test[0]) + self.assertIsNotNone(m, 'expected positive match for ' + test[0]) self.assertEqual(m.group("locale"), test[1]) for test in ['default', 'C', 'English', 'ru_RU.txt', 'ru.txt']: - self.assert_(regex.match(test) is None, 'expected negative match for '+test) + self.assertIsNone(regex.match(test), 'expected negative match for '+test) def test_localization_paths(self): """Unit test for localization_paths()""" @@ -127,7 +127,7 @@ def test_localization_paths(self): locales.add_xml(configpath) counter = 0 for path in locales.localization_paths(['en']): - self.assert_(os.path.lexists(path)) + self.assertLExists(path) # self.assert_(path.startswith('/usr/share/locale')) # /usr/share/locale/en_* should be ignored self.assert_(path.find('/en_') == -1) @@ -186,8 +186,7 @@ def test_fakelocalizationdirs(self): def test_rotated_logs(self): """Unit test for rotated_logs()""" for path in rotated_logs(): - self.assert_(os.path.exists(path), - "Rotated log path '%s' does not exist" % path) + self.assertLExists(path, "Rotated log path '%s' does not exist" % path) def test_run_cleaner_cmd(self): from subprocess import CalledProcessError @@ -208,7 +207,7 @@ def test_run_cleaner_cmd(self): def test_start_with_computer(self): """Unit test for start_with_computer*""" b = start_with_computer_check() - self.assert_(isinstance(b, bool)) + self.assertIsInstance(b, bool) if not os.path.exists(bleachbit.launcher_path) and \ os.path.exists('bleachbit.desktop'): @@ -218,12 +217,12 @@ def test_start_with_computer(self): # opposite setting start_with_computer(not b) two_b = start_with_computer_check() - self.assert_(isinstance(two_b, bool)) - self.assertEqual(b, not two_b) + self.assertIsInstance(two_b, bool) + self.assertNotEqual(b, two_b) # original setting start_with_computer(b) three_b = start_with_computer_check() - self.assert_(isinstance(b, bool)) + self.assertIsInstance(b, bool) self.assertEqual(b, three_b) def test_wine_to_linux_path(self): @@ -241,5 +240,5 @@ def test_yum_clean(self): self.assertRaises(RuntimeError, yum_clean) else: bytes_freed = yum_clean() - self.assert_(isinstance(bytes_freed, (int, long))) + self.assertIsInteger(bytes_freed) bleachbit.logger.debug('yum bytes cleaned %d', bytes_freed) diff --git a/tests/TestUpdate.py b/tests/TestUpdate.py index ac2ea53aa..77bb8d3a3 100644 --- a/tests/TestUpdate.py +++ b/tests/TestUpdate.py @@ -130,24 +130,24 @@ def on_success(): succeeded['r'] = False self.assertRaises(RuntimeError, update_winapp2, url, "notahash", append_text, on_success) - self.assert_(not succeeded['r']) + self.assertFalse(succeeded['r']) # blank hash, download file succeeded['r'] = False update_winapp2(url, None, append_text, on_success) - self.assert_(succeeded['r']) + self.assertTrue(succeeded['r']) # blank hash, do not download again update_winapp2(url, None, append_text, on_success) succeeded['r'] = False update_winapp2(url, None, append_text, on_success) - self.assert_(not succeeded['r']) + self.assertFalse(succeeded['r']) def test_user_agent(self): """Unit test for method user_agent()""" agent = user_agent() logger.debug("user agent = '%s'", agent) - self.assert_(isinstance(agent, str)) + self.assertIsString(agent) def test_environment(self): """Check the sanity of the environment""" diff --git a/tests/TestWorker.py b/tests/TestWorker.py index 364cda6ce..bc2bea718 100644 --- a/tests/TestWorker.py +++ b/tests/TestWorker.py @@ -205,7 +205,7 @@ def action_test_helper(self, command, special_expected, errors_expected, (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-worker') os.write(fd, '123') os.close(fd) - self.assert_(os.path.exists(filename)) + self.assertExists(filename) astr = '' % (command, filename) cleaner = TestCleaner.action_to_cleaner(astr) backends['test'] = cleaner @@ -214,8 +214,7 @@ def action_test_helper(self, command, special_expected, errors_expected, run = worker.run() while run.next(): pass - self.assert_(not os.path.exists(filename), - "Path still exists '%s'" % filename) + self.assertNotExists(filename, "Path still exists '%s'" % filename) self.assertEqual(worker.total_special, special_expected, 'For command %s expecting %s special operations but observed %d' % (command, special_expected, worker.total_special)) @@ -316,10 +315,10 @@ def test_multiple_options(self): ui = CLI.CliCallback() (fd, filename1) = tempfile.mkstemp(prefix='bleachbit-test-worker') os.close(fd) - self.assert_(os.path.exists(filename1)) + self.assertExists(filename1) (fd, filename2) = tempfile.mkstemp(prefix='bleachbit-test-worker') os.close(fd) - self.assert_(os.path.exists(filename2)) + self.assertExists(filename2) astr1 = '' % filename1 astr2 = '' % filename2 @@ -330,10 +329,8 @@ def test_multiple_options(self): run = worker.run() while run.next(): pass - self.assert_(not os.path.exists(filename1), - "Path still exists '%s'" % filename1) - self.assert_(not os.path.exists(filename2), - "Path still exists '%s'" % filename2) + self.assertNotExists(filename1, "Path still exists '%s'" % filename1) + self.assertNotExists(filename2, "Path still exists '%s'" % filename2) self.assertEqual(worker.total_special, 0) self.assertEqual(worker.total_errors, 0) self.assertEqual(worker.total_deleted, 2) diff --git a/tests/common.py b/tests/common.py index fdcc1ecbe..07cf81da0 100644 --- a/tests/common.py +++ b/tests/common.py @@ -53,6 +53,9 @@ def tearDownClass(cls): def assertIsInteger(self, obj, msg=''): self.assertIsInstance(obj, (int, long), msg) + def assertIsUnicodeString(self, obj, msg=''): + self.assertIsInstance(obj, unicode, msg) + def assertIsString(self, obj, msg=''): self.assertIsInstance(obj, (unicode, str), msg) From fc4ac0acff3752f32c59e0ef27671fcb7cb74a7d Mon Sep 17 00:00:00 2001 From: Tristan Stenner Date: Sun, 5 Feb 2017 21:21:31 +0100 Subject: [PATCH 3/4] temp file handling --- tests/TestAction.py | 20 +-- tests/TestCLI.py | 14 +-- tests/TestCleaner.py | 48 +++----- tests/TestCleanerML.py | 15 +-- tests/TestCommand.py | 13 +- tests/TestCommon.py | 31 ++--- tests/TestDeepScan.py | 38 ++---- tests/TestFileUtilities.py | 208 ++++++++++++-------------------- tests/TestGeneral.py | 67 ++++------ tests/TestMemory.py | 4 +- tests/TestOptions.py | 10 +- tests/TestRecognizeCleanerML.py | 1 - tests/TestSpecial.py | 74 +++++------- tests/TestUnix.py | 60 +++++---- tests/TestUpdate.py | 57 ++++----- tests/TestWinapp.py | 1 - tests/TestWorker.py | 38 ++---- tests/common.py | 18 ++- 18 files changed, 260 insertions(+), 457 deletions(-) diff --git a/tests/TestAction.py b/tests/TestAction.py index b7cb8dbba..858a1883f 100644 --- a/tests/TestAction.py +++ b/tests/TestAction.py @@ -146,9 +146,7 @@ def test_delete(self): for path in paths: for mode in ('delete', 'truncate', 'delete_forward'): expanded = expanduser(expandvars(path)) - (fd, filename) = tempfile.mkstemp( - dir=expanded, prefix='bleachbit-action-delete') - os.close(fd) + filename = self.mkstemp(dir=expanded, prefix='bleachbit-action-delete') command = mode if 'delete_forward' == mode: # forward slash needs to be normalized on Windows @@ -166,19 +164,16 @@ def test_delete(self): def test_delete_special_filenames(self): """Unit test for deleting special filenames""" - dirname = tempfile.mkdtemp(prefix='bleachbit-action-delete-special') tests = [ 'normal', 'space in name', 'sigil$should-not-be-expanded', ] for test in tests: - pathname = os.path.join(dirname, test) - common.touch_file(pathname) + pathname = self.write_file(test) action_str = u'' % pathname self._test_action_str(action_str) self.assertNotExists(pathname) - os.rmdir(dirname) def test_ini(self): """Unit test for class Ini""" @@ -207,10 +202,7 @@ def execute_json(path, address): def test_process(self): """Unit test for process action""" - if 'nt' == os.name: - cmd = 'cmd.exe /c dir' - if 'posix' == os.name: - cmd = 'dir' + cmds = {'nt': 'cmd.exe /c dir', 'posix': 'dir'} tests = [u'', u'', u'', @@ -219,7 +211,7 @@ def test_process(self): ] for test in tests: - self._test_action_str(test % cmd) + self._test_action_str(test % cmds[os.name]) def test_regex(self): """Unit test for regex option""" @@ -308,7 +300,7 @@ def test_wholeregex(self): def test_type(self): """Unit test for type attribute""" - dirname = tempfile.mkdtemp(prefix='bleachbit-action-type') + dirname = self.mkdtemp(prefix='bleachbit-action-type') filename = os.path.join(dirname, 'file') # this should not delete anything @@ -340,7 +332,7 @@ def test_type(self): def test_walk_all(self): """Unit test for walk.all""" - dirname = tempfile.mkdtemp(prefix='bleachbit-walk-all') + dirname = self.mkdtemp(prefix='bleachbit-walk-all') # this sub-directory should be deleted subdir = os.path.join(dirname, 'sub') diff --git a/tests/TestCLI.py b/tests/TestCLI.py index 40eed39a3..093eaa983 100644 --- a/tests/TestCLI.py +++ b/tests/TestCLI.py @@ -38,7 +38,6 @@ class CLITestCase(common.BleachbitTestCase): - """Test case for module CLI""" def setUp(self): @@ -82,16 +81,13 @@ def test_cleaners_list(self): def test_encoding(self): """Unit test for encoding""" - (fd, filename) = tempfile.mkstemp( - prefix='bleachbit-test-cli-encoding-\xe4\xf6\xfc~', dir='/tmp') - os.close(fd) + filename = self.write_file('/tmp/bleachbit-test-cli-encoding-\xe4\xf6\xfc~') # not assertExists because it doesn't cope with invalid encodings self.assertTrue(os.path.exists(filename)) env = copy.deepcopy(os.environ) env['LANG'] = 'en_US' # not UTF-8 - module = 'bleachbit.CLI' - args = [sys.executable, '-m', module, '-p', 'system.tmp'] + args = [sys.executable, '-m', 'bleachbit.CLI', '-p', 'system.tmp'] # If Python pipes stdout to file or devnull, the test may give # a false negative. It must print stdout to terminal. self._test_preview(args, stdout=True, env=env) @@ -104,8 +100,7 @@ def test_invalid_locale(self): lang = os.environ['LANG'] os.environ['LANG'] = 'blahfoo' # tests are run from the parent directory - module = 'bleachbit.CLI' - args = [sys.executable, '-m', module, '--version'] + args = [sys.executable, '-m', 'bleachbit.CLI', '--version'] output = run_external(args) self.assertNotEqual(output[1].find('Copyright'), -1, str(output)) os.environ['LANG'] = lang @@ -127,8 +122,7 @@ def test_preview(self): def test_delete(self): """Unit test for --delete option""" - (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-cli-delete') - os.close(fd) + filename = self.mkstemp(prefix='bleachbit-test-cli-delete') if 'nt' == os.name: import win32api filename = os.path.normcase(filename) diff --git a/tests/TestCleaner.py b/tests/TestCleaner.py index 0172acef6..92b5c9aff 100644 --- a/tests/TestCleaner.py +++ b/tests/TestCleaner.py @@ -32,12 +32,11 @@ from tests import common import logging -import tempfile -import unittest from xml.dom.minidom import parseString logger = logging.getLogger('bleachbit') + def action_to_cleaner(action_str): """Given an action XML fragment, return a cleaner""" return actions_to_cleaner([action_str]) @@ -69,25 +68,20 @@ def test_add_action(self): """Unit test for Cleaner.add_action()""" self.actions = [] if 'nt' == os.name: - self.actions.append( - '') - self.actions.append( - '') - self.actions.append( - '') - self.actions.append( - '') + self.actions += [ + '', + '', + '', + ''] elif 'posix' == os.name: print(__file__) - self.actions.append( - '' % __file__) - self.actions.append( - '') - self.actions.append( - '') - self.actions.append( - '') - + self.actions += [ + '' % __file__, + '', + '', + ''] + else: + raise AssertionError('Unknown OS.') self.assertGreater(len(self.actions), 0) for action_str in self.actions: @@ -115,27 +109,23 @@ def test_auto_hide(self): def test_create_simple_cleaner(self): """Unit test for method create_simple_cleaner""" - dirname = tempfile.mkdtemp( - prefix='bleachbit-test-create-simple-cleaner') + dirname = self.mkdtemp(prefix='bleachbit-test-create-simple-cleaner') filename1 = os.path.join(dirname, '1') common.touch_file(filename1) # test Cyrillic for https://bugs.launchpad.net/bleachbit/+bug/1541808 filename2 = os.path.join(dirname, u'чистый') common.touch_file(filename2) - self.assertExists(filename1) - self.assertExists(filename2) - cleaner = create_simple_cleaner([filename1, filename2, dirname]) + targets = [filename1, filename2, dirname] + cleaner = create_simple_cleaner(targets) for cmd in cleaner.get_commands('files'): # preview for result in cmd.execute(False): common.validate_result(self, result) # delete - for result in cmd.execute(True): - pass + list(cmd.execute(True)) - self.assertNotExists(filename1) - self.assertNotExists(filename2) - self.assertNotExists(dirname) + for target in targets: + self.assertNotExists(target) def test_get_name(self): for key in sorted(backends): diff --git a/tests/TestCleanerML.py b/tests/TestCleanerML.py index 4184c90e1..2a9490905 100644 --- a/tests/TestCleanerML.py +++ b/tests/TestCleanerML.py @@ -21,18 +21,13 @@ """ Test cases for module CleanerML """ - - from __future__ import absolute_import, print_function from tests import common from bleachbit.CleanerML import * -import unittest - class CleanerMLTestCase(common.BleachbitTestCase): - """Test cases for CleanerML""" def test_CleanerML(self): @@ -82,14 +77,10 @@ def test_load_cleaners(self): load_cleaners() # should catch exception with invalid XML - import tempfile pcd = bleachbit.personal_cleaners_dir - bleachbit.personal_cleaners_dir = tempfile.mkdtemp( - prefix='bleachbit-cleanerml-load') - fn_xml = os.path.join(bleachbit.personal_cleaners_dir, 'invalid.xml') - f = open(fn_xml, 'w') - f.write('') - f.close() + bleachbit.personal_cleaners_dir = self.mkdtemp(prefix='bleachbit-cleanerml-load') + self.write_file(os.path.join(bleachbit.personal_cleaners_dir, 'invalid.xml'), + contents='') load_cleaners() import shutil shutil.rmtree(bleachbit.personal_cleaners_dir) diff --git a/tests/TestCommand.py b/tests/TestCommand.py index 9f5e98047..751cc1654 100644 --- a/tests/TestCommand.py +++ b/tests/TestCommand.py @@ -21,25 +21,18 @@ """ Test case for Command """ - - from __future__ import absolute_import, print_function from tests import common from bleachbit.Command import * -import tempfile - class CommandTestCase(common.BleachbitTestCase): - """Test case for Command""" def test_Delete(self, cls=Delete): """Unit test for Delete""" - (fd, path) = tempfile.mkstemp(prefix='bleachbit-test-command') - os.write(fd, "foo") - os.close(fd) + path = self.write_file('test_Delete', b'foo') cmd = cls(path) self.assertExists(path) @@ -58,9 +51,7 @@ def test_Delete(self, cls=Delete): def test_Function(self): """Unit test for Function""" - (fd, path) = tempfile.mkstemp(prefix='bleachbit-test-command') - os.write(fd, "foo") - os.close(fd) + path = self.write_file('test_Function', b'foo') cmd = Function(path, FileUtilities.delete, 'bar') self.assertExists(path) self.assertGreater(os.path.getsize(path), 0) diff --git a/tests/TestCommon.py b/tests/TestCommon.py index 3e275f302..eaff732a1 100644 --- a/tests/TestCommon.py +++ b/tests/TestCommon.py @@ -31,7 +31,6 @@ class CommonTestCase(common.BleachbitTestCase): - """Test case for Common.""" def test_expandvars(self): @@ -43,36 +42,32 @@ def test_environment(self): """Test for important environment variables""" # useful for researching # grep -Poh "([\\$%]\w+)" cleaners/*xml | cut -b2- | sort | uniq -i - if 'posix' == os.name: - envs = ('XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', - 'HOME') - else: - envs = ('AppData', 'CommonAppData', 'Documents', 'ProgramFiles', - 'UserProfile', 'WinDir') - for env in envs: + envs = {'posix': ['XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'HOME'], + 'nt': ['AppData', 'CommonAppData', 'Documents', 'ProgramFiles', 'UserProfile', 'WinDir']} + for env in envs[os.name]: e = os.getenv(env) self.assertIsNotNone(e) - self.assertTrue(len(e) > 4) + self.assertGreater(len(e), 4) def test_expanduser(self): """Unit test for expanduser.""" # Return Unicode when given str. - var = bleachbit.expanduser('~') - self.assertIsUnicodeString(var) + self.assertIsUnicodeString(bleachbit.expanduser('~')) + # Return Unicode when given Unicode. - var = bleachbit.expanduser(u'~') - self.assertIsUnicodeString(var) + self.assertIsUnicodeString(bleachbit.expanduser(u'~')) + # Blank input should give blank output. self.assertEqual(bleachbit.expanduser(''), u'') + # An absolute path should not be altered. - if 'posix' == os.name: - abs_dir = os.path.expandvars('$HOME') - if 'nt' == os.name: - abs_dir = os.path.expandvars('%USERPROFILE%') + abs_dirs = {'posix': '$HOME', 'nt': '%USERPROFILE%'} + abs_dir = os.path.expandvars(abs_dirs[os.name]) self.assertExists(abs_dir) self.assertEqual(bleachbit.expanduser(abs_dir), abs_dir) # Path with tilde should be expanded - self.assertEqual(os.path.normpath(bleachbit.expanduser('~')), os.path.normpath(os.path.expanduser('~'))) + self.assertEqual(os.path.normpath(bleachbit.expanduser('~')), + os.path.normpath(os.path.expanduser('~'))) # A relative path (without a reference to the home directory) # should not be expanded. self.assertEqual(bleachbit.expanduser('common'), 'common') diff --git a/tests/TestDeepScan.py b/tests/TestDeepScan.py index da0befede..271a39992 100644 --- a/tests/TestDeepScan.py +++ b/tests/TestDeepScan.py @@ -35,32 +35,26 @@ class DeepScanTestCase(common.BleachbitTestCase): - """Test Case for module DeepScan""" def _test_encoding(self, fn): """Test encoding""" - tempd = tempfile.mkdtemp(prefix='bleachbit-test-deepscan') - self.assertExists(tempd) - - fullpath = os.path.join(tempd, fn) - common.touch_file(fullpath) + fullpath = self.write_file(fn) ds = DeepScan() - ds.add_search(tempd, '^%s$' % fn) + ds.add_search(self.tempdir, '^%s$' % fn) found = False for ret in ds.scan(): if True == ret: continue - self.assert_(ret == fullpath) + print(ret) + self.assertEqual(ret, fullpath) found = True - self.assert_(found, "Did not find '%s'" % fullpath) + self.assertTrue(found, "Did not find '%s'" % fullpath) os.unlink(fullpath) self.assertNotExists(fullpath) - os.rmdir(tempd) - self.assertNotExists(tempd) def test_encoding(self): """Test encoding""" @@ -87,15 +81,11 @@ def test_delete(self): """Delete files in a test environment""" # make some files - base = tempfile.mkdtemp(prefix='bleachbit-deepscan-test') - f_del1 = os.path.join(base, 'foo.txt.bbtestbak') - open(f_del1, 'w').close() - f_keep = os.path.join(base, 'foo.txt') - open(f_keep, 'w').close() - subdir = os.path.join(base, 'sub') + f_del1 = self.write_file('foo.txt.bbtestbak') + f_keep = self.write_file('foo.txt') + subdir = os.path.join(self.tempdir, 'sub') os.mkdir(subdir) - f_del2 = os.path.join(base, 'sub/bar.ini.bbtestbak') - open(f_del2, 'w').close() + f_del2 = self.write_file(os.path.join(subdir,'bar.ini.bbtestbak')) # sanity check self.assertExists(f_del1) @@ -103,7 +93,7 @@ def test_delete(self): self.assertExists(f_del2) # run deep scan - astr = '' % base + astr = '' % self.tempdir from tests import TestCleaner cleaner = TestCleaner.action_to_cleaner(astr) from bleachbit.Worker import backends, Worker @@ -112,19 +102,13 @@ def test_delete(self): from bleachbit import CLI ui = CLI.CliCallback() worker = Worker(ui, True, operations) - run = worker.run() - while run.next(): - pass + list(worker.run()) # validate results - self.assertFalse(os.path.exists(f_del1)) self.assertExists(f_keep) self.assertFalse(os.path.exists(f_del2)) - # clean up - shutil.rmtree(base) - def test_normalized_walk_darwin(self): import mock diff --git a/tests/TestFileUtilities.py b/tests/TestFileUtilities.py index 4d013f134..0b0e832cf 100644 --- a/tests/TestFileUtilities.py +++ b/tests/TestFileUtilities.py @@ -39,24 +39,20 @@ def test_ini_helper(self, execute): """Used to test .ini cleaning in TestAction and in TestFileUtilities""" + teststr = b'#Test\n[RecentsMRL]\nlist=C:\\Users\\me\\Videos\\movie.mpg,C:\\Users\\me\\movie2.mpg\n\n' # create test file - (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-ini') - os.write(fd, '#Test\n') - os.write(fd, '[RecentsMRL]\n') - os.write( - fd, 'list=C:\\Users\\me\\Videos\\movie.mpg,C:\\Users\\me\\movie2.mpg\n\n') - os.close(fd) + filename = self.write_file('bleachbit-test-ini', teststr) self.assertExists(filename) size = os.path.getsize(filename) - self.assertEqual(77, size) + self.assertEqual(len(teststr), size) # section does not exist execute(filename, 'Recents', None) - self.assertEqual(77, os.path.getsize(filename)) + self.assertEqual(len(teststr), os.path.getsize(filename)) # parameter does not exist execute(filename, 'RecentsMRL', 'files') - self.assertEqual(77, os.path.getsize(filename)) + self.assertEqual(len(teststr), os.path.getsize(filename)) # parameter does exist execute(filename, 'RecentsMRL', 'list') @@ -78,20 +74,22 @@ def load_js(js_fn): with open(js_fn, 'r') as js_fd: return json.load(js_fd) + expected = {'deleteme': 1, 'spareme': {'deletemetoo': 1}} + # create test file - (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-json') + (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-json', dir=self.tempdir) os.write(fd, '{ "deleteme" : 1, "spareme" : { "deletemetoo" : 1 } }') os.close(fd) self.assertExists(filename) - self.assertEqual(load_js(filename), {'deleteme': 1, 'spareme': {'deletemetoo': 1}}) + self.assertEqual(load_js(filename), expected) # invalid key execute(filename, 'doesnotexist') - self.assertEqual(load_js(filename), {'deleteme': 1, 'spareme': {'deletemetoo': 1}}) + self.assertEqual(load_js(filename), expected) # invalid key execute(filename, 'deleteme/doesnotexist') - self.assertEqual(load_js(filename), {'deleteme': 1, 'spareme': {'deletemetoo': 1}}) + self.assertEqual(load_js(filename), expected) # valid key execute(filename, 'deleteme') @@ -180,15 +178,14 @@ def test_children_in_directory(self): # test an existing directory that usually exists dirname = expanduser("~/.config") for filename in children_in_directory(dirname, True): - self.assert_(os.path.isabs(filename)) + self.assertTrue(os.path.isabs(filename)) for filename in children_in_directory(dirname, False): - self.assert_(os.path.isabs(filename)) - self.assert_(not os.path.isdir(filename)) + self.assertTrue(os.path.isabs(filename)) + self.assertFalse(os.path.isdir(filename)) # test a constructed file in a constructed directory - dirname = tempfile.mkdtemp(prefix='bleachbit-test-children') - filename = os.path.join(dirname, "somefile") - common.touch_file(filename) + dirname = self.mkdtemp(prefix='bleachbit-test-children') + filename = self.mkstemp(prefix="somefile", dir=dirname) for loopfilename in children_in_directory(dirname, True): self.assertEqual(loopfilename, filename) for loopfilename in children_in_directory(dirname, False): @@ -244,43 +241,32 @@ def delete_helper(self, shred): katanana = u"アメリカ" umlauts = u"ÄäǞǟËëḦḧÏïḮḯÖöȪȫṎṏT̈ẗÜüǕǖǗǘǙǚǛǜṲṳṺṻẄẅẌẍŸÿ" - tests = [('.prefix', 'suffix'), # simple - ("x".zfill(100), ".y".zfill(50)), # long - (' ', 'begins_with_space'), - ("'", "'"), # quotation mark - ("~`!@#$%^&()-_+=", "x"), # non-alphanumeric characters - ("[]{};'.,", "x"), # non-alphanumeric characters - (u'abcd', u'efgh'), # simple Unicode - (u'J\xf8rgen', 'Scandinavian'), - (u'\u2014', 'em-dash'), # LP#1454030 - (hebrew, hebrew), - (katanana, katanana), - (umlauts, umlauts), - ('sigil', 'should$not-change')] + tests = ['.prefixandsuffix', # simple + "x".zfill(150), # long + ' begins_with_space', + "''", # quotation mark + "~`!@#$%^&()-_+=x", # non-alphanumeric characters + "[]{};'.,x", # non-alphanumeric characters + u'abcdefgh', # simple Unicode + u'J\xf8rgen Scandinavian', + u'\u2014em-dash', # LP#1454030 + hebrew, + katanana, + umlauts, + 'sigil-should$not-change'] if 'posix' == os.name: # Windows doesn't allow these characters but Unix systems do - tests.append(('"', '*')) - tests.append(('\t', '\\')) - tests.append((':?', '<>|')) - # Windows filenames cannot end with space or period - tests.append((' ', ' ')) - tests.append(('.', '.')) + tests += ['"*', '\t\\', ':?<>|', + ' ', '.file.'] # Windows filenames cannot end with space or period for test in tests: - # delete a file - (fd, filename) = tempfile.mkstemp( - prefix='bleachbit-test-delete-file' + test[0], suffix=test[1]) - self.assert_(os.path.exists(filename)) - for x in range(0, 4096): - bytes_written = os.write(fd, "top secret") - self.assertEqual(bytes_written, 10) - os.close(fd) - self.assertExists(filename) + # create the file + filename = self.write_file(test, "top secret") + # delete the file delete(filename, shred) self.assertNotExists(filename) # delete an empty directory - dirname = tempfile.mkdtemp( - prefix='bleachbit-test-delete-dir' + test[0], suffix=test[1]) + dirname = self.mkdtemp(prefix=test) self.assertExists(dirname) delete(dirname, shred) self.assertNotExists(dirname) @@ -292,9 +278,7 @@ def symlink_helper(link_fn): self.skipTest('skipping symlink test because of insufficient privileges') # make regular file - (fd, srcname) = tempfile.mkstemp( - prefix='bleachbit-test-delete-regular') - os.close(fd) + srcname = self.mkstemp(prefix='bleachbit-test-delete-regular') # make symlink self.assertExists(srcname) @@ -316,9 +300,7 @@ def symlink_helper(link_fn): # # test broken symlink # - (fd, srcname) = tempfile.mkstemp( - prefix='bleachbit-test-delete-sym') - os.close(fd) + srcname = self.mkstemp(prefix='bleachbit-test-delete-sym') self.assertLExists(srcname) link_fn(srcname, linkname) self.assertLExists(linkname) @@ -326,7 +308,7 @@ def symlink_helper(link_fn): # delete regular file first delete(srcname, shred) - self.assertNotExists(srcname)) + self.assertNotExists(srcname) self.assertLExists(linkname) # clean up @@ -353,8 +335,7 @@ def win_symlink(src, linkname): return # test file with mode 0444/-r--r--r-- - (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-0444') - os.close(fd) + filename = self.write_file('bleachbit-test-0444') os.chmod(filename, 0o444) delete(filename, shred) self.assertNotExists(filename) @@ -371,7 +352,7 @@ def win_symlink(src, linkname): self.assertNotExists(filename) # test directory - path = tempfile.mkdtemp(prefix='bleachbit-test-delete-dir') + path = self.mkdtemp(prefix='bleachbit-test-delete-dir') self.assertExists(path) delete(path, shred) self.assertNotExists(path) @@ -428,7 +409,7 @@ def test_exists_in_path(self): filename = 'ls' if 'nt' == os.name: filename = 'cmd.exe' - self.assert_(exists_in_path(filename)) + self.assertTrue(exists_in_path(filename)) def test_exe_exists(self): """Unit test for exe_exists()""" @@ -459,29 +440,21 @@ def test_expandvars(self): def test_extended_path(self): """Unit test for extended_path() and extended_path_undo()""" if 'nt' == os.name: - tests = ( + tests = [ (r'c:\windows\notepad.exe', r'\\?\c:\windows\notepad.exe'), - (r'c:\windows\notepad.exe', r'\\?\c:\windows\notepad.exe'), - (r'\\?\c:\windows\notepad.exe', r'\\?\c:\windows\notepad.exe'), (r'\\server\share\windows\notepad.exe', r'\\?\unc\server\share\windows\notepad.exe'), - (r'\\?\unc\server\share\windows\notepad.exe', r'\\?\unc\server\share\windows\notepad.exe') - ) - tests_undo = ( - (r'\\?\c:\windows\notepad.exe', r'c:\windows\notepad.exe'), - (r'c:\windows\notepad.exe', r'c:\windows\notepad.exe'), - (r'\\?\unc\server\share\windows\notepad.exe', r'\\server\share\windows\notepad.exe'), - (r'\\server\share\windows\notepad.exe', - r'\\server\share\windows\notepad.exe') - ) - + ] else: # unchanged tests = (('/home/foo', '/home/foo'),) - tests_undo = tests - for test in tests: - self.assertEqual(extended_path(test[0]), test[1]) - for test in tests_undo: - self.assertEqual(extended_path_undo(test[0]), test[1]) + for short, extended in tests: + # already extended path shouldn't be changed + self.assertEqual(extended_path(extended), extended) + # does the conversion work both ways? + self.assertEqual(extended_path(short), extended) + self.assertEqual(extended_path_undo(extended), short) + # unextended paths shouldn't be shortened any more + self.assertEqual(extended_path_undo(short), short) def test_free_space(self): """Unit test for free_space()""" @@ -513,7 +486,7 @@ def test_free_space(self): def test_getsize(self): """Unit test for method getsize()""" - dirname = tempfile.mkdtemp(prefix='bleachbit-test-getsize', dir=self.tempdir) + dirname = self.mkdtemp(prefix='bleachbit-test-getsize') def test_getsize_helper(fname): filename = self.write_file(os.path.join(dirname, fname), "abcdefghij" * 12345) @@ -564,10 +537,8 @@ def test_getsize_helper(fname): return # create a symlink - (handle, filename) = tempfile.mkstemp(prefix='bleachbit-test-symlink') - os.write(handle, "abcdefghij" * 12345) - os.close(handle) - linkname = '/tmp/bleachbitsymlinktest' + filename = self.write_file('bleachbit-test-symlink', 'abcdefghij' * 12345) + linkname = os.path.join(self.tempdir, 'bleachbitsymlinktest') if os.path.lexists(linkname): delete(linkname) os.symlink(filename, linkname) @@ -600,16 +571,13 @@ def test_globex(self): def test_guess_overwrite_paths(self): """Unit test for guess_overwrite_paths()""" for path in guess_overwrite_paths(): - self.assert_(os.path.isdir(path), '%s is not a directory' % path) + self.assertTrue(os.path.isdir(path), '%s is not a directory' % path) def test_human_to_bytes(self): """Unit test for human_to_bytes()""" self.assertRaises(ValueError, human_to_bytes, '', hformat='invalid') - invalid = ['Bazillion kB', - '120XB', - '.12MB'] - for test in invalid: + for test in ['Bazillion kB', '120XB', '.12MB']: self.assertRaises(ValueError, human_to_bytes, test) valid = {'1kB': 1000, @@ -660,8 +628,7 @@ def test_same_partition(self): from bleachbit.Windows import get_fixed_drives for drive in get_fixed_drives(): this_drive = os.path.splitdrive(drive)[0] - self.assertEqual(same_partition(home, drive), - home_drive == this_drive) + self.assertEqual(same_partition(home, drive), home_drive == this_drive) def test_whitelisted(self): """Unit test for whitelisted()""" @@ -718,16 +685,15 @@ def test_whitelisted(self): self.assertEqual( set(old_whitelist), set(options.get_whitelist_paths())) - @unittest.skipUnless('posix' == os.name, 'skipping on non-POSIX platform') def test_whitelisted_posix_symlink(self): """Symlink test for whitelisted_posix()""" # setup old_whitelist = options.get_whitelist_paths() - tmpdir = tempfile.mkdtemp(prefix='bleachbit-whitelist') - realpath = os.path.join(tmpdir, 'real') + tmpdir = os.path.join(self.tempdir, 'bleachbit-whitelist') + os.mkdir(tmpdir) + realpath = self.write_file('real') linkpath = os.path.join(tmpdir, 'link') - common.touch_file(realpath) os.symlink(realpath, linkpath) self.assertExists(realpath) self.assertExists(linkpath) @@ -746,9 +712,6 @@ def test_whitelisted_posix_symlink(self): self.assertFalse(whitelisted(realpath)) self.assertTrue(whitelisted(linkpath)) - # clean up - import shutil - shutil.rmtree(tmpdir) options.set_whitelist_paths(old_whitelist) def test_whitelisted_speed(self): @@ -781,9 +744,7 @@ def test_wipe_contents(self): """Unit test for wipe_delete()""" # create test file - (handle, filename) = tempfile.mkstemp(prefix="bleachbit-test-wipe") - os.write(handle, "abcdefghij" * 12345) - os.close(handle) + filename = self.write_file('bleachbit-test-wipe', 'abcdefghij' * 12345) # wipe it wipe_contents(filename) @@ -819,32 +780,27 @@ def test_wipe_name(self): """Unit test for wipe_name()""" # create test file with moderately long name - (handle, filename) = tempfile.mkstemp( - prefix="bleachbit-test-wipe" + "0" * 50) - os.close(handle) + filename = self.write_file('bleachbit-test-wipe' + '0' * 50) self.wipe_name_helper(filename) # create file with short name in temporary directory with long name - if 'posix' == os.name: - dir0len = 210 - dir1len = 210 - filelen = 10 if 'nt' == os.name: # In Windows, the maximum path length is 260 characters # http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maxpath dir0len = 100 dir1len = 5 + else: + dir0len = 210 + dir1len = 210 filelen = 10 - dir0 = tempfile.mkdtemp(prefix="0" * dir0len) + dir0 = self.mkdtemp(prefix="0" * dir0len) self.assertExists(dir0) - dir1 = tempfile.mkdtemp(prefix="1" * dir1len, dir=dir0) + dir1 = self.mkdtemp(prefix="1" * dir1len, dir=dir0) self.assertExists(dir1) - (handle, filename) = tempfile.mkstemp( - dir=dir1, prefix="2" * filelen) - os.close(handle) + filename = self.write_file(os.path.join(dir1, '2' * filelen)) self.wipe_name_helper(filename) self.assertExists(dir0) self.assertExists(dir1) @@ -860,14 +816,12 @@ def test_wipe_name(self): os.rmdir(dir0) self.assertNotExists(dir0) + @unittest.skipUnless(os.getenv('ALLTESTS') is not None, + 'warning: skipping long test test_wipe_path() because environment variable ALLTESTS not set') def test_wipe_path(self): """Unit test for wipe_path()""" - if None == os.getenv('ALLTESTS'): - self.skipTest('warning: skipping long test test_wipe_path() because environment variable ALLTESTS not set') - - pathname = tempfile.gettempdir() - for ret in wipe_path(pathname): + for ret in wipe_path(self.tempdir): # no idle handler pass @@ -887,8 +841,7 @@ def test_vacuum_sqlite3(self): def number_generator(): for x in range(1, 10000): yield (x, ) - conn.executemany( - 'insert into numbers (number) values ( ? ) ', number_generator()) + conn.executemany('insert into numbers (number) values ( ? ) ', number_generator()) conn.commit() self.assertLess(empty_size, getsize(path)) conn.execute('delete from numbers') @@ -904,8 +857,8 @@ def number_generator(): def test_OpenFiles(self): """Unit test for class OpenFiles""" - (handle, filename) = tempfile.mkstemp( - prefix='bleachbit-test-open-files') + filename = os.path.join(self.tempdir, 'bleachbit-test-open-files') + f = open(filename, 'w') openfiles = OpenFiles() self.assertTrue(openfiles.is_open(filename), "Expected is_open(%s) to return True)\n" @@ -915,7 +868,6 @@ def test_OpenFiles(self): time.time() - openfiles.last_scan_time, openfiles.files)) - f = os.fdopen(handle) f.close() openfiles.scan() self.assertFalse(openfiles.is_open(filename)) @@ -925,14 +877,4 @@ def test_OpenFiles(self): self.assertFalse(openfiles.is_open(filename)) def test_open_files_lsof(self): - self.assertEqual(list(open_files_lsof(lambda: - 'n/bar/foo\nn/foo/bar\nnoise' - )), ['/bar/foo', '/foo/bar']) - - -def suite(): - return unittest.makeSuite(FileUtilitiesTestCase) - - -if __name__ == '__main__': - unittest.main() + self.assertEqual(list(open_files_lsof(lambda: 'n/bar/foo\nn/foo/bar\nnoise')), ['/bar/foo', '/foo/bar']) diff --git a/tests/TestGeneral.py b/tests/TestGeneral.py index 47ca86a83..1a2e3899d 100644 --- a/tests/TestGeneral.py +++ b/tests/TestGeneral.py @@ -28,11 +28,11 @@ from bleachbit import logger from tests import common +import shutil import unittest class GeneralTestCase(common.BleachbitTestCase): - """Test case for module General""" def test_boolstr_to_bool(self): @@ -66,18 +66,8 @@ def test_getrealuid(self): def test_makedirs(self): """Unit test for makedirs""" - def cleanup(dir): - if not os.path.lexists(dir): - return - os.rmdir(dir) - os.rmdir(os.path.dirname(dir)) - self.assertNotLExists(dir) - - if 'nt' == os.name: - dir = 'c:\\temp\\bleachbit-test-makedirs\\a' - if 'posix' == os.name: - dir = '/tmp/bleachbit-test-makedirs/a' - cleanup(dir) + + dir = os.path.join(self.tempdir, 'just', 'a', 'directory', 'adventure') # directory does not exist makedirs(dir) self.assertLExists(dir) @@ -85,54 +75,43 @@ def cleanup(dir): makedirs(dir) self.assertLExists(dir) # clean up - cleanup(dir) + shutil.rmtree(os.path.join(self.tempdir, 'just')) def test_run_external(self): """Unit test for run_external""" - if 'nt' == os.name: - args = ['cmd.exe', '/c', 'dir', '%windir%\system32', '/s', '/b'] - elif 'posix' == os.name: - args = ['find', '/usr/bin'] - (rc, stdout, stderr) = run_external(args) + args = {'nt': ['cmd.exe', '/c', 'dir', '%windir%\system32', '/s', '/b'], + 'posix': ['find', '/usr/bin']} + (rc, stdout, stderr) = run_external(args[os.name]) self.assertEqual(0, rc) self.assertEqual(0, len(stderr)) - args = ['cmddoesnotexist'] - self.assertRaises(OSError, run_external, args) + self.assertRaises(OSError, run_external, ['cmddoesnotexist']) - if 'nt' == os.name: - args = ['cmd.exe', '/c', 'dir', 'c:\doesnotexist'] - elif 'posix' == os.name: - args = ['ls', '/doesnotexist'] - (rc, stdout, stderr) = run_external(args) + args = {'nt': ['cmd.exe', '/c', 'dir', 'c:\doesnotexist'], + 'posix': ['ls', '/doesnotexist']} + (rc, stdout, stderr) = run_external(args[os.name]) self.assertNotEqual(0, rc) @unittest.skipUnless('posix' == os.name, 'skipping on platforms without sudo') def test_run_external_clean_env(self): """Unit test for clean_env parameter to run_external()""" - # clean_env should set language to C - (rc, stdout, stderr) = run_external( - ['bash', '-c', 'echo $LANG'], clean_env=True) - self.assertEqual(rc, 0) - self.assertEqual(stdout.rstrip('\n'), 'C') + def run(args, clean_env): + (rc, stdout, stderr) = run_external(args, clean_env=clean_env) + self.assertEqual(rc, 0) + return stdout.rstrip('\n') - (rc, stdout, stderr) = run_external( - ['bash', '-c', 'echo $LC_ALL'], clean_env=True) - self.assertEqual(rc, 0) - self.assertEqual(stdout.rstrip('\n'), 'C') + # clean_env should set language to C + run(['sh', '-c', '[ "x$LANG" = "xC" ]'], clean_env=True) + run(['sh', '-c', '[ "x$LC_ALL" = "xC" ]'], clean_env=True) # clean_env parameter should not alter the PATH, and the PATH # should not be empty - (rc, path_clean, stderr) = run_external( - ['bash', '-c', 'echo $PATH'], clean_env=True) - self.assertEqual(rc, 0) - self.assertEqual(os.getenv('PATH'), path_clean.rstrip('\n')) - self.assertTrue(len(path_clean) > 10) - - (rc, path_unclean, stderr) = run_external( - ['bash', '-c', 'echo $PATH'], clean_env=False) - self.assertEqual(rc, 0) + path_clean = run(['bash', '-c', 'echo $PATH'], clean_env=True) + self.assertEqual(os.getenv('PATH'), path_clean) + self.assertGreater(len(path_clean), 10) + + path_unclean = run(['bash', '-c', 'echo $PATH'], clean_env=False) self.assertEqual(path_clean, path_unclean) # With parent environment set to English and parameter clean_env=False, diff --git a/tests/TestMemory.py b/tests/TestMemory.py index 0951f3032..23f69fbfb 100644 --- a/tests/TestMemory.py +++ b/tests/TestMemory.py @@ -65,6 +65,7 @@ def test_count_linux_swap(self): self.assertTrue(0 <= n_swaps < 10) def test_physical_free_darwin(self): + # TODO: use mock self.assertEqual(physical_free_darwin(lambda: """Mach Virtual Memory Statistics: (page size of 4096 bytes) Pages free: 836891. @@ -105,8 +106,7 @@ def test_get_swap_size_linux(self): with open('/proc/swaps') as f: swapdev = f.read().split('\n')[1].split(' ')[0] if 0 == len(swapdev): - print('no active swap device detected') - return + self.skipTest('no active swap device detected') size = get_swap_size_linux(swapdev) self.assertIsInteger(size) self.assertGreater(size, 1024 ** 2) diff --git a/tests/TestOptions.py b/tests/TestOptions.py index 3349fc646..28159437a 100644 --- a/tests/TestOptions.py +++ b/tests/TestOptions.py @@ -31,7 +31,6 @@ class OptionsTestCase(common.BleachbitTestCase): - """Test case for class Options""" def test_Options(self): @@ -105,11 +104,7 @@ def test_purge(self): # By default ConfigParser stores keys (the filenames) as lowercase. # This needs special consideration when combined with purging. o1 = bleachbit.Options.Options() - import tempfile - dirname = tempfile.mkdtemp(prefix='bleachbit-test-options') - pathname = os.path.join(dirname, 'foo.xml') - open(pathname, 'w').close() # make an empty file - self.assertTrue(os.path.exists(pathname)) + pathname = self.write_file('foo.xml') myhash = '0ABCD' o1.set_hashpath(pathname, myhash) self.assertEqual(myhash, o1.get_hashpath(pathname)) @@ -136,9 +131,6 @@ def test_purge(self): # verify the path was purged self.assertRaises(NoOptionError, lambda: o3.get_hashpath(pathname)) - # clean up - os.rmdir(dirname) - def test_abbreviations(self): """Test non-standard, abbreviated booleans T and F""" diff --git a/tests/TestRecognizeCleanerML.py b/tests/TestRecognizeCleanerML.py index 927ec1643..dc05bf344 100644 --- a/tests/TestRecognizeCleanerML.py +++ b/tests/TestRecognizeCleanerML.py @@ -29,7 +29,6 @@ class RecognizeCleanerMLTestCase(common.BleachbitTestCase): - """Test case for RecognizeCleanerML""" def test_hash(self): diff --git a/tests/TestSpecial.py b/tests/TestSpecial.py index 59f5332ca..5f2da5977 100644 --- a/tests/TestSpecial.py +++ b/tests/TestSpecial.py @@ -33,7 +33,6 @@ import os.path import shutil import sqlite3 -import tempfile chrome_bookmarks = """ @@ -173,17 +172,18 @@ class SpecialAssertions: - def assertTableIsEmpty(self, path, table): - """Asserts SQLite table exists and is empty""" + def assertTablesAreEmpty(self, path, tables): + """Asserts SQLite tables exists and are empty""" if not os.path.lexists(path): raise AssertionError('Path does not exist: %s' % path) import sqlite3 conn = sqlite3.connect(path) cursor = conn.cursor() - cursor.execute('select 1 from %s limit 1' % table) - row = cursor.fetchone() - if row: - raise AssertionError('Table is not empty: %s ' % table) + for table in tables: + cursor.execute('select 1 from %s limit 1' % table) + row = cursor.fetchone() + if row: + raise AssertionError('Table is not empty: %s ' % table) class SpecialTestCase(common.BleachbitTestCase, SpecialAssertions): @@ -192,9 +192,8 @@ class SpecialTestCase(common.BleachbitTestCase, SpecialAssertions): def setUp(self): """Create test browser files.""" - self.dir_base = tempfile.mkdtemp(prefix='bleachbit-test-special') - self.dir_google_chrome_default = os.path.join( - self.dir_base, 'google-chrome/Default/') + self.dir_base = self.mkdtemp(prefix='bleachbit-test-special') + self.dir_google_chrome_default = os.path.join(self.dir_base, 'google-chrome/Default/') os.makedirs(self.dir_google_chrome_default) # google-chrome/Default/Bookmarks @@ -205,12 +204,10 @@ def setUp(self): f.close() # google-chrome/Default/Web Data - FileUtilities.execute_sqlite3( - os.path.join(self.dir_google_chrome_default, 'Web Data'), chrome_webdata) + FileUtilities.execute_sqlite3(os.path.join(self.dir_google_chrome_default, 'Web Data'), chrome_webdata) # google-chrome/Default/History - FileUtilities.execute_sqlite3( - os.path.join(self.dir_google_chrome_default, 'History'), chrome_history_sql) + FileUtilities.execute_sqlite3(os.path.join(self.dir_google_chrome_default, 'History'), chrome_history_sql) # google-chrome/Default/databases/Databases.db os.makedirs(os.path.join(self.dir_google_chrome_default, 'databases')) @@ -221,8 +218,7 @@ def tearDown(self): """Remove test browser files.""" shutil.rmtree(self.dir_base) - def sqlite_clean_helper( - self, sql, fn, clean_func, check_func=None, setup_func=None): + def sqlite_clean_helper(self, sql, fn, clean_func, check_func=None, setup_func=None): """Helper for cleaning special SQLite cleaning""" self.assertFalse(sql and fn, "sql and fn are mutually exclusive ways to create the data") @@ -234,9 +230,7 @@ def sqlite_clean_helper( # create sqlite file elif sql: # create test file - tmpdir = tempfile.mkdtemp(prefix='bleachbit-test-sqlite') - (fd, filename) = tempfile.mkstemp(dir=tmpdir) - os.close(fd) + filename = self.mkstemp(prefix='bleachbit-test-sqlite') # additional setup if setup_func: @@ -273,15 +267,11 @@ def test_delete_chrome_autofill(self): """Unit test for delete_chrome_autofill""" fn = "google-chrome/Default/Web Data" - def check_autofill(self, filename): - self.assertTableIsEmpty(filename, 'autofill') - self.assertTableIsEmpty(filename, 'autofill_profile_emails') - self.assertTableIsEmpty(filename, 'autofill_profile_names') - self.assertTableIsEmpty(filename, 'autofill_profile_phones') - self.assertTableIsEmpty(filename, 'autofill_profiles') - self.assertTableIsEmpty(filename, 'server_addresses') - self.sqlite_clean_helper( - None, fn, Special.delete_chrome_autofill, check_func=check_autofill) + def check_autofill(testcase, filename): + testcase.assertTablesAreEmpty(filename, ['autofill','autofill_profile_emails', 'autofill_profile_names', + 'autofill_profile_phones', 'autofill_profiles','server_addresses']) + + self.sqlite_clean_helper(None, fn, Special.delete_chrome_autofill, check_func=check_autofill) def test_delete_chrome_databases_db(self): """Unit test for delete_chrome_databases_db""" @@ -304,11 +294,8 @@ def check_chrome_history(self, filename): self.assertEqual(ids, [2]) # these tables should always be empty after cleaning - self.assertTableIsEmpty(filename, 'downloads') - self.assertTableIsEmpty(filename, 'keyword_search_terms') - self.assertTableIsEmpty(filename, 'segment_usage') - self.assertTableIsEmpty(filename, 'segments') - self.assertTableIsEmpty(filename, 'visits') + self.assertTablesAreEmpty(filename, ['downloads', 'keyword_search_terms', + 'segment_usage', 'segments', 'visits']) self.sqlite_clean_helper(None, "google-chrome/Default/History", Special.delete_chrome_history, check_chrome_history) @@ -325,9 +312,8 @@ def check_chrome_keywords(self, filename): ids.append(row[0]) self.assertEqual(ids, [2, 3, 4, 5, 6]) - self.sqlite_clean_helper( - None, "google-chrome/Default/Web Data", Special.delete_chrome_keywords, - check_chrome_keywords) + self.sqlite_clean_helper(None, "google-chrome/Default/Web Data", Special.delete_chrome_keywords, + check_chrome_keywords) def test_delete_mozilla_url_history(self): """Test for delete_mozilla_url_history""" @@ -345,8 +331,7 @@ def test_delete_mozilla_url_history(self): INSERT INTO "moz_inputhistory" VALUES(164860,'blog',0.0125459501500806); INSERT INTO "moz_places" VALUES(17251,'http://download.openoffice.org/2.3.1/index.html','download: OpenOffice.org 2.3.1 Downloads','gro.eciffonepo.daolnwod.',0,0,0,28,20,NULL); """ - self.sqlite_clean_helper( - sql, None, Special.delete_mozilla_url_history) + self.sqlite_clean_helper(sql, None, Special.delete_mozilla_url_history) def test_get_chrome_bookmark_ids(self): """Unit test for get_chrome_bookmark_ids()""" @@ -358,14 +343,11 @@ def test_get_chrome_bookmark_ids(self): def test_get_chrome_bookmark_urls(self): """Unit test for get_chrome_bookmark_urls()""" - (fd, path) = tempfile.mkstemp(prefix='bleachbit-test-chrome') - os.write(fd, chrome_bookmarks) - os.close(fd) + path= self.write_file('bleachbit-test-sqlite', chrome_bookmarks) self.assertExists(path) urls = Special.get_chrome_bookmark_urls(path) - self.assertEqual( - urls, [u'https://www.bleachbit.org/', u'http://www.slashdot.org/']) + self.assertEqual(set(urls), {u'https://www.bleachbit.org/', u'http://www.slashdot.org/'}) os.unlink(path) @@ -374,11 +356,9 @@ def test_get_sqlite_int(self): sql = """CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,value LONGVARCHAR); INSERT INTO "meta" VALUES('version','20');""" # create test file - (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-sqlite') - os.close(fd) + filename = self.mkstemp(prefix='bleachbit-test-sqlite') FileUtilities.execute_sqlite3(filename, sql) self.assertExists(filename) # run the test - ver = Special.get_sqlite_int( - filename, 'select value from meta where key="version"') + ver = Special.get_sqlite_int(filename, 'select value from meta where key="version"') self.assertEqual(ver, [20]) diff --git a/tests/TestUnix.py b/tests/TestUnix.py index 34a625ef6..12fc15dfd 100644 --- a/tests/TestUnix.py +++ b/tests/TestUnix.py @@ -30,7 +30,6 @@ from bleachbit.Unix import * import sys -import tempfile import unittest @@ -103,21 +102,21 @@ def test_journald_clean(self): def test_locale_regex(self): """Unit test for locale_to_language()""" - tests = [('en', 'en'), - ('en_US', 'en'), - ('en_US@piglatin', 'en'), - ('en_US.utf8', 'en'), - ('ko_KR.eucKR', 'ko'), - ('pl.ISO8859-2', 'pl'), - ('zh_TW.Big5', 'zh')] + tests = {'en': 'en', + 'en_US': 'en', + 'en_US@piglatin': 'en', + 'en_US.utf8': 'en', + 'ko_KR.eucKR': 'ko', + 'pl.ISO8859-2': 'pl', + 'zh_TW.Big5': 'zh'} import re regex = re.compile('^' + Locales.localepattern + '$') - for test in tests: - m = regex.match(test[0]) - self.assertIsNotNone(m, 'expected positive match for ' + test[0]) - self.assertEqual(m.group("locale"), test[1]) + for locale, tlc in tests.items(): + m = regex.match(locale) + self.assertIsNotNone(m, 'expected positive match for ' + locale) + self.assertEqual(m.group("locale"), tlc) for test in ['default', 'C', 'English', 'ru_RU.txt', 'ru.txt']: - self.assertIsNone(regex.match(test), 'expected negative match for '+test) + self.assertIsNone(regex.match(test), 'expected negative match for ' + test) def test_localization_paths(self): """Unit test for localization_paths()""" @@ -130,15 +129,13 @@ def test_localization_paths(self): self.assertLExists(path) # self.assert_(path.startswith('/usr/share/locale')) # /usr/share/locale/en_* should be ignored - self.assert_(path.find('/en_') == -1) + self.assertEqual(path.find('/en_'), -1) counter += 1 - self.assert_( - counter > 0, 'Zero files deleted by localization cleaner.' - 'This may be an error unless you really deleted all the files.') + self.assertGreater(counter, 0, 'Zero files deleted by localization cleaner.' + + 'This may be an error unless you really deleted all the files.') def test_fakelocalizationdirs(self): """Create a faked localization hierarchy and clean it afterwards""" - dirname = tempfile.mkdtemp(prefix='bleachbit-test-localizations') keepdirs = [ 'important_dontdelete', @@ -161,9 +158,9 @@ def test_fakelocalizationdirs(self): 'delete/dummyfiles/ru.txt', 'delete/locale/ru_RU.UTF8.txt'] for path in keepdirs + nukedirs: - os.mkdir(os.path.join(dirname, path)) + os.mkdir(os.path.join(self.tempdir, path)) for path in keepfiles + nukefiles: - open(os.path.join(dirname, path), 'w').close() + self.write_file(path) configxml = '' \ ' ' \ @@ -173,15 +170,14 @@ def test_fakelocalizationdirs(self): '' from xml.dom.minidom import parseString config = parseString(configxml) - locales = Locales() - locales._paths = LocaleCleanerPath(dirname) - locales.add_xml(config.firstChild, None) + self.locales._paths = LocaleCleanerPath(self.tempdir) + self.locales.add_xml(config.firstChild, None) # normpath because paths may contain ./ - deletelist = [os.path.normpath(path) for path in locales.localization_paths(['en', 'de'])] + deletelist = [os.path.normpath(path) for path in self.locales.localization_paths(['en', 'de'])] for path in keepdirs + keepfiles: - self.assert_(os.path.join(dirname, path) not in deletelist) + self.assertNotIn(os.path.join(self.tempdir, path), deletelist) for path in nukedirs + nukefiles: - self.assert_(os.path.join(dirname, path) in deletelist) + self.assertIn(os.path.join(self.tempdir, path), deletelist) def test_rotated_logs(self): """Unit test for rotated_logs()""" @@ -209,8 +205,7 @@ def test_start_with_computer(self): b = start_with_computer_check() self.assertIsInstance(b, bool) - if not os.path.exists(bleachbit.launcher_path) and \ - os.path.exists('bleachbit.desktop'): + if not os.path.exists(bleachbit.launcher_path) and os.path.exists('bleachbit.desktop'): # this happens when BleachBit is not installed bleachbit.launcher_path = 'bleachbit.desktop' @@ -227,11 +222,10 @@ def test_start_with_computer(self): def test_wine_to_linux_path(self): """Unit test for wine_to_linux_path()""" - tests = [("/home/foo/.wine", - "C:\\Program Files\\NSIS\\NSIS.exe", - "/home/foo/.wine/drive_c/Program Files/NSIS/NSIS.exe")] - for test in tests: - self.assertEqual(wine_to_linux_path(test[0], test[1]), test[2]) + wineprefix = "/home/foo/.wine" + windows_pathname = "C:\\Program Files\\NSIS\\NSIS.exe" + result = "/home/foo/.wine/drive_c/Program Files/NSIS/NSIS.exe" + self.assertEqual(wine_to_linux_path(wineprefix, windows_pathname), result) def test_yum_clean(self): """Unit test for yum_clean()""" diff --git a/tests/TestUpdate.py b/tests/TestUpdate.py index 77bb8d3a3..38d023769 100644 --- a/tests/TestUpdate.py +++ b/tests/TestUpdate.py @@ -36,31 +36,26 @@ class UpdateTestCase(common.BleachbitTestCase): - """Test case for module Update""" def test_UpdateCheck_fake(self): """Unit tests for class UpdateCheck using fake network""" - update_tests = [] wa = '' - update_tests.append( + update_tests = [ ('http://084http://085beta%s' % wa, - ((u'0.8.4', u'http://084'), (u'0.8.5beta', u'http://085beta')))) - update_tests.append( + ((u'0.8.4', u'http://084'), (u'0.8.5beta', u'http://085beta'))), ('http://084%s' % wa, - ((u'0.8.4', u'http://084'), ))) - update_tests.append( + ((u'0.8.4', u'http://084'), )), ('http://085beta%s' % wa, - ((u'0.8.5beta', u'http://085beta'), ))) - update_tests.append(('', ())) + ((u'0.8.5beta', u'http://085beta'), )), + ('', ())] # fake network original_open = bleachbit.Update.build_opener xml = "" - class fake_opener: - + class FakeOpener: def add_headers(self): pass @@ -70,15 +65,14 @@ def read(self): def open(self, url): return self - bleachbit.Update.build_opener = fake_opener - for update_test in update_tests: - xml = update_test[0] + # TODO: mock + bleachbit.Update.build_opener = FakeOpener + for xml, expected in update_tests: updates = check_updates(True, False, None, None) - self.assertEqual(updates, update_test[1]) + self.assertEqual(updates, expected) bleachbit.Update.build_opener = original_open - - def test_UpdateCheck_real(self): + def test_UpdateCheck_real_network(self): """Unit tests for class UpdateCheck using real network""" # real network @@ -87,8 +81,8 @@ def test_UpdateCheck_real(self): continue ver = update[0] url = update[1] - self.assert_(isinstance(ver, (type(None), unicode))) - self.assert_(isinstance(url, (type(None), unicode))) + self.assertIsInstance(ver, (type(None), unicode)) + self.assertIsInstance(url, (type(None), unicode)) def test_UpdateCheck_real(self): """Unit test for class UpdateCheck with bad network address""" @@ -107,7 +101,7 @@ def test_update_url(self): handle = opener.open(bleachbit.update_check_url) doc = handle.read() import xml - dom = xml.dom.minidom.parseString(doc) + xml.dom.minidom.parseString(doc) def test_update_winapp2(self): from bleachbit import personal_cleaners_dir @@ -118,30 +112,24 @@ def test_update_winapp2(self): url = 'http://katana.oooninja.com/bleachbit/winapp2/winapp2-2016-03-14.ini' - def append_text(s): - print(s) - - succeeded = {'r': False} # scope + def expect_failure(): + raise AssertionError('Call should have failed') def on_success(): succeeded['r'] = True + succeeded = {'r': False} # scope + # bad hash - succeeded['r'] = False - self.assertRaises(RuntimeError, update_winapp2, url, "notahash", - append_text, on_success) - self.assertFalse(succeeded['r']) + self.assertRaises(RuntimeError, update_winapp2, url, "notahash", print, expect_failure) # blank hash, download file - succeeded['r'] = False - update_winapp2(url, None, append_text, on_success) + update_winapp2(url, None, print, on_success) self.assertTrue(succeeded['r']) # blank hash, do not download again - update_winapp2(url, None, append_text, on_success) - succeeded['r'] = False - update_winapp2(url, None, append_text, on_success) - self.assertFalse(succeeded['r']) + update_winapp2(url, None, print, on_success) + update_winapp2(url, None, print, expect_failure) def test_user_agent(self): """Unit test for method user_agent()""" @@ -155,4 +143,3 @@ def test_environment(self): self.assertTrue(hasattr(httplib, 'HTTPS')) import socket self.assertTrue(hasattr(socket, 'ssl')) - import _ssl diff --git a/tests/TestWinapp.py b/tests/TestWinapp.py index f02884fd2..73656d97c 100644 --- a/tests/TestWinapp.py +++ b/tests/TestWinapp.py @@ -70,7 +70,6 @@ def get_winapp2(): @unittest.skipUnless('win32' == sys.platform, 'not running on windows') class WinappTestCase(common.BleachbitTestCase): - """Test cases for Winapp""" def run_all(self, cleaner, really_delete): diff --git a/tests/TestWorker.py b/tests/TestWorker.py index bc2bea718..11c2d241d 100644 --- a/tests/TestWorker.py +++ b/tests/TestWorker.py @@ -37,7 +37,6 @@ class AccessDeniedActionAction(ActionProvider): - action_key = 'access.denied' def __init__(self, action_element): @@ -55,7 +54,6 @@ def accessdenied(): class DoesNotExistAction(ActionProvider): - action_key = 'does.not.exist' def __init__(self, action_element): @@ -70,7 +68,6 @@ def get_commands(self): class FunctionGeneratorAction(ActionProvider): - action_key = 'function.generator' def __init__(self, action_element): @@ -87,7 +84,6 @@ def funcgenerator(): class FunctionPathAction(ActionProvider): - action_key = 'function.path' def __init__(self, action_element): @@ -105,7 +101,6 @@ def pathfunc(path): class InvalidEncodingAction(ActionProvider): - action_key = 'invalid.encoding' def __init__(self, action_element): @@ -123,7 +118,6 @@ def get_commands(self): class FunctionPlainAction(ActionProvider): - action_key = 'function.plain' def __init__(self, action_element): @@ -202,7 +196,7 @@ def action_test_helper(self, command, special_expected, errors_expected, bytes_expected_posix, count_deleted_posix, bytes_expected_nt, count_deleted_nt): ui = CLI.CliCallback() - (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-worker') + (fd, filename) = tempfile.mkstemp(prefix='bleachbit-test-worker', dir=self.tempdir) os.write(fd, '123') os.close(fd) self.assertExists(filename) @@ -238,8 +232,7 @@ def test_DoesNotExist(self): def test_FunctionGenerator(self): """Test Worker using Action.FunctionGenerator""" - self.action_test_helper( - 'function.generator', 1, 0, 4096 + 10, 1, 3 + 10, 1) + self.action_test_helper('function.generator', 1, 0, 4096 + 10, 1, 3 + 10, 1) def test_FunctionPath(self): """Test Worker using Action.FunctionPathAction""" @@ -281,22 +274,17 @@ def test_deep_scan(self): import bleachbit.DeepScan SaveDeepScan = bleachbit.DeepScan.DeepScan self.scanned = 0 - self_assertequal = self.assertEqual - self_assert = self.assert_ - - def increment_count(): - self.scanned += 1 + parent = self class MyDeepScan: - def add_search(self, dirname, regex): - self_assertequal(dirname, expanduser('~')) - self_assert( - regex in ('^Thumbs\\.db$', '^Thumbs\\.db:encryptable$')) + parent.assertEqual(dirname, expanduser('~')) + parent.assertIn(regex, ['^Thumbs\\.db$', '^Thumbs\\.db:encryptable$']) def scan(self): - increment_count() + parent.scanned+=1 yield True + bleachbit.DeepScan.DeepScan = MyDeepScan # test @@ -313,12 +301,8 @@ def scan(self): def test_multiple_options(self): """Test one cleaner with two options""" ui = CLI.CliCallback() - (fd, filename1) = tempfile.mkstemp(prefix='bleachbit-test-worker') - os.close(fd) - self.assertExists(filename1) - (fd, filename2) = tempfile.mkstemp(prefix='bleachbit-test-worker') - os.close(fd) - self.assertExists(filename2) + filename1 = self.mkstemp(prefix='bleachbit-test-worker') + filename2 = self.mkstemp(prefix='bleachbit-test-worker') astr1 = '' % filename1 astr2 = '' % filename2 @@ -329,8 +313,8 @@ def test_multiple_options(self): run = worker.run() while run.next(): pass - self.assertNotExists(filename1, "Path still exists '%s'" % filename1) - self.assertNotExists(filename2, "Path still exists '%s'" % filename2) + self.assertNotExists(filename1) + self.assertNotExists(filename2) self.assertEqual(worker.total_special, 0) self.assertEqual(worker.total_errors, 0) self.assertEqual(worker.total_deleted, 2) diff --git a/tests/common.py b/tests/common.py index 07cf81da0..dde8435cf 100644 --- a/tests/common.py +++ b/tests/common.py @@ -95,12 +95,23 @@ def write_file(self, filename, contents=''): """Create a temporary file, optionally writing contents to it""" if not os.path.isabs(filename): filename = os.path.join(self.tempdir, filename) - filename = extended_path(filename) - with open(filename, 'w') as f: + with open(extended_path(filename), 'wb') as f: f.write(contents) - assert (os.path.exists(filename)) + assert (os.path.exists(extended_path(filename))) return filename + def mkstemp(self, **kwargs): + if 'dir' not in kwargs: + kwargs['dir'] = self.tempdir + (fd, filename) = tempfile.mkstemp(**kwargs) + os.close(fd) + return filename + + def mkdtemp(self, **kwargs): + if 'dir' not in kwargs: + kwargs['dir'] = self.tempdir + return tempfile.mkdtemp(**kwargs) + def getTestPath(path): if 'nt' == os.name: @@ -120,7 +131,6 @@ def touch_file(filename): """Create an empty file""" with open(filename, "w") as f: pass - import os.path assert(os.path.exists(filename)) From d0be80a52683e3a1e61c2e8bdea6bd84e53270bd Mon Sep 17 00:00:00 2001 From: Tristan Stenner Date: Sun, 12 Feb 2017 08:01:23 +0100 Subject: [PATCH 4/4] Fix typo --- bleachbit/FileUtilities.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bleachbit/FileUtilities.py b/bleachbit/FileUtilities.py index ab617c8c5..0a504c829 100644 --- a/bleachbit/FileUtilities.py +++ b/bleachbit/FileUtilities.py @@ -660,7 +660,7 @@ def wipe_write(): with open(path, 'wb') as f: truncate_f(f) except IOError as e2: - if errno.EACCESS == e.errno: + if errno.EACCES == e2.errno: # Common when the file is locked # Errno 13 Permission Denied pass