https://bugs.webkit.org/show_bug.cgi?id=159019
Reviewed by Daniel Bates.
Fixed the formatting issues as reported by check-webkit-style in webkitpy.
There is no functionality change.
Only affected file names retained below for brevity.
* Scripts/webkitpy/benchmark_runner/browser_driver/browser_driver.py:
* Scripts/webkitpy/benchmark_runner/browser_driver/browser_driver_factory.py:
* Scripts/webkitpy/benchmark_runner/http_server_driver/http_server/twisted_http_server.py:
* Scripts/webkitpy/benchmark_runner/http_server_driver/simple_http_server_driver.py:
* Scripts/webkitpy/benchmark_runner/utils.py:
* Scripts/webkitpy/common/checkout/changelog.py:
* Scripts/webkitpy/common/checkout/changelog_unittest.py:
* Scripts/webkitpy/common/checkout/checkout.py:
* Scripts/webkitpy/common/checkout/checkout_mock.py:
* Scripts/webkitpy/common/checkout/checkout_unittest.py:
* Scripts/webkitpy/common/checkout/commitinfo.py:
* Scripts/webkitpy/common/checkout/commitinfo_unittest.py:
* Scripts/webkitpy/common/checkout/diff_parser_unittest.py:
* Scripts/webkitpy/common/checkout/scm/scm.py:
* Scripts/webkitpy/common/checkout/scm/scm_unittest.py:
* Scripts/webkitpy/common/config/committers_unittest.py:
* Scripts/webkitpy/common/config/irc.py:
* Scripts/webkitpy/common/config/ports.py:
* Scripts/webkitpy/common/config/ports_unittest.py:
* Scripts/webkitpy/common/config/urls.py:
* Scripts/webkitpy/common/host_mock.py:
* Scripts/webkitpy/common/net/bugzilla/bugzilla.py:
* Scripts/webkitpy/common/net/bugzilla/bugzilla_unittest.py:
* Scripts/webkitpy/common/net/buildbot/buildbot.py:
* Scripts/webkitpy/common/net/buildbot/buildbot_mock.py:
* Scripts/webkitpy/common/net/buildbot/buildbot_unittest.py:
* Scripts/webkitpy/common/net/credentials_unittest.py:
* Scripts/webkitpy/common/net/irc/ircproxy_unittest.py:
* Scripts/webkitpy/common/net/networktransaction_unittest.py:
* Scripts/webkitpy/common/net/statusserver.py:
* Scripts/webkitpy/common/system/autoinstall.py:
* Scripts/webkitpy/common/system/crashlogs_unittest.py:
* Scripts/webkitpy/common/system/executive.py:
* Scripts/webkitpy/common/system/executive_mock.py:
* Scripts/webkitpy/common/system/executive_unittest.py:
* Scripts/webkitpy/common/system/filesystem_mock.py:
* Scripts/webkitpy/common/system/filesystem_unittest.py:
* Scripts/webkitpy/common/system/logutils_unittest.py:
* Scripts/webkitpy/common/system/path.py:
* Scripts/webkitpy/common/system/path_unittest.py:
* Scripts/webkitpy/common/system/platforminfo.py:
* Scripts/webkitpy/common/system/user.py:
* Scripts/webkitpy/common/system/user_unittest.py:
* Scripts/webkitpy/common/system/workspace_unittest.py:
* Scripts/webkitpy/common/thread/threadedmessagequeue.py:
* Scripts/webkitpy/common/thread/threadedmessagequeue_unittest.py:
* Scripts/webkitpy/layout_tests/controllers/layout_test_finder.py:
* Scripts/webkitpy/layout_tests/controllers/manager.py:
* Scripts/webkitpy/layout_tests/controllers/test_result_writer.py:
* Scripts/webkitpy/layout_tests/layout_package/json_results_generator.py:
* Scripts/webkitpy/layout_tests/lint_test_expectations_unittest.py:
* Scripts/webkitpy/layout_tests/models/test_configuration.py:
* Scripts/webkitpy/layout_tests/models/test_expectations.py:
* Scripts/webkitpy/layout_tests/models/test_failures.py:
* Scripts/webkitpy/layout_tests/models/test_run_results.py:
* Scripts/webkitpy/layout_tests/run_webkit_tests_integrationtest.py:
* Scripts/webkitpy/layout_tests/views/metered_stream_unittest.py:
* Scripts/webkitpy/layout_tests/views/printing.py:
* Scripts/webkitpy/performance_tests/perftestsrunner.py:
* Scripts/webkitpy/performance_tests/perftestsrunner_integrationtest.py:
* Scripts/webkitpy/port/base_unittest.py:
* Scripts/webkitpy/port/driver.py:
* Scripts/webkitpy/port/driver_unittest.py:
* Scripts/webkitpy/port/factory.py:
* Scripts/webkitpy/port/gtk.py:
* Scripts/webkitpy/port/server_process_unittest.py:
* Scripts/webkitpy/port/test.py:
* Scripts/webkitpy/port/win.py:
* Scripts/webkitpy/style/checker.py:
* Scripts/webkitpy/style/checkers/common_unittest.py:
* Scripts/webkitpy/style/checkers/cpp.py:
* Scripts/webkitpy/style/checkers/cpp_unittest.py:
* Scripts/webkitpy/style/checkers/js.py:
* Scripts/webkitpy/style/checkers/jsonchecker.py:
* Scripts/webkitpy/style/checkers/png.py:
* Scripts/webkitpy/style/checkers/text.py:
* Scripts/webkitpy/style/checkers/text_unittest.py:
* Scripts/webkitpy/style/error_handlers.py:
* Scripts/webkitpy/style/filter.py:
* Scripts/webkitpy/style/filter_unittest.py:
* Scripts/webkitpy/style/optparser.py:
* Scripts/webkitpy/style/optparser_unittest.py:
* Scripts/webkitpy/test/main.py:
* Scripts/webkitpy/w3c/test_converter.py:
* Scripts/webkitpy/w3c/test_converter_unittest.py:
* Scripts/webkitpy/w3c/test_importer_unittest.py:
* Scripts/webkitpy/xcode/simulator.py:
git-svn-id: https://svn.webkit.org/repository/webkit/trunk@202362
268f45cc-cd09-0410-ab3c-
d52691b4dbfc
+2016-06-22 Aakash Jain <aakash_jain@apple.com>
+
+ Fix style issues in webkitpy
+ https://bugs.webkit.org/show_bug.cgi?id=159019
+
+ Reviewed by Daniel Bates.
+
+ Fixed the formatting issues as reported by check-webkit-style in webkitpy.
+ There is no functionality change.
+ Only affected file names retained below for brevity.
+
+ * Scripts/webkitpy/benchmark_runner/browser_driver/browser_driver.py:
+ * Scripts/webkitpy/benchmark_runner/browser_driver/browser_driver_factory.py:
+ * Scripts/webkitpy/benchmark_runner/http_server_driver/http_server/twisted_http_server.py:
+ * Scripts/webkitpy/benchmark_runner/http_server_driver/simple_http_server_driver.py:
+ * Scripts/webkitpy/benchmark_runner/utils.py:
+ * Scripts/webkitpy/common/checkout/changelog.py:
+ * Scripts/webkitpy/common/checkout/changelog_unittest.py:
+ * Scripts/webkitpy/common/checkout/checkout.py:
+ * Scripts/webkitpy/common/checkout/checkout_mock.py:
+ * Scripts/webkitpy/common/checkout/checkout_unittest.py:
+ * Scripts/webkitpy/common/checkout/commitinfo.py:
+ * Scripts/webkitpy/common/checkout/commitinfo_unittest.py:
+ * Scripts/webkitpy/common/checkout/diff_parser_unittest.py:
+ * Scripts/webkitpy/common/checkout/scm/scm.py:
+ * Scripts/webkitpy/common/checkout/scm/scm_unittest.py:
+ * Scripts/webkitpy/common/config/committers_unittest.py:
+ * Scripts/webkitpy/common/config/irc.py:
+ * Scripts/webkitpy/common/config/ports.py:
+ * Scripts/webkitpy/common/config/ports_unittest.py:
+ * Scripts/webkitpy/common/config/urls.py:
+ * Scripts/webkitpy/common/host_mock.py:
+ * Scripts/webkitpy/common/net/bugzilla/bugzilla.py:
+ * Scripts/webkitpy/common/net/bugzilla/bugzilla_unittest.py:
+ * Scripts/webkitpy/common/net/buildbot/buildbot.py:
+ * Scripts/webkitpy/common/net/buildbot/buildbot_mock.py:
+ * Scripts/webkitpy/common/net/buildbot/buildbot_unittest.py:
+ * Scripts/webkitpy/common/net/credentials_unittest.py:
+ * Scripts/webkitpy/common/net/irc/ircproxy_unittest.py:
+ * Scripts/webkitpy/common/net/networktransaction_unittest.py:
+ * Scripts/webkitpy/common/net/statusserver.py:
+ * Scripts/webkitpy/common/system/autoinstall.py:
+ * Scripts/webkitpy/common/system/crashlogs_unittest.py:
+ * Scripts/webkitpy/common/system/executive.py:
+ * Scripts/webkitpy/common/system/executive_mock.py:
+ * Scripts/webkitpy/common/system/executive_unittest.py:
+ * Scripts/webkitpy/common/system/filesystem_mock.py:
+ * Scripts/webkitpy/common/system/filesystem_unittest.py:
+ * Scripts/webkitpy/common/system/logutils_unittest.py:
+ * Scripts/webkitpy/common/system/path.py:
+ * Scripts/webkitpy/common/system/path_unittest.py:
+ * Scripts/webkitpy/common/system/platforminfo.py:
+ * Scripts/webkitpy/common/system/user.py:
+ * Scripts/webkitpy/common/system/user_unittest.py:
+ * Scripts/webkitpy/common/system/workspace_unittest.py:
+ * Scripts/webkitpy/common/thread/threadedmessagequeue.py:
+ * Scripts/webkitpy/common/thread/threadedmessagequeue_unittest.py:
+ * Scripts/webkitpy/layout_tests/controllers/layout_test_finder.py:
+ * Scripts/webkitpy/layout_tests/controllers/manager.py:
+ * Scripts/webkitpy/layout_tests/controllers/test_result_writer.py:
+ * Scripts/webkitpy/layout_tests/layout_package/json_results_generator.py:
+ * Scripts/webkitpy/layout_tests/lint_test_expectations_unittest.py:
+ * Scripts/webkitpy/layout_tests/models/test_configuration.py:
+ * Scripts/webkitpy/layout_tests/models/test_expectations.py:
+ * Scripts/webkitpy/layout_tests/models/test_failures.py:
+ * Scripts/webkitpy/layout_tests/models/test_run_results.py:
+ * Scripts/webkitpy/layout_tests/run_webkit_tests_integrationtest.py:
+ * Scripts/webkitpy/layout_tests/views/metered_stream_unittest.py:
+ * Scripts/webkitpy/layout_tests/views/printing.py:
+ * Scripts/webkitpy/performance_tests/perftestsrunner.py:
+ * Scripts/webkitpy/performance_tests/perftestsrunner_integrationtest.py:
+ * Scripts/webkitpy/port/base_unittest.py:
+ * Scripts/webkitpy/port/driver.py:
+ * Scripts/webkitpy/port/driver_unittest.py:
+ * Scripts/webkitpy/port/factory.py:
+ * Scripts/webkitpy/port/gtk.py:
+ * Scripts/webkitpy/port/server_process_unittest.py:
+ * Scripts/webkitpy/port/test.py:
+ * Scripts/webkitpy/port/win.py:
+ * Scripts/webkitpy/style/checker.py:
+ * Scripts/webkitpy/style/checkers/common_unittest.py:
+ * Scripts/webkitpy/style/checkers/cpp.py:
+ * Scripts/webkitpy/style/checkers/cpp_unittest.py:
+ * Scripts/webkitpy/style/checkers/js.py:
+ * Scripts/webkitpy/style/checkers/jsonchecker.py:
+ * Scripts/webkitpy/style/checkers/png.py:
+ * Scripts/webkitpy/style/checkers/text.py:
+ * Scripts/webkitpy/style/checkers/text_unittest.py:
+ * Scripts/webkitpy/style/error_handlers.py:
+ * Scripts/webkitpy/style/filter.py:
+ * Scripts/webkitpy/style/filter_unittest.py:
+ * Scripts/webkitpy/style/optparser.py:
+ * Scripts/webkitpy/style/optparser_unittest.py:
+ * Scripts/webkitpy/test/main.py:
+ * Scripts/webkitpy/w3c/test_converter.py:
+ * Scripts/webkitpy/w3c/test_converter_unittest.py:
+ * Scripts/webkitpy/w3c/test_importer_unittest.py:
+ * Scripts/webkitpy/xcode/simulator.py:
+
2016-06-22 Brady Eidson <beidson@apple.com>
DatabaseProcess doesn't handle WebProcesses going away uncleanly.
from abc import ABCMeta, abstractmethod
+
class BrowserDriver(object):
platform = None
browser_name = None
platforms = set()
browsers = set()
-
@classmethod
def available_platforms(cls):
return list(cls.platforms)
_log = logging.getLogger(__name__)
+
class ServerControl(Resource):
isLeaf = True
_log.info('HTTP Server is serving at port: %d', self._server_port)
break
except Exception as error:
- _log.info('Error: %s' % error)
+ _log.info('Error: %s' % error)
_log.info('Server port is not found this time, retry after %f seconds' % interval)
time.sleep(interval)
interval *= 2
_log.info("Error removing %s: %s" % (path, error))
pass
+
# Borrow this code from
# 'http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish'
class TimeoutError(Exception):
return False
return True
+
# FIXME: Various methods on ChangeLog should move into ChangeLogEntry instead.
class ChangeLog(object):
expected_contents = "== Rolled over to ChangeLog-2009-06-16 ==\n"
self.assertEqual(actual_contents.splitlines(), expected_contents.splitlines())
-
def test_prepend_text(self):
fs = MockFileSystem()
fs.write_text_file(self._changelog_path, self._example_changelog)
try:
return parse_bug_id_from_changelog(self.commit_message_for_this_commit(git_commit, changed_files).message())
except ScriptError, e:
- pass # We might not have ChangeLogs.
+ pass # We might not have ChangeLogs.
def apply_patch(self, patch):
# It's possible that the patch was not made from the root directory.
})
}
+
class MockCheckout(object):
def __init__(self):
# FIXME: It's unclear if a MockCheckout is very useful. A normal Checkout
commit_message.message_lines = commit_message.message_lines[1:]
self.assertMultiLineEqual(commit_message.message(), expected_commit_message)
+
class CheckoutTest(unittest.TestCase):
def _make_checkout(self):
return Checkout(scm=MockSCM(), filesystem=MockFileSystem(), executive=MockExecutive())
self.author(),
self.reviewer(),
]
- return set([party for party in responsible_parties if party]) # Filter out None
+ return set([party for party in responsible_parties if party]) # Filter out None
# FIXME: It is slightly lame that this "view" method is on this "model" class (in MVC terms)
def blame_string(self, bugs):
from webkitpy.common.checkout.commitinfo import CommitInfo
from webkitpy.common.config.committers import CommitterList, Committer, Reviewer
+
class CommitInfoTest(unittest.TestCase):
def test_commit_info_creation(self):
from webkitpy.common.checkout.diff_test_data import DIFF_TEST_DATA
+
class DiffParserTest(unittest.TestCase):
maxDiff = None
- def test_diff_parser(self, parser = None):
+ def test_diff_parser(self, parser=None):
if not parser:
parser = diff_parser.DiffParser(DIFF_TEST_DATA.splitlines())
self.assertEqual(3, len(parser.files))
p = re.compile(r' ([a|b])/')
prefixes = [
- { 'a' : 'i', 'b' : 'w' }, # git-diff (compares the (i)ndex and the (w)ork tree)
- { 'a' : 'c', 'b' : 'w' }, # git-diff HEAD (compares a (c)ommit and the (w)ork tree)
- { 'a' : 'c', 'b' : 'i' }, # git diff --cached (compares a (c)ommit and the (i)ndex)
- { 'a' : 'o', 'b' : 'w' }, # git-diff HEAD:file1 file2 (compares an (o)bject and a (w)ork tree entity)
- { 'a' : '1', 'b' : '2' }, # git diff --no-index a b (compares two non-git things (1) and (2))
+ {'a': 'i', 'b': 'w'}, # git-diff (compares the (i)ndex and the (w)ork tree)
+ {'a': 'c', 'b': 'w'}, # git-diff HEAD (compares a (c)ommit and the (w)ork tree)
+ {'a': 'c', 'b': 'i'}, # git diff --cached (compares a (c)ommit and the (i)ndex)
+ {'a': 'o', 'b': 'w'}, # git-diff HEAD:file1 file2 (compares an (o)bject and a (w)ork tree entity)
+ {'a': '1', 'b': '2'}, # git diff --no-index a b (compares two non-git things (1) and (2))
]
for prefix in prefixes:
self.prompt_for_password = prompt_for_password
-
# SCM methods are expected to return paths relative to self.checkout_root.
class SCM:
def __init__(self, cwd, executive=None, filesystem=None):
from datetime import date
from webkitpy.common.checkout.checkout import Checkout
from webkitpy.common.config.committers import Committer # FIXME: This should not be needed
-from webkitpy.common.net.bugzilla import Attachment # FIXME: This should not be needed
+from webkitpy.common.net.bugzilla import Attachment # FIXME: This should not be needed
from webkitpy.common.system.executive import Executive, ScriptError
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.outputcapture import OutputCapture
# Eventually we will want to write tests which work for both scms. (like update_webkit, changed_files, etc.)
# Perhaps through some SCMTest base-class which both SVNTest and GitTest inherit from.
+
def run_command(*args, **kwargs):
# FIXME: This should not be a global static.
# New code should use Executive.run_command directly instead
def run_silent(args, cwd=None):
# Note: Not thread safe: http://bugs.python.org/issue2320
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)
- process.communicate() # ignore output
+ process.communicate() # ignore output
exit_code = process.wait()
if exit_code:
raise ScriptError('Failed to run "%s" exit_code: %d cwd: %s' % (args, exit_code, cwd))
# For testing the SCM baseclass directly.
class SCMClassTests(unittest.TestCase):
def setUp(self):
- self.dev_null = open(os.devnull, "w") # Used to make our Popen calls quiet.
+ self.dev_null = open(os.devnull, "w") # Used to make our Popen calls quiet.
def tearDown(self):
self.dev_null.close()
self.assertRaises(ScriptError, run_command, ['grep', 'bar'], input=input_process.stdout)
# Test when the run_command process fails.
- input_process = subprocess.Popen(['echo', 'foo\nbar'], stdout=subprocess.PIPE, stderr=self.dev_null) # grep shows usage and calls exit(2) when called w/o arguments.
+ input_process = subprocess.Popen(['echo', 'foo\nbar'], stdout=subprocess.PIPE, stderr=self.dev_null) # grep shows usage and calls exit(2) when called w/o arguments.
self.assertRaises(ScriptError, run_command, command_returns_non_zero, input=input_process.stdout)
def test_error_handlers(self):
- git_failure_message="Merge conflict during commit: Your file or directory 'WebCore/ChangeLog' is probably out-of-date: resource out of date; try updating at /usr/local/libexec/git-core//git-svn line 469"
- svn_failure_message="""svn: Commit failed (details follow):
+ git_failure_message = "Merge conflict during commit: Your file or directory 'WebCore/ChangeLog' is probably out-of-date: resource out of date; try updating at /usr/local/libexec/git-core//git-svn line 469"
+ svn_failure_message = """svn: Commit failed (details follow):
svn: File or directory 'ChangeLog' is out of date; try updating
svn: resource out of date; try updating
"""
scripts_path = os.path.join(self.svn_checkout_path, 'Tools', 'Scripts')
os.makedirs(scripts_path)
create_patch_path = os.path.join(scripts_path, 'svn-create-patch')
- write_into_file_at_path(create_patch_path, '#!/bin/sh\necho $PWD') # We could pass -n to prevent the \n, but not all echo accept -n.
+ write_into_file_at_path(create_patch_path, '#!/bin/sh\necho $PWD') # We could pass -n to prevent the \n, but not all echo accept -n.
os.chmod(create_patch_path, stat.S_IXUSR | stat.S_IRUSR)
# Change into our test directory and run the create_patch command.
self.assertEqual(scm.checkout_root, self.svn_checkout_path) # Sanity check that detection worked right.
patch_contents = scm.create_patch()
# Our fake 'svn-create-patch' returns $PWD instead of a patch, check that it was executed from the root of the repo.
- self.assertEqual("%s\n" % os.path.realpath(scm.checkout_root), patch_contents) # Add a \n because echo adds a \n.
+ self.assertEqual("%s\n" % os.path.realpath(scm.checkout_root), patch_contents) # Add a \n because echo adds a \n.
def test_detection(self):
self.assertEqual(self.scm.display_name(), "svn")
def test_exists(self):
self._shared_test_exists(self.scm, self.scm.commit_with_message)
+
class GitTest(SCMTest):
def setUp(self):
run_command(['git', 'commit', '-a', '-m', 'commit to be thrown away by rebase abort'])
# --quiet doesn't make git svn silent, so use run_silent to redirect output
- self.assertRaises(ScriptError, run_silent, ['git', 'svn', '--quiet', 'rebase']) # Will fail due to a conflict leaving us mid-rebase.
+ self.assertRaises(ScriptError, run_silent, ['git', 'svn', '--quiet', 'rebase']) # Will fail due to a conflict leaving us mid-rebase.
self.assertTrue(self.scm.rebase_in_progress())
import unittest
from webkitpy.common.config.committers import CommitterList, Contributor, Committer, Reviewer
+
class CommittersTest(unittest.TestCase):
def test_committer_lookup(self):
committer = Committer('Test One', 'one@test.com', 'one')
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-server="irc.freenode.net"
-port=6665
-channel="#webkit"
+server = "irc.freenode.net"
+port = 6665
+channel = "#webkit"
command.append("--ios-simulator")
return command
+
class MacPort(DeprecatedPort):
port_flag_name = "mac"
command.append("--dump-render-tree")
return command
+
class MacWK2Port(DeprecatedPort):
port_flag_name = "mac-wk2"
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
-#
+#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
-#
+#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
statusserver_default_host = "webkit-queues.webkit.org"
+
def parse_bug_id(string):
if not string:
return None
def watch_list(self):
return self._watch_list
-
import socket
import urllib
-from datetime import datetime # used in timestamp()
+from datetime import datetime # used in timestamp()
from .attachment import Attachment
from .bug import Bug
results_page = self._load_query(review_queue_url)
return bool(re.search("did not match anything", results_page.read()))
+
class CommitQueueFlag(object):
mark_for_nothing = 0
mark_for_commit_queue = 1
for attachment in attachments:
if attachment.id() == int(attachment_id):
return attachment
- return None # This should never be hit.
+ return None # This should never be hit.
def authenticate(self):
if self.authenticated:
'''
_expected_example_attachment_parsing = {
'attach_date': datetime.datetime(2009, 07, 29, 10, 23),
- 'bug_id' : 100,
- 'is_obsolete' : True,
- 'is_patch' : True,
- 'id' : 33721,
- 'url' : "https://bugs.webkit.org/attachment.cgi?id=33721",
- 'name' : "Fixed whitespace issue",
- 'type' : "text/plain",
- 'review' : '+',
- 'reviewer_email' : 'one@test.com',
- 'commit-queue' : '+',
- 'committer_email' : 'two@test.com',
- 'attacher_email' : 'christian.plesner.hansen@gmail.com',
+ 'bug_id': 100,
+ 'is_obsolete': True,
+ 'is_patch': True,
+ 'id': 33721,
+ 'url': "https://bugs.webkit.org/attachment.cgi?id=33721",
+ 'name': "Fixed whitespace issue",
+ 'type': "text/plain",
+ 'review': '+',
+ 'reviewer_email': 'one@test.com',
+ 'commit-queue': '+',
+ 'committer_email': 'two@test.com',
+ 'attacher_email': 'christian.plesner.hansen@gmail.com',
}
def test_url_creation(self):
self._revision_to_build_number = None
from webkitpy.thirdparty.autoinstalled.mechanize import Browser
self._browser = Browser()
- self._browser.set_handle_robots(False) # The builder pages are excluded by robots.txt
+ self._browser.set_handle_robots(False) # The builder pages are excluded by robots.txt
def name(self):
return self._name
def _parse_current_build_cell(self, builder, cell):
activity_lines = cell.renderContents().split("<br />")
- builder["activity"] = activity_lines[0] # normally "building" or "idle"
+ builder["activity"] = activity_lines[0] # normally "building" or "idle"
# The middle lines document how long left for any current builds.
match = re.match("(?P<pending_builds>\d) pending", activity_lines[-1])
builder["pending_builds"] = int(match.group("pending_builds")) if match else 0
self._revision = revision
self._is_green = is_green
+
class MockBuilder(object):
def __init__(self, name):
self._name = name
)
results = [self._mock_test_result(testname) for testname in failure(build_number)]
layout_test_results = LayoutTestResults(test_results=results, did_exceed_test_failure_limit=False)
+
def mock_layout_test_results():
return layout_test_results
build.layout_test_results = mock_layout_test_results
def test_build_and_revision_for_filename(self):
expectations = {
- "r47483 (1)/" : (47483, 1),
- "r47483 (1).zip" : (47483, 1),
+ "r47483 (1)/": (47483, 1),
+ "r47483 (1).zip": (47483, 1),
"random junk": None,
}
for filename, revision_and_build in expectations.items():
_expected_example_one_box_parsings = [
{
'is_green': True,
- 'build_number' : 3693,
+ 'build_number': 3693,
'name': u'Windows Debug (Tests)',
'built_revision': 47380,
'activity': 'building',
},
{
'is_green': False,
- 'build_number' : None,
+ 'build_number': None,
'name': u'SnowLeopard Intel Release',
'built_revision': None,
'activity': 'building',
},
{
'is_green': False,
- 'build_number' : 654,
+ 'build_number': 654,
'name': u'Qt Linux Release',
'built_revision': 47383,
'activity': 'idle',
},
{
'is_green': True,
- 'build_number' : 2090,
+ 'build_number': 2090,
'name': u'Qt Windows 32-bit Debug',
'built_revision': 60563,
'activity': 'building',
def mock_fetch_build_dictionary(self, build_number):
build_dictionary = {
"sourceStamp": {
- "revision" : 2 * build_number,
+ "revision": 2 * build_number,
},
- "number" : int(build_number),
- "results" : build_number % 2, # 0 means pass
+ "number": int(build_number),
+ "results": build_number % 2, # 0 means pass
}
return build_dictionary
buildbot._fetch_build_dictionary = mock_fetch_build_dictionary
'''
_expected_files = [
{
- "filename" : "r47483 (1)/",
- "size" : "",
- "type" : "[Directory]",
- "encoding" : "",
+ "filename": "r47483 (1)/",
+ "size": "",
+ "type": "[Directory]",
+ "encoding": "",
},
{
- "filename" : "r47484 (2).zip",
- "size" : "89K",
- "type" : "[application/zip]",
- "encoding" : "",
+ "filename": "r47484 (2).zip",
+ "size": "89K",
+ "type": "[application/zip]",
+ "encoding": "",
},
]
# FIXME: This test won't work if the user has a credential for foo.example.com!
credentials = Credentials("foo.example.com")
if not credentials._is_mac_os_x():
- return # This test does not run on a non-Mac.
+ return # This test does not run on a non-Mac.
# Note, we ignore the captured output because it is already covered
# by the test case CredentialsTest._assert_security_call (below).
# credential source could be affected by the user's environment.
self.assertEqual(credentials.read_credentials(), ("test@webkit.org", "SECRETSAUCE"))
-
def test_keyring_without_git_repo(self):
# FIXME: This should share more code with test_read_credentials_without_git_repo
class MockKeyring(object):
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
-#
+#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
-#
+#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.thirdparty.mock import Mock
+
class IRCProxyTest(unittest.TestCase):
def test_trivial(self):
def fun():
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
-#
+#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
-#
+#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
def test_timeout(self):
self._run_count = 0
- transaction = NetworkTransaction(initial_backoff_seconds=60*60, timeout_seconds=60)
+ transaction = NetworkTransaction(initial_backoff_seconds=60 * 60, timeout_seconds=60)
did_process_exception = False
did_throw_exception = True
try:
# Copyright (C) 2009 Google Inc. All rights reserved.
-#
+#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
-#
+#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
-#
+#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
_SOURCEFORGE_ENV_VAR = 'SOURCEFORGE_MIRRORS'
_CACHE_ENV_VAR = 'LOCAL_AUTOINSTALL_CACHE'
+
class AutoInstaller(object):
"""Supports automatically installing Python packages from an URL.
if not 200 <= code < 300:
raise ValueError("HTTP Error code %s" % code)
- BUFSIZE = 2**13 # 8KB
+ BUFSIZE = 2 ** 13 # 8KB
while True:
data = netstream.read(BUFSIZE)
if not data:
# Needed to support Windows port tests
from webkitpy.port.win import WinPort
+
def make_mock_crash_report_darwin(process_name, pid):
return """Process: {process_name} [{pid}]
Path: /Volumes/Data/slave/snowleopard-intel-release-tests/build/WebKitBuild/Release/{process_name}
quit:
""".format(process_name=process_name, pid=pid)
+
class CrashLogsTest(unittest.TestCase):
def create_crash_logs_darwin(self):
if not SystemHost().platform.is_mac():
message += " cwd: %s" % cwd
Exception.__init__(self, message)
- self.script_args = script_args # 'args' is already used by Exception
+ self.script_args = script_args # 'args' is already used by Exception
self.exit_code = exit_code
self.output = output
self.cwd = cwd
def communicate(self, input=None):
return (self.stdout, self.stderr)
+
# FIXME: This should be unified with MockExecutive2
class MockExecutive(object):
PIPE = "MOCK PIPE"
error = ScriptError('', ('my', 'command'), -1, 'My output.', '/Users/username/blah')
self.assertEqual(error.message_with_output(), 'Failed to run "(\'my\', \'command\')" exit_code: -1 cwd: /Users/username/blah\n\nMy output.')
+
def never_ending_command():
"""Arguments for a command that will never end (useful for testing process
killing). It should be a process that is unlikely to already be running
dirs.append(dirpath)
return sorted(dirs)
-
def files_under(self, path, dirs_to_skip=[], file_filter=None):
def filter_all(fs, dirpath, basename):
return True
self.fs.chdir(self.generic_test_dir)
self.assertEqual(set(self.fs.glob('foo.*')), set(['foo.txt']))
+
class RealFileSystemTest(unittest.TestCase, GenericFileSystemTests):
def setUp(self):
self.fs = FileSystem()
self._log.debug("test message")
self._assert_log_messages(["unittest: [DEBUG] test message\n"])
+
class ConfigureLoggingCustomLevelTest(ConfigureLoggingTestBase):
"""Tests configure_logging() with a custom logging level."""
_log = logging.getLogger(__name__)
+
def abspath_to_uri(platform, path):
"""Converts a platform-specific absolute path to a file: URL."""
return "file:" + _escape(_convert_path(platform, path))
from webkitpy.common.system.platforminfo_mock import MockPlatformInfo
from webkitpy.common.system import path
+
class AbspathTest(unittest.TestCase):
def platforminfo(self):
return SystemHost().platform
from webkitpy.common.system.executive import Executive
+
class PlatformInfo(object):
"""This class provides a consistent (and mockable) interpretation of
system-specific values (like sys.platform and platform.mac_ver())
# Copyright (c) 2009, Google Inc. All rights reserved.
-#
+#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
-#
+#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
-#
+#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.common.system.user import User
+
class UserTest(unittest.TestCase):
example_user_response = "example user response"
def test_prompt_repeat(self):
self.repeatsRemaining = 2
+
def mock_raw_input(message):
self.repeatsRemaining -= 1
if not self.repeatsRemaining:
def test_prompt_when_exceeded_repeats(self):
self.repeatsRemaining = 2
+
def mock_raw_input(message):
self.repeatsRemaining -= 1
return None
def test_create_zip(self):
workspace = Workspace(None, MockExecutive(should_log=True))
expected_logs = "MOCK run_command: ['zip', '-9', '-r', '/zip/path', '.'], cwd=/source/path\n"
+
class MockZipFile(object):
def __init__(self, path):
self.filename = path
MOCK output of child process
"""
+
class MockZipFile(object):
def __init__(self, path):
self.filename = path
is_running = self._is_running
self._messages = []
return (messages, is_running)
-
from webkitpy.common.thread.threadedmessagequeue import ThreadedMessageQueue
+
class ThreadedMessageQueueTest(unittest.TestCase):
def test_basic(self):
tests_to_skip = self.skip_tests(potential_test_paths, tests, expectations, None)
return [test for test in tests if test not in tests_to_skip]
-
def _strip_test_dir_prefixes(self, paths):
return [self._strip_test_dir_prefix(path) for path in paths if path]
TestExpectations = test_expectations.TestExpectations
-
class Manager(object):
"""A class for managing running a series of tests on a series of layout
test files."""
for failure in failures:
failure.write_failure(writer, driver_output, expected_driver_output, port)
+
class TestResultWriter(object):
"""A class which handles all writing operations to the result directory."""
self._write_binary_file(diff_filename, image_diff)
base_dir = self._port.path_from_webkit_base('LayoutTests', 'fast', 'harness')
-
+
image_diff_template = self._filesystem.join(base_dir, 'image-diff-template.html');
image_diff_file = ""
if self._filesystem.exists(image_diff_template):
trie[directory] = {}
add_path_to_trie(rest, value, trie[directory])
+
def test_timings_trie(port, individual_test_timings):
"""Breaks a test name into chunks by directory and puts the test time as a value in the lowest part, e.g.
foo/bar/baz.html: 1ms
return trie
+
# FIXME: We already have a TestResult class in test_results.py
class TestResult(object):
"""A simple class that represents a single test result."""
_log.error("Upload failed: %s" % err)
return
-
def _get_test_timing(self, test_name):
"""Returns test timing data (elapsed time) in second
for the given test_name."""
def path_to_generic_test_expectations_file(self):
return ''
+
class FakeFactory(object):
def __init__(self, host, ports):
self.host = host
import itertools
+
class TestConfiguration(object):
def __init__(self, version, architecture, build_type):
self.version = version
while try_abbreviating(self._collapsing_sets_by_size.values()):
pass
-
# 4) Substitute specifier subsets that match macros witin each set:
# (xp, vista, win7, release) -> (win, release)
self.collapse_macros(self._configuration_macros, specifiers_list)
return item[0].upper()
raise ValueError(expectation)
-
def add_expectation_line(self, expectation_line, in_skipped=False):
"""Returns a list of warnings encountered while matching modifiers."""
_log = logging.getLogger(__name__)
+
def is_reftest_failure(failure_list):
failure_types = [type(f) for f in failure_list]
return set((FailureReftestMismatch, FailureReftestMismatchDidNotOccur, FailureReftestNoImagesGenerated)).intersection(failure_types)
+
# FIXME: This is backwards. Each TestFailure subclass should know what
# test_expectation type it corresponds too. Then this method just
# collects them all from the failure list and returns the worst one.
writer.write_image_files(driver_output.image, expected_image=None)
writer.write_reftest(self.reference_filename)
+
class FailureReftestNoImagesGenerated(TestFailure):
def __init__(self, reference_filename=None):
super(FailureReftestNoImagesGenerated, self).__init__()
INTERRUPTED_EXIT_STATUS = signal.SIGINT + 128
+
class TestRunResults(object):
def __init__(self, expectations, num_tests):
self.total = num_tests
return test_dict
+
# These results must match ones in print_unexpected_results() in views/buildbot_results.py.
def summarize_results(port_obj, expectations, initial_results, retry_results, enabled_pixel_tests_in_retry, include_passes=False, include_time_and_modifiers=False):
"""Returns a dictionary containing a summary of the test runs, with the following fields:
self.assertEqual(host.user.opened_urls, [path.abspath_to_uri(MockHost().platform, '/tmp/layout-test-results/results.html')])
-
def test_batch_size(self):
batch_tests_run = get_test_batches(['--batch-size', '2'])
for batch in batch_tests_run:
self.logger.info('foo %s %d', 'bar', 2)
self.assertEqual(self.buflist, ['foo bar 2\n'])
+
class TtyTest(RegularTest):
verbose = False
isatty = True
else:
return ' failed%s (%s)' % (exp_string, ', '.join(failure.message() for failure in failures))
-
def _print_test_trace(self, result, exp_str, got_str):
test_name = result.test_name
self._print_default(self._test_status_line(test_name, ''))
self._timestamp = time.time()
self._utc_timestamp = datetime.datetime.utcnow()
-
@staticmethod
def _parse_args(args=None):
def _expand_path(option, opt_str, value, parser):
class TestDriverWithStopCount(TestDriver):
stop_count = 0
+
def stop(self):
TestDriverWithStopCount.stop_count += 1
from webkitpy.port import Port, Driver, DriverOutput
from webkitpy.port.test import add_unit_tests_to_mock_filesystem, TestPort
+
class PortTest(unittest.TestCase):
def make_port(self, executive=None, with_tests=False, port_name=None, **kwargs):
host = MockSystemHost()
self.assertEqual(port.pretty_patch.pretty_patch_text("patch.txt"),
port.pretty_patch.pretty_patch_error_html)
-
def test_diff_text(self):
port = self.make_port()
# Make sure that we don't run into decoding exceptions when the
for pattern in patterns:
self.error = re.sub(pattern[0], pattern[1], self.error)
+
class Driver(object):
"""object for running test(s) using DumpRenderTree/WebKitTestRunner."""
else:
self.decoded_content = self.content
+
class DriverProxy(object):
"""A wrapper for managing two Driver instances, one with pixel tests and
one without. This allows us to handle plain text tests and ref tests with a
import os
import sys
+
class DriverOutputTest(unittest.TestCase):
def test_strip_metrics(self):
patterns = [
]
-
def _builder_options(builder_name):
configuration = "Debug" if re.search(r"[d|D](ebu|b)g", builder_name) else "Release"
is_webkit2 = builder_name.find("WK2") != -1
_log = logging.getLogger(__name__)
+
class GtkPort(Port):
port_name = "gtk"
from webkitpy.common.system.outputcapture import OutputCapture
-
class TrivialMockPort(object):
def __init__(self):
self.host = MockSystemHost()
UNEXPECTED_PASSES = 7
UNEXPECTED_FAILURES = 17
+
def unit_test_list():
silent_audio = "RIFF2\x00\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\x22\x56\x00\x00\x44\xAC\x00\x00\x02\x00\x10\x00data\x0E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
silent_audio_with_single_bit_difference = "RIFF2\x00\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\x22\x56\x00\x00\x44\xAC\x00\x00\x02\x00\x10\x00data\x0E\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
def all_baseline_variants(self):
return self.ALL_BASELINE_VARIANTS
+
class TestDriver(Driver):
"""Test/Dummy implementation of the DumpRenderTree interface."""
next_pid = 1
except ImportError:
_log.warn("Not running on native Windows.")
+
class WinPort(ApplePort):
port_name = "win"
# API and therefore do not follow the same header including
# discipline as WebCore.
- ([# TestNetscapePlugIn has no config.h and uses funny names like
+ ([ # TestNetscapePlugIn has no config.h and uses funny names like
# NPP_SetWindow.
os.path.join('Tools', 'DumpRenderTree', 'TestNetscapePlugIn')],
["-build/include",
CMAKE = 11
FEATUREDEFINES = 12
+
class CheckerDispatcher(object):
"""Supports determining whether and how to check style, based on path."""
from common import CarriageReturnChecker
from common import TabChecker
+
# FIXME: The unit tests for the cpp, text, and common checkers should
# share supporting test code. This can include, for example, the
# mock style error handling code and the code to check that all
"better to use only a \\n")
def setUp(self):
- self._style_errors = [] # The list of accumulated style errors.
+ self._style_errors = [] # The list of accumulated style errors.
def _mock_style_error_handler(self, line_number, category, confidence,
message):
return text.lower()
-
def _create_acronym(text):
"""Creates an acronym for the given text."""
# Removes all lower case letters except those starting words.
"""
i = 1
for pos, c in enumerate(s):
- if c == '(':
- i += 1
- elif c == ')':
- i -= 1
- if i == 0:
- return s[:pos], s[pos + 1:]
+ if c == '(':
+ i += 1
+ elif c == ')':
+ i -= 1
+ if i == 0:
+ return s[:pos], s[pos + 1:]
return None, None
+
class _IncludeState(dict):
"""Tracks line numbers for includes, and the order in which includes appear.
self._parameter_list = None
def modifiers_and_return_type(self):
- """Returns the modifiers and the return type."""
- # Go backwards from where the function name is until we encounter one of several things:
- # ';' or '{' or '}' or 'private:', etc. or '#' or return Position(0, 0)
- elided = self._clean_lines.elided
- start_modifiers = _rfind_in_lines(r';|\{|\}|((private|public|protected):)|(#.*)', elided, self.parameter_start_position, Position(0, 0))
- return SingleLineView(elided, start_modifiers, self.function_name_start_position).single_line.strip()
+ """Returns the modifiers and the return type."""
+ # Go backwards from where the function name is until we encounter one of several things:
+ # ';' or '{' or '}' or 'private:', etc. or '#' or return Position(0, 0)
+ elided = self._clean_lines.elided
+ start_modifiers = _rfind_in_lines(r';|\{|\}|((private|public|protected):)|(#.*)', elided, self.parameter_start_position, Position(0, 0))
+ return SingleLineView(elided, start_modifiers, self.function_name_start_position).single_line.strip()
def is_virtual(self):
return bool(search(r'\bvirtual\b', self.modifiers_and_return_type()))
error(line_number, 'readability/fn_size', error_level,
'Small and focused functions are preferred:'
' %s has %d non-comment lines'
- ' (error triggered by exceeding %d lines).' % (
+ ' (error triggered by exceeding %d lines).' % (
self.current_function, self.lines_in_function, trigger))
def end(self):
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
-
# Not SVN <= 1.6? Try to find a git, or svn top level directory by
# searching up from the current path.
root_dir = os.path.dirname(fullname)
# The given item was not closed.
return Position(len(elided), -1)
+
def check_for_copyright(lines, error):
"""Logs an error if no Copyright message appears at the top of the file."""
return True
return True
+
def check_for_non_standard_constructs(clean_lines, line_number,
class_state, error):
"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
else:
break
+
def get_previous_non_blank_line(clean_lines, line_number):
"""Return the most recent non-blank line and its line number.
error: The function to call with any errors found.
"""
- line = clean_lines.elided[line_number] # Get rid of comments and strings.
+ line = clean_lines.elided[line_number] # Get rid of comments and strings.
namespace_match = match(r'(?P<namespace_indentation>\s*)namespace\s+\S+\s*{\s*$', line)
if not namespace_match:
error(line_number, 'whitespace/indent', 4,
'namespace should never be indented.')
return
- looking_for_semicolon = False;
+ looking_for_semicolon = False
line_offset = 0
- in_preprocessor_directive = False;
+ in_preprocessor_directive = False
for current_line in clean_lines.elided[line_number + 1:]:
line_offset += 1
if not current_line.strip():
file_state.set_did_inside_namespace_indent_warning()
error(line_number + line_offset, 'whitespace/indent', 4,
'Code inside a namespace should not be indented.')
- if in_preprocessor_directive or (current_line.strip()[0] == '#'): # This takes care of preprocessor directive syntax.
+ if in_preprocessor_directive or (current_line.strip()[0] == '#'): # This takes care of preprocessor directive syntax.
in_preprocessor_directive = current_line[-1] == '\\'
else:
looking_for_semicolon = ((current_line.find(';') == -1) and (current_line.strip()[-1] != '}')) or (current_line[-1] == '\\')
else:
- looking_for_semicolon = False; # If we have a brace we may not need a semicolon.
+ looking_for_semicolon = False # If we have a brace we may not need a semicolon.
current_indentation_level += current_line.count('{') - current_line.count('}')
current_indentation_level += current_line.count('(') - current_line.count(')')
if current_indentation_level < 0:
- break;
+ break
# Enum declaration whitelist
_ALLOW_ALL_UPPERCASE_ENUM = ['JSTokenType']
+
def check_enum_casing(clean_lines, line_number, enum_state, error):
"""Looks for incorrectly named enum values.
error(line_number, 'readability/enum_casing', 4,
'enum members should use InterCaps with an initial capital letter or initial \'k\' for C-style enums.')
+
def check_directive_indentation(clean_lines, line_number, file_state, error):
"""Looks for indentation of preprocessor directives.
initial_spaces += 1
return initial_spaces
+
def check_indentation_amount(clean_lines, line_number, error):
line = clean_lines.elided[line_number]
initial_spaces = get_initial_spaces_for_line(line)
if file_state.is_c_or_objective_c():
return
- line = clean_lines.elided[line_number] # Get rid of comments and strings.
+ line = clean_lines.elided[line_number] # Get rid of comments and strings.
using_std_match = match(r'\s*using\s+std::(?P<method_name>\S+)\s*;\s*$', line)
if not using_std_match:
error(line_number, 'build/using_namespace', 4,
"Do not use 'using namespace %s;'." % method_name)
+
def check_max_min_macros(clean_lines, line_number, file_state, error):
"""Looks for use of MAX() and MIN() macros that should be replaced with std::max() and std::min().
if file_state.is_c_or_objective_c():
return
- line = clean_lines.elided[line_number] # Get rid of comments and strings.
+ line = clean_lines.elided[line_number] # Get rid of comments and strings.
max_min_macros_search = search(r'\b(?P<max_min_macro>(MAX|MIN))\s*\(', line)
if not max_min_macros_search:
'Use equivelent function in <wtf/ASCIICType.h> instead of the %s() function.'
% (ctype_function))
+
def check_switch_indentation(clean_lines, line_number, error):
"""Looks for indentation errors inside of switch statements.
error: The function to call with any errors found.
"""
- line = clean_lines.elided[line_number] # Get rid of comments and strings.
+ line = clean_lines.elided[line_number] # Get rid of comments and strings.
switch_match = match(r'(?P<switch_indentation>\s*)switch\s*\(.+\)\s*{\s*$', line)
if not switch_match:
# still catch all indentation issues in practice.
encountered_nested_switch = True
- current_indentation_match = match(r'(?P<indentation>\s*)(?P<remaining_line>.*)$', current_line);
+ current_indentation_match = match(r'(?P<indentation>\s*)(?P<remaining_line>.*)$', current_line)
current_indentation = current_indentation_match.group('indentation')
remaining_line = current_indentation_match.group('remaining_line')
error: The function to call with any errors found.
"""
- line = clean_lines.elided[line_number] # Get rid of comments and strings.
+ line = clean_lines.elided[line_number] # Get rid of comments and strings.
if match(r'\s*{\s*$', line):
# We allow an open brace to start a line in the case where someone
error: The function to call with any errors found.
"""
- line = clean_lines.elided[line_number] # Get rid of comments and strings.
+ line = clean_lines.elided[line_number] # Get rid of comments and strings.
else_match = match(r'(?P<else_indentation>\s*)(\}\s*)?else(\s+if\s*\(|(?P<else>\s*(\{\s*)?\Z))', line)
if not else_match:
if current_line == else_indentation + '}':
continue
- current_indentation_match = match(r'(?P<indentation>\s*)(?P<remaining_line>.*)$', current_line);
+ current_indentation_match = match(r'(?P<indentation>\s*)(?P<remaining_line>.*)$', current_line)
current_indentation = current_indentation_match.group('indentation')
remaining_line = current_indentation_match.group('remaining_line')
if search(r'\bNULL\b', line) and search(r'\bNULL\b', CleansedLines.collapse_strings(line)):
error(line_number, 'readability/null', 4, 'Use nullptr instead of NULL (even in *comments*).')
+
def get_line_width(line):
"""Determines the width of the line in column positions.
'Consider using toText helper function in WebCore/dom/Text.h '
'instead of static_cast<Text*>')
+
def check_identifier_name_in_declaration(filename, line_number, line, file_state, error):
"""Checks if identifier names contain any underscores.
number_of_identifiers += 1
line = line[matched.end():]
+
def check_c_style_cast(line_number, line, raw_line, cast_type, pattern,
error):
"""Checks for a C-style cast by looking for the pattern.
# include_state is modified during iteration, so we iterate over a copy of
# the keys.
- for header in include_state.keys(): #NOLINT
+ for header in include_state.keys(): # NOLINT
(same_module, common_path) = files_belong_to_same_module(abs_filename, header)
fullpath = common_path + header
if same_module and update_include_state(fullpath, include_state):
error(line_number, 'build/cpp_comment', 5, 'CPP comments are not allowed in Platform.h, '
'please use C comments /* ... */')
+
def process_line(filename, file_extension,
clean_lines, line, include_state, function_state,
class_state, file_state, enum_state, asm_state, error):
from cpp import CppChecker
from ..filter import FilterConfiguration
+
# This class works as an error collector and replaces cpp_style.Error
# function for the unit tests. We also verify each category we see
# is in CppChecker.categories, to help keep that list up to date.
self.assertEqual(error_collector.results(),
'The parameter name "ooF" adds no information, so it should be removed. [readability/parameter_name] [5]')
+
class CppStyleTestBase(unittest.TestCase):
"""Provides some useful helper functions for cpp_style tests.
# FIXME: Refactor the unit tests so the confidence level is passed
# explicitly, just like it is in the real code.
- min_confidence = 1;
+ min_confidence = 1
# Helper function to avoid needing to explicitly pass confidence
# in all the unit test calls to cpp_style.process_file_data().
def test_rvaule_reference_in_parameter_pack(self):
self.assert_lint('void requestCompleted(Arguments&&... arguments)', '')
+
class CppStyleTest(CppStyleTestBase):
def test_asm_lines_ignored(self):
' [whitespace/comments] [5]')
self.assert_lint('printf("foo"); // Outside quotes.',
'')
- self.assert_lint('int i = 0; // Having one space is fine.','')
+ self.assert_lint('int i = 0; // Having one space is fine.', '')
self.assert_lint('int i = 0; // Having two spaces is bad.',
'One space before end of line comments'
' [whitespace/comments] [5]')
self.assert_lint('int a = 1 ? 0 : 30;', '')
self.assert_lint('bool a : 1;', '')
+
class CleansedLinesTest(unittest.TestCase):
def test_init(self):
lines = ['Line 1',
self.assert_lint('Ref<Node> protector = node;', '')
self.assert_lint('Ref<Node> protector = *node;', '')
-
# Invalid protector RefPtr/Ref variable names.
self.assert_lint('RefPtr<Node> protector(this);', "'protector' is incorrectly named. It should be named 'protectedThis'. [readability/naming/protected] [4]")
self.assert_lint('Ref<Node> protector(*this);', "'protector' is incorrectly named. It should be named 'protectedThis'. [readability/naming/protected] [4]")
from common import TabChecker
import re
+
class JSChecker(object):
"""Processes JavaScript lines for checking style."""
import re
from sets import Set
+
class JSONChecker(object):
"""Processes JSON lines for checking style."""
from webkitpy.common.system.systemhost import SystemHost
from webkitpy.common.checkout.scm.detection import SCMDetector
+
class PNGChecker(object):
"""Check svn:mime-type for checking style"""
if prop_get != "image/png":
errorstr = "Set the svn:mime-type property (svn propset svn:mime-type image/png %s)." % self._file_path
self._handle_style_error(0, 'image/png', 5, errorstr)
-
from common import TabChecker
+
class TextChecker(object):
"""Processes text lines for checking style."""
import text as text_style
from text import TextChecker
+
class TextStyleTestCase(unittest.TestCase):
"""TestCase for text_style.py"""
self.process_file_data('', lines, error_for_test)
self.assertTrue(self.had_error, '%s should have an error [whitespace/tab].' % lines)
-
def test_no_error(self):
"""Tests for no error cases."""
self.assertNoError([''])
self.assertNoError(['abc def', 'ggg'])
-
def test_error(self):
"""Tests for error cases."""
self.assertError(['2009-12-16\tKent Tamura\t<tkent@chromium.org>'], 1)
def _add_reportable_error(self, category):
"""Increment the error count and return the new category total."""
- self._increment_error_count() # Increment the total.
+ self._increment_error_count() # Increment the total.
# Increment the category total.
if not category in self._category_totals:
filter_rules = []
self._filter_rules = filter_rules
- self._should_check_category = {} # Cached dictionary of category to True/False
+ self._should_check_category = {} # Cached dictionary of category to True/False
def __str__(self):
return ",".join(self._filter_rules)
if category in self._should_check_category:
return self._should_check_category[category]
- should_check = True # All categories checked by default.
+ should_check = True # All categories checked by default.
for rule in self._filter_rules:
if not category.startswith(rule[1:]):
continue
should_check = rule.startswith('+')
- self._should_check_category[category] = should_check # Update cache.
+ self._should_check_category[category] = should_check # Update cache.
return should_check
for sub_path in sub_paths:
if path.find(sub_path) > -1:
return tuple(path_rules)
- return () # Default to the empty tuple.
+ return () # Default to the empty tuple.
def _filter_from_path_rules(self, path_rules):
"""Return the CategoryFilter associated to the given path rules.
# We reuse the same CategoryFilter where possible to take
# advantage of the caching they do.
if path_rules not in self._path_rules_to_filter:
- rules = list(self._base_rules) # Make a copy
+ rules = list(self._base_rules) # Make a copy
rules.extend(path_rules)
rules.extend(self._user_rules)
self._path_rules_to_filter[path_rules] = _CategoryFilter(rules)
"""
return self._filter_from_path(path).should_check(category)
-
#
# (from http://docs.python.org/reference/datamodel.html#object.__ne__ )
+
class ValidateFilterRulesTest(unittest.TestCase):
"""Tests validate_filter_rules() function."""
self.assertFalse(config.should_check("a", "path"))
self.assertTrue(config.should_check("b", "path"))
-
"""Supports the printing of check-webkit-style command arguments."""
def _flag_pair_to_string(self, flag_key, flag_value):
- return '--%(key)s=%(val)s' % {'key': flag_key, 'val': flag_value }
+ return '--%(key)s=%(val)s' % {'key': flag_key, 'val': flag_value}
def to_flag_string(self, options):
"""Return a flag string of the given CommandOptionValues instance.
git_index=git_index)
return (paths, options)
-
"""Return an ArgumentParser instance for testing."""
default_options = self._create_defaults()
- all_categories = ["build" ,"whitespace"]
+ all_categories = ["build", "whitespace"]
mock_stderr = self._MockStdErr()
self.assertRaises(SystemExit, parse, ['--min-confidence=6'])
self.assertLog(['ERROR: option --min-confidence: invalid integer: 6: '
'value must be between 1 and 5\n'])
- parse(['--min-confidence=1']) # works
- parse(['--min-confidence=5']) # works
+ parse(['--min-confidence=1']) # works
+ parse(['--min-confidence=5']) # works
self.assertRaises(SystemExit, parse, ['--output=bad'])
self.assertLog(['ERROR: option --output-format: invalid choice: '
"'bad' (choose from 'emacs', 'vs7')\n"])
- parse(['--output=vs7']) # works
+ parse(['--output=vs7']) # works
# Pass a filter rule not beginning with + or -.
self.assertRaises(SystemExit, parse, ['--filter=build'])
self.assertLog(['ERROR: Invalid filter rule "build": '
'every rule must start with + or -.\n'])
- parse(['--filter=+build']) # works
+ parse(['--filter=+build']) # works
def test_parse_default_arguments(self):
parse = self._parse
# Check argument validation.
self.assertRaises(ValueError, ProcessorOptions, output_format="bad")
- ProcessorOptions(output_format="emacs") # No ValueError: works
- ProcessorOptions(output_format="vs7") # works
+ ProcessorOptions(output_format="emacs") # No ValueError: works
+ ProcessorOptions(output_format="vs7") # works
self.assertRaises(ValueError, ProcessorOptions, min_confidence=0)
self.assertRaises(ValueError, ProcessorOptions, min_confidence=6)
- ProcessorOptions(min_confidence=1) # works
- ProcessorOptions(min_confidence=5) # works
+ ProcessorOptions(min_confidence=1) # works
+ ProcessorOptions(min_confidence=5) # works
# Check attributes.
options = ProcessorOptions(filter_rules=["+"],
# Thus, just check the distinguishing case to verify that the
# code defines __ne__.
self.assertFalse(ProcessorOptions().__ne__(ProcessorOptions()))
-
json.dump(results, stream, separators=(',', ':'))
+
class Tester(object):
def __init__(self, filesystem=None):
self.finder = Finder(filesystem or FileSystem())
def handle_pi(self, data):
self.converted_data.extend(['<?', data, '>'])
-
DUMMY_FILENAME = 'dummy.html'
DUMMY_PATH = 'dummy/testharness/path'
+
class W3CTestConverterTest(unittest.TestCase):
# FIXME: When we move to using a MockHost, this method should be removed, since
]
''' }
+
class TestImporterTest(unittest.TestCase):
def _parse_options(self, args):
Do not use PyObjC to dlopen the framework.
"""
+
class DeviceType(object):
"""
Represents a CoreSimulator device type.