From 0674531a8a8dd39d5a7dd13be74f51e26447fcbd Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 6 Mar 2025 07:13:50 +0100 Subject: [PATCH] ruff format cpplint_unittest.py --- cpplint_unittest.py | 7097 ++++++++++++++++++++++++------------------- pyproject.toml | 4 + 2 files changed, 3971 insertions(+), 3130 deletions(-) diff --git a/cpplint_unittest.py b/cpplint_unittest.py index 08eb375..e39bd01 100755 --- a/cpplint_unittest.py +++ b/cpplint_unittest.py @@ -48,12 +48,14 @@ import cpplint + def codecs_latin_encode(x): if sys.version_info < (3,): return x else: return codecs.latin_1_encode(x)[0] + # This class works as an error collector and replaces cpplint.Error # function for the unit tests. We also verify each category we see # is in cpplint._ERROR_CATEGORIES, to help keep that list up to date. @@ -68,11 +70,12 @@ def __init__(self, assert_fn): self._errors = [] cpplint.ResetNolintSuppressions() - def __call__(self, filename, linenum, - category, confidence, message): - self._assert_fn(category in self._ERROR_CATEGORIES, - 'Message "%s" has category "%s",' - ' which is not in _ERROR_CATEGORIES' % (message, category)) + def __call__(self, filename, linenum, category, confidence, message): + self._assert_fn( + category in self._ERROR_CATEGORIES, + 'Message "%s" has category "%s",' + ' which is not in _ERROR_CATEGORIES' % (message, category), + ) self._SEEN_ERROR_CATEGORIES[category] = 1 if cpplint._ShouldPrintError(category, confidence, filename, linenum): self._errors.append('%s [%s] [%d]' % (message, category, confidence)) @@ -100,15 +103,15 @@ def VerifyAllCategoriesAreSeen(self): sys.exit('FATAL ERROR: There are no tests for category "%s"' % category) def RemoveIfPresent(self, substr): - for (index, error) in enumerate(self._errors): + for index, error in enumerate(self._errors): if error.find(substr) != -1: - self._errors = self._errors[0:index] + self._errors[(index + 1):] + self._errors = self._errors[0:index] + self._errors[(index + 1) :] break + # This class is a lame mock of codecs. We do not verify filename, mode, or # encoding, but for the current use case it is not needed. class MockIo(object): - def __init__(self, mock_file): # wrap list to allow "with open(mock)" class EnterableList(list): @@ -117,10 +120,16 @@ def __enter__(self): def __exit__(self, type, value, tb): return self + self.mock_file = EnterableList(mock_file) - def open(self, # pylint: disable=C6409 - unused_filename, unused_mode, unused_encoding, _): + def open( + self, # pylint: disable=C6409 + unused_filename, + unused_mode, + unused_encoding, + _, + ): return self.mock_file @@ -143,13 +152,19 @@ def PerformSingleLineLint(self, code): include_state = cpplint._IncludeState() function_state = cpplint._FunctionState() nesting_state = cpplint.NestingState() - cpplint.ProcessLine('foo.cc', 'cc', clean_lines, 0, - include_state, function_state, - nesting_state, error_collector) + cpplint.ProcessLine( + 'foo.cc', + 'cc', + clean_lines, + 0, + include_state, + function_state, + nesting_state, + error_collector, + ) # Single-line lint tests are allowed to fail the 'unlintable function' # check. - error_collector.RemoveIfPresent( - 'Lint failed to find start of function body.') + error_collector.RemoveIfPresent('Lint failed to find start of function body.') return error_collector.Results() # Perform lint over multiple lines and return the error message. @@ -161,10 +176,10 @@ def PerformMultiLineLint(self, code): nesting_state = cpplint.NestingState() for i in range(lines.NumLines()): nesting_state.Update('foo.h', lines, i, error_collector) - cpplint.CheckStyle('foo.h', lines, i, 'h', nesting_state, - error_collector) - cpplint.CheckForNonStandardConstructs('foo.h', lines, i, - nesting_state, error_collector) + cpplint.CheckStyle('foo.h', lines, i, 'h', nesting_state, error_collector) + cpplint.CheckForNonStandardConstructs( + 'foo.h', lines, i, nesting_state, error_collector + ) return error_collector.Results() # Similar to PerformMultiLineLint, but calls CheckLanguage instead of @@ -176,10 +191,11 @@ def PerformLanguageRulesCheck(self, file_name, code): lines = code.split('\n') cpplint.RemoveMultiLineComments(file_name, lines, error_collector) lines = cpplint.CleansedLines(lines) - ext = file_name[file_name.rfind('.') + 1:] + ext = file_name[file_name.rfind('.') + 1 :] for i in range(lines.NumLines()): - cpplint.CheckLanguage(file_name, lines, i, ext, include_state, - nesting_state, error_collector) + cpplint.CheckLanguage( + file_name, lines, i, ext, include_state, nesting_state, error_collector + ) return error_collector.Results() def PerformFunctionLengthsCheck(self, code): @@ -204,8 +220,9 @@ def PerformFunctionLengthsCheck(self, code): cpplint.RemoveMultiLineComments(file_name, lines, error_collector) lines = cpplint.CleansedLines(lines) for i in range(lines.NumLines()): - cpplint.CheckForFunctionLengths(file_name, lines, i, - function_state, error_collector) + cpplint.CheckForFunctionLengths( + file_name, lines, i, function_state, error_collector + ) return error_collector.Results() def PerformIncludeWhatYouUse(self, code, filename='foo.h', io=codecs): @@ -217,20 +234,23 @@ def PerformIncludeWhatYouUse(self, code, filename='foo.h', io=codecs): cpplint.RemoveMultiLineComments(filename, lines, error_collector) lines = cpplint.CleansedLines(lines) for i in range(lines.NumLines()): - cpplint.CheckLanguage(filename, lines, i, '.h', include_state, - nesting_state, error_collector) + cpplint.CheckLanguage( + filename, lines, i, '.h', include_state, nesting_state, error_collector + ) # We could clear the error_collector here, but this should # also be fine, since our IncludeWhatYouUse unittests do not # have language problems. # Second, look for missing includes. - cpplint.CheckForIncludeWhatYouUse(filename, lines, include_state, - error_collector, io) + cpplint.CheckForIncludeWhatYouUse( + filename, lines, include_state, error_collector, io + ) return error_collector.Results() # Perform lint and make sure one of the errors is what we want def TestLintContains(self, code, expected_message): self.assertTrue(expected_message in self.PerformSingleLineLint(code)) + def TestLintNotContains(self, code, expected_message): self.assertFalse(expected_message in self.PerformSingleLineLint(code)) @@ -244,16 +264,15 @@ def TestMultiLineLint(self, code, expected_message): def TestMultiLineLintRE(self, code, expected_message_re): message = self.PerformMultiLineLint(code) if not re.search(expected_message_re, message): - self.fail('Message was:\n' + message + 'Expected match to "' + - expected_message_re + '"') + self.fail( + 'Message was:\n' + message + 'Expected match to "' + expected_message_re + '"' + ) def TestLanguageRulesCheck(self, file_name, code, expected_message): - self.assertEqual(expected_message, - self.PerformLanguageRulesCheck(file_name, code)) + self.assertEqual(expected_message, self.PerformLanguageRulesCheck(file_name, code)) def TestIncludeWhatYouUse(self, code, expected_message): - self.assertEqual(expected_message, - self.PerformIncludeWhatYouUse(code)) + self.assertEqual(expected_message, self.PerformIncludeWhatYouUse(code)) def TestBlankLinesCheck(self, lines, start_errors, end_errors): for extension in ['c', 'cc', 'cpp', 'cxx', 'c++', 'cu']: @@ -263,18 +282,22 @@ def doTestBlankLinesCheck(self, lines, start_errors, end_errors, extension): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData('foo.' + extension, extension, lines, error_collector) self.assertEqual( - start_errors, - error_collector.Results().count( - 'Redundant blank line at the start of a code block ' - 'should be deleted. [whitespace/blank_line] [2]')) + start_errors, + error_collector.Results().count( + 'Redundant blank line at the start of a code block ' + 'should be deleted. [whitespace/blank_line] [2]' + ), + ) self.assertEqual( - end_errors, - error_collector.Results().count( - 'Redundant blank line at the end of a code block ' - 'should be deleted. [whitespace/blank_line] [3]')) + end_errors, + error_collector.Results().count( + 'Redundant blank line at the end of a code block ' + 'should be deleted. [whitespace/blank_line] [3]' + ), + ) -class CpplintTest(CpplintTestBase): +class CpplintTest(CpplintTestBase): def GetNamespaceResults(self, lines): error_collector = ErrorCollector(self.assertTrue) cpplint.RemoveMultiLineComments('foo.h', lines, error_collector) @@ -282,52 +305,60 @@ def GetNamespaceResults(self, lines): nesting_state = cpplint.NestingState() for i in range(lines.NumLines()): nesting_state.Update('foo.h', lines, i, error_collector) - cpplint.CheckForNamespaceIndentation('foo.h', nesting_state, - lines, i, error_collector) + cpplint.CheckForNamespaceIndentation( + 'foo.h', nesting_state, lines, i, error_collector + ) return error_collector.Results() def testForwardDeclarationNamespaceIndentation(self): - lines = ['namespace Test {', - ' class ForwardDeclaration;', - '} // namespace Test'] + lines = ['namespace Test {', ' class ForwardDeclaration;', '} // namespace Test'] results = self.GetNamespaceResults(lines) - self.assertEqual(results, 'Do not indent within a namespace. ' - ' [whitespace/indent_namespace] [4]') + self.assertEqual( + results, 'Do not indent within a namespace. [whitespace/indent_namespace] [4]' + ) def testNamespaceIndentationForClass(self): - lines = ['namespace Test {', - 'void foo() { }', - ' class Test {', - ' };', - '} // namespace Test'] + lines = [ + 'namespace Test {', + 'void foo() { }', + ' class Test {', + ' };', + '} // namespace Test', + ] results = self.GetNamespaceResults(lines) - self.assertEqual(results, ['Do not indent within a namespace. ' - ' [whitespace/indent_namespace] [4]', - 'Do not indent within a namespace. ' - ' [whitespace/indent_namespace] [4]']) + self.assertEqual( + results, + [ + 'Do not indent within a namespace. [whitespace/indent_namespace] [4]', + 'Do not indent within a namespace. [whitespace/indent_namespace] [4]', + ], + ) def testNamespaceIndentationIndentedParameter(self): - lines = ['namespace Test {', - 'void foo(' - ' SuperLongTypeName d = 418) { }', - '} // namespace Test'] + lines = [ + 'namespace Test {', + 'void foo( SuperLongTypeName d = 418) { }', + '} // namespace Test', + ] results = self.GetNamespaceResults(lines) self.assertEqual(results, '') def testNestingInNamespace(self): - lines = ['namespace Test {', - 'struct OuterClass {', - ' struct NoFalsePositivesHere;', - ' struct NoFalsePositivesHere member_variable;', - '};', - 'void foo() {', - ' const int no_positives_eh = 418;', - '}', - '} // namespace Test'] + lines = [ + 'namespace Test {', + 'struct OuterClass {', + ' struct NoFalsePositivesHere;', + ' struct NoFalsePositivesHere member_variable;', + '};', + 'void foo() {', + ' const int no_positives_eh = 418;', + '}', + '} // namespace Test', + ] results = self.GetNamespaceResults(lines) self.assertEqual(results, '') @@ -336,33 +367,42 @@ def testNestingInNamespace(self): def testGetLineWidth(self): self.assertEqual(0, cpplint.GetLineWidth('')) self.assertEqual(10, cpplint.GetLineWidth(str('x') * 10)) - self.assertEqual(16, cpplint.GetLineWidth('\u90fd|\u9053|\u5e9c|\u770c|\u652f\u5e81')) - self.assertEqual(16, cpplint.GetLineWidth(u'都|道|府|県|支庁')) - self.assertEqual(5 + 13 + 9, cpplint.GetLineWidth( - u'd𝐱/dt' + u'f : t ⨯ 𝐱 → ℝ' + u't ⨯ 𝐱 → ℝ')) + self.assertEqual( + 16, cpplint.GetLineWidth('\u90fd|\u9053|\u5e9c|\u770c|\u652f\u5e81') + ) + self.assertEqual(16, cpplint.GetLineWidth('都|道|府|県|支庁')) + self.assertEqual( + 5 + 13 + 9, cpplint.GetLineWidth('d𝐱/dt' + 'f : t ⨯ 𝐱 → ℝ' + 't ⨯ 𝐱 → ℝ') + ) def testGetTextInside(self): self.assertEqual('', cpplint._GetTextInside('fun()', r'fun\(')) self.assertEqual('x, y', cpplint._GetTextInside('f(x, y)', r'f\(')) - self.assertEqual('a(), b(c())', cpplint._GetTextInside( - 'printf(a(), b(c()))', r'printf\(')) + self.assertEqual( + 'a(), b(c())', cpplint._GetTextInside('printf(a(), b(c()))', r'printf\(') + ) self.assertEqual('x, y{}', cpplint._GetTextInside('f[x, y{}]', r'f\[')) self.assertEqual(None, cpplint._GetTextInside('f[a, b(}]', r'f\[')) self.assertEqual(None, cpplint._GetTextInside('f[x, y]', r'f\(')) - self.assertEqual('y, h(z, (a + b))', cpplint._GetTextInside( - 'f(x, g(y, h(z, (a + b))))', r'g\(')) + self.assertEqual( + 'y, h(z, (a + b))', cpplint._GetTextInside('f(x, g(y, h(z, (a + b))))', r'g\(') + ) self.assertEqual('f(f(x))', cpplint._GetTextInside('f(f(f(x)))', r'f\(')) # Supports multiple lines. - self.assertEqual('\n return loop(x);\n', - cpplint._GetTextInside( - 'int loop(int x) {\n return loop(x);\n}\n', r'\{')) + self.assertEqual( + '\n return loop(x);\n', + cpplint._GetTextInside('int loop(int x) {\n return loop(x);\n}\n', r'\{'), + ) # '^' matches the beginning of each line. - self.assertEqual('x, y', - cpplint._GetTextInside( - '#include "inl.h" // skip #define\n' - '#define A2(x, y) a_inl_(x, y, __LINE__)\n' - '#define A(x) a_inl_(x, "", __LINE__)\n', - r'^\s*#define\s*\w+\(')) + self.assertEqual( + 'x, y', + cpplint._GetTextInside( + '#include "inl.h" // skip #define\n' + '#define A2(x, y) a_inl_(x, y, __LINE__)\n' + '#define A(x) a_inl_(x, "", __LINE__)\n', + r'^\s*#define\s*\w+\(', + ), + ) def testFindNextMultiLineCommentStart(self): self.assertEqual(1, cpplint.FindNextMultiLineCommentStart([''], 0)) @@ -385,343 +425,397 @@ def testRemoveMultiLineCommentsFromRange(self): def testSpacesAtEndOfLine(self): self.TestLint( - '// Hello there ', - 'Line ends in whitespace. Consider deleting these extra spaces.' - ' [whitespace/end_of_line] [4]') + '// Hello there ', + 'Line ends in whitespace. Consider deleting these extra spaces.' + ' [whitespace/end_of_line] [4]', + ) # Test line length check. def testLineLengthCheck(self): + self.TestLint('// Hello', '') self.TestLint( - '// Hello', - '') - self.TestLint( - '// x' + ' x' * 40, - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') - self.TestLint( - '// x' + ' x' * 50, - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') - self.TestLint( - '// //some/path/to/f' + ('i' * 100) + 'le', - '') - self.TestLint( - '// //some/path/to/f' + ('i' * 100) + 'le', - '') - self.TestLint( - '// //some/path/to/f' + ('i' * 50) + 'le and some comments', - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') - self.TestLint( - '// http://g' + ('o' * 100) + 'gle.com/', - '') - self.TestLint( - '// https://g' + ('o' * 100) + 'gle.com/', - '') + '// x' + ' x' * 40, + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) self.TestLint( - '// https://g' + ('o' * 60) + 'gle.com/ and some comments', - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') + '// x' + ' x' * 50, + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) + self.TestLint('// //some/path/to/f' + ('i' * 100) + 'le', '') + self.TestLint('// //some/path/to/f' + ('i' * 100) + 'le', '') self.TestLint( - '// Read https://g' + ('o' * 60) + 'gle.com/', - '') + '// //some/path/to/f' + ('i' * 50) + 'le and some comments', + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) + self.TestLint('// http://g' + ('o' * 100) + 'gle.com/', '') + self.TestLint('// https://g' + ('o' * 100) + 'gle.com/', '') self.TestLint( - '// $Id: g' + ('o' * 80) + 'gle.cc#1 $', - '') + '// https://g' + ('o' * 60) + 'gle.com/ and some comments', + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) + self.TestLint('// Read https://g' + ('o' * 60) + 'gle.com/', '') + self.TestLint('// $Id: g' + ('o' * 80) + 'gle.cc#1 $', '') self.TestLint( - '// $Id: g' + ('o' * 80) + 'gle.cc#1', - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') + '// $Id: g' + ('o' * 80) + 'gle.cc#1', + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) self.TestMultiLineLint( - 'static const char kCStr[] = "g' + ('o' * 50) + 'gle";\n', - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') + 'static const char kCStr[] = "g' + ('o' * 50) + 'gle";\n', + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) self.TestMultiLineLint( - 'static const char kRawStr[] = R"(g' + ('o' * 50) + 'gle)";\n', - '') # no warning because raw string content is elided + 'static const char kRawStr[] = R"(g' + ('o' * 50) + 'gle)";\n', '' + ) # no warning because raw string content is elided self.TestMultiLineLint( - 'static const char kMultiLineRawStr[] = R"(\n' - 'g' + ('o' * 80) + 'gle\n' - ')";', - '') + 'static const char kMultiLineRawStr[] = R"(\ng' + ('o' * 80) + 'gle\n)";', '' + ) self.TestMultiLineLint( - 'static const char kL' + ('o' * 50) + 'ngIdentifier[] = R"()";\n', - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') - self.TestLint( - ' /// @copydoc ' + ('o' * (cpplint._line_length * 2)), - '') - self.TestLint( - ' /// @copydetails ' + ('o' * (cpplint._line_length * 2)), - '') - self.TestLint( - ' /// @copybrief ' + ('o' * (cpplint._line_length * 2)), - '') + 'static const char kL' + ('o' * 50) + 'ngIdentifier[] = R"()";\n', + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) + self.TestLint(' /// @copydoc ' + ('o' * (cpplint._line_length * 2)), '') + self.TestLint(' /// @copydetails ' + ('o' * (cpplint._line_length * 2)), '') + self.TestLint(' /// @copybrief ' + ('o' * (cpplint._line_length * 2)), '') # Test error suppression annotations. def testErrorSuppression(self): # Two errors on same line: self.TestLint( - 'long a = (int64_t) 65;', - ['Using C-style cast. Use static_cast(...) instead' - ' [readability/casting] [4]', - 'Use int16_t/int64_t/etc, rather than the C type long' - ' [runtime/int] [4]', - ]) + 'long a = (int64_t) 65;', + [ + 'Using C-style cast. Use static_cast(...) instead' + ' [readability/casting] [4]', + 'Use int16_t/int64_t/etc, rather than the C type long [runtime/int] [4]', + ], + ) # One category of error suppressed: self.TestLint( - 'long a = (int64_t) 65; // NOLINT(runtime/int)', - 'Using C-style cast. Use static_cast(...) instead' - ' [readability/casting] [4]') + 'long a = (int64_t) 65; // NOLINT(runtime/int)', + 'Using C-style cast. Use static_cast(...) instead' + ' [readability/casting] [4]', + ) # Two categories of errors suppressed: self.TestLint( - 'long a = (int64_t) 65; // NOLINT(runtime/int,readability/casting)', - '') + 'long a = (int64_t) 65; // NOLINT(runtime/int,readability/casting)', '' + ) # All categories suppressed: (two aliases) self.TestLint('long a = (int64_t) 65; // NOLINT', '') self.TestLint('long a = (int64_t) 65; // NOLINT(*)', '') # Malformed NOLINT directive: self.TestLint( - 'long a = 65; // NOLINT(foo)', - ['Unknown NOLINT error category: foo' - ' [readability/nolint] [5]', - 'Use int16_t/int64_t/etc, rather than the C type long [runtime/int] [4]', - ]) + 'long a = 65; // NOLINT(foo)', + [ + 'Unknown NOLINT error category: foo [readability/nolint] [5]', + 'Use int16_t/int64_t/etc, rather than the C type long [runtime/int] [4]', + ], + ) # Irrelevant NOLINT directive has no effect: self.TestLint( - 'long a = 65; // NOLINT(readability/casting)', - 'Use int16_t/int64_t/etc, rather than the C type long' - ' [runtime/int] [4]') + 'long a = 65; // NOLINT(readability/casting)', + 'Use int16_t/int64_t/etc, rather than the C type long [runtime/int] [4]', + ) # NOLINTNEXTLINE silences warning for the next line instead of current line error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTNEXTLINE(whitespace/line_length)', - '// ./command' + (' -verbose' * 80), - ''], - error_collector) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTNEXTLINE(whitespace/line_length)', + '// ./command' + (' -verbose' * 80), + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # NOLINTNEXTLINE multiple categories silences warning for the next line instead of current line error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTNEXTLINE(runtime/int,readability/casting)', - 'long a = (int64_t) 65;', - ''], - error_collector) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTNEXTLINE(runtime/int,readability/casting)', + 'long a = (int64_t) 65;', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # LINT_C_FILE silences cast warnings for entire file. error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.h', 'h', - ['// Copyright 2014 Your Company.', - '// NOLINT(build/header_guard)', - 'int64_t a = (uint64_t) 65;', - '// LINT_C_FILE', - ''], - error_collector) + cpplint.ProcessFileData( + 'test.h', + 'h', + [ + '// Copyright 2014 Your Company.', + '// NOLINT(build/header_guard)', + 'int64_t a = (uint64_t) 65;', + '// LINT_C_FILE', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # Vim modes silence cast warnings for entire file. - for modeline in ['vi:filetype=c', - 'vi:sw=8 filetype=c', - 'vi:sw=8 filetype=c ts=8', - 'vi: filetype=c', - 'vi: sw=8 filetype=c', - 'vi: sw=8 filetype=c ts=8', - 'vim:filetype=c', - 'vim:sw=8 filetype=c', - 'vim:sw=8 filetype=c ts=8', - 'vim: filetype=c', - 'vim: sw=8 filetype=c', - 'vim: sw=8 filetype=c ts=8', - 'vim: set filetype=c:', - 'vim: set sw=8 filetype=c:', - 'vim: set sw=8 filetype=c ts=8:', - 'vim: set filetype=c :', - 'vim: set sw=8 filetype=c :', - 'vim: set sw=8 filetype=c ts=8 :', - 'vim: se filetype=c:', - 'vim: se sw=8 filetype=c:', - 'vim: se sw=8 filetype=c ts=8:', - 'vim: se filetype=c :', - 'vim: se sw=8 filetype=c :', - 'vim: se sw=8 filetype=c ts=8 :']: + for modeline in [ + 'vi:filetype=c', + 'vi:sw=8 filetype=c', + 'vi:sw=8 filetype=c ts=8', + 'vi: filetype=c', + 'vi: sw=8 filetype=c', + 'vi: sw=8 filetype=c ts=8', + 'vim:filetype=c', + 'vim:sw=8 filetype=c', + 'vim:sw=8 filetype=c ts=8', + 'vim: filetype=c', + 'vim: sw=8 filetype=c', + 'vim: sw=8 filetype=c ts=8', + 'vim: set filetype=c:', + 'vim: set sw=8 filetype=c:', + 'vim: set sw=8 filetype=c ts=8:', + 'vim: set filetype=c :', + 'vim: set sw=8 filetype=c :', + 'vim: set sw=8 filetype=c ts=8 :', + 'vim: se filetype=c:', + 'vim: se sw=8 filetype=c:', + 'vim: se sw=8 filetype=c ts=8:', + 'vim: se filetype=c :', + 'vim: se sw=8 filetype=c :', + 'vim: se sw=8 filetype=c ts=8 :', + ]: error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.h', 'h', - ['// Copyright 2014 Your Company.', - '// NOLINT(build/header_guard)', - 'int64_t a = (uint64_t) 65;', - '/* Prevent warnings about the modeline', - modeline, - '*/', - ''], - error_collector) + cpplint.ProcessFileData( + 'test.h', + 'h', + [ + '// Copyright 2014 Your Company.', + '// NOLINT(build/header_guard)', + 'int64_t a = (uint64_t) 65;', + '/* Prevent warnings about the modeline', + modeline, + '*/', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # LINT_KERNEL_FILE silences whitespace/tab warnings for entire file. error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.h', 'h', - ['// Copyright 2014 Your Company.', - '// NOLINT(build/header_guard)', - 'struct test {', - '\tint member;', - '};', - '// LINT_KERNEL_FILE', - ''], - error_collector) + cpplint.ProcessFileData( + 'test.h', + 'h', + [ + '// Copyright 2014 Your Company.', + '// NOLINT(build/header_guard)', + 'struct test {', + '\tint member;', + '};', + '// LINT_KERNEL_FILE', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # NOLINT, NOLINTNEXTLINE silences the readability/braces warning for "};". error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '#include ', - 'for (int i = 0; i != 100; ++i) {', - ' std::cout << i << std::endl;', - '}; // NOLINT', - 'for (int i = 0; i != 100; ++i) {', - ' std::cout << i << std::endl;', - '// NOLINTNEXTLINE', - '};', - '// LINT_KERNEL_FILE', - ''], - error_collector) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '#include ', + 'for (int i = 0; i != 100; ++i) {', + ' std::cout << i << std::endl;', + '}; // NOLINT', + 'for (int i = 0; i != 100; ++i) {', + ' std::cout << i << std::endl;', + '// NOLINTNEXTLINE', + '};', + '// LINT_KERNEL_FILE', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # NOLINTBEGIN and silences all warnings after it error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTBEGIN', - 'long a = (int64_t) 65;' - 'long a = 65;', - '// ./command' + (' -verbose' * 80)], - error_collector) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTBEGIN', + 'long a = (int64_t) 65;long a = 65;', + '// ./command' + (' -verbose' * 80), + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTBEGIN(*)', - 'long a = (int64_t) 65;' - 'long a = 65;', - '// ./command' + (' -verbose' * 80)], - error_collector) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTBEGIN(*)', + 'long a = (int64_t) 65;long a = 65;', + '// ./command' + (' -verbose' * 80), + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # NOLINTEND will show warnings after that point error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTBEGIN', - 'long a = (int64_t) 65;' - 'long a = 65;', - '// NOLINTEND', - '// ./command' + (' -verbose' * 80), - ''], - error_collector) - self.assertEqual('Lines should be <= 80 characters long ' - '[whitespace/line_length] [2]', error_collector.Results()) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTBEGIN', + 'long a = (int64_t) 65;long a = 65;', + '// NOLINTEND', + '// ./command' + (' -verbose' * 80), + '', + ], + error_collector, + ) + self.assertEqual( + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + error_collector.Results(), + ) # NOLINTBEGIN(category) silences category warnings after it error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTBEGIN(readability/casting,runtime/int)', - 'long a = (int64_t) 65;', - 'long a = 65;', - '// ./command' + (' -verbose' * 80), - '// NOLINTEND', - ''], - error_collector) - self.assertEqual('Lines should be <= 80 characters long ' - '[whitespace/line_length] [2]', - error_collector.Results()) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTBEGIN(readability/casting,runtime/int)', + 'long a = (int64_t) 65;', + 'long a = 65;', + '// ./command' + (' -verbose' * 80), + '// NOLINTEND', + '', + ], + error_collector, + ) + self.assertEqual( + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + error_collector.Results(), + ) # NOLINTEND(category) will generate an error that categories are not supported error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTBEGIN(readability/casting,runtime/int)', - 'long a = (int64_t) 65;', - 'long a = 65;', - '// NOLINTEND(readability/casting)', - ''], - error_collector) - self.assertEqual('NOLINT categories not supported in block END: readability/casting ' - '[readability/nolint] [5]', - error_collector.Results()) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTBEGIN(readability/casting,runtime/int)', + 'long a = (int64_t) 65;', + 'long a = 65;', + '// NOLINTEND(readability/casting)', + '', + ], + error_collector, + ) + self.assertEqual( + 'NOLINT categories not supported in block END: readability/casting ' + '[readability/nolint] [5]', + error_collector.Results(), + ) # nested NOLINTBEGIN is not allowed error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTBEGIN(readability/casting,runtime/int)', - 'long a = (int64_t) 65;', - '// NOLINTBEGIN(runtime/int)', - 'long a = 65;', - '// NOLINTEND(*)', - ''], - error_collector) - self.assertEqual('NONLINT block already defined on line 2 ' - '[readability/nolint] [5]', error_collector.Results()) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTBEGIN(readability/casting,runtime/int)', + 'long a = (int64_t) 65;', + '// NOLINTBEGIN(runtime/int)', + 'long a = 65;', + '// NOLINTEND(*)', + '', + ], + error_collector, + ) + self.assertEqual( + 'NONLINT block already defined on line 2 [readability/nolint] [5]', + error_collector.Results(), + ) # error if NOLINGBEGIN is not ended error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('test.cc', 'cc', - ['// Copyright 2014 Your Company.', - '// NOLINTBEGIN(readability/casting,runtime/int)', - 'long a = (int64_t) 65;', - 'long a = 65;', - ''], - error_collector) - self.assertEqual('NONLINT block never ended [readability/nolint] [5]', error_collector.Results()) + cpplint.ProcessFileData( + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '// NOLINTBEGIN(readability/casting,runtime/int)', + 'long a = (int64_t) 65;', + 'long a = 65;', + '', + ], + error_collector, + ) + self.assertEqual( + 'NONLINT block never ended [readability/nolint] [5]', error_collector.Results() + ) # error if unmatched NOLINTEND - self.TestLint( - '// NOLINTEND', - 'Not in a NOLINT block ' - '[readability/nolint] [5]') - self.TestLint( - '// NOLINTEND(*)', - 'Not in a NOLINT block ' - '[readability/nolint] [5]') + self.TestLint('// NOLINTEND', 'Not in a NOLINT block [readability/nolint] [5]') + self.TestLint('// NOLINTEND(*)', 'Not in a NOLINT block [readability/nolint] [5]') # Test Variable Declarations. def testVariableDeclarations(self): self.TestLint( - 'long a = 65;', - 'Use int16_t/int64_t/etc, rather than the C type long' - ' [runtime/int] [4]') - self.TestLint( - 'long double b = 65.0;', - '') + 'long a = 65;', + 'Use int16_t/int64_t/etc, rather than the C type long [runtime/int] [4]', + ) + self.TestLint('long double b = 65.0;', '') self.TestLint( - 'long long aa = 6565;', - 'Use int16_t/int64_t/etc, rather than the C type long' - ' [runtime/int] [4]') + 'long long aa = 6565;', + 'Use int16_t/int64_t/etc, rather than the C type long [runtime/int] [4]', + ) # Test C-style cast cases. def testCStyleCast(self): self.TestLint( - 'int a = (int)1.0;', - 'Using C-style cast. Use static_cast(...) instead' - ' [readability/casting] [4]') + 'int a = (int)1.0;', + 'Using C-style cast. Use static_cast(...) instead' + ' [readability/casting] [4]', + ) self.TestLint( - 'int a = (int)-1.0;', - 'Using C-style cast. Use static_cast(...) instead' - ' [readability/casting] [4]') + 'int a = (int)-1.0;', + 'Using C-style cast. Use static_cast(...) instead' + ' [readability/casting] [4]', + ) self.TestLint( - 'int *a = (int *)NULL;', - 'Using C-style cast. Use reinterpret_cast(...) instead' - ' [readability/casting] [4]') + 'int *a = (int *)NULL;', + 'Using C-style cast. Use reinterpret_cast(...) instead' + ' [readability/casting] [4]', + ) self.TestLint( - 'uint16_t a = (uint16_t)1.0;', - 'Using C-style cast. Use static_cast(...) instead' - ' [readability/casting] [4]') + 'uint16_t a = (uint16_t)1.0;', + 'Using C-style cast. Use static_cast(...) instead' + ' [readability/casting] [4]', + ) self.TestLint( - 'int32_t a = (int32_t)1.0;', - 'Using C-style cast. Use static_cast(...) instead' - ' [readability/casting] [4]') + 'int32_t a = (int32_t)1.0;', + 'Using C-style cast. Use static_cast(...) instead' + ' [readability/casting] [4]', + ) self.TestLint( - 'uint64_t a = (uint64_t)1.0;', - 'Using C-style cast. Use static_cast(...) instead' - ' [readability/casting] [4]') + 'uint64_t a = (uint64_t)1.0;', + 'Using C-style cast. Use static_cast(...) instead' + ' [readability/casting] [4]', + ) self.TestLint( - 'size_t a = (size_t)1.0;', - 'Using C-style cast. Use static_cast(...) instead' - ' [readability/casting] [4]') + 'size_t a = (size_t)1.0;', + 'Using C-style cast. Use static_cast(...) instead' + ' [readability/casting] [4]', + ) # These shouldn't be recognized casts. self.TestLint('u a = (u)NULL;', '') @@ -756,34 +850,37 @@ def testCStyleCast(self): # Brace initializer with templated type self.TestMultiLineLint( - """ + """ template void Function(int arg1, int arg2) { variable &= ~Type1{0} - 1; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ template class Class { void Function() { variable &= ~Type{0} - 1; } };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ template class Class { void Function() { variable &= ~Type{0} - 1; } };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ namespace { template class Class { @@ -794,30 +891,38 @@ class Class { } }; }""", - '') + '', + ) # Test taking address of casts (runtime/casting) def testRuntimeCasting(self): - error_msg = ('Are you taking an address of a cast? ' - 'This is dangerous: could be a temp var. ' - 'Take the address before doing the cast, rather than after' - ' [runtime/casting] [4]') + error_msg = ( + 'Are you taking an address of a cast? ' + 'This is dangerous: could be a temp var. ' + 'Take the address before doing the cast, rather than after' + ' [runtime/casting] [4]' + ) self.TestLint('int* x = &static_cast(foo);', error_msg) self.TestLint('int* x = &reinterpret_cast(foo);', error_msg) - self.TestLint('int* x = &(int*)foo;', - ['Using C-style cast. Use reinterpret_cast(...) ' - 'instead [readability/casting] [4]', - error_msg]) - self.TestLint('BudgetBuckets&(BudgetWinHistory::*BucketFn)(void) const;', - '') + self.TestLint( + 'int* x = &(int*)foo;', + [ + 'Using C-style cast. Use reinterpret_cast(...) ' + 'instead [readability/casting] [4]', + error_msg, + ], + ) + self.TestLint('BudgetBuckets&(BudgetWinHistory::*BucketFn)(void) const;', '') self.TestLint('&(*func_ptr)(arg)', '') self.TestLint('Compute(arg, &(*func_ptr)(i, j));', '') # Alternative error message - alt_error_msg = ('Are you taking an address of something dereferenced ' - 'from a cast? Wrapping the dereferenced expression in ' - 'parentheses will make the binding more obvious' - ' [readability/casting] [4]') + alt_error_msg = ( + 'Are you taking an address of something dereferenced ' + 'from a cast? Wrapping the dereferenced expression in ' + 'parentheses will make the binding more obvious' + ' [readability/casting] [4]' + ) self.TestLint('int* x = &down_cast(obj)->member_;', alt_error_msg) self.TestLint('int* x = &down_cast(obj)[index];', alt_error_msg) self.TestLint('int* x = &(down_cast(obj)->member_);', '') @@ -834,19 +939,15 @@ def testRuntimeCasting(self): def testRuntimeSelfinit(self): self.TestLint( - 'Foo::Foo(Bar r, Bel l) : r_(r_), l_(l_) { }', - 'You seem to be initializing a member variable with itself.' - ' [runtime/init] [4]') - self.TestLint( - 'Foo::Foo(Bar r, Bel l) : r_(CHECK_NOTNULL(r_)) { }', - 'You seem to be initializing a member variable with itself.' - ' [runtime/init] [4]') - self.TestLint( - 'Foo::Foo(Bar r, Bel l) : r_(r), l_(l) { }', - '') + 'Foo::Foo(Bar r, Bel l) : r_(r_), l_(l_) { }', + 'You seem to be initializing a member variable with itself. [runtime/init] [4]', + ) self.TestLint( - 'Foo::Foo(Bar r) : r_(r), l_(r_), ll_(l_) { }', - '') + 'Foo::Foo(Bar r, Bel l) : r_(CHECK_NOTNULL(r_)) { }', + 'You seem to be initializing a member variable with itself. [runtime/init] [4]', + ) + self.TestLint('Foo::Foo(Bar r, Bel l) : r_(r), l_(l) { }', '') + self.TestLint('Foo::Foo(Bar r) : r_(r), l_(r_), ll_(l_) { }', '') # Test for unnamed arguments in a method. def testCheckForUnnamedParams(self): @@ -884,22 +985,25 @@ def testCheckForUnnamedParams(self): # Test deprecated casts such as int(d) def testDeprecatedCast(self): self.TestLint( - 'int a = int(2.2);', - 'Using deprecated casting style. ' - 'Use static_cast(...) instead' - ' [readability/casting] [4]') + 'int a = int(2.2);', + 'Using deprecated casting style. ' + 'Use static_cast(...) instead' + ' [readability/casting] [4]', + ) self.TestLint( - '(char *) "foo"', - 'Using C-style cast. ' - 'Use const_cast(...) instead' - ' [readability/casting] [4]') + '(char *) "foo"', + 'Using C-style cast. ' + 'Use const_cast(...) instead' + ' [readability/casting] [4]', + ) self.TestLint( - '(int*)foo', - 'Using C-style cast. ' - 'Use reinterpret_cast(...) instead' - ' [readability/casting] [4]') + '(int*)foo', + 'Using C-style cast. ' + 'Use reinterpret_cast(...) instead' + ' [readability/casting] [4]', + ) # Checks for false positives... self.TestLint('int a = int();', '') # constructor @@ -913,9 +1017,7 @@ def testDeprecatedCast(self): self.TestLint('void F(const char(&src)[N]);', '') # array of references # Placement new - self.TestLint( - 'new(field_ptr) int(field->default_value_enum()->number());', - '') + self.TestLint('new(field_ptr) int(field->default_value_enum()->number());', '') # C++11 function wrappers self.TestLint('std::function', '') @@ -925,12 +1027,16 @@ def testDeprecatedCast(self): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'test.cc', 'cc', - ['// Copyright 2014 Your Company. All Rights Reserved.', - 'typedef std::function<', - ' bool(int)> F;', - ''], - error_collector) + 'test.cc', + 'cc', + [ + '// Copyright 2014 Your Company. All Rights Reserved.', + 'typedef std::function<', + ' bool(int)> F;', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # Return types for function pointers @@ -943,294 +1049,316 @@ def testDeprecatedCast(self): self.TestLint('void Function(bool(FunctionPointerArg)()) {}', '') self.TestLint('typedef set SortedIdSet', '') self.TestLint( - 'bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *t)) {}', - '') + 'bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *t)) {}', '' + ) # The second parameter to a gMock method definition is a function signature # that often looks like a bad cast but should not picked up by lint. def testMockMethod(self): - self.TestLint( - 'MOCK_METHOD0(method, int());', - '') - self.TestLint( - 'MOCK_CONST_METHOD1(method, float(string));', - '') - self.TestLint( - 'MOCK_CONST_METHOD2_T(method, double(float, float));', - '') - self.TestLint( - 'MOCK_CONST_METHOD1(method, SomeType(int));', - '') + self.TestLint('MOCK_METHOD0(method, int());', '') + self.TestLint('MOCK_CONST_METHOD1(method, float(string));', '') + self.TestLint('MOCK_CONST_METHOD2_T(method, double(float, float));', '') + self.TestLint('MOCK_CONST_METHOD1(method, SomeType(int));', '') error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('mock.cc', 'cc', - ['MOCK_METHOD1(method1,', - ' bool(int));', - 'MOCK_METHOD1(', - ' method2,', - ' bool(int));', - 'MOCK_CONST_METHOD2(', - ' method3, bool(int,', - ' int));', - 'MOCK_METHOD1(method4, int(bool));', - 'const int kConstant = int(42);'], # true positive - error_collector) + cpplint.ProcessFileData( + 'mock.cc', + 'cc', + [ + 'MOCK_METHOD1(method1,', + ' bool(int));', + 'MOCK_METHOD1(', + ' method2,', + ' bool(int));', + 'MOCK_CONST_METHOD2(', + ' method3, bool(int,', + ' int));', + 'MOCK_METHOD1(method4, int(bool));', + 'const int kConstant = int(42);', + ], # true positive + error_collector, + ) self.assertEqual( - 0, - error_collector.Results().count( - ('Using deprecated casting style. ' - 'Use static_cast(...) instead ' - '[readability/casting] [4]'))) + 0, + error_collector.Results().count( + ( + 'Using deprecated casting style. ' + 'Use static_cast(...) instead ' + '[readability/casting] [4]' + ) + ), + ) self.assertEqual( - 1, - error_collector.Results().count( - ('Using deprecated casting style. ' - 'Use static_cast(...) instead ' - '[readability/casting] [4]'))) + 1, + error_collector.Results().count( + ( + 'Using deprecated casting style. ' + 'Use static_cast(...) instead ' + '[readability/casting] [4]' + ) + ), + ) # Like gMock method definitions, MockCallback instantiations look very similar # to bad casts. def testMockCallback(self): - self.TestLint( - 'MockCallback', - '') - self.TestLint( - 'MockCallback', - '') + self.TestLint('MockCallback', '') + self.TestLint('MockCallback', '') # Test false errors that happened with some include file names def testIncludeFilenameFalseError(self): - self.TestLint( - '#include "foo/long-foo.h"', - '') - self.TestLint( - '#include "foo/sprintf.h"', - '') + self.TestLint('#include "foo/long-foo.h"', '') + self.TestLint('#include "foo/sprintf.h"', '') # Test typedef cases. There was a bug that cpplint misidentified # typedef for pointer to function as C-style cast and produced # false-positive error messages. def testTypedefForPointerToFunction(self): - self.TestLint( - 'typedef void (*Func)(int x);', - '') - self.TestLint( - 'typedef void (*Func)(int *x);', - '') - self.TestLint( - 'typedef void Func(int x);', - '') - self.TestLint( - 'typedef void Func(int *x);', - '') + self.TestLint('typedef void (*Func)(int x);', '') + self.TestLint('typedef void (*Func)(int *x);', '') + self.TestLint('typedef void Func(int x);', '') + self.TestLint('typedef void Func(int *x);', '') def testIncludeWhatYouUseNoImplementationFiles(self): code = 'std::vector foo;' - for extension in ['h', 'hpp', 'hxx', 'h++', 'cuh', - 'c', 'cc', 'cpp', 'cxx', 'c++', 'cu']: - self.assertEqual('Add #include for vector<>' - ' [build/include_what_you_use] [4]', - self.PerformIncludeWhatYouUse(code, 'foo.' + extension)) + for extension in [ + 'h', + 'hpp', + 'hxx', + 'h++', + 'cuh', + 'c', + 'cc', + 'cpp', + 'cxx', + 'c++', + 'cu', + ]: + self.assertEqual( + 'Add #include for vector<> [build/include_what_you_use] [4]', + self.PerformIncludeWhatYouUse(code, 'foo.' + extension), + ) def testIncludeWhatYouUse(self): self.TestIncludeWhatYouUse( - """#include + """#include std::vector foo; """, - '') + '', + ) self.TestIncludeWhatYouUse( - """#include + """#include std::pair foo; """, - 'Add #include for pair<>' - ' [build/include_what_you_use] [4]') + 'Add #include for pair<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include std::pair foo; """, - 'Add #include for pair<>' - ' [build/include_what_you_use] [4]') + 'Add #include for pair<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include std::pair foo; """, - 'Add #include for pair<>' - ' [build/include_what_you_use] [4]') + 'Add #include for pair<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include auto foo = std::make_pair(1, 2); """, - 'Add #include for make_pair' - ' [build/include_what_you_use] [4]') + 'Add #include for make_pair [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include std::pair foo; """, - '') + '', + ) self.TestIncludeWhatYouUse( - """#include + """#include DECLARE_string(foobar); """, - '') + '', + ) self.TestIncludeWhatYouUse( - """#include + """#include DEFINE_string(foobar, "", ""); """, - '') + '', + ) self.TestIncludeWhatYouUse( - """#include + """#include std::pair foo; """, - 'Add #include for pair<>' - ' [build/include_what_you_use] [4]') + 'Add #include for pair<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include "base/foobar.h" + """#include "base/foobar.h" std::vector foo; """, - 'Add #include for vector<>' - ' [build/include_what_you_use] [4]') + 'Add #include for vector<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include std::set foo; """, - 'Add #include for set<>' - ' [build/include_what_you_use] [4]') + 'Add #include for set<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include "base/foobar.h" + """#include "base/foobar.h" hash_map foobar; """, - 'Add #include for hash_map<>' - ' [build/include_what_you_use] [4]') + 'Add #include for hash_map<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include "base/containers/hash_tables.h" + """#include "base/containers/hash_tables.h" base::hash_map foobar; """, - '') + '', + ) self.TestIncludeWhatYouUse( - """#include "base/foobar.h" + """#include "base/foobar.h" bool foobar = std::less(0,1); """, - 'Add #include for less<>' - ' [build/include_what_you_use] [4]') + 'Add #include for less<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include "base/foobar.h" + """#include "base/foobar.h" bool foobar = min(0,1); """, - 'Add #include for min [build/include_what_you_use] [4]') + 'Add #include for min [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - 'cout << "hello world" << endl;', - 'Add #include for cout [build/include_what_you_use] [4]') + 'cout << "hello world" << endl;', + 'Add #include for cout [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - 'printf("hello world");', - 'Add #include for printf [build/include_what_you_use] [4]') + 'printf("hello world");', + 'Add #include for printf [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( """#include - printf("hello world");""", '') # Avoid false positives w/ c-style include + printf("hello world");""", + '', + ) # Avoid false positives w/ c-style include self.TestIncludeWhatYouUse( - 'void a(const string &foobar);', - 'Add #include for string [build/include_what_you_use] [4]') + 'void a(const string &foobar);', + 'Add #include for string [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - 'void a(const std::string &foobar);', - 'Add #include for string [build/include_what_you_use] [4]') + 'void a(const std::string &foobar);', + 'Add #include for string [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - 'void a(const my::string &foobar);', - '') # Avoid false positives on strings in other namespaces. + 'void a(const my::string &foobar);', '' + ) # Avoid false positives on strings in other namespaces. self.TestIncludeWhatYouUse( - """#include "base/foobar.h" + """#include "base/foobar.h" bool foobar = swap(0,1); """, - 'Add #include for swap [build/include_what_you_use] [4]') + 'Add #include for swap [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include "base/foobar.h" + """#include "base/foobar.h" bool foobar = transform(a.begin(), a.end(), b.start(), Foo); """, - 'Add #include for transform ' - '[build/include_what_you_use] [4]') + 'Add #include for transform [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include "base/foobar.h" + """#include "base/foobar.h" boost::range::transform(input, std::back_inserter(output), square); """, - '') # Avoid false positives on transform in other namespaces. + '', + ) # Avoid false positives on transform in other namespaces. self.TestIncludeWhatYouUse( - """#include "base/foobar.h" + """#include "base/foobar.h" bool foobar = std::min_element(a.begin(), a.end()); """, - 'Add #include for min_element ' - '[build/include_what_you_use] [4]') + 'Add #include for min_element [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """foo->swap(0,1); + """foo->swap(0,1); foo.swap(0,1); """, - '') + '', + ) self.TestIncludeWhatYouUse( - """#include + """#include void a(const std::multimap &foobar); """, - 'Add #include for multimap<>' - ' [build/include_what_you_use] [4]') + 'Add #include for multimap<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include void a(const std::unordered_map &foobar); """, - 'Add #include for unordered_map<>' - ' [build/include_what_you_use] [4]') + 'Add #include for unordered_map<>' + ' [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include void a(const std::unordered_set &foobar); """, - 'Add #include for unordered_set<>' - ' [build/include_what_you_use] [4]') + 'Add #include for unordered_set<>' + ' [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include void a(const std::priority_queue &foobar); """, - '') + '', + ) self.TestIncludeWhatYouUse( - """#include + """#include #include #include #include "base/basictypes.h" #include "base/port.h" - vector hajoa;""", '') + vector hajoa;""", + '', + ) self.TestIncludeWhatYouUse( - """#include + """#include int i = numeric_limits::max() """, - 'Add #include for numeric_limits<>' - ' [build/include_what_you_use] [4]') + 'Add #include for numeric_limits<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include int i = numeric_limits::max() """, - '') + '', + ) self.TestIncludeWhatYouUse( - """#include + """#include std::unique_ptr x; """, - 'Add #include for unique_ptr<>' - ' [build/include_what_you_use] [4]') + 'Add #include for unique_ptr<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include auto x = std::make_unique(0); """, - 'Add #include for make_unique<>' - ' [build/include_what_you_use] [4]') + 'Add #include for make_unique<> [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include vector foo(vector x) { return std::move(x); } """, - 'Add #include for move' - ' [build/include_what_you_use] [4]') + 'Add #include for move [build/include_what_you_use] [4]', + ) self.TestIncludeWhatYouUse( - """#include + """#include int a, b; std::swap(a, b); """, - 'Add #include for swap' - ' [build/include_what_you_use] [4]') + 'Add #include for swap [build/include_what_you_use] [4]', + ) # False positive for std::set self.TestIncludeWhatYouUse( - """ + """ #include struct Foo { template @@ -1240,10 +1368,11 @@ def testIncludeWhatYouUse(self): Foo* pbar = &bar; bar.set("int", 5); pbar->set("bool", false);""", - '') + '', + ) # False positive for std::map self.TestIncludeWhatYouUse( - """ + """ template struct Foo { T t; @@ -1256,13 +1385,15 @@ def testIncludeWhatYouUse(self): }; auto res = map(); """, - '') + '', + ) # False positive for boost::container::set self.TestIncludeWhatYouUse( - """ + """ boost::container::set foo; """, - '') + '', + ) def testFilesBelongToSameModule(self): f = cpplint.FilesBelongToSameModule @@ -1275,86 +1406,89 @@ def testFilesBelongToSameModule(self): self.assertEqual((True, ''), f('base/google_test.cpp', 'base/google.hpp')) self.assertEqual((True, ''), f('base/google_test.c++', 'base/google.h++')) self.assertEqual((True, ''), f('base/google_test.cu', 'base/google.cuh')) - self.assertEqual((True, ''), - f('base/google_unittest.cc', 'base/google.h')) - self.assertEqual((True, ''), - f('base/internal/google_unittest.cc', - 'base/public/google.h')) - self.assertEqual((True, 'xxx/yyy/'), - f('xxx/yyy/base/internal/google_unittest.cc', - 'base/public/google.h')) - self.assertEqual((True, 'xxx/yyy/'), - f('xxx/yyy/base/google_unittest.cc', - 'base/public/google.h')) - self.assertEqual((True, ''), - f('base/google_unittest.cc', 'base/google-inl.h')) - self.assertEqual((True, '/home/build/google3/'), - f('/home/build/google3/base/google.cc', 'base/google.h')) - - self.assertEqual((False, ''), - f('/home/build/google3/base/google.cc', 'basu/google.h')) + self.assertEqual((True, ''), f('base/google_unittest.cc', 'base/google.h')) + self.assertEqual( + (True, ''), f('base/internal/google_unittest.cc', 'base/public/google.h') + ) + self.assertEqual( + (True, 'xxx/yyy/'), + f('xxx/yyy/base/internal/google_unittest.cc', 'base/public/google.h'), + ) + self.assertEqual( + (True, 'xxx/yyy/'), f('xxx/yyy/base/google_unittest.cc', 'base/public/google.h') + ) + self.assertEqual((True, ''), f('base/google_unittest.cc', 'base/google-inl.h')) + self.assertEqual( + (True, '/home/build/google3/'), + f('/home/build/google3/base/google.cc', 'base/google.h'), + ) + + self.assertEqual( + (False, ''), f('/home/build/google3/base/google.cc', 'basu/google.h') + ) self.assertEqual((False, ''), f('a.cc', 'b.h')) def testCleanseLine(self): - self.assertEqual('int foo = 0;', - cpplint.CleanseComments('int foo = 0; // danger!')) - self.assertEqual('int o = 0;', - cpplint.CleanseComments('int /* foo */ o = 0;')) - self.assertEqual('foo(int a, int b);', - cpplint.CleanseComments('foo(int a /* abc */, int b);')) - self.assertEqual('f(a, b);', - cpplint.CleanseComments('f(a, /* name */ b);')) - self.assertEqual('f(a, b);', - cpplint.CleanseComments('f(a /* name */, b);')) - self.assertEqual('f(a, b);', - cpplint.CleanseComments('f(a, /* name */b);')) - self.assertEqual('f(a, b, c);', - cpplint.CleanseComments('f(a, /**/b, /**/c);')) - self.assertEqual('f(a, b, c);', - cpplint.CleanseComments('f(a, /**/b/**/, c);')) + self.assertEqual( + 'int foo = 0;', cpplint.CleanseComments('int foo = 0; // danger!') + ) + self.assertEqual('int o = 0;', cpplint.CleanseComments('int /* foo */ o = 0;')) + self.assertEqual( + 'foo(int a, int b);', cpplint.CleanseComments('foo(int a /* abc */, int b);') + ) + self.assertEqual('f(a, b);', cpplint.CleanseComments('f(a, /* name */ b);')) + self.assertEqual('f(a, b);', cpplint.CleanseComments('f(a /* name */, b);')) + self.assertEqual('f(a, b);', cpplint.CleanseComments('f(a, /* name */b);')) + self.assertEqual('f(a, b, c);', cpplint.CleanseComments('f(a, /**/b, /**/c);')) + self.assertEqual('f(a, b, c);', cpplint.CleanseComments('f(a, /**/b/**/, c);')) def testRawStrings(self): self.TestMultiLineLint( - """ + """ int main() { struct A { A(std::string s, A&& a); }; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ template > class unique_ptr { public: unique_ptr(unique_ptr&& u) noexcept; };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ void Func() { static const char kString[] = R"( #endif <- invalid preprocessor should be ignored */ <- invalid comment should be ignored too )"; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ void Func() { string s = R"TrueDelimiter( )" )FalseDelimiter" )TrueDelimiter"; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ void Func() { char char kString[] = R"( ";" )"; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ static const char kRawString[] = R"( \tstatic const int kLineWithTab = 1; static const int kLineWithTrailingWhiteSpace = 1;\x20 @@ -1371,9 +1505,10 @@ def testRawStrings(self): } )";""", - '') + '', + ) self.TestMultiLineLint( - """ + """ void Func() { string s = StrCat(R"TrueDelimiter( )" @@ -1383,64 +1518,79 @@ def testRawStrings(self): )FalseDelimiter2" )TrueDelimiter2"); }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ static SomeStruct kData = { {0, R"(line1 line2 )"} };""", - '') + '', + ) def testMultiLineComments(self): # missing explicit is bad self.TestMultiLineLint( - r"""int a = 0; + r"""int a = 0; /* multi-liner class Foo { Foo(int f); // should cause a lint warning in code } */ """, - '') + '', + ) self.TestMultiLineLint( - r"""/* int a = 0; multi-liner + r"""/* int a = 0; multi-liner static const int b = 0;""", - 'Could not find end of multi-line comment' - ' [readability/multiline_comment] [5]') - self.TestMultiLineLint(r""" /* multi-line comment""", - 'Could not find end of multi-line comment' - ' [readability/multiline_comment] [5]') + 'Could not find end of multi-line comment [readability/multiline_comment] [5]', + ) + self.TestMultiLineLint( + r""" /* multi-line comment""", + 'Could not find end of multi-line comment [readability/multiline_comment] [5]', + ) self.TestMultiLineLint(r""" // /* comment, but not multi-line""", '') - self.TestMultiLineLint(r"""/********** - */""", '') - self.TestMultiLineLint(r"""/** + self.TestMultiLineLint( + r"""/********** + */""", + '', + ) + self.TestMultiLineLint( + r"""/** * Doxygen comment */""", - '') - self.TestMultiLineLint(r"""/*! + '', + ) + self.TestMultiLineLint( + r"""/*! * Doxygen comment */""", - '') + '', + ) def testMultilineStrings(self): multiline_string_error_message = ( - 'Multi-line string ("...") found. This lint script doesn\'t ' - 'do well with such strings, and may give bogus warnings. ' - 'Use C++11 raw strings or concatenation instead.' - ' [readability/multiline_string] [5]') + 'Multi-line string ("...") found. This lint script doesn\'t ' + 'do well with such strings, and may give bogus warnings. ' + 'Use C++11 raw strings or concatenation instead.' + ' [readability/multiline_string] [5]' + ) for extension in ['c', 'cc', 'cpp', 'cxx', 'c++', 'cu']: file_path = 'mydir/foo.' + extension error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, extension, - ['const char* str = "This is a\\', - ' multiline string.";'], - error_collector) + cpplint.ProcessFileData( + file_path, + extension, + ['const char* str = "This is a\\', ' multiline string.";'], + error_collector, + ) self.assertEqual( - 2, # One per line. - error_collector.ResultList().count(multiline_string_error_message)) + 2, # One per line. + error_collector.ResultList().count(multiline_string_error_message), + ) # Test non-explicit single-argument constructors def testExplicitSingleArgumentConstructors(self): @@ -1450,424 +1600,509 @@ def testExplicitSingleArgumentConstructors(self): try: # missing explicit is bad self.TestMultiLineLint( - """ + """ class Foo { Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # missing explicit is bad, even with whitespace self.TestMultiLineLint( - """ + """ class Foo { Foo (int f); };""", - ['Extra space before ( in function call [whitespace/parens] [4]', - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]']) + [ + 'Extra space before ( in function call [whitespace/parens] [4]', + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ], + ) # missing explicit, with distracting comment, is still bad self.TestMultiLineLint( - """ + """ class Foo { Foo(int f); // simpler than Foo(blargh, blarg) };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # missing explicit, with qualified classname self.TestMultiLineLint( - """ + """ class Qualifier::AnotherOne::Foo { Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # missing explicit for inline constructors is bad as well self.TestMultiLineLint( - """ + """ class Foo { inline Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # missing explicit for constexpr constructors is bad as well self.TestMultiLineLint( - """ + """ class Foo { constexpr Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # missing explicit for constexpr+inline constructors is bad as well self.TestMultiLineLint( - """ + """ class Foo { constexpr inline Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) self.TestMultiLineLint( - """ + """ class Foo { inline constexpr Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # explicit with inline is accepted self.TestMultiLineLint( - """ + """ class Foo { inline explicit Foo(int f); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { explicit inline Foo(int f); };""", - '') + '', + ) # explicit with constexpr is accepted self.TestMultiLineLint( - """ + """ class Foo { constexpr explicit Foo(int f); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { explicit constexpr Foo(int f); };""", - '') + '', + ) # explicit with constexpr+inline is accepted self.TestMultiLineLint( - """ + """ class Foo { inline constexpr explicit Foo(int f); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { explicit inline constexpr Foo(int f); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { constexpr inline explicit Foo(int f); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { explicit constexpr inline Foo(int f); };""", - '') + '', + ) # structs are caught as well. self.TestMultiLineLint( - """ + """ struct Foo { Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # Templatized classes are caught as well. self.TestMultiLineLint( - """ + """ template class Foo { Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # inline case for templatized classes. self.TestMultiLineLint( - """ + """ template class Foo { inline Foo(int f); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # constructors with a default argument should still be marked explicit self.TestMultiLineLint( - """ + """ class Foo { Foo(int f = 0); };""", - 'Constructors callable with one argument should be marked explicit.' - ' [runtime/explicit] [4]') + 'Constructors callable with one argument should be marked explicit.' + ' [runtime/explicit] [4]', + ) # multi-argument constructors with all but one default argument should be # marked explicit self.TestMultiLineLint( - """ + """ class Foo { Foo(int f, int g = 0); };""", - 'Constructors callable with one argument should be marked explicit.' - ' [runtime/explicit] [4]') + 'Constructors callable with one argument should be marked explicit.' + ' [runtime/explicit] [4]', + ) # multi-argument constructors with all default arguments should be marked # explicit self.TestMultiLineLint( - """ + """ class Foo { Foo(int f = 0, int g = 0); };""", - 'Constructors callable with one argument should be marked explicit.' - ' [runtime/explicit] [4]') + 'Constructors callable with one argument should be marked explicit.' + ' [runtime/explicit] [4]', + ) # explicit no-argument constructors are just fine self.TestMultiLineLint( - """ + """ class Foo { explicit Foo(); };""", - '') + '', + ) # void constructors are considered no-argument self.TestMultiLineLint( - """ + """ class Foo { explicit Foo(void); };""", - '') + '', + ) # No warning for multi-parameter constructors self.TestMultiLineLint( - """ + """ class Foo { explicit Foo(int f, int g); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { explicit Foo(int f, int g = 0); };""", - '') + '', + ) # single-argument constructors that take a function that takes multiple # arguments should be explicit self.TestMultiLineLint( - """ + """ class Foo { Foo(void (*f)(int f, int g)); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # single-argument constructors that take a single template argument with # multiple parameters should be explicit self.TestMultiLineLint( - """ + """ template class Foo { Foo(Bar b); };""", - 'Single-parameter constructors should be marked explicit.' - ' [runtime/explicit] [4]') + 'Single-parameter constructors should be marked explicit.' + ' [runtime/explicit] [4]', + ) # but copy constructors that take multiple template parameters are OK self.TestMultiLineLint( - """ + """ template class Foo { Foo(Foo& f); };""", - '') + '', + ) # proper style is okay self.TestMultiLineLint( - """ + """ class Foo { explicit Foo(int f); };""", - '') + '', + ) # two argument constructor is okay self.TestMultiLineLint( - """ + """ class Foo { Foo(int f, int b); };""", - '') + '', + ) # two argument constructor, across two lines, is okay self.TestMultiLineLint( - """ + """ class Foo { Foo(int f, int b); };""", - '') + '', + ) # non-constructor (but similar name), is okay self.TestMultiLineLint( - """ + """ class Foo { aFoo(int f); };""", - '') + '', + ) # constructor with void argument is okay self.TestMultiLineLint( - """ + """ class Foo { Foo(void); };""", - '') + '', + ) # single argument method is okay self.TestMultiLineLint( - """ + """ class Foo { Bar(int b); };""", - '') + '', + ) # comments should be ignored self.TestMultiLineLint( - """ + """ class Foo { // Foo(int f); };""", - '') + '', + ) # single argument function following class definition is okay # (okay, it's not actually valid, but we don't want a false positive) self.TestMultiLineLint( - """ + """ class Foo { Foo(int f, int b); }; Foo(int f);""", - '') + '', + ) # single argument function is okay - self.TestMultiLineLint( - """static Foo(int f);""", - '') + self.TestMultiLineLint("""static Foo(int f);""", '') # single argument copy constructor is okay. self.TestMultiLineLint( - """ + """ class Foo { Foo(const Foo&); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { Foo(volatile Foo&); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { Foo(volatile const Foo&); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { Foo(const volatile Foo&); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { Foo(Foo const&); };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo { Foo(Foo&); };""", - '') + '', + ) # templatized copy constructor is okay. self.TestMultiLineLint( - """ + """ template class Foo { Foo(const Foo&); };""", - '') + '', + ) # Special case for std::initializer_list self.TestMultiLineLint( - """ + """ class Foo { Foo(std::initializer_list &arg) {} };""", - '') + '', + ) # Special case for variadic arguments error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['class Foo {', + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'class Foo {', ' template', ' explicit Foo(const int arg, Args&&... args) {}', - '};'], - error_collector) - self.assertEqual(0, error_collector.ResultList().count( - 'Constructors that require multiple arguments should not be marked ' - 'explicit. [runtime/explicit] [0]')) + '};', + ], + error_collector, + ) + self.assertEqual( + 0, + error_collector.ResultList().count( + 'Constructors that require multiple arguments should not be marked ' + 'explicit. [runtime/explicit] [0]' + ), + ) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['class Foo {', + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'class Foo {', ' template', ' explicit Foo(Args&&... args) {}', - '};'], - error_collector) - self.assertEqual(0, error_collector.ResultList().count( - 'Constructors that require multiple arguments should not be marked ' - 'explicit. [runtime/explicit] [0]')) + '};', + ], + error_collector, + ) + self.assertEqual( + 0, + error_collector.ResultList().count( + 'Constructors that require multiple arguments should not be marked ' + 'explicit. [runtime/explicit] [0]' + ), + ) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['class Foo {', + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'class Foo {', ' template', ' Foo(const int arg, Args&&... args) {}', - '};'], - error_collector) - self.assertEqual(1, error_collector.ResultList().count( - 'Constructors callable with one argument should be marked explicit.' - ' [runtime/explicit] [4]')) + '};', + ], + error_collector, + ) + self.assertEqual( + 1, + error_collector.ResultList().count( + 'Constructors callable with one argument should be marked explicit.' + ' [runtime/explicit] [4]' + ), + ) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['class Foo {', + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'class Foo {', ' template', ' Foo(Args&&... args) {}', - '};'], - error_collector) - self.assertEqual(1, error_collector.ResultList().count( - 'Constructors callable with one argument should be marked explicit.' - ' [runtime/explicit] [4]')) + '};', + ], + error_collector, + ) + self.assertEqual( + 1, + error_collector.ResultList().count( + 'Constructors callable with one argument should be marked explicit.' + ' [runtime/explicit] [4]' + ), + ) # Anything goes inside an assembly block error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['void Func() {', - ' __asm__ (', - ' "hlt"', - ' );', - ' asm {', - ' movdqa [edx + 32], xmm2', - ' }', - '}'], - error_collector) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'void Func() {', + ' __asm__ (', + ' "hlt"', + ' );', + ' asm {', + ' movdqa [edx + 32], xmm2', + ' }', + '}', + ], + error_collector, + ) self.assertEqual( - 0, - error_collector.ResultList().count( - 'Extra space before ( in function call [whitespace/parens] [4]')) + 0, + error_collector.ResultList().count( + 'Extra space before ( in function call [whitespace/parens] [4]' + ), + ) self.assertEqual( - 0, - error_collector.ResultList().count( - 'Closing ) should be moved to the previous line ' - '[whitespace/parens] [2]')) + 0, + error_collector.ResultList().count( + 'Closing ) should be moved to the previous line [whitespace/parens] [2]' + ), + ) self.assertEqual( - 0, - error_collector.ResultList().count( - 'Extra space before [ [whitespace/braces] [5]')) + 0, + error_collector.ResultList().count( + 'Extra space before [ [whitespace/braces] [5]' + ), + ) finally: cpplint._cpplint_state.verbose_level = old_verbose_level def testSlashStarCommentOnSingleLine(self): + self.TestMultiLineLint("""/* static */ Foo(int f);""", '') + self.TestMultiLineLint("""/*/ static */ Foo(int f);""", '') self.TestMultiLineLint( - """/* static */ Foo(int f);""", - '') - self.TestMultiLineLint( - """/*/ static */ Foo(int f);""", - '') - self.TestMultiLineLint( - """/*/ static Foo(int f);""", - 'Could not find end of multi-line comment' - ' [readability/multiline_comment] [5]') - self.TestMultiLineLint( - """ /*/ static Foo(int f);""", - 'Could not find end of multi-line comment' - ' [readability/multiline_comment] [5]') + """/*/ static Foo(int f);""", + 'Could not find end of multi-line comment [readability/multiline_comment] [5]', + ) self.TestMultiLineLint( - """ /**/ static Foo(int f);""", - '') + """ /*/ static Foo(int f);""", + 'Could not find end of multi-line comment [readability/multiline_comment] [5]', + ) + self.TestMultiLineLint(""" /**/ static Foo(int f);""", '') # Test suspicious usage of "if" like this: # if (a == b) { @@ -1876,57 +2111,46 @@ def testSlashStarCommentOnSingleLine(self): # DoSomething(); // This gets called twice if a == b && a == c. # } def testSuspiciousUsageOfIf(self): + self.TestLint(' if (a == b) {', '') self.TestLint( - ' if (a == b) {', - '') - self.TestLint( - ' } if (a == b) {', - 'Did you mean "else if"? If not, start a new line for "if".' - ' [readability/braces] [4]') + ' } if (a == b) {', + 'Did you mean "else if"? If not, start a new line for "if".' + ' [readability/braces] [4]', + ) # Test suspicious usage of memset. Specifically, a 0 # as the final argument is almost certainly an error. def testSuspiciousUsageOfMemset(self): # Normal use is okay. - self.TestLint( - ' memset(buf, 0, sizeof(buf))', - '') + self.TestLint(' memset(buf, 0, sizeof(buf))', '') # A 0 as the final argument is almost certainly an error. self.TestLint( - ' memset(buf, sizeof(buf), 0)', - 'Did you mean "memset(buf, 0, sizeof(buf))"?' - ' [runtime/memset] [4]') + ' memset(buf, sizeof(buf), 0)', + 'Did you mean "memset(buf, 0, sizeof(buf))"? [runtime/memset] [4]', + ) self.TestLint( - ' memset(buf, xsize * ysize, 0)', - 'Did you mean "memset(buf, 0, xsize * ysize)"?' - ' [runtime/memset] [4]') + ' memset(buf, xsize * ysize, 0)', + 'Did you mean "memset(buf, 0, xsize * ysize)"? [runtime/memset] [4]', + ) # There is legitimate test code that uses this form. # This is okay since the second argument is a literal. - self.TestLint( - " memset(buf, 'y', 0)", - '') - self.TestLint( - ' memset(buf, 4, 0)', - '') - self.TestLint( - ' memset(buf, -1, 0)', - '') - self.TestLint( - ' memset(buf, 0xF1, 0)', - '') - self.TestLint( - ' memset(buf, 0xcd, 0)', - '') + self.TestLint(" memset(buf, 'y', 0)", '') + self.TestLint(' memset(buf, 4, 0)', '') + self.TestLint(' memset(buf, -1, 0)', '') + self.TestLint(' memset(buf, 0xF1, 0)', '') + self.TestLint(' memset(buf, 0xcd, 0)', '') def testRedundantVirtual(self): self.TestLint('virtual void F()', '') self.TestLint('virtual void F();', '') self.TestLint('virtual void F() {}', '') - message_template = ('"%s" is redundant since function is already ' - 'declared as "%s" [readability/inheritance] [4]') + message_template = ( + '"%s" is redundant since function is already ' + 'declared as "%s" [readability/inheritance] [4]' + ) for virt_specifier in ['override', 'final']: error_message = message_template % ('virtual', virt_specifier) self.TestLint('virtual int F() %s' % virt_specifier, error_message) @@ -1935,20 +2159,24 @@ def testRedundantVirtual(self): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company.', - 'virtual void F(int a,', - ' int b) ' + virt_specifier + ';', - 'virtual void F(int a,', - ' int b) LOCKS_EXCLUDED(lock) ' + virt_specifier + ';', - 'virtual void F(int a,', - ' int b)', - ' LOCKS_EXCLUDED(lock) ' + virt_specifier + ';', - ''], - error_collector) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + 'virtual void F(int a,', + ' int b) ' + virt_specifier + ';', + 'virtual void F(int a,', + ' int b) LOCKS_EXCLUDED(lock) ' + virt_specifier + ';', + 'virtual void F(int a,', + ' int b)', + ' LOCKS_EXCLUDED(lock) ' + virt_specifier + ';', + '', + ], + error_collector, + ) self.assertEqual( - [error_message, error_message, error_message], - error_collector.Results()) + [error_message, error_message, error_message], error_collector.Results() + ) error_message = message_template % ('override', 'final') self.TestLint('int F() override final', error_message) @@ -1960,18 +2188,21 @@ def testRedundantVirtual(self): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company.', - 'struct A : virtual B {', - ' ~A() override;' - '};', - 'class C', - ' : public D,', - ' public virtual E {', - ' void Func() override;', - '}', - ''], - error_collector) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + 'struct A : virtual B {', + ' ~A() override;};', + 'class C', + ' : public D,', + ' public virtual E {', + ' void Func() override;', + '}', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) self.TestLint('void Finalize(AnnotationProto *final) override;', '') @@ -1990,15 +2221,19 @@ def testCheckPosixThreading(self): self.TestLint('->rand()', '') self.TestLint('ACMRandom rand(seed)', '') self.TestLint('ISAACRandom rand()', '') - self.TestLint('var = rand()', - 'Consider using rand_r(...) instead of rand(...)' - ' for improved thread safety.' - ' [runtime/threadsafe_fn] [2]') - self.TestLint('var = strtok(str, delim)', - 'Consider using strtok_r(...) ' - 'instead of strtok(...)' - ' for improved thread safety.' - ' [runtime/threadsafe_fn] [2]') + self.TestLint( + 'var = rand()', + 'Consider using rand_r(...) instead of rand(...)' + ' for improved thread safety.' + ' [runtime/threadsafe_fn] [2]', + ) + self.TestLint( + 'var = strtok(str, delim)', + 'Consider using strtok_r(...) ' + 'instead of strtok(...)' + ' for improved thread safety.' + ' [runtime/threadsafe_fn] [2]', + ) def testVlogMisuse(self): self.TestLint('VLOG(1)', '') @@ -2010,9 +2245,11 @@ def testVlogMisuse(self): self.TestLint('LOG(DFATAL)', '') self.TestLint('VLOG(SOMETHINGWEIRD)', '') self.TestLint('MYOWNVLOG(ERROR)', '') - errmsg = ('VLOG() should be used with numeric verbosity level. ' - 'Use LOG() if you want symbolic severity levels.' - ' [runtime/vlog] [5]') + errmsg = ( + 'VLOG() should be used with numeric verbosity level. ' + 'Use LOG() if you want symbolic severity levels.' + ' [runtime/vlog] [5]' + ) self.TestLint('VLOG(ERROR)', errmsg) self.TestLint('VLOG(INFO)', errmsg) self.TestLint('VLOG(WARNING)', errmsg) @@ -2034,44 +2271,53 @@ def testFormatStrings(self): self.TestLint('printf(format.c_str(), value)', '') # Should not trigger. self.TestLint('printf(format(index).c_str(), value)', '') self.TestLint( - 'printf(foo)', - 'Potential format string bug. Do printf("%s", foo) instead.' - ' [runtime/printf] [4]') + 'printf(foo)', + 'Potential format string bug. Do printf("%s", foo) instead.' + ' [runtime/printf] [4]', + ) self.TestLint( - 'printf(foo.c_str())', - 'Potential format string bug. ' - 'Do printf("%s", foo.c_str()) instead.' - ' [runtime/printf] [4]') + 'printf(foo.c_str())', + 'Potential format string bug. ' + 'Do printf("%s", foo.c_str()) instead.' + ' [runtime/printf] [4]', + ) self.TestLint( - 'printf(foo->c_str())', - 'Potential format string bug. ' - 'Do printf("%s", foo->c_str()) instead.' - ' [runtime/printf] [4]') + 'printf(foo->c_str())', + 'Potential format string bug. ' + 'Do printf("%s", foo->c_str()) instead.' + ' [runtime/printf] [4]', + ) self.TestLint( - 'StringPrintf(foo)', - 'Potential format string bug. Do StringPrintf("%s", foo) instead.' - '' - ' [runtime/printf] [4]') + 'StringPrintf(foo)', + 'Potential format string bug. Do StringPrintf("%s", foo) instead.' + '' + ' [runtime/printf] [4]', + ) # Test disallowed use of operator& and other operators. def testIllegalOperatorOverloading(self): - errmsg = ('Unary operator& is dangerous. Do not use it.' - ' [runtime/operator] [4]') + errmsg = 'Unary operator& is dangerous. Do not use it. [runtime/operator] [4]' self.TestLint('void operator=(const Myclass&)', '') - self.TestLint('void operator&(int a, int b)', '') # binary operator& ok + self.TestLint('void operator&(int a, int b)', '') # binary operator& ok self.TestLint('void operator&() { }', errmsg) - self.TestLint('void operator & ( ) { }', - ['Extra space after ( [whitespace/parens] [2]', errmsg]) + self.TestLint( + 'void operator & ( ) { }', + ['Extra space after ( [whitespace/parens] [2]', errmsg], + ) # const string reference members are dangerous.. def testConstStringReferenceMembers(self): - errmsg = ('const string& members are dangerous. It is much better to use ' - 'alternatives, such as pointers or simple constants.' - ' [runtime/member_string_references] [2]') + errmsg = ( + 'const string& members are dangerous. It is much better to use ' + 'alternatives, such as pointers or simple constants.' + ' [runtime/member_string_references] [2]' + ) - members_declarations = ['const string& church', - 'const string &turing', - 'const string & godel'] + members_declarations = [ + 'const string& church', + 'const string &turing', + 'const string & godel', + ] # TODO(unknown): Enable also these tests if and when we ever # decide to check for arbitrary member references. # "const Turing & a", @@ -2097,9 +2343,11 @@ def testConstStringReferenceMembers(self): # Variable-length arrays are not permitted. def testVariableLengthArrayDetection(self): - errmsg = ('Do not use variable-length arrays. Use an appropriately named ' - "('k' followed by CamelCase) compile-time constant for the size." - ' [runtime/arrays] [1]') + errmsg = ( + 'Do not use variable-length arrays. Use an appropriately named ' + "('k' followed by CamelCase) compile-time constant for the size." + ' [runtime/arrays] [1]' + ) self.TestLint('int a[any_old_variable];', errmsg) self.TestLint('int doublesize[some_var * 2];', errmsg) @@ -2129,76 +2377,88 @@ def testVariableLengthArrayDetection(self): # DISALLOW_COPY_AND_ASSIGN and DISALLOW_IMPLICIT_CONSTRUCTORS should be at # end of class if present. def testDisallowMacrosAtEnd(self): - for macro_name in ( - 'DISALLOW_COPY_AND_ASSIGN', - 'DISALLOW_IMPLICIT_CONSTRUCTORS'): + for macro_name in ('DISALLOW_COPY_AND_ASSIGN', 'DISALLOW_IMPLICIT_CONSTRUCTORS'): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company.', - 'class SomeClass {', - ' private:', - ' %s(SomeClass);' % macro_name, - ' int member_;', - '};', - ''], - error_collector) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + 'class SomeClass {', + ' private:', + ' %s(SomeClass);' % macro_name, + ' int member_;', + '};', + '', + ], + error_collector, + ) self.assertEqual( - ('%s should be the last thing in the class' % macro_name) + - ' [readability/constructors] [3]', - error_collector.Results()) + ('%s should be the last thing in the class' % macro_name) + + ' [readability/constructors] [3]', + error_collector.Results(), + ) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company.', - 'class OuterClass {', - ' private:', - ' struct InnerClass {', - ' private:', - ' %s(InnerClass);' % macro_name, - ' int member;', - ' };', - '};', - ''], - error_collector) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + 'class OuterClass {', + ' private:', + ' struct InnerClass {', + ' private:', + ' %s(InnerClass);' % macro_name, + ' int member;', + ' };', + '};', + '', + ], + error_collector, + ) self.assertEqual( - ('%s should be the last thing in the class' % macro_name) + - ' [readability/constructors] [3]', - error_collector.Results()) + ('%s should be the last thing in the class' % macro_name) + + ' [readability/constructors] [3]', + error_collector.Results(), + ) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company.', - 'class OuterClass1 {', - ' private:', - ' struct InnerClass1 {', - ' private:', - ' %s(InnerClass1);' % macro_name, - ' };', - ' %s(OuterClass1);' % macro_name, - '};', - 'struct OuterClass2 {', - ' private:', - ' class InnerClass2 {', - ' private:', - ' %s(InnerClass2);' % macro_name, - ' // comment', - ' };', - '', - ' %s(OuterClass2);' % macro_name, - '', - ' // comment', - '};', - 'void Func() {', - ' struct LocalClass {', - ' private:', - ' %s(LocalClass);' % macro_name, - ' } variable;', - '}', - ''], - error_collector) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + 'class OuterClass1 {', + ' private:', + ' struct InnerClass1 {', + ' private:', + ' %s(InnerClass1);' % macro_name, + ' };', + ' %s(OuterClass1);' % macro_name, + '};', + 'struct OuterClass2 {', + ' private:', + ' class InnerClass2 {', + ' private:', + ' %s(InnerClass2);' % macro_name, + ' // comment', + ' };', + '', + ' %s(OuterClass2);' % macro_name, + '', + ' // comment', + '};', + 'void Func() {', + ' struct LocalClass {', + ' private:', + ' %s(LocalClass);' % macro_name, + ' } variable;', + '}', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # Brace usage @@ -2207,24 +2467,28 @@ def testBraces(self): # or initializing an array self.TestLint('int a[3] = { 1, 2, 3 };', '') self.TestLint( - """const int foo[] = + """const int foo[] = {1, 2, 3 };""", - '') + '', + ) # For single line, unmatched '}' with a ';' is ignored (not enough context) self.TestMultiLineLint( - """int a[3] = { 1, + """int a[3] = { 1, 2, 3 };""", - '') + '', + ) self.TestMultiLineLint( - """int a[2][3] = { { 1, 2 }, + """int a[2][3] = { { 1, 2 }, { 3, 4 } };""", - '') + '', + ) self.TestMultiLineLint( - """int a[2][3] = + """int a[2][3] = { { 1, 2 }, { 3, 4 } };""", - '') + '', + ) self.TestMultiLineLint( # should not claim else should have braces on both sides """if (foo) { bar; @@ -2232,115 +2496,144 @@ def testBraces(self): else { baz; }""", - 'An else should appear on the same line as the preceding } [whitespace/newline] [4]') + 'An else should appear on the same line as the preceding } [whitespace/newline] [4]', + ) # CHECK/EXPECT_TRUE/EXPECT_FALSE replacements def testCheckCheck(self): - self.TestLint('CHECK(x == 42);', - 'Consider using CHECK_EQ instead of CHECK(a == b)' - ' [readability/check] [2]') - self.TestLint('CHECK(x != 42);', - 'Consider using CHECK_NE instead of CHECK(a != b)' - ' [readability/check] [2]') - self.TestLint('CHECK(x >= 42);', - 'Consider using CHECK_GE instead of CHECK(a >= b)' - ' [readability/check] [2]') - self.TestLint('CHECK(x > 42);', - 'Consider using CHECK_GT instead of CHECK(a > b)' - ' [readability/check] [2]') - self.TestLint('CHECK(x <= 42);', - 'Consider using CHECK_LE instead of CHECK(a <= b)' - ' [readability/check] [2]') - self.TestLint('CHECK(x < 42);', - 'Consider using CHECK_LT instead of CHECK(a < b)' - ' [readability/check] [2]') - - self.TestLint('DCHECK(x == 42);', - 'Consider using DCHECK_EQ instead of DCHECK(a == b)' - ' [readability/check] [2]') - self.TestLint('DCHECK(x != 42);', - 'Consider using DCHECK_NE instead of DCHECK(a != b)' - ' [readability/check] [2]') - self.TestLint('DCHECK(x >= 42);', - 'Consider using DCHECK_GE instead of DCHECK(a >= b)' - ' [readability/check] [2]') - self.TestLint('DCHECK(x > 42);', - 'Consider using DCHECK_GT instead of DCHECK(a > b)' - ' [readability/check] [2]') - self.TestLint('DCHECK(x <= 42);', - 'Consider using DCHECK_LE instead of DCHECK(a <= b)' - ' [readability/check] [2]') - self.TestLint('DCHECK(x < 42);', - 'Consider using DCHECK_LT instead of DCHECK(a < b)' - ' [readability/check] [2]') - - self.TestLint( - 'EXPECT_TRUE("42" == x);', - 'Consider using EXPECT_EQ instead of EXPECT_TRUE(a == b)' - ' [readability/check] [2]') - self.TestLint( - 'EXPECT_TRUE("42" != x);', - 'Consider using EXPECT_NE instead of EXPECT_TRUE(a != b)' - ' [readability/check] [2]') - self.TestLint( - 'EXPECT_TRUE(+42 >= x);', - 'Consider using EXPECT_GE instead of EXPECT_TRUE(a >= b)' - ' [readability/check] [2]') - - self.TestLint( - 'EXPECT_FALSE(x == 42);', - 'Consider using EXPECT_NE instead of EXPECT_FALSE(a == b)' - ' [readability/check] [2]') - self.TestLint( - 'EXPECT_FALSE(x != 42);', - 'Consider using EXPECT_EQ instead of EXPECT_FALSE(a != b)' - ' [readability/check] [2]') - self.TestLint( - 'EXPECT_FALSE(x >= 42);', - 'Consider using EXPECT_LT instead of EXPECT_FALSE(a >= b)' - ' [readability/check] [2]') - self.TestLint( - 'ASSERT_FALSE(x > 42);', - 'Consider using ASSERT_LE instead of ASSERT_FALSE(a > b)' - ' [readability/check] [2]') - self.TestLint( - 'ASSERT_FALSE(x <= 42);', - 'Consider using ASSERT_GT instead of ASSERT_FALSE(a <= b)' - ' [readability/check] [2]') - - self.TestLint('CHECK(x<42);', - ['Missing spaces around <' - ' [whitespace/operators] [3]', - 'Consider using CHECK_LT instead of CHECK(a < b)' - ' [readability/check] [2]']) - self.TestLint('CHECK(x>42);', - ['Missing spaces around >' - ' [whitespace/operators] [3]', - 'Consider using CHECK_GT instead of CHECK(a > b)' - ' [readability/check] [2]']) + self.TestLint( + 'CHECK(x == 42);', + 'Consider using CHECK_EQ instead of CHECK(a == b) [readability/check] [2]', + ) + self.TestLint( + 'CHECK(x != 42);', + 'Consider using CHECK_NE instead of CHECK(a != b) [readability/check] [2]', + ) + self.TestLint( + 'CHECK(x >= 42);', + 'Consider using CHECK_GE instead of CHECK(a >= b) [readability/check] [2]', + ) + self.TestLint( + 'CHECK(x > 42);', + 'Consider using CHECK_GT instead of CHECK(a > b) [readability/check] [2]', + ) + self.TestLint( + 'CHECK(x <= 42);', + 'Consider using CHECK_LE instead of CHECK(a <= b) [readability/check] [2]', + ) + self.TestLint( + 'CHECK(x < 42);', + 'Consider using CHECK_LT instead of CHECK(a < b) [readability/check] [2]', + ) + + self.TestLint( + 'DCHECK(x == 42);', + 'Consider using DCHECK_EQ instead of DCHECK(a == b) [readability/check] [2]', + ) + self.TestLint( + 'DCHECK(x != 42);', + 'Consider using DCHECK_NE instead of DCHECK(a != b) [readability/check] [2]', + ) + self.TestLint( + 'DCHECK(x >= 42);', + 'Consider using DCHECK_GE instead of DCHECK(a >= b) [readability/check] [2]', + ) + self.TestLint( + 'DCHECK(x > 42);', + 'Consider using DCHECK_GT instead of DCHECK(a > b) [readability/check] [2]', + ) + self.TestLint( + 'DCHECK(x <= 42);', + 'Consider using DCHECK_LE instead of DCHECK(a <= b) [readability/check] [2]', + ) + self.TestLint( + 'DCHECK(x < 42);', + 'Consider using DCHECK_LT instead of DCHECK(a < b) [readability/check] [2]', + ) + + self.TestLint( + 'EXPECT_TRUE("42" == x);', + 'Consider using EXPECT_EQ instead of EXPECT_TRUE(a == b)' + ' [readability/check] [2]', + ) + self.TestLint( + 'EXPECT_TRUE("42" != x);', + 'Consider using EXPECT_NE instead of EXPECT_TRUE(a != b)' + ' [readability/check] [2]', + ) + self.TestLint( + 'EXPECT_TRUE(+42 >= x);', + 'Consider using EXPECT_GE instead of EXPECT_TRUE(a >= b)' + ' [readability/check] [2]', + ) + + self.TestLint( + 'EXPECT_FALSE(x == 42);', + 'Consider using EXPECT_NE instead of EXPECT_FALSE(a == b)' + ' [readability/check] [2]', + ) + self.TestLint( + 'EXPECT_FALSE(x != 42);', + 'Consider using EXPECT_EQ instead of EXPECT_FALSE(a != b)' + ' [readability/check] [2]', + ) + self.TestLint( + 'EXPECT_FALSE(x >= 42);', + 'Consider using EXPECT_LT instead of EXPECT_FALSE(a >= b)' + ' [readability/check] [2]', + ) + self.TestLint( + 'ASSERT_FALSE(x > 42);', + 'Consider using ASSERT_LE instead of ASSERT_FALSE(a > b)' + ' [readability/check] [2]', + ) + self.TestLint( + 'ASSERT_FALSE(x <= 42);', + 'Consider using ASSERT_GT instead of ASSERT_FALSE(a <= b)' + ' [readability/check] [2]', + ) + + self.TestLint( + 'CHECK(x<42);', + [ + 'Missing spaces around < [whitespace/operators] [3]', + 'Consider using CHECK_LT instead of CHECK(a < b) [readability/check] [2]', + ], + ) + self.TestLint( + 'CHECK(x>42);', + [ + 'Missing spaces around > [whitespace/operators] [3]', + 'Consider using CHECK_GT instead of CHECK(a > b) [readability/check] [2]', + ], + ) self.TestLint('using some::namespace::operator<<;', '') self.TestLint('using some::namespace::operator>>;', '') - self.TestLint('CHECK(x->y == 42);', - 'Consider using CHECK_EQ instead of CHECK(a == b)' - ' [readability/check] [2]') + self.TestLint( + 'CHECK(x->y == 42);', + 'Consider using CHECK_EQ instead of CHECK(a == b) [readability/check] [2]', + ) self.TestLint( - ' EXPECT_TRUE(42 < x); // Random comment.', - 'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)' - ' [readability/check] [2]') + ' EXPECT_TRUE(42 < x); // Random comment.', + 'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b) [readability/check] [2]', + ) self.TestLint( - 'EXPECT_TRUE( 42 < x );', - ['Extra space after ( in function call' - ' [whitespace/parens] [4]', - 'Extra space before ) [whitespace/parens] [2]', - 'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)' - ' [readability/check] [2]']) + 'EXPECT_TRUE( 42 < x );', + [ + 'Extra space after ( in function call [whitespace/parens] [4]', + 'Extra space before ) [whitespace/parens] [2]', + 'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)' + ' [readability/check] [2]', + ], + ) - self.TestLint('CHECK(4\'2 == x);', - 'Consider using CHECK_EQ instead of CHECK(a == b)' - ' [readability/check] [2]') + self.TestLint( + 'CHECK(4\'2 == x);', + 'Consider using CHECK_EQ instead of CHECK(a == b) [readability/check] [2]', + ) def testCheckCheckFalsePositives(self): self.TestLint('CHECK(some_iterator == obj.end());', '') @@ -2360,7 +2653,7 @@ def testCheckCheckFalsePositives(self): self.TestLint('SOFT_CHECK(x > 42);', '') self.TestMultiLineLint( - """_STLP_DEFINE_BINARY_OP_CHECK(==, _OP_EQUAL); + """_STLP_DEFINE_BINARY_OP_CHECK(==, _OP_EQUAL); _STLP_DEFINE_BINARY_OP_CHECK(!=, _OP_NOT_EQUAL); _STLP_DEFINE_BINARY_OP_CHECK(<, _OP_LESS_THAN); _STLP_DEFINE_BINARY_OP_CHECK(<=, _OP_LESS_EQUAL); @@ -2371,51 +2664,54 @@ def testCheckCheckFalsePositives(self): _STLP_DEFINE_BINARY_OP_CHECK(/, _OP_DIVIDE); _STLP_DEFINE_BINARY_OP_CHECK(-, _OP_SUBTRACT); _STLP_DEFINE_BINARY_OP_CHECK(%, _OP_MOD);""", - '') + '', + ) self.TestLint('CHECK(x < 42) << "Custom error message";', '') # Alternative token to punctuation operator replacements def testCheckAltTokens(self): - self.TestLint('true or true', - 'Use operator || instead of or' - ' [readability/alt_tokens] [2]') - self.TestLint('true and true', - 'Use operator && instead of and' - ' [readability/alt_tokens] [2]') - self.TestLint('if (not true)', - 'Use operator ! instead of not' - ' [readability/alt_tokens] [2]') - self.TestLint('1 bitor 1', - 'Use operator | instead of bitor' - ' [readability/alt_tokens] [2]') - self.TestLint('1 xor 1', - 'Use operator ^ instead of xor' - ' [readability/alt_tokens] [2]') - self.TestLint('1 bitand 1', - 'Use operator & instead of bitand' - ' [readability/alt_tokens] [2]') - self.TestLint('x = compl 1', - 'Use operator ~ instead of compl' - ' [readability/alt_tokens] [2]') - self.TestLint('x and_eq y', - 'Use operator &= instead of and_eq' - ' [readability/alt_tokens] [2]') - self.TestLint('x or_eq y', - 'Use operator |= instead of or_eq' - ' [readability/alt_tokens] [2]') - self.TestLint('x xor_eq y', - 'Use operator ^= instead of xor_eq' - ' [readability/alt_tokens] [2]') - self.TestLint('x not_eq y', - 'Use operator != instead of not_eq' - ' [readability/alt_tokens] [2]') - self.TestLint('line_continuation or', - 'Use operator || instead of or' - ' [readability/alt_tokens] [2]') - self.TestLint('if(true and(parentheses', - 'Use operator && instead of and' - ' [readability/alt_tokens] [2]') + self.TestLint( + 'true or true', 'Use operator || instead of or [readability/alt_tokens] [2]' + ) + self.TestLint( + 'true and true', 'Use operator && instead of and [readability/alt_tokens] [2]' + ) + self.TestLint( + 'if (not true)', 'Use operator ! instead of not [readability/alt_tokens] [2]' + ) + self.TestLint( + '1 bitor 1', 'Use operator | instead of bitor [readability/alt_tokens] [2]' + ) + self.TestLint( + '1 xor 1', 'Use operator ^ instead of xor [readability/alt_tokens] [2]' + ) + self.TestLint( + '1 bitand 1', 'Use operator & instead of bitand [readability/alt_tokens] [2]' + ) + self.TestLint( + 'x = compl 1', 'Use operator ~ instead of compl [readability/alt_tokens] [2]' + ) + self.TestLint( + 'x and_eq y', 'Use operator &= instead of and_eq [readability/alt_tokens] [2]' + ) + self.TestLint( + 'x or_eq y', 'Use operator |= instead of or_eq [readability/alt_tokens] [2]' + ) + self.TestLint( + 'x xor_eq y', 'Use operator ^= instead of xor_eq [readability/alt_tokens] [2]' + ) + self.TestLint( + 'x not_eq y', 'Use operator != instead of not_eq [readability/alt_tokens] [2]' + ) + self.TestLint( + 'line_continuation or', + 'Use operator || instead of or [readability/alt_tokens] [2]', + ) + self.TestLint( + 'if(true and(parentheses', + 'Use operator && instead of and [readability/alt_tokens] [2]', + ) self.TestLint('#include "base/false-and-false.h"', '') self.TestLint('#error false or false', '') @@ -2425,16 +2721,20 @@ def testCheckAltTokens(self): # Passing and returning non-const references def testNonConstReference(self): # Passing a non-const reference as function parameter is forbidden. - operand_error_message = ('Is this a non-const reference? ' - 'If so, make const or use a pointer: %s' - ' [runtime/references] [2]') + operand_error_message = ( + 'Is this a non-const reference? ' + 'If so, make const or use a pointer: %s' + ' [runtime/references] [2]' + ) # Warn of use of a non-const reference in operators and functions - self.TestLint('bool operator>(Foo& s, Foo& f);', - [operand_error_message % 'Foo& s', - operand_error_message % 'Foo& f']) - self.TestLint('bool operator+(Foo& s, Foo& f);', - [operand_error_message % 'Foo& s', - operand_error_message % 'Foo& f']) + self.TestLint( + 'bool operator>(Foo& s, Foo& f);', + [operand_error_message % 'Foo& s', operand_error_message % 'Foo& f'], + ) + self.TestLint( + 'bool operator+(Foo& s, Foo& f);', + [operand_error_message % 'Foo& s', operand_error_message % 'Foo& f'], + ) self.TestLint('int len(Foo& s);', operand_error_message % 'Foo& s') # Allow use of non-const references in a few specific cases self.TestLint('stream& operator>>(stream& s, Foo& f);', '') @@ -2457,26 +2757,27 @@ def testNonConstReference(self): # Const reference to a templated type is OK. self.TestLint('void foo(const std::vector& v);', '') # Non-const reference to a pointer type is not OK. - self.TestLint('void foo(Bar*& p);', - operand_error_message % 'Bar*& p') - self.TestLint('void foo(const Bar*& p);', - operand_error_message % 'const Bar*& p') - self.TestLint('void foo(Bar const*& p);', - operand_error_message % 'Bar const*& p') - self.TestLint('void foo(struct Bar*& p);', - operand_error_message % 'struct Bar*& p') - self.TestLint('void foo(const struct Bar*& p);', - operand_error_message % 'const struct Bar*& p') - self.TestLint('void foo(struct Bar const*& p);', - operand_error_message % 'struct Bar const*& p') + self.TestLint('void foo(Bar*& p);', operand_error_message % 'Bar*& p') + self.TestLint('void foo(const Bar*& p);', operand_error_message % 'const Bar*& p') + self.TestLint('void foo(Bar const*& p);', operand_error_message % 'Bar const*& p') + self.TestLint('void foo(struct Bar*& p);', operand_error_message % 'struct Bar*& p') + self.TestLint( + 'void foo(const struct Bar*& p);', operand_error_message % 'const struct Bar*& p' + ) + self.TestLint( + 'void foo(struct Bar const*& p);', operand_error_message % 'struct Bar const*& p' + ) # Non-const reference to a templated type is not OK. - self.TestLint('void foo(std::vector& p);', - operand_error_message % 'std::vector& p') + self.TestLint( + 'void foo(std::vector& p);', operand_error_message % 'std::vector& p' + ) # Returning an address of something is not prohibited. self.TestLint('return &something;', '') - self.TestLint('if (condition) {return &something; }', - 'Controlled statements inside brackets of if clause should be on a separate line' - ' [whitespace/newline] [5]') + self.TestLint( + 'if (condition) {return &something; }', + 'Controlled statements inside brackets of if clause should be on a separate line' + ' [whitespace/newline] [5]', + ) self.TestLint('if (condition) return &something;', '') self.TestLint('if (condition) address = &something;', '') self.TestLint('if (condition) result = lhs&rhs;', '') @@ -2496,9 +2797,10 @@ def testNonConstReference(self): self.TestLint('COMPILE_ASSERT((kBits & kMask) == 0, text);', '') # Spaces before template arguments. This is poor style, but # happens 0.15% of the time. - self.TestLint('void Func(const vector &const_x, ' - 'vector &nonconst_x) {', - operand_error_message % 'vector &nonconst_x') + self.TestLint( + 'void Func(const vector &const_x, vector &nonconst_x) {', + operand_error_message % 'vector &nonconst_x', + ) # Derived member functions are spared from override check self.TestLint('void Func(X& x);', operand_error_message % 'X& x') @@ -2512,156 +2814,191 @@ def testNonConstReference(self): self.TestLint('void NS::Func(X& x) {', '') error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company. All Rights Reserved.', - 'void a::b() {}', - 'void f(int& q) {}', - ''], - error_collector) - self.assertEqual( - operand_error_message % 'int& q', - error_collector.Results()) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company. All Rights Reserved.', + 'void a::b() {}', + 'void f(int& q) {}', + '', + ], + error_collector, + ) + self.assertEqual(operand_error_message % 'int& q', error_collector.Results()) # Other potential false positives. These need full parser # state to reproduce as opposed to just TestLint. error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company. All Rights Reserved.', - '#include ', - '#include ', - 'void swap(int &x,', - ' int &y) {', - '}', - 'void swap(', - ' sparsegroup &x,', - ' sparsegroup &y) {', - '}', - 'ostream& operator<<(', - ' ostream& out', - ' const dense_hash_set& seq) {', - '}', - 'class A {', - ' void Function(', - ' string &x) override {', - ' }', - '};', - 'void Derived::Function(', - ' string &x) {', - '}', - '#define UNSUPPORTED_MASK(_mask) \\', - ' if (flags & _mask) { \\', - ' LOG(FATAL) << "Unsupported flag: " << #_mask; \\', - ' }', - 'Constructor::Constructor()', - ' : initializer1_(a1 & b1),', - ' initializer2_(a2 & b2) {', - '}', - 'Constructor::Constructor()', - ' : initializer1_{a3 & b3},', - ' initializer2_(a4 & b4) {', - '}', - 'Constructor::Constructor()', - ' : initializer1_{a5 & b5},', - ' initializer2_(a6 & b6) {}', - ''], - error_collector) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company. All Rights Reserved.', + '#include ', + '#include ', + 'void swap(int &x,', + ' int &y) {', + '}', + 'void swap(', + ' sparsegroup &x,', + ' sparsegroup &y) {', + '}', + 'ostream& operator<<(', + ' ostream& out', + ' const dense_hash_set& seq) {', + '}', + 'class A {', + ' void Function(', + ' string &x) override {', + ' }', + '};', + 'void Derived::Function(', + ' string &x) {', + '}', + '#define UNSUPPORTED_MASK(_mask) \\', + ' if (flags & _mask) { \\', + ' LOG(FATAL) << "Unsupported flag: " << #_mask; \\', + ' }', + 'Constructor::Constructor()', + ' : initializer1_(a1 & b1),', + ' initializer2_(a2 & b2) {', + '}', + 'Constructor::Constructor()', + ' : initializer1_{a3 & b3},', + ' initializer2_(a4 & b4) {', + '}', + 'Constructor::Constructor()', + ' : initializer1_{a5 & b5},', + ' initializer2_(a6 & b6) {}', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) # Multi-line references error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company. All Rights Reserved.', - 'void Func(const Outer::', - ' Inner& const_x,', - ' const Outer', - ' ::Inner& const_y,', - ' const Outer<', - ' int>::Inner& const_z,', - ' Outer::', - ' Inner& nonconst_x,', - ' Outer', - ' ::Inner& nonconst_y,', - ' Outer<', - ' int>::Inner& nonconst_z) {', - '}', - ''], - error_collector) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company. All Rights Reserved.', + 'void Func(const Outer::', + ' Inner& const_x,', + ' const Outer', + ' ::Inner& const_y,', + ' const Outer<', + ' int>::Inner& const_z,', + ' Outer::', + ' Inner& nonconst_x,', + ' Outer', + ' ::Inner& nonconst_y,', + ' Outer<', + ' int>::Inner& nonconst_z) {', + '}', + '', + ], + error_collector, + ) self.assertEqual( - [operand_error_message % 'Outer::Inner& nonconst_x', - operand_error_message % 'Outer::Inner& nonconst_y', - operand_error_message % 'Outer::Inner& nonconst_z'], - error_collector.Results()) + [ + operand_error_message % 'Outer::Inner& nonconst_x', + operand_error_message % 'Outer::Inner& nonconst_y', + operand_error_message % 'Outer::Inner& nonconst_z', + ], + error_collector.Results(), + ) # A peculiar false positive due to bad template argument parsing error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company. All Rights Reserved.', - 'inline RCULocked::ReadPtr::ReadPtr(const RCULocked* rcu) {', - ' DCHECK(!(data & kFlagMask)) << "Error";', - '}', - '', - 'RCULocked::WritePtr::WritePtr(RCULocked* rcu)', - ' : lock_(&rcu_->mutex_) {', - '}', - ''], - error_collector.Results()) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company. All Rights Reserved.', + 'inline RCULocked::ReadPtr::ReadPtr(const RCULocked* rcu) {', + ' DCHECK(!(data & kFlagMask)) << "Error";', + '}', + '', + 'RCULocked::WritePtr::WritePtr(RCULocked* rcu)', + ' : lock_(&rcu_->mutex_) {', + '}', + '', + ], + error_collector.Results(), + ) self.assertEqual('', error_collector.Results()) def testBraceAtBeginOfLine(self): - self.TestLint('{', - '{ should almost always be at the end of the previous line' - ' [whitespace/braces] [4]') + self.TestLint( + '{', + '{ should almost always be at the end of the previous line' + ' [whitespace/braces] [4]', + ) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['int function()', - '{', # warning here - ' MutexLock l(&mu);', - '}', - 'int variable;' - '{', # no warning - ' MutexLock l(&mu);', - '}', - 'MyType m = {', - ' {value1, value2},', - ' {', # no warning - ' loooong_value1, looooong_value2', - ' }', - '};', - '#if PREPROCESSOR', - '{', # no warning - ' MutexLock l(&mu);', - '}', - '#endif'], - error_collector) - self.assertEqual(1, error_collector.Results().count( + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'int function()', + '{', # warning here + ' MutexLock l(&mu);', + '}', + 'int variable;{', # no warning + ' MutexLock l(&mu);', + '}', + 'MyType m = {', + ' {value1, value2},', + ' {', # no warning + ' loooong_value1, looooong_value2', + ' }', + '};', + '#if PREPROCESSOR', + '{', # no warning + ' MutexLock l(&mu);', + '}', + '#endif', + ], + error_collector, + ) + self.assertEqual( + 1, + error_collector.Results().count( '{ should almost always be at the end of the previous line' - ' [whitespace/braces] [4]')) + ' [whitespace/braces] [4]' + ), + ) self.TestMultiLineLint( - """ + """ foo( { loooooooooooooooong_value, });""", - '') + '', + ) def testMismatchingSpacesInParens(self): - self.TestLint('if (foo ) {', 'Mismatching spaces inside () in if' - ' [whitespace/parens] [5]') - self.TestLint('switch ( foo) {', 'Mismatching spaces inside () in switch' - ' [whitespace/parens] [5]') - self.TestLint('for (foo; ba; bar ) {', 'Mismatching spaces inside () in for' - ' [whitespace/parens] [5]') + self.TestLint( + 'if (foo ) {', 'Mismatching spaces inside () in if [whitespace/parens] [5]' + ) + self.TestLint( + 'switch ( foo) {', + 'Mismatching spaces inside () in switch [whitespace/parens] [5]', + ) + self.TestLint( + 'for (foo; ba; bar ) {', + 'Mismatching spaces inside () in for [whitespace/parens] [5]', + ) self.TestLint('for (; foo; bar) {', '') self.TestLint('for ( ; foo; bar) {', '') self.TestLint('for ( ; foo; bar ) {', '') self.TestLint('for (foo; bar; ) {', '') - self.TestLint('while ( foo ) {', 'Should have zero or one spaces inside' - ' ( and ) in while [whitespace/parens] [5]') + self.TestLint( + 'while ( foo ) {', + 'Should have zero or one spaces inside ( and ) in while [whitespace/parens] [5]', + ) def testSpacingForFncall(self): self.TestLint('if (foo) {', '') @@ -2671,32 +3008,40 @@ def testSpacingForFncall(self): self.TestLint('Something* p = new (place) Something();', '') # Test that there is no warning when increment statement is empty. self.TestLint('for (foo; baz;) {', '') - self.TestLint('for (foo;bar;baz) {', 'Missing space after ;' - ' [whitespace/semicolon] [3]') + self.TestLint( + 'for (foo;bar;baz) {', 'Missing space after ; [whitespace/semicolon] [3]' + ) # we don't warn about this semicolon, at least for now - self.TestLintNotContains('if (condition) { return &something; }', - 'Missing space after ; [whitespace/semicolon] [3]') + self.TestLintNotContains( + 'if (condition) { return &something; }', + 'Missing space after ; [whitespace/semicolon] [3]', + ) # seen in some macros self.TestLint('DoSth();\\', '') # Test that there is no warning about semicolon here. - self.TestLint('abc;// this is abc', - 'At least two spaces is best between code' - ' and comments [whitespace/comments] [2]') + self.TestLint( + 'abc;// this is abc', + 'At least two spaces is best between code' + ' and comments [whitespace/comments] [2]', + ) self.TestLint('while (foo) {', '') self.TestLint('switch (foo) {', '') - self.TestLint('foo( bar)', 'Extra space after ( in function call' - ' [whitespace/parens] [4]') + self.TestLint( + 'foo( bar)', 'Extra space after ( in function call [whitespace/parens] [4]' + ) self.TestLint('foo( // comment', '') - self.TestLint('foo( // comment', - 'At least two spaces is best between code' - ' and comments [whitespace/comments] [2]') + self.TestLint( + 'foo( // comment', + 'At least two spaces is best between code' + ' and comments [whitespace/comments] [2]', + ) self.TestLint('foobar( \\', '') self.TestLint('foobar( \\', '') - self.TestLint('( a + b)', 'Extra space after (' - ' [whitespace/parens] [2]') + self.TestLint('( a + b)', 'Extra space after ( [whitespace/parens] [2]') self.TestLint('((a+b))', '') - self.TestLint('foo (foo)', 'Extra space before ( in function call' - ' [whitespace/parens] [4]') + self.TestLint( + 'foo (foo)', 'Extra space before ( in function call [whitespace/parens] [4]' + ) # asm volatile () may have a space, as it isn't a function call. self.TestLint('asm volatile ("")', '') self.TestLint('__asm__ __volatile__ ("")', '') @@ -2710,9 +3055,10 @@ def testSpacingForFncall(self): self.TestLint('using foo = type (Foo::*)(', '') self.TestLint('foo (Foo::*bar)(', '') self.TestLint('foo (x::y::*z)(', '') - self.TestLint('foo (Foo::bar)(', - 'Extra space before ( in function call' - ' [whitespace/parens] [4]') + self.TestLint( + 'foo (Foo::bar)(', + 'Extra space before ( in function call [whitespace/parens] [4]', + ) self.TestLint('foo (*bar)(', '') self.TestLint('typedef foo (Foo::*bar)(', '') self.TestLint('(foo)(bar)', '') @@ -2734,19 +3080,23 @@ def testReplaceAlternateTokens(self): assert cpplint.ReplaceAlternateTokens('orc or tor') == 'orc || tor' assert cpplint.ReplaceAlternateTokens('tor or (orc)') == 'tor || (orc)' assert cpplint.ReplaceAlternateTokens('tor or(orc)') == 'tor ||(orc)' - assert cpplint.ReplaceAlternateTokens('sand and(android)') == \ - 'sand &&(android)' - assert cpplint.ReplaceAlternateTokens('(sand) and (android)') == \ - '(sand) && (android)' + assert cpplint.ReplaceAlternateTokens('sand and(android)') == 'sand &&(android)' + assert ( + cpplint.ReplaceAlternateTokens('(sand) and (android)') == '(sand) && (android)' + ) assert cpplint.ReplaceAlternateTokens(' not note') == ' !note' assert cpplint.ReplaceAlternateTokens(')not note') == ')!note' assert cpplint.ReplaceAlternateTokens('(not note') == '(!note' assert cpplint.ReplaceAlternateTokens(' not(note)') == ' !(note)' assert cpplint.ReplaceAlternateTokens(' not (splinot)') == ' !(splinot)' - assert cpplint.ReplaceAlternateTokens('tor and orc or android') == \ - 'tor && orc || android' - assert cpplint.ReplaceAlternateTokens('tor or orc and ands not note') == \ - 'tor || orc && ands !note' + assert ( + cpplint.ReplaceAlternateTokens('tor and orc or android') + == 'tor && orc || android' + ) + assert ( + cpplint.ReplaceAlternateTokens('tor or orc and ands not note') + == 'tor || orc && ands !note' + ) def testSpacingAfterAlternateToken(self): try: @@ -2757,45 +3107,48 @@ def testSpacingAfterAlternateToken(self): self.TestLint('if (not foo) {', '') self.TestLint('if (not (foo)) {', '') self.TestLint('if (not(foo)) {', '') - self.TestLint('if ((foo)or(bar)) {', 'Missing spaces around ||' - ' [whitespace/operators] [3]') + self.TestLint( + 'if ((foo)or(bar)) {', 'Missing spaces around || [whitespace/operators] [3]' + ) finally: cpplint._cpplint_state.SetFilters('') def testSpacingBeforeBraces(self): - self.TestLint('if (foo){', 'Missing space before {' - ' [whitespace/braces] [5]') - self.TestLint('for{', 'Missing space before {' - ' [whitespace/braces] [5]') + self.TestLint('if (foo){', 'Missing space before { [whitespace/braces] [5]') + self.TestLint('for{', 'Missing space before { [whitespace/braces] [5]') self.TestLint('for {', '') self.TestLint('EXPECT_DEBUG_DEATH({', '') self.TestLint('std::is_convertible{}', '') - self.TestLint('blah{32}', 'Missing space before {' - ' [whitespace/braces] [5]') + self.TestLint('blah{32}', 'Missing space before { [whitespace/braces] [5]') self.TestLint('int8_t{3}', '') self.TestLint('int16_t{3}', '') self.TestLint('int32_t{3}', '') self.TestLint('uint64_t{12345}', '') - self.TestLint('constexpr int64_t kBatchGapMicros =' - ' int64_t{7} * 24 * 3600 * 1000000; // 1 wk.', '') - self.TestLint('MoveOnly(int i1, int i2) : ip1{new int{i1}}, ' - 'ip2{new int{i2}} {}', - '') + self.TestLint( + 'constexpr int64_t kBatchGapMicros = int64_t{7} * 24 * 3600 * 1000000; // 1 wk.', + '', + ) + self.TestLint( + 'MoveOnly(int i1, int i2) : ip1{new int{i1}}, ip2{new int{i2}} {}', '' + ) def testSemiColonAfterBraces(self): - self.TestLintContains('if (cond) { func(); };', - 'You don\'t need a ; after a } [readability/braces] [4]') - self.TestLint('void Func() {};', - 'You don\'t need a ; after a } [readability/braces] [4]') - self.TestLint('void Func() const {};', - 'You don\'t need a ; after a } [readability/braces] [4]') + self.TestLintContains( + 'if (cond) { func(); };', + 'You don\'t need a ; after a } [readability/braces] [4]', + ) + self.TestLint( + 'void Func() {};', 'You don\'t need a ; after a } [readability/braces] [4]' + ) + self.TestLint( + 'void Func() const {};', 'You don\'t need a ; after a } [readability/braces] [4]' + ) self.TestLint('class X {};', '') for keyword in ['struct', 'union']: for align in ['', ' alignas(16)']: for typename in ['', ' X']: for identifier in ['', ' x']: - self.TestLint(keyword + align + typename + ' {}' + identifier + ';', - '') + self.TestLint(keyword + align + typename + ' {}' + identifier + ';', '') self.TestLint('class X : public Y {};', '') self.TestLint('class X : public MACRO() {};', '') @@ -2804,32 +3157,41 @@ def testSemiColonAfterBraces(self): self.TestLint('VCLASS(XfaTest, XfaContextTest) {};', '') self.TestLint('class STUBBY_CLASS(H, E) {};', '') self.TestLint('class STUBBY2_CLASS(H, E) {};', '') - self.TestLint('TEST(TestCase, TestName) {};', - 'You don\'t need a ; after a } [readability/braces] [4]') - self.TestLint('TEST_F(TestCase, TestName) {};', - 'You don\'t need a ; after a } [readability/braces] [4]') + self.TestLint( + 'TEST(TestCase, TestName) {};', + 'You don\'t need a ; after a } [readability/braces] [4]', + ) + self.TestLint( + 'TEST_F(TestCase, TestName) {};', + 'You don\'t need a ; after a } [readability/braces] [4]', + ) self.TestLint('file_tocs_[i] = (FileToc) {a, b, c};', '') self.TestMultiLineLint('class X : public Y,\npublic Z {};', '') - self.TestMultiLineLint('template\n' - 'concept Addable = requires(T x) { x + x; };', - '') - self.TestMultiLineLint('template \n' - 'concept C = requires(T a, T b) {\n' - ' requires a == b;\n' - '};', - '') - self.TestMultiLineLint('template \n' - 'concept C = (std::integral || std::floating_point) &&\n' - ' (std::integral || std::floating_point) &&\n' - ' requires(T t, U u) {\n' - ' std::min(static_cast(t), static_cast(u));\n' - '};', - '') + self.TestMultiLineLint( + 'template\nconcept Addable = requires(T x) { x + x; };', '' + ) + self.TestMultiLineLint( + 'template \n' + 'concept C = requires(T a, T b) {\n' + ' requires a == b;\n' + '};', + '', + ) + self.TestMultiLineLint( + 'template \n' + 'concept C = (std::integral || std::floating_point) &&\n' + ' (std::integral || std::floating_point) &&\n' + ' requires(T t, U u) {\n' + ' std::min(static_cast(t), static_cast(u));\n' + '};', + '', + ) def testSpacingBeforeBrackets(self): - self.TestLint('int numbers [] = { 1, 2, 3 };', - 'Extra space before [ [whitespace/braces] [5]') + self.TestLint( + 'int numbers [] = { 1, 2, 3 };', 'Extra space before [ [whitespace/braces] [5]' + ) # space allowed in some cases self.TestLint('auto [abc, def] = func();', '') self.TestLint('#define NODISCARD [[nodiscard]]', '') @@ -2839,19 +3201,23 @@ def testLambda(self): self.TestLint('auto x = []() {};', '') self.TestLint('return []() {};', '') self.TestMultiLineLint('auto x = []() {\n};\n', '') - self.TestLint('int operator[](int x) {};', - 'You don\'t need a ; after a } [readability/braces] [4]') + self.TestLint( + 'int operator[](int x) {};', + 'You don\'t need a ; after a } [readability/braces] [4]', + ) self.TestMultiLineLint('auto x = [&a,\nb]() {};', '') self.TestMultiLineLint('auto x = [&a,\nb]\n() {};', '') - self.TestMultiLineLint('auto x = [&a,\n' - ' b](\n' - ' int a,\n' - ' int b) {\n' - ' return a +\n' - ' b;\n' - '};\n', - '') + self.TestMultiLineLint( + 'auto x = [&a,\n' + ' b](\n' + ' int a,\n' + ' int b) {\n' + ' return a +\n' + ' b;\n' + '};\n', + '', + ) # Avoid false positives with operator[] self.TestLint('table_to_children[&*table].push_back(dependent);', '') @@ -2878,45 +3244,40 @@ def testBraceInitializerList(self): self.TestLint('ItemView{has_offer() ? new Offer{offer()} : nullptr', '') self.TestLint('template {}> = 0>', '') - self.TestMultiLineLint('std::unique_ptr foo{\n' - ' new Foo{}\n' - '};\n', '') - self.TestMultiLineLint('std::unique_ptr foo{\n' - ' new Foo{\n' - ' new Bar{}\n' - ' }\n' - '};\n', '') - self.TestMultiLineLint('if (true) {\n' - ' if (false){\n' - ' func();\n' - ' }' - '}\n', - 'Missing space before { [whitespace/braces] [5]') - self.TestMultiLineLint('MyClass::MyClass()\n' - ' : initializer_{\n' - ' Func()} {\n' - '}\n', '') - self.TestLint('const pair kCL' + - ('o' * 41) + 'gStr[] = {\n', - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') - self.TestMultiLineLint('const pair kCL' + - ('o' * 40) + 'ngStr[] =\n' - ' {\n' - ' {"gooooo", "oooogle"},\n' - '};\n', '') - self.TestMultiLineLint('const pair kCL' + - ('o' * 39) + 'ngStr[] =\n' - ' {\n' - ' {"gooooo", "oooogle"},\n' - '};\n', '{ should almost always be at the end of ' - 'the previous line [whitespace/braces] [4]') + self.TestMultiLineLint('std::unique_ptr foo{\n new Foo{}\n};\n', '') + self.TestMultiLineLint( + 'std::unique_ptr foo{\n new Foo{\n new Bar{}\n }\n};\n', '' + ) + self.TestMultiLineLint( + 'if (true) {\n if (false){\n func();\n }}\n', + 'Missing space before { [whitespace/braces] [5]', + ) + self.TestMultiLineLint( + 'MyClass::MyClass()\n : initializer_{\n Func()} {\n}\n', '' + ) + self.TestLint( + 'const pair kCL' + ('o' * 41) + 'gStr[] = {\n', + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) + self.TestMultiLineLint( + 'const pair kCL' + ('o' * 40) + 'ngStr[] =\n' + ' {\n' + ' {"gooooo", "oooogle"},\n' + '};\n', + '', + ) + self.TestMultiLineLint( + 'const pair kCL' + ('o' * 39) + 'ngStr[] =\n' + ' {\n' + ' {"gooooo", "oooogle"},\n' + '};\n', + '{ should almost always be at the end of ' + 'the previous line [whitespace/braces] [4]', + ) def testSpacingAroundElse(self): - self.TestLint('}else {', 'Missing space before else' - ' [whitespace/braces] [5]') - self.TestLint('} else{', 'Missing space before {' - ' [whitespace/braces] [5]') + self.TestLint('}else {', 'Missing space before else [whitespace/braces] [5]') + self.TestLint('} else{', 'Missing space before { [whitespace/braces] [5]') self.TestLint('} else {', '') self.TestLint('} else if (foo) {', '') @@ -2925,38 +3286,41 @@ def testSpacingWithInitializerLists(self): self.TestLint('int v[1][1] = {{0}};', '') def testSpacingForBinaryOps(self): - self.TestLint('if (foo||bar) {', 'Missing spaces around ||' - ' [whitespace/operators] [3]') - self.TestLint('if (foo<=bar) {', 'Missing spaces around <=' - ' [whitespace/operators] [3]') - self.TestLint('if (foobar) {', 'Missing spaces around >' - ' [whitespace/operators] [3]') - self.TestLint('if (foobaz) {', 'Missing spaces around <' - ' [whitespace/operators] [3]') - self.TestLint('if (foobar) {', 'Missing spaces around <' - ' [whitespace/operators] [3]') + self.TestLint( + 'if (foo||bar) {', 'Missing spaces around || [whitespace/operators] [3]' + ) + self.TestLint( + 'if (foo<=bar) {', 'Missing spaces around <= [whitespace/operators] [3]' + ) + self.TestLint( + 'if (foobar) {', 'Missing spaces around > [whitespace/operators] [3]' + ) + self.TestLint( + 'if (foobaz) {', 'Missing spaces around < [whitespace/operators] [3]' + ) + self.TestLint( + 'if (foobar) {', 'Missing spaces around < [whitespace/operators] [3]' + ) self.TestLint('template', '') self.TestLint('std::unique_ptr>', '') self.TestLint('typedef hash_map', '') self.TestLint('10<<20', '') - self.TestLint('10<>b', - 'Missing spaces around >> [whitespace/operators] [3]') - self.TestLint('10>>b', - 'Missing spaces around >> [whitespace/operators] [3]') - self.TestLint('LOG(ERROR)<<*foo', - 'Missing spaces around << [whitespace/operators] [3]') - self.TestLint('LOG(ERROR)<<&foo', - 'Missing spaces around << [whitespace/operators] [3]') + self.TestLint('a>>b', 'Missing spaces around >> [whitespace/operators] [3]') + self.TestLint('10>>b', 'Missing spaces around >> [whitespace/operators] [3]') + self.TestLint( + 'LOG(ERROR)<<*foo', 'Missing spaces around << [whitespace/operators] [3]' + ) + self.TestLint( + 'LOG(ERROR)<<&foo', 'Missing spaces around << [whitespace/operators] [3]' + ) self.TestLint('StringCoder>::ToString()', '') self.TestLint('map, map>::iterator', '') self.TestLint('func>>()', '') @@ -2975,164 +3339,201 @@ def testSpacingForBinaryOps(self): self.TestLint('using Vector3::operator!=;', '') def testSpacingBeforeLastSemicolon(self): - self.TestLint('call_function() ;', - 'Extra space before last semicolon. If this should be an ' - 'empty statement, use {} instead.' - ' [whitespace/semicolon] [5]') - self.TestLint('while (true) ;', - 'Extra space before last semicolon. If this should be an ' - 'empty statement, use {} instead.' - ' [whitespace/semicolon] [5]') - self.TestLint('default:;', - 'Semicolon defining empty statement. Use {} instead.' - ' [whitespace/semicolon] [5]') - self.TestLint(' ;', - 'Line contains only semicolon. If this should be an empty ' - 'statement, use {} instead.' - ' [whitespace/semicolon] [5]') + self.TestLint( + 'call_function() ;', + 'Extra space before last semicolon. If this should be an ' + 'empty statement, use {} instead.' + ' [whitespace/semicolon] [5]', + ) + self.TestLint( + 'while (true) ;', + 'Extra space before last semicolon. If this should be an ' + 'empty statement, use {} instead.' + ' [whitespace/semicolon] [5]', + ) + self.TestLint( + 'default:;', + 'Semicolon defining empty statement. Use {} instead. [whitespace/semicolon] [5]', + ) + self.TestLint( + ' ;', + 'Line contains only semicolon. If this should be an empty ' + 'statement, use {} instead.' + ' [whitespace/semicolon] [5]', + ) self.TestLint('for (int i = 0; ;', '') def testEmptyBlockBody(self): - self.TestLint('while (true);', - 'Empty loop bodies should use {} or continue' - ' [whitespace/empty_loop_body] [5]') - self.TestLint('if (true);', - 'Empty conditional bodies should use {}' - ' [whitespace/empty_conditional_body] [5]') + self.TestLint( + 'while (true);', + 'Empty loop bodies should use {} or continue [whitespace/empty_loop_body] [5]', + ) + self.TestLint( + 'if (true);', + 'Empty conditional bodies should use {} [whitespace/empty_conditional_body] [5]', + ) self.TestLint('while (true)', '') self.TestLint('while (true) continue;', '') - self.TestLint('for (;;);', - 'Empty loop bodies should use {} or continue' - ' [whitespace/empty_loop_body] [5]') + self.TestLint( + 'for (;;);', + 'Empty loop bodies should use {} or continue [whitespace/empty_loop_body] [5]', + ) self.TestLint('for (;;)', '') self.TestLint('for (;;) continue;', '') self.TestLint('for (;;) func();', '') - self.TestLint('if (test) {}', - 'If statement had no body and no else clause' - ' [whitespace/empty_if_body] [4]') + self.TestLint( + 'if (test) {}', + 'If statement had no body and no else clause [whitespace/empty_if_body] [4]', + ) self.TestLint('if (test) func();', '') self.TestLint('if (test) {} else {}', '') - self.TestMultiLineLint("""while (true && + self.TestMultiLineLint( + """while (true && false);""", - 'Empty loop bodies should use {} or continue' - ' [whitespace/empty_loop_body] [5]') - self.TestMultiLineLint("""do { + 'Empty loop bodies should use {} or continue [whitespace/empty_loop_body] [5]', + ) + self.TestMultiLineLint( + """do { } while (false);""", - '') - self.TestMultiLineLint("""#define MACRO \\ + '', + ) + self.TestMultiLineLint( + """#define MACRO \\ do { \\ } while (false);""", - '') - self.TestMultiLineLint("""do { + '', + ) + self.TestMultiLineLint( + """do { } while (false); // next line gets a warning while (false);""", - 'Empty loop bodies should use {} or continue' - ' [whitespace/empty_loop_body] [5]') - self.TestMultiLineLint("""if (test) { + 'Empty loop bodies should use {} or continue [whitespace/empty_loop_body] [5]', + ) + self.TestMultiLineLint( + """if (test) { }""", - 'If statement had no body and no else clause' - ' [whitespace/empty_if_body] [4]') - self.TestMultiLineLint("""if (test, + 'If statement had no body and no else clause [whitespace/empty_if_body] [4]', + ) + self.TestMultiLineLint( + """if (test, func({})) { }""", - 'If statement had no body and no else clause' - ' [whitespace/empty_if_body] [4]') - self.TestMultiLineLint("""if (test) - func();""", '') - self.TestLint('if (test) { hello; }', - 'Controlled statements inside brackets of if clause should be on a separate line' - ' [whitespace/newline] [5]') - self.TestLint('if (test({})) { hello; }', - 'Controlled statements inside brackets of if clause should be on a separate line' - ' [whitespace/newline] [5]') - self.TestMultiLineLint("""if (test) { + 'If statement had no body and no else clause [whitespace/empty_if_body] [4]', + ) + self.TestMultiLineLint( + """if (test) + func();""", + '', + ) + self.TestLint( + 'if (test) { hello; }', + 'Controlled statements inside brackets of if clause should be on a separate line' + ' [whitespace/newline] [5]', + ) + self.TestLint( + 'if (test({})) { hello; }', + 'Controlled statements inside brackets of if clause should be on a separate line' + ' [whitespace/newline] [5]', + ) + self.TestMultiLineLint( + """if (test) { func(); - }""", '') - self.TestMultiLineLint("""if (test) { + }""", + '', + ) + self.TestMultiLineLint( + """if (test) { // multiline // comment - }""", '') - self.TestMultiLineLint("""if (test) { // comment - }""", '') - self.TestMultiLineLint("""if (test) { + }""", + '', + ) + self.TestMultiLineLint( + """if (test) { // comment + }""", + '', + ) + self.TestMultiLineLint( + """if (test) { } else { - }""", '') - self.TestMultiLineLint("""if (func(p1, + }""", + '', + ) + self.TestMultiLineLint( + """if (func(p1, p2, p3)) { func(); - }""", '') - self.TestMultiLineLint("""if (func({}, p1)) { + }""", + '', + ) + self.TestMultiLineLint( + """if (func({}, p1)) { func(); - }""", '') + }""", + '', + ) def testSpacingForRangeBasedFor(self): # Basic correctly formatted case: self.TestLint('for (int i : numbers) {', '') # Missing space before colon: - self.TestLint('for (int i: numbers) {', - 'Missing space around colon in range-based for loop' - ' [whitespace/forcolon] [2]') + self.TestLint( + 'for (int i: numbers) {', + 'Missing space around colon in range-based for loop [whitespace/forcolon] [2]', + ) # Missing space after colon: - self.TestLint('for (int i :numbers) {', - 'Missing space around colon in range-based for loop' - ' [whitespace/forcolon] [2]') + self.TestLint( + 'for (int i :numbers) {', + 'Missing space around colon in range-based for loop [whitespace/forcolon] [2]', + ) # Missing spaces both before and after the colon. - self.TestLint('for (int i:numbers) {', - 'Missing space around colon in range-based for loop' - ' [whitespace/forcolon] [2]') + self.TestLint( + 'for (int i:numbers) {', + 'Missing space around colon in range-based for loop [whitespace/forcolon] [2]', + ) # The scope operator '::' shouldn't cause warnings... self.TestLint('for (std::size_t i : sizes) {}', '') # ...but it shouldn't suppress them either. - self.TestLint('for (std::size_t i: sizes) {}', - 'Missing space around colon in range-based for loop' - ' [whitespace/forcolon] [2]') + self.TestLint( + 'for (std::size_t i: sizes) {}', + 'Missing space around colon in range-based for loop [whitespace/forcolon] [2]', + ) # Static or global STL strings. def testStaticOrGlobalSTLStrings(self): # A template for the error message for a const global/static string. - error_msg = ('For a static/global string constant, use a C style ' - 'string instead: "%s[]". [runtime/string] [4]') + error_msg = ( + 'For a static/global string constant, use a C style ' + 'string instead: "%s[]". [runtime/string] [4]' + ) # The error message for a non-const global/static string variable. - nonconst_error_msg = ('Static/global string variables are not permitted.' - ' [runtime/string] [4]') - - self.TestLint('string foo;', - nonconst_error_msg) - self.TestLint('string kFoo = "hello"; // English', - nonconst_error_msg) - self.TestLint('static string foo;', - nonconst_error_msg) - self.TestLint('static const string foo;', - error_msg % 'static const char foo') - self.TestLint('static const std::string foo;', - error_msg % 'static const char foo') - self.TestLint('string Foo::bar;', - nonconst_error_msg) - - self.TestLint('std::string foo;', - nonconst_error_msg) - self.TestLint('std::string kFoo = "hello"; // English', - nonconst_error_msg) - self.TestLint('static std::string foo;', - nonconst_error_msg) - self.TestLint('static const std::string foo;', - error_msg % 'static const char foo') - self.TestLint('std::string Foo::bar;', - nonconst_error_msg) - - self.TestLint('::std::string foo;', - nonconst_error_msg) - self.TestLint('::std::string kFoo = "hello"; // English', - nonconst_error_msg) - self.TestLint('static ::std::string foo;', - nonconst_error_msg) - self.TestLint('static const ::std::string foo;', - error_msg % 'static const char foo') - self.TestLint('::std::string Foo::bar;', - nonconst_error_msg) + nonconst_error_msg = ( + 'Static/global string variables are not permitted. [runtime/string] [4]' + ) + + self.TestLint('string foo;', nonconst_error_msg) + self.TestLint('string kFoo = "hello"; // English', nonconst_error_msg) + self.TestLint('static string foo;', nonconst_error_msg) + self.TestLint('static const string foo;', error_msg % 'static const char foo') + self.TestLint('static const std::string foo;', error_msg % 'static const char foo') + self.TestLint('string Foo::bar;', nonconst_error_msg) + + self.TestLint('std::string foo;', nonconst_error_msg) + self.TestLint('std::string kFoo = "hello"; // English', nonconst_error_msg) + self.TestLint('static std::string foo;', nonconst_error_msg) + self.TestLint('static const std::string foo;', error_msg % 'static const char foo') + self.TestLint('std::string Foo::bar;', nonconst_error_msg) + + self.TestLint('::std::string foo;', nonconst_error_msg) + self.TestLint('::std::string kFoo = "hello"; // English', nonconst_error_msg) + self.TestLint('static ::std::string foo;', nonconst_error_msg) + self.TestLint( + 'static const ::std::string foo;', error_msg % 'static const char foo' + ) + self.TestLint('::std::string Foo::bar;', nonconst_error_msg) self.TestLint('string* pointer', '') self.TestLint('string *pointer', '') @@ -3161,150 +3562,173 @@ def testStaticOrGlobalSTLStrings(self): self.TestLint('string EmptyString () { return ""; }', '') self.TestLint('string const& FileInfo::Pathname() const;', '') self.TestLint('string const &FileInfo::Pathname() const;', '') - self.TestLint('string VeryLongNameFunctionSometimesEndsWith(\n' - ' VeryLongNameType very_long_name_variable) {}', '') - self.TestLint('template<>\n' - 'string FunctionTemplateSpecialization(\n' - ' int x) { return ""; }', '') - self.TestLint('template<>\n' - 'string FunctionTemplateSpecialization* >(\n' - ' int x) { return ""; }', '') + self.TestLint( + 'string VeryLongNameFunctionSometimesEndsWith(\n' + ' VeryLongNameType very_long_name_variable) {}', + '', + ) + self.TestLint( + 'template<>\n' + 'string FunctionTemplateSpecialization(\n' + ' int x) { return ""; }', + '', + ) + self.TestLint( + 'template<>\n' + 'string FunctionTemplateSpecialization* >(\n' + ' int x) { return ""; }', + '', + ) # should not catch methods of template classes. - self.TestLint('string Class::Method() const {\n' - ' return "";\n' - '}\n', '') - self.TestLint('string Class::Method(\n' - ' int arg) const {\n' - ' return "";\n' - '}\n', '') + self.TestLint('string Class::Method() const {\n return "";\n}\n', '') + self.TestLint( + 'string Class::Method(\n int arg) const {\n return "";\n}\n', '' + ) # Check multiline cases. error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['// Copyright 2014 Your Company.', - '#include ', - 'string Class', - '::MemberFunction1();', - 'string Class::', - 'MemberFunction2();', - 'string Class::', - 'NestedClass::MemberFunction3();', - 'string TemplateClass::', - 'NestedClass::MemberFunction4();', - 'const string Class', - '::static_member_variable1;', - 'const string Class::', - 'static_member_variable2;', - 'const string Class', - '::static_member_variable3 = "initial value";', - 'const string Class::', - 'static_member_variable4 = "initial value";', - 'string Class::', - 'static_member_variable5;', - ''], - error_collector) - self.assertEqual(error_collector.Results(), - [error_msg % 'const char Class::static_member_variable1', - error_msg % 'const char Class::static_member_variable2', - error_msg % 'const char Class::static_member_variable3', - error_msg % 'const char Class::static_member_variable4', - nonconst_error_msg]) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '#include ', + 'string Class', + '::MemberFunction1();', + 'string Class::', + 'MemberFunction2();', + 'string Class::', + 'NestedClass::MemberFunction3();', + 'string TemplateClass::', + 'NestedClass::MemberFunction4();', + 'const string Class', + '::static_member_variable1;', + 'const string Class::', + 'static_member_variable2;', + 'const string Class', + '::static_member_variable3 = "initial value";', + 'const string Class::', + 'static_member_variable4 = "initial value";', + 'string Class::', + 'static_member_variable5;', + '', + ], + error_collector, + ) + self.assertEqual( + error_collector.Results(), + [ + error_msg % 'const char Class::static_member_variable1', + error_msg % 'const char Class::static_member_variable2', + error_msg % 'const char Class::static_member_variable3', + error_msg % 'const char Class::static_member_variable4', + nonconst_error_msg, + ], + ) def testNoSpacesInFunctionCalls(self): - self.TestLint('TellStory(1, 3);', - '') - self.TestLint('TellStory(1, 3 );', - 'Extra space before )' - ' [whitespace/parens] [2]') - self.TestLint('TellStory(1 /* wolf */, 3 /* pigs */);', - '') - self.TestMultiLineLint("""TellStory(1, 3 + self.TestLint('TellStory(1, 3);', '') + self.TestLint('TellStory(1, 3 );', 'Extra space before ) [whitespace/parens] [2]') + self.TestLint('TellStory(1 /* wolf */, 3 /* pigs */);', '') + self.TestMultiLineLint( + """TellStory(1, 3 );""", - 'Closing ) should be moved to the previous line' - ' [whitespace/parens] [2]') - self.TestMultiLineLint("""TellStory(Wolves(1), + 'Closing ) should be moved to the previous line [whitespace/parens] [2]', + ) + self.TestMultiLineLint( + """TellStory(Wolves(1), Pigs(3 ));""", - 'Closing ) should be moved to the previous line' - ' [whitespace/parens] [2]') - self.TestMultiLineLint("""TellStory(1, + 'Closing ) should be moved to the previous line [whitespace/parens] [2]', + ) + self.TestMultiLineLint( + """TellStory(1, 3 );""", - 'Extra space before )' - ' [whitespace/parens] [2]') + 'Extra space before ) [whitespace/parens] [2]', + ) def testToDoComments(self): - start_space = ('Too many spaces before TODO' - ' [whitespace/todo] [2]') - missing_username = ('Missing username in TODO; it should look like ' - '"// TODO(my_username): Stuff."' - ' [readability/todo] [2]') - end_space = ('TODO(my_username) should be followed by a space' - ' [whitespace/todo] [2]') - - self.TestLint('// TODOfix this', - [start_space, missing_username, end_space]) - self.TestLint('// TODO(ljenkins)fix this', - [start_space, end_space]) - self.TestLint('// TODO fix this', - [start_space, missing_username]) + start_space = 'Too many spaces before TODO [whitespace/todo] [2]' + missing_username = ( + 'Missing username in TODO; it should look like ' + '"// TODO(my_username): Stuff."' + ' [readability/todo] [2]' + ) + end_space = 'TODO(my_username) should be followed by a space [whitespace/todo] [2]' + + self.TestLint('// TODOfix this', [start_space, missing_username, end_space]) + self.TestLint('// TODO(ljenkins)fix this', [start_space, end_space]) + self.TestLint('// TODO fix this', [start_space, missing_username]) self.TestLint('// TODO fix this', missing_username) self.TestLint('// TODO: fix this', missing_username) - self.TestLint('//TODO(ljenkins): Fix this', - 'Should have a space between // and comment' - ' [whitespace/comments] [4]') + self.TestLint( + '//TODO(ljenkins): Fix this', + 'Should have a space between // and comment [whitespace/comments] [4]', + ) self.TestLint('// TODO(ljenkins):Fix this', end_space) self.TestLint('// TODO(ljenkins):', '') self.TestLint('// TODO(ljenkins): fix this', '') self.TestLint('// TODO(ljenkins): Fix this', '') self.TestLint('#if 1 // TEST_URLTODOCID_WHICH_HAS_THAT_WORD_IN_IT_H_', '') self.TestLint('// See also similar TODO above', '') - self.TestLint(r'EXPECT_EQ("\\", ' - r'NormalizePath("/./../foo///bar/..//x/../..", ""));', - '') + self.TestLint( + r'EXPECT_EQ("\\", ' + r'NormalizePath("/./../foo///bar/..//x/../..", ""));', + '', + ) def testTwoSpacesBetweenCodeAndComments(self): - self.TestLint('} // namespace foo', - 'At least two spaces is best between code and comments' - ' [whitespace/comments] [2]') - self.TestLint('}// namespace foo', - 'At least two spaces is best between code and comments' - ' [whitespace/comments] [2]') - self.TestLint('printf("foo"); // Outside quotes.', - 'At least two spaces is best between code and comments' - ' [whitespace/comments] [2]') + self.TestLint( + '} // namespace foo', + 'At least two spaces is best between code and comments' + ' [whitespace/comments] [2]', + ) + self.TestLint( + '}// namespace foo', + 'At least two spaces is best between code and comments' + ' [whitespace/comments] [2]', + ) + self.TestLint( + 'printf("foo"); // Outside quotes.', + 'At least two spaces is best between code and comments' + ' [whitespace/comments] [2]', + ) self.TestLint('int i = 0; // Having two spaces is fine.', '') self.TestLint('int i = 0; // Having three spaces is OK.', '') self.TestLint('// Top level comment', '') self.TestLint(' // Line starts with two spaces.', '') - self.TestMultiLineLint('void foo() {\n' - ' { // A scope is opening.\n' - ' int a;', '') - self.TestMultiLineLint('void foo() {\n' - ' { // A scope is opening.\n' - '#define A a', - 'At least two spaces is best between code and ' - 'comments [whitespace/comments] [2]') - self.TestMultiLineLint(' foo();\n' - ' { // An indented scope is opening.\n' - ' int a;', '') - self.TestMultiLineLint('vector my_elements = {// first\n' - ' 1,', '') - self.TestMultiLineLint('vector my_elements = {// my_elements is ..\n' - ' 1,', - 'At least two spaces is best between code and ' - 'comments [whitespace/comments] [2]') - self.TestLint('if (foo) { // not a pure scope; comment is too close!', - 'At least two spaces is best between code and comments' - ' [whitespace/comments] [2]') + self.TestMultiLineLint('void foo() {\n { // A scope is opening.\n int a;', '') + self.TestMultiLineLint( + 'void foo() {\n { // A scope is opening.\n#define A a', + 'At least two spaces is best between code and ' + 'comments [whitespace/comments] [2]', + ) + self.TestMultiLineLint( + ' foo();\n { // An indented scope is opening.\n int a;', '' + ) + self.TestMultiLineLint( + 'vector my_elements = {// first\n 1,', '' + ) + self.TestMultiLineLint( + 'vector my_elements = {// my_elements is ..\n 1,', + 'At least two spaces is best between code and ' + 'comments [whitespace/comments] [2]', + ) + self.TestLint( + 'if (foo) { // not a pure scope; comment is too close!', + 'At least two spaces is best between code and comments' + ' [whitespace/comments] [2]', + ) self.TestLint('printf("// In quotes.")', '') self.TestLint('printf("\\"%s // In quotes.")', '') self.TestLint('printf("%s", "// In quotes.")', '') def testSpaceAfterCommentMarker(self): self.TestLint('//', '') - self.TestLint('//x', 'Should have a space between // and comment' - ' [whitespace/comments] [4]') + self.TestLint( + '//x', 'Should have a space between // and comment [whitespace/comments] [4]' + ) self.TestLint('// x', '') self.TestLint('///', '') self.TestLint('/// x', '') @@ -3315,15 +3739,19 @@ def testSpaceAfterCommentMarker(self): self.TestLint('////// x', '') self.TestLint('///< x', '') # After-member Doxygen comment self.TestLint('//!< x', '') # After-member Doxygen comment - self.TestLint('////x', 'Should have a space between // and comment' - ' [whitespace/comments] [4]') + self.TestLint( + '////x', 'Should have a space between // and comment [whitespace/comments] [4]' + ) self.TestLint('//}', '') - self.TestLint('//}x', 'Should have a space between // and comment' - ' [whitespace/comments] [4]') - self.TestLint('//!, ', - ' class B = piyo, ', - ' class C = fuga >', - 'class D {', - ' public:', - '};', - '', '', '', '', - '}'], - error_collector) - self.assertEqual(0, error_collector.Results().count( + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'namespace {', + '', + '} // namespace', + 'namespace another_namespace {', + '', + '}', + 'namespace {', + '', + 'template, ', + ' class B = piyo, ', + ' class C = fuga >', + 'class D {', + ' public:', + '};', + '', + '', + '', + '', + '}', + ], + error_collector, + ) + self.assertEqual( + 0, + error_collector.Results().count( 'Redundant blank line at the end of a code block should be deleted.' - ' [whitespace/blank_line] [3]')) + ' [whitespace/blank_line] [3]' + ), + ) def testAllowBlankLineBeforeIfElseChain(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['if (hoge) {', - '', # No warning - '} else if (piyo) {', - '', # No warning - '} else if (piyopiyo) {', - ' hoge = true;', # No warning - '} else {', - '', # Warning on this line - '}'], - error_collector) - self.assertEqual(1, error_collector.Results().count( + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'if (hoge) {', + '', # No warning + '} else if (piyo) {', + '', # No warning + '} else if (piyopiyo) {', + ' hoge = true;', # No warning + '} else {', + '', # Warning on this line + '}', + ], + error_collector, + ) + self.assertEqual( + 1, + error_collector.Results().count( 'Redundant blank line at the end of a code block should be deleted.' - ' [whitespace/blank_line] [3]')) + ' [whitespace/blank_line] [3]' + ), + ) def testAllowBlankLineAfterExtern(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['extern "C" {', - '', - 'EXPORTAPI void APICALL Some_function() {}', - '', - '}'], - error_collector) - self.assertEqual(0, error_collector.Results().count( + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + ['extern "C" {', '', 'EXPORTAPI void APICALL Some_function() {}', '', '}'], + error_collector, + ) + self.assertEqual( + 0, + error_collector.Results().count( 'Redundant blank line at the start of a code block should be deleted.' - ' [whitespace/blank_line] [2]')) - self.assertEqual(0, error_collector.Results().count( + ' [whitespace/blank_line] [2]' + ), + ) + self.assertEqual( + 0, + error_collector.Results().count( 'Redundant blank line at the end of a code block should be deleted.' - ' [whitespace/blank_line] [3]')) + ' [whitespace/blank_line] [3]' + ), + ) def testBlankLineBeforeSectionKeyword(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['class A {', - ' public:', - ' protected:', # warning 1 - ' private:', # warning 2 - ' struct B {', - ' public:', - ' private:'] + # warning 3 - ([''] * 100) + # Make A and B longer than 100 lines - [' };', - ' struct C {', - ' protected:', - ' private:', # C is too short for warnings - ' };', - '};', - 'class D', - ' : public {', - ' public:', # no warning - '};', - 'class E {\\', - ' public:\\'] + - (['\\'] * 100) + # Makes E > 100 lines - [' int non_empty_line;\\', - ' private:\\', # no warning - ' int a;\\', - '};'], - error_collector) - self.assertEqual(2, error_collector.Results().count( - '"private:" should be preceded by a blank line' - ' [whitespace/blank_line] [3]')) - self.assertEqual(1, error_collector.Results().count( - '"protected:" should be preceded by a blank line' - ' [whitespace/blank_line] [3]')) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'class A {', + ' public:', + ' protected:', # warning 1 + ' private:', # warning 2 + ' struct B {', + ' public:', + ' private:', + ] # warning 3 + + ([''] * 100) # Make A and B longer than 100 lines + + [ + ' };', + ' struct C {', + ' protected:', + ' private:', # C is too short for warnings + ' };', + '};', + 'class D', + ' : public {', + ' public:', # no warning + '};', + 'class E {\\', + ' public:\\', + ] + + (['\\'] * 100) # Makes E > 100 lines + + [ + ' int non_empty_line;\\', + ' private:\\', # no warning + ' int a;\\', + '};', + ], + error_collector, + ) + self.assertEqual( + 2, + error_collector.Results().count( + '"private:" should be preceded by a blank line [whitespace/blank_line] [3]' + ), + ) + self.assertEqual( + 1, + error_collector.Results().count( + '"protected:" should be preceded by a blank line [whitespace/blank_line] [3]' + ), + ) def testNoBlankLineAfterSectionKeyword(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['class A {', - ' public:', - '', # warning 1 - ' private:', - '', # warning 2 - ' struct B {', - ' protected:', - '', # warning 3 - ' };', - '};'], - error_collector) - self.assertEqual(1, error_collector.Results().count( - 'Do not leave a blank line after "public:"' - ' [whitespace/blank_line] [3]')) - self.assertEqual(1, error_collector.Results().count( - 'Do not leave a blank line after "protected:"' - ' [whitespace/blank_line] [3]')) - self.assertEqual(1, error_collector.Results().count( - 'Do not leave a blank line after "private:"' - ' [whitespace/blank_line] [3]')) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'class A {', + ' public:', + '', # warning 1 + ' private:', + '', # warning 2 + ' struct B {', + ' protected:', + '', # warning 3 + ' };', + '};', + ], + error_collector, + ) + self.assertEqual( + 1, + error_collector.Results().count( + 'Do not leave a blank line after "public:" [whitespace/blank_line] [3]' + ), + ) + self.assertEqual( + 1, + error_collector.Results().count( + 'Do not leave a blank line after "protected:" [whitespace/blank_line] [3]' + ), + ) + self.assertEqual( + 1, + error_collector.Results().count( + 'Do not leave a blank line after "private:" [whitespace/blank_line] [3]' + ), + ) def testAllowBlankLinesInRawStrings(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['// Copyright 2014 Your Company.', - 'static const char *kData[] = {R"(', - '', - ')", R"(', - '', - ')"};', - ''], - error_collector) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + 'static const char *kData[] = {R"(', + '', + ')", R"(', + '', + ')"};', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) def testElseOnSameLineAsClosingBraces(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['if (hoge) {', - '}', - 'else if (piyo) {', # Warning on this line - '}', - ' else {' # Warning on this line - '', - '}'], - error_collector) - self.assertEqual(2, error_collector.Results().count( + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'if (hoge) {', + '}', + 'else if (piyo) {', # Warning on this line + '}', + ' else {' # Warning on this line + '', + '}', + ], + error_collector, + ) + self.assertEqual( + 2, + error_collector.Results().count( 'An else should appear on the same line as the preceding }' - ' [whitespace/newline] [4]')) + ' [whitespace/newline] [4]' + ), + ) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['if (hoge) {', - '', - '}', - 'else', # Warning on this line - '{', - '', - '}'], - error_collector) - self.assertEqual(1, error_collector.Results().count( + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'if (hoge) {', + '', + '}', + 'else', # Warning on this line + '{', + '', + '}', + ], + error_collector, + ) + self.assertEqual( + 1, + error_collector.Results().count( 'An else should appear on the same line as the preceding }' - ' [whitespace/newline] [4]')) + ' [whitespace/newline] [4]' + ), + ) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['if (hoge) {', - '', - '}', - 'else_function();'], - error_collector) - self.assertEqual(0, error_collector.Results().count( + cpplint.ProcessFileData( + 'foo.cc', 'cc', ['if (hoge) {', '', '}', 'else_function();'], error_collector + ) + self.assertEqual( + 0, + error_collector.Results().count( 'An else should appear on the same line as the preceding }' - ' [whitespace/newline] [4]')) + ' [whitespace/newline] [4]' + ), + ) def testMultipleStatementsOnSameLine(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['for (int i = 0; i < 1; i++) {}', - 'switch (x) {', - ' case 0: func(); break; ', - '}', - 'sum += MathUtil::SafeIntRound(x); x += 0.1;'], - error_collector) - self.assertEqual(0, error_collector.Results().count( - 'More than one command on the same line [whitespace/newline] [0]')) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'for (int i = 0; i < 1; i++) {}', + 'switch (x) {', + ' case 0: func(); break; ', + '}', + 'sum += MathUtil::SafeIntRound(x); x += 0.1;', + ], + error_collector, + ) + self.assertEqual( + 0, + error_collector.Results().count( + 'More than one command on the same line [whitespace/newline] [0]' + ), + ) old_verbose_level = cpplint._cpplint_state.verbose_level cpplint._cpplint_state.verbose_level = 0 - cpplint.ProcessFileData('foo.cc', 'cc', - ['sum += MathUtil::SafeIntRound(x); x += 0.1;'], - error_collector) + cpplint.ProcessFileData( + 'foo.cc', 'cc', ['sum += MathUtil::SafeIntRound(x); x += 0.1;'], error_collector + ) cpplint._cpplint_state.verbose_level = old_verbose_level def testLambdasOnSameLine(self): error_collector = ErrorCollector(self.assertTrue) old_verbose_level = cpplint._cpplint_state.verbose_level cpplint._cpplint_state.verbose_level = 0 - cpplint.ProcessFileData('foo.cc', 'cc', - ['const auto lambda = ' - '[](const int i) { return i; };'], - error_collector) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + ['const auto lambda = [](const int i) { return i; };'], + error_collector, + ) cpplint._cpplint_state.verbose_level = old_verbose_level - self.assertEqual(0, error_collector.Results().count( - 'More than one command on the same line [whitespace/newline] [0]')) + self.assertEqual( + 0, + error_collector.Results().count( + 'More than one command on the same line [whitespace/newline] [0]' + ), + ) error_collector = ErrorCollector(self.assertTrue) old_verbose_level = cpplint._cpplint_state.verbose_level cpplint._cpplint_state.verbose_level = 0 - cpplint.ProcessFileData('foo.cc', 'cc', - ['const auto result = std::any_of(vector.begin(), ' - 'vector.end(), ' - '[](const int i) { return i > 0; });'], - error_collector) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'const auto result = std::any_of(vector.begin(), ' + 'vector.end(), ' + '[](const int i) { return i > 0; });' + ], + error_collector, + ) cpplint._cpplint_state.verbose_level = old_verbose_level - self.assertEqual(0, error_collector.Results().count( - 'More than one command on the same line [whitespace/newline] [0]')) + self.assertEqual( + 0, + error_collector.Results().count( + 'More than one command on the same line [whitespace/newline] [0]' + ), + ) error_collector = ErrorCollector(self.assertTrue) old_verbose_level = cpplint._cpplint_state.verbose_level cpplint._cpplint_state.verbose_level = 0 - cpplint.ProcessFileData('foo.cc', 'cc', - ['return mutex::Lock([this]() { ' - 'this->ReadLock(); }, [this]() { ' - 'this->ReadUnlock(); });'], - error_collector) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'return mutex::Lock([this]() { ' + 'this->ReadLock(); }, [this]() { ' + 'this->ReadUnlock(); });' + ], + error_collector, + ) cpplint._cpplint_state.verbose_level = old_verbose_level - self.assertEqual(0, error_collector.Results().count( - 'More than one command on the same line [whitespace/newline] [0]')) + self.assertEqual( + 0, + error_collector.Results().count( + 'More than one command on the same line [whitespace/newline] [0]' + ), + ) error_collector = ErrorCollector(self.assertTrue) old_verbose_level = cpplint._cpplint_state.verbose_level cpplint._cpplint_state.verbose_level = 0 - cpplint.ProcessFileData('foo.cc', 'cc', - ['return mutex::Lock([this]() { ' - 'this->ReadLock(); }, [this]() { ' - 'this->ReadUnlock(); }, object);'], - error_collector) + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'return mutex::Lock([this]() { ' + 'this->ReadLock(); }, [this]() { ' + 'this->ReadUnlock(); }, object);' + ], + error_collector, + ) cpplint._cpplint_state.verbose_level = old_verbose_level - self.assertEqual(0, error_collector.Results().count( - 'More than one command on the same line [whitespace/newline] [0]')) + self.assertEqual( + 0, + error_collector.Results().count( + 'More than one command on the same line [whitespace/newline] [0]' + ), + ) def testEndOfNamespaceComments(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('foo.cc', 'cc', - ['namespace {', - '', - '}', # No warning (too short) - 'namespace expected {', - '} // namespace mismatched', # Warning here - 'namespace {', - '} // namespace mismatched', # Warning here - 'namespace outer { namespace nested {'] + - ([''] * 10) + - ['}', # Warning here - '}', # Warning here - 'namespace {'] + - ([''] * 10) + - ['}', # Warning here - 'namespace {'] + - ([''] * 10) + - ['} // namespace some description', # Anon warning - 'namespace {'] + - ([''] * 10) + - ['} // namespace anonymous', # Variant warning - 'namespace {'] + - ([''] * 10) + - ['} // anonymous namespace (utils)', # Variant - 'namespace {'] + - ([''] * 10) + - ['} // anonymous namespace', # No warning - 'namespace missing_comment {'] + - ([''] * 10) + - ['}', # Warning here - 'namespace no_warning {'] + - ([''] * 10) + - ['} // namespace no_warning', - 'namespace no_warning {'] + - ([''] * 10) + - ['}; // end namespace no_warning', - '#define MACRO \\', - 'namespace c_style { \\'] + - (['\\'] * 10) + - ['} /* namespace c_style. */ \\', - ';'], - error_collector) - self.assertEqual(1, error_collector.Results().count( + cpplint.ProcessFileData( + 'foo.cc', + 'cc', + [ + 'namespace {', + '', + '}', # No warning (too short) + 'namespace expected {', + '} // namespace mismatched', # Warning here + 'namespace {', + '} // namespace mismatched', # Warning here + 'namespace outer { namespace nested {', + ] + + ([''] * 10) + + [ + '}', # Warning here + '}', # Warning here + 'namespace {', + ] + + ([''] * 10) + + [ + '}', # Warning here + 'namespace {', + ] + + ([''] * 10) + + [ + '} // namespace some description', # Anon warning + 'namespace {', + ] + + ([''] * 10) + + [ + '} // namespace anonymous', # Variant warning + 'namespace {', + ] + + ([''] * 10) + + [ + '} // anonymous namespace (utils)', # Variant + 'namespace {', + ] + + ([''] * 10) + + [ + '} // anonymous namespace', # No warning + 'namespace missing_comment {', + ] + + ([''] * 10) + + [ + '}', # Warning here + 'namespace no_warning {', + ] + + ([''] * 10) + + ['} // namespace no_warning', 'namespace no_warning {'] + + ([''] * 10) + + [ + '}; // end namespace no_warning', + '#define MACRO \\', + 'namespace c_style { \\', + ] + + (['\\'] * 10) + + ['} /* namespace c_style. */ \\', ';'], + error_collector, + ) + self.assertEqual( + 1, + error_collector.Results().count( 'Namespace should be terminated with "// namespace expected"' - ' [readability/namespace] [5]')) - self.assertEqual(1, error_collector.Results().count( + ' [readability/namespace] [5]' + ), + ) + self.assertEqual( + 1, + error_collector.Results().count( 'Namespace should be terminated with "// namespace outer"' - ' [readability/namespace] [5]')) - self.assertEqual(1, error_collector.Results().count( + ' [readability/namespace] [5]' + ), + ) + self.assertEqual( + 1, + error_collector.Results().count( 'Namespace should be terminated with "// namespace nested"' - ' [readability/namespace] [5]')) - self.assertEqual(3, error_collector.Results().count( + ' [readability/namespace] [5]' + ), + ) + self.assertEqual( + 3, + error_collector.Results().count( 'Anonymous namespace should be terminated with "// namespace"' - ' [readability/namespace] [5]')) - self.assertEqual(2, error_collector.Results().count( + ' [readability/namespace] [5]' + ), + ) + self.assertEqual( + 2, + error_collector.Results().count( 'Anonymous namespace should be terminated with "// namespace" or' ' "// anonymous namespace"' - ' [readability/namespace] [5]')) - self.assertEqual(1, error_collector.Results().count( + ' [readability/namespace] [5]' + ), + ) + self.assertEqual( + 1, + error_collector.Results().count( 'Namespace should be terminated with "// namespace missing_comment"' - ' [readability/namespace] [5]')) - self.assertEqual(0, error_collector.Results().count( + ' [readability/namespace] [5]' + ), + ) + self.assertEqual( + 0, + error_collector.Results().count( 'Namespace should be terminated with "// namespace no_warning"' - ' [readability/namespace] [5]')) + ' [readability/namespace] [5]' + ), + ) def testComma(self): - self.TestLint('a = f(1,2);', - 'Missing space after , [whitespace/comma] [3]') - self.TestLint('int tmp=a,a=b,b=tmp;', - ['Missing spaces around = [whitespace/operators] [4]', - 'Missing space after , [whitespace/comma] [3]']) + self.TestLint('a = f(1,2);', 'Missing space after , [whitespace/comma] [3]') + self.TestLint( + 'int tmp=a,a=b,b=tmp;', + [ + 'Missing spaces around = [whitespace/operators] [4]', + 'Missing space after , [whitespace/comma] [3]', + ], + ) self.TestLint('f(a, /* name */ b);', '') self.TestLint('f(a, /* name */b);', '') self.TestLint('f(a, /* name */-1);', '') @@ -3759,44 +4380,44 @@ def testComma(self): self.TestLint('f(1, /* empty macro arg */, 2)', '') self.TestLint('f(1,, 2)', '') self.TestLint('operator,()', '') - self.TestLint('operator,(a,b)', - 'Missing space after , [whitespace/comma] [3]') + self.TestLint('operator,(a,b)', 'Missing space after , [whitespace/comma] [3]') self.TestLint('__VA_OPT__(,)', '') - self.TestLint('__VA_OPT__ (,)', - 'Extra space before ( in function call [whitespace/parens] [4]') + self.TestLint( + '__VA_OPT__ (,)', 'Extra space before ( in function call [whitespace/parens] [4]' + ) def testEqualsOperatorSpacing(self): - self.TestLint('int tmp= a;', - 'Missing spaces around = [whitespace/operators] [4]') - self.TestLint('int tmp =a;', - 'Missing spaces around = [whitespace/operators] [4]') - self.TestLint('int tmp=a;', - 'Missing spaces around = [whitespace/operators] [4]') - self.TestLint('int tmp= 7;', - 'Missing spaces around = [whitespace/operators] [4]') - self.TestLint('int tmp =7;', - 'Missing spaces around = [whitespace/operators] [4]') - self.TestLint('int tmp=7;', - 'Missing spaces around = [whitespace/operators] [4]') - self.TestLint('int* tmp=*p;', - 'Missing spaces around = [whitespace/operators] [4]') - self.TestLint('int* tmp= *p;', - 'Missing spaces around = [whitespace/operators] [4]') + self.TestLint('int tmp= a;', 'Missing spaces around = [whitespace/operators] [4]') + self.TestLint('int tmp =a;', 'Missing spaces around = [whitespace/operators] [4]') + self.TestLint('int tmp=a;', 'Missing spaces around = [whitespace/operators] [4]') + self.TestLint('int tmp= 7;', 'Missing spaces around = [whitespace/operators] [4]') + self.TestLint('int tmp =7;', 'Missing spaces around = [whitespace/operators] [4]') + self.TestLint('int tmp=7;', 'Missing spaces around = [whitespace/operators] [4]') + self.TestLint('int* tmp=*p;', 'Missing spaces around = [whitespace/operators] [4]') + self.TestLint( + 'int* tmp= *p;', 'Missing spaces around = [whitespace/operators] [4]' + ) self.TestMultiLineLint( - TrimExtraIndent(''' + TrimExtraIndent(''' lookahead_services_= ::strings::Split(FLAGS_ls, ",", ::strings::SkipEmpty());'''), - 'Missing spaces around = [whitespace/operators] [4]') - self.TestLint('bool result = a>=42;', - 'Missing spaces around >= [whitespace/operators] [3]') - self.TestLint('bool result = a<=42;', - 'Missing spaces around <= [whitespace/operators] [3]') - self.TestLint('bool result = a==42;', - 'Missing spaces around == [whitespace/operators] [3]') - self.TestLint('auto result = a!=42;', - 'Missing spaces around != [whitespace/operators] [3]') - self.TestLint('int a = b!=c;', - 'Missing spaces around != [whitespace/operators] [3]') + 'Missing spaces around = [whitespace/operators] [4]', + ) + self.TestLint( + 'bool result = a>=42;', 'Missing spaces around >= [whitespace/operators] [3]' + ) + self.TestLint( + 'bool result = a<=42;', 'Missing spaces around <= [whitespace/operators] [3]' + ) + self.TestLint( + 'bool result = a==42;', 'Missing spaces around == [whitespace/operators] [3]' + ) + self.TestLint( + 'auto result = a!=42;', 'Missing spaces around != [whitespace/operators] [3]' + ) + self.TestLint( + 'int a = b!=c;', 'Missing spaces around != [whitespace/operators] [3]' + ) self.TestLint('a&=42;', '') self.TestLint('a|=42;', '') self.TestLint('a^=42;', '') @@ -3808,10 +4429,8 @@ def testEqualsOperatorSpacing(self): self.TestLint('a<<=5;', '') def testShiftOperatorSpacing(self): - self.TestLint('a<>b', - 'Missing spaces around >> [whitespace/operators] [3]') + self.TestLint('a<>b', 'Missing spaces around >> [whitespace/operators] [3]') self.TestLint('1<<20', '') self.TestLint('1024>>10', '') self.TestLint('Kernel<<<1, 2>>>()', '') @@ -3820,15 +4439,21 @@ def testIndent(self): self.TestLint('static int noindent;', '') self.TestLint(' int two_space_indent;', '') self.TestLint(' int four_space_indent;', '') - self.TestLint(' int one_space_indent;', - 'Weird number of spaces at line-start. ' - 'Are you using a 2-space indent? [whitespace/indent] [3]') - self.TestLint(' int three_space_indent;', - 'Weird number of spaces at line-start. ' - 'Are you using a 2-space indent? [whitespace/indent] [3]') - self.TestLint(' char* one_space_indent = "public:";', - 'Weird number of spaces at line-start. ' - 'Are you using a 2-space indent? [whitespace/indent] [3]') + self.TestLint( + ' int one_space_indent;', + 'Weird number of spaces at line-start. ' + 'Are you using a 2-space indent? [whitespace/indent] [3]', + ) + self.TestLint( + ' int three_space_indent;', + 'Weird number of spaces at line-start. ' + 'Are you using a 2-space indent? [whitespace/indent] [3]', + ) + self.TestLint( + ' char* one_space_indent = "public:";', + 'Weird number of spaces at line-start. ' + 'Are you using a 2-space indent? [whitespace/indent] [3]', + ) self.TestLint(' public:', '') self.TestLint(' protected:', '') self.TestLint(' private:', '') @@ -3837,55 +4462,60 @@ def testIndent(self): self.TestLint(' private: \\', '') # examples using QT signals/slots macro self.TestMultiLineLint( - TrimExtraIndent(""" + TrimExtraIndent(""" class foo { public slots: void bar(); signals: };"""), - '') + '', + ) self.TestMultiLineLint( - TrimExtraIndent(""" + TrimExtraIndent(""" class foo { public slots: void bar(); };"""), - 'public slots: should be indented +1 space inside class foo' - ' [whitespace/indent] [3]') + 'public slots: should be indented +1 space inside class foo' + ' [whitespace/indent] [3]', + ) self.TestMultiLineLint( - TrimExtraIndent(""" + TrimExtraIndent(""" class foo { signals: void bar(); };"""), - 'signals: should be indented +1 space inside class foo' - ' [whitespace/indent] [3]') + 'signals: should be indented +1 space inside class foo [whitespace/indent] [3]', + ) self.TestMultiLineLint( - TrimExtraIndent(''' + TrimExtraIndent(''' static const char kRawString[] = R"(" ")";'''), - '') + '', + ) self.TestMultiLineLint( - TrimExtraIndent(''' + TrimExtraIndent(''' KV>'''), - '') + '', + ) self.TestMultiLineLint( - ' static const char kSingleLineRawString[] = R"(...)";', - 'Weird number of spaces at line-start. ' - 'Are you using a 2-space indent? [whitespace/indent] [3]') + ' static const char kSingleLineRawString[] = R"(...)";', + 'Weird number of spaces at line-start. ' + 'Are you using a 2-space indent? [whitespace/indent] [3]', + ) def testSectionIndent(self): self.TestMultiLineLint( - """ + """ class A { public: // no warning private: // warning here };""", - 'private: should be indented +1 space inside class A' - ' [whitespace/indent] [3]') + 'private: should be indented +1 space inside class A [whitespace/indent] [3]', + ) self.TestMultiLineLint( - """ + """ class B { public: // no warning template<> struct C { @@ -3893,251 +4523,280 @@ class B { protected: // no warning }; };""", - 'public: should be indented +1 space inside struct C' - ' [whitespace/indent] [3]') + 'public: should be indented +1 space inside struct C [whitespace/indent] [3]', + ) self.TestMultiLineLint( - """ + """ struct D { };""", - 'Closing brace should be aligned with beginning of struct D' - ' [whitespace/indent] [3]') + 'Closing brace should be aligned with beginning of struct D' + ' [whitespace/indent] [3]', + ) self.TestMultiLineLint( - """ + """ template class F { };""", - 'Closing brace should be aligned with beginning of class F' - ' [whitespace/indent] [3]') + 'Closing brace should be aligned with beginning of class F' + ' [whitespace/indent] [3]', + ) self.TestMultiLineLint( - """ + """ class G { Q_OBJECT public slots: signals: };""", - ['public slots: should be indented +1 space inside class G' - ' [whitespace/indent] [3]', - 'signals: should be indented +1 space inside class G' - ' [whitespace/indent] [3]']) + [ + 'public slots: should be indented +1 space inside class G' + ' [whitespace/indent] [3]', + 'signals: should be indented +1 space inside class G [whitespace/indent] [3]', + ], + ) self.TestMultiLineLint( - """ + """ class H { /* comments */ class I { public: // no warning private: // warning here }; };""", - 'private: should be indented +1 space inside class I' - ' [whitespace/indent] [3]') + 'private: should be indented +1 space inside class I [whitespace/indent] [3]', + ) self.TestMultiLineLint( - """ + """ class J : public ::K { public: // no warning protected: // warning here };""", - 'protected: should be indented +1 space inside class J' - ' [whitespace/indent] [3]') + 'protected: should be indented +1 space inside class J [whitespace/indent] [3]', + ) self.TestMultiLineLint( - """ + """ class L : public M, public ::N { };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ template static void Func() { }""", - '') + '', + ) def testConditionals(self): self.TestMultiLineLint( - """ + """ if (foo) goto fail; goto fail;""", - 'If/else bodies with multiple statements require braces' - ' [readability/braces] [4]') + 'If/else bodies with multiple statements require braces' + ' [readability/braces] [4]', + ) self.TestMultiLineLint( - """ + """ if (foo) goto fail; goto fail;""", - 'If/else bodies with multiple statements require braces' - ' [readability/braces] [4]') + 'If/else bodies with multiple statements require braces' + ' [readability/braces] [4]', + ) self.TestMultiLineLint( - """ + """ if (foo) foo; else goto fail; goto fail;""", - 'If/else bodies with multiple statements require braces' - ' [readability/braces] [4]') + 'If/else bodies with multiple statements require braces' + ' [readability/braces] [4]', + ) self.TestMultiLineLint( - """ + """ if (foo) goto fail; goto fail;""", - 'If/else bodies with multiple statements require braces' - ' [readability/braces] [4]') + 'If/else bodies with multiple statements require braces' + ' [readability/braces] [4]', + ) self.TestMultiLineLint( - """ + """ if constexpr (foo) { goto fail; goto fail; } else if constexpr (bar) { hello(); }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ if (foo) if (bar) baz; else qux;""", - 'Else clause should be indented at the same level as if. Ambiguous' - ' nested if/else chains require braces. [readability/braces] [4]') + 'Else clause should be indented at the same level as if. Ambiguous' + ' nested if/else chains require braces. [readability/braces] [4]', + ) self.TestMultiLineLint( - """ + """ if (foo) if (bar) baz; else qux;""", - 'Else clause should be indented at the same level as if. Ambiguous' - ' nested if/else chains require braces. [readability/braces] [4]') + 'Else clause should be indented at the same level as if. Ambiguous' + ' nested if/else chains require braces. [readability/braces] [4]', + ) self.TestMultiLineLint( - """ + """ if (foo) { bar; baz; } else qux;""", - 'If an else has a brace on one side, it should have it on both' - ' [readability/braces] [5]') + 'If an else has a brace on one side, it should have it on both' + ' [readability/braces] [5]', + ) self.TestMultiLineLint( - """ + """ if (foo) bar; else { baz; }""", - 'If an else has a brace on one side, it should have it on both' - ' [readability/braces] [5]') + 'If an else has a brace on one side, it should have it on both' + ' [readability/braces] [5]', + ) self.TestMultiLineLint( - """ + """ if (foo) bar; else if (baz) { qux; }""", - 'If an else has a brace on one side, it should have it on both' - ' [readability/braces] [5]') + 'If an else has a brace on one side, it should have it on both' + ' [readability/braces] [5]', + ) self.TestMultiLineLint( - """ + """ if (foo) { bar; } else if (baz) qux;""", - 'If an else has a brace on one side, it should have it on both' - ' [readability/braces] [5]') + 'If an else has a brace on one side, it should have it on both' + ' [readability/braces] [5]', + ) self.TestMultiLineLint( - """ + """ if (foo) goto fail; bar;""", - '') + '', + ) self.TestMultiLineLint( - """ + """ if (foo && bar) { baz; qux; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ if (foo) goto fail;""", - '') + '', + ) self.TestMultiLineLint( - """ + """ if (foo) bar; else baz; qux;""", - '') + '', + ) self.TestMultiLineLint( - """ + """ for (;;) { if (foo) bar; else baz; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ if (foo) bar; else if (baz) baz;""", - '') + '', + ) self.TestMultiLineLint( - """ + """ if (foo) bar; else baz;""", - '') + '', + ) self.TestMultiLineLint( - """ + """ if (foo) { bar; } else { baz; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ if (foo) { bar; } else if (baz) { qux; }""", - '') + '', + ) # Note: this is an error for a different reason, but should not trigger the # single-line if error. self.TestMultiLineLint( - """ + """ if (foo) { bar; baz; }""", - '{ should almost always be at the end of the previous line' - ' [whitespace/braces] [4]') + '{ should almost always be at the end of the previous line' + ' [whitespace/braces] [4]', + ) self.TestMultiLineLint( - """ + """ void foo() { if (bar) baz; }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ #if foo bar; #else baz; qux; #endif""", - '') + '', + ) self.TestMultiLineLint( - """void F() { + """void F() { variable = [] { if (true); }; variable = [] { if (true); }; @@ -4145,34 +4804,37 @@ def testConditionals(self): [] { if (true); }, [] { if (true); }); }""", - '') + '', + ) self.TestMultiLineLint( - """ + """ #if(A == 0) foo(); #elif(A == 1) bar(); #endif""", - '') + '', + ) self.TestMultiLineLint( - """ + """ #if (A == 0) foo(); #elif (A == 1) bar(); #endif""", - '') + '', + ) @parameterized.expand(['else if', 'if', 'while', 'for', 'switch']) def testControlClauseWithParensNewline(self, keyword): # The % 2 part is pseudorandom whitespace-support testing self.TestLintContains( f'{keyword}{["", " "][len(keyword) % 2]}(condition)' - f'{[" ", ""][len(keyword) % 2]}[[unlikely]]' - f'{[" ", ""][len(keyword) % 2]}{{' - f'{["", " "][len(keyword) % 2]}do_something(); }}', + f'{[" ", ""][len(keyword) % 2]}[[unlikely]]' + f'{[" ", ""][len(keyword) % 2]}{{' + f'{["", " "][len(keyword) % 2]}do_something(); }}', f'Controlled statements inside brackets of {keyword} clause' - f' should be on a separate line [whitespace/newline] [5]' + f' should be on a separate line [whitespace/newline] [5]', ) @parameterized.expand(['else', 'do', 'try']) @@ -4180,9 +4842,9 @@ def testControlClauseWithoutParensNewline(self, keyword): # The % 2 part is pseudorandom whitespace-support testing self.TestLintContains( f'{keyword}{["", " "][len(keyword) % 2]}{{' - f'{[" ", ""][len(keyword) % 2]}do_something(); }}', + f'{[" ", ""][len(keyword) % 2]}do_something(); }}', f'Controlled statements inside brackets of {keyword} clause' - f' should be on a separate line [whitespace/newline] [5]' + f' should be on a separate line [whitespace/newline] [5]', ) def testControlClauseNewlineNameFalsePositives(self): @@ -4191,10 +4853,11 @@ def testControlClauseNewlineNameFalsePositives(self): self.TestLint(' variable_ends_in_else = true;', '') def testTab(self): - self.TestLint('\tint a;', - 'Tab found; better to use spaces [whitespace/tab] [1]') - self.TestLint('int a = 5;\t\t// set a to 5', - 'Tab found; better to use spaces [whitespace/tab] [1]') + self.TestLint('\tint a;', 'Tab found; better to use spaces [whitespace/tab] [1]') + self.TestLint( + 'int a = 5;\t\t// set a to 5', + 'Tab found; better to use spaces [whitespace/tab] [1]', + ) def testParseArguments(self): old_output_format = cpplint._cpplint_state.output_format @@ -4216,68 +4879,64 @@ def testParseArguments(self): self.assertRaises(SystemExit, cpplint.ParseArguments, ['--filter=']) # This is illegal because all filters must start with + or - self.assertRaises(SystemExit, cpplint.ParseArguments, ['--filter=foo']) - self.assertRaises(SystemExit, cpplint.ParseArguments, - ['--filter=+a,b,-c']) + self.assertRaises(SystemExit, cpplint.ParseArguments, ['--filter=+a,b,-c']) self.assertRaises(SystemExit, cpplint.ParseArguments, ['--headers']) self.assertEqual(['foo.cc'], cpplint.ParseArguments(['foo.cc'])) self.assertEqual(old_output_format, cpplint._cpplint_state.output_format) self.assertEqual(old_verbose_level, cpplint._cpplint_state.verbose_level) - self.assertEqual(['foo.cc'], - cpplint.ParseArguments(['--v=1', 'foo.cc'])) + self.assertEqual(['foo.cc'], cpplint.ParseArguments(['--v=1', 'foo.cc'])) self.assertEqual(1, cpplint._cpplint_state.verbose_level) - self.assertEqual(['foo.h'], - cpplint.ParseArguments(['--v=3', 'foo.h'])) + self.assertEqual(['foo.h'], cpplint.ParseArguments(['--v=3', 'foo.h'])) self.assertEqual(3, cpplint._cpplint_state.verbose_level) - self.assertEqual(['foo.cpp'], - cpplint.ParseArguments(['--verbose=5', 'foo.cpp'])) + self.assertEqual(['foo.cpp'], cpplint.ParseArguments(['--verbose=5', 'foo.cpp'])) self.assertEqual(5, cpplint._cpplint_state.verbose_level) - self.assertRaises(ValueError, - cpplint.ParseArguments, ['--v=f', 'foo.cc']) + self.assertRaises(ValueError, cpplint.ParseArguments, ['--v=f', 'foo.cc']) - self.assertEqual(['foo.cc'], - cpplint.ParseArguments(['--output=emacs', 'foo.cc'])) + self.assertEqual(['foo.cc'], cpplint.ParseArguments(['--output=emacs', 'foo.cc'])) self.assertEqual('emacs', cpplint._cpplint_state.output_format) - self.assertEqual(['foo.h'], - cpplint.ParseArguments(['--output=vs7', 'foo.h'])) + self.assertEqual(['foo.h'], cpplint.ParseArguments(['--output=vs7', 'foo.h'])) self.assertEqual('vs7', cpplint._cpplint_state.output_format) - self.assertRaises(SystemExit, - cpplint.ParseArguments, ['--output=blah', 'foo.cc']) + self.assertRaises(SystemExit, cpplint.ParseArguments, ['--output=blah', 'foo.cc']) filt = '-,+whitespace,-whitespace/indent' - self.assertEqual(['foo.h'], - cpplint.ParseArguments(['--filter='+filt, 'foo.h'])) - self.assertEqual(['-', '+whitespace', '-whitespace/indent'], - cpplint._cpplint_state.filters) + self.assertEqual(['foo.h'], cpplint.ParseArguments(['--filter=' + filt, 'foo.h'])) + self.assertEqual( + ['-', '+whitespace', '-whitespace/indent'], cpplint._cpplint_state.filters + ) - self.assertEqual(['foo.cc', 'foo.h'], - cpplint.ParseArguments(['foo.cc', 'foo.h'])) + self.assertEqual(['foo.cc', 'foo.h'], cpplint.ParseArguments(['foo.cc', 'foo.h'])) cpplint._hpp_headers = old_headers cpplint._valid_extensions = old_valid_extensions - self.assertEqual(['foo.h'], - cpplint.ParseArguments(['--linelength=120', 'foo.h'])) + self.assertEqual(['foo.h'], cpplint.ParseArguments(['--linelength=120', 'foo.h'])) self.assertEqual(120, cpplint._line_length) - self.assertEqual(set(['h', 'hh', 'hpp', 'hxx', 'h++', 'cuh']), cpplint.GetHeaderExtensions()) # Default value + self.assertEqual( + set(['h', 'hh', 'hpp', 'hxx', 'h++', 'cuh']), cpplint.GetHeaderExtensions() + ) # Default value cpplint._hpp_headers = old_headers cpplint._valid_extensions = old_valid_extensions - self.assertEqual(['foo.h'], - cpplint.ParseArguments(['--headers=h', 'foo.h'])) - self.assertEqual(set(['h', 'c', 'cc', 'cpp', 'cxx', 'c++', 'cu']), cpplint.GetAllExtensions()) + self.assertEqual(['foo.h'], cpplint.ParseArguments(['--headers=h', 'foo.h'])) + self.assertEqual( + set(['h', 'c', 'cc', 'cpp', 'cxx', 'c++', 'cu']), cpplint.GetAllExtensions() + ) cpplint._hpp_headers = old_headers cpplint._valid_extensions = old_valid_extensions - self.assertEqual(['foo.h'], - cpplint.ParseArguments(['--extensions=hpp,cpp,cpp', 'foo.h'])) + self.assertEqual( + ['foo.h'], cpplint.ParseArguments(['--extensions=hpp,cpp,cpp', 'foo.h']) + ) self.assertEqual(set(['hpp', 'cpp']), cpplint.GetAllExtensions()) self.assertEqual(set(['hpp']), cpplint.GetHeaderExtensions()) cpplint._hpp_headers = old_headers cpplint._valid_extensions = old_valid_extensions - self.assertEqual(['foo.h'], - cpplint.ParseArguments(['--extensions=cpp,cpp', '--headers=hpp,h', 'foo.h'])) + self.assertEqual( + ['foo.h'], + cpplint.ParseArguments(['--extensions=cpp,cpp', '--headers=hpp,h', 'foo.h']), + ) self.assertEqual(set(['hpp', 'h']), cpplint.GetHeaderExtensions()) self.assertEqual(set(['hpp', 'h', 'cpp']), cpplint.GetAllExtensions()) @@ -4302,14 +4961,17 @@ def testRecursiveArgument(self): open(os.path.join(src_dir, "two.cpp"), 'w').close() open(os.path.join(nested_dir, "three.cpp"), 'w').close() os.chdir(temp_dir) - expected = ['one.cpp', os.path.join('src', 'two.cpp'), - os.path.join('src', 'nested', 'three.cpp')] + expected = [ + 'one.cpp', + os.path.join('src', 'two.cpp'), + os.path.join('src', 'nested', 'three.cpp'), + ] cpplint._excludes = None actual = cpplint.ParseArguments(['--recursive', 'one.cpp', 'src']) self.assertEqual(set(expected), set(actual)) finally: - os.chdir(working_dir) - shutil.rmtree(temp_dir) + os.chdir(working_dir) + shutil.rmtree(temp_dir) def testRecursiveExcludeInvalidFileExtension(self): working_dir = os.getcwd() @@ -4323,14 +4985,15 @@ def testRecursiveExcludeInvalidFileExtension(self): os.chdir(temp_dir) expected = ['one.cpp', os.path.join('src', 'two.cpp')] cpplint._excludes = None - actual = cpplint.ParseArguments(['--recursive', '--extensions=cpp', - 'one.cpp', 'src']) + actual = cpplint.ParseArguments( + ['--recursive', '--extensions=cpp', 'one.cpp', 'src'] + ) self.assertEqual(set(expected), set(actual)) finally: - os.chdir(working_dir) - shutil.rmtree(temp_dir) - cpplint._hpp_headers = set([]) - cpplint._valid_extensions = set([]) + os.chdir(working_dir) + shutil.rmtree(temp_dir) + cpplint._hpp_headers = set([]) + cpplint._valid_extensions = set([]) def testRecursiveExclude(self): working_dir = os.getcwd() @@ -4351,7 +5014,7 @@ def testRecursiveExclude(self): expected = [ os.path.join('src', 'one.cc'), os.path.join('src', 'two.cc'), - os.path.join('src', 'three.cc') + os.path.join('src', 'three.cc'), ] cpplint._excludes = None actual = cpplint.ParseArguments(['src']) @@ -4363,87 +5026,105 @@ def testRecursiveExclude(self): expected = [os.path.join('src', 'one.cc')] cpplint._excludes = None - actual = cpplint.ParseArguments(['--recursive', - '--exclude=src{0}t*'.format(os.sep), 'src']) + actual = cpplint.ParseArguments( + ['--recursive', '--exclude=src{0}t*'.format(os.sep), 'src'] + ) self.assertEqual(set(expected), set(actual)) expected = [os.path.join('src', 'one.cc')] cpplint._excludes = None - actual = cpplint.ParseArguments(['--recursive', - '--exclude=src/two.cc', '--exclude=src/three.cc', 'src']) + actual = cpplint.ParseArguments( + ['--recursive', '--exclude=src/two.cc', '--exclude=src/three.cc', 'src'] + ) self.assertEqual(set(expected), set(actual)) - expected = set([ - os.path.join('src2', 'one.cc'), - os.path.join('src2', 'two.cc'), - os.path.join('src2', 'three.cc') - ]) + expected = set( + [ + os.path.join('src2', 'one.cc'), + os.path.join('src2', 'two.cc'), + os.path.join('src2', 'three.cc'), + ] + ) cpplint._excludes = None - actual = cpplint.ParseArguments(['--recursive', - '--exclude=src', '.']) + actual = cpplint.ParseArguments(['--recursive', '--exclude=src', '.']) self.assertEqual(expected, set(actual)) finally: - os.chdir(working_dir) - shutil.rmtree(temp_dir) + os.chdir(working_dir) + shutil.rmtree(temp_dir) def testJUnitXML(self): try: cpplint._cpplint_state._junit_errors = [] cpplint._cpplint_state._junit_failures = [] - expected = ('\n' - '' - '' - '') + expected = ( + '\n' + '' + '' + '' + ) self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) cpplint._cpplint_state._junit_errors = ['ErrMsg1'] cpplint._cpplint_state._junit_failures = [] - expected = ('\n' - '' - 'ErrMsg1' - '') + expected = ( + '\n' + '' + 'ErrMsg1' + '' + ) self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) cpplint._cpplint_state._junit_errors = ['ErrMsg1', 'ErrMsg2'] cpplint._cpplint_state._junit_failures = [] - expected = ('\n' - '' - 'ErrMsg1\nErrMsg2' - '') + expected = ( + '\n' + '' + 'ErrMsg1\nErrMsg2' + '' + ) self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) cpplint._cpplint_state._junit_errors = ['ErrMsg'] cpplint._cpplint_state._junit_failures = [ - ('File', 5, 'FailMsg', 'category/subcategory', 3)] - expected = ('\n' - '' - 'ErrMsg' - '5: FailMsg [category/subcategory] ' - '[3]') + ('File', 5, 'FailMsg', 'category/subcategory', 3) + ] + expected = ( + '\n' + '' + 'ErrMsg' + '5: FailMsg [category/subcategory] ' + '[3]' + ) self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) cpplint._cpplint_state._junit_errors = [] cpplint._cpplint_state._junit_failures = [ - ('File1', 5, 'FailMsg1', 'category/subcategory', 3), - ('File2', 99, 'FailMsg2', 'category/subcategory', 3), - ('File1', 19, 'FailMsg3', 'category/subcategory', 3)] - expected = ('\n' - '' - '5: FailMsg1 [category/subcategory]' - ' [3]\n19: FailMsg3 [category/subcategory] [3]' - '99: FailMsg2 ' - '[category/subcategory] [3]') + ('File1', 5, 'FailMsg1', 'category/subcategory', 3), + ('File2', 99, 'FailMsg2', 'category/subcategory', 3), + ('File1', 19, 'FailMsg3', 'category/subcategory', 3), + ] + expected = ( + '\n' + '' + '5: FailMsg1 [category/subcategory]' + ' [3]\n19: FailMsg3 [category/subcategory] [3]' + '99: FailMsg2 ' + '[category/subcategory] [3]' + ) self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) cpplint._cpplint_state._junit_errors = ['&'] cpplint._cpplint_state._junit_failures = [ - ('File1', 5, '&', 'category/subcategory', 3)] - expected = ('\n' - '' - '&</error>' - '5: ' - '&</failure> [category/subcategory] [3]' - '') + ('File1', 5, '&', 'category/subcategory', 3) + ] + expected = ( + '\n' + '' + '&</error>' + '5: ' + '&</failure> [category/subcategory] [3]' + '' + ) self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) finally: @@ -4459,21 +5140,17 @@ def testLineLength(self): old_line_length = cpplint._line_length try: cpplint._line_length = 80 + self.TestLint('// H %s' % ('H' * 75), '') self.TestLint( - '// H %s' % ('H' * 75), - '') - self.TestLint( - '// H %s' % ('H' * 76), - 'Lines should be <= 80 characters long' - ' [whitespace/line_length] [2]') + '// H %s' % ('H' * 76), + 'Lines should be <= 80 characters long [whitespace/line_length] [2]', + ) cpplint._line_length = 120 + self.TestLint('// H %s' % ('H' * 115), '') self.TestLint( - '// H %s' % ('H' * 115), - '') - self.TestLint( - '// H %s' % ('H' * 116), - 'Lines should be <= 120 characters long' - ' [whitespace/line_length] [2]') + '// H %s' % ('H' * 116), + 'Lines should be <= 120 characters long [whitespace/line_length] [2]', + ) finally: cpplint._line_length = old_line_length @@ -4482,9 +5159,10 @@ def testFilter(self): try: cpplint._cpplint_state.SetFilters('-,+whitespace,-whitespace/indent') self.TestLint( - '// Hello there ', - 'Line ends in whitespace. Consider deleting these extra spaces.' - ' [whitespace/end_of_line] [4]') + '// Hello there ', + 'Line ends in whitespace. Consider deleting these extra spaces.' + ' [whitespace/end_of_line] [4]', + ) self.TestLint('int a = (int)1.0;', '') self.TestLint(' weird opening space', '') finally: @@ -4500,9 +5178,10 @@ def testDefaultFilter(self): self.TestLint('// Hello there ', '') cpplint._cpplint_state.SetFilters('+whitespace/end_of_line') self.TestLint( - '// Hello there ', - 'Line ends in whitespace. Consider deleting these extra spaces.' - ' [whitespace/end_of_line] [4]') + '// Hello there ', + 'Line ends in whitespace. Consider deleting these extra spaces.' + ' [whitespace/end_of_line] [4]', + ) self.TestLint(' weird opening space', '') finally: cpplint._cpplint_state.filters = old_filters @@ -4519,62 +5198,72 @@ class Foo { };""" cpplint._cpplint_state.SetFilters('') self.TestMultiLineLint( - test_code, - ['Single-parameter constructors should be marked explicit.' + test_code, + [ + 'Single-parameter constructors should be marked explicit.' ' [runtime/explicit] [4]', '{ should almost always be at the end of the previous line' - ' [whitespace/braces] [4]'] - ) + ' [whitespace/braces] [4]', + ], + ) cpplint._cpplint_state.SetFilters('-runtime/explicit:foo.h') self.TestMultiLineLint( - test_code, - '{ should almost always be at the end of the previous line' - ' [whitespace/braces] [4]' - ) + test_code, + '{ should almost always be at the end of the previous line' + ' [whitespace/braces] [4]', + ) cpplint._cpplint_state.SetFilters('-runtime/explicit:foo.h:2') self.TestMultiLineLint( - test_code, - '{ should almost always be at the end of the previous line' - ' [whitespace/braces] [4]' - ) + test_code, + '{ should almost always be at the end of the previous line' + ' [whitespace/braces] [4]', + ) - cpplint._cpplint_state.SetFilters('-runtime/explicit:foo.h:14,-whitespace/braces:otherfile.h:3') + cpplint._cpplint_state.SetFilters( + '-runtime/explicit:foo.h:14,-whitespace/braces:otherfile.h:3' + ) self.TestMultiLineLint( - test_code, - ['Single-parameter constructors should be marked explicit.' + test_code, + [ + 'Single-parameter constructors should be marked explicit.' ' [runtime/explicit] [4]', '{ should almost always be at the end of the previous line' - ' [whitespace/braces] [4]'] - ) - - cpplint._cpplint_state.SetFilters('-runtime/explicit:foo.h:2,-whitespace/braces:foo.h:3') - self.TestMultiLineLint( - test_code, - '' - ) + ' [whitespace/braces] [4]', + ], + ) + + cpplint._cpplint_state.SetFilters( + '-runtime/explicit:foo.h:2,-whitespace/braces:foo.h:3' + ) + self.TestMultiLineLint(test_code, '') finally: cpplint._cpplint_state.filters = old_filters def testDuplicateHeader(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('path/self.cc', 'cc', - ['// Copyright 2014 Your Company. All Rights Reserved.', - '#include "path/self.h"', - '#include "path/duplicate.h"', - '#include "path/duplicate.h"', - '#ifdef MACRO', - '#include "path/unique.h"', - '#else', - '#include "path/unique.h"', - '#endif', - ''], - error_collector) + cpplint.ProcessFileData( + 'path/self.cc', + 'cc', + [ + '// Copyright 2014 Your Company. All Rights Reserved.', + '#include "path/self.h"', + '#include "path/duplicate.h"', + '#include "path/duplicate.h"', + '#ifdef MACRO', + '#include "path/unique.h"', + '#else', + '#include "path/unique.h"', + '#endif', + '', + ], + error_collector, + ) self.assertEqual( - ['"path/duplicate.h" already included at path/self.cc:3 ' - '[build/include] [4]'], - error_collector.ResultList()) + ['"path/duplicate.h" already included at path/self.cc:3 [build/include] [4]'], + error_collector.ResultList(), + ) def testUnnamedNamespacesInHeaders(self): for extension in ['h', 'hpp', 'hxx', 'h++', 'cuh']: @@ -4582,10 +5271,12 @@ def testUnnamedNamespacesInHeaders(self): def doTestUnnamedNamespacesInHeaders(self, extension): self.TestLanguageRulesCheck( - 'foo.' + extension, 'namespace {', - 'Do not use unnamed namespaces in header files. See' - ' https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' - ' for more information. [build/namespaces_headers] [4]') + 'foo.' + extension, + 'namespace {', + 'Do not use unnamed namespaces in header files. See' + ' https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' + ' for more information. [build/namespaces_headers] [4]', + ) # namespace registration macros are OK. self.TestLanguageRulesCheck('foo.' + extension, 'namespace { \\', '') # named namespaces are OK. @@ -4601,24 +5292,24 @@ def testBuildClass(self): # Test that the linter can parse to the end of class definitions, # and that it will report when it can't. # Don't warn on forward declarations of various types. + self.TestMultiLineLint('class Foo;', '') self.TestMultiLineLint( - 'class Foo;', - '') - self.TestMultiLineLint( - """struct Foo* + """struct Foo* foo = NewFoo();""", - '') + '', + ) # Test preprocessor. self.TestMultiLineLint( - """#ifdef DERIVE_FROM_GOO + """#ifdef DERIVE_FROM_GOO struct Foo : public Goo { #else struct Foo : public Hoo { #endif };""", - '') + '', + ) self.TestMultiLineLint( - """ + """ class Foo #ifdef DERIVE_FROM_GOO : public Goo { @@ -4626,24 +5317,28 @@ class Foo : public Hoo { #endif };""", - '') + '', + ) def testBuildEndComment(self): # The crosstool compiler we currently use will fail to compile the # code in this test, so we might consider removing the lint check. self.TestMultiLineLint( - """#if 0 + """#if 0 #endif Not a comment""", - 'Uncommented text after #endif is non-standard. Use a comment.' - ' [build/endif_comment] [5]') + 'Uncommented text after #endif is non-standard. Use a comment.' + ' [build/endif_comment] [5]', + ) def testBuildForwardDecl(self): # The crosstool compiler we currently use will fail to compile the # code in this test, so we might consider removing the lint check. - self.TestLint('class Foo::Goo;', - 'Inner-style forward declarations are invalid.' - ' Remove this line.' - ' [build/forward_decl] [5]') + self.TestLint( + 'class Foo::Goo;', + 'Inner-style forward declarations are invalid.' + ' Remove this line.' + ' [build/forward_decl] [5]', + ) def GetBuildHeaderGuardPreprocessorSymbol(self, file_path): # Figure out the expected header guard by processing an empty file. @@ -4651,9 +5346,8 @@ def GetBuildHeaderGuardPreprocessorSymbol(self, file_path): cpplint.ProcessFileData(file_path, 'h', [], error_collector) for error in error_collector.ResultList(): matched = re.search( - 'No #ifndef header guard found, suggested CPP variable is: ' - '([A-Z0-9_]+)', - error) + 'No #ifndef header guard found, suggested CPP variable is: ([A-Z0-9_]+)', error + ) if matched is not None: return matched.group(1) @@ -4666,115 +5360,145 @@ def testBuildHeaderGuard(self): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData(file_path, 'h', [], error_collector) self.assertEqual( - 1, - error_collector.ResultList().count( - 'No #ifndef header guard found, suggested CPP variable is: %s' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + 'No #ifndef header guard found, suggested CPP variable is: %s' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # No header guard, but the error is suppressed. error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['// Copyright 2014 Your Company.', - '// NOLINT(build/header_guard)', ''], - error_collector) + cpplint.ProcessFileData( + file_path, + 'h', + ['// Copyright 2014 Your Company.', '// NOLINT(build/header_guard)', ''], + error_collector, + ) self.assertEqual([], error_collector.ResultList()) # Wrong guard error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef FOO_H', '#define FOO_H'], error_collector) + cpplint.ProcessFileData( + file_path, 'h', ['#ifndef FOO_H', '#define FOO_H'], error_collector + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#ifndef header guard has wrong style, please use: %s' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#ifndef header guard has wrong style, please use: %s' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # No define error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef %s' % expected_guard], error_collector) + cpplint.ProcessFileData( + file_path, 'h', ['#ifndef %s' % expected_guard], error_collector + ) self.assertEqual( - 1, - error_collector.ResultList().count( - 'No #ifndef header guard found, suggested CPP variable is: %s' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + 'No #ifndef header guard found, suggested CPP variable is: %s' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # Mismatched define error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef %s' % expected_guard, - '#define FOO_H'], - error_collector) + cpplint.ProcessFileData( + file_path, 'h', ['#ifndef %s' % expected_guard, '#define FOO_H'], error_collector + ) self.assertEqual( - 1, - error_collector.ResultList().count( - 'No #ifndef header guard found, suggested CPP variable is: %s' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + 'No #ifndef header guard found, suggested CPP variable is: %s' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # No endif error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef %s' % expected_guard, - '#define %s' % expected_guard, - ''], - error_collector) + cpplint.ProcessFileData( + file_path, + 'h', + ['#ifndef %s' % expected_guard, '#define %s' % expected_guard, ''], + error_collector, + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#endif line should be "#endif // %s"' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#endif line should be "#endif // %s"' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # Commentless endif error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef %s' % expected_guard, - '#define %s' % expected_guard, - '#endif'], - error_collector) + cpplint.ProcessFileData( + file_path, + 'h', + ['#ifndef %s' % expected_guard, '#define %s' % expected_guard, '#endif'], + error_collector, + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#endif line should be "#endif // %s"' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#endif line should be "#endif // %s"' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # Commentless endif for old-style guard error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef %s_' % expected_guard, - '#define %s_' % expected_guard, - '#endif'], - error_collector) + cpplint.ProcessFileData( + file_path, + 'h', + ['#ifndef %s_' % expected_guard, '#define %s_' % expected_guard, '#endif'], + error_collector, + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#endif line should be "#endif // %s"' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#endif line should be "#endif // %s"' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # No header guard errors error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef %s' % expected_guard, - '#define %s' % expected_guard, - '#endif // %s' % expected_guard], - error_collector) + cpplint.ProcessFileData( + file_path, + 'h', + [ + '#ifndef %s' % expected_guard, + '#define %s' % expected_guard, + '#endif // %s' % expected_guard, + ], + error_collector, + ) for line in error_collector.ResultList(): if line.find('build/header_guard') != -1: self.fail('Unexpected error: %s' % line) # No header guard errors for old-style guard error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef %s_' % expected_guard, - '#define %s_' % expected_guard, - '#endif // %s_' % expected_guard], - error_collector) + cpplint.ProcessFileData( + file_path, + 'h', + [ + '#ifndef %s_' % expected_guard, + '#define %s_' % expected_guard, + '#endif // %s_' % expected_guard, + ], + error_collector, + ) for line in error_collector.ResultList(): if line.find('build/header_guard') != -1: self.fail('Unexpected error: %s' % line) @@ -4784,100 +5508,124 @@ def testBuildHeaderGuard(self): cpplint._cpplint_state.verbose_level = 0 # Warn on old-style guard if verbosity is 0. error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef %s_' % expected_guard, - '#define %s_' % expected_guard, - '#endif // %s_' % expected_guard], - error_collector) + cpplint.ProcessFileData( + file_path, + 'h', + [ + '#ifndef %s_' % expected_guard, + '#define %s_' % expected_guard, + '#endif // %s_' % expected_guard, + ], + error_collector, + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#ifndef header guard has wrong style, please use: %s' - ' [build/header_guard] [0]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#ifndef header guard has wrong style, please use: %s' + ' [build/header_guard] [0]' % expected_guard + ), + error_collector.ResultList(), + ) finally: cpplint._cpplint_state.verbose_level = old_verbose_level # Completely incorrect header guard error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef FOO', - '#define FOO', - '#endif // FOO'], - error_collector) + cpplint.ProcessFileData( + file_path, 'h', ['#ifndef FOO', '#define FOO', '#endif // FOO'], error_collector + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#ifndef header guard has wrong style, please use: %s' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#ifndef header guard has wrong style, please use: %s' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#endif line should be "#endif // %s"' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#endif line should be "#endif // %s"' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # incorrect header guard with nolint error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'h', - ['#ifndef FOO // NOLINT', - '#define FOO', - '#endif // FOO NOLINT'], - error_collector) - self.assertEqual( - 0, - error_collector.ResultList().count( - '#ifndef header guard has wrong style, please use: %s' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + cpplint.ProcessFileData( + file_path, + 'h', + ['#ifndef FOO // NOLINT', '#define FOO', '#endif // FOO NOLINT'], + error_collector, + ) self.assertEqual( - 0, - error_collector.ResultList().count( - '#endif line should be "#endif // %s"' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 0, + error_collector.ResultList().count( + '#ifndef header guard has wrong style, please use: %s' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) + self.assertEqual( + 0, + error_collector.ResultList().count( + '#endif line should be "#endif // %s"' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # Special case for flymake for test_file in ['mydir/foo_flymake.h', 'mydir/.flymake/foo.h']: error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(test_file, 'h', - ['// Copyright 2014 Your Company.', ''], - error_collector) + cpplint.ProcessFileData( + test_file, 'h', ['// Copyright 2014 Your Company.', ''], error_collector + ) self.assertEqual( - 1, - error_collector.ResultList().count( - 'No #ifndef header guard found, suggested CPP variable is: %s' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + 'No #ifndef header guard found, suggested CPP variable is: %s' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) # Cuda guard file_path = 'mydir/foo.cuh' expected_guard = self.GetBuildHeaderGuardPreprocessorSymbol(file_path) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData(file_path, 'cuh', - ['#ifndef FOO', - '#define FOO', - '#endif // FOO'], - error_collector) + cpplint.ProcessFileData( + file_path, + 'cuh', + ['#ifndef FOO', '#define FOO', '#endif // FOO'], + error_collector, + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#ifndef header guard has wrong style, please use: %s' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#ifndef header guard has wrong style, please use: %s' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) self.assertEqual( - 1, - error_collector.ResultList().count( - '#endif line should be "#endif // %s"' - ' [build/header_guard] [5]' % expected_guard), - error_collector.ResultList()) + 1, + error_collector.ResultList().count( + '#endif line should be "#endif // %s"' + ' [build/header_guard] [5]' % expected_guard + ), + error_collector.ResultList(), + ) def testPragmaOnce(self): error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData('mydir/foo.h', 'h', - ['// Copyright 2014 Your Company.', '#pragma once', ''], - error_collector) + cpplint.ProcessFileData( + 'mydir/foo.h', + 'h', + ['// Copyright 2014 Your Company.', '#pragma once', ''], + error_collector, + ) self.assertEqual([], error_collector.ResultList()) def testBuildHeaderGuardWithRoot(self): @@ -4893,11 +5641,9 @@ def testBuildHeaderGuardWithRoot(self): shutil.rmtree(temp_directory) def doTestBuildHeaderGuardWithRoot(self, header_directory): - # note: Tested file paths must be real, otherwise # the repository name lookup will fail. - file_path = os.path.join(header_directory, - 'cpplint_test_header.h') + file_path = os.path.join(header_directory, 'cpplint_test_header.h') open(file_path, 'a').close() file_info = cpplint.FileInfo(file_path) if file_info.FullName() == file_info.RepositoryName(): @@ -4909,8 +5655,9 @@ def doTestBuildHeaderGuardWithRoot(self, header_directory): # when the root directory of the repository is properly deduced. return - self.assertEqual('CPPLINT_CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'CPPLINT_CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(file_path) + ) # # test --root flags: # this changes the cpp header guard prefix @@ -4919,8 +5666,9 @@ def doTestBuildHeaderGuardWithRoot(self, header_directory): # left-strip the header guard by using a root dir inside of the repo dir. # relative directory cpplint._root = 'cpplint' - self.assertEqual('CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(file_path) + ) nested_header_directory = os.path.join(header_directory, "nested") nested_file_path = os.path.join(nested_header_directory, 'cpplint_test_header.h') @@ -4929,23 +5677,25 @@ def doTestBuildHeaderGuardWithRoot(self, header_directory): cpplint._root = os.path.join('cpplint', 'nested') actual = cpplint.GetHeaderGuardCPPVariable(nested_file_path) - self.assertEqual('CPPLINT_TEST_HEADER_H_', - actual) + self.assertEqual('CPPLINT_TEST_HEADER_H_', actual) # absolute directory # (note that CPPLINT.cfg root=setting is always made absolute) cpplint._root = header_directory - self.assertEqual('CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(file_path) + ) cpplint._root = nested_header_directory - self.assertEqual('CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(nested_file_path)) + self.assertEqual( + 'CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(nested_file_path) + ) # --root flag is ignored if an non-existent directory is specified. cpplint._root = 'NON_EXISTENT_DIR' - self.assertEqual('CPPLINT_CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'CPPLINT_CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(file_path) + ) # prepend to the header guard by using a root dir that is more outer # than the repo dir @@ -4961,8 +5711,10 @@ def doTestBuildHeaderGuardWithRoot(self, header_directory): # do not hardcode the 'styleguide' repository name, it could be anything. expected_prefix = re.sub(r'[^a-zA-Z0-9]', '_', styleguide_dir_name).upper() + '_' # do not have 'styleguide' repo in '/' - self.assertEqual('%sCPPLINT_CPPLINT_TEST_HEADER_H_' % (expected_prefix), - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + '%sCPPLINT_CPPLINT_TEST_HEADER_H_' % (expected_prefix), + cpplint.GetHeaderGuardCPPVariable(file_path), + ) # To run the 'relative path' tests, we must be in the directory of this test file. cur_dir = os.getcwd() @@ -4972,14 +5724,18 @@ def doTestBuildHeaderGuardWithRoot(self, header_directory): styleguide_rel_path = os.path.relpath(styleguide_path, this_files_path) # '..' cpplint._root = styleguide_rel_path - self.assertEqual('CPPLINT_CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'CPPLINT_CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(file_path) + ) - styleguide_rel_path = os.path.relpath(styleguide_parent_path, - this_files_path) # '../..' + styleguide_rel_path = os.path.relpath( + styleguide_parent_path, this_files_path + ) # '../..' cpplint._root = styleguide_rel_path - self.assertEqual('%sCPPLINT_CPPLINT_TEST_HEADER_H_' % (expected_prefix), - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + '%sCPPLINT_CPPLINT_TEST_HEADER_H_' % (expected_prefix), + cpplint.GetHeaderGuardCPPVariable(file_path), + ) cpplint._root = None @@ -5000,86 +5756,57 @@ def testIncludeItsHeader(self): os.chdir(temp_directory) error_collector = ErrorCollector(self.assertTrue) - cpplint.ProcessFileData( - 'test/foo.cc', 'cc', - [''], - error_collector) + cpplint.ProcessFileData('test/foo.cc', 'cc', [''], error_collector) if platform.system() == 'Windows': test_directory = test_directory.replace('\\', '/') expected = "{dir}/{fn}.cc should include its header file {dir}/{fn}.h [build/include] [5]".format( - fn="foo", - dir=test_directory) - self.assertEqual( - 1, - error_collector.Results().count(expected)) + fn="foo", dir=test_directory + ) + self.assertEqual(1, error_collector.Results().count(expected)) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'test/foo.cc', 'cc', - [r'#include "test/foo.h"', - '' - ], - error_collector) - self.assertEqual( - 0, - error_collector.Results().count(expected)) + 'test/foo.cc', 'cc', [r'#include "test/foo.h"', ''], error_collector + ) + self.assertEqual(0, error_collector.Results().count(expected)) # Unix directory aliases are not allowed, and should trigger the # "include itse header file" error error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'test/foo.cc', 'cc', - [r'#include "./test/foo.h"', - '' - ], - error_collector) + 'test/foo.cc', 'cc', [r'#include "./test/foo.h"', ''], error_collector + ) expected = "{dir}/{fn}.cc should include its header file {dir}/{fn}.h{unix_text} [build/include] [5]".format( - fn="foo", - dir=test_directory, - unix_text=". Relative paths like . and .. are not allowed.") - self.assertEqual( - 1, - error_collector.Results().count(expected)) + fn="foo", + dir=test_directory, + unix_text=". Relative paths like . and .. are not allowed.", + ) + self.assertEqual(1, error_collector.Results().count(expected)) # This should continue to work error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'test/Bar.cc', 'cc', - [r'#include "test/Bar.h"', - '' - ], - error_collector) + 'test/Bar.cc', 'cc', [r'#include "test/Bar.h"', ''], error_collector + ) expected = "{dir}/{fn}.cc should include its header file {dir}/{fn}.h [build/include] [5]".format( - fn="Bar", - dir=test_directory) - self.assertEqual( - 0, - error_collector.Results().count(expected)) + fn="Bar", dir=test_directory + ) + self.assertEqual(0, error_collector.Results().count(expected)) # Since Bar.cc & Bar.h look 3rd party-ish, it should be ok without the include dir error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'test/Bar.cc', 'cc', - [r'#include "Bar.h"', - '' - ], - error_collector) - self.assertEqual( - 0, - error_collector.Results().count(expected)) + 'test/Bar.cc', 'cc', [r'#include "Bar.h"', ''], error_collector + ) + self.assertEqual(0, error_collector.Results().count(expected)) # Test edge case in which multiple files have the same base name open(os.path.join(test_directory, 'foo.hpp'), 'a').close() cpplint.ProcessFileData( - 'test/foo.cc', 'cc', - [r'#include "foo.hpp"', - '' - ], - error_collector) - self.assertEqual( - 0, - error_collector.Results().count(expected)) + 'test/foo.cc', 'cc', [r'#include "foo.hpp"', ''], error_collector + ) + self.assertEqual(0, error_collector.Results().count(expected)) finally: # Restore previous CWD. @@ -5087,20 +5814,19 @@ def testIncludeItsHeader(self): shutil.rmtree(temp_directory) def testPathSplitToList(self): - self.assertEqual([''], - cpplint.PathSplitToList(os.path.join(''))) + self.assertEqual([''], cpplint.PathSplitToList(os.path.join(''))) - self.assertEqual(['.'], - cpplint.PathSplitToList(os.path.join('.'))) + self.assertEqual(['.'], cpplint.PathSplitToList(os.path.join('.'))) - self.assertEqual(['..'], - cpplint.PathSplitToList(os.path.join('..'))) + self.assertEqual(['..'], cpplint.PathSplitToList(os.path.join('..'))) - self.assertEqual(['..', 'a', 'b'], - cpplint.PathSplitToList(os.path.join('..', 'a', 'b'))) + self.assertEqual( + ['..', 'a', 'b'], cpplint.PathSplitToList(os.path.join('..', 'a', 'b')) + ) - self.assertEqual(['a', 'b', 'c', 'd'], - cpplint.PathSplitToList(os.path.join('a', 'b', 'c', 'd'))) + self.assertEqual( + ['a', 'b', 'c', 'd'], cpplint.PathSplitToList(os.path.join('a', 'b', 'c', 'd')) + ) def testBuildHeaderGuardWithRepository(self): temp_directory = os.path.realpath(tempfile.mkdtemp()) @@ -5123,32 +5849,41 @@ def testBuildHeaderGuardWithRepository(self): open(file_path, 'a').close() # search for .svn if _repository is not specified - self.assertEqual('TRUNK_CPPLINT_CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'TRUNK_CPPLINT_CPPLINT_TEST_HEADER_H_', + cpplint.GetHeaderGuardCPPVariable(file_path), + ) # use the provided repository root for header guards cpplint._repository = os.path.relpath(trunk_dir) - self.assertEqual('CPPLINT_CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'CPPLINT_CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(file_path) + ) cpplint._repository = os.path.abspath(trunk_dir) - self.assertEqual('CPPLINT_CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'CPPLINT_CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(file_path) + ) # ignore _repository if it doesn't exist cpplint._repository = os.path.join(temp_directory, 'NON_EXISTENT') - self.assertEqual('TRUNK_CPPLINT_CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'TRUNK_CPPLINT_CPPLINT_TEST_HEADER_H_', + cpplint.GetHeaderGuardCPPVariable(file_path), + ) # ignore _repository if it exists but file isn't in it cpplint._repository = os.path.relpath(temp_directory2) - self.assertEqual('TRUNK_CPPLINT_CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'TRUNK_CPPLINT_CPPLINT_TEST_HEADER_H_', + cpplint.GetHeaderGuardCPPVariable(file_path), + ) # _root should be relative to _repository cpplint._repository = os.path.relpath(trunk_dir) cpplint._root = 'cpplint' - self.assertEqual('CPPLINT_TEST_HEADER_H_', - cpplint.GetHeaderGuardCPPVariable(file_path)) + self.assertEqual( + 'CPPLINT_TEST_HEADER_H_', cpplint.GetHeaderGuardCPPVariable(file_path) + ) finally: os.chdir(current_directory) @@ -5159,116 +5894,143 @@ def testBuildHeaderGuardWithRepository(self): def testBuildInclude(self): # Test that include statements have slashes in them. - self.TestLint('#include "foo.h"', - 'Include the directory when naming header files' - ' [build/include_subdir] [4]') - self.TestLint('#include "bar.hh"', - 'Include the directory when naming header files' - ' [build/include_subdir] [4]') + self.TestLint( + '#include "foo.h"', + 'Include the directory when naming header files [build/include_subdir] [4]', + ) + self.TestLint( + '#include "bar.hh"', + 'Include the directory when naming header files [build/include_subdir] [4]', + ) self.TestLint('#include "baz.aa"', '') self.TestLint('#include "dir/foo.h"', '') self.TestLint('#include "Python.h"', '') self.TestLint('#include "lua.h"', '') def testHppInclude(self): - code = '\n'.join([ - '#include ', - '#include ' - ]) + code = '\n'.join(['#include ', '#include ']) self.TestLanguageRulesCheck('foo.h', code, '') def testBuildPrintfFormat(self): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - [r'printf("\%%d", value);', - r'snprintf(buffer, sizeof(buffer), "\[%d", value);', - r'fprintf(file, "\(%d", value);', - r'vsnprintf(buffer, sizeof(buffer), "\\\{%d", ap);'], - error_collector) + 'foo.cc', + 'cc', + [ + r'printf("\%%d", value);', + r'snprintf(buffer, sizeof(buffer), "\[%d", value);', + r'fprintf(file, "\(%d", value);', + r'vsnprintf(buffer, sizeof(buffer), "\\\{%d", ap);', + ], + error_collector, + ) self.assertEqual( - 4, - error_collector.Results().count( - '%, [, (, and { are undefined character escapes. Unescape them.' - ' [build/printf_format] [3]')) + 4, + error_collector.Results().count( + '%, [, (, and { are undefined character escapes. Unescape them.' + ' [build/printf_format] [3]' + ), + ) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - 'foo.cc', 'cc', - ['// Copyright 2014 Your Company.', - '#include ', - r'printf("\\%%%d", value);', - r'printf(R"(\[)");', - r'printf(R"(\[%s)", R"(\])");', - ''], - error_collector) + 'foo.cc', + 'cc', + [ + '// Copyright 2014 Your Company.', + '#include ', + r'printf("\\%%%d", value);', + r'printf(R"(\[)");', + r'printf(R"(\[%s)", R"(\])");', + '', + ], + error_collector, + ) self.assertEqual('', error_collector.Results()) def testRuntimePrintfFormat(self): self.TestLint( - r'fprintf(file, "%q", value);', - '%q in format strings is deprecated. Use %ll instead.' - ' [runtime/printf_format] [3]') + r'fprintf(file, "%q", value);', + '%q in format strings is deprecated. Use %ll instead.' + ' [runtime/printf_format] [3]', + ) self.TestLint( - r'aprintf(file, "The number is %12q", value);', - '%q in format strings is deprecated. Use %ll instead.' - ' [runtime/printf_format] [3]') + r'aprintf(file, "The number is %12q", value);', + '%q in format strings is deprecated. Use %ll instead.' + ' [runtime/printf_format] [3]', + ) self.TestLint( - r'printf(file, "The number is" "%-12q", value);', - '%q in format strings is deprecated. Use %ll instead.' - ' [runtime/printf_format] [3]') + r'printf(file, "The number is" "%-12q", value);', + '%q in format strings is deprecated. Use %ll instead.' + ' [runtime/printf_format] [3]', + ) self.TestLint( - r'printf(file, "The number is" "%+12q", value);', - '%q in format strings is deprecated. Use %ll instead.' - ' [runtime/printf_format] [3]') + r'printf(file, "The number is" "%+12q", value);', + '%q in format strings is deprecated. Use %ll instead.' + ' [runtime/printf_format] [3]', + ) self.TestLint( - r'printf(file, "The number is" "% 12q", value);', - '%q in format strings is deprecated. Use %ll instead.' - ' [runtime/printf_format] [3]') + r'printf(file, "The number is" "% 12q", value);', + '%q in format strings is deprecated. Use %ll instead.' + ' [runtime/printf_format] [3]', + ) self.TestLint( - r'snprintf(file, "Never mix %d and %1$d parameters!", value);', - '%N$ formats are unconventional. Try rewriting to avoid them.' - ' [runtime/printf_format] [2]') + r'snprintf(file, "Never mix %d and %1$d parameters!", value);', + '%N$ formats are unconventional. Try rewriting to avoid them.' + ' [runtime/printf_format] [2]', + ) def TestLintLogCodeOnError(self, code, expected_message): # Special TestLint which logs the input code on error. result = self.PerformSingleLineLint(code) if result != expected_message: - self.fail('For code: "%s"\nGot: "%s"\nExpected: "%s"' - % (code, result, expected_message)) + self.fail( + 'For code: "%s"\nGot: "%s"\nExpected: "%s"' % (code, result, expected_message) + ) def testBuildStorageClass(self): qualifiers = [None, 'const', 'volatile'] signs = [None, 'signed', 'unsigned'] - types = ['void', 'char', 'int', 'float', 'double', - 'schar', 'int8_t', 'uint8_t', 'int16_t', 'uint16_t', - 'int32_t', 'uint32_t', 'int64_t', 'uint64_t'] + types = [ + 'void', + 'char', + 'int', + 'float', + 'double', + 'schar', + 'int8_t', + 'uint8_t', + 'int16_t', + 'uint16_t', + 'int32_t', + 'uint32_t', + 'int64_t', + 'uint64_t', + ] storage_classes = ['extern', 'register', 'static', 'typedef'] build_storage_class_error_message = ( - 'Storage-class specifier (static, extern, typedef, etc) should be ' - 'at the beginning of the declaration. [build/storage_class] [5]') + 'Storage-class specifier (static, extern, typedef, etc) should be ' + 'at the beginning of the declaration. [build/storage_class] [5]' + ) # Some explicit cases. Legal in C++, deprecated in C99. - self.TestLint('const int static foo = 5;', - build_storage_class_error_message) + self.TestLint('const int static foo = 5;', build_storage_class_error_message) - self.TestLint('char static foo;', - build_storage_class_error_message) + self.TestLint('char static foo;', build_storage_class_error_message) - self.TestLint('double const static foo = 2.0;', - build_storage_class_error_message) + self.TestLint('double const static foo = 2.0;', build_storage_class_error_message) - self.TestLint('uint64_t typedef unsigned_long_long;', - build_storage_class_error_message) + self.TestLint( + 'uint64_t typedef unsigned_long_long;', build_storage_class_error_message + ) - self.TestLint('int register foo = 0;', - build_storage_class_error_message) + self.TestLint('int register foo = 0;', build_storage_class_error_message) # Since there are a very large number of possibilities, randomly # construct declarations. @@ -5277,8 +6039,11 @@ def testBuildStorageClass(self): random.seed(25) for unused_i in range(10): # Build up random list of non-storage-class declaration specs. - other_decl_specs = [random.choice(qualifiers), random.choice(signs), - random.choice(types)] + other_decl_specs = [ + random.choice(qualifiers), + random.choice(signs), + random.choice(types), + ] # remove None other_decl_specs = [x for x in other_decl_specs if x is not None] @@ -5288,24 +6053,25 @@ def testBuildStorageClass(self): # insert storage class after the first storage_class = random.choice(storage_classes) insertion_point = random.randint(1, len(other_decl_specs)) - decl_specs = (other_decl_specs[0:insertion_point] - + [storage_class] - + other_decl_specs[insertion_point:]) + decl_specs = ( + other_decl_specs[0:insertion_point] + + [storage_class] + + other_decl_specs[insertion_point:] + ) self.TestLintLogCodeOnError( - ' '.join(decl_specs) + ';', - build_storage_class_error_message) + ' '.join(decl_specs) + ';', build_storage_class_error_message + ) # but no error if storage class is first - self.TestLintLogCodeOnError( - storage_class + ' ' + ' '.join(other_decl_specs), - '') + self.TestLintLogCodeOnError(storage_class + ' ' + ' '.join(other_decl_specs), '') def testLegalCopyright(self): legal_copyright_message = ( - 'No copyright message found. ' - 'You should have a line: "Copyright [year] "' - ' [legal/copyright] [5]') + 'No copyright message found. ' + 'You should have a line: "Copyright [year] "' + ' [legal/copyright] [5]' + ) copyright_line = '// Copyright 2014 Google Inc. All Rights Reserved.' @@ -5314,18 +6080,16 @@ def testLegalCopyright(self): # There should be a copyright message in the first 10 lines error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData(file_path, 'cc', [], error_collector) - self.assertEqual( - 1, - error_collector.ResultList().count(legal_copyright_message)) + self.assertEqual(1, error_collector.ResultList().count(legal_copyright_message)) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - file_path, 'cc', - ['' for unused_i in range(10)] + [copyright_line], - error_collector) - self.assertEqual( - 1, - error_collector.ResultList().count(legal_copyright_message)) + file_path, + 'cc', + ['' for unused_i in range(10)] + [copyright_line], + error_collector, + ) + self.assertEqual(1, error_collector.ResultList().count(legal_copyright_message)) # Test that warning isn't issued if Copyright line appears early enough. error_collector = ErrorCollector(self.assertTrue) @@ -5336,25 +6100,29 @@ def testLegalCopyright(self): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( - file_path, 'cc', - ['' for unused_i in range(9)] + [copyright_line], - error_collector) + file_path, 'cc', ['' for unused_i in range(9)] + [copyright_line], error_collector + ) for message in error_collector.ResultList(): if message.find('legal/copyright') != -1: self.fail('Unexpected error: %s' % message) def testInvalidIncrement(self): - self.TestLint('*count++;', - 'Changing pointer instead of value (or unused value of ' - 'operator*). [runtime/invalid_increment] [5]') + self.TestLint( + '*count++;', + 'Changing pointer instead of value (or unused value of ' + 'operator*). [runtime/invalid_increment] [5]', + ) def testSnprintfSize(self): self.TestLint('vsnprintf(NULL, 0, format)', '') - self.TestLint('snprintf(fisk, 1, format)', - 'If you can, use sizeof(fisk) instead of 1 as the 2nd arg ' - 'to snprintf. [runtime/printf] [3]') -class CxxTest(CpplintTestBase): + self.TestLint( + 'snprintf(fisk, 1, format)', + 'If you can, use sizeof(fisk) instead of 1 as the 2nd arg ' + 'to snprintf. [runtime/printf] [3]', + ) + +class CxxTest(CpplintTestBase): def Helper(self, package, extension, lines, count): filename = package + '/foo.' + extension lines = lines[:] @@ -5384,58 +6152,58 @@ def TestCxxFeature(self, code, expected_error): self.assertEqual(expected_error, collector.Results()) def testBlockedHeaders(self): - self.TestCxxFeature('#include ', - ' is an unapproved C++11 header.' - ' [build/c++11] [5]') - self.TestCxxFeature('#include ', - ' is an unapproved C++11 header.' - ' [build/c++11] [5]') - self.TestCxxFeature('#include ', - ' is an unapproved C++17 header.' - ' [build/c++17] [5]') + self.TestCxxFeature( + '#include ', ' is an unapproved C++11 header. [build/c++11] [5]' + ) + self.TestCxxFeature( + '#include ', ' is an unapproved C++11 header. [build/c++11] [5]' + ) + self.TestCxxFeature( + '#include ', + ' is an unapproved C++17 header. [build/c++17] [5]', + ) def testExplicitMakePair(self): self.TestLint('make_pair', '') self.TestLint('make_pair(42, 42)', '') - self.TestLint('make_pair<', - 'For C++11-compatibility, omit template arguments from' - ' make_pair OR use pair directly OR if appropriate,' - ' construct a pair directly' - ' [build/explicit_make_pair] [4]') - self.TestLint('make_pair <', - 'For C++11-compatibility, omit template arguments from' - ' make_pair OR use pair directly OR if appropriate,' - ' construct a pair directly' - ' [build/explicit_make_pair] [4]') + self.TestLint( + 'make_pair<', + 'For C++11-compatibility, omit template arguments from' + ' make_pair OR use pair directly OR if appropriate,' + ' construct a pair directly' + ' [build/explicit_make_pair] [4]', + ) + self.TestLint( + 'make_pair <', + 'For C++11-compatibility, omit template arguments from' + ' make_pair OR use pair directly OR if appropriate,' + ' construct a pair directly' + ' [build/explicit_make_pair] [4]', + ) self.TestLint('my_make_pair', '') class CleansedLinesTest(unittest.TestCase): - def testInit(self): - lines = ['Line 1', - 'Line 2', - 'Line 3 // Comment test', - 'Line 4 /* Comment test */', - 'Line 5 "foo"'] + lines = [ + 'Line 1', + 'Line 2', + 'Line 3 // Comment test', + 'Line 4 /* Comment test */', + 'Line 5 "foo"', + ] clean_lines = cpplint.CleansedLines(lines) self.assertEqual(lines, clean_lines.raw_lines) self.assertEqual(5, clean_lines.NumLines()) - self.assertEqual(['Line 1', - 'Line 2', - 'Line 3', - 'Line 4', - 'Line 5 "foo"'], - clean_lines.lines) + self.assertEqual( + ['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5 "foo"'], clean_lines.lines + ) - self.assertEqual(['Line 1', - 'Line 2', - 'Line 3', - 'Line 4', - 'Line 5 ""'], - clean_lines.elided) + self.assertEqual( + ['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5 ""'], clean_lines.elided + ) def testInitEmpty(self): clean_lines = cpplint.CleansedLines([]) @@ -5444,24 +6212,24 @@ def testInitEmpty(self): def testCollapseStrings(self): collapse = cpplint.CleansedLines._CollapseStrings - self.assertEqual('""', collapse('""')) # "" (empty) - self.assertEqual('"""', collapse('"""')) # """ (bad) - self.assertEqual('""', collapse('"xyz"')) # "xyz" (string) - self.assertEqual('""', collapse('"\\\""')) # "\"" (string) - self.assertEqual('""', collapse('"\'"')) # "'" (string) - self.assertEqual('"\"', collapse('"\"')) # "\" (bad) - self.assertEqual('""', collapse('"\\\\"')) # "\\" (string) - self.assertEqual('"', collapse('"\\\\\\"')) # "\\\" (bad) - self.assertEqual('""', collapse('"\\\\\\\\"')) # "\\\\" (string) - - self.assertEqual('\'\'', collapse('\'\'')) # '' (empty) - self.assertEqual('\'\'', collapse('\'a\'')) # 'a' (char) - self.assertEqual('\'\'', collapse('\'\\\'\'')) # '\'' (char) - self.assertEqual('\'', collapse('\'\\\'')) # '\' (bad) - self.assertEqual('', collapse('\\012')) # '\012' (char) - self.assertEqual('', collapse('\\xfF0')) # '\xfF0' (char) - self.assertEqual('', collapse('\\n')) # '\n' (char) - self.assertEqual(r'\#', collapse('\\#')) # '\#' (bad) + self.assertEqual('""', collapse('""')) # "" (empty) + self.assertEqual('"""', collapse('"""')) # """ (bad) + self.assertEqual('""', collapse('"xyz"')) # "xyz" (string) + self.assertEqual('""', collapse('"\\""')) # "\"" (string) + self.assertEqual('""', collapse('"\'"')) # "'" (string) + self.assertEqual('""', collapse('""')) # "\" (bad) + self.assertEqual('""', collapse('"\\\\"')) # "\\" (string) + self.assertEqual('"', collapse('"\\\\\\"')) # "\\\" (bad) + self.assertEqual('""', collapse('"\\\\\\\\"')) # "\\\\" (string) + + self.assertEqual('\'\'', collapse('\'\'')) # '' (empty) + self.assertEqual('\'\'', collapse('\'a\'')) # 'a' (char) + self.assertEqual('\'\'', collapse('\'\\\'\'')) # '\'' (char) + self.assertEqual('\'', collapse('\'\\\'')) # '\' (bad) + self.assertEqual('', collapse('\\012')) # '\012' (char) + self.assertEqual('', collapse('\\xfF0')) # '\xfF0' (char) + self.assertEqual('', collapse('\\n')) # '\n' (char) + self.assertEqual(r'\#', collapse('\\#')) # '\#' (bad) self.assertEqual('"" + ""', collapse('"\'" + "\'"')) self.assertEqual("'', ''", collapse("'\"', '\"'")) @@ -5478,153 +6246,172 @@ def testCollapseStrings(self): self.assertEqual('0x.03p100', collapse('0x.0\'3p1\'0\'0')) self.assertEqual('123.45', collapse('1\'23.4\'5')) - self.assertEqual('StringReplace(body, "", "");', - collapse('StringReplace(body, "\\\\", "\\\\\\\\");')) - self.assertEqual('\'\' ""', - collapse('\'"\' "foo"')) + self.assertEqual( + 'StringReplace(body, "", "");', + collapse('StringReplace(body, "\\\\", "\\\\\\\\");'), + ) + self.assertEqual('\'\' ""', collapse('\'"\' "foo"')) class OrderOfIncludesTest(CpplintTestBase): - def setUp(self): CpplintTestBase.setUp(self) self.include_state = cpplint._IncludeState() os.path.abspath = lambda value: value def testCheckNextIncludeOrder_OtherThenCpp(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._OTHER_HEADER)) - self.assertEqual('Found C++ system header after other header', - self.include_state.CheckNextIncludeOrder( - cpplint._CPP_SYS_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._OTHER_HEADER) + ) + self.assertEqual( + 'Found C++ system header after other header', + self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER), + ) def testCheckNextIncludeOrder_CppThenC(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._CPP_SYS_HEADER)) - self.assertEqual('Found C system header after C++ system header', - self.include_state.CheckNextIncludeOrder( - cpplint._C_SYS_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) + ) + self.assertEqual( + 'Found C system header after C++ system header', + self.include_state.CheckNextIncludeOrder(cpplint._C_SYS_HEADER), + ) def testCheckNextIncludeOrder_OtherSysThenC(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._OTHER_SYS_HEADER)) - self.assertEqual('Found C system header after other system header', - self.include_state.CheckNextIncludeOrder( - cpplint._C_SYS_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER) + ) + self.assertEqual( + 'Found C system header after other system header', + self.include_state.CheckNextIncludeOrder(cpplint._C_SYS_HEADER), + ) def testCheckNextIncludeOrder_OtherSysThenCpp(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._OTHER_SYS_HEADER)) - self.assertEqual('Found C++ system header after other system header', - self.include_state.CheckNextIncludeOrder( - cpplint._CPP_SYS_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER) + ) + self.assertEqual( + 'Found C++ system header after other system header', + self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER), + ) def testCheckNextIncludeOrder_LikelyThenCpp(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._LIKELY_MY_HEADER)) - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._CPP_SYS_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._LIKELY_MY_HEADER) + ) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) + ) def testCheckNextIncludeOrder_PossibleThenCpp(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._POSSIBLE_MY_HEADER)) - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._CPP_SYS_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER) + ) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) + ) def testCheckNextIncludeOrder_CppThenLikely(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._CPP_SYS_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) + ) # This will eventually fail. - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._LIKELY_MY_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._LIKELY_MY_HEADER) + ) def testCheckNextIncludeOrder_CppThenPossible(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._CPP_SYS_HEADER)) - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._POSSIBLE_MY_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) + ) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER) + ) def testCheckNextIncludeOrder_CppThenOtherSys(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._CPP_SYS_HEADER)) - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._OTHER_SYS_HEADER)) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) + ) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER) + ) def testCheckNextIncludeOrder_OtherSysThenPossible(self): - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._OTHER_SYS_HEADER)) - self.assertEqual('', self.include_state.CheckNextIncludeOrder( - cpplint._POSSIBLE_MY_HEADER)) - + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER) + ) + self.assertEqual( + '', self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER) + ) def testClassifyInclude(self): file_info = cpplint.FileInfo classify_include = cpplint._ClassifyInclude - self.assertEqual(cpplint._C_SYS_HEADER, - classify_include(file_info('foo/foo.cc'), - 'stdio.h', - True)) - self.assertEqual(cpplint._C_SYS_HEADER, - classify_include(file_info('foo/foo.cc'), - 'sys/time.h', - True)) - self.assertEqual(cpplint._C_SYS_HEADER, - classify_include(file_info('foo/foo.cc'), - 'netipx/ipx.h', - True)) - self.assertEqual(cpplint._C_SYS_HEADER, - classify_include(file_info('foo/foo.cc'), - 'arpa/ftp.h', - True)) - self.assertEqual(cpplint._CPP_SYS_HEADER, - classify_include(file_info('foo/foo.cc'), - 'string', - True)) - self.assertEqual(cpplint._CPP_SYS_HEADER, - classify_include(file_info('foo/foo.cc'), - 'typeinfo', - True)) - self.assertEqual(cpplint._C_SYS_HEADER, - classify_include(file_info('foo/foo.cc'), - 'foo/foo.h', - True)) - self.assertEqual(cpplint._OTHER_SYS_HEADER, - classify_include(file_info('foo/foo.cc'), - 'foo/foo.h', - True, - "standardcfirst")) - self.assertEqual(cpplint._OTHER_HEADER, - classify_include(file_info('foo/foo.cc'), - 'string', - False)) - self.assertEqual(cpplint._OTHER_HEADER, - classify_include(file_info('foo/foo.cc'), - 'boost/any.hpp', - True)) - self.assertEqual(cpplint._OTHER_HEADER, - classify_include(file_info('foo/foo.hxx'), - 'boost/any.hpp', - True)) - self.assertEqual(cpplint._OTHER_HEADER, - classify_include(file_info('foo/foo.h++'), - 'boost/any.hpp', - True)) - self.assertEqual(cpplint._LIKELY_MY_HEADER, - classify_include(file_info('foo/foo.cc'), - 'foo/foo-inl.h', - False)) - self.assertEqual(cpplint._LIKELY_MY_HEADER, - classify_include(file_info('foo/internal/foo.cc'), - 'foo/public/foo.h', - False)) - self.assertEqual(cpplint._POSSIBLE_MY_HEADER, - classify_include(file_info('foo/internal/foo.cc'), - 'foo/other/public/foo.h', - False)) - self.assertEqual(cpplint._OTHER_HEADER, - classify_include(file_info('foo/internal/foo.cc'), - 'foo/other/public/foop.h', - False)) + self.assertEqual( + cpplint._C_SYS_HEADER, classify_include(file_info('foo/foo.cc'), 'stdio.h', True) + ) + self.assertEqual( + cpplint._C_SYS_HEADER, + classify_include(file_info('foo/foo.cc'), 'sys/time.h', True), + ) + self.assertEqual( + cpplint._C_SYS_HEADER, + classify_include(file_info('foo/foo.cc'), 'netipx/ipx.h', True), + ) + self.assertEqual( + cpplint._C_SYS_HEADER, + classify_include(file_info('foo/foo.cc'), 'arpa/ftp.h', True), + ) + self.assertEqual( + cpplint._CPP_SYS_HEADER, classify_include(file_info('foo/foo.cc'), 'string', True) + ) + self.assertEqual( + cpplint._CPP_SYS_HEADER, + classify_include(file_info('foo/foo.cc'), 'typeinfo', True), + ) + self.assertEqual( + cpplint._C_SYS_HEADER, + classify_include(file_info('foo/foo.cc'), 'foo/foo.h', True), + ) + self.assertEqual( + cpplint._OTHER_SYS_HEADER, + classify_include(file_info('foo/foo.cc'), 'foo/foo.h', True, "standardcfirst"), + ) + self.assertEqual( + cpplint._OTHER_HEADER, classify_include(file_info('foo/foo.cc'), 'string', False) + ) + self.assertEqual( + cpplint._OTHER_HEADER, + classify_include(file_info('foo/foo.cc'), 'boost/any.hpp', True), + ) + self.assertEqual( + cpplint._OTHER_HEADER, + classify_include(file_info('foo/foo.hxx'), 'boost/any.hpp', True), + ) + self.assertEqual( + cpplint._OTHER_HEADER, + classify_include(file_info('foo/foo.h++'), 'boost/any.hpp', True), + ) + self.assertEqual( + cpplint._LIKELY_MY_HEADER, + classify_include(file_info('foo/foo.cc'), 'foo/foo-inl.h', False), + ) + self.assertEqual( + cpplint._LIKELY_MY_HEADER, + classify_include(file_info('foo/internal/foo.cc'), 'foo/public/foo.h', False), + ) + self.assertEqual( + cpplint._POSSIBLE_MY_HEADER, + classify_include( + file_info('foo/internal/foo.cc'), 'foo/other/public/foo.h', False + ), + ) + self.assertEqual( + cpplint._OTHER_HEADER, + classify_include( + file_info('foo/internal/foo.cc'), 'foo/other/public/foop.h', False + ), + ) def testTryDropCommonSuffixes(self): cpplint._hpp_headers = set([]) @@ -5633,27 +6420,24 @@ def testTryDropCommonSuffixes(self): self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo-inl.hxx')) self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo-inl.h++')) self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo-inl.hpp')) - self.assertEqual('foo/bar/foo', - cpplint._DropCommonSuffixes('foo/bar/foo_inl.h')) + self.assertEqual('foo/bar/foo', cpplint._DropCommonSuffixes('foo/bar/foo_inl.h')) self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo.cc')) self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo.cxx')) self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo.c')) - self.assertEqual('foo/foo_unusualinternal', - cpplint._DropCommonSuffixes('foo/foo_unusualinternal.h')) - self.assertEqual('foo/foo_unusualinternal', - cpplint._DropCommonSuffixes('foo/foo_unusualinternal.hpp')) - self.assertEqual('', - cpplint._DropCommonSuffixes('_test.cc')) - self.assertEqual('', - cpplint._DropCommonSuffixes('_test.c')) - self.assertEqual('', - cpplint._DropCommonSuffixes('_test.c++')) - self.assertEqual('test', - cpplint._DropCommonSuffixes('test.c')) - self.assertEqual('test', - cpplint._DropCommonSuffixes('test.cc')) - self.assertEqual('test', - cpplint._DropCommonSuffixes('test.c++')) + self.assertEqual( + 'foo/foo_unusualinternal', + cpplint._DropCommonSuffixes('foo/foo_unusualinternal.h'), + ) + self.assertEqual( + 'foo/foo_unusualinternal', + cpplint._DropCommonSuffixes('foo/foo_unusualinternal.hpp'), + ) + self.assertEqual('', cpplint._DropCommonSuffixes('_test.cc')) + self.assertEqual('', cpplint._DropCommonSuffixes('_test.c')) + self.assertEqual('', cpplint._DropCommonSuffixes('_test.c++')) + self.assertEqual('test', cpplint._DropCommonSuffixes('test.c')) + self.assertEqual('test', cpplint._DropCommonSuffixes('test.cc')) + self.assertEqual('test', cpplint._DropCommonSuffixes('test.c++')) def testRegression(self): def Format(includes): @@ -5674,126 +6458,156 @@ def Format(includes): self.TestLanguageRulesCheck('foo/foo.cc', Format(['"bar/bar.h"']), '') # Test everything in a good and new order. - self.TestLanguageRulesCheck('foo/foo.cc', - Format(['"foo/foo.h"', - '"foo/foo-inl.h"', - '', - '', - '', - '"bar/bar-inl.h"', - '"bar/bar.h"']), - '') + self.TestLanguageRulesCheck( + 'foo/foo.cc', + Format( + [ + '"foo/foo.h"', + '"foo/foo-inl.h"', + '', + '', + '', + '"bar/bar-inl.h"', + '"bar/bar.h"', + ] + ), + '', + ) # Test bad orders. self.TestLanguageRulesCheck( - 'foo/foo.cc', - Format(['', '']), - 'Found C system header after C++ system header.' - ' Should be: foo.h, c system, c++ system, other.' - ' [build/include_order] [4]') + 'foo/foo.cc', + Format(['', '']), + 'Found C system header after C++ system header.' + ' Should be: foo.h, c system, c++ system, other.' + ' [build/include_order] [4]', + ) self.TestLanguageRulesCheck( - 'foo/foo.cc', - Format(['"foo/bar-inl.h"', - '"foo/foo-inl.h"']), - '') + 'foo/foo.cc', Format(['"foo/bar-inl.h"', '"foo/foo-inl.h"']), '' + ) self.TestLanguageRulesCheck( - 'foo/foo.cc', - Format(['"foo/e.h"', - '"foo/b.h"', # warning here (e>b) - '"foo/c.h"', - '"foo/d.h"', - '"foo/a.h"']), # warning here (d>a) - ['Include "foo/b.h" not in alphabetical order' - ' [build/include_alpha] [4]', - 'Include "foo/a.h" not in alphabetical order' - ' [build/include_alpha] [4]']) + 'foo/foo.cc', + Format( + [ + '"foo/e.h"', + '"foo/b.h"', # warning here (e>b) + '"foo/c.h"', + '"foo/d.h"', + '"foo/a.h"', + ] + ), # warning here (d>a) + [ + 'Include "foo/b.h" not in alphabetical order [build/include_alpha] [4]', + 'Include "foo/a.h" not in alphabetical order [build/include_alpha] [4]', + ], + ) # -inl.h headers are no longer special. - self.TestLanguageRulesCheck('foo/foo.cc', - Format(['"foo/foo-inl.h"', '']), - '') - self.TestLanguageRulesCheck('foo/foo.cc', - Format(['"foo/bar.h"', '"foo/bar-inl.h"']), - '') + self.TestLanguageRulesCheck( + 'foo/foo.cc', Format(['"foo/foo-inl.h"', '']), '' + ) + self.TestLanguageRulesCheck( + 'foo/foo.cc', Format(['"foo/bar.h"', '"foo/bar-inl.h"']), '' + ) # Test componentized header. OK to have my header in ../public dir. - self.TestLanguageRulesCheck('foo/internal/foo.cc', - Format(['"foo/public/foo.h"', '']), - '') + self.TestLanguageRulesCheck( + 'foo/internal/foo.cc', Format(['"foo/public/foo.h"', '']), '' + ) # OK to have my header in other dir (not stylistically, but # cpplint isn't as good as a human). - self.TestLanguageRulesCheck('foo/internal/foo.cc', - Format(['"foo/other/public/foo.h"', - '']), - '') - self.TestLanguageRulesCheck('foo/foo.cc', - Format(['"foo/foo.h"', - '', - '"base/google.h"', - '"base/flags.h"']), - 'Include "base/flags.h" not in alphabetical ' - 'order [build/include_alpha] [4]') + self.TestLanguageRulesCheck( + 'foo/internal/foo.cc', Format(['"foo/other/public/foo.h"', '']), '' + ) + self.TestLanguageRulesCheck( + 'foo/foo.cc', + Format(['"foo/foo.h"', '', '"base/google.h"', '"base/flags.h"']), + 'Include "base/flags.h" not in alphabetical order [build/include_alpha] [4]', + ) # According to the style, -inl.h should come before .h, but we don't # complain about that. - self.TestLanguageRulesCheck('foo/foo.cc', - Format(['"foo/foo-inl.h"', - '"foo/foo.h"', - '"base/google.h"', - '"base/google-inl.h"']), - '') + self.TestLanguageRulesCheck( + 'foo/foo.cc', + Format( + ['"foo/foo-inl.h"', '"foo/foo.h"', '"base/google.h"', '"base/google-inl.h"'] + ), + '', + ) # Allow project includes to be separated by blank lines - self.TestLanguageRulesCheck('a/a.cc', - Format(['"a/a.h"', - '', - '"base/google.h"', - '', - '"b/c.h"', - '', - 'MACRO', - '"a/b.h"']), - '') - self.TestLanguageRulesCheck('a/a.cc', - Format(['"a/a.h"', - '', - '"base/google.h"', - '"a/b.h"']), - 'Include "a/b.h" not in alphabetical ' - 'order [build/include_alpha] [4]') + self.TestLanguageRulesCheck( + 'a/a.cc', + Format( + [ + '"a/a.h"', + '', + '"base/google.h"', + '', + '"b/c.h"', + '', + 'MACRO', + '"a/b.h"', + ] + ), + '', + ) + self.TestLanguageRulesCheck( + 'a/a.cc', + Format(['"a/a.h"', '', '"base/google.h"', '"a/b.h"']), + 'Include "a/b.h" not in alphabetical order [build/include_alpha] [4]', + ) # Test conditional includes self.TestLanguageRulesCheck( - 'a/a.cc', - ''.join(['#include \n', - '#include "base/port.h"\n', - '#include \n']), - ('Found C++ system header after other header. ' - 'Should be: a.h, c system, c++ system, other. ' - '[build/include_order] [4]')) + 'a/a.cc', + ''.join( + [ + '#include \n', + '#include "base/port.h"\n', + '#include \n', + ] + ), + ( + 'Found C++ system header after other header. ' + 'Should be: a.h, c system, c++ system, other. ' + '[build/include_order] [4]' + ), + ) self.TestLanguageRulesCheck( - 'a/a.cc', - ''.join(['#include \n', - '#include "base/port.h"\n', - '#ifdef LANG_CXX11\n', - '#include \n', - '#endif // LANG_CXX11\n']), - '') + 'a/a.cc', + ''.join( + [ + '#include \n', + '#include "base/port.h"\n', + '#ifdef LANG_CXX11\n', + '#include \n', + '#endif // LANG_CXX11\n', + ] + ), + '', + ) self.TestLanguageRulesCheck( - 'a/a.cc', - ''.join(['#include \n', - '#ifdef LANG_CXX11\n', - '#include "base/port.h"\n', - '#include \n', - '#endif // LANG_CXX11\n']), - ('Found C++ system header after other header. ' - 'Should be: a.h, c system, c++ system, other. ' - '[build/include_order] [4]')) + 'a/a.cc', + ''.join( + [ + '#include \n', + '#ifdef LANG_CXX11\n', + '#include "base/port.h"\n', + '#include \n', + '#endif // LANG_CXX11\n', + ] + ), + ( + 'Found C++ system header after other header. ' + 'Should be: a.h, c system, c++ system, other. ' + '[build/include_order] [4]' + ), + ) # Third party headers are exempt from order checks - self.TestLanguageRulesCheck('foo/foo.cc', - Format(['', '"Python.h"', '']), - '') + self.TestLanguageRulesCheck( + 'foo/foo.cc', Format(['', '"Python.h"', '']), '' + ) class CheckForFunctionLengthsTest(CpplintTestBase): - def setUp(self): # Reducing these thresholds for the tests speeds up tests significantly. CpplintTestBase.setUp(self) @@ -5814,8 +6628,7 @@ def TestFunctionLengthsCheck(self, code, expected_message): code: C++ source code expected to generate a warning message. expected_message: Message expected to be generated by the C++ code. """ - self.assertEqual(expected_message, - self.PerformFunctionLengthsCheck(code)) + self.assertEqual(expected_message, self.PerformFunctionLengthsCheck(code)) def TriggerLines(self, error_level): """Return number of lines needed to trigger a function length warning. @@ -5848,12 +6661,14 @@ def TestFunctionLengthCheckDefinition(self, lines, error_level): """ trigger_level = self.TriggerLines(cpplint._VerboseLevel()) self.TestFunctionLengthsCheck( - 'void test(int x)' + self.FunctionBody(lines), - ('Small and focused functions are preferred: ' - 'test() has %d non-comment lines ' - '(error triggered by exceeding %d lines).' - ' [readability/fn_size] [%d]' - % (lines, trigger_level, error_level))) + 'void test(int x)' + self.FunctionBody(lines), + ( + 'Small and focused functions are preferred: ' + 'test() has %d non-comment lines ' + '(error triggered by exceeding %d lines).' + ' [readability/fn_size] [%d]' % (lines, trigger_level, error_level) + ), + ) def TestFunctionLengthCheckDefinitionOK(self, lines): """Generate shorter function definition and check no warning is produced. @@ -5861,9 +6676,7 @@ def TestFunctionLengthCheckDefinitionOK(self, lines): Args: lines: Number of lines to generate. """ - self.TestFunctionLengthsCheck( - 'void test(int x)' + self.FunctionBody(lines), - '') + self.TestFunctionLengthsCheck('void test(int x)' + self.FunctionBody(lines), '') def TestFunctionLengthCheckAtErrorLevel(self, error_level): """Generate and check function at the trigger level for --v setting. @@ -5871,8 +6684,7 @@ def TestFunctionLengthCheckAtErrorLevel(self, error_level): Args: error_level: --v setting for cpplint. """ - self.TestFunctionLengthCheckDefinition(self.TriggerLines(error_level), - error_level) + self.TestFunctionLengthCheckDefinition(self.TriggerLines(error_level), error_level) def TestFunctionLengthCheckBelowErrorLevel(self, error_level): """Generate and check function just below the trigger level for --v setting. @@ -5880,8 +6692,9 @@ def TestFunctionLengthCheckBelowErrorLevel(self, error_level): Args: error_level: --v setting for cpplint. """ - self.TestFunctionLengthCheckDefinition(self.TriggerLines(error_level)-1, - error_level-1) + self.TestFunctionLengthCheckDefinition( + self.TriggerLines(error_level) - 1, error_level - 1 + ) def TestFunctionLengthCheckAboveErrorLevel(self, error_level): """Generate and check function just above the trigger level for --v setting. @@ -5889,49 +6702,49 @@ def TestFunctionLengthCheckAboveErrorLevel(self, error_level): Args: error_level: --v setting for cpplint. """ - self.TestFunctionLengthCheckDefinition(self.TriggerLines(error_level)+1, - error_level) + self.TestFunctionLengthCheckDefinition( + self.TriggerLines(error_level) + 1, error_level + ) def FunctionBody(self, number_of_lines): - return ' {\n' + ' this_is_just_a_test();\n'*number_of_lines + '}' + return ' {\n' + ' this_is_just_a_test();\n' * number_of_lines + '}' def FunctionBodyWithBlankLines(self, number_of_lines): - return ' {\n' + ' this_is_just_a_test();\n\n'*number_of_lines + '}' + return ' {\n' + ' this_is_just_a_test();\n\n' * number_of_lines + '}' def FunctionBodyWithNoLints(self, number_of_lines): - return (' {\n' + - ' this_is_just_a_test(); // NOLINT\n'*number_of_lines + '}') + return ' {\n' + ' this_is_just_a_test(); // NOLINT\n' * number_of_lines + '}' # Test line length checks. def testFunctionLengthCheckDeclaration(self): self.TestFunctionLengthsCheck( - 'void test();', # Not a function definition - '') + 'void test();', # Not a function definition + '', + ) def testFunctionLengthCheckDeclarationWithBlockFollowing(self): self.TestFunctionLengthsCheck( - ('void test();\n' - + self.FunctionBody(66)), # Not a function definition - '') + ('void test();\n' + self.FunctionBody(66)), # Not a function definition + '', + ) def testFunctionLengthCheckClassDefinition(self): self.TestFunctionLengthsCheck( # Not a function definition - 'class Test' + self.FunctionBody(66) + ';', - '') + 'class Test' + self.FunctionBody(66) + ';', '' + ) def testFunctionLengthCheckTrivial(self): self.TestFunctionLengthsCheck( - 'void test() {}', # Not counted - '') + 'void test() {}', # Not counted + '', + ) def testFunctionLengthCheckEmpty(self): - self.TestFunctionLengthsCheck( - 'void test() {\n}', - '') + self.TestFunctionLengthsCheck('void test() {\n}', '') def testFunctionLengthCheckDefinitionBelowSeverity0(self): old_verbosity = cpplint._SetVerboseLevel(0) - self.TestFunctionLengthCheckDefinitionOK(self.TriggerLines(0)-1) + self.TestFunctionLengthCheckDefinitionOK(self.TriggerLines(0) - 1) cpplint._SetVerboseLevel(old_verbosity) def testFunctionLengthCheckDefinitionAtSeverity0(self): @@ -5955,7 +6768,7 @@ def testFunctionLengthCheckDefinitionAtSeverity1v0(self): cpplint._SetVerboseLevel(old_verbosity) def testFunctionLengthCheckDefinitionBelowSeverity1(self): - self.TestFunctionLengthCheckDefinitionOK(self.TriggerLines(1)-1) + self.TestFunctionLengthCheckDefinitionOK(self.TriggerLines(1) - 1) def testFunctionLengthCheckDefinitionAtSeverity1(self): self.TestFunctionLengthCheckDefinitionOK(self.TriggerLines(1)) @@ -5968,85 +6781,110 @@ def testFunctionLengthCheckDefinitionSeverity1PlusBlanks(self): error_lines = self.TriggerLines(error_level) + 1 trigger_level = self.TriggerLines(cpplint._VerboseLevel()) self.TestFunctionLengthsCheck( - 'void test_blanks(int x)' + self.FunctionBody(error_lines), - ('Small and focused functions are preferred: ' - 'test_blanks() has %d non-comment lines ' - '(error triggered by exceeding %d lines).' - ' [readability/fn_size] [%d]') - % (error_lines, trigger_level, error_level)) + 'void test_blanks(int x)' + self.FunctionBody(error_lines), + ( + 'Small and focused functions are preferred: ' + 'test_blanks() has %d non-comment lines ' + '(error triggered by exceeding %d lines).' + ' [readability/fn_size] [%d]' + ) + % (error_lines, trigger_level, error_level), + ) def testFunctionLengthCheckComplexDefinitionSeverity1(self): error_level = 1 error_lines = self.TriggerLines(error_level) + 1 trigger_level = self.TriggerLines(cpplint._VerboseLevel()) self.TestFunctionLengthsCheck( - ('my_namespace::my_other_namespace::MyVeryLongTypeName*\n' - 'my_namespace::my_other_namespace::MyFunction(int arg1, char* arg2)' - + self.FunctionBody(error_lines)), - ('Small and focused functions are preferred: ' - 'my_namespace::my_other_namespace::MyFunction()' - ' has %d non-comment lines ' - '(error triggered by exceeding %d lines).' - ' [readability/fn_size] [%d]') - % (error_lines, trigger_level, error_level)) + ( + 'my_namespace::my_other_namespace::MyVeryLongTypeName*\n' + 'my_namespace::my_other_namespace::MyFunction(int arg1, char* arg2)' + + self.FunctionBody(error_lines) + ), + ( + 'Small and focused functions are preferred: ' + 'my_namespace::my_other_namespace::MyFunction()' + ' has %d non-comment lines ' + '(error triggered by exceeding %d lines).' + ' [readability/fn_size] [%d]' + ) + % (error_lines, trigger_level, error_level), + ) def testFunctionLengthCheckDefinitionSeverity1ForTest(self): error_level = 1 error_lines = self.TestLines(error_level) + 1 trigger_level = self.TestLines(cpplint._VerboseLevel()) self.TestFunctionLengthsCheck( - 'TEST_F(Test, Mutator)' + self.FunctionBody(error_lines), - ('Small and focused functions are preferred: ' - 'TEST_F(Test, Mutator) has %d non-comment lines ' - '(error triggered by exceeding %d lines).' - ' [readability/fn_size] [%d]') - % (error_lines, trigger_level, error_level)) + 'TEST_F(Test, Mutator)' + self.FunctionBody(error_lines), + ( + 'Small and focused functions are preferred: ' + 'TEST_F(Test, Mutator) has %d non-comment lines ' + '(error triggered by exceeding %d lines).' + ' [readability/fn_size] [%d]' + ) + % (error_lines, trigger_level, error_level), + ) def testFunctionLengthCheckDefinitionSeverity1ForSplitLineTest(self): error_level = 1 error_lines = self.TestLines(error_level) + 1 trigger_level = self.TestLines(cpplint._VerboseLevel()) self.TestFunctionLengthsCheck( - ('TEST_F(GoogleUpdateRecoveryRegistryProtectedTest,\n' - ' FixGoogleUpdate_AllValues_MachineApp)' # note: 4 spaces - + self.FunctionBody(error_lines)), - ('Small and focused functions are preferred: ' - 'TEST_F(GoogleUpdateRecoveryRegistryProtectedTest, ' # 1 space - 'FixGoogleUpdate_AllValues_MachineApp) has %d non-comment lines ' - '(error triggered by exceeding %d lines).' - ' [readability/fn_size] [%d]') - % (error_lines+1, trigger_level, error_level)) + ( + 'TEST_F(GoogleUpdateRecoveryRegistryProtectedTest,\n' + ' FixGoogleUpdate_AllValues_MachineApp)' # note: 4 spaces + + self.FunctionBody(error_lines) + ), + ( + 'Small and focused functions are preferred: ' + 'TEST_F(GoogleUpdateRecoveryRegistryProtectedTest, ' # 1 space + 'FixGoogleUpdate_AllValues_MachineApp) has %d non-comment lines ' + '(error triggered by exceeding %d lines).' + ' [readability/fn_size] [%d]' + ) + % (error_lines + 1, trigger_level, error_level), + ) def testFunctionLengthCheckDefinitionSeverity1ForBadTestDoesntBreak(self): error_level = 1 error_lines = self.TestLines(error_level) + 1 trigger_level = self.TestLines(cpplint._VerboseLevel()) self.TestFunctionLengthsCheck( - ('TEST_F(' - + self.FunctionBody(error_lines)), - ('Small and focused functions are preferred: ' - 'TEST_F has %d non-comment lines ' - '(error triggered by exceeding %d lines).' - ' [readability/fn_size] [%d]') - % (error_lines, trigger_level, error_level)) + ('TEST_F(' + self.FunctionBody(error_lines)), + ( + 'Small and focused functions are preferred: ' + 'TEST_F has %d non-comment lines ' + '(error triggered by exceeding %d lines).' + ' [readability/fn_size] [%d]' + ) + % (error_lines, trigger_level, error_level), + ) def testFunctionLengthCheckDefinitionSeverity1WithEmbeddedNoLints(self): error_level = 1 - error_lines = self.TriggerLines(error_level)+1 + error_lines = self.TriggerLines(error_level) + 1 trigger_level = self.TriggerLines(cpplint._VerboseLevel()) self.TestFunctionLengthsCheck( - 'void test(int x)' + self.FunctionBodyWithNoLints(error_lines), - ('Small and focused functions are preferred: ' - 'test() has %d non-comment lines ' - '(error triggered by exceeding %d lines).' - ' [readability/fn_size] [%d]') - % (error_lines, trigger_level, error_level)) + 'void test(int x)' + self.FunctionBodyWithNoLints(error_lines), + ( + 'Small and focused functions are preferred: ' + 'test() has %d non-comment lines ' + '(error triggered by exceeding %d lines).' + ' [readability/fn_size] [%d]' + ) + % (error_lines, trigger_level, error_level), + ) def testFunctionLengthCheckDefinitionSeverity1WithNoLint(self): self.TestFunctionLengthsCheck( - ('void test(int x)' + self.FunctionBody(self.TriggerLines(1)) - + ' // NOLINT -- long function'), - '') + ( + 'void test(int x)' + + self.FunctionBody(self.TriggerLines(1)) + + ' // NOLINT -- long function' + ), + '', + ) def testFunctionLengthCheckDefinitionBelowSeverity2(self): self.TestFunctionLengthCheckBelowErrorLevel(2) @@ -6090,32 +6928,31 @@ def testFunctionLengthCheckDefinitionHugeLines(self): def testFunctionLengthNotDeterminable(self): # Macro invocation without terminating semicolon. - self.TestFunctionLengthsCheck( - 'MACRO(arg)', - '') + self.TestFunctionLengthsCheck('MACRO(arg)', '') # Macro with underscores - self.TestFunctionLengthsCheck( - 'MACRO_WITH_UNDERSCORES(arg1, arg2, arg3)', - '') + self.TestFunctionLengthsCheck('MACRO_WITH_UNDERSCORES(arg1, arg2, arg3)', '') self.TestFunctionLengthsCheck( - 'NonMacro(arg)', - 'Lint failed to find start of function body.' - ' [readability/fn_size] [5]') + 'NonMacro(arg)', + 'Lint failed to find start of function body. [readability/fn_size] [5]', + ) def testFunctionLengthCheckWithNamespace(self): old_verbosity = cpplint._SetVerboseLevel(1) self.TestFunctionLengthsCheck( - ('namespace {\n' - 'void CodeCoverageCL35256059() {\n' + - (' X++;\n' * 3000) + - '}\n' - '} // namespace\n'), - ('Small and focused functions are preferred: ' - 'CodeCoverageCL35256059() has 3000 non-comment lines ' - '(error triggered by exceeding 20 lines).' - ' [readability/fn_size] [5]')) + ( + 'namespace {\n' + 'void CodeCoverageCL35256059() {\n' + (' X++;\n' * 3000) + '}\n' + '} // namespace\n' + ), + ( + 'Small and focused functions are preferred: ' + 'CodeCoverageCL35256059() has 3000 non-comment lines ' + '(error triggered by exceeding 20 lines).' + ' [readability/fn_size] [5]' + ), + ) cpplint._SetVerboseLevel(old_verbosity) @@ -6139,57 +6976,63 @@ def CountLeadingWhitespace(s): break count += 1 return count + # find the minimum indent (except for blank lines) - min_indent = min([CountLeadingWhitespace(line) - for line in text_block.split('\n') if line]) + min_indent = min( + [CountLeadingWhitespace(line) for line in text_block.split('\n') if line] + ) return '\n'.join([line[min_indent:] for line in text_block.split('\n')]) class CloseExpressionTest(unittest.TestCase): - def setUp(self): self.lines = cpplint.CleansedLines( - # 1 2 3 4 5 - # 0123456789012345678901234567890123456789012345678901234567890 - ['// Line 0', - 'inline RCULocked::ReadPtr::ReadPtr(const RCULocked* rcu) {', - ' DCHECK(!(data & kFlagMask)) << "Error";', - '}', - '// Line 4', - 'RCULocked::WritePtr::WritePtr(RCULocked* rcu)', - ' : lock_(&rcu_->mutex_) {', - '}', - '// Line 8', - 'template ', - 'typename std::enable_if<', - ' std::is_array::value && (std::extent::value > 0)>::type', - 'MakeUnique(A&&... a) = delete;', - '// Line 13', - 'auto x = []() {};', - '// Line 15', - 'template ', - 'friend bool operator==(const reffed_ptr& a,', - ' const reffed_ptr& b) {', - ' return a.get() == b.get();', - '}', - '// Line 21']) + # 1 2 3 4 5 + # 0123456789012345678901234567890123456789012345678901234567890 + [ + '// Line 0', + 'inline RCULocked::ReadPtr::ReadPtr(const RCULocked* rcu) {', + ' DCHECK(!(data & kFlagMask)) << "Error";', + '}', + '// Line 4', + 'RCULocked::WritePtr::WritePtr(RCULocked* rcu)', + ' : lock_(&rcu_->mutex_) {', + '}', + '// Line 8', + 'template ', + 'typename std::enable_if<', + ' std::is_array::value && (std::extent::value > 0)>::type', + 'MakeUnique(A&&... a) = delete;', + '// Line 13', + 'auto x = []() {};', + '// Line 15', + 'template ', + 'friend bool operator==(const reffed_ptr& a,', + ' const reffed_ptr& b) {', + ' return a.get() == b.get();', + '}', + '// Line 21', + ] + ) def testCloseExpression(self): # List of positions to test: # (start line, start position, end line, end position + 1) - positions = [(1, 16, 1, 19), - (1, 37, 1, 59), - (1, 60, 3, 1), - (2, 8, 2, 29), - (2, 30, 22, -1), # Left shift operator - (9, 9, 9, 36), - (10, 23, 11, 59), - (11, 54, 22, -1), # Greater than operator - (14, 9, 14, 11), - (14, 11, 14, 13), - (14, 14, 14, 16), - (17, 22, 18, 46), - (18, 47, 20, 1)] + positions = [ + (1, 16, 1, 19), + (1, 37, 1, 59), + (1, 60, 3, 1), + (2, 8, 2, 29), + (2, 30, 22, -1), # Left shift operator + (9, 9, 9, 36), + (10, 23, 11, 59), + (11, 54, 22, -1), # Greater than operator + (14, 9, 14, 11), + (14, 11, 14, 13), + (14, 14, 14, 16), + (17, 22, 18, 46), + (18, 47, 20, 1), + ] for p in positions: (_, line, column) = cpplint.CloseExpression(self.lines, p[0], p[1]) self.assertEqual((p[2], p[3]), (line, column)) @@ -6197,26 +7040,27 @@ def testCloseExpression(self): def testReverseCloseExpression(self): # List of positions to test: # (end line, end position, start line, start position) - positions = [(1, 18, 1, 16), - (1, 58, 1, 37), - (2, 27, 2, 10), - (2, 28, 2, 8), - (6, 18, 0, -1), # -> operator - (9, 35, 9, 9), - (11, 54, 0, -1), # Greater than operator - (11, 57, 11, 31), - (14, 10, 14, 9), - (14, 12, 14, 11), - (14, 15, 14, 14), - (18, 45, 17, 22), - (20, 0, 18, 47)] + positions = [ + (1, 18, 1, 16), + (1, 58, 1, 37), + (2, 27, 2, 10), + (2, 28, 2, 8), + (6, 18, 0, -1), # -> operator + (9, 35, 9, 9), + (11, 54, 0, -1), # Greater than operator + (11, 57, 11, 31), + (14, 10, 14, 9), + (14, 12, 14, 11), + (14, 15, 14, 14), + (18, 45, 17, 22), + (20, 0, 18, 47), + ] for p in positions: (_, line, column) = cpplint.ReverseCloseExpression(self.lines, p[0], p[1]) self.assertEqual((p[2], p[3]), (line, column)) class NestingStateTest(unittest.TestCase): - def setUp(self): self.nesting_state = cpplint.NestingState() self.error_collector = ErrorCollector(self.assertTrue) @@ -6224,8 +7068,7 @@ def setUp(self): def UpdateWithLines(self, lines): clean_lines = cpplint.CleansedLines(lines) for line in range(clean_lines.NumLines()): - self.nesting_state.Update('test.cc', - clean_lines, line, self.error_collector) + self.nesting_state.Update('test.cc', clean_lines, line, self.error_collector) def testEmpty(self): self.UpdateWithLines([]) @@ -6234,8 +7077,7 @@ def testEmpty(self): def testNamespace(self): self.UpdateWithLines(['namespace {']) self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], - cpplint._NamespaceInfo)) + self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._NamespaceInfo)) self.assertTrue(self.nesting_state.stack[0].seen_open_brace) self.assertEqual(self.nesting_state.stack[0].name, '') @@ -6282,23 +7124,19 @@ def testClass(self): self.assertFalse(self.nesting_state.stack[0].is_derived) self.assertEqual(self.nesting_state.stack[0].class_indent, 0) - self.UpdateWithLines(['};', - 'struct B : public A {']) + self.UpdateWithLines(['};', 'struct B : public A {']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) self.assertEqual(self.nesting_state.stack[0].name, 'B') self.assertTrue(self.nesting_state.stack[0].is_derived) - self.UpdateWithLines(['};', - 'class C', - ': public A {']) + self.UpdateWithLines(['};', 'class C', ': public A {']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) self.assertEqual(self.nesting_state.stack[0].name, 'C') self.assertTrue(self.nesting_state.stack[0].is_derived) - self.UpdateWithLines(['};', - 'template']) + self.UpdateWithLines(['};', 'template']) self.assertEqual(len(self.nesting_state.stack), 0) self.UpdateWithLines(['class D {', ' class E {']) @@ -6350,11 +7188,9 @@ def testStruct(self): self.assertEqual(self.nesting_state.stack[0].name, 'A') self.assertFalse(self.nesting_state.stack[0].is_derived) - self.UpdateWithLines(['}', - 'void Func(struct B arg) {']) + self.UpdateWithLines(['}', 'void Func(struct B arg) {']) self.assertEqual(len(self.nesting_state.stack), 1) - self.assertFalse(isinstance(self.nesting_state.stack[0], - cpplint._ClassInfo)) + self.assertFalse(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) self.UpdateWithLines(['}']) self.assertEqual(len(self.nesting_state.stack), 0) @@ -6379,13 +7215,17 @@ def testPreprocessor(self): self.UpdateWithLines(['#endif']) self.assertEqual(len(self.nesting_state.pp_stack), 0) - self.UpdateWithLines(['#ifdef MACRO5', - 'class A {', - '#elif MACRO6', - 'class B {', - '#else', - 'class C {', - '#endif']) + self.UpdateWithLines( + [ + '#ifdef MACRO5', + 'class A {', + '#elif MACRO6', + 'class B {', + '#else', + 'class C {', + '#endif', + ] + ) self.assertEqual(len(self.nesting_state.pp_stack), 0) self.assertEqual(len(self.nesting_state.stack), 1) self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) @@ -6393,23 +7233,20 @@ def testPreprocessor(self): self.UpdateWithLines(['};']) self.assertEqual(len(self.nesting_state.stack), 0) - self.UpdateWithLines(['class D', - '#ifdef MACRO7']) + self.UpdateWithLines(['class D', '#ifdef MACRO7']) self.assertEqual(len(self.nesting_state.pp_stack), 1) self.assertEqual(len(self.nesting_state.stack), 1) self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) self.assertEqual(self.nesting_state.stack[0].name, 'D') self.assertFalse(self.nesting_state.stack[0].is_derived) - self.UpdateWithLines(['#elif MACRO8', - ': public E']) + self.UpdateWithLines(['#elif MACRO8', ': public E']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[0].name, 'D') self.assertTrue(self.nesting_state.stack[0].is_derived) self.assertFalse(self.nesting_state.stack[0].seen_open_brace) - self.UpdateWithLines(['#else', - '{']) + self.UpdateWithLines(['#else', '{']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[0].name, 'D') self.assertFalse(self.nesting_state.stack[0].is_derived) @@ -6426,18 +7263,16 @@ def testPreprocessor(self): self.assertEqual(len(self.nesting_state.stack), 0) def testTemplate(self): - self.UpdateWithLines(['template >']) + self.UpdateWithLines(['template >']) self.assertEqual(len(self.nesting_state.stack), 0) self.UpdateWithLines(['class A {']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) self.assertEqual(self.nesting_state.stack[0].name, 'A') - self.UpdateWithLines(['};', - 'template class B>', - 'class C']) + self.UpdateWithLines( + ['};', 'template class B>', 'class C'] + ) self.assertEqual(len(self.nesting_state.stack), 1) self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) self.assertEqual(self.nesting_state.stack[0].name, 'C') @@ -6452,35 +7287,40 @@ def testTemplate(self): self.UpdateWithLines(['{', '};']) self.assertEqual(len(self.nesting_state.stack), 0) - self.UpdateWithLines(['template ', - 'static void Func() {']) + self.UpdateWithLines( + [ + 'template ', + 'static void Func() {', + ] + ) self.assertEqual(len(self.nesting_state.stack), 1) - self.assertFalse(isinstance(self.nesting_state.stack[0], - cpplint._ClassInfo)) - self.UpdateWithLines(['}', - 'template class K {']) + self.assertFalse(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) + self.UpdateWithLines(['}', 'template class K {']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) self.assertEqual(self.nesting_state.stack[0].name, 'K') def testTemplateDefaultArg(self): - self.UpdateWithLines([ - 'template > class unique_ptr {']) + self.UpdateWithLines( + ['template > class unique_ptr {'] + ) self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(self.nesting_state.stack[0], isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) + self.assertTrue( + self.nesting_state.stack[0], + isinstance(self.nesting_state.stack[0], cpplint._ClassInfo), + ) def testTemplateInnerClass(self): - self.UpdateWithLines(['class A {', - ' public:']) + self.UpdateWithLines(['class A {', ' public:']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.UpdateWithLines([' template ', - ' class C >', - ' : public A {']) + self.UpdateWithLines( + [' template ', ' class C >', ' : public A {'] + ) self.assertEqual(len(self.nesting_state.stack), 2) self.assertTrue(isinstance(self.nesting_state.stack[1], cpplint._ClassInfo)) @@ -6491,8 +7331,7 @@ def testArguments(self): self.assertEqual(self.nesting_state.stack[0].name, 'A') self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) - self.UpdateWithLines([' void Func(', - ' struct X arg1,']) + self.UpdateWithLines([' void Func(', ' struct X arg1,']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) self.UpdateWithLines([' struct X *arg2);']) @@ -6507,17 +7346,14 @@ def testArguments(self): self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) self.assertEqual(self.nesting_state.stack[0].name, 'B') - self.UpdateWithLines(['#ifdef MACRO', - ' void Func(', - ' struct X arg1']) + self.UpdateWithLines(['#ifdef MACRO', ' void Func(', ' struct X arg1']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) self.UpdateWithLines(['#else']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) - self.UpdateWithLines([' void Func(', - ' struct X arg1']) + self.UpdateWithLines([' void Func(', ' struct X arg1']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) @@ -6532,8 +7368,12 @@ def testArguments(self): self.assertEqual(len(self.nesting_state.stack), 0) def testInlineAssembly(self): - self.UpdateWithLines(['void CopyRow_SSE2(const uint8_t* src, uint8_t* dst,', - ' int count) {']) + self.UpdateWithLines( + [ + 'void CopyRow_SSE2(const uint8_t* src, uint8_t* dst,', + ' int count) {', + ] + ) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._NO_ASM) @@ -6541,40 +7381,39 @@ def testInlineAssembly(self): self.UpdateWithLines([' asm volatile (']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, - cpplint._INSIDE_ASM) - - self.UpdateWithLines([' "sub %0,%1 \\n"', - ' "1: \\n"', - ' "movdqa (%0),%%xmm0 \\n"', - ' "movdqa 0x10(%0),%%xmm1 \\n"', - ' "movdqa %%xmm0,(%0,%1) \\n"', - ' "movdqa %%xmm1,0x10(%0,%1) \\n"', - ' "lea 0x20(%0),%0 \\n"', - ' "sub $0x20,%2 \\n"', - ' "jg 1b \\n"', - ' : "+r"(src), // %0', - ' "+r"(dst), // %1', - ' "+r"(count) // %2', - ' :', - ' : "memory", "cc"']) + self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._INSIDE_ASM) + + self.UpdateWithLines( + [ + ' "sub %0,%1 \\n"', + ' "1: \\n"', + ' "movdqa (%0),%%xmm0 \\n"', + ' "movdqa 0x10(%0),%%xmm1 \\n"', + ' "movdqa %%xmm0,(%0,%1) \\n"', + ' "movdqa %%xmm1,0x10(%0,%1) \\n"', + ' "lea 0x20(%0),%0 \\n"', + ' "sub $0x20,%2 \\n"', + ' "jg 1b \\n"', + ' : "+r"(src), // %0', + ' "+r"(dst), // %1', + ' "+r"(count) // %2', + ' :', + ' : "memory", "cc"', + ] + ) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, - cpplint._INSIDE_ASM) + self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._INSIDE_ASM) - self.UpdateWithLines(['#if defined(__SSE2__)', - ' , "xmm0", "xmm1"']) + self.UpdateWithLines(['#if defined(__SSE2__)', ' , "xmm0", "xmm1"']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, - cpplint._INSIDE_ASM) + self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._INSIDE_ASM) self.UpdateWithLines(['#endif']) self.assertEqual(len(self.nesting_state.stack), 1) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, - cpplint._INSIDE_ASM) + self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._INSIDE_ASM) self.UpdateWithLines([' );']) self.assertEqual(len(self.nesting_state.stack), 1) @@ -6584,8 +7423,7 @@ def testInlineAssembly(self): self.UpdateWithLines(['__asm {']) self.assertEqual(len(self.nesting_state.stack), 2) self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, - cpplint._BLOCK_ASM) + self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._BLOCK_ASM) self.UpdateWithLines(['}']) self.assertEqual(len(self.nesting_state.stack), 1) @@ -6595,34 +7433,33 @@ def testInlineAssembly(self): class QuietTest(unittest.TestCase): - def setUp(self): self.temp_dir = os.path.realpath(tempfile.mkdtemp()) self.this_dir_path = os.path.abspath(self.temp_dir) self.python_executable = sys.executable or 'python' - self.cpplint_test_h = os.path.join(self.this_dir_path, - 'cpplint_test_header.h') + self.cpplint_test_h = os.path.join(self.this_dir_path, 'cpplint_test_header.h') open(self.cpplint_test_h, 'w').close() def tearDown(self): shutil.rmtree(self.temp_dir) def _runCppLint(self, *args): - cpplint_abspath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cpplint.py') + cpplint_abspath = os.path.join( + os.path.dirname(os.path.abspath(__file__)), 'cpplint.py' + ) - cmd_line = [self.python_executable, cpplint_abspath] + \ - list(args) + \ - [self.cpplint_test_h] + cmd_line = ( + [self.python_executable, cpplint_abspath] + list(args) + [self.cpplint_test_h] + ) return_code = 0 try: - output = subprocess.check_output(cmd_line, - stderr=subprocess.STDOUT) + output = subprocess.check_output(cmd_line, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: return_code = err.returncode output = err.output if isinstance(output, bytes): - output = output.decode('utf-8') + output = output.decode('utf-8') return (return_code, output) def testNonQuietWithErrors(self): @@ -6648,9 +7485,9 @@ def testQuietWithErrors(self): def testNonQuietWithoutErrors(self): # This will succeed. We filtered out all the known errors for that file. - (return_code, output) = self._runCppLint('--filter=' + - '-legal/copyright,' + - '-build/header_guard') + (return_code, output) = self._runCppLint( + '--filter=' + '-legal/copyright,' + '-build/header_guard' + ) self.assertEqual(0, return_code, output) # No cpplint errors are printed since there were no errors. self.assertNotIn("[legal/copyright]", output) @@ -6661,10 +7498,9 @@ def testNonQuietWithoutErrors(self): def testQuietWithoutErrors(self): # This will succeed. We filtered out all the known errors for that file. - (return_code, output) = self._runCppLint('--quiet', - '--filter=' + - '-legal/copyright,' + - '-build/header_guard') + (return_code, output) = self._runCppLint( + '--quiet', '--filter=' + '-legal/copyright,' + '-build/header_guard' + ) self.assertEqual(0, return_code, output) # No cpplint errors are printed since there were no errors. self.assertNotIn("[legal/copyright]", output) @@ -6676,14 +7512,15 @@ def testQuietWithoutErrors(self): # Output with no errors must be completely blank! self.assertEqual("", output) + # class FileFilterTest(unittest.TestCase): # def testFilterExcludedFiles(self): # self.assertEqual([], _FilterExcludedFiles([])) + # pylint: disable=C6409 def setUp(): - """Runs before all tests are executed. - """ + """Runs before all tests are executed.""" # Enable all filters, so we don't miss anything that is off by default. cpplint._DEFAULT_FILTERS = [] cpplint._cpplint_state.SetFilters('') @@ -6719,7 +7556,7 @@ def run_around_tests(): # only run VerifyAllCategoriesAreSeen() when no commandline flags # are passed in. global _run_verifyallcategoriesseen - _run_verifyallcategoriesseen = (len(sys.argv) == 1) + _run_verifyallcategoriesseen = len(sys.argv) == 1 setUp() unittest.main() diff --git a/pyproject.toml b/pyproject.toml index 29ae077..8714db5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,3 +4,7 @@ requires = [ "setuptools", "wheel", ] + +[tool.ruff] +indent-width = 2 +format.quote-style = "preserve"