Refactoring benchmark runner script to follow pep8 code style.
authorcommit-queue@webkit.org <commit-queue@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 24 Jun 2015 02:13:24 +0000 (02:13 +0000)
committercommit-queue@webkit.org <commit-queue@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 24 Jun 2015 02:13:24 +0000 (02:13 +0000)
https://bugs.webkit.org/show_bug.cgi?id=146264

Patch by Dewei Zhu <dewei_zhu@apple.com> on 2015-06-23
Reviewed by Ryosuke Niwa.

Refactor benchmark runner script to follow pep8 code style.

* Scripts/webkitpy/benchmark_runner/benchmark_builder/generic_benchmark_builder.py:
(GenericBenchmarkBuilder.prepare):
(GenericBenchmarkBuilder._run_create_script):
(GenericBenchmarkBuilder._copy_benchmark_to_temp_dir):
(GenericBenchmarkBuilder._fetch_remote_archive):
(GenericBenchmarkBuilder):
(GenericBenchmarkBuilder._checkout_with_subversion):
(GenericBenchmarkBuilder._apply_patch):
(GenericBenchmarkBuilder.clean):
(GenericBenchmarkBuilder._runCreateScript): Deleted.
(GenericBenchmarkBuilder._copyBenchmarkToTempDir): Deleted.
(GenericBenchmarkBuilder._fetchRemoteArchive): Deleted.
(GenericBenchmarkBuilder._checkoutWithSubverion): Deleted.
(GenericBenchmarkBuilder._applyPatch): Deleted.
* Scripts/webkitpy/benchmark_runner/benchmark_runner.py:
(BenchmarkRunner.__init__):
(BenchmarkRunner._find_plan_file):
(BenchmarkRunner.execute):
(BenchmarkRunner._cleanup):
(BenchmarkRunner._dump):
(BenchmarkRunner._wrap):
(BenchmarkRunner._merge):
(BenchmarkRunner._show_results):
(BenchmarkRunner._findPlanFile): Deleted.
(BenchmarkRunner.cleanup): Deleted.
(BenchmarkRunner.dump): Deleted.
(BenchmarkRunner.wrap): Deleted.
(BenchmarkRunner.merge): Deleted.
(BenchmarkRunner.show_results): Deleted.
* Scripts/webkitpy/benchmark_runner/browser_driver/browser_driver.py:
(BrowserDriver.prepare_env):
(BrowserDriver.launch_url):
(BrowserDriver.close_browsers):
(BrowserDriver.prepareEnv): Deleted.
(BrowserDriver.launchUrl): Deleted.
(BrowserDriver.closeBrowser): Deleted.
* Scripts/webkitpy/benchmark_runner/browser_driver/osx_browser_driver.py:
(OSXBrowserDriver):
(OSXBrowserDriver.prepare_env):
(OSXBrowserDriver.close_browsers):
(OSXBrowserDriver._launch_process):
(OSXBrowserDriver._terminiate_processes):
(OSXBrowserDriver._launch_process_with_caffinate):
(OSXBrowserDriver._screen_size):
(OSXBrowserDriver.prepareEnv): Deleted.
(OSXBrowserDriver.closeBrowsers): Deleted.
(OSXBrowserDriver.launchProcess): Deleted.
(OSXBrowserDriver.terminateProcesses): Deleted.
(OSXBrowserDriver.launchProcessWithCaffinate): Deleted.
(OSXBrowserDriver.screenSize): Deleted.
* Scripts/webkitpy/benchmark_runner/browser_driver/osx_chrome_driver.py:
(OSXChromeDriver):
(OSXChromeDriver.launch_url):
(OSXChromeCanaryDriver):
(OSXChromeCanaryDriver.launch_url):
(OSXChromeDriver.launchUrl): Deleted.
(OSXChromeCanaryDriver.launchUrl): Deleted.
* Scripts/webkitpy/benchmark_runner/browser_driver/osx_firefox_driver.py:
(OSXFirefoxDriver):
(OSXFirefoxDriver.launch_url):
(OSXFirefoxNightlyDriver):
(OSXFirefoxNightlyDriver.launch_url):
(OSXFirefoxDriver.launchUrl): Deleted.
(OSXFirefoxNightlyDriver.launchUrl): Deleted.
* Scripts/webkitpy/benchmark_runner/browser_driver/osx_safari_driver.py:
(OSXSafariDriver):
(OSXSafariDriver.prepare_env):
(OSXSafariDriver.launch_url):
(OSXSafariDriver.close_browsers):
(OSXSafariDriver._maximize_window):
(OSXSafariDriver.prepareEnv): Deleted.
(OSXSafariDriver.launchUrl): Deleted.
(OSXSafariDriver.closeBrowsers): Deleted.
(OSXSafariDriver.maximizeWindow): Deleted.
* Scripts/webkitpy/benchmark_runner/http_server_driver/http_server_driver.py:
(HTTPServerDriver.fetch_result):
(HTTPServerDriver.kill_server):
(HTTPServerDriver.get_return_code):
(HTTPServerDriver.set_device_id):
(HTTPServerDriver.fetchResult): Deleted.
(HTTPServerDriver.killServer): Deleted.
(HTTPServerDriver.getReturnCode): Deleted.
(HTTPServerDriver.setDeviceID): Deleted.
* Scripts/webkitpy/benchmark_runner/http_server_driver/simple_http_server_driver.py:
(SimpleHTTPServerDriver.serve):
(SimpleHTTPServerDriver.base_url):
(SimpleHTTPServerDriver.fetch_result):
(SimpleHTTPServerDriver.kill_server):
(SimpleHTTPServerDriver.get_return_code):
(SimpleHTTPServerDriver): Deleted.
(SimpleHTTPServerDriver.baseUrl): Deleted.
(SimpleHTTPServerDriver.fetchResult): Deleted.
(SimpleHTTPServerDriver.killServer): Deleted.
(SimpleHTTPServerDriver.getReturnCode): Deleted.
* Scripts/webkitpy/benchmark_runner/utils.py:
(get_path_from_project_root):
(force_remove):
(getPathFromProjectRoot): Deleted.
(forceRemove): Deleted.

