blob: 2ea35468e59dc1162df9f9837a4a8687b4a9e339 [file] [log] [blame]
maruel@chromium.org561d4b22013-09-26 21:08:08 +00001#!/usr/bin/env python
2# coding=utf-8
maruelea586f32016-04-05 11:11:33 -07003# Copyright 2013 The LUCI Authors. All rights reserved.
4# Use of this source code is governed by the Apache v2.0 license that can be
5# found in the LICENSE file.
maruel@chromium.org561d4b22013-09-26 21:08:08 +00006
maruel9cdd7612015-12-02 13:40:52 -08007import getpass
maruel@chromium.org561d4b22013-09-26 21:08:08 +00008import logging
9import os
10import tempfile
11import unittest
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040012import StringIO
13import subprocess
maruel@chromium.org561d4b22013-09-26 21:08:08 +000014import sys
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040015import time
maruel@chromium.org561d4b22013-09-26 21:08:08 +000016
17BASE_DIR = unicode(os.path.dirname(os.path.abspath(__file__)))
18ROOT_DIR = os.path.dirname(BASE_DIR)
19sys.path.insert(0, ROOT_DIR)
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050020sys.path.insert(0, os.path.join(ROOT_DIR, 'third_party'))
maruel@chromium.org561d4b22013-09-26 21:08:08 +000021
22FILE_PATH = unicode(os.path.abspath(__file__))
23
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050024from depot_tools import auto_stub
maruel4b14f042015-10-06 12:08:08 -070025from depot_tools import fix_encoding
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040026import test_utils
maruel@chromium.org561d4b22013-09-26 21:08:08 +000027from utils import file_path
maruel4e732992015-10-16 10:17:21 -070028from utils import fs
maruel@chromium.org561d4b22013-09-26 21:08:08 +000029
30
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040031def write_content(filepath, content):
maruel4e732992015-10-16 10:17:21 -070032 with fs.open(filepath, 'wb') as f:
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040033 f.write(content)
34
35
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050036class FilePathTest(auto_stub.TestCase):
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040037 def setUp(self):
38 super(FilePathTest, self).setUp()
39 self._tempdir = None
40
41 def tearDown(self):
maruel4b14f042015-10-06 12:08:08 -070042 try:
43 if self._tempdir:
maruel4e732992015-10-16 10:17:21 -070044 for dirpath, dirnames, filenames in fs.walk(
maruel4b14f042015-10-06 12:08:08 -070045 self._tempdir, topdown=True):
46 for filename in filenames:
47 file_path.set_read_only(os.path.join(dirpath, filename), False)
48 for dirname in dirnames:
49 file_path.set_read_only(os.path.join(dirpath, dirname), False)
50 file_path.rmtree(self._tempdir)
51 finally:
52 super(FilePathTest, self).tearDown()
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040053
54 @property
55 def tempdir(self):
56 if not self._tempdir:
Marc-Antoine Ruel3c979cb2015-03-11 13:43:28 -040057 self._tempdir = tempfile.mkdtemp(prefix=u'run_isolated_test')
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040058 return self._tempdir
59
60 def assertFileMode(self, filepath, mode, umask=None):
61 umask = test_utils.umask() if umask is None else umask
maruel4e732992015-10-16 10:17:21 -070062 actual = fs.stat(filepath).st_mode
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040063 expected = mode & ~umask
64 self.assertEqual(
65 expected,
66 actual,
67 (filepath, oct(expected), oct(actual), oct(umask)))
68
69 def assertMaskedFileMode(self, filepath, mode):
70 """It's usually when the file was first marked read only."""
71 self.assertFileMode(filepath, mode, 0 if sys.platform == 'win32' else 077)
72
maruel@chromium.org561d4b22013-09-26 21:08:08 +000073 def test_native_case_end_with_os_path_sep(self):
74 # Make sure the trailing os.path.sep is kept.
75 path = file_path.get_native_path_case(ROOT_DIR) + os.path.sep
76 self.assertEqual(file_path.get_native_path_case(path), path)
77
78 def test_native_case_end_with_dot_os_path_sep(self):
79 path = file_path.get_native_path_case(ROOT_DIR + os.path.sep)
80 self.assertEqual(
81 file_path.get_native_path_case(path + '.' + os.path.sep),
82 path)
83
84 def test_native_case_non_existing(self):
85 # Make sure it doesn't throw on non-existing files.
86 non_existing = 'trace_input_test_this_file_should_not_exist'
87 path = os.path.expanduser('~/' + non_existing)
88 self.assertFalse(os.path.exists(path))
89 path = file_path.get_native_path_case(ROOT_DIR) + os.path.sep
90 self.assertEqual(file_path.get_native_path_case(path), path)
91
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040092 def test_delete_wd_rf(self):
93 # Confirms that a RO file in a RW directory can be deleted on non-Windows.
94 dir_foo = os.path.join(self.tempdir, 'foo')
95 file_bar = os.path.join(dir_foo, 'bar')
maruel4e732992015-10-16 10:17:21 -070096 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040097 write_content(file_bar, 'bar')
98 file_path.set_read_only(dir_foo, False)
99 file_path.set_read_only(file_bar, True)
100 self.assertFileMode(dir_foo, 040777)
101 self.assertMaskedFileMode(file_bar, 0100444)
102 if sys.platform == 'win32':
103 # On Windows, a read-only file can't be deleted.
104 with self.assertRaises(OSError):
maruel4e732992015-10-16 10:17:21 -0700105 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400106 else:
maruel4e732992015-10-16 10:17:21 -0700107 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400108
109 def test_delete_rd_wf(self):
110 # Confirms that a Rw file in a RO directory can be deleted on Windows only.
111 dir_foo = os.path.join(self.tempdir, 'foo')
112 file_bar = os.path.join(dir_foo, 'bar')
maruel4e732992015-10-16 10:17:21 -0700113 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400114 write_content(file_bar, 'bar')
115 file_path.set_read_only(dir_foo, True)
116 file_path.set_read_only(file_bar, False)
117 self.assertMaskedFileMode(dir_foo, 040555)
118 self.assertFileMode(file_bar, 0100666)
119 if sys.platform == 'win32':
120 # A read-only directory has a convoluted meaning on Windows, it means that
121 # the directory is "personalized". This is used as a signal by Windows
122 # Explorer to tell it to look into the directory for desktop.ini.
123 # See http://support.microsoft.com/kb/326549 for more details.
124 # As such, it is important to not try to set the read-only bit on
125 # directories on Windows since it has no effect other than trigger
126 # Windows Explorer to look for desktop.ini, which is unnecessary.
maruel4e732992015-10-16 10:17:21 -0700127 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400128 else:
129 with self.assertRaises(OSError):
maruel4e732992015-10-16 10:17:21 -0700130 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400131
132 def test_delete_rd_rf(self):
133 # Confirms that a RO file in a RO directory can't be deleted.
134 dir_foo = os.path.join(self.tempdir, 'foo')
135 file_bar = os.path.join(dir_foo, 'bar')
maruel4e732992015-10-16 10:17:21 -0700136 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400137 write_content(file_bar, 'bar')
138 file_path.set_read_only(dir_foo, True)
139 file_path.set_read_only(file_bar, True)
140 self.assertMaskedFileMode(dir_foo, 040555)
141 self.assertMaskedFileMode(file_bar, 0100444)
142 with self.assertRaises(OSError):
143 # It fails for different reason depending on the OS. See the test cases
144 # above.
maruel4e732992015-10-16 10:17:21 -0700145 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400146
147 def test_hard_link_mode(self):
148 # Creates a hard link, see if the file mode changed on the node or the
149 # directory entry.
150 dir_foo = os.path.join(self.tempdir, 'foo')
151 file_bar = os.path.join(dir_foo, 'bar')
152 file_link = os.path.join(dir_foo, 'link')
maruel4e732992015-10-16 10:17:21 -0700153 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400154 write_content(file_bar, 'bar')
155 file_path.hardlink(file_bar, file_link)
156 self.assertFileMode(file_bar, 0100666)
157 self.assertFileMode(file_link, 0100666)
158 file_path.set_read_only(file_bar, True)
159 self.assertMaskedFileMode(file_bar, 0100444)
160 self.assertMaskedFileMode(file_link, 0100444)
161 # This is bad news for Windows; on Windows, the file must be writeable to be
162 # deleted, but the file node is modified. This means that every hard links
163 # must be reset to be read-only after deleting one of the hard link
164 # directory entry.
165
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500166 def test_rmtree_unicode(self):
167 subdir = os.path.join(self.tempdir, 'hi')
maruel4e732992015-10-16 10:17:21 -0700168 fs.mkdir(subdir)
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500169 filepath = os.path.join(
170 subdir, u'\u0627\u0644\u0635\u064A\u0646\u064A\u0629')
maruel4e732992015-10-16 10:17:21 -0700171 with fs.open(filepath, 'wb') as f:
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500172 f.write('hi')
173 # In particular, it fails when the input argument is a str.
174 file_path.rmtree(str(subdir))
175
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400176 if sys.platform == 'darwin':
177 def test_native_case_symlink_wrong_case(self):
178 base_dir = file_path.get_native_path_case(BASE_DIR)
179 trace_inputs_dir = os.path.join(base_dir, 'trace_inputs')
180 actual = file_path.get_native_path_case(trace_inputs_dir)
181 self.assertEqual(trace_inputs_dir, actual)
182
183 # Make sure the symlink is not resolved.
184 data = os.path.join(trace_inputs_dir, 'Files2')
185 actual = file_path.get_native_path_case(data)
186 self.assertEqual(
187 os.path.join(trace_inputs_dir, 'files2'), actual)
188
189 data = os.path.join(trace_inputs_dir, 'Files2', '')
190 actual = file_path.get_native_path_case(data)
191 self.assertEqual(
192 os.path.join(trace_inputs_dir, 'files2', ''), actual)
193
194 data = os.path.join(trace_inputs_dir, 'Files2', 'Child1.py')
195 actual = file_path.get_native_path_case(data)
196 # TODO(maruel): Should be child1.py.
197 self.assertEqual(
198 os.path.join(trace_inputs_dir, 'files2', 'Child1.py'), actual)
199
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000200 if sys.platform in ('darwin', 'win32'):
201 def test_native_case_not_sensitive(self):
202 # The home directory is almost guaranteed to have mixed upper/lower case
203 # letters on both Windows and OSX.
204 # This test also ensures that the output is independent on the input
205 # string case.
206 path = os.path.expanduser(u'~')
207 self.assertTrue(os.path.isdir(path))
208 path = path.replace('/', os.path.sep)
209 if sys.platform == 'win32':
210 # Make sure the drive letter is upper case for consistency.
211 path = path[0].upper() + path[1:]
212 # This test assumes the variable is in the native path case on disk, this
213 # should be the case. Verify this assumption:
214 self.assertEqual(path, file_path.get_native_path_case(path))
215 self.assertEqual(
216 file_path.get_native_path_case(path.lower()),
217 file_path.get_native_path_case(path.upper()))
218
219 def test_native_case_not_sensitive_non_existent(self):
220 # This test also ensures that the output is independent on the input
221 # string case.
222 non_existing = os.path.join(
223 'trace_input_test_this_dir_should_not_exist', 'really not', '')
224 path = os.path.expanduser(os.path.join(u'~', non_existing))
225 path = path.replace('/', os.path.sep)
maruel4e732992015-10-16 10:17:21 -0700226 self.assertFalse(fs.exists(path))
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000227 lower = file_path.get_native_path_case(path.lower())
228 upper = file_path.get_native_path_case(path.upper())
229 # Make sure non-existing element is not modified:
230 self.assertTrue(lower.endswith(non_existing.lower()))
231 self.assertTrue(upper.endswith(non_existing.upper()))
232 self.assertEqual(lower[:-len(non_existing)], upper[:-len(non_existing)])
233
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400234 if sys.platform == 'win32':
235 def test_native_case_alternate_datastream(self):
236 # Create the file manually, since tempfile doesn't support ADS.
Marc-Antoine Ruel3c979cb2015-03-11 13:43:28 -0400237 tempdir = unicode(tempfile.mkdtemp(prefix=u'trace_inputs'))
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400238 try:
239 tempdir = file_path.get_native_path_case(tempdir)
240 basename = 'foo.txt'
241 filename = basename + ':Zone.Identifier'
242 filepath = os.path.join(tempdir, filename)
243 open(filepath, 'w').close()
244 self.assertEqual(filepath, file_path.get_native_path_case(filepath))
245 data_suffix = ':$DATA'
246 self.assertEqual(
247 filepath + data_suffix,
248 file_path.get_native_path_case(filepath + data_suffix))
249
250 open(filepath + '$DATA', 'w').close()
251 self.assertEqual(
252 filepath + data_suffix,
253 file_path.get_native_path_case(filepath + data_suffix))
254 # Ensure the ADS weren't created as separate file. You love NTFS, don't
255 # you?
maruel4e732992015-10-16 10:17:21 -0700256 self.assertEqual([basename], fs.listdir(tempdir))
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400257 finally:
maruel4b14f042015-10-06 12:08:08 -0700258 file_path.rmtree(tempdir)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400259
260 def test_rmtree_win(self):
261 # Mock our sleep for faster test case execution.
262 sleeps = []
263 self.mock(time, 'sleep', sleeps.append)
264 self.mock(sys, 'stderr', StringIO.StringIO())
265
266 # Open a child process, so the file is locked.
267 subdir = os.path.join(self.tempdir, 'to_be_deleted')
maruel4e732992015-10-16 10:17:21 -0700268 fs.mkdir(subdir)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400269 script = 'import time; open(\'a\', \'w\'); time.sleep(60)'
270 proc = subprocess.Popen([sys.executable, '-c', script], cwd=subdir)
271 try:
272 # Wait until the file exist.
maruel4e732992015-10-16 10:17:21 -0700273 while not fs.isfile(os.path.join(subdir, 'a')):
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400274 self.assertEqual(None, proc.poll())
275 file_path.rmtree(subdir)
276 self.assertEqual([2, 4, 2], sleeps)
277 # sys.stderr.getvalue() would return a fair amount of output but it is
278 # not completely deterministic so we're not testing it here.
279 finally:
280 proc.wait()
281
Marc-Antoine Ruela275b292014-11-25 15:17:21 -0500282 def test_filter_processes_dir_win(self):
283 python_dir = os.path.dirname(sys.executable)
284 processes = file_path.filter_processes_dir_win(
285 file_path.enum_processes_win(), python_dir)
286 self.assertTrue(processes)
287 proc_names = [proc.ExecutablePath for proc in processes]
288 # Try to find at least one python process.
289 self.assertTrue(
290 any(proc == sys.executable for proc in proc_names), proc_names)
291
292 def test_filter_processes_tree_win(self):
293 # Create a grand-child.
294 script = (
295 'import subprocess,sys;'
296 'proc = subprocess.Popen('
297 '[sys.executable, \'-u\', \'-c\', \'import time; print(1); '
298 'time.sleep(60)\'], stdout=subprocess.PIPE); '
299 # Signal grand child is ready.
300 'print(proc.stdout.read(1)); '
301 # Wait for parent to have completed the test.
302 'sys.stdin.read(1); '
303 'proc.kill()'
304 )
305 proc = subprocess.Popen(
306 [sys.executable, '-u', '-c', script],
307 stdin=subprocess.PIPE,
308 stdout=subprocess.PIPE)
309 try:
310 proc.stdout.read(1)
311 processes = file_path.filter_processes_tree_win(
312 file_path.enum_processes_win())
313 self.assertEqual(3, len(processes), processes)
314 proc.stdin.write('a')
315 proc.wait()
316 except Exception:
317 proc.kill()
318 finally:
319 proc.wait()
320
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000321 if sys.platform != 'win32':
322 def test_symlink(self):
323 # This test will fail if the checkout is in a symlink.
324 actual = file_path.split_at_symlink(None, ROOT_DIR)
325 expected = (ROOT_DIR, None, None)
326 self.assertEqual(expected, actual)
327
328 actual = file_path.split_at_symlink(
329 None, os.path.join(BASE_DIR, 'trace_inputs'))
330 expected = (
331 os.path.join(BASE_DIR, 'trace_inputs'), None, None)
332 self.assertEqual(expected, actual)
333
334 actual = file_path.split_at_symlink(
335 None, os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
336 expected = (
337 os.path.join(BASE_DIR, 'trace_inputs'), 'files2', '')
338 self.assertEqual(expected, actual)
339
340 actual = file_path.split_at_symlink(
341 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2'))
342 expected = (
343 os.path.join('tests', 'trace_inputs'), 'files2', '')
344 self.assertEqual(expected, actual)
345 actual = file_path.split_at_symlink(
346 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2', 'bar'))
347 expected = (
348 os.path.join('tests', 'trace_inputs'), 'files2', '/bar')
349 self.assertEqual(expected, actual)
350
351 def test_native_case_symlink_right_case(self):
352 actual = file_path.get_native_path_case(
353 os.path.join(BASE_DIR, 'trace_inputs'))
354 self.assertEqual('trace_inputs', os.path.basename(actual))
355
356 # Make sure the symlink is not resolved.
357 actual = file_path.get_native_path_case(
358 os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
359 self.assertEqual('files2', os.path.basename(actual))
360
maruel9cdd7612015-12-02 13:40:52 -0800361 else:
362 def test_undeleteable_chmod(self):
363 # Create a file and a directory with an empty ACL. Then try to delete it.
364 dirpath = os.path.join(self.tempdir, 'd')
365 filepath = os.path.join(dirpath, 'f')
366 os.mkdir(dirpath)
367 with open(filepath, 'w') as f:
368 f.write('hi')
369 os.chmod(filepath, 0)
370 os.chmod(dirpath, 0)
371 file_path.rmtree(dirpath)
372
373 def test_undeleteable_owner(self):
374 # Create a file and a directory with an empty ACL. Then try to delete it.
375 dirpath = os.path.join(self.tempdir, 'd')
376 filepath = os.path.join(dirpath, 'f')
377 os.mkdir(dirpath)
378 with open(filepath, 'w') as f:
379 f.write('hi')
380 import win32security
381 user, _domain, _type = win32security.LookupAccountName(
382 '', getpass.getuser())
383 sd = win32security.SECURITY_DESCRIPTOR()
384 sd.Initialize()
385 sd.SetSecurityDescriptorOwner(user, False)
386 # Create an empty DACL, which removes all rights.
387 dacl = win32security.ACL()
388 dacl.Initialize()
389 sd.SetSecurityDescriptorDacl(1, dacl, 0)
390 win32security.SetFileSecurity(
391 fs.extend(filepath), win32security.DACL_SECURITY_INFORMATION, sd)
392 win32security.SetFileSecurity(
393 fs.extend(dirpath), win32security.DACL_SECURITY_INFORMATION, sd)
394 file_path.rmtree(dirpath)
395
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000396
397if __name__ == '__main__':
maruel4b14f042015-10-06 12:08:08 -0700398 fix_encoding.fix_encoding()
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000399 logging.basicConfig(
400 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
401 if '-v' in sys.argv:
402 unittest.TestCase.maxDiff = None
403 unittest.main()