Skip to content

Commit

Permalink
temp file handling part 3
Browse files Browse the repository at this point in the history
  • Loading branch information
tstenner committed Feb 10, 2017
1 parent aff94a5 commit 0aa45ad
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 200 deletions.
2 changes: 1 addition & 1 deletion tests/TestFileUtilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,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
Expand Down
67 changes: 23 additions & 44 deletions tests/TestGeneral.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -66,73 +66,52 @@ 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)
# directory already exists
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,
Expand Down
4 changes: 2 additions & 2 deletions tests/TestMemory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
10 changes: 1 addition & 9 deletions tests/TestOptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@


class OptionsTestCase(common.BleachbitTestCase):

"""Test case for class Options"""

def test_Options(self):
Expand Down Expand Up @@ -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))
Expand All @@ -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"""

Expand Down
1 change: 0 additions & 1 deletion tests/TestRecognizeCleanerML.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@


class RecognizeCleanerMLTestCase(common.BleachbitTestCase):

"""Test case for RecognizeCleanerML"""

def test_hash(self):
Expand Down
74 changes: 27 additions & 47 deletions tests/TestSpecial.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import os.path
import shutil
import sqlite3
import tempfile


chrome_bookmarks = """
Expand Down Expand Up @@ -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):
Expand All @@ -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
Expand All @@ -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'))
Expand All @@ -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")
Expand All @@ -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:
Expand Down Expand Up @@ -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"""
Expand All @@ -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)
Expand All @@ -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"""
Expand All @@ -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()"""
Expand All @@ -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)

Expand All @@ -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])
Loading

0 comments on commit 0aa45ad

Please sign in to comment.