git-svn-id: http://svn.webkit.org/repository/webkit/trunk@185898 268f45cc-cd09-0410-ab3c-d52691b4dbfc

Tools/ChangeLog
Tools/Scripts/webkitpy/benchmark_runner/benchmark_builder/generic_benchmark_builder.py
Tools/Scripts/webkitpy/benchmark_runner/benchmark_runner.py
Tools/Scripts/webkitpy/benchmark_runner/browser_driver/browser_driver.py
Tools/Scripts/webkitpy/benchmark_runner/browser_driver/osx_browser_driver.py
Tools/Scripts/webkitpy/benchmark_runner/browser_driver/osx_chrome_driver.py
Tools/Scripts/webkitpy/benchmark_runner/browser_driver/osx_firefox_driver.py
Tools/Scripts/webkitpy/benchmark_runner/browser_driver/osx_safari_driver.py
Tools/Scripts/webkitpy/benchmark_runner/http_server_driver/http_server_driver.py
Tools/Scripts/webkitpy/benchmark_runner/http_server_driver/simple_http_server_driver.py
Tools/Scripts/webkitpy/benchmark_runner/utils.py

index b1bfecccc40280bc712228cf69485386ad8c9eb7..50b06f27a45fb3ba8f79878a1ea5b3aea845af4b 100644 (file)
@@ -1,3 +1,112 @@
+2015-06-23  Dewei Zhu  <dewei_zhu@apple.com>
+
+        Refactoring benchmark runner script to follow pep8 code style.
+        https://bugs.webkit.org/show_bug.cgi?id=146264
+
+        Reviewed by Ryosuke Niwa.
+
+        Refactor benchmark runner script to follow pep8 code style.
+
+        * Scripts/webkitpy/benchmark_runner/benchmark_builder/generic_benchmark_builder.py:
+        (GenericBenchmarkBuilder.prepare):
+        (GenericBenchmarkBuilder._run_create_script):
+        (GenericBenchmarkBuilder._copy_benchmark_to_temp_dir):
+        (GenericBenchmarkBuilder._fetch_remote_archive):
+        (GenericBenchmarkBuilder):
+        (GenericBenchmarkBuilder._checkout_with_subversion):
+        (GenericBenchmarkBuilder._apply_patch):
+        (GenericBenchmarkBuilder.clean):
+        (GenericBenchmarkBuilder._runCreateScript): Deleted.
+        (GenericBenchmarkBuilder._copyBenchmarkToTempDir): Deleted.
+        (GenericBenchmarkBuilder._fetchRemoteArchive): Deleted.
+        (GenericBenchmarkBuilder._checkoutWithSubverion): Deleted.
+        (GenericBenchmarkBuilder._applyPatch): Deleted.
+        * Scripts/webkitpy/benchmark_runner/benchmark_runner.py:
+        (BenchmarkRunner.__init__):
+        (BenchmarkRunner._find_plan_file):
+        (BenchmarkRunner.execute):
+        (BenchmarkRunner._cleanup):
+        (BenchmarkRunner._dump):
+        (BenchmarkRunner._wrap):
+        (BenchmarkRunner._merge):
+        (BenchmarkRunner._show_results):
+        (BenchmarkRunner._findPlanFile): Deleted.
+        (BenchmarkRunner.cleanup): Deleted.
+        (BenchmarkRunner.dump): Deleted.
+        (BenchmarkRunner.wrap): Deleted.
+        (BenchmarkRunner.merge): Deleted.
+        (BenchmarkRunner.show_results): Deleted.
+        * Scripts/webkitpy/benchmark_runner/browser_driver/browser_driver.py:
+        (BrowserDriver.prepare_env):
+        (BrowserDriver.launch_url):
+        (BrowserDriver.close_browsers):
+        (BrowserDriver.prepareEnv): Deleted.
+        (BrowserDriver.launchUrl): Deleted.
+        (BrowserDriver.closeBrowser): Deleted.
+        * Scripts/webkitpy/benchmark_runner/browser_driver/osx_browser_driver.py:
+        (OSXBrowserDriver):
+        (OSXBrowserDriver.prepare_env):
+        (OSXBrowserDriver.close_browsers):
+        (OSXBrowserDriver._launch_process):
+        (OSXBrowserDriver._terminiate_processes):
+        (OSXBrowserDriver._launch_process_with_caffinate):
+        (OSXBrowserDriver._screen_size):
+        (OSXBrowserDriver.prepareEnv): Deleted.
+        (OSXBrowserDriver.closeBrowsers): Deleted.
+        (OSXBrowserDriver.launchProcess): Deleted.
+        (OSXBrowserDriver.terminateProcesses): Deleted.
+        (OSXBrowserDriver.launchProcessWithCaffinate): Deleted.
+        (OSXBrowserDriver.screenSize): Deleted.
+        * Scripts/webkitpy/benchmark_runner/browser_driver/osx_chrome_driver.py:
+        (OSXChromeDriver):
+        (OSXChromeDriver.launch_url):
+        (OSXChromeCanaryDriver):
+        (OSXChromeCanaryDriver.launch_url):
+        (OSXChromeDriver.launchUrl): Deleted.
+        (OSXChromeCanaryDriver.launchUrl): Deleted.
+        * Scripts/webkitpy/benchmark_runner/browser_driver/osx_firefox_driver.py:
+        (OSXFirefoxDriver):
+        (OSXFirefoxDriver.launch_url):
+        (OSXFirefoxNightlyDriver):
+        (OSXFirefoxNightlyDriver.launch_url):
+        (OSXFirefoxDriver.launchUrl): Deleted.
+        (OSXFirefoxNightlyDriver.launchUrl): Deleted.
+        * Scripts/webkitpy/benchmark_runner/browser_driver/osx_safari_driver.py:
+        (OSXSafariDriver):
+        (OSXSafariDriver.prepare_env):
+        (OSXSafariDriver.launch_url):
+        (OSXSafariDriver.close_browsers):
+        (OSXSafariDriver._maximize_window):
+        (OSXSafariDriver.prepareEnv): Deleted.
+        (OSXSafariDriver.launchUrl): Deleted.
+        (OSXSafariDriver.closeBrowsers): Deleted.
+        (OSXSafariDriver.maximizeWindow): Deleted.
+        * Scripts/webkitpy/benchmark_runner/http_server_driver/http_server_driver.py:
+        (HTTPServerDriver.fetch_result):
+        (HTTPServerDriver.kill_server):
+        (HTTPServerDriver.get_return_code):
+        (HTTPServerDriver.set_device_id):
+        (HTTPServerDriver.fetchResult): Deleted.
+        (HTTPServerDriver.killServer): Deleted.
+        (HTTPServerDriver.getReturnCode): Deleted.
+        (HTTPServerDriver.setDeviceID): Deleted.
+        * Scripts/webkitpy/benchmark_runner/http_server_driver/simple_http_server_driver.py:
+        (SimpleHTTPServerDriver.serve):
+        (SimpleHTTPServerDriver.base_url):
+        (SimpleHTTPServerDriver.fetch_result):
+        (SimpleHTTPServerDriver.kill_server):
+        (SimpleHTTPServerDriver.get_return_code):
+        (SimpleHTTPServerDriver): Deleted.
+        (SimpleHTTPServerDriver.baseUrl): Deleted.
+        (SimpleHTTPServerDriver.fetchResult): Deleted.
+        (SimpleHTTPServerDriver.killServer): Deleted.
+        (SimpleHTTPServerDriver.getReturnCode): Deleted.
+        * Scripts/webkitpy/benchmark_runner/utils.py:
+        (get_path_from_project_root):
+        (force_remove):
+        (getPathFromProjectRoot): Deleted.
+        (forceRemove): Deleted.
+
 2015-06-23  Anders Carlsson  <andersca@apple.com>
 
         Add operator! and copy/move constructors to WeakObjCPtr
