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