blob: d8fbcb34dd6e8379414835f89d1c72f4674effb7 [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:
52 self._tempdir = tempfile.mkdtemp(prefix='run_isolated_test')
53 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
161 if sys.platform == 'darwin':
162 def test_native_case_symlink_wrong_case(self):
163 base_dir = file_path.get_native_path_case(BASE_DIR)
164 trace_inputs_dir = os.path.join(base_dir, 'trace_inputs')
165 actual = file_path.get_native_path_case(trace_inputs_dir)
166 self.assertEqual(trace_inputs_dir, actual)
167
168 # Make sure the symlink is not resolved.
169 data = os.path.join(trace_inputs_dir, 'Files2')
170 actual = file_path.get_native_path_case(data)
171 self.assertEqual(
172 os.path.join(trace_inputs_dir, 'files2'), actual)
173
174 data = os.path.join(trace_inputs_dir, 'Files2', '')
175 actual = file_path.get_native_path_case(data)
176 self.assertEqual(
177 os.path.join(trace_inputs_dir, 'files2', ''), actual)
178
179 data = os.path.join(trace_inputs_dir, 'Files2', 'Child1.py')
180 actual = file_path.get_native_path_case(data)
181 # TODO(maruel): Should be child1.py.
182 self.assertEqual(
183 os.path.join(trace_inputs_dir, 'files2', 'Child1.py'), actual)
184
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000185 if sys.platform in ('darwin', 'win32'):
186 def test_native_case_not_sensitive(self):
187 # The home directory is almost guaranteed to have mixed upper/lower case
188 # letters on both Windows and OSX.
189 # This test also ensures that the output is independent on the input
190 # string case.
191 path = os.path.expanduser(u'~')
192 self.assertTrue(os.path.isdir(path))
193 path = path.replace('/', os.path.sep)
194 if sys.platform == 'win32':
195 # Make sure the drive letter is upper case for consistency.
196 path = path[0].upper() + path[1:]
197 # This test assumes the variable is in the native path case on disk, this
198 # should be the case. Verify this assumption:
199 self.assertEqual(path, file_path.get_native_path_case(path))
200 self.assertEqual(
201 file_path.get_native_path_case(path.lower()),
202 file_path.get_native_path_case(path.upper()))
203
204 def test_native_case_not_sensitive_non_existent(self):
205 # This test also ensures that the output is independent on the input
206 # string case.
207 non_existing = os.path.join(
208 'trace_input_test_this_dir_should_not_exist', 'really not', '')
209 path = os.path.expanduser(os.path.join(u'~', non_existing))
210 path = path.replace('/', os.path.sep)
211 self.assertFalse(os.path.exists(path))
212 lower = file_path.get_native_path_case(path.lower())
213 upper = file_path.get_native_path_case(path.upper())
214 # Make sure non-existing element is not modified:
215 self.assertTrue(lower.endswith(non_existing.lower()))
216 self.assertTrue(upper.endswith(non_existing.upper()))
217 self.assertEqual(lower[:-len(non_existing)], upper[:-len(non_existing)])
218
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400219 if sys.platform == 'win32':
220 def test_native_case_alternate_datastream(self):
221 # Create the file manually, since tempfile doesn't support ADS.
222 tempdir = unicode(tempfile.mkdtemp(prefix='trace_inputs'))
223 try:
224 tempdir = file_path.get_native_path_case(tempdir)
225 basename = 'foo.txt'
226 filename = basename + ':Zone.Identifier'
227 filepath = os.path.join(tempdir, filename)
228 open(filepath, 'w').close()
229 self.assertEqual(filepath, file_path.get_native_path_case(filepath))
230 data_suffix = ':$DATA'
231 self.assertEqual(
232 filepath + data_suffix,
233 file_path.get_native_path_case(filepath + data_suffix))
234
235 open(filepath + '$DATA', 'w').close()
236 self.assertEqual(
237 filepath + data_suffix,
238 file_path.get_native_path_case(filepath + data_suffix))
239 # Ensure the ADS weren't created as separate file. You love NTFS, don't
240 # you?
241 self.assertEqual([basename], os.listdir(tempdir))
242 finally:
243 shutil.rmtree(tempdir)
244
245 def test_rmtree_win(self):
246 # Mock our sleep for faster test case execution.
247 sleeps = []
248 self.mock(time, 'sleep', sleeps.append)
249 self.mock(sys, 'stderr', StringIO.StringIO())
250
251 # Open a child process, so the file is locked.
252 subdir = os.path.join(self.tempdir, 'to_be_deleted')
253 os.mkdir(subdir)
254 script = 'import time; open(\'a\', \'w\'); time.sleep(60)'
255 proc = subprocess.Popen([sys.executable, '-c', script], cwd=subdir)
256 try:
257 # Wait until the file exist.
258 while not os.path.isfile(os.path.join(subdir, 'a')):
259 self.assertEqual(None, proc.poll())
260 file_path.rmtree(subdir)
261 self.assertEqual([2, 4, 2], sleeps)
262 # sys.stderr.getvalue() would return a fair amount of output but it is
263 # not completely deterministic so we're not testing it here.
264 finally:
265 proc.wait()
266
Marc-Antoine Ruela275b292014-11-25 15:17:21 -0500267 def test_filter_processes_dir_win(self):
268 python_dir = os.path.dirname(sys.executable)
269 processes = file_path.filter_processes_dir_win(
270 file_path.enum_processes_win(), python_dir)
271 self.assertTrue(processes)
272 proc_names = [proc.ExecutablePath for proc in processes]
273 # Try to find at least one python process.
274 self.assertTrue(
275 any(proc == sys.executable for proc in proc_names), proc_names)
276
277 def test_filter_processes_tree_win(self):
278 # Create a grand-child.
279 script = (
280 'import subprocess,sys;'
281 'proc = subprocess.Popen('
282 '[sys.executable, \'-u\', \'-c\', \'import time; print(1); '
283 'time.sleep(60)\'], stdout=subprocess.PIPE); '
284 # Signal grand child is ready.
285 'print(proc.stdout.read(1)); '
286 # Wait for parent to have completed the test.
287 'sys.stdin.read(1); '
288 'proc.kill()'
289 )
290 proc = subprocess.Popen(
291 [sys.executable, '-u', '-c', script],
292 stdin=subprocess.PIPE,
293 stdout=subprocess.PIPE)
294 try:
295 proc.stdout.read(1)
296 processes = file_path.filter_processes_tree_win(
297 file_path.enum_processes_win())
298 self.assertEqual(3, len(processes), processes)
299 proc.stdin.write('a')
300 proc.wait()
301 except Exception:
302 proc.kill()
303 finally:
304 proc.wait()
305
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000306 if sys.platform != 'win32':
307 def test_symlink(self):
308 # This test will fail if the checkout is in a symlink.
309 actual = file_path.split_at_symlink(None, ROOT_DIR)
310 expected = (ROOT_DIR, None, None)
311 self.assertEqual(expected, actual)
312
313 actual = file_path.split_at_symlink(
314 None, os.path.join(BASE_DIR, 'trace_inputs'))
315 expected = (
316 os.path.join(BASE_DIR, 'trace_inputs'), None, None)
317 self.assertEqual(expected, actual)
318
319 actual = file_path.split_at_symlink(
320 None, os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
321 expected = (
322 os.path.join(BASE_DIR, 'trace_inputs'), 'files2', '')
323 self.assertEqual(expected, actual)
324
325 actual = file_path.split_at_symlink(
326 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2'))
327 expected = (
328 os.path.join('tests', 'trace_inputs'), 'files2', '')
329 self.assertEqual(expected, actual)
330 actual = file_path.split_at_symlink(
331 ROOT_DIR, os.path.join('tests', 'trace_inputs', 'files2', 'bar'))
332 expected = (
333 os.path.join('tests', 'trace_inputs'), 'files2', '/bar')
334 self.assertEqual(expected, actual)
335
336 def test_native_case_symlink_right_case(self):
337 actual = file_path.get_native_path_case(
338 os.path.join(BASE_DIR, 'trace_inputs'))
339 self.assertEqual('trace_inputs', os.path.basename(actual))
340
341 # Make sure the symlink is not resolved.
342 actual = file_path.get_native_path_case(
343 os.path.join(BASE_DIR, 'trace_inputs', 'files2'))
344 self.assertEqual('files2', os.path.basename(actual))
345
maruel@chromium.org561d4b22013-09-26 21:08:08 +0000346
347if __name__ == '__main__':
348 logging.basicConfig(
349 level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
350 if '-v' in sys.argv:
351 unittest.TestCase.maxDiff = None
352 unittest.main()