index 69e4e68521f54c59a52fc83cb2192f0701ed98f6..272ada408e9696ee4774ace0bf9c7c5e01febe38 100644 (file)
@@ -8,7 +8,7 @@ import shutil
 import subprocess
 
 from zipfile import ZipFile
-from webkitpy.benchmark_runner.utils import getPathFromProjectRoot, forceRemove
+from webkitpy.benchmark_runner.utils import get_path_from_project_root, force_remove
 
 
 _log = logging.getLogger(__name__)
@@ -19,71 +19,71 @@ class GenericBenchmarkBuilder(object):
     builder_name = 'GenericBenchmarkBuilder'
 
     def prepare(self, name, plan):
-        self.name = name
-        self.webRoot = tempfile.mkdtemp()
-        self.dest = os.path.join(self.webRoot, self.name)
+        self._name = name
+        self._web_root = tempfile.mkdtemp()
+        self._dest = os.path.join(self._web_root, self._name)
         if 'local_copy' in plan:
-            self._copyBenchmarkToTempDir(plan['local_copy'])
+            self._copy_benchmark_to_temp_dir(plan['local_copy'])
         elif 'remote_archive' in plan:
-            self._fetchRemoteArchive(plan['remote_archive'])
+            self._fetch_remote_archive(plan['remote_archive'])
         elif 'svn_source' in plan:
-            self._checkoutWithSubverion(plan['svn_source'])
+            self._checkout_with_subversion(plan['svn_source'])
         else:
             raise Exception('The benchmark location was not specified')
 
-        _log.info('Copied the benchmark into: %s' % self.dest)
+        _log.info('Copied the benchmark into: %s' % self._dest)
         try:
             if 'create_script' in plan:
-                self._runCreateScript(plan['create_script'])
+                self._run_create_script(plan['create_script'])
             if 'benchmark_patch' in plan:
-                self._applyPatch(plan['benchmark_patch'])
-            return self.webRoot
+                self._apply_patch(plan['benchmark_patch'])
+            return self._web_root
         except Exception:
             self.clean()
             raise
 
