Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / test / chromedriver / util.py
blobb28502af483216d8c65e85310d0e55c2db5383e5
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Generic utilities for all python scripts."""
7 import atexit
8 import httplib
9 import os
10 import signal
11 import stat
12 import subprocess
13 import sys
14 import tempfile
15 import urlparse
16 import zipfile
19 def GetPlatformName():
20 """Return a string to be used in paths for the platform."""
21 if IsWindows():
22 return 'win'
23 if IsMac():
24 return 'mac'
25 if IsLinux():
26 return 'linux'
27 raise NotImplementedError('Unknown platform "%s".' % sys.platform)
30 def IsWindows():
31 return sys.platform == 'cygwin' or sys.platform.startswith('win')
34 def IsLinux():
35 return sys.platform.startswith('linux')
38 def IsMac():
39 return sys.platform.startswith('darwin')
42 def _DeleteDir(path):
43 """Deletes a directory recursively, which must exist."""
44 # Don't use shutil.rmtree because it can't delete read-only files on Win.
45 for root, dirs, files in os.walk(path, topdown=False):
46 for name in files:
47 filename = os.path.join(root, name)
48 os.chmod(filename, stat.S_IWRITE)
49 os.remove(filename)
50 for name in dirs:
51 os.rmdir(os.path.join(root, name))
52 os.rmdir(path)
55 def Delete(path):
56 """Deletes the given file or directory (recursively), which must exist."""
57 if os.path.isdir(path):
58 _DeleteDir(path)
59 else:
60 os.remove(path)
63 def MaybeDelete(path):
64 """Deletes the given file or directory (recurisvely), if it exists."""
65 if os.path.exists(path):
66 Delete(path)
69 def MakeTempDir(parent_dir=None):
70 """Creates a temporary directory and returns an absolute path to it.
72 The temporary directory is automatically deleted when the python interpreter
73 exits normally.
75 Args:
76 parent_dir: the directory to create the temp dir in. If None, the system
77 temp dir is used.
79 Returns:
80 The absolute path to the temporary directory.
81 """
82 path = tempfile.mkdtemp(dir=parent_dir)
83 atexit.register(MaybeDelete, path)
84 return path
87 def Zip(path):
88 """Zips the given path and returns the zipped file."""
89 zip_path = os.path.join(MakeTempDir(), 'build.zip')
90 f = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
91 f.write(path, os.path.basename(path))
92 f.close()
93 return zip_path
96 def Unzip(zip_path, output_dir):
97 """Unzips the given zip file using a system installed unzip tool.
99 Args:
100 zip_path: zip file to unzip.
101 output_dir: directory to unzip the contents of the zip file. The directory
102 must exist.
104 Raises:
105 RuntimeError if the unzip operation fails.
107 if IsWindows():
108 unzip_cmd = ['C:\\Program Files\\7-Zip\\7z.exe', 'x', '-y']
109 else:
110 unzip_cmd = ['unzip', '-o']
111 unzip_cmd += [zip_path]
112 if RunCommand(unzip_cmd, output_dir) != 0:
113 raise RuntimeError('Unable to unzip %s to %s' % (zip_path, output_dir))
116 def Kill(pid):
117 """Terminate the given pid."""
118 if IsWindows():
119 subprocess.call(['taskkill.exe', '/T', '/F', '/PID', str(pid)])
120 else:
121 os.kill(pid, signal.SIGTERM)
124 def RunCommand(cmd, cwd=None):
125 """Runs the given command and returns the exit code.
127 Args:
128 cmd: list of command arguments.
129 cwd: working directory to execute the command, or None if the current
130 working directory should be used.
132 Returns:
133 The exit code of the command.
135 sys.stdout.flush()
136 process = subprocess.Popen(cmd, cwd=cwd)
137 process.wait()
138 sys.stdout.flush()
139 return process.returncode
142 def DoesUrlExist(url):
143 """Determines whether a resource exists at the given URL.
145 Args:
146 url: URL to be verified.
148 Returns:
149 True if url exists, otherwise False.
151 parsed = urlparse.urlparse(url)
152 try:
153 conn = httplib.HTTPConnection(parsed.netloc)
154 conn.request('HEAD', parsed.path)
155 response = conn.getresponse()
156 except (socket.gaierror, socket.error):
157 return False
158 finally:
159 conn.close()
160 # Follow both permanent (301) and temporary (302) redirects.
161 if response.status == 302 or response.status == 301:
162 return DoesUrlExist(response.getheader('location'))
163 return response.status == 200
166 def MarkBuildStepStart(name):
167 print '@@@BUILD_STEP %s@@@' % name
168 sys.stdout.flush()
171 def MarkBuildStepError():
172 print '@@@STEP_FAILURE@@@'
173 sys.stdout.flush()
176 def AddBuildStepText(text):
177 print '@@@STEP_TEXT@%s@@@' % text
178 sys.stdout.flush()
181 def PrintAndFlush(text):
182 print text
183 sys.stdout.flush()
186 def AddLink(label, url):
187 """Adds a link with name |label| linking to |url| to current buildbot step.
189 Args:
190 label: A string with the name of the label.
191 url: A string of the URL.
193 print '@@@STEP_LINK@%s@%s@@@' % (label, url)