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