-    def _runCreateScript(self, createScript):
-        oldWorkingDirectory = os.getcwd()
-        os.chdir(self.dest)
-        _log.debug('Running %s in %s' % (createScript, self.dest))
-        errorCode = subprocess.call(createScript)
-        os.chdir(oldWorkingDirectory)
-        if errorCode:
-            raise Exception('Cannot create the benchmark - Error: %s' % errorCode)
-
-    def _copyBenchmarkToTempDir(self, benchmarkPath):
-        shutil.copytree(getPathFromProjectRoot(benchmarkPath), self.dest)
-
-    def _fetchRemoteArchive(self, archiveURL):
-        archivePath = os.path.join(self.webRoot, 'archive.zip')
-        _log.info('Downloading %s to %s' % (archiveURL, archivePath))
-        urllib.urlretrieve(archiveURL, archivePath)
-
-        with ZipFile(archivePath, 'r') as archive:
-            archive.extractall(self.dest)
-
-        unarchivedFiles = filter(lambda name: not name.startswith('.'), os.listdir(self.dest))
-        if len(unarchivedFiles) == 1:
-            firstFile = os.path.join(self.dest, unarchivedFiles[0])
-            if os.path.isdir(firstFile):
-                shutil.move(firstFile, self.webRoot)
-                os.rename(os.path.join(self.webRoot, unarchivedFiles[0]), self.dest)
-
-    def _checkoutWithSubverion(self, subversionURL):
-        _log.info('Checking out %s to %s' % (subversionURL, self.dest))
-        errorCode = subprocess.call(['svn', 'checkout', subversionURL, self.dest])
-        if errorCode:
-            raise Exception('Cannot checkout the benchmark - Error: %s' % errorCode)
-
-    def _applyPatch(self, patch):
-        oldWorkingDirectory = os.getcwd()
-        os.chdir(self.dest)
-        errorCode = subprocess.call(['patch', '-p1', '-f', '-i', getPathFromProjectRoot(patch)])
-        os.chdir(oldWorkingDirectory)
-        if errorCode:
-            raise Exception('Cannot apply patch, will skip current benchmarkPath - Error: %s' % errorCode)
+    def _run_create_script(self, create_script):
+        old_working_directory = os.getcwd()
+        os.chdir(self._dest)
+        _log.debug('Running %s in %s' % (create_script, self._dest))
+        error_code = subprocess.call(create_script)
+        os.chdir(old_working_directory)
+        if error_code:
+            raise Exception('Cannot create the benchmark - Error: %s' % error_code)
+
+    def _copy_benchmark_to_temp_dir(self, benchmark_path):
+        shutil.copytree(get_path_from_project_root(benchmark_path), self._dest)
+
+    def _fetch_remote_archive(self, archive_url):
+        archive_path = os.path.join(self._web_root, 'archive.zip')
+        _log.info('Downloading %s to %s' % (archive_url, archive_path))
+        urllib.urlretrieve(archive_url, archive_path)
+
+        with ZipFile(archive_path, 'r') as archive:
+            archive.extractall(self._dest)
+
+        unarchived_files = filter(lambda name: not name.startswith('.'), os.listdir(self._dest))
+        if len(unarchived_files) == 1:
+            first_file = os.path.join(self._dest, unarchived_files[0])
+            if os.path.isdir(first_file):
+                shutil.move(first_file, self._web_root)
+                os.rename(os.path.join(self._web_root, unarchived_files[0]), self._dest)
+
+    def _checkout_with_subversion(self, subversion_url):
+        _log.info('Checking out %s to %s' % (subversion_url, self._dest))
+        error_code = subprocess.call(['svn', 'checkout', subversion_url, self._dest])
+        if error_code:
+            raise Exception('Cannot checkout the benchmark - Error: %s' % error_code)
+
+    def _apply_patch(self, patch):
+        old_working_directory = os.getcwd()
+        os.chdir(self._dest)
+        error_code = subprocess.call(['patch', '-p1', '-f', '-i', get_path_from_project_root(patch)])
+        os.chdir(old_working_directory)
+        if error_code:
+            raise Exception('Cannot apply patch, will skip current benchmark_path - Error: %s' % error_code)
 
     def clean(self):
         _log.info('Cleaning Benchmark')
-        if self.webRoot:
-            forceRemove(self.webRoot)
+        if self._web_root:
+            force_remove(self._web_root)
index 810507256f820f9d40d250a35b92596d1ba60537..c1d2b66a9fe98317fb0647cb985326fe8a1b37bc 100644 (file)
@@ -16,7 +16,6 @@ from benchmark_builder.benchmark_builder_factory import BenchmarkBuilderFactory
 from benchmark_results import BenchmarkResults
 from browser_driver.browser_driver_factory import BrowserDriverFactory
 from http_server_driver.http_server_driver_factory import HTTPServerDriverFactory
-from utils import getPathFromProjectRoot
 from utils import timeout
 
 
@@ -25,116 +24,116 @@ _log = logging.getLogger(__name__)
 
 class BenchmarkRunner(object):
 
-    def __init__(self, planFile, localCopy, countOverride, buildDir, outputFile, platform, browser, httpServerDriverOverride=None, deviceID=None):
+    def __init__(self, plan_file, local_copy, count_override, build_dir, output_file, platform, browser, http_server_driver_override=None, device_id=None):
         try:
-            planFile = self._findPlanFile(planFile)
-            with open(planFile, 'r') as fp:
-                self.planName = os.path.split(os.path.splitext(planFile)[0])[1]
-                self.plan = json.load(fp)
-                if localCopy:
-                    self.plan['local_copy'] = localCopy
-                if countOverride:
-                    self.plan['count'] = countOverride
-                if httpServerDriverOverride:
-                    self.plan['http_server_driver'] = httpServerDriverOverride
-                self.browserDriver = BrowserDriverFactory.create(platform, browser)
-                self.httpServerDriver = HTTPServerDriverFactory.create(self.plan['http_server_driver'])
-                self.httpServerDriver.setDeviceID(deviceID)
-                self.buildDir = os.path.abspath(buildDir) if buildDir else None
-                self.outputFile = outputFile
-                self.deviceID = deviceID
+            plan_file = self._find_plan_file(plan_file)
+            with open(plan_file, 'r') as fp:
+                self._plan_name = os.path.split(os.path.splitext(plan_file)[0])[1]
+                self._plan = json.load(fp)
+                if local_copy:
+                    self._plan['local_copy'] = local_copy
+                if count_override:
+                    self._plan['count'] = count_override
+                if http_server_driver_override:
+                    self._plan['http_server_driver'] = http_server_driver_override
+                self._browser_driver = BrowserDriverFactory.create(platform, browser)
+                self._http_server_driver = HTTPServerDriverFactory.create(self._plan['http_server_driver'])
+                self._http_server_driver.set_device_id(device_id)
+                self._build_dir = os.path.abspath(build_dir) if build_dir else None
+                self._output_file = output_file
+                self._device_id = device_id
         except IOError as error:
-            _log.error('Can not open plan file: %s - Error %s' % (planFile, error))
+            _log.error('Can not open plan file: %s - Error %s' % (plan_file, error))
             raise error
         except ValueError as error:
-            _log.error('Plan file: %s may not follow JSON format - Error %s' % (planFile, error))
+            _log.error('Plan file: %s may not follow JSON format - Error %s' % (plan_file, error))
             raise error
 
