Commit a84d0f87 authored by Igor Makarov's avatar Igor Makarov Committed by Commit Bot

Reformat python code in third_party/blink/tools/blinkpy/style for PEP8

- added .style.yapf file
- reformat *.py files

Bug: 1051750
Change-Id: I4d1e6054ce940d975710d8114f2f193304b554c2
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2134236Reviewed-by: default avatarKent Tamura <tkent@chromium.org>
Commit-Queue: Kent Tamura <tkent@chromium.org>
Cr-Commit-Position: refs/heads/master@{#758456}
parent 2465afa5
......@@ -19,22 +19,17 @@
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Supports style checking not specific to any one file type."""
# FIXME: Test this list in the same way that the list of CppChecker
# categories is tested, for example by checking that all of its
# elements appear in the unit tests. This should probably be done
# after moving the relevant cpp_unittest.ErrorCollector code
# into a shared location and refactoring appropriately.
categories = set([
'whitespace/carriage_return',
'whitespace/tab'])
categories = set(['whitespace/carriage_return', 'whitespace/tab'])
class CarriageReturnChecker(object):
"""Supports checking for and handling carriage returns."""
def __init__(self, handle_style_error):
......@@ -46,7 +41,8 @@ class CarriageReturnChecker(object):
if not lines[line_number].endswith('\r'):
continue
self._handle_style_error(line_number + 1, # Correct for offset.
self._handle_style_error(
line_number + 1, # Correct for offset.
'whitespace/carriage_return',
1,
'One or more unexpected \\r (^M) found; '
......@@ -58,7 +54,6 @@ class CarriageReturnChecker(object):
class TabChecker(object):
"""Supports checking for and handling tabs."""
def __init__(self, file_path, handle_style_error):
......@@ -69,6 +64,5 @@ class TabChecker(object):
# FIXME: share with cpp_style.
for line_number, line in enumerate(lines):
if '\t' in line:
self.handle_style_error(line_number + 1,
'whitespace/tab', 5,
self.handle_style_error(line_number + 1, 'whitespace/tab', 5,
'Line contains tab character.')
......@@ -19,7 +19,6 @@
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for common.py."""
import unittest
......@@ -36,7 +35,6 @@ from blinkpy.style.checkers.common import TabChecker
class CarriageReturnCheckerTest(unittest.TestCase):
"""Tests check_no_carriage_return()."""
_category = 'whitespace/carriage_return'
......@@ -69,35 +67,29 @@ class CarriageReturnCheckerTest(unittest.TestCase):
self.assertEqual(self._style_errors, expected_errors)
def test_ends_with_carriage(self):
self.assert_carriage_return(['carriage return\r'],
['carriage return'],
self.assert_carriage_return(['carriage return\r'], ['carriage return'],
[1])
def test_ends_with_nothing(self):
self.assert_carriage_return(['no carriage return'],
['no carriage return'],
[])
['no carriage return'], [])
def test_ends_with_newline(self):
self.assert_carriage_return(['no carriage return\n'],
['no carriage return\n'],
[])
['no carriage return\n'], [])
def test_carriage_in_middle(self):
# The CarriageReturnChecker checks only the final character
# of each line.
self.assert_carriage_return(['carriage\r in a string'],
['carriage\r in a string'],
[])
['carriage\r in a string'], [])
def test_multiple_errors(self):
self.assert_carriage_return(['line1', 'line2\r', 'line3\r'],
['line1', 'line2', 'line3'],
[2, 3])
['line1', 'line2', 'line3'], [2, 3])
class TabCheckerTest(unittest.TestCase):
"""Tests for TabChecker."""
def assert_tab(self, input_lines, error_lines):
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -19,7 +19,6 @@
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Checks WebKit style for JSON files."""
import json
......@@ -29,7 +28,7 @@ import re
class JSONChecker(object):
"""Processes JSON lines for checking style."""
categories = set(('json/syntax',))
categories = set(('json/syntax', ))
def __init__(self, _, handle_style_error):
self._handle_style_error = handle_style_error
......@@ -40,8 +39,8 @@ class JSONChecker(object):
json.loads('\n'.join(lines) + '\n')
except ValueError as error:
self._handle_style_error(
self.line_number_from_json_exception(error),
'json/syntax', 5, str(error))
self.line_number_from_json_exception(error), 'json/syntax', 5,
str(error))
@staticmethod
def line_number_from_json_exception(error):
......
......@@ -19,7 +19,6 @@
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for jsonchecker.py."""
import unittest
......@@ -28,7 +27,6 @@ from blinkpy.style.checkers import jsonchecker
class MockErrorHandler(object):
def __init__(self, handle_style_error):
self.turned_off_filtering = False
self._handle_style_error = handle_style_error
......@@ -37,7 +35,8 @@ class MockErrorHandler(object):
self.turned_off_filtering = True
def __call__(self, line_number, category, confidence, message):
self._handle_style_error(self, line_number, category, confidence, message)
self._handle_style_error(self, line_number, category, confidence,
message)
return True
......@@ -52,11 +51,16 @@ class JSONCheckerTest(unittest.TestCase):
(9, 'Expecting property name: line 9 column 21 (char 478)'),
)
for expected_line, message in tests:
self.assertEqual(expected_line, jsonchecker.JSONChecker.line_number_from_json_exception(ValueError(message)))
self.assertEqual(
expected_line,
jsonchecker.JSONChecker.line_number_from_json_exception(
ValueError(message)))
def assert_no_error(self, json_data):
def handle_style_error(mock_error_handler, line_number, category, confidence, message):
self.fail('Unexpected error: %d %s %d %s' % (line_number, category, confidence, message))
def handle_style_error(mock_error_handler, line_number, category,
confidence, message):
self.fail('Unexpected error: %d %s %d %s' % (line_number, category,
confidence, message))
error_handler = MockErrorHandler(handle_style_error)
checker = jsonchecker.JSONChecker('foo.json', error_handler)
......@@ -64,7 +68,8 @@ class JSONCheckerTest(unittest.TestCase):
self.assertTrue(error_handler.turned_off_filtering)
def assert_error(self, expected_line_number, expected_category, json_data):
def handle_style_error(mock_error_handler, line_number, category, confidence, message):
def handle_style_error(mock_error_handler, line_number, category,
confidence, message):
mock_error_handler.had_error = True
self.assertEqual(expected_line_number, line_number)
self.assertEqual(expected_category, category)
......
......@@ -20,7 +20,6 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Supports checking WebKit style in png files."""
from blinkpy.common import read_checksum_from_png
......@@ -38,9 +37,12 @@ class PNGChecker(object):
self._fs = self._host.filesystem
def check(self, inline=None):
if self._fs.exists(self._file_path) and self._file_path.endswith('-expected.png'):
with self._fs.open_binary_file_for_reading(self._file_path) as filehandle:
if self._fs.exists(
self._file_path) and self._file_path.endswith('-expected.png'):
with self._fs.open_binary_file_for_reading(
self._file_path) as filehandle:
if not read_checksum_from_png.read_checksum(filehandle):
self._handle_style_error(
0, 'image/png', 5,
'Image lacks a checksum. Generate pngs using run_web_tests.py to ensure they have a checksum.')
'Image lacks a checksum. Generate pngs using run_web_tests.py to ensure they have a checksum.'
)
......@@ -20,7 +20,6 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for png.py."""
import unittest
......@@ -39,14 +38,16 @@ class PNGCheckerTest(unittest.TestCase):
def mock_handle_style_error(self):
pass
checker = PNGChecker("test/config", mock_handle_style_error, MockSystemHost())
checker = PNGChecker("test/config", mock_handle_style_error,
MockSystemHost())
self.assertEqual(checker._file_path, "test/config")
self.assertEqual(checker._handle_style_error, mock_handle_style_error)
def test_check(self):
errors = []
def mock_handle_style_error(line_number, category, confidence, message):
def mock_handle_style_error(line_number, category, confidence,
message):
error = (line_number, category, confidence, message)
errors.append(error)
......@@ -55,16 +56,19 @@ class PNGCheckerTest(unittest.TestCase):
file_path = "foo.png"
fs.write_binary_file(file_path, "Dummy binary data")
errors = []
checker = PNGChecker(file_path, mock_handle_style_error, MockSystemHost(os_name='linux', filesystem=fs))
checker = PNGChecker(file_path, mock_handle_style_error,
MockSystemHost(os_name='linux', filesystem=fs))
checker.check()
self.assertEqual(len(errors), 0)
file_path = "foo-expected.png"
fs.write_binary_file(file_path, "Dummy binary data")
errors = []
checker = PNGChecker(file_path, mock_handle_style_error, MockSystemHost(os_name='linux', filesystem=fs))
checker = PNGChecker(file_path, mock_handle_style_error,
MockSystemHost(os_name='linux', filesystem=fs))
checker.check()
self.assertEqual(len(errors), 1)
self.assertEqual(
errors[0],
(0, 'image/png', 5, 'Image lacks a checksum. Generate pngs using run_web_tests.py to ensure they have a checksum.'))
self.assertEqual(errors[0], (
0, 'image/png', 5,
'Image lacks a checksum. Generate pngs using run_web_tests.py to ensure they have a checksum.'
))
......@@ -19,14 +19,12 @@
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Supports checking WebKit style in Python files."""
import os
import re
import sys
from blinkpy.common.path_finder import PathFinder
from blinkpy.common.path_finder import get_blink_tools_dir
from blinkpy.common.path_finder import get_blinkpy_thirdparty_dir
......@@ -94,7 +92,9 @@ class PythonChecker(object):
'--output-format=parseable',
'--rcfile=' + finder.path_from_blink_tools('blinkpy', 'pylintrc'),
path,
], env=env, error_handler=executive.ignore_error)
],
env=env,
error_handler=executive.ignore_error)
def _parse_pylint_output(self, output):
# We filter out these messages because they are bugs in pylint that produce false positives.
......@@ -123,7 +123,8 @@ class PythonChecker(object):
category_and_method = match_obj.group(3).split(', ')
category = 'pylint/' + (category_and_method[0])
if len(category_and_method) > 1:
message = '[%s] %s' % (category_and_method[1], match_obj.group(4))
message = '[%s] %s' % (category_and_method[1],
match_obj.group(4))
else:
message = match_obj.group(4)
errors.append((line_number, category, message))
......
......@@ -19,7 +19,6 @@
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for python.py."""
import os
......@@ -29,7 +28,6 @@ from blinkpy.style.checkers.python import PythonChecker
class PythonCheckerTest(unittest.TestCase):
"""Tests the PythonChecker class."""
def test_init(self):
......@@ -40,8 +38,7 @@ class PythonCheckerTest(unittest.TestCase):
checker = PythonChecker("foo.txt", _mock_handle_style_error)
self.assertEqual(checker._file_path, "foo.txt")
self.assertEqual(checker._handle_style_error,
_mock_handle_style_error)
self.assertEqual(checker._handle_style_error, _mock_handle_style_error)
# TODO(crbug.com/757067): Figure out why this is failing on LUCI mac/win.
def disable_test_check(self):
......@@ -59,13 +56,13 @@ class PythonCheckerTest(unittest.TestCase):
checker = PythonChecker(file_path, _mock_handle_style_error)
checker.check()
self.assertEqual(
[
self.assertEqual([
(2, 'pep8/W291', 5, 'trailing whitespace'),
(3, 'pep8/E261', 5, 'at least two spaces before inline comment'),
(3, 'pep8/E262', 5, "inline comment should start with '# '"),
(2, 'pylint/C0303(trailing-whitespace)', 5, '[] Trailing whitespace'),
(2, 'pylint/E0602(undefined-variable)', 5, u"[] Undefined variable 'error'"),
(2, 'pylint/C0303(trailing-whitespace)', 5,
'[] Trailing whitespace'),
(2, 'pylint/E0602(undefined-variable)', 5,
u"[] Undefined variable 'error'"),
(3, 'pylint/W0611(unused-import)', 5, '[] Unused import math'),
],
errors)
], errors)
......@@ -25,7 +25,6 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Checks WebKit style for test_expectations files."""
import logging
......@@ -51,7 +50,8 @@ class TestExpectationsChecker(object):
self._port_obj = host.port_factory.get()
# Suppress error messages of test_expectations module since they will be reported later.
log = logging.getLogger('blinkpy.web_tests.layout_package.test_expectations')
log = logging.getLogger(
'blinkpy.web_tests.layout_package.test_expectations')
log.setLevel(logging.CRITICAL)
def check_test_expectations(self, expectations_str, tests=None):
......@@ -66,7 +66,8 @@ class TestExpectationsChecker(object):
def check(self, lines):
expectations = '\n'.join(lines)
if self._port_obj:
self.check_test_expectations(expectations_str=expectations, tests=None)
self.check_test_expectations(
expectations_str=expectations, tests=None)
# Warn tabs in lines as well
self.check_tabs(lines)
......@@ -42,7 +42,11 @@ class ErrorCollector(object):
def turn_off_line_filtering(self):
self.turned_off_filtering = True
def __call__(self, lineno=0, category='test/expectations', confidence=100, message=''):
def __call__(self,
lineno=0,
category='test/expectations',
confidence=100,
message=''):
self._errors.append('%s\n[%s] [%d]' % (message, category, confidence))
return True
......@@ -65,20 +69,21 @@ class TestExpectationsTestCase(unittest.TestCase):
self._error_collector.reset_errors()
host = MockHost()
checker = TestExpectationsChecker('test/TestExpectations',
self._error_collector, host=host)
checker = TestExpectationsChecker(
'test/TestExpectations', self._error_collector, host=host)
# We should have a valid port, but override it with a test port so we
# can check the lines.
self.assertIsNotNone(checker._port_obj)
checker._port_obj = host.port_factory.get('test-mac-mac10.10')
checker.check_test_expectations(expectations_str='\n'.join(lines),
tests=[self._test_file])
checker.check_test_expectations(
expectations_str='\n'.join(lines), tests=[self._test_file])
checker.check_tabs(lines)
if should_pass:
self.assertEqual('', self._error_collector.get_errors())
elif expected_output:
self.assertEqual(expected_output, self._error_collector.get_errors())
self.assertEqual(expected_output,
self._error_collector.get_errors())
else:
self.assertNotEquals('', self._error_collector.get_errors())
......@@ -92,16 +97,25 @@ class TestExpectationsTestCase(unittest.TestCase):
self.assert_lines_lint([
'# tags: [ Mac ]\n'
'# results: [ Pass Failure ]\n'
'crbug.com/1234 [ Mac ] passes/text.html [ Pass Failure ]'], should_pass=True)
'crbug.com/1234 [ Mac ] passes/text.html [ Pass Failure ]'
],
should_pass=True)
def test_invalid_expectations(self):
self.assert_lines_lint(['Bug(me) passes/text.html [ Give Up]'], should_pass=False)
self.assert_lines_lint(['Bug(me) passes/text.html [ Give Up]'],
should_pass=False)
def test_tab(self):
self.assert_lines_lint([
self.assert_lines_lint(
[
'# results: [ Pass ]\n'
'\tcrbug.com/b/1 passes/text.html [ Pass ]'], should_pass=False,
expected_output='Line contains tab character.\n[whitespace/tab] [5]')
'\tcrbug.com/b/1 passes/text.html [ Pass ]'
],
should_pass=False,
expected_output='Line contains tab character.\n[whitespace/tab] [5]'
)
def test_missing_expectation_not_allowed(self):
self.assert_lines_lint(['crbug.com/1234 [ Mac ] passes/text.html [ Missing ]'], should_pass=False)
self.assert_lines_lint(
['crbug.com/1234 [ Mac ] passes/text.html [ Missing ]'],
should_pass=False)
......@@ -26,7 +26,6 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Checks WebKit style for text files."""
from blinkpy.style.checkers.common import TabChecker
......
......@@ -43,7 +43,8 @@ class TextStyleTestCase(unittest.TestCase):
self.had_error = True
process_file_data('', lines, error_for_test)
self.assertFalse(self.had_error, '%s should not have any errors.' % lines)
self.assertFalse(self.had_error,
'%s should not have any errors.' % lines)
def assertError(self, lines, expected_line_number):
"""Asserts that the specified lines has an error."""
......@@ -56,7 +57,8 @@ class TextStyleTestCase(unittest.TestCase):
self.had_error = True
process_file_data('', lines, error_for_test)
self.assertTrue(self.had_error, '%s should have an error [whitespace/tab].' % lines)
self.assertTrue(self.had_error,
'%s should have an error [whitespace/tab].' % lines)
def test_no_error(self):
"""Tests for no error cases."""
......@@ -66,13 +68,13 @@ class TextStyleTestCase(unittest.TestCase):
def test_error(self):
"""Tests for error cases."""
self.assertError(['2009-12-16\tKent Tamura\t<tkent@chromium.org>'], 1)
self.assertError(['2009-12-16 Kent Tamura <tkent@chromium.org>',
'',
'\tReviewed by NOBODY.'], 3)
self.assertError([
'2009-12-16 Kent Tamura <tkent@chromium.org>', '',
'\tReviewed by NOBODY.'
], 3)
class TextCheckerTest(unittest.TestCase):
"""Tests TextChecker class."""
def mock_handle_style_error(self):
......@@ -82,4 +84,5 @@ class TextCheckerTest(unittest.TestCase):
"""Test __init__ constructor."""
checker = TextChecker('foo.txt', self.mock_handle_style_error)
self.assertEqual(checker.file_path, 'foo.txt')
self.assertEqual(checker.handle_style_error, self.mock_handle_style_error)
self.assertEqual(checker.handle_style_error,
self.mock_handle_style_error)
......@@ -20,21 +20,20 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Checks Xcode project files."""
import re
class XcodeProjectFileChecker(object):
"""Processes Xcode project file lines for checking style."""
def __init__(self, file_path, handle_style_error):
self.file_path = file_path
self.handle_style_error = handle_style_error
self.handle_style_error.turn_off_line_filtering()
self._development_region_regex = re.compile('developmentRegion = (?P<region>.+);')
self._development_region_regex = re.compile(
'developmentRegion = (?P<region>.+);')
def _check_development_region(self, line_index, line):
"""Returns True when developmentRegion is detected."""
......@@ -42,8 +41,7 @@ class XcodeProjectFileChecker(object):
if not matched:
return False
if matched.group('region') != 'English':
self.handle_style_error(line_index,
'xcodeproj/settings', 5,
self.handle_style_error(line_index, 'xcodeproj/settings', 5,
'developmentRegion is not English.')
return True
......@@ -54,6 +52,6 @@ class XcodeProjectFileChecker(object):
development_region_is_detected = True
if not development_region_is_detected:
self.handle_style_error(len(lines),
'xcodeproj/settings', 5,
self.handle_style_error(
len(lines), 'xcodeproj/settings', 5,
'Missing "developmentRegion = English".')
......@@ -20,7 +20,6 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for xcodeproj.py."""
import unittest
......@@ -47,7 +46,8 @@ class XcodeProjectFileCheckerTest(unittest.TestCase):
def assert_no_error(self, lines):
def handler(error_handler, line_number, category, confidence, message):
self.fail('Unexpected error: %d %s %d %s' % (line_number, category, confidence, message))
self.fail('Unexpected error: %d %s %d %s' % (line_number, category,
confidence, message))
error_handler = TestErrorHandler(handler)
checker = xcodeproj.XcodeProjectFileChecker('', error_handler)
......@@ -59,10 +59,13 @@ class XcodeProjectFileCheckerTest(unittest.TestCase):
def handler(error_handler, line_number, category, confidence, message):
self.assertEqual(expected_message, message)
self.had_error = True
error_handler = TestErrorHandler(handler)
checker = xcodeproj.XcodeProjectFileChecker('', error_handler)
checker.check(lines)
self.assertTrue(self.had_error, '%s should have error: %s.' % (lines, expected_message))
self.assertTrue(
self.had_error,
'%s should have error: %s.' % (lines, expected_message))
def test_detect_development_region(self):
self.assert_no_error(['developmentRegion = English;'])
......
......@@ -19,7 +19,6 @@
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Checks WebKit style for XML files."""
from __future__ import absolute_import
......@@ -42,4 +41,5 @@ class XMLChecker(object):
parser.Parse('\n')
parser.Parse('', True)
except expat.ExpatError as error:
self._handle_style_error(error.lineno, 'xml/syntax', 5, expat.ErrorString(error.code))
self._handle_style_error(error.lineno, 'xml/syntax', 5,
expat.ErrorString(error.code))
......@@ -19,7 +19,6 @@
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for xml.py."""
import unittest
......@@ -28,7 +27,6 @@ from blinkpy.style.checkers import xml
class MockErrorHandler(object):
def __init__(self, handle_style_error):
self.turned_off_filtering = False
self._handle_style_error = handle_style_error
......@@ -37,7 +35,8 @@ class MockErrorHandler(object):
self.turned_off_filtering = True
def __call__(self, line_number, category, confidence, message):
self._handle_style_error(self, line_number, category, confidence, message)
self._handle_style_error(self, line_number, category, confidence,
message)
return True
......@@ -45,8 +44,10 @@ class XMLCheckerTest(unittest.TestCase):
"""Tests XMLChecker class."""
def assert_no_error(self, xml_data):
def handle_style_error(mock_error_handler, line_number, category, confidence, message):
self.fail('Unexpected error: %d %s %d %s' % (line_number, category, confidence, message))
def handle_style_error(mock_error_handler, line_number, category,
confidence, message):
self.fail('Unexpected error: %d %s %d %s' % \
(line_number, category, confidence, message))
error_handler = MockErrorHandler(handle_style_error)
checker = xml.XMLChecker('foo.xml', error_handler)
......@@ -54,7 +55,8 @@ class XMLCheckerTest(unittest.TestCase):
self.assertTrue(error_handler.turned_off_filtering)
def assert_error(self, expected_line_number, expected_category, xml_data):
def handle_style_error(mock_error_handler, line_number, category, confidence, message):
def handle_style_error(mock_error_handler, line_number, category,
confidence, message):
mock_error_handler.had_error = True
self.assertEqual(expected_line_number, line_number)
self.assertEqual(expected_category, category)
......
......@@ -19,7 +19,6 @@
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Defines style error handler classes.
A style error handler is a function to call when a style error is
......@@ -49,10 +48,12 @@ Methods:
class DefaultStyleErrorHandler(object):
"""The default style error handler."""
def __init__(self, file_path, configuration, increment_error_count,
def __init__(self,
file_path,
configuration,
increment_error_count,
line_numbers=None):
"""Create a default style error handler.
......@@ -126,7 +127,11 @@ class DefaultStyleErrorHandler(object):
def turn_off_line_filtering(self):
self._line_numbers = None
def __call__(self, line_number=0, category='error', confidence='1', message=''):
def __call__(self,
line_number=0,
category='error',
confidence='1',
message=''):
"""Handle the occurrence of a style error.
See the docstring of this module for more information.
......@@ -134,7 +139,8 @@ class DefaultStyleErrorHandler(object):
if not self.should_line_be_checked(line_number):
return False
if not self._configuration.is_reportable(category=category,
if not self._configuration.is_reportable(
category=category,
confidence_in_error=confidence,
file_path=self._file_path):
return False
......@@ -147,12 +153,14 @@ class DefaultStyleErrorHandler(object):
# Then suppress displaying the error.
return False
self._configuration.write_style_error(category=category,
self._configuration.write_style_error(
category=category,
confidence_in_error=confidence,
file_path=self._file_path,
line_number=line_number,
message=message)
if category_total == max_reports:
self._configuration.stderr_write('Suppressing further [%s] reports '
self._configuration.stderr_write(
'Suppressing further [%s] reports '
'for this file.\n' % category)
return True
......@@ -19,7 +19,6 @@
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for error_handlers.py."""
import unittest
......@@ -30,7 +29,6 @@ from blinkpy.style.filter import FilterConfiguration
class DefaultStyleErrorHandlerTest(unittest.TestCase):
"""Tests the DefaultStyleErrorHandler class."""
def setUp(self):
......@@ -62,7 +60,8 @@ class DefaultStyleErrorHandlerTest(unittest.TestCase):
stderr_write=self._mock_stderr_write)
def _error_handler(self, configuration, line_numbers=None):
return DefaultStyleErrorHandler(configuration=configuration,
return DefaultStyleErrorHandler(
configuration=configuration,
file_path=self._file_path,
increment_error_count=self._mock_increment_error_count,
line_numbers=line_numbers)
......@@ -74,7 +73,8 @@ class DefaultStyleErrorHandlerTest(unittest.TestCase):
def _call_error_handler(self, handle_error, confidence, line_number=100):
"""Call the given error handler with a test error."""
handle_error(line_number=line_number,
handle_error(
line_number=line_number,
category=self._category,
confidence=confidence,
message='message')
......@@ -88,11 +88,14 @@ class DefaultStyleErrorHandlerTest(unittest.TestCase):
def test_eq__false_return_value(self):
"""Test the __eq__() method for the return value of False."""
def make_handler(configuration=self._style_checker_configuration(),
file_path='foo.txt', increment_error_count=lambda: True,
file_path='foo.txt',
increment_error_count=lambda: True,
line_numbers=None):
line_numbers = line_numbers or [100]
return DefaultStyleErrorHandler(configuration=configuration,
return DefaultStyleErrorHandler(
configuration=configuration,
file_path=file_path,
increment_error_count=increment_error_count,
line_numbers=line_numbers)
......@@ -105,7 +108,8 @@ class DefaultStyleErrorHandlerTest(unittest.TestCase):
# Verify that a difference in any argument causes equality to fail.
self.assertFalse(handler.__eq__(make_handler(configuration=None)))
self.assertFalse(handler.__eq__(make_handler(file_path='bar.txt')))
self.assertFalse(handler.__eq__(make_handler(increment_error_count=None)))
self.assertFalse(
handler.__eq__(make_handler(increment_error_count=None)))
self.assertFalse(handler.__eq__(make_handler(line_numbers=[50])))
def test_ne(self):
......@@ -125,8 +129,8 @@ class DefaultStyleErrorHandlerTest(unittest.TestCase):
confidence = 1
# Confirm the error is not reportable.
self.assertFalse(configuration.is_reportable(self._category,
confidence,
self.assertFalse(
configuration.is_reportable(self._category, confidence,
self._file_path))
error_handler = self._error_handler(configuration)
self._call_error_handler(error_handler, confidence)
......@@ -158,7 +162,8 @@ class DefaultStyleErrorHandlerTest(unittest.TestCase):
self.assertEqual(3, len(self._error_messages))
self.assertEqual(self._error_messages[-2],
'foo.h(100): message [whitespace/tab] [5]\n')
self.assertEqual(self._error_messages[-1],
self.assertEqual(
self._error_messages[-1],
'Suppressing further [whitespace/tab] reports '
'for this file.\n')
......@@ -171,8 +176,7 @@ class DefaultStyleErrorHandlerTest(unittest.TestCase):
"""Test the line_numbers parameter."""
self._check_initialized()
configuration = self._style_checker_configuration()
error_handler = self._error_handler(configuration,
line_numbers=[50])
error_handler = self._error_handler(configuration, line_numbers=[50])
confidence = 5
# Error on non-modified line: no error.
......@@ -190,7 +194,8 @@ class DefaultStyleErrorHandlerTest(unittest.TestCase):
error_handler.turn_off_line_filtering()
self._call_error_handler(error_handler, confidence, line_number=60)
self.assertEqual(2, self._error_count)
self.assertEqual(self._error_messages,
['foo.h(50): message [whitespace/tab] [5]\n',
self.assertEqual(self._error_messages, [
'foo.h(50): message [whitespace/tab] [5]\n',
'foo.h(60): message [whitespace/tab] [5]\n',
'Suppressing further [whitespace/tab] reports for this file.\n'])
'Suppressing further [whitespace/tab] reports for this file.\n'
])
......@@ -27,7 +27,6 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Supports reading and processing text files."""
import codecs
......@@ -35,12 +34,10 @@ import logging
import os
import sys
_log = logging.getLogger(__name__)
class TextFileReader(object):
"""Supports reading and processing text files.
Attributes:
......@@ -109,7 +106,8 @@ class TextFileReader(object):
if not self.filesystem.exists(file_path) and file_path != '-':
_log.error("File does not exist: '%s'", file_path)
sys.exit(1) # FIXME: This should throw or return instead of exiting directly.
# FIXME: This should throw or return instead of exiting directly.
sys.exit(1)
if not self._processor.should_process(file_path):
_log.debug("Skipping file: '%s'", file_path)
......@@ -119,7 +117,8 @@ class TextFileReader(object):
try:
lines = self._read_lines(file_path)
except IOError as err:
message = ("Could not read file. Skipping: '%s'\n %s" % (file_path, err))
message = (
"Could not read file. Skipping: '%s'\n %s" % (file_path, err))
_log.warning(message)
return
......
......@@ -20,7 +20,6 @@
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from blinkpy.common.system.filesystem import FileSystem
from blinkpy.common.system.log_testing import LoggingTestCase
from blinkpy.style.checker import ProcessorBase
......@@ -28,9 +27,7 @@ from blinkpy.style.filereader import TextFileReader
class TextFileReaderTest(LoggingTestCase):
class MockProcessor(ProcessorBase):
"""A processor for test purposes.
This processor simply records the parameters passed to its process()
......@@ -101,7 +98,9 @@ class TextFileReaderTest(LoggingTestCase):
# remain.
message = log_messages.pop()
self.assertTrue(message.startswith("WARNING: Could not read file. Skipping: '%s'\n " % temp_dir))
self.assertTrue(
message.startswith(
"WARNING: Could not read file. Skipping: '%s'\n " % temp_dir))
self._assert_file_reader([], 1)
......@@ -143,8 +142,7 @@ class TextFileReaderTest(LoggingTestCase):
file_path2 = self._create_file(rel_path, 'bar')
self._file_reader.process_paths([dir, file_path1])
processed = [(['bar'], file_path2, None),
(['foo'], file_path1, None)]
processed = [(['bar'], file_path2, None), (['foo'], file_path1, None)]
self._assert_file_reader(processed, 2)
def test_count_delete_only_file(self):
......
......@@ -19,7 +19,6 @@
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Contains filter-related code."""
......@@ -53,7 +52,6 @@ def validate_filter_rules(filter_rules, all_categories):
class _CategoryFilter(object):
"""Filters whether to check style categories."""
def __init__(self, filter_rules=None):
......@@ -74,7 +72,8 @@ class _CategoryFilter(object):
filter_rules = []
self._filter_rules = filter_rules
self._should_check_category = {} # Cached dictionary of category to True/False
# Cached dictionary of category to True/False
self._should_check_category = {}
def __str__(self):
return ','.join(self._filter_rules)
......@@ -115,7 +114,6 @@ class _CategoryFilter(object):
class FilterConfiguration(object):
"""Supports filtering with path-specific and user-specified rules."""
def __init__(self, base_rules=None, path_specific=None, user_rules=None):
......
......@@ -19,7 +19,6 @@
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for filter.py."""
import unittest
......@@ -51,7 +50,6 @@ from blinkpy.style.filter import FilterConfiguration
class ValidateFilterRulesTest(unittest.TestCase):
"""Tests validate_filter_rules() function."""
def test_validate_filter_rules(self):
......@@ -66,11 +64,7 @@ class ValidateFilterRulesTest(unittest.TestCase):
"+xxx",
]
good_rules = [
"+tabs",
"-tabs",
"+build"
]
good_rules = ["+tabs", "-tabs", "+build"]
for rule in bad_rules:
with self.assertRaises(ValueError):
......@@ -82,7 +76,6 @@ class ValidateFilterRulesTest(unittest.TestCase):
class CategoryFilterTest(unittest.TestCase):
"""Tests CategoryFilter class."""
def test_init(self):
......@@ -144,12 +137,12 @@ class CategoryFilterTest(unittest.TestCase):
class FilterConfigurationTest(unittest.TestCase):
"""Tests FilterConfiguration class."""
def _config(self, base_rules, path_specific, user_rules):
"""Return a FilterConfiguration instance."""
return FilterConfiguration(base_rules=base_rules,
return FilterConfiguration(
base_rules=base_rules,
path_specific=path_specific,
user_rules=user_rules)
......@@ -189,12 +182,12 @@ class FilterConfigurationTest(unittest.TestCase):
path_specific = [(["path"], ["+a"])]
user_rules = ["+"]
self.assertFalse(config.__eq__(FilterConfiguration(
base_rules=base_rules)))
self.assertFalse(config.__eq__(FilterConfiguration(
path_specific=path_specific)))
self.assertFalse(config.__eq__(FilterConfiguration(
user_rules=user_rules)))
self.assertFalse(
config.__eq__(FilterConfiguration(base_rules=base_rules)))
self.assertFalse(
config.__eq__(FilterConfiguration(path_specific=path_specific)))
self.assertFalse(
config.__eq__(FilterConfiguration(user_rules=user_rules)))
def test_ne(self):
"""Test __ne__ method."""
......@@ -220,8 +213,7 @@ class FilterConfigurationTest(unittest.TestCase):
def test_path_specific(self):
"""Test effect of path_rules_specifier on should_check()."""
base_rules = ["-"]
path_specific = [(["path1"], ["+b"]),
(["path2"], ["+c"])]
path_specific = [(["path1"], ["+b"]), (["path2"], ["+c"])]
user_rules = []
config = self._config(base_rules, path_specific, user_rules)
......
......@@ -30,7 +30,6 @@ from blinkpy.style.checker import StyleProcessor
from blinkpy.style.filereader import TextFileReader
from blinkpy.style.patchreader import PatchReader
_log = logging.getLogger(__name__)
......@@ -86,8 +85,7 @@ def change_directory(filesystem, checkout_root, paths):
Pass only files below the checkout root to ensure correct results.
See the help documentation for more info.
""",
path, checkout_root)
""", path, checkout_root)
return paths
rel_paths.append(rel_path)
......@@ -101,14 +99,12 @@ def change_directory(filesystem, checkout_root, paths):
class CheckBlinkStyle(object):
def _engage_awesome_stderr_hacks(self):
# Change stderr to write with replacement characters so we don't die
# if we try to print something containing non-ASCII characters.
stderr = codecs.StreamReaderWriter(sys.stderr,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace')
codecs.getwriter('utf8'), 'replace')
# Setting an "encoding" attribute on the stream is necessary to
# prevent the logging module from raising an error. See
# the checker.configure_logging() function for more information.
......@@ -140,7 +136,10 @@ class CheckBlinkStyle(object):
configuration = checker.check_blink_style_configuration(options)
paths = change_directory(host.filesystem, checkout_root=host.git().checkout_root, paths=paths)
paths = change_directory(
host.filesystem,
checkout_root=host.git().checkout_root,
paths=paths)
style_processor = StyleProcessor(configuration)
file_reader = TextFileReader(host.filesystem, style_processor)
......@@ -149,7 +148,8 @@ class CheckBlinkStyle(object):
file_reader.process_paths(paths)
else:
changed_files = paths if options.diff_files else None
patch = host.git().create_patch(options.git_commit, changed_files=changed_files)
patch = host.git().create_patch(
options.git_commit, changed_files=changed_files)
patch_checker = PatchReader(file_reader)
patch_checker.check(patch)
......@@ -157,6 +157,7 @@ class CheckBlinkStyle(object):
file_count = file_reader.file_count
delete_only_file_count = file_reader.delete_only_file_count
_log.info('Total errors found: %d in %d files', error_count, file_count)
_log.info('Total errors found: %d in %d files', error_count,
file_count)
# We fail when style errors are found.
return error_count > 0
......@@ -31,10 +31,13 @@ class ChangeDirectoryTest(LoggingTestCase):
def setUp(self):
super(ChangeDirectoryTest, self).setUp()
self.filesystem = MockFileSystem(dirs=[self._original_directory, self._checkout_root], cwd=self._original_directory)
self.filesystem = MockFileSystem(
dirs=[self._original_directory, self._checkout_root],
cwd=self._original_directory)
def _change_directory(self, paths, checkout_root):
return change_directory(self.filesystem, paths=paths, checkout_root=checkout_root)
return change_directory(
self.filesystem, paths=paths, checkout_root=checkout_root)
def _assert_result(self, actual_return_value, expected_return_value,
expected_log_messages, expected_current_directory):
......@@ -43,17 +46,21 @@ class ChangeDirectoryTest(LoggingTestCase):
self.assertEqual(self.filesystem.getcwd(), expected_current_directory)
def test_paths_none(self):
paths = self._change_directory(checkout_root=self._checkout_root, paths=None)
paths = self._change_directory(
checkout_root=self._checkout_root, paths=None)
self._assert_result(paths, None, [], self._checkout_root)
def test_paths_convertible(self):
paths = ['/chromium/src/foo1.txt', '/chromium/src/foo2.txt']
paths = self._change_directory(checkout_root=self._checkout_root, paths=paths)
self._assert_result(paths, ['foo1.txt', 'foo2.txt'], [], self._checkout_root)
paths = self._change_directory(
checkout_root=self._checkout_root, paths=paths)
self._assert_result(paths, ['foo1.txt', 'foo2.txt'], [],
self._checkout_root)
def test_with_git_paths_unconvertible(self):
paths = ['/chromium/src/foo1.txt', '/outside/foo2.txt']
paths = self._change_directory(checkout_root=self._checkout_root, paths=paths)
paths = self._change_directory(
checkout_root=self._checkout_root, paths=paths)
log_messages = [
"""WARNING: Path-dependent style checks may not work correctly:
......@@ -66,5 +73,7 @@ class ChangeDirectoryTest(LoggingTestCase):
Pass only files below the checkout root to ensure correct results.
See the help documentation for more info.
"""]
self._assert_result(paths, paths, log_messages, self._original_directory)
"""
]
self._assert_result(paths, paths, log_messages,
self._original_directory)
......@@ -19,7 +19,6 @@
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Supports the parsing of command-line options for check_blink_style.py."""
import logging
......@@ -102,7 +101,6 @@ _EPILOG = ('This script can miss errors and does not substitute for '
# This class should not have knowledge of the flag key names.
class DefaultCommandOptionValues(object):
"""Stores the default check_blink_style.py command-line options.
Attributes:
......@@ -117,7 +115,6 @@ class DefaultCommandOptionValues(object):
# This class should not have knowledge of the flag key names.
class CommandOptionValues(object):
"""Stores the option values passed by the user via the command line.
Attributes:
......@@ -192,7 +189,6 @@ class CommandOptionValues(object):
class ArgumentPrinter(object):
"""Supports the printing of check_blink_style.py command arguments."""
def _flag_pair_to_string(self, flag_key, flag_value):
......@@ -282,55 +278,86 @@ class ArgumentParser(object):
self.default_options = default_options
self.stderr_write = stderr.write
self._parser = self._create_option_parser(stderr=stderr,
self._parser = self._create_option_parser(
stderr=stderr,
usage=usage,
default_min_confidence=self.default_options.min_confidence,
default_output_format=self.default_options.output_format)
def _create_option_parser(self, stderr, usage,
default_min_confidence, default_output_format):
def _create_option_parser(self, stderr, usage, default_min_confidence,
default_output_format):
# Since the epilog string is short, it is not necessary to replace
# the epilog string with a mock epilog string when testing.
# For this reason, we use _EPILOG directly rather than passing it
# as an argument like we do for the usage string.
parser = OptionParser(usage=usage, epilog=_EPILOG)
filter_help = ('set a filter to control what categories of style '
filter_help = (
'set a filter to control what categories of style '
'errors to report. Specify a filter using a comma-'
'delimited list of boolean filter rules, for example '
'"--filter -whitespace,+whitespace/braces". To display '
'all categories and which are enabled by default, pass '
"""no value (e.g. '-f ""' or '--filter=').""")
parser.add_option('-f', '--filter-rules', metavar='RULES',
dest='filter_value', help=filter_help)
git_commit_help = ('check all changes in the given commit. '
parser.add_option(
'-f',
'--filter-rules',
metavar='RULES',
dest='filter_value',
help=filter_help)
git_commit_help = (
'check all changes in the given commit. '
"Use 'commit_id..' to check all changes after commit_id")
parser.add_option('-g', '--git-diff', '--git-commit',
metavar='COMMIT', dest='git_commit', help=git_commit_help,)
parser.add_option(
'-g',
'--git-diff',
'--git-commit',
metavar='COMMIT',
dest='git_commit',
help=git_commit_help,
)
diff_files_help = 'diff the files passed on the command line rather than checking the style of every line'
parser.add_option('--diff-files', action='store_true', dest='diff_files', default=False, help=diff_files_help)
parser.add_option(
'--diff-files',
action='store_true',
dest='diff_files',
default=False,
help=diff_files_help)
min_confidence_help = ('set the minimum confidence of style errors '
'to report. Can be an integer 1-5, with 1 '
'displaying all errors. Defaults to %default.')
parser.add_option('-m', '--min-confidence', metavar='INT',
type='int', dest='min_confidence',
parser.add_option(
'-m',
'--min-confidence',
metavar='INT',
type='int',
dest='min_confidence',
default=default_min_confidence,
help=min_confidence_help)
output_format_help = ('set the output format, which can be "emacs" '
'or "vs7" (for Visual Studio). '
'Defaults to "%default".')
parser.add_option('-o', '--output-format', metavar='FORMAT',
parser.add_option(
'-o',
'--output-format',
metavar='FORMAT',
choices=['emacs', 'vs7'],
dest='output_format', default=default_output_format,
dest='output_format',
default=default_output_format,
help=output_format_help)
verbose_help = 'enable verbose logging.'
parser.add_option('-v', '--verbose', dest='is_verbose', default=False,
action='store_true', help=verbose_help)
parser.add_option(
'-v',
'--verbose',
dest='is_verbose',
default=False,
action='store_true',
help=verbose_help)
# Override OptionParser's error() method so that option help will
# also display when an error occurs. Normally, just the usage
......@@ -425,9 +452,9 @@ class ArgumentParser(object):
min_confidence = int(min_confidence)
if (min_confidence < 1) or (min_confidence > 5):
self._parse_error('option --min-confidence: invalid integer: '
'%s: value must be between 1 and 5'
% min_confidence)
self._parse_error(
'option --min-confidence: invalid integer: '
'%s: value must be between 1 and 5' % min_confidence)
if filter_value:
filter_rules = self._parse_filter_flag(filter_value)
......@@ -439,7 +466,8 @@ class ArgumentParser(object):
except ValueError as err:
self._parse_error(err)
options = CommandOptionValues(filter_rules=filter_rules,
options = CommandOptionValues(
filter_rules=filter_rules,
git_commit=git_commit,
diff_files=diff_files,
is_verbose=is_verbose,
......
......@@ -19,7 +19,6 @@
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for parser.py."""
import unittest
......@@ -32,7 +31,6 @@ from blinkpy.style.optparser import DefaultCommandOptionValues
class ArgumentPrinterTest(unittest.TestCase):
"""Tests the ArgumentPrinter class."""
_printer = ArgumentPrinter()
......@@ -42,14 +40,16 @@ class ArgumentPrinterTest(unittest.TestCase):
min_confidence=3,
filter_rules=None,
git_commit=None):
return ProcessorOptions(filter_rules=filter_rules,
return ProcessorOptions(
filter_rules=filter_rules,
git_commit=git_commit,
min_confidence=min_confidence,
output_format=output_format)
def test_to_flag_string(self):
options = self._create_options('vs7', 5, ['+foo', '-bar'], 'git')
self.assertEqual('--filter=+foo,-bar --git-commit=git '
self.assertEqual(
'--filter=+foo,-bar --git-commit=git '
'--min-confidence=5 --output=vs7',
self._printer.to_flag_string(options))
......@@ -61,11 +61,9 @@ class ArgumentPrinterTest(unittest.TestCase):
class ArgumentParserTest(LoggingTestCase):
"""Test the ArgumentParser class."""
class _MockStdErr(object):
def write(self, _):
# We do not want the usage string or style categories
# to print during unit tests, so print nothing.
......@@ -78,8 +76,8 @@ class ArgumentParserTest(LoggingTestCase):
def _create_defaults(self):
"""Return a DefaultCommandOptionValues instance for testing."""
return DefaultCommandOptionValues(min_confidence=3,
output_format='vs7')
return DefaultCommandOptionValues(
min_confidence=3, output_format='vs7')
def _create_parser(self):
"""Return an ArgumentParser instance for testing."""
......@@ -89,7 +87,8 @@ class ArgumentParserTest(LoggingTestCase):
mock_stderr = self._MockStdErr()
return ArgumentParser(all_categories=all_categories,
return ArgumentParser(
all_categories=all_categories,
base_filter_rules=[],
default_options=default_options,
mock_stderr=mock_stderr,
......@@ -118,30 +117,40 @@ class ArgumentParserTest(LoggingTestCase):
with self.assertRaises(SystemExit):
parse(['--min-confidence=bad'])
self.assertLog(['ERROR: option --min-confidence: '
"invalid integer value: 'bad'\n"])
self.assertLog([
'ERROR: option --min-confidence: '
"invalid integer value: 'bad'\n"
])
with self.assertRaises(SystemExit):
parse(['--min-confidence=0'])
self.assertLog(['ERROR: option --min-confidence: invalid integer: 0: '
'value must be between 1 and 5\n'])
self.assertLog([
'ERROR: option --min-confidence: invalid integer: 0: '
'value must be between 1 and 5\n'
])
with self.assertRaises(SystemExit):
parse(['--min-confidence=6'])
self.assertLog(['ERROR: option --min-confidence: invalid integer: 6: '
'value must be between 1 and 5\n'])
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
with self.assertRaises(SystemExit):
parse(['--output=bad'])
self.assertLog(['ERROR: option --output-format: invalid choice: '
"'bad' (choose from 'emacs', 'vs7')\n"])
self.assertLog([
'ERROR: option --output-format: invalid choice: '
"'bad' (choose from 'emacs', 'vs7')\n"
])
parse(['--output=vs7']) # works
# Pass a filter rule not beginning with + or -.
with self.assertRaises(SystemExit):
parse(['--filter=build'])
self.assertLog(['ERROR: Invalid filter rule "build": '
'every rule must start with + or -.\n'])
self.assertLog([
'ERROR: Invalid filter rule "build": '
'every rule must start with + or -.\n'
])
parse(['--filter=+build']) # works
def test_parse_default_arguments(self):
......@@ -179,13 +188,11 @@ class ArgumentParserTest(LoggingTestCase):
# Pass user_rules.
_, options = parse(['--filter=+build,-whitespace'])
self.assertEqual(options.filter_rules,
['+build', '-whitespace'])
self.assertEqual(options.filter_rules, ['+build', '-whitespace'])
# Pass spurious white space in user rules.
_, options = parse(['--filter=+build, -whitespace'])
self.assertEqual(options.filter_rules,
['+build', '-whitespace'])
self.assertEqual(options.filter_rules, ['+build', '-whitespace'])
def test_parse_files(self):
parse = self._parse
......@@ -199,7 +206,6 @@ class ArgumentParserTest(LoggingTestCase):
class CommandOptionValuesTest(unittest.TestCase):
"""Tests CommandOptionValues class."""
def test_init(self):
......@@ -222,7 +228,8 @@ class CommandOptionValuesTest(unittest.TestCase):
ProcessorOptions(min_confidence=5) # works
# Check attributes.
options = ProcessorOptions(filter_rules=['+'],
options = ProcessorOptions(
filter_rules=['+'],
git_commit='commit',
is_verbose=True,
min_confidence=3,
......@@ -242,7 +249,8 @@ class CommandOptionValuesTest(unittest.TestCase):
# Explicitly create a ProcessorOptions instance with all default
# values. We do this to be sure we are assuming the right default
# values in our self.assertFalse() calls below.
options = ProcessorOptions(filter_rules=[],
options = ProcessorOptions(
filter_rules=[],
git_commit=None,
is_verbose=False,
min_confidence=1,
......
......@@ -32,7 +32,6 @@ import logging
from blinkpy.common.checkout.diff_parser import DiffParser
_log = logging.getLogger(__name__)
......@@ -53,7 +52,8 @@ class PatchReader(object):
for path, diff_file in patch_files.iteritems():
line_numbers = diff_file.added_or_modified_line_numbers()
_log.debug('Found %s new or modified lines in: %s', len(line_numbers), path)
_log.debug('Found %s new or modified lines in: %s',
len(line_numbers), path)
if not line_numbers:
# Don't check files which contain only deleted lines
......@@ -62,4 +62,5 @@ class PatchReader(object):
self._text_file_reader.count_delete_only_file()
continue
self._text_file_reader.process_file(file_path=path, line_numbers=line_numbers)
self._text_file_reader.process_file(
file_path=path, line_numbers=line_numbers)
......@@ -35,11 +35,10 @@ from blinkpy.style.patchreader import PatchReader
class PatchReaderTest(unittest.TestCase):
class MockTextFileReader(object):
def __init__(self):
self.passed_to_process_file = [] # A list of (file_path, line_numbers) pairs.
# A list of (file_path, line_numbers) pairs.
self.passed_to_process_file = []
self.delete_only_file_count = 0 # A number of times count_delete_only_file() called.
def process_file(self, file_path, line_numbers):
......@@ -52,8 +51,10 @@ class PatchReaderTest(unittest.TestCase):
self._file_reader = self.MockTextFileReader()
def _assert_checked(self, passed_to_process_file, delete_only_file_count):
self.assertEqual(self._file_reader.passed_to_process_file, passed_to_process_file)
self.assertEqual(self._file_reader.delete_only_file_count, delete_only_file_count)
self.assertEqual(self._file_reader.passed_to_process_file,
passed_to_process_file)
self.assertEqual(self._file_reader.delete_only_file_count,
delete_only_file_count)
def test_check_patch(self):
PatchReader(self._file_reader).check(
......@@ -78,7 +79,8 @@ class PatchReaderTest(unittest.TestCase):
'@@ -1 +0,0 @@\n'
'-foobar\n')
# The deleted file isn't be processed.
self._assert_checked(passed_to_process_file=[], delete_only_file_count=1)
self._assert_checked(
passed_to_process_file=[], delete_only_file_count=1)
def test_check_patch_with_png_deletion(self):
PatchReader(self._file_reader).check(
......@@ -86,4 +88,5 @@ class PatchReaderTest(unittest.TestCase):
'deleted file mode 100644\n'
'index ef65bee..0000000\n'
'Binary files a/foo-expected.png and /dev/null differ\n')
self._assert_checked(passed_to_process_file=[], delete_only_file_count=1)
self._assert_checked(
passed_to_process_file=[], delete_only_file_count=1)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment