blob: bba2ed0c6f1f130ab500e80a44f6a680fdc2e2fd [file] [log] [blame]
maruel@chromium.org561d4b22013-09-26 21:08:08 +00001#!/usr/bin/env python
2# coding=utf-8
Marc-Antoine Ruel8add1242013-11-05 17:28:27 -05003# Copyright 2013 The Swarming Authors. All rights reserved.
Marc-Antoine Ruele98b1122013-11-05 20:27:57 -05004# Use of this source code is governed under the Apache License, Version 2.0 that
5# can be found in the LICENSE file.
maruel@chromium.org561d4b22013-09-26 21:08:08 +00006
7import logging
8import os
9import tempfile
10import unittest
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040011import StringIO
12import subprocess
maruel@chromium.org561d4b22013-09-26 21:08:08 +000013import sys
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040014import time
maruel@chromium.org561d4b22013-09-26 21:08:08 +000015
16BASE_DIR = unicode(os.path.dirname(os.path.abspath(__file__)))
17ROOT_DIR = os.path.dirname(BASE_DIR)
18sys.path.insert(0, ROOT_DIR)
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050019sys.path.insert(0, os.path.join(ROOT_DIR, 'third_party'))
maruel@chromium.org561d4b22013-09-26 21:08:08 +000020
21FILE_PATH = unicode(os.path.abspath(__file__))
22
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050023from depot_tools import auto_stub
maruel4b14f042015-10-06 12:08:08 -070024from depot_tools import fix_encoding
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040025import test_utils
maruel@chromium.org561d4b22013-09-26 21:08:08 +000026from utils import file_path
maruel4e732992015-10-16 10:17:21 -070027from utils import fs
maruel@chromium.org561d4b22013-09-26 21:08:08 +000028
29
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040030def write_content(filepath, content):
maruel4e732992015-10-16 10:17:21 -070031 with fs.open(filepath, 'wb') as f:
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040032 f.write(content)
33
34
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050035class FilePathTest(auto_stub.TestCase):
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040036 def setUp(self):
37 super(FilePathTest, self).setUp()
38 self._tempdir = None
39
40 def tearDown(self):
maruel4b14f042015-10-06 12:08:08 -070041 try:
42 if self._tempdir:
maruel4e732992015-10-16 10:17:21 -070043 for dirpath, dirnames, filenames in fs.walk(
maruel4b14f042015-10-06 12:08:08 -070044 self._tempdir, topdown=True):
45 for filename in filenames:
46 file_path.set_read_only(os.path.join(dirpath, filename), False)
47 for dirname in dirnames:
48 file_path.set_read_only(os.path.join(dirpath, dirname), False)
49 file_path.rmtree(self._tempdir)
50 finally:
51 super(FilePathTest, self).tearDown()
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040052
53 @property
54 def tempdir(self):
55 if not self._tempdir:
Marc-Antoine Ruel3c979cb2015-03-11 13:43:28 -040056 self._tempdir = tempfile.mkdtemp(prefix=u'run_isolated_test')
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040057 return self._tempdir
58
59 def assertFileMode(self, filepath, mode, umask=None):
60 umask = test_utils.umask() if umask is None else umask
maruel4e732992015-10-16 10:17:21 -070061 actual = fs.stat(filepath).st_mode
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040062 expected = mode & ~umask
63 self.assertEqual(
64 expected,
65 actual,
66 (filepath, oct(expected), oct(actual), oct(umask)))
67
68 def assertMaskedFileMode(self, filepath, mode):
69 """It's usually when the file was first marked read only."""
70 self.assertFileMode(filepath, mode, 0 if sys.platform == 'win32' else 077)
71
maruel@chromium.org561d4b22013-09-26 21:08:08 +000072 def test_native_case_end_with_os_path_sep(self):
73 # Make sure the trailing os.path.sep is kept.
74 path = file_path.get_native_path_case(ROOT_DIR) + os.path.sep
75 self.assertEqual(file_path.get_native_path_case(path), path)
76
77 def test_native_case_end_with_dot_os_path_sep(self):
78 path = file_path.get_native_path_case(ROOT_DIR + os.path.sep)
79 self.assertEqual(
80 file_path.get_native_path_case(path + '.' + os.path.sep),
81 path)
82
83 def test_native_case_non_existing(self):
84 # Make sure it doesn't throw on non-existing files.
85 non_existing = 'trace_input_test_this_file_should_not_exist'
86 path = os.path.expanduser('~/' + non_existing)
87 self.assertFalse(os.path.exists(path))
88 path = file_path.get_native_path_case(ROOT_DIR) + os.path.sep
89 self.assertEqual(file_path.get_native_path_case(path), path)
90
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040091 def test_delete_wd_rf(self):
92 # Confirms that a RO file in a RW directory can be deleted on non-Windows.
93 dir_foo = os.path.join(self.tempdir, 'foo')
94 file_bar = os.path.join(dir_foo, 'bar')
maruel4e732992015-10-16 10:17:21 -070095 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040096 write_content(file_bar, 'bar')
97 file_path.set_read_only(dir_foo, False)
98 file_path.set_read_only(file_bar, True)
99 self.assertFileMode(dir_foo, 040777)
100 self.assertMaskedFileMode(file_bar, 0100444)
101 if sys.platform == 'win32':
102 # On Windows, a read-only file can't be deleted.
103 with self.assertRaises(OSError):
maruel4e732992015-10-16 10:17:21 -0700104 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400105 else:
maruel4e732992015-10-16 10:17:21 -0700106 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400107
108 def test_delete_rd_wf(self):
109 # Confirms that a Rw file in a RO directory can be deleted on Windows only.
110 dir_foo = os.path.join(self.tempdir, 'foo')
111 file_bar = os.path.join(dir_foo, 'bar')
maruel4e732992015-10-16 10:17:21 -0700112 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400113 write_content(file_bar, 'bar')
114 file_path.set_read_only(dir_foo, True)
115 file_path.set_read_only(file_bar, False)
116 self.assertMaskedFileMode(dir_foo, 040555)
117 self.assertFileMode(file_bar, 0100666)
118 if sys.platform == 'win32':
119 # A read-only directory has a convoluted meaning on Windows, it means that
120 # the directory is "personalized". This is used as a signal by Windows
121 # Explorer to tell it to look into the directory for desktop.ini.
122 # See http://support.microsoft.com/kb/326549 for more details.
123 # As such, it is important to not try to set the read-only bit on
124 # directories on Windows since it has no effect other than trigger
125 # Windows Explorer to look for desktop.ini, which is unnecessary.
maruel4e732992015-10-16 10:17:21 -0700126 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400127 else:
128 with self.assertRaises(OSError):
maruel4e732992015-10-16 10:17:21 -0700129 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400130
131 def test_delete_rd_rf(self):
132 # Confirms that a RO file in a RO directory can't be deleted.
133 dir_foo = os.path.join(self.tempdir, 'foo')
134 file_bar = os.path.join(dir_foo, 'bar')
maruel4e732992015-10-16 10:17:21 -0700135 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400136 write_content(file_bar, 'bar')
137 file_path.set_read_only(dir_foo, True)
138 file_path.set_read_only(file_bar, True)
139 self.assertMaskedFileMode(dir_foo, 040555)
140 self.assertMaskedFileMode(file_bar, 0100444)
141 with self.assertRaises(OSError):
142 # It fails for different reason depending on the OS. See the test cases
143 # above.
maruel4e732992015-10-16 10:17:21 -0700144 fs.remove(file_bar)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400145
146 def test_hard_link_mode(self):
147 # Creates a hard link, see if the file mode changed on the node or the
148 # directory entry.
149 dir_foo = os.path.join(self.tempdir, 'foo')
150 file_bar = os.path.join(dir_foo, 'bar')
151 file_link = os.path.join(dir_foo, 'link')
maruel4e732992015-10-16 10:17:21 -0700152 fs.mkdir(dir_foo, 0777)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400153 write_content(file_bar, 'bar')
154 file_path.hardlink(file_bar, file_link)
155 self.assertFileMode(file_bar, 0100666)
156 self.assertFileMode(file_link, 0100666)
157 file_path.set_read_only(file_bar, True)
158 self.assertMaskedFileMode(file_bar, 0100444)
159 self.assertMaskedFileMode(file_link, 0100444)
160 # This is bad news for Windows; on Windows, the file must be writeable to be
161 # deleted, but the file node is modified. This means that every hard links
162 # must be reset to be read-only after deleting one of the hard link
163 # directory entry.
164
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500165 def test_rmtree_unicode(self):
166 subdir = os.path.join(self.tempdir, 'hi')
maruel4e732992015-10-16 10:17:21 -0700167 fs.mkdir(subdir)
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500168 filepath = os.path.join(
169 subdir, u'\u0627\u0644\u0635\u064A\u0646\u064A\u0629')
maruel4e732992015-10-16 10:17:21 -0700170 with fs.open(filepath, 'wb') as f:
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500171 f.write('hi')
172 # In particular, it fails when the input argument is a str.
173 file_path.rmtree(str(subdir))
174
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400175 if sys.platform == 'darwin':
176 def test_native_case_symlink_wrong_case(self):
177 base_dir = file_path.get_native_path_case(BASE_DIR)
178 trace_inputs_dir = os.path.join(base_dir, 'trace_inputs')
179 actual = file_path.get_native_path_case(trace_inputs_dir)
180 self.assertEqual(trace_inputs_dir, actual)
181
182 # Make sure the symlink is not resolved.
183 data = os.path.join(trace_inputs_dir, 'Files2')
184 actual = file_path.get_native_path_case(data)
185 self.assertEqual(
186 os.path.join(trace_inputs_dir, 'files2'), actual)
187
188 data = os.path.join(trace_inputs_dir, 'Files2', '')
189 actual = file_path.get_native_path_case(data)
190 self.assertEqual(
191 os.path.join(trace_inputs_dir, 'files2', ''), actual)
192
193 data = os.path.join(trace_inputs_dir, 'Files2', 'Child1.py')
194 actual = file_path.get_native_path_case(data)
195 # TODO(maruel): Should be child1.py.
196 self.assertEqual(
197 os.path.join(trace_inputs_dir, 'files2', 'Child1.py'), actual)
198
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000199 if sys.platform in ('darwin', 'win32'):
200 def test_native_case_not_sensitive(self):
201 # The home directory is almost guaranteed to have mixed upper/lower case
202 # letters on both Windows and OSX.
203 # This test also ensures that the output is independent on the input
204 # string case.
205 path = os.path.expanduser(u'~')
206 self.assertTrue(os.path.isdir(path))
207 path = path.replace('/', os.path.sep)
208 if sys.platform == 'win32':
209 # Make sure the drive letter is upper case for consistency.
210 path = path[0].upper() + path[1:]
211 # This test assumes the variable is in the native path case on disk, this
212 # should be the case. Verify this assumption:
213 self.assertEqual(path, file_path.get_native_path_case(path))
214 self.assertEqual(
215 file_path.get_native_path_case(path.lower()),
216 file_path.get_native_path_case(path.upper()))
217
218 def test_native_case_not_sensitive_non_existent(self):
219 # This test also ensures that the output is independent on the input
220 # string case.
221 non_existing = os.path.join(
222 'trace_input_test_this_dir_should_not_exist', 'really not', '')
223 path = os.path.expanduser(os.path.join(u'~', non_existing))
224 path = path.replace('/', os.path.sep)
maruel4e732992015-10-16 10:17:21 -0700225 self.assertFalse(fs.exists(path))
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000226 lower = file_path.get_native_path_case(path.lower())
227 upper = file_path.get_native_path_case(path.upper())
228 # Make sure non-existing element is not modified:
229 self.assertTrue(lower.endswith(non_existing.lower()))
230 self.assertTrue(upper.endswith(non_existing.upper()))
231 self.assertEqual(lower[:-len(non_existing)], upper[:-len(non_existing)])
232
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400233 if sys.platform == 'win32':
234 def test_native_case_alternate_datastream(self):
235 # Create the file manually, since tempfile doesn't support ADS.
Marc-Antoine Ruel3c979cb2015-03-11 13:43:28 -0400236 tempdir = unicode(tempfile.mkdtemp(prefix=u'trace_inputs'))
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400237 try:
238 tempdir = file_path.get_native_path_case(tempdir)
239 basename = 'foo.txt'
240 filename = basename + ':Zone.Identifier'
241 filepath = os.path.join(tempdir, filename)
242 open(filepath, 'w').close()
243 self.assertEqual(filepath, file_path.get_native_path_case(filepath))
244 data_suffix = ':$DATA'
245 self.assertEqual(
246 filepath + data_suffix,
247 file_path.get_native_path_case(filepath + data_suffix))
248
249 open(filepath + '$DATA', 'w').close()
250 self.assertEqual(
251 filepath + data_suffix,
252 file_path.get_native_path_case(filepath + data_suffix))
253 # Ensure the ADS weren't created as separate file. You love NTFS, don't
254 # you?
maruel4e732992015-10-16 10:17:21 -0700255 self.assertEqual([basename], fs.listdir(tempdir))
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400256 finally:
maruel4b14f042015-10-06 12:08:08 -0700257 file_path.rmtree(tempdir)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400258
259 def test_rmtree_win(self):
260 # Mock our sleep for faster test case execution.
261 sleeps = []
262 self.mock(time, 'sleep', sleeps.append)
263 self.mock(sys, 'stderr', StringIO.StringIO())
264
265 # Open a child process, so the file is locked.
266 subdir = os.path.join(self.tempdir, 'to_be_deleted')
maruel4e732992015-10-16 10:17:21 -0700267 fs.mkdir(subdir)
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400268 script = 'import time; open(\'a\', \'w\'); time.sleep(60)'
269 proc = subprocess.Popen([sys.executable, '-c', script], cwd=subdir)
270 try:
271 # Wait until the file exist.
maruel4e732992015-10-16 10:17:21 -0700272 while not fs.isfile(os.path.join(subdir, 'a')):
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400273 self.assertEqual(None, proc.poll())
274 file_path.rmtree(subdir)
275 self.assertEqual([2, 4, 2], sleeps)
276 # sys.stderr.getvalue() would return a fair amount of output but it is
277 # not completely deterministic so we're not testing it here.
278 finally:
279 proc.wait()
280
Marc-Antoine Ruela275b292014-11-25 15:17:21 -0500281 def test_filter_processes_dir_win(self):
282 python_dir = os.path.dirname(sys.executable)
283 processes = file_path.filter_processes_dir_win(
284 file_path.enum_processes_win(), python_dir)
285 self.assertTrue(processes)
286 proc_names = [proc.ExecutablePath for proc in processes]
287 # Try to find at least one python process.
288 self.assertTrue(
289 any(proc == sys.executable for proc in proc_names), proc_names)
290
291 def test_filter_processes_tree_win(self):
292 # Create a grand-child.
293 script = (
294 'import subprocess,sys;'
295 'proc = subprocess.Popen('
296 '[sys.executable, \'-u\', \'-c\', \'import time; print(1); '
297 'time.sleep(60)\'], stdout=subprocess.PIPE); '
298 # Signal grand child is ready.
299 'print(proc.stdout.read(1)); '
300 # Wait for parent to have completed the test.
301 'sys.stdin.read(1); '
302 'proc.kill()'
303 )
304 proc = subprocess.Popen(
305 [sys.executable, '-u', '-c', script],
306 stdin=subprocess.PIPE,
307 stdout=subprocess.PIPE)
308 try:
309 proc.stdout.read(1)
310 processes = file_path.filter_processes_tree_win(
311 file_path.enum_processes_win())
312 self.assertEqual(3, len(processes), processes)
313 proc.stdin.write('a')
314 proc.wait()
315 except Exception:
316 proc.kill()
317 finally:
318 proc.wait()
319
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000320 if sys.platform != 'win32':
321 def test_symlink(self):
322 # This test will fail if the checkout is in a symlink.
323 actual = file_path.split_at_symlink(None, ROOT_DIR)
324 expected = (ROOT_DIR, None, None)
325 self.assertEqual(expected, actual)
326
327 actual = file_path.split_at_symlink(
328 None, os.path.join(BASE_DIR, 'trace_inputs'))
329 expected = (
330 os.path.join(BASE_DIR, 'trace_inputs'), None, None)
331 self.assertEqual(expected, actual)
332
333 actual = file_path.split_at_symlink(
334 None, os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
335 expected = (
336 os.path.join(BASE_DIR, 'trace_inputs'), 'files2', '')
337 self.assertEqual(expected, actual)
338
339 actual = file_path.split_at_symlink(
340 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2'))
341 expected = (
342 os.path.join('tests', 'trace_inputs'), 'files2', '')
343 self.assertEqual(expected, actual)
344 actual = file_path.split_at_symlink(
345 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2', 'bar'))
346 expected = (
347 os.path.join('tests', 'trace_inputs'), 'files2', '/bar')
348 self.assertEqual(expected, actual)
349
350 def test_native_case_symlink_right_case(self):
351 actual = file_path.get_native_path_case(
352 os.path.join(BASE_DIR, 'trace_inputs'))
353 self.assertEqual('trace_inputs', os.path.basename(actual))
354
355 # Make sure the symlink is not resolved.
356 actual = file_path.get_native_path_case(
357 os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
358 self.assertEqual('files2', os.path.basename(actual))
359
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000360
361if __name__ == '__main__':
maruel4b14f042015-10-06 12:08:08 -0700362 fix_encoding.fix_encoding()
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000363 logging.basicConfig(
364 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
365 if '-v' in sys.argv:
366 unittest.TestCase.maxDiff = None
367 unittest.main()