-    def _findPlanFile(self, planFile):
-        if not os.path.exists(planFile):
-            absPath = os.path.join(os.path.dirname(__file__), 'data/plans', planFile)
+    def _find_plan_file(self, plan_file):
+        if not os.path.exists(plan_file):
+            absPath = os.path.join(os.path.dirname(__file__), 'data/plans', plan_file)
             if os.path.exists(absPath):
                 return absPath
             if not absPath.endswith('.plan'):
                 absPath += '.plan'
             if os.path.exists(absPath):
                 return absPath
-        return planFile
+        return plan_file
 
     def execute(self):
         _log.info('Start to execute the plan')
         _log.info('Start a new benchmark')
         results = []
-        self.benchmarkBuilder = BenchmarkBuilderFactory.create(self.plan['benchmark_builder'])
+        self._benchmark_builder = BenchmarkBuilderFactory.create(self._plan['benchmark_builder'])
 
-        webRoot = self.benchmarkBuilder.prepare(self.planName, self.plan)
-        for x in xrange(int(self.plan['count'])):
+        web_root = self._benchmark_builder.prepare(self._plan_name, self._plan)
+        for x in xrange(int(self._plan['count'])):
             _log.info('Start the iteration %d of current benchmark' % (x + 1))
-            self.httpServerDriver.serve(webRoot)
-            self.browserDriver.prepareEnv(self.deviceID)
-            url = urlparse.urljoin(self.httpServerDriver.baseUrl(), self.planName + '/' + self.plan['entry_point'])
-            self.browserDriver.launchUrl(url, self.buildDir)
+            self._http_server_driver.serve(web_root)
+            self._browser_driver.prepare_env(self._device_id)
+            url = urlparse.urljoin(self._http_server_driver.base_url(), self._plan_name + '/' + self._plan['entry_point'])
+            self._browser_driver.launch_url(url, self._build_dir)
             result = None
             try:
-                with timeout(self.plan['timeout']):
-                    result = self.httpServerDriver.fetchResult()
-                assert(not self.httpServerDriver.getReturnCode())
+                with timeout(self._plan['timeout']):
+                    result = self._http_server_driver.fetch_result()
+                assert(not self._http_server_driver.get_return_code())
                 assert(result)
                 results.append(json.loads(result))
             except Exception as error:
-                _log.error('No result or the server crashed. Something went wrong. Will skip current benchmark.\nError: %s, Server return code: %d, result: %s' % (error, not self.httpServerDriver.getReturnCode(), result))
-                self.cleanup()
+                _log.error('No result or the server crashed. Something went wrong. Will skip current benchmark.\nError: %s, Server return code: %d, result: %s' % (error, self._http_server_driver.get_return_code(), result))
+                self._cleanup()
                 sys.exit(1)
             finally:
-                self.browserDriver.closeBrowsers()
+                self._browser_driver.close_browsers()
                 _log.info('End of %d iteration of current benchmark' % (x + 1))
-        results = self.wrap(results)
-        self.dump(results, self.outputFile if self.outputFile else self.plan['output_file'])
-        self.show_results(results)
-        self.benchmarkBuilder.clean()
+        results = self._wrap(results)
+        self._dump(results, self._output_file if self._output_file else self._plan['output_file'])
+        self._show_results(results)
+        self._benchmark_builder.clean()
         sys.exit()
 
-    def cleanup(self):
-        if self.browserDriver:
-            self.browserDriver.closeBrowsers()
-        if self.httpServerDriver:
-            self.httpServerDriver.killServer()
-        if self.benchmarkBuilder:
-            self.benchmarkBuilder.clean()
+    def _cleanup(self):
+        if self._browser_driver:
+            self._browser_driver.close_browsers()
+        if self._http_server_driver:
+            self._http_server_driver.kill_server()
+        if self._benchmark_builder:
+            self._benchmark_builder.clean()
 
     @classmethod
-    def dump(cls, results, outputFile):
+    def _dump(cls, results, output_file):
         _log.info('Dumping the results to file')
         try:
-            with open(outputFile, 'w') as fp:
+            with open(output_file, 'w') as fp:
                 json.dump(results, fp)
         except IOError as error:
-            _log.error('Cannot open output file: %s - Error: %s' % (outputFile, error))
+            _log.error('Cannot open output file: %s - Error: %s' % (output_file, error))
             _log.error('Results are:\n %s', json.dumps(results))
 
     @classmethod
-    def wrap(cls, dicts):
+    def _wrap(cls, dicts):
         _log.debug('Merging following results:\n%s', json.dumps(dicts))
         if not dicts:
             return None
         ret = {}
         for dic in dicts:
-            ret = cls.merge(ret, dic)
+            ret = cls._merge(ret, dic)
         _log.debug('Results after merging:\n%s', json.dumps(ret))
         return ret
 
     @classmethod
-    def merge(cls, a, b):
+    def _merge(cls, a, b):
         assert(isinstance(a, type(b)))
-        argType = type(a)
+        arg_type = type(a)
         # special handle for list type, and should be handle before equal check
-        if argType == types.ListType and len(a) and (type(a[0]) == types.StringType or type(a[0]) == types.UnicodeType):
+        if arg_type == types.ListType and len(a) and (type(a[0]) == types.StringType or type(a[0]) == types.UnicodeType):
             return a
-        if argType == types.DictType:
+        if arg_type == types.DictType:
             result = {}
             for key, value in a.items():
                 if key in b:
-                    result[key] = cls.merge(value, b[key])
+                    result[key] = cls._merge(value, b[key])
                 else:
                     result[key] = value
             for key, value in b.items():
@@ -145,6 +144,6 @@ class BenchmarkRunner(object):
         return a + b
 
     @classmethod
-    def show_results(cls, results):
+    def _show_results(cls, results):
         results = BenchmarkResults(results)
         print results.format()
index 0f56b8346d1c059934ccc0aec4a0c84376575f89..95dad01076c68e5344d5e7a891ca99fd501e930d 100644 (file)
@@ -8,13 +8,13 @@ class BrowserDriver(object):
     browser_name = None
 
     @abc.abstractmethod
