blob: 7a69bbb12d9c502bde982f29d177cc6035a1c2ab [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
11import shutil
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
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040025import test_utils
maruel@chromium.org561d4b22013-09-26 21:08:08 +000026from utils import file_path
27
28
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040029def write_content(filepath, content):
30 with open(filepath, 'wb') as f:
31 f.write(content)
32
33
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -050034class FilePathTest(auto_stub.TestCase):
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040035 def setUp(self):
36 super(FilePathTest, self).setUp()
37 self._tempdir = None
38
39 def tearDown(self):
40 if self._tempdir:
41 for dirpath, dirnames, filenames in os.walk(self._tempdir, topdown=True):
42 for filename in filenames:
43 file_path.set_read_only(os.path.join(dirpath, filename), False)
44 for dirname in dirnames:
45 file_path.set_read_only(os.path.join(dirpath, dirname), False)
46 shutil.rmtree(self._tempdir)
47 super(FilePathTest, self).tearDown()
48
49 @property
50 def tempdir(self):
51 if not self._tempdir:
Marc-Antoine Ruel3c979cb2015-03-11 13:43:28 -040052 self._tempdir = tempfile.mkdtemp(prefix=u'run_isolated_test')
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040053 return self._tempdir
54
55 def assertFileMode(self, filepath, mode, umask=None):
56 umask = test_utils.umask() if umask is None else umask
57 actual = os.stat(filepath).st_mode
58 expected = mode & ~umask
59 self.assertEqual(
60 expected,
61 actual,
62 (filepath, oct(expected), oct(actual), oct(umask)))
63
64 def assertMaskedFileMode(self, filepath, mode):
65 """It's usually when the file was first marked read only."""
66 self.assertFileMode(filepath, mode, 0 if sys.platform == 'win32' else 077)
67
maruel@chromium.org561d4b22013-09-26 21:08:08 +000068 def test_native_case_end_with_os_path_sep(self):
69 # Make sure the trailing os.path.sep is kept.
70 path = file_path.get_native_path_case(ROOT_DIR) + os.path.sep
71 self.assertEqual(file_path.get_native_path_case(path), path)
72
73 def test_native_case_end_with_dot_os_path_sep(self):
74 path = file_path.get_native_path_case(ROOT_DIR + os.path.sep)
75 self.assertEqual(
76 file_path.get_native_path_case(path + '.' + os.path.sep),
77 path)
78
79 def test_native_case_non_existing(self):
80 # Make sure it doesn't throw on non-existing files.
81 non_existing = 'trace_input_test_this_file_should_not_exist'
82 path = os.path.expanduser('~/' + non_existing)
83 self.assertFalse(os.path.exists(path))
84 path = file_path.get_native_path_case(ROOT_DIR) + os.path.sep
85 self.assertEqual(file_path.get_native_path_case(path), path)
86
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040087 def test_delete_wd_rf(self):
88 # Confirms that a RO file in a RW directory can be deleted on non-Windows.
89 dir_foo = os.path.join(self.tempdir, 'foo')
90 file_bar = os.path.join(dir_foo, 'bar')
91 os.mkdir(dir_foo, 0777)
92 write_content(file_bar, 'bar')
93 file_path.set_read_only(dir_foo, False)
94 file_path.set_read_only(file_bar, True)
95 self.assertFileMode(dir_foo, 040777)
96 self.assertMaskedFileMode(file_bar, 0100444)
97 if sys.platform == 'win32':
98 # On Windows, a read-only file can't be deleted.
99 with self.assertRaises(OSError):
100 os.remove(file_bar)
101 else:
102 os.remove(file_bar)
103
104 def test_delete_rd_wf(self):
105 # Confirms that a Rw file in a RO directory can be deleted on Windows only.
106 dir_foo = os.path.join(self.tempdir, 'foo')
107 file_bar = os.path.join(dir_foo, 'bar')
108 os.mkdir(dir_foo, 0777)
109 write_content(file_bar, 'bar')
110 file_path.set_read_only(dir_foo, True)
111 file_path.set_read_only(file_bar, False)
112 self.assertMaskedFileMode(dir_foo, 040555)
113 self.assertFileMode(file_bar, 0100666)
114 if sys.platform == 'win32':
115 # A read-only directory has a convoluted meaning on Windows, it means that
116 # the directory is "personalized". This is used as a signal by Windows
117 # Explorer to tell it to look into the directory for desktop.ini.
118 # See http://support.microsoft.com/kb/326549 for more details.
119 # As such, it is important to not try to set the read-only bit on
120 # directories on Windows since it has no effect other than trigger
121 # Windows Explorer to look for desktop.ini, which is unnecessary.
122 os.remove(file_bar)
123 else:
124 with self.assertRaises(OSError):
125 os.remove(file_bar)
126
127 def test_delete_rd_rf(self):
128 # Confirms that a RO file in a RO directory can't be deleted.
129 dir_foo = os.path.join(self.tempdir, 'foo')
130 file_bar = os.path.join(dir_foo, 'bar')
131 os.mkdir(dir_foo, 0777)
132 write_content(file_bar, 'bar')
133 file_path.set_read_only(dir_foo, True)
134 file_path.set_read_only(file_bar, True)
135 self.assertMaskedFileMode(dir_foo, 040555)
136 self.assertMaskedFileMode(file_bar, 0100444)
137 with self.assertRaises(OSError):
138 # It fails for different reason depending on the OS. See the test cases
139 # above.
140 os.remove(file_bar)
141
142 def test_hard_link_mode(self):
143 # Creates a hard link, see if the file mode changed on the node or the
144 # directory entry.
145 dir_foo = os.path.join(self.tempdir, 'foo')
146 file_bar = os.path.join(dir_foo, 'bar')
147 file_link = os.path.join(dir_foo, 'link')
148 os.mkdir(dir_foo, 0777)
149 write_content(file_bar, 'bar')
150 file_path.hardlink(file_bar, file_link)
151 self.assertFileMode(file_bar, 0100666)
152 self.assertFileMode(file_link, 0100666)
153 file_path.set_read_only(file_bar, True)
154 self.assertMaskedFileMode(file_bar, 0100444)
155 self.assertMaskedFileMode(file_link, 0100444)
156 # This is bad news for Windows; on Windows, the file must be writeable to be
157 # deleted, but the file node is modified. This means that every hard links
158 # must be reset to be read-only after deleting one of the hard link
159 # directory entry.
160
Marc-Antoine Ruel0a795bd2015-01-16 20:32:10 -0500161 def test_rmtree_unicode(self):
162 subdir = os.path.join(self.tempdir, 'hi')
163 os.mkdir(subdir)
164 filepath = os.path.join(
165 subdir, u'\u0627\u0644\u0635\u064A\u0646\u064A\u0629')
166 with open(filepath, 'wb') as f:
167 f.write('hi')
168 # In particular, it fails when the input argument is a str.
169 file_path.rmtree(str(subdir))
170
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400171 if sys.platform == 'darwin':
172 def test_native_case_symlink_wrong_case(self):
173 base_dir = file_path.get_native_path_case(BASE_DIR)
174 trace_inputs_dir = os.path.join(base_dir, 'trace_inputs')
175 actual = file_path.get_native_path_case(trace_inputs_dir)
176 self.assertEqual(trace_inputs_dir, actual)
177
178 # Make sure the symlink is not resolved.
179 data = os.path.join(trace_inputs_dir, 'Files2')
180 actual = file_path.get_native_path_case(data)
181 self.assertEqual(
182 os.path.join(trace_inputs_dir, 'files2'), actual)
183
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', 'Child1.py')
190 actual = file_path.get_native_path_case(data)
191 # TODO(maruel): Should be child1.py.
192 self.assertEqual(
193 os.path.join(trace_inputs_dir, 'files2', 'Child1.py'), actual)
194
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000195 if sys.platform in ('darwin', 'win32'):
196 def test_native_case_not_sensitive(self):
197 # The home directory is almost guaranteed to have mixed upper/lower case
198 # letters on both Windows and OSX.
199 # This test also ensures that the output is independent on the input
200 # string case.
201 path = os.path.expanduser(u'~')
202 self.assertTrue(os.path.isdir(path))
203 path = path.replace('/', os.path.sep)
204 if sys.platform == 'win32':
205 # Make sure the drive letter is upper case for consistency.
206 path = path[0].upper() + path[1:]
207 # This test assumes the variable is in the native path case on disk, this
208 # should be the case. Verify this assumption:
209 self.assertEqual(path, file_path.get_native_path_case(path))
210 self.assertEqual(
211 file_path.get_native_path_case(path.lower()),
212 file_path.get_native_path_case(path.upper()))
213
214 def test_native_case_not_sensitive_non_existent(self):
215 # This test also ensures that the output is independent on the input
216 # string case.
217 non_existing = os.path.join(
218 'trace_input_test_this_dir_should_not_exist', 'really not', '')
219 path = os.path.expanduser(os.path.join(u'~', non_existing))
220 path = path.replace('/', os.path.sep)
221 self.assertFalse(os.path.exists(path))
222 lower = file_path.get_native_path_case(path.lower())
223 upper = file_path.get_native_path_case(path.upper())
224 # Make sure non-existing element is not modified:
225 self.assertTrue(lower.endswith(non_existing.lower()))
226 self.assertTrue(upper.endswith(non_existing.upper()))
227 self.assertEqual(lower[:-len(non_existing)], upper[:-len(non_existing)])
228
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400229 if sys.platform == 'win32':
230 def test_native_case_alternate_datastream(self):
231 # Create the file manually, since tempfile doesn't support ADS.
Marc-Antoine Ruel3c979cb2015-03-11 13:43:28 -0400232 tempdir = unicode(tempfile.mkdtemp(prefix=u'trace_inputs'))
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400233 try:
234 tempdir = file_path.get_native_path_case(tempdir)
235 basename = 'foo.txt'
236 filename = basename + ':Zone.Identifier'
237 filepath = os.path.join(tempdir, filename)
238 open(filepath, 'w').close()
239 self.assertEqual(filepath, file_path.get_native_path_case(filepath))
240 data_suffix = ':$DATA'
241 self.assertEqual(
242 filepath + data_suffix,
243 file_path.get_native_path_case(filepath + data_suffix))
244
245 open(filepath + '$DATA', 'w').close()
246 self.assertEqual(
247 filepath + data_suffix,
248 file_path.get_native_path_case(filepath + data_suffix))
249 # Ensure the ADS weren't created as separate file. You love NTFS, don't
250 # you?
251 self.assertEqual([basename], os.listdir(tempdir))
252 finally:
253 shutil.rmtree(tempdir)
254
255 def test_rmtree_win(self):
256 # Mock our sleep for faster test case execution.
257 sleeps = []
258 self.mock(time, 'sleep', sleeps.append)
259 self.mock(sys, 'stderr', StringIO.StringIO())
260
261 # Open a child process, so the file is locked.
262 subdir = os.path.join(self.tempdir, 'to_be_deleted')
263 os.mkdir(subdir)
264 script = 'import time; open(\'a\', \'w\'); time.sleep(60)'
265 proc = subprocess.Popen([sys.executable, '-c', script], cwd=subdir)
266 try:
267 # Wait until the file exist.
268 while not os.path.isfile(os.path.join(subdir, 'a')):
269 self.assertEqual(None, proc.poll())
270 file_path.rmtree(subdir)
271 self.assertEqual([2, 4, 2], sleeps)
272 # sys.stderr.getvalue() would return a fair amount of output but it is
273 # not completely deterministic so we're not testing it here.
274 finally:
275 proc.wait()
276
Marc-Antoine Ruela275b292014-11-25 15:17:21 -0500277 def test_filter_processes_dir_win(self):
278 python_dir = os.path.dirname(sys.executable)
279 processes = file_path.filter_processes_dir_win(
280 file_path.enum_processes_win(), python_dir)
281 self.assertTrue(processes)
282 proc_names = [proc.ExecutablePath for proc in processes]
283 # Try to find at least one python process.
284 self.assertTrue(
285 any(proc == sys.executable for proc in proc_names), proc_names)
286
287 def test_filter_processes_tree_win(self):
288 # Create a grand-child.
289 script = (
290 'import subprocess,sys;'
291 'proc = subprocess.Popen('
292 '[sys.executable, \'-u\', \'-c\', \'import time; print(1); '
293 'time.sleep(60)\'], stdout=subprocess.PIPE); '
294 # Signal grand child is ready.
295 'print(proc.stdout.read(1)); '
296 # Wait for parent to have completed the test.
297 'sys.stdin.read(1); '
298 'proc.kill()'
299 )
300 proc = subprocess.Popen(
301 [sys.executable, '-u', '-c', script],
302 stdin=subprocess.PIPE,
303 stdout=subprocess.PIPE)
304 try:
305 proc.stdout.read(1)
306 processes = file_path.filter_processes_tree_win(
307 file_path.enum_processes_win())
308 self.assertEqual(3, len(processes), processes)
309 proc.stdin.write('a')
310 proc.wait()
311 except Exception:
312 proc.kill()
313 finally:
314 proc.wait()
315
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000316 if sys.platform != 'win32':
317 def test_symlink(self):
318 # This test will fail if the checkout is in a symlink.
319 actual = file_path.split_at_symlink(None, ROOT_DIR)
320 expected = (ROOT_DIR, None, None)
321 self.assertEqual(expected, actual)
322
323 actual = file_path.split_at_symlink(
324 None, os.path.join(BASE_DIR, 'trace_inputs'))
325 expected = (
326 os.path.join(BASE_DIR, 'trace_inputs'), None, None)
327 self.assertEqual(expected, actual)
328
329 actual = file_path.split_at_symlink(
330 None, os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
331 expected = (
332 os.path.join(BASE_DIR, 'trace_inputs'), 'files2', '')
333 self.assertEqual(expected, actual)
334
335 actual = file_path.split_at_symlink(
336 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2'))
337 expected = (
338 os.path.join('tests', 'trace_inputs'), 'files2', '')
339 self.assertEqual(expected, actual)
340 actual = file_path.split_at_symlink(
341 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2', 'bar'))
342 expected = (
343 os.path.join('tests', 'trace_inputs'), 'files2', '/bar')
344 self.assertEqual(expected, actual)
345
346 def test_native_case_symlink_right_case(self):
347 actual = file_path.get_native_path_case(
348 os.path.join(BASE_DIR, 'trace_inputs'))
349 self.assertEqual('trace_inputs', os.path.basename(actual))
350
351 # Make sure the symlink is not resolved.
352 actual = file_path.get_native_path_case(
353 os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
354 self.assertEqual('files2', os.path.basename(actual))
355
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000356
357if __name__ == '__main__':
358 logging.basicConfig(
359 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
360 if '-v' in sys.argv:
361 unittest.TestCase.maxDiff = None
362 unittest.main()