blob: e73e494d8598ac377c0ea408245fb19f86a3d46a [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.
maruelf1f5e2a2016-05-25 17:10:39 -07004# Use of this source code is governed under the Apache License, Version 2.0
5# that can be 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
tansella4949442016-06-23 22:34:32 -070017BASE_DIR = os.path.dirname(os.path.abspath(
18 __file__.decode(sys.getfilesystemencoding())))
maruel@chromium.org561d4b22013-09-26 21:08:08 +000019ROOT_DIR = os.path.dirname(BASE_DIR)
20sys.path.insert(0, ROOT_DIR)
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050021sys.path.insert(0, os.path.join(ROOT_DIR, 'third_party'))
maruel@chromium.org561d4b22013-09-26 21:08:08 +000022
tansella4949442016-06-23 22:34:32 -070023FILE_PATH = os.path.abspath(__file__.decode(sys.getfilesystemencoding()))
maruel@chromium.org561d4b22013-09-26 21:08:08 +000024
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050025from depot_tools import auto_stub
maruel4b14f042015-10-06 12:08:08 -070026from depot_tools import fix_encoding
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040027import test_utils
maruel@chromium.org561d4b22013-09-26 21:08:08 +000028from utils import file_path
maruel4e732992015-10-16 10:17:21 -070029from utils import fs
maruel@chromium.org561d4b22013-09-26 21:08:08 +000030
31
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040032def write_content(filepath, content):
maruel4e732992015-10-16 10:17:21 -070033 with fs.open(filepath, 'wb') as f:
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040034 f.write(content)
35
36
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050037class FilePathTest(auto_stub.TestCase):
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040038 def setUp(self):
39 super(FilePathTest, self).setUp()
40 self._tempdir = None
41
42 def tearDown(self):
maruel4b14f042015-10-06 12:08:08 -070043 try:
44 if self._tempdir:
maruel4e732992015-10-16 10:17:21 -070045 for dirpath, dirnames, filenames in fs.walk(
maruel4b14f042015-10-06 12:08:08 -070046 self._tempdir, topdown=True):
47 for filename in filenames:
48 file_path.set_read_only(os.path.join(dirpath, filename), False)
49 for dirname in dirnames:
50 file_path.set_read_only(os.path.join(dirpath, dirname), False)
51 file_path.rmtree(self._tempdir)
52 finally:
53 super(FilePathTest, self).tearDown()
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040054
55 @property
56 def tempdir(self):
57 if not self._tempdir:
Marc-Antoine Ruel3c979cb2015-03-11 13:43:28 -040058 self._tempdir = tempfile.mkdtemp(prefix=u'run_isolated_test')
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040059 return self._tempdir
60
vadimshe42aeba2016-06-03 12:32:21 -070061 def test_atomic_replace_new_file(self):
62 path = os.path.join(self.tempdir, 'new_file')
63 file_path.atomic_replace(path, 'blah')
64 with open(path, 'rb') as f:
65 self.assertEqual('blah', f.read())
66 self.assertEqual([u'new_file'], os.listdir(self.tempdir))
67
68 def test_atomic_replace_existing_file(self):
69 path = os.path.join(self.tempdir, 'existing_file')
70 with open(path, 'wb') as f:
71 f.write('existing body')
72 file_path.atomic_replace(path, 'new body')
73 with open(path, 'rb') as f:
74 self.assertEqual('new body', f.read())
75 self.assertEqual([u'existing_file'], os.listdir(self.tempdir))
76
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040077 def assertFileMode(self, filepath, mode, umask=None):
78 umask = test_utils.umask() if umask is None else umask
maruel4e732992015-10-16 10:17:21 -070079 actual = fs.stat(filepath).st_mode
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040080 expected = mode & ~umask
81 self.assertEqual(
82 expected,
83 actual,
84 (filepath, oct(expected), oct(actual), oct(umask)))
85
86 def assertMaskedFileMode(self, filepath, mode):
87 """It's usually when the file was first marked read only."""
88 self.assertFileMode(filepath, mode, 0 if sys.platform == 'win32' else 077)
89
maruel@chromium.org561d4b22013-09-26 21:08:08 +000090 def test_native_case_end_with_os_path_sep(self):
91 # Make sure the trailing os.path.sep is kept.
92 path = file_path.get_native_path_case(ROOT_DIR) + os.path.sep
93 self.assertEqual(file_path.get_native_path_case(path), path)
94
95 def test_native_case_end_with_dot_os_path_sep(self):
96 path = file_path.get_native_path_case(ROOT_DIR + os.path.sep)
97 self.assertEqual(
98 file_path.get_native_path_case(path + '.' + os.path.sep),
99 path)
100
101 def test_native_case_non_existing(self):
102 # Make sure it doesn't throw on non-existing files.
103 non_existing = 'trace_input_test_this_file_should_not_exist'
104 path = os.path.expanduser('~/' + non_existing)
105 self.assertFalse(os.path.exists(path))
106 path = file_path.get_native_path_case(ROOT_DIR) + os.path.sep
107 self.assertEqual(file_path.get_native_path_case(path), path)
108
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400109 def test_delete_wd_rf(self):
110 # Confirms that a RO file in a RW directory can be deleted on non-Windows.
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, False)
116 file_path.set_read_only(file_bar, True)
117 self.assertFileMode(dir_foo, 040777)
118 self.assertMaskedFileMode(file_bar, 0100444)
119 if sys.platform == 'win32':
120 # On Windows, a read-only file can't be deleted.
121 with self.assertRaises(OSError):
maruel4e732992015-10-16 10:17:21 -0700122 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400123 else:
maruel4e732992015-10-16 10:17:21 -0700124 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400125
126 def test_delete_rd_wf(self):
127 # Confirms that a Rw file in a RO directory can be deleted on Windows only.
128 dir_foo = os.path.join(self.tempdir, 'foo')
129 file_bar = os.path.join(dir_foo, 'bar')
maruel4e732992015-10-16 10:17:21 -0700130 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400131 write_content(file_bar, 'bar')
132 file_path.set_read_only(dir_foo, True)
133 file_path.set_read_only(file_bar, False)
134 self.assertMaskedFileMode(dir_foo, 040555)
135 self.assertFileMode(file_bar, 0100666)
136 if sys.platform == 'win32':
137 # A read-only directory has a convoluted meaning on Windows, it means that
138 # the directory is "personalized". This is used as a signal by Windows
139 # Explorer to tell it to look into the directory for desktop.ini.
140 # See http://support.microsoft.com/kb/326549 for more details.
141 # As such, it is important to not try to set the read-only bit on
142 # directories on Windows since it has no effect other than trigger
143 # Windows Explorer to look for desktop.ini, which is unnecessary.
maruel4e732992015-10-16 10:17:21 -0700144 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400145 else:
146 with self.assertRaises(OSError):
maruel4e732992015-10-16 10:17:21 -0700147 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400148
149 def test_delete_rd_rf(self):
150 # Confirms that a RO file in a RO directory can't be deleted.
151 dir_foo = os.path.join(self.tempdir, 'foo')
152 file_bar = os.path.join(dir_foo, 'bar')
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.set_read_only(dir_foo, True)
156 file_path.set_read_only(file_bar, True)
157 self.assertMaskedFileMode(dir_foo, 040555)
158 self.assertMaskedFileMode(file_bar, 0100444)
159 with self.assertRaises(OSError):
160 # It fails for different reason depending on the OS. See the test cases
161 # above.
maruel4e732992015-10-16 10:17:21 -0700162 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400163
164 def test_hard_link_mode(self):
165 # Creates a hard link, see if the file mode changed on the node or the
166 # directory entry.
167 dir_foo = os.path.join(self.tempdir, 'foo')
168 file_bar = os.path.join(dir_foo, 'bar')
169 file_link = os.path.join(dir_foo, 'link')
maruel4e732992015-10-16 10:17:21 -0700170 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400171 write_content(file_bar, 'bar')
172 file_path.hardlink(file_bar, file_link)
173 self.assertFileMode(file_bar, 0100666)
174 self.assertFileMode(file_link, 0100666)
175 file_path.set_read_only(file_bar, True)
176 self.assertMaskedFileMode(file_bar, 0100444)
177 self.assertMaskedFileMode(file_link, 0100444)
178 # This is bad news for Windows; on Windows, the file must be writeable to be
179 # deleted, but the file node is modified. This means that every hard links
180 # must be reset to be read-only after deleting one of the hard link
181 # directory entry.
182
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500183 def test_rmtree_unicode(self):
184 subdir = os.path.join(self.tempdir, 'hi')
maruel4e732992015-10-16 10:17:21 -0700185 fs.mkdir(subdir)
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500186 filepath = os.path.join(
187 subdir, u'\u0627\u0644\u0635\u064A\u0646\u064A\u0629')
maruel4e732992015-10-16 10:17:21 -0700188 with fs.open(filepath, 'wb') as f:
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500189 f.write('hi')
190 # In particular, it fails when the input argument is a str.
191 file_path.rmtree(str(subdir))
192
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400193 if sys.platform == 'darwin':
194 def test_native_case_symlink_wrong_case(self):
195 base_dir = file_path.get_native_path_case(BASE_DIR)
196 trace_inputs_dir = os.path.join(base_dir, 'trace_inputs')
197 actual = file_path.get_native_path_case(trace_inputs_dir)
198 self.assertEqual(trace_inputs_dir, actual)
199
200 # Make sure the symlink is not resolved.
201 data = os.path.join(trace_inputs_dir, 'Files2')
202 actual = file_path.get_native_path_case(data)
203 self.assertEqual(
204 os.path.join(trace_inputs_dir, 'files2'), actual)
205
206 data = os.path.join(trace_inputs_dir, 'Files2', '')
207 actual = file_path.get_native_path_case(data)
208 self.assertEqual(
209 os.path.join(trace_inputs_dir, 'files2', ''), actual)
210
211 data = os.path.join(trace_inputs_dir, 'Files2', 'Child1.py')
212 actual = file_path.get_native_path_case(data)
213 # TODO(maruel): Should be child1.py.
214 self.assertEqual(
215 os.path.join(trace_inputs_dir, 'files2', 'Child1.py'), actual)
216
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000217 if sys.platform in ('darwin', 'win32'):
218 def test_native_case_not_sensitive(self):
219 # The home directory is almost guaranteed to have mixed upper/lower case
220 # letters on both Windows and OSX.
221 # This test also ensures that the output is independent on the input
222 # string case.
223 path = os.path.expanduser(u'~')
224 self.assertTrue(os.path.isdir(path))
225 path = path.replace('/', os.path.sep)
226 if sys.platform == 'win32':
227 # Make sure the drive letter is upper case for consistency.
228 path = path[0].upper() + path[1:]
229 # This test assumes the variable is in the native path case on disk, this
230 # should be the case. Verify this assumption:
231 self.assertEqual(path, file_path.get_native_path_case(path))
232 self.assertEqual(
233 file_path.get_native_path_case(path.lower()),
234 file_path.get_native_path_case(path.upper()))
235
236 def test_native_case_not_sensitive_non_existent(self):
237 # This test also ensures that the output is independent on the input
238 # string case.
239 non_existing = os.path.join(
240 'trace_input_test_this_dir_should_not_exist', 'really not', '')
241 path = os.path.expanduser(os.path.join(u'~', non_existing))
242 path = path.replace('/', os.path.sep)
maruel4e732992015-10-16 10:17:21 -0700243 self.assertFalse(fs.exists(path))
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000244 lower = file_path.get_native_path_case(path.lower())
245 upper = file_path.get_native_path_case(path.upper())
246 # Make sure non-existing element is not modified:
247 self.assertTrue(lower.endswith(non_existing.lower()))
248 self.assertTrue(upper.endswith(non_existing.upper()))
249 self.assertEqual(lower[:-len(non_existing)], upper[:-len(non_existing)])
250
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400251 if sys.platform == 'win32':
252 def test_native_case_alternate_datastream(self):
253 # Create the file manually, since tempfile doesn't support ADS.
Marc-Antoine Ruel3c979cb2015-03-11 13:43:28 -0400254 tempdir = unicode(tempfile.mkdtemp(prefix=u'trace_inputs'))
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400255 try:
256 tempdir = file_path.get_native_path_case(tempdir)
257 basename = 'foo.txt'
258 filename = basename + ':Zone.Identifier'
259 filepath = os.path.join(tempdir, filename)
260 open(filepath, 'w').close()
261 self.assertEqual(filepath, file_path.get_native_path_case(filepath))
262 data_suffix = ':$DATA'
263 self.assertEqual(
264 filepath + data_suffix,
265 file_path.get_native_path_case(filepath + data_suffix))
266
267 open(filepath + '$DATA', 'w').close()
268 self.assertEqual(
269 filepath + data_suffix,
270 file_path.get_native_path_case(filepath + data_suffix))
271 # Ensure the ADS weren't created as separate file. You love NTFS, don't
272 # you?
maruel4e732992015-10-16 10:17:21 -0700273 self.assertEqual([basename], fs.listdir(tempdir))
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400274 finally:
maruel4b14f042015-10-06 12:08:08 -0700275 file_path.rmtree(tempdir)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400276
277 def test_rmtree_win(self):
278 # Mock our sleep for faster test case execution.
279 sleeps = []
280 self.mock(time, 'sleep', sleeps.append)
281 self.mock(sys, 'stderr', StringIO.StringIO())
282
283 # Open a child process, so the file is locked.
284 subdir = os.path.join(self.tempdir, 'to_be_deleted')
maruel4e732992015-10-16 10:17:21 -0700285 fs.mkdir(subdir)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400286 script = 'import time; open(\'a\', \'w\'); time.sleep(60)'
287 proc = subprocess.Popen([sys.executable, '-c', script], cwd=subdir)
288 try:
289 # Wait until the file exist.
maruel4e732992015-10-16 10:17:21 -0700290 while not fs.isfile(os.path.join(subdir, 'a')):
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400291 self.assertEqual(None, proc.poll())
292 file_path.rmtree(subdir)
293 self.assertEqual([2, 4, 2], sleeps)
294 # sys.stderr.getvalue() would return a fair amount of output but it is
295 # not completely deterministic so we're not testing it here.
296 finally:
297 proc.wait()
298
Marc-Antoine Ruela275b292014-11-25 15:17:21 -0500299 def test_filter_processes_dir_win(self):
300 python_dir = os.path.dirname(sys.executable)
301 processes = file_path.filter_processes_dir_win(
302 file_path.enum_processes_win(), python_dir)
303 self.assertTrue(processes)
304 proc_names = [proc.ExecutablePath for proc in processes]
305 # Try to find at least one python process.
306 self.assertTrue(
307 any(proc == sys.executable for proc in proc_names), proc_names)
308
309 def test_filter_processes_tree_win(self):
310 # Create a grand-child.
311 script = (
312 'import subprocess,sys;'
313 'proc = subprocess.Popen('
314 '[sys.executable, \'-u\', \'-c\', \'import time; print(1); '
315 'time.sleep(60)\'], stdout=subprocess.PIPE); '
316 # Signal grand child is ready.
317 'print(proc.stdout.read(1)); '
318 # Wait for parent to have completed the test.
319 'sys.stdin.read(1); '
320 'proc.kill()'
321 )
322 proc = subprocess.Popen(
323 [sys.executable, '-u', '-c', script],
324 stdin=subprocess.PIPE,
325 stdout=subprocess.PIPE)
326 try:
327 proc.stdout.read(1)
328 processes = file_path.filter_processes_tree_win(
329 file_path.enum_processes_win())
330 self.assertEqual(3, len(processes), processes)
331 proc.stdin.write('a')
332 proc.wait()
333 except Exception:
334 proc.kill()
335 finally:
336 proc.wait()
337
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000338 if sys.platform != 'win32':
339 def test_symlink(self):
340 # This test will fail if the checkout is in a symlink.
341 actual = file_path.split_at_symlink(None, ROOT_DIR)
342 expected = (ROOT_DIR, None, None)
343 self.assertEqual(expected, actual)
344
345 actual = file_path.split_at_symlink(
346 None, os.path.join(BASE_DIR, 'trace_inputs'))
347 expected = (
348 os.path.join(BASE_DIR, 'trace_inputs'), None, None)
349 self.assertEqual(expected, actual)
350
351 actual = file_path.split_at_symlink(
352 None, os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
353 expected = (
354 os.path.join(BASE_DIR, 'trace_inputs'), 'files2', '')
355 self.assertEqual(expected, actual)
356
357 actual = file_path.split_at_symlink(
358 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2'))
359 expected = (
360 os.path.join('tests', 'trace_inputs'), 'files2', '')
361 self.assertEqual(expected, actual)
362 actual = file_path.split_at_symlink(
363 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2', 'bar'))
364 expected = (
365 os.path.join('tests', 'trace_inputs'), 'files2', '/bar')
366 self.assertEqual(expected, actual)
367
368 def test_native_case_symlink_right_case(self):
369 actual = file_path.get_native_path_case(
370 os.path.join(BASE_DIR, 'trace_inputs'))
371 self.assertEqual('trace_inputs', os.path.basename(actual))
372
373 # Make sure the symlink is not resolved.
374 actual = file_path.get_native_path_case(
375 os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
376 self.assertEqual('files2', os.path.basename(actual))
377
maruel9cdd7612015-12-02 13:40:52 -0800378 else:
379 def test_undeleteable_chmod(self):
380 # Create a file and a directory with an empty ACL. Then try to delete it.
381 dirpath = os.path.join(self.tempdir, 'd')
382 filepath = os.path.join(dirpath, 'f')
383 os.mkdir(dirpath)
384 with open(filepath, 'w') as f:
385 f.write('hi')
386 os.chmod(filepath, 0)
387 os.chmod(dirpath, 0)
388 file_path.rmtree(dirpath)
389
390 def test_undeleteable_owner(self):
391 # Create a file and a directory with an empty ACL. Then try to delete it.
392 dirpath = os.path.join(self.tempdir, 'd')
393 filepath = os.path.join(dirpath, 'f')
394 os.mkdir(dirpath)
395 with open(filepath, 'w') as f:
396 f.write('hi')
397 import win32security
398 user, _domain, _type = win32security.LookupAccountName(
399 '', getpass.getuser())
400 sd = win32security.SECURITY_DESCRIPTOR()
401 sd.Initialize()
402 sd.SetSecurityDescriptorOwner(user, False)
403 # Create an empty DACL, which removes all rights.
404 dacl = win32security.ACL()
405 dacl.Initialize()
406 sd.SetSecurityDescriptorDacl(1, dacl, 0)
407 win32security.SetFileSecurity(
408 fs.extend(filepath), win32security.DACL_SECURITY_INFORMATION, sd)
409 win32security.SetFileSecurity(
410 fs.extend(dirpath), win32security.DACL_SECURITY_INFORMATION, sd)
411 file_path.rmtree(dirpath)
412
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000413
414if __name__ == '__main__':
maruel4b14f042015-10-06 12:08:08 -0700415 fix_encoding.fix_encoding()
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000416 logging.basicConfig(
417 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
418 if '-v' in sys.argv:
419 unittest.TestCase.maxDiff = None
420 unittest.main()