-    def prepareEnv(self, deviceID):
+    def prepare_env(self, device_id):
         pass
 
     @abc.abstractmethod
-    def launchUrl(self, url, browserBuildPath=None):
+    def launch_url(self, url, browser_build_path=None):
         pass
 
     @abc.abstractmethod
-    def closeBrowser(self):
+    def close_browsers(self):
         pass
index fa7ade128d2e4c02a6c842d15807a8e4b622e9c6..4cc2c76a706a35b0cc52aac91c933341545e7516 100644 (file)
@@ -10,44 +10,44 @@ _log = logging.getLogger(__name__)
 
 
 class OSXBrowserDriver(BrowserDriver):
-    bundleIdentifier = None
+    bundle_identifier = None
     platform = 'osx'
 
-    def prepareEnv(self, deviceID):
-        self.closeBrowsers()
+    def prepare_env(self, device_id):
+        self.close_browsers()
         from Quartz import CGWarpMouseCursorPosition
         CGWarpMouseCursorPosition((10, 0))
 
-    def closeBrowsers(self):
-        self.terminateProcesses(self.bundleIdentifier)
+    def close_browsers(self):
+        self._terminiate_processes(self.bundle_identifier)
 
     @classmethod
-    def launchProcess(cls, buildDir, appName, url, args):
-        if not buildDir:
-            buildDir = '/Applications/'
-        appPath = os.path.join(buildDir, appName)
+    def _launch_process(cls, build_dir, app_name, url, args):
+        if not build_dir:
+            build_dir = '/Applications/'
+        app_path = os.path.join(build_dir, app_name)
 
-        _log.info('Launching "%s" with url "%s"' % (appPath, url))
+        _log.info('Launching "%s" with url "%s"' % (app_path, url))
 
         # FIXME: May need to be modified for a local build such as setting up DYLD libraries
-        args = ['open', '-a', appPath] + args
-        cls.launchProcessWithCaffinate(args)
+        args = ['open', '-a', app_path] + args
+        cls._launch_process_with_caffinate(args)
 
     @classmethod
-    def terminateProcesses(cls, bundleIdentifier):
-        _log.info('Closing all terminating all processes with the bundle identifier %s' % bundleIdentifier)
+    def _terminiate_processes(cls, bundle_identifier):
+        _log.info('Closing all terminating all processes with the bundle identifier %s' % bundle_identifier)
         from AppKit import NSRunningApplication
-        processes = NSRunningApplication.runningApplicationsWithBundleIdentifier_(bundleIdentifier)
+        processes = NSRunningApplication.runningApplicationsWithBundleIdentifier_(bundle_identifier)
         for process in processes:
             process.terminate()
 
     @classmethod
-    def launchProcessWithCaffinate(cls, args, env=None):
+    def _launch_process_with_caffinate(cls, args, env=None):
         process = subprocess.Popen(args, env=env)
         subprocess.Popen(["/usr/bin/caffeinate", "-disw", str(process.pid)])
         return process
 
     @classmethod
-    def screenSize(cls):
+    def _screen_size(cls):
         from AppKit import NSScreen
         return NSScreen.mainScreen().frame().size
index 437f10ac6db95e07b80d82e3e3e2f80e2526a2ba..03a482c160da04878950d5b82879cd817285758c 100644 (file)
@@ -12,16 +12,16 @@ _log = logging.getLogger(__name__)
 
 
 class OSXChromeDriver(OSXBrowserDriver):
-    bundleIdentifier = 'com.google.Chrome'
+    bundle_identifier = 'com.google.Chrome'
     browser_name = 'chrome'
 
-    def launchUrl(self, url, browserBuildPath):
-        self.launchProcess(buildDir=browserBuildPath, appName='Google Chrome.app', url=url, args=['--args', '--homepage', url, '--window-size={width},{height}'.format(width=int(self.screenSize().width), height=int(self.screenSize().height))])
+    def launch_url(self, url, browser_build_path):
+        self._launch_process(build_dir=browser_build_path, app_name='Google Chrome.app', url=url, args=['--args', '--homepage', url, '--window-size={width},{height}'.format(width=int(self._screen_size().width), height=int(self._screen_size().height))])
 
 
 class OSXChromeCanaryDriver(OSXBrowserDriver):
-    bundleIdentifier = 'com.google.Chrome.canary'
+    bundle_identifier = 'com.google.Chrome.canary'
     browser_name = 'chrome-canary'
 
-    def launchUrl(self, url, browserBuildPath):
-        self.launchProcess(buildDir=browserBuildPath, appName='Google Chrome Canary.app', url=url, args=['--args', '--homepage', url, '--window-size={width},{height}'.format(width=int(self.screenSize().width), height=int(self.screenSize().height))])
+    def launch_url(self, url, browser_build_path):
+        self._launch_process(build_dir=browser_build_path, app_name='Google Chrome Canary.app', url=url, args=['--args', '--homepage', url, '--window-size={width},{height}'.format(width=int(self._screen_size().width), height=int(self._screen_size().height))])
index d061ee4cc003d7e27dbe297d097238fa2cd893d9..dac6690d5d69c7ba13407212d341135e82ff797d 100644 (file)
@@ -12,16 +12,16 @@ _log = logging.getLogger(__name__)
 
 
 class OSXFirefoxDriver(OSXBrowserDriver):
-    bundleIdentifier = 'org.mozilla.firefox'
+    bundle_identifier = 'org.mozilla.firefox'
     browser_name = 'firefox'
 
-    def launchUrl(self, url, browserBuildPath):
-        self.launchProcess(buildDir=browserBuildPath, appName='Firefox.app', url=url, args=[url, '--args', '-width', str(int(self.screenSize().width)), '-height', str(int(self.screenSize().height))])
+    def launch_url(self, url, browser_build_path):
+        self._launch_process(build_dir=browser_build_path, app_name='Firefox.app', url=url, args=[url, '--args', '-width', str(int(self._screen_size().width)), '-height', str(int(self._screen_size().height))])
 
 
 class OSXFirefoxNightlyDriver(OSXBrowserDriver):
