0
|
1 |
#
|
|
2 |
# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
|
|
3 |
# All rights reserved.
|
|
4 |
# This component and the accompanying materials are made available
|
|
5 |
# under the terms of "Eclipse Public License v1.0"
|
|
6 |
# which accompanies this distribution, and is available
|
|
7 |
# at the URL "http://www.eclipse.org/legal/epl-v10.html".
|
|
8 |
#
|
|
9 |
# Initial Contributors:
|
|
10 |
# Nokia Corporation - initial contribution.
|
|
11 |
#
|
|
12 |
# Contributors:
|
|
13 |
#
|
|
14 |
# Description:
|
|
15 |
#
|
|
16 |
|
|
17 |
import sys, os, re, unittest, shutil, zipfile, filecmp, subprocess
|
|
18 |
|
|
19 |
class BaseTestCase(unittest.TestCase):
|
|
20 |
def set_modification_reference_time(self, path):
|
|
21 |
"""
|
|
22 |
Set modification reference time for a subsequent call to assert_modified()
|
|
23 |
or assert_not_modified().
|
|
24 |
@param path: The path to use, can be a file or a directory.
|
|
25 |
"""
|
|
26 |
if not hasattr(self, '_mod_refs'):
|
|
27 |
self._mod_refs = {}
|
|
28 |
|
|
29 |
if os.path.isdir(path):
|
|
30 |
self._mod_refs[path] = self._get_dir_modtime_dict(path)
|
|
31 |
elif os.path.isfile(path):
|
|
32 |
self._mod_refs[path] = os.stat(path).st_mtime
|
|
33 |
else:
|
|
34 |
self.fail("'%s' does not exist" % path)
|
|
35 |
|
|
36 |
def assert_modified(self, path):
|
|
37 |
"""
|
|
38 |
Assert that a given file or directory has been modified since the last
|
|
39 |
call to set_modification_reference_time() with the same path.
|
|
40 |
"""
|
3
|
41 |
# This fails on linux for some reason, probably because the modification
|
|
42 |
# timestamps are not accurate enough
|
|
43 |
if sys.platform == "win32":
|
|
44 |
self._assert_modification(path, assert_not_modified=False)
|
0
|
45 |
|
|
46 |
def assert_not_modified(self, path):
|
|
47 |
"""
|
|
48 |
Assert that a given file or directory has NOT been modified since the last
|
|
49 |
call to set_modification_reference_time() with the same path.
|
|
50 |
"""
|
|
51 |
self._assert_modification(path, assert_not_modified=True)
|
|
52 |
|
|
53 |
def remove_if_exists(self, path_or_paths):
|
|
54 |
"""Remove files or directories if they exist.
|
|
55 |
@param path_or_paths: The path to remove. Can also be a list of paths."""
|
|
56 |
if isinstance(path_or_paths, list):
|
|
57 |
paths = path_or_paths
|
|
58 |
else:
|
|
59 |
paths = [path_or_paths]
|
|
60 |
|
|
61 |
for path in paths:
|
|
62 |
if os.path.isdir(path):
|
|
63 |
shutil.rmtree(path)
|
|
64 |
elif os.path.isfile(path):
|
|
65 |
os.remove(path)
|
|
66 |
|
|
67 |
def create_dir(self, path):
|
|
68 |
"""Create the given directory if it doesn't exist."""
|
|
69 |
if not os.path.exists(path):
|
|
70 |
os.makedirs(path)
|
|
71 |
|
|
72 |
def recreate_dir(self, path):
|
|
73 |
"""Remove the given directory if it exists, and recreate it."""
|
|
74 |
if os.path.exists(path):
|
|
75 |
shutil.rmtree(path)
|
|
76 |
os.makedirs(path)
|
|
77 |
|
|
78 |
def create_dir_for_file_path(self, path):
|
|
79 |
"""Create the directories for the given file"""
|
|
80 |
dir = os.path.dirname(path)
|
|
81 |
if dir != '' and not os.path.exists(dir):
|
|
82 |
os.makedirs(dir)
|
|
83 |
|
|
84 |
def assert_exists_and_contains_something(self, path):
|
|
85 |
"""
|
|
86 |
Assert that the given path is a file or a directory and contains some data.
|
|
87 |
"""
|
|
88 |
if os.path.isdir(path):
|
|
89 |
if len(os.listdir(path)) == 0:
|
|
90 |
self.fail("Path '%s' exists (is a directory) but does not contain anything)" % path)
|
|
91 |
elif os.path.isfile(path):
|
|
92 |
if os.stat(path).st_size == 0:
|
|
93 |
self.fail("Path '%s' exists (is a file) but does not contain anything)" % path)
|
|
94 |
else:
|
|
95 |
self.fail("Path '%s' does not exist" % path)
|
|
96 |
|
|
97 |
def assert_dir_contents_equal(self, dir1, dir2, ignore=[], custom_comparison_functions={}, current_root_dir=''):
|
|
98 |
"""
|
|
99 |
Assert recursively that the contents of two directories are equal.
|
|
100 |
@param ignore: List containing names that should be ignored in the comparison (e.g. '.svn').
|
|
101 |
The entries can either be relative, e.g. 'file.txt', which would ignore 'file.txt'
|
|
102 |
in any directory, or they can be absolute, e.g. '/some/dir/file.txt', which would
|
|
103 |
ignore 'file.txt' only under 'some/dir/', relative to the comparison root.
|
|
104 |
@param custom_comparison_functions: Dictionary containing custom comparison functions
|
|
105 |
for files. Each entry in the dict should contain the following contents:
|
|
106 |
Key: The relative path of the file under the directories, e.g.
|
|
107 |
'some/path/file.txt'
|
|
108 |
Value: The function used to compare the file contents. The function should
|
|
109 |
take as parameters the raw binary data of the files, and should return
|
|
110 |
True if the contents are equal.
|
|
111 |
@param current_root_dir: For internal use.
|
|
112 |
"""
|
|
113 |
msg = "Directory contents are not equal ('%s' vs. '%s')\n" % (dir1, dir2)
|
|
114 |
|
|
115 |
ignore_list = []
|
|
116 |
for entry in ignore:
|
|
117 |
if entry.startswith('/'):
|
|
118 |
dirname, entryname = entry.rsplit('/', 1)
|
|
119 |
dirname = dirname.lstrip('/')
|
|
120 |
#print "dirname = %r" % dirname
|
|
121 |
#print "entryname = %r" % entryname
|
|
122 |
#print "current_root_dir = %r" % current_root_dir
|
|
123 |
if dirname == current_root_dir.rstrip('/'):
|
|
124 |
ignore_list.append(entryname)
|
|
125 |
else:
|
|
126 |
ignore_list.append(entry)
|
|
127 |
|
|
128 |
# Compare files with the custom comparison functions if necessary
|
|
129 |
for path, func in custom_comparison_functions.iteritems():
|
|
130 |
dirname = os.path.dirname(path).replace('\\', '/')
|
|
131 |
filename = os.path.basename(path)
|
|
132 |
|
|
133 |
filepath1 = os.path.join(dir1, filename)
|
|
134 |
filepath2 = os.path.join(dir2, filename)
|
|
135 |
|
|
136 |
# Compare if the file is in the current path and they both exist
|
|
137 |
if dirname == current_root_dir and \
|
|
138 |
os.path.isfile(filepath1) and \
|
|
139 |
os.path.isfile(filepath2):
|
|
140 |
comp_result = func(
|
|
141 |
self.read_data_from_file(filepath1),
|
|
142 |
self.read_data_from_file(filepath2))
|
|
143 |
if not comp_result:
|
|
144 |
# The files are not equal -> fail
|
|
145 |
self.fail(msg + "File '%s' differs" % filename)
|
|
146 |
else:
|
|
147 |
# The files are equal -> ignore from dircmp comparison
|
|
148 |
ignore_list.append(filename)
|
|
149 |
|
|
150 |
dcmp = filecmp.dircmp(dir1, dir2, ignore=ignore_list)
|
|
151 |
self.assertEquals(0, len(dcmp.left_only), msg + "Files only on left: %s" % dcmp.left_only)
|
|
152 |
self.assertEquals(0, len(dcmp.right_only), msg + "Files only on right: %s" % dcmp.right_only)
|
|
153 |
self.assertEquals(0, len(dcmp.diff_files), msg + "Differing files: %s" % dcmp.diff_files)
|
|
154 |
self.assertEquals(0, len(dcmp.funny_files), msg + "Funny files: %s" % dcmp.funny_files)
|
|
155 |
# Recurse into sub-directories
|
|
156 |
for d in dcmp.common_dirs:
|
|
157 |
if current_root_dir: cr = current_root_dir + '/' + d
|
|
158 |
else: cr = d
|
|
159 |
self.assert_dir_contents_equal(
|
|
160 |
os.path.join(dir1, d), os.path.join(dir2, d),
|
|
161 |
ignore, custom_comparison_functions, cr)
|
|
162 |
|
3
|
163 |
def assert_file_contents_equal(self, file1, file2, ignore_patterns=[], ignore_endline_style=False):
|
0
|
164 |
"""
|
|
165 |
Assert the the given two files exist and their contents are equal.
|
|
166 |
@param ignore_patterns: List of regular expressions for portions of the
|
|
167 |
file content to ignore in the comparison. The ignored parts are
|
|
168 |
deleted from the files before actual comparison.
|
3
|
169 |
@param ignore_endline_style: If True, the endline style (CRLF or LF) is
|
|
170 |
ignored during the comparison.
|
0
|
171 |
"""
|
|
172 |
self.assertTrue(os.path.exists(file1), "File '%s' does not exist!" % file1)
|
|
173 |
self.assertTrue(os.path.exists(file2), "File '%s' does not exist!" % file2)
|
|
174 |
|
|
175 |
data1 = self.read_data_from_file(file1)
|
|
176 |
data2 = self.read_data_from_file(file2)
|
|
177 |
|
|
178 |
def remove_ignored(data, pattern_list):
|
|
179 |
for i, pattern in enumerate(pattern_list):
|
|
180 |
data = re.sub(pattern, '{{{ignore_%d}}}' % i, data)
|
|
181 |
return data
|
|
182 |
data1 = remove_ignored(data1, ignore_patterns)
|
|
183 |
data2 = remove_ignored(data2, ignore_patterns)
|
|
184 |
|
3
|
185 |
if ignore_endline_style:
|
|
186 |
data1 = data1.replace('\r\n', '\n')
|
|
187 |
data2 = data2.replace('\r\n', '\n')
|
|
188 |
|
|
189 |
import difflib
|
|
190 |
difseq = difflib.ndiff(data1, data2)
|
|
191 |
# take only the first ten rows of the difference
|
|
192 |
difference = ''.join(list(difseq)[:10])
|
0
|
193 |
if data1 != data2:
|
|
194 |
if len(ignore_patterns) > 0:
|
3
|
195 |
self.write_data_to_file(file1 + '.diff', ''.join(difseq))
|
0
|
196 |
self.write_data_to_file(file1 + '.comparetemp', data1)
|
|
197 |
self.write_data_to_file(file2 + '.comparetemp', data2)
|
3
|
198 |
self.fail("Data of the files '%s' and '%s' are not equal\nSee *.comparetemp files for the actual data that was compared.\nDifference %s" % (file1, file2, difference))
|
0
|
199 |
else:
|
3
|
200 |
self.fail("Data of the files '%s' and '%s' are not equal\nDifference %s" % (file1, file2, difference))
|
0
|
201 |
|
3
|
202 |
def assert_file_content_equals(self, filepath, expected_data, ignore_endline_style=False):
|
0
|
203 |
"""
|
|
204 |
Assert that the content of the given file is equals to the given expected data.
|
3
|
205 |
@param ignore_endline_style: If True, the endline style (CRLF or LF) is
|
|
206 |
ignored during the comparison.
|
0
|
207 |
"""
|
|
208 |
self.assertTrue(os.path.exists(filepath), "'%s' does not exist!" % filepath)
|
|
209 |
self.assertTrue(os.path.isfile(filepath), "'%s' is not a file!" % filepath)
|
|
210 |
|
|
211 |
f = open(filepath, "rb")
|
|
212 |
try: filedata = f.read()
|
|
213 |
finally: f.close()
|
|
214 |
|
3
|
215 |
if ignore_endline_style:
|
|
216 |
filedata = filedata.replace('\r\n', '\n')
|
|
217 |
expected_data = expected_data.replace('\r\n', '\n')
|
|
218 |
|
0
|
219 |
if filedata != expected_data:
|
|
220 |
msg = ("The content of the file '%s' is not what was expected!\n" % filepath) +\
|
|
221 |
("Expected: %r\nActual: %r" % (expected_data, filedata))
|
|
222 |
self.fail(msg)
|
|
223 |
|
3
|
224 |
def assert_file_contains(self, filepath, data, encoding=None, regexes=[]):
|
0
|
225 |
"""
|
|
226 |
Assert that the given file contains the given text somewhere in its contents.
|
|
227 |
@param filepath: Path to the file to check.
|
|
228 |
@param data: The data the file is expected to contain.
|
|
229 |
@param encoding: Encoding used to decode the contents of the file.
|
|
230 |
If None, noe decoding is done.
|
3
|
231 |
@param regexes: A list of regular expressions that are used to search for
|
|
232 |
a match in the file data. If any of them doesn't find a match,
|
|
233 |
the assertion fails.
|
0
|
234 |
"""
|
|
235 |
self.assertTrue(os.path.exists(filepath), "'%s' does not exist!" % filepath)
|
|
236 |
self.assertTrue(os.path.isfile(filepath), "'%s' is not a file!" % filepath)
|
|
237 |
|
|
238 |
f = open(filepath, "rb")
|
|
239 |
try: filedata = f.read()
|
|
240 |
finally: f.close()
|
|
241 |
|
|
242 |
if encoding is not None:
|
|
243 |
filedata = filedata.decode(encoding)
|
|
244 |
|
|
245 |
if not isinstance(data, list):
|
|
246 |
data = [data]
|
|
247 |
|
|
248 |
for entry in data:
|
|
249 |
if not filedata.find(entry) != -1:
|
|
250 |
self.fail("The file '%s' does not contain the data '%s'" % (filepath, entry))
|
3
|
251 |
|
|
252 |
for regex in regexes:
|
|
253 |
if re.search(regex, filedata, re.MULTILINE) is None:
|
|
254 |
self.fail("The regex %r does not match anything in file '%s'" % (regex, filepath))
|
0
|
255 |
|
|
256 |
def assert_file_does_not_contain(self, filepath, data, encoding=None):
|
|
257 |
"""
|
|
258 |
Assert that the given file doesn't contain the given text somewhere in its contents.
|
|
259 |
@param filepath: Path to the file to check.
|
|
260 |
@param data: The data the file is expected to not contain.
|
|
261 |
@param encoding: Encoding used to decode the contents of the file.
|
|
262 |
If None, noe decoding is done.
|
|
263 |
"""
|
|
264 |
self.assertTrue(os.path.exists(filepath), "'%s' does not exist!" % filepath)
|
|
265 |
self.assertTrue(os.path.isfile(filepath), "'%s' is not a file!" % filepath)
|
|
266 |
|
|
267 |
f = open(filepath, "rb")
|
|
268 |
try: filedata = f.read()
|
|
269 |
finally: f.close()
|
|
270 |
|
|
271 |
if encoding is not None:
|
|
272 |
filedata = filedata.decode(encoding)
|
|
273 |
|
|
274 |
if not isinstance(data, list):
|
|
275 |
data = [data]
|
|
276 |
|
|
277 |
for entry in data:
|
|
278 |
if not filedata.find(entry) == -1:
|
|
279 |
self.fail("The file '%s' contains the data '%s'" % (filepath, entry))
|
|
280 |
|
|
281 |
def read_data_from_file(self, path):
|
|
282 |
"""Read the raw binary data from the given file."""
|
|
283 |
f = open(path, "rb")
|
|
284 |
try: return f.read()
|
|
285 |
finally: f.close()
|
|
286 |
|
|
287 |
def read_data_from_zip_file(self, path, entry):
|
|
288 |
"""Read the raw binary data from the given ZIP file with the given ZIP entry."""
|
|
289 |
zf = zipfile.ZipFile(path, "r")
|
|
290 |
try: return zf.read(entry)
|
|
291 |
finally: zf.close()
|
|
292 |
|
|
293 |
def write_data_to_file(self, path, data):
|
|
294 |
"""Write raw binary data into the given file."""
|
|
295 |
f = open(path, "wb")
|
|
296 |
try: f.write(data)
|
|
297 |
finally: f.close()
|
|
298 |
|
|
299 |
def run_command(self, command, expected_return_code=0):
|
|
300 |
"""
|
|
301 |
Run the given command, asserting that it returns the expected value.
|
|
302 |
@param command: The command to run.
|
|
303 |
@param expected_return_code: The expected return code. Can be None if the return
|
|
304 |
code doesn't matter.
|
|
305 |
@return: The command output.
|
|
306 |
"""
|
|
307 |
# Using shell=True on windows uses
|
|
308 |
# cmd.exe /c <command>
|
|
309 |
# to run the actual command, and if cmd.exe sees that the first
|
|
310 |
# character in the command is ", it strips that and a trailing ".
|
|
311 |
# For this reason we add quotes to the command to prevent e.g.
|
|
312 |
# "C:\some\command.cmd" --some-arg "xyz"
|
|
313 |
# from becoming
|
|
314 |
# C:\some\command.cmd" --some-arg "xyz
|
|
315 |
if sys.platform == 'win32' and command.startswith('"'):
|
|
316 |
command = '"' + command + '"'
|
|
317 |
|
|
318 |
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
|
|
319 |
out, err = p.communicate()
|
|
320 |
if expected_return_code is not None:
|
|
321 |
self.assertTrue(p.returncode == expected_return_code,
|
|
322 |
"Could not execute command (%s)\n"\
|
|
323 |
"Return code is not what was expected (expected %d, got %d)\n"\
|
|
324 |
"Output: \n%s" % (command, expected_return_code, p.returncode, out))
|
|
325 |
return out
|
|
326 |
|
3
|
327 |
def assert_problem_lists_equal(self, actual, expected, outdir):
|
|
328 |
"""
|
|
329 |
Assert that two lists of api.Problem objects are equal.
|
|
330 |
@param actual: The list of actual problems.
|
|
331 |
@param expected: The list of expected problems.
|
|
332 |
@param outdir: The directory where output is written if the assertion
|
|
333 |
fails.
|
|
334 |
"""
|
|
335 |
act = sorted([repr(p) for p in actual])
|
|
336 |
exp = sorted([repr(p) for p in expected])
|
|
337 |
if act != exp:
|
|
338 |
if not os.path.exists(outdir):
|
|
339 |
os.makedirs(outdir)
|
|
340 |
self.write_data_to_file(os.path.join(outdir, 'actual.txt'), os.linesep.join(act))
|
|
341 |
self.write_data_to_file(os.path.join(outdir, 'expected.txt'), os.linesep.join(exp))
|
|
342 |
self.fail("Problem lists not equal, see the files in '%s'" % outdir)
|
|
343 |
|
|
344 |
def assert_problem_list_equals_expected(self, actual, expected_file, outdir):
|
|
345 |
"""
|
|
346 |
Assert that the given list of api.Problem objects is equal to the
|
|
347 |
list specified in the given file.
|
|
348 |
@param actual: The list of actual problems.
|
|
349 |
@param expected_file: Path to the file containing the list of
|
|
350 |
expected problems. The file should contain the repr() output
|
|
351 |
for an api.Problem object on each line.
|
|
352 |
@param outdir: The directory where output is written if the assertion
|
|
353 |
fails.
|
|
354 |
"""
|
|
355 |
act = sorted([repr(p) for p in actual])
|
|
356 |
|
|
357 |
if not os.path.isfile(expected_file):
|
|
358 |
raise RuntimeError("Expected problem file '%s' does not exist or is not a file!" % expected_file)
|
|
359 |
f = open(expected_file, 'r')
|
|
360 |
try: exp = sorted([line.rstrip('\r\n') for line in f])
|
|
361 |
finally: f.close()
|
|
362 |
|
|
363 |
# Delete lines starting with #
|
|
364 |
for i in reversed(range(len(exp))):
|
|
365 |
if exp[i].startswith('#'):
|
|
366 |
del exp[i]
|
|
367 |
|
|
368 |
if act != exp:
|
|
369 |
if not os.path.exists(outdir):
|
|
370 |
os.makedirs(outdir)
|
|
371 |
self.write_data_to_file(os.path.join(outdir, 'actual.txt'), os.linesep.join(act))
|
|
372 |
self.write_data_to_file(os.path.join(outdir, 'expected.txt'), os.linesep.join(exp))
|
|
373 |
self.fail("Problem list is not what was expected, see the files in '%s'" % outdir)
|
|
374 |
|
|
375 |
|
0
|
376 |
# =====================================================
|
|
377 |
# Private helper methods
|
|
378 |
# =====================================================
|
|
379 |
|
|
380 |
def _get_dir_modtime_dict(self, dir_path):
|
|
381 |
"""
|
|
382 |
Return a dictionary of all files and directories and their last
|
|
383 |
modification times in a given directory.
|
|
384 |
"""
|
|
385 |
refdict = {}
|
|
386 |
for root, dirs, files in os.walk(dir_path):
|
|
387 |
for f in files:
|
|
388 |
path = os.path.join(root, f)
|
|
389 |
refdict[path] = os.stat(path).st_mtime
|
|
390 |
for d in dirs:
|
|
391 |
path = os.path.join(root, d)
|
|
392 |
refdict[path] = os.stat(path).st_mtime
|
|
393 |
return refdict
|
|
394 |
|
|
395 |
def _assert_modification(self, path, assert_not_modified=True):
|
|
396 |
if os.path.isdir(path):
|
|
397 |
if assert_not_modified:
|
|
398 |
self._assert_dir_not_modified(path)
|
|
399 |
else:
|
|
400 |
self.assert_dir_modified(path)
|
|
401 |
elif os.path.isfile(path):
|
|
402 |
if assert_not_modified:
|
|
403 |
self._assert_file_not_modified(path)
|
|
404 |
else:
|
|
405 |
self._assert_file_modified(path)
|
|
406 |
else:
|
|
407 |
self.fail("'%s' does not exist" % path)
|
|
408 |
|
|
409 |
def _assert_dir_not_modified(self, dir_path):
|
|
410 |
refdict = self._mod_refs[dir_path]
|
|
411 |
curdict = self._get_dir_modtime_dict(dir_path)
|
|
412 |
|
|
413 |
# If the keys of the dicts are not the same, the contents of the
|
|
414 |
# dir have been modified (added or removed files/subdirs)
|
|
415 |
self.assertEquals(curdict.keys(), refdict.keys())
|
|
416 |
|
|
417 |
# Compare manually so that assertion error output shows the specific file/dir
|
|
418 |
for path in curdict.iterkeys():
|
|
419 |
self.assertEquals(curdict[path], refdict[path], "File or dir '%s' modified" % path)
|
|
420 |
|
|
421 |
def assert_dir_modified(self, dir_path):
|
|
422 |
refdict = self._mod_refs[dir_path]
|
|
423 |
curdict = self._get_dir_modtime_dict(dir_path)
|
|
424 |
|
|
425 |
self.assertNotEqual(curdict, refdict, "Directory '%s' has not been modified when it was expected to be" % dir_path)
|
|
426 |
|
|
427 |
def _assert_file_not_modified(self, file_path):
|
|
428 |
time1 = self._mod_refs[file_path]
|
|
429 |
time2 = os.stat(file_path).st_mtime
|
|
430 |
self.assertEquals(time1, time2,
|
|
431 |
("File '%s' was modified when it should not have been "+\
|
|
432 |
"(mod time %f vs. %f)") % (file_path, time1, time2))
|
|
433 |
|
|
434 |
def _assert_file_modified(self, file_path):
|
|
435 |
time1 = self._mod_refs[file_path]
|
|
436 |
time2 = os.stat(file_path).st_mtime
|
|
437 |
self.assertNotEqual(time1, time2,
|
|
438 |
("File '%s' was modified not when it should have been "+\
|
|
439 |
"(mod time %f vs. %f)") % (file_path, time1, time2))
|