Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve unit tests #191

Merged
merged 4 commits into from
Feb 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bleachbit/FileUtilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
65 changes: 26 additions & 39 deletions tests/TestAction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""

Expand All @@ -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)
Expand All @@ -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"""
Expand All @@ -148,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
Expand All @@ -168,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'<action command="delete" search="file" path="%s" />' % pathname
self._test_action_str(action_str)
self.assertNotExists(pathname)
os.rmdir(dirname)

def test_ini(self):
"""Unit test for class Ini"""
Expand Down Expand Up @@ -209,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'}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a creative use of a dictionary. Nice.

tests = [u'<action command="process" cmd="%s" />',
u'<action command="process" wait="false" cmd="%s" />',
u'<action command="process" wait="f" cmd="%s" />',
Expand All @@ -221,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"""
Expand All @@ -233,49 +223,48 @@ def test_regex(self):
# should match three files using no regexes
action_str = u'<action command="delete" search="glob" path="/tmp/foo*" />'
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'<action command="delete" search="glob" path="/tmp/foo*" regex="^foo2$"/>'
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'<action command="delete" search="glob" path="/tmp/foo*" regex="^FOO2$"/>'
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'<action command="delete" search="glob" path="/tmp/foo*" nregex="^(foo1|bar1)$"/>'
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'<action command="delete" search="glob" path="/tmp/foo*" regex="^f" nregex="1$"/>'
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'<action command="delete" search="glob" path="/tmp/foo*" regex="^bar$"/>'
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'<action command="delete" search="glob" path="/tmp/foo*" nregex="."/>'
results = _action_str_to_results(action_str)
self.assert_(0 == len(results))
self.assertEqual(len(results), 0)

# should give an error
action_str = u'<action command="delete" search="invalid" path="/tmp/foo*" regex="^bar$"/>'
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
Expand All @@ -291,18 +280,18 @@ def test_wholeregex(self):
# should match three files using no regexes
action_str = u'<action command="delete" search="glob" path="/tmp/foo*" />'
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'<action command="delete" search="glob" path="/tmp/foo*" wholeregex="^/tmp/foo.*$"/>'
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'<action command="delete" search="glob" path="/tmp/foo*" nwholeregex="^/tmp/foo.*$"/>'
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
Expand All @@ -311,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
Expand Down Expand Up @@ -343,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')
Expand All @@ -362,19 +351,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'<action command="delete" search="walk.files" path="%s" />' % path
paths = {'posix': '/var', 'nt': '$WINDIR\\system32'}

action_str = u'<action command="delete" search="walk.files" path="%s" />' % 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():
Expand Down
55 changes: 18 additions & 37 deletions tests/TestCLI.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@
import unittest



class CLITestCase(unittest.TestCase):

class CLITestCase(common.BleachbitTestCase):
"""Test case for module CLI"""

def setUp(self):
Expand Down Expand Up @@ -77,40 +75,32 @@ 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):
"""Unit test for encoding"""

(fd, filename) = tempfile.mkstemp(
prefix='bleachbit-test-cli-encoding-\xe4\xf6\xfc~', dir='/tmp')
os.close(fd)
self.assert_(os.path.exists(filename))
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)

os.remove(filename)
self.assert_(not os.path.exists(filename))
self.assertNotExists(filename)

def test_invalid_locale(self):
"""Unit test for invalid locales"""
lang = os.environ['LANG']
os.environ['LANG'] = 'blahfoo'
# tests are run from the parent directory
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
Expand All @@ -132,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)
Expand All @@ -142,39 +131,31 @@ 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"""
suffixes = ['', '.', '.txt']
dirs = ['.', None]
for dir_ in dirs:
for suffix in suffixes:
(fd, filename) = tempfile.mkstemp(
prefix='bleachbit-test-cli-shred', suffix=suffix, dir=dir_)
(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))


def suite():
return unittest.makeSuite(CLITestCase)

output = run_external(args)
self.assertNotExists(filename)

if __name__ == '__main__':
unittest.main()
Loading