-    bundleIdentifier = 'org.mozilla.nightly'
+    bundle_identifier = 'org.mozilla.nightly'
     browser_name = 'firefox-nightly'
 
-    def launchUrl(self, url, browserBuildPath):
-        self.launchProcess(buildDir=browserBuildPath, appName='FirefoxNightly.app', url=url, args=[url, '--args', '-width', str(int(self.screenSize().width)), '-height', str(int(self.screenSize().height))])
+    def launch_url(self, url, browser_build_path):
+        self._launch_process(build_dir=browser_build_path, app_name='FirefoxNightly.app', url=url, args=[url, '--args', '-width', str(int(self._screen_size().width)), '-height', str(int(self._screen_size().height))])
index ca461ea9ea20e91622dba3dca5352a43cb17d27f..10699c963a569b62654143a43255b4ddc179f40c 100644 (file)
@@ -7,52 +7,52 @@ import subprocess
 import time
 
 from osx_browser_driver import OSXBrowserDriver
-from webkitpy.benchmark_runner.utils import forceRemove
+from webkitpy.benchmark_runner.utils import force_remove
 
 
 _log = logging.getLogger(__name__)
 
 
 class OSXSafariDriver(OSXBrowserDriver):
-    bundleIdentifier = 'com.apple.Safari'
+    bundle_identifier = 'com.apple.Safari'
     browser_name = 'safari'
 
-    def prepareEnv(self, deviceID):
-        self.safariProcess = None
-        super(OSXSafariDriver, self).prepareEnv(deviceID)
-        forceRemove(os.path.join(os.path.expanduser('~'), 'Library/Saved Application State/com.apple.Safari.savedState'))
-        forceRemove(os.path.join(os.path.expanduser('~'), 'Library/Safari/LastSession.plist'))
-        self.maximizeWindow()
-        self.safariPreferences = ["-HomePage", "about:blank", "-WarnAboutFraudulentWebsites", "0", "-ExtensionsEnabled", "0", "-ShowStatusBar", "0", "-NewWindowBehavior", "1", "-NewTabBehavior", "1"]
+    def prepare_env(self, device_id):
+        self._safari_process = None
+        super(OSXSafariDriver, self).prepare_env(device_id)
+        force_remove(os.path.join(os.path.expanduser('~'), 'Library/Saved Application State/com.apple.Safari.savedState'))
+        force_remove(os.path.join(os.path.expanduser('~'), 'Library/Safari/LastSession.plist'))
+        self._maximize_window()
+        self._safari_preferences = ["-HomePage", "about:blank", "-WarnAboutFraudulentWebsites", "0", "-ExtensionsEnabled", "0", "-ShowStatusBar", "0", "-NewWindowBehavior", "1", "-NewTabBehavior", "1"]
 
-    def launchUrl(self, url, browserBuildPath):
+    def launch_url(self, url, browser_build_path):
         args = ['/Applications/Safari.app/Contents/MacOS/Safari']
         env = {}
-        if browserBuildPath:
-            safariAppInBuildPath = os.path.join(browserBuildPath, 'Safari.app/Contents/MacOS/Safari')
-            if os.path.exists(safariAppInBuildPath):
-                args = [safariAppInBuildPath]
-                env = {'DYLD_FRAMEWORK_PATH': browserBuildPath, 'DYLD_LIBRARY_PATH': browserBuildPath, '__XPC_DYLD_LIBRARY_PATH': browserBuildPath}
+        if browser_build_path:
+            safari_app_in_build_path = os.path.join(browser_build_path, 'Safari.app/Contents/MacOS/Safari')
+            if os.path.exists(safari_app_in_build_path):
+                args = [safari_app_in_build_path]
+                env = {'DYLD_FRAMEWORK_PATH': browser_build_path, 'DYLD_LIBRARY_PATH': browser_build_path, '__XPC_DYLD_LIBRARY_PATH': browser_build_path}
             else:
-                _log.info('Could not find Safari.app at %s, using the system Safari instead' % safariAppInBuildPath)
+                _log.info('Could not find Safari.app at %s, using the system Safari instead' % safari_app_in_build_path)
 
-        args.extend(self.safariPreferences)
+        args.extend(self._safari_preferences)
         _log.info('Launching safari: %s with url: %s' % (args[0], url))
-        self.safariProcess = OSXSafariDriver.launchProcessWithCaffinate(args, env)
+        self._safari_process = OSXSafariDriver._launch_process_with_caffinate(args, env)
 
         # Stop for initialization of the safari process, otherwise, open
         # command may use the system safari.
         time.sleep(3)
         subprocess.Popen(['open', url])
 
-    def closeBrowsers(self):
-        super(OSXSafariDriver, self).closeBrowsers()
-        if self.safariProcess and self.safariProcess.returncode:
+    def close_browsers(self):
+        super(OSXSafariDriver, self).close_browsers()
+        if self._safari_process and self._safari_process.returncode:
             sys.exit('Browser crashed with exitcode %d' % self._process.returncode)
 
     @classmethod
-    def maximizeWindow(cls):
+    def _maximize_window(cls):
         try:
-            subprocess.check_call(['/usr/bin/defaults', 'write', 'com.apple.Safari', 'NSWindow Frame BrowserWindowFrame', ' '.join(['0', '0', str(cls.screenSize().width), str(cls.screenSize().height)] * 2)])
+            subprocess.check_call(['/usr/bin/defaults', 'write', 'com.apple.Safari', 'NSWindow Frame BrowserWindowFrame', ' '.join(['0', '0', str(cls._screen_size().width), str(cls._screen_size().height)] * 2)])
         except Exception as error:
             _log.error('Reset safari window size failed - Error: {}'.format(error))
index aa70190ea8e26582f091ba820ef9aae52f590267..754d23a8126a589f1430a93301e83001e4bcf63d 100644 (file)
@@ -10,17 +10,17 @@ class HTTPServerDriver(object):
         pass
 
     @abstractmethod
-    def fetchResult(self):
+    def fetch_result(self):
         pass
 
     @abstractmethod
-    def killServer(self):
+    def kill_server(self):
         pass
 
     @abstractmethod
-    def getReturnCode(self):
+    def get_return_code(self):
         pass
 
     @abstractmethod
-    def setDeviceID(self, deviceID):
+    def set_device_id(self, deviceID):
         pass
index 64955df9144d5470c6482089ab77804d99346a9d..9e2a7e6e5ac228339f8d0dce4c47625b662e3fb3 100644 (file)
@@ -21,13 +21,13 @@ class SimpleHTTPServerDriver(HTTPServerDriver):
     name = 'SimpleHTTPServerDriver'
 
     def __init__(self):
-        self.server_process = None
-        self.server_port = 0
+        self._server_process = None
+        self._server_port = 0
         # FIXME: This may not be reliable.
         _log.info('Finding the IP address of current machine')
         try:
-            self.ip = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][0]
-            _log.info('IP of current machine is: %s' % self.ip)
+            self._ip = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][0]
+            _log.info('IP of current machine is: %s' % self._ip)
         except Exception as error:
             _log.error('Cannot get the ip address of current machine - Error: %s' % error)
             raise
@@ -35,18 +35,18 @@ class SimpleHTTPServerDriver(HTTPServerDriver):
     def serve(self, web_root):
         _log.info('Launching an http server')
         http_server_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "http_server/twisted_http_server.py")
-        self.server_process = subprocess.Popen(["/usr/bin/python", http_server_path, web_root], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+        self._server_process = subprocess.Popen(["/usr/bin/python", http_server_path, web_root], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
-        maxAttempt = 5
+        max_attempt = 5
         interval = 0.5
         _log.info('Start to fetching the port number of the http server')
         try:
             import psutil
-            for attempt in xrange(maxAttempt):
+            for attempt in xrange(max_attempt):
                 try:
-                    self.server_port = psutil.Process(self.server_process.pid).connections()[0][3][1]
-                    if self.server_port:
-                        _log.info('HTTP Server is serving at port: %d', self.server_port)
+                    self._server_port = psutil.Process(self._server_process.pid).connections()[0][3][1]
+                    if self._server_port:
+                        _log.info('HTTP Server is serving at port: %d', self._server_port)
                         break
                 except IndexError:
                     pass
@@ -56,12 +56,12 @@ class SimpleHTTPServerDriver(HTTPServerDriver):
             else:
                 raise Exception("Cannot listen to server, max tries exceeded")
         except ImportError:
-            for attempt in xrange(maxAttempt):
+            for attempt in xrange(max_attempt):
                 try:
-                    output = subprocess.check_output(['/usr/sbin/lsof', '-a', '-iTCP', '-sTCP:LISTEN', '-p', str(self.server_process.pid)])
-                    self.server_port = int(re.search('TCP \*:(\d+) \(LISTEN\)', output).group(1))
-                    if self.server_port:
-                        _log.info('HTTP Server is serving at port: %d', self.server_port)
+                    output = subprocess.check_output(['/usr/sbin/lsof', '-a', '-iTCP', '-sTCP:LISTEN', '-p', str(self._server_process.pid)])
+                    self._server_port = int(re.search('TCP \*:(\d+) \(LISTEN\)', output).group(1))
+                    if self._server_port:
+                        _log.info('HTTP Server is serving at port: %d', self._server_port)
                         break
                 except Exception as error:
                      _log.info('Error: %s' % error)
@@ -72,29 +72,28 @@ class SimpleHTTPServerDriver(HTTPServerDriver):
                 raise Exception("Cannot listen to server, max tries exceeded")
 
         # Wait for server to be up completely before exiting
-        for attempt in xrange(maxAttempt):
+        for attempt in xrange(max_attempt):
             try:
-                subprocess.check_call(["curl", "--silent", "--head", "--fail", "--output", "/dev/null", self.baseUrl()])
+                subprocess.check_call(["curl", "--silent", "--head", "--fail", "--output", "/dev/null", self.base_url()])
                 return
             except Exception as error:
                 _log.info('Server not running yet: %s' % error)
                 time.sleep(interval)
         raise Exception('Server not running, max tries exceeded: %s' % error)
 
+    def base_url(self):
+        return "http://%s:%d" % (self._ip, self._server_port)
 
-    def baseUrl(self):
-        return "http://%s:%d" % (self.ip, self.server_port)
-
-    def fetchResult(self):
-        (stdout, stderr) = self.server_process.communicate()
+    def fetch_result(self):
+        (stdout, stderr) = self._server_process.communicate()
         print stderr
         return stdout
 
-    def killServer(self):
+    def kill_server(self):
         try:
-            self.server_process.terminate()
+            self._server_process.terminate()
         except OSError as error:
             _log.info('Error terminating server process: %s' % (error))
 
-    def getReturnCode(self):
-        return self.server_process.returncode
+    def get_return_code(self):
+        return self._server_process.returncode
index 985e2fd4018baee001885b31d9fdb5e0da3ea42d..c7cb62eb2404368149b656d86e8c2a7b026dcf93 100644 (file)
@@ -30,14 +30,14 @@ def load_subclasses(dirname, base_class_name, loader):
                 loader(item)
 
 
-def getPathFromProjectRoot(relativePathToProjectRoot):
+def get_path_from_project_root(relative_path_to_project_root):
     # Choose the directory containing current file as start point,
     # compute relative path base on the parameter,
     # and return an absolute path
-    return os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), relativePathToProjectRoot))
+    return os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path_to_project_root))
 
 
-def forceRemove(path):
+def force_remove(path):
     try:
         shutil.rmtree(path)
     except Exception as error: