Home | History | Annotate | Download | only in processors
      1 #!/usr/bin/python
      2 # -*- coding: utf-8; -*-
      3 #
      4 # Copyright (C) 2009 Google Inc. All rights reserved.
      5 # Copyright (C) 2009 Torch Mobile Inc.
      6 # Copyright (C) 2009 Apple Inc. All rights reserved.
      7 # Copyright (C) 2010 Chris Jerdonek (cjerdonek (at] webkit.org)
      8 #
      9 # Redistribution and use in source and binary forms, with or without
     10 # modification, are permitted provided that the following conditions are
     11 # met:
     12 #
     13 #    * Redistributions of source code must retain the above copyright
     14 # notice, this list of conditions and the following disclaimer.
     15 #    * Redistributions in binary form must reproduce the above
     16 # copyright notice, this list of conditions and the following disclaimer
     17 # in the documentation and/or other materials provided with the
     18 # distribution.
     19 #    * Neither the name of Google Inc. nor the names of its
     20 # contributors may be used to endorse or promote products derived from
     21 # this software without specific prior written permission.
     22 #
     23 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     24 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     25 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     26 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     27 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     28 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     29 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     30 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     31 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     32 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     33 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     34 
     35 """Unit test for cpp_style.py."""
     36 
     37 # FIXME: Add a good test that tests UpdateIncludeState.
     38 
     39 import codecs
     40 import os
     41 import random
     42 import re
     43 import unittest
     44 import cpp as cpp_style
     45 from cpp import CppProcessor
     46 
     47 # This class works as an error collector and replaces cpp_style.Error
     48 # function for the unit tests.  We also verify each category we see
     49 # is in STYLE_CATEGORIES, to help keep that list up to date.
     50 class ErrorCollector:
     51     _all_style_categories = CppProcessor.categories
     52     # This is a list including all categories seen in any unit test.
     53     _seen_style_categories = {}
     54 
     55     def __init__(self, assert_fn):
     56         """assert_fn: a function to call when we notice a problem."""
     57         self._assert_fn = assert_fn
     58         self._errors = []
     59 
     60     def __call__(self, unused_linenum, category, confidence, message):
     61         self._assert_fn(category in self._all_style_categories,
     62                         'Message "%s" has category "%s",'
     63                         ' which is not in STYLE_CATEGORIES' % (message, category))
     64         self._seen_style_categories[category] = 1
     65         self._errors.append('%s  [%s] [%d]' % (message, category, confidence))
     66 
     67     def results(self):
     68         if len(self._errors) < 2:
     69             return ''.join(self._errors)  # Most tests expect to have a string.
     70         else:
     71             return self._errors  # Let's give a list if there is more than one.
     72 
     73     def result_list(self):
     74         return self._errors
     75 
     76     def verify_all_categories_are_seen(self):
     77         """Fails if there's a category in _all_style_categories - _seen_style_categories.
     78 
     79         This should only be called after all tests are run, so
     80         _seen_style_categories has had a chance to fully populate.  Since
     81         this isn't called from within the normal unittest framework, we
     82         can't use the normal unittest assert macros.  Instead we just exit
     83         when we see an error.  Good thing this test is always run last!
     84         """
     85         for category in self._all_style_categories:
     86             if category not in self._seen_style_categories:
     87                 import sys
     88                 sys.exit('FATAL ERROR: There are no tests for category "%s"' % category)
     89 
     90     def remove_if_present(self, substr):
     91         for (index, error) in enumerate(self._errors):
     92             if error.find(substr) != -1:
     93                 self._errors = self._errors[0:index] + self._errors[(index + 1):]
     94                 break
     95 
     96 
     97 # This class is a lame mock of codecs. We do not verify filename, mode, or
     98 # encoding, but for the current use case it is not needed.
     99 class MockIo:
    100     def __init__(self, mock_file):
    101         self.mock_file = mock_file
    102 
    103     def open(self, unused_filename, unused_mode, unused_encoding, _):  # NOLINT
    104         # (lint doesn't like open as a method name)
    105         return self.mock_file
    106 
    107 
    108 class CppFunctionsTest(unittest.TestCase):
    109 
    110     """Supports testing functions that do not need CppStyleTestBase."""
    111 
    112     def test_is_c_or_objective_c(self):
    113         self.assertTrue(cpp_style.is_c_or_objective_c("c"))
    114         self.assertTrue(cpp_style.is_c_or_objective_c("m"))
    115         self.assertFalse(cpp_style.is_c_or_objective_c("cpp"))
    116 
    117 
    118 class CppStyleTestBase(unittest.TestCase):
    119     """Provides some useful helper functions for cpp_style tests.
    120 
    121     Attributes:
    122       verbosity: An integer that is the current verbosity level for
    123                  the tests.
    124 
    125     """
    126 
    127     # FIXME: Refactor the unit tests so the verbosity level is passed
    128     #        explicitly, just like it is in the real code.
    129     verbosity = 1;
    130 
    131     # Helper function to avoid needing to explicitly pass verbosity
    132     # in all the unit test calls to cpp_style.process_file_data().
    133     def process_file_data(self, filename, file_extension, lines, error):
    134         """Call cpp_style.process_file_data() with the current verbosity."""
    135         return cpp_style.process_file_data(filename, file_extension, lines, error, self.verbosity)
    136 
    137     # Perform lint on single line of input and return the error message.
    138     def perform_single_line_lint(self, code, file_name):
    139         error_collector = ErrorCollector(self.assert_)
    140         lines = code.split('\n')
    141         cpp_style.remove_multi_line_comments(lines, error_collector)
    142         clean_lines = cpp_style.CleansedLines(lines)
    143         include_state = cpp_style._IncludeState()
    144         function_state = cpp_style._FunctionState(self.verbosity)
    145         ext = file_name[file_name.rfind('.') + 1:]
    146         class_state = cpp_style._ClassState()
    147         file_state = cpp_style._FileState()
    148         cpp_style.process_line(file_name, ext, clean_lines, 0,
    149                                include_state, function_state,
    150                                class_state, file_state, error_collector)
    151         # Single-line lint tests are allowed to fail the 'unlintable function'
    152         # check.
    153         error_collector.remove_if_present(
    154             'Lint failed to find start of function body.')
    155         return error_collector.results()
    156 
    157     # Perform lint over multiple lines and return the error message.
    158     def perform_multi_line_lint(self, code, file_extension):
    159         error_collector = ErrorCollector(self.assert_)
    160         lines = code.split('\n')
    161         cpp_style.remove_multi_line_comments(lines, error_collector)
    162         lines = cpp_style.CleansedLines(lines)
    163         class_state = cpp_style._ClassState()
    164         file_state = cpp_style._FileState()
    165         for i in xrange(lines.num_lines()):
    166             cpp_style.check_style(lines, i, file_extension, file_state, error_collector)
    167             cpp_style.check_for_non_standard_constructs(lines, i, class_state,
    168                                                         error_collector)
    169         class_state.check_finished(error_collector)
    170         return error_collector.results()
    171 
    172     # Similar to perform_multi_line_lint, but calls check_language instead of
    173     # check_for_non_standard_constructs
    174     def perform_language_rules_check(self, file_name, code):
    175         error_collector = ErrorCollector(self.assert_)
    176         include_state = cpp_style._IncludeState()
    177         lines = code.split('\n')
    178         cpp_style.remove_multi_line_comments(lines, error_collector)
    179         lines = cpp_style.CleansedLines(lines)
    180         ext = file_name[file_name.rfind('.') + 1:]
    181         for i in xrange(lines.num_lines()):
    182             cpp_style.check_language(file_name, lines, i, ext, include_state,
    183                                      error_collector)
    184         return error_collector.results()
    185 
    186     def perform_function_lengths_check(self, code):
    187         """Perform Lint function length check on block of code and return warnings.
    188 
    189         Builds up an array of lines corresponding to the code and strips comments
    190         using cpp_style functions.
    191 
    192         Establishes an error collector and invokes the function length checking
    193         function following cpp_style's pattern.
    194 
    195         Args:
    196           code: C++ source code expected to generate a warning message.
    197 
    198         Returns:
    199           The accumulated errors.
    200         """
    201         error_collector = ErrorCollector(self.assert_)
    202         function_state = cpp_style._FunctionState(self.verbosity)
    203         lines = code.split('\n')
    204         cpp_style.remove_multi_line_comments(lines, error_collector)
    205         lines = cpp_style.CleansedLines(lines)
    206         for i in xrange(lines.num_lines()):
    207             cpp_style.check_for_function_lengths(lines, i,
    208                                                  function_state, error_collector)
    209         return error_collector.results()
    210 
    211     def perform_include_what_you_use(self, code, filename='foo.h', io=codecs):
    212         # First, build up the include state.
    213         error_collector = ErrorCollector(self.assert_)
    214         include_state = cpp_style._IncludeState()
    215         lines = code.split('\n')
    216         cpp_style.remove_multi_line_comments(lines, error_collector)
    217         lines = cpp_style.CleansedLines(lines)
    218         file_extension = filename[filename.rfind('.') + 1:]
    219         for i in xrange(lines.num_lines()):
    220             cpp_style.check_language(filename, lines, i, file_extension, include_state,
    221                                      error_collector)
    222         # We could clear the error_collector here, but this should
    223         # also be fine, since our IncludeWhatYouUse unittests do not
    224         # have language problems.
    225 
    226         # Second, look for missing includes.
    227         cpp_style.check_for_include_what_you_use(filename, lines, include_state,
    228                                                  error_collector, io)
    229         return error_collector.results()
    230 
    231     # Perform lint and compare the error message with "expected_message".
    232     def assert_lint(self, code, expected_message, file_name='foo.cpp'):
    233         self.assertEquals(expected_message, self.perform_single_line_lint(code, file_name))
    234 
    235     def assert_lint_one_of_many_errors_re(self, code, expected_message_re, file_name='foo.cpp'):
    236         messages = self.perform_single_line_lint(code, file_name)
    237         for message in messages:
    238             if re.search(expected_message_re, message):
    239                 return
    240 
    241         self.assertEquals(expected_message, messages)
    242 
    243     def assert_multi_line_lint(self, code, expected_message, file_name='foo.h'):
    244         file_extension = file_name[file_name.rfind('.') + 1:]
    245         self.assertEquals(expected_message, self.perform_multi_line_lint(code, file_extension))
    246 
    247     def assert_multi_line_lint_re(self, code, expected_message_re, file_name='foo.h'):
    248         file_extension = file_name[file_name.rfind('.') + 1:]
    249         message = self.perform_multi_line_lint(code, file_extension)
    250         if not re.search(expected_message_re, message):
    251             self.fail('Message was:\n' + message + 'Expected match to "' + expected_message_re + '"')
    252 
    253     def assert_language_rules_check(self, file_name, code, expected_message):
    254         self.assertEquals(expected_message,
    255                           self.perform_language_rules_check(file_name, code))
    256 
    257     def assert_include_what_you_use(self, code, expected_message):
    258         self.assertEquals(expected_message,
    259                           self.perform_include_what_you_use(code))
    260 
    261     def assert_blank_lines_check(self, lines, start_errors, end_errors):
    262         error_collector = ErrorCollector(self.assert_)
    263         self.process_file_data('foo.cpp', 'cpp', lines, error_collector)
    264         self.assertEquals(
    265             start_errors,
    266             error_collector.results().count(
    267                 'Blank line at the start of a code block.  Is this needed?'
    268                 '  [whitespace/blank_line] [2]'))
    269         self.assertEquals(
    270             end_errors,
    271             error_collector.results().count(
    272                 'Blank line at the end of a code block.  Is this needed?'
    273                 '  [whitespace/blank_line] [3]'))
    274 
    275 
    276 class CppStyleTest(CppStyleTestBase):
    277 
    278     # Test get line width.
    279     def test_get_line_width(self):
    280         self.assertEquals(0, cpp_style.get_line_width(''))
    281         self.assertEquals(10, cpp_style.get_line_width(u'x' * 10))
    282         self.assertEquals(16, cpp_style.get_line_width(u'||||'))
    283 
    284     def test_find_next_multi_line_comment_start(self):
    285         self.assertEquals(1, cpp_style.find_next_multi_line_comment_start([''], 0))
    286 
    287         lines = ['a', 'b', '/* c']
    288         self.assertEquals(2, cpp_style.find_next_multi_line_comment_start(lines, 0))
    289 
    290         lines = ['char a[] = "/*";']  # not recognized as comment.
    291         self.assertEquals(1, cpp_style.find_next_multi_line_comment_start(lines, 0))
    292 
    293     def test_find_next_multi_line_comment_end(self):
    294         self.assertEquals(1, cpp_style.find_next_multi_line_comment_end([''], 0))
    295         lines = ['a', 'b', ' c */']
    296         self.assertEquals(2, cpp_style.find_next_multi_line_comment_end(lines, 0))
    297 
    298     def test_remove_multi_line_comments_from_range(self):
    299         lines = ['a', '  /* comment ', ' * still comment', ' comment */   ', 'b']
    300         cpp_style.remove_multi_line_comments_from_range(lines, 1, 4)
    301         self.assertEquals(['a', '// dummy', '// dummy', '// dummy', 'b'], lines)
    302 
    303     def test_spaces_at_end_of_line(self):
    304         self.assert_lint(
    305             '// Hello there ',
    306             'Line ends in whitespace.  Consider deleting these extra spaces.'
    307             '  [whitespace/end_of_line] [4]')
    308 
    309     # Test C-style cast cases.
    310     def test_cstyle_cast(self):
    311         self.assert_lint(
    312             'int a = (int)1.0;',
    313             'Using C-style cast.  Use static_cast<int>(...) instead'
    314             '  [readability/casting] [4]')
    315         self.assert_lint(
    316             'int *a = (int *)DEFINED_VALUE;',
    317             'Using C-style cast.  Use reinterpret_cast<int *>(...) instead'
    318             '  [readability/casting] [4]', 'foo.c')
    319         self.assert_lint(
    320             'uint16 a = (uint16)1.0;',
    321             'Using C-style cast.  Use static_cast<uint16>(...) instead'
    322             '  [readability/casting] [4]')
    323         self.assert_lint(
    324             'int32 a = (int32)1.0;',
    325             'Using C-style cast.  Use static_cast<int32>(...) instead'
    326             '  [readability/casting] [4]')
    327         self.assert_lint(
    328             'uint64 a = (uint64)1.0;',
    329             'Using C-style cast.  Use static_cast<uint64>(...) instead'
    330             '  [readability/casting] [4]')
    331 
    332     # Test taking address of casts (runtime/casting)
    333     def test_runtime_casting(self):
    334         self.assert_lint(
    335             'int* x = &static_cast<int*>(foo);',
    336             'Are you taking an address of a cast?  '
    337             'This is dangerous: could be a temp var.  '
    338             'Take the address before doing the cast, rather than after'
    339             '  [runtime/casting] [4]')
    340 
    341         self.assert_lint(
    342             'int* x = &dynamic_cast<int *>(foo);',
    343             ['Are you taking an address of a cast?  '
    344              'This is dangerous: could be a temp var.  '
    345              'Take the address before doing the cast, rather than after'
    346              '  [runtime/casting] [4]',
    347              'Do not use dynamic_cast<>.  If you need to cast within a class '
    348              'hierarchy, use static_cast<> to upcast.  Google doesn\'t support '
    349              'RTTI.  [runtime/rtti] [5]'])
    350 
    351         self.assert_lint(
    352             'int* x = &reinterpret_cast<int *>(foo);',
    353             'Are you taking an address of a cast?  '
    354             'This is dangerous: could be a temp var.  '
    355             'Take the address before doing the cast, rather than after'
    356             '  [runtime/casting] [4]')
    357 
    358         # It's OK to cast an address.
    359         self.assert_lint(
    360             'int* x = reinterpret_cast<int *>(&foo);',
    361             '')
    362 
    363     def test_runtime_selfinit(self):
    364         self.assert_lint(
    365             'Foo::Foo(Bar r, Bel l) : r_(r_), l_(l_) { }',
    366             'You seem to be initializing a member variable with itself.'
    367             '  [runtime/init] [4]')
    368         self.assert_lint(
    369             'Foo::Foo(Bar r, Bel l) : r_(r), l_(l) { }',
    370             '')
    371         self.assert_lint(
    372             'Foo::Foo(Bar r) : r_(r), l_(r_), ll_(l_) { }',
    373             '')
    374 
    375     def test_runtime_rtti(self):
    376         statement = 'int* x = dynamic_cast<int*>(&foo);'
    377         error_message = (
    378             'Do not use dynamic_cast<>.  If you need to cast within a class '
    379             'hierarchy, use static_cast<> to upcast.  Google doesn\'t support '
    380             'RTTI.  [runtime/rtti] [5]')
    381         # dynamic_cast is disallowed in most files.
    382         self.assert_language_rules_check('foo.cpp', statement, error_message)
    383         self.assert_language_rules_check('foo.h', statement, error_message)
    384 
    385     # We cannot test this functionality because of difference of
    386     # function definitions.  Anyway, we may never enable this.
    387     #
    388     # # Test for unnamed arguments in a method.
    389     # def test_check_for_unnamed_params(self):
    390     #   message = ('All parameters should be named in a function'
    391     #              '  [readability/function] [3]')
    392     #   self.assert_lint('virtual void A(int*) const;', message)
    393     #   self.assert_lint('virtual void B(void (*fn)(int*));', message)
    394     #   self.assert_lint('virtual void C(int*);', message)
    395     #   self.assert_lint('void *(*f)(void *) = x;', message)
    396     #   self.assert_lint('void Method(char*) {', message)
    397     #   self.assert_lint('void Method(char*);', message)
    398     #   self.assert_lint('void Method(char* /*x*/);', message)
    399     #   self.assert_lint('typedef void (*Method)(int32);', message)
    400     #   self.assert_lint('static void operator delete[](void*) throw();', message)
    401     # 
    402     #   self.assert_lint('virtual void D(int* p);', '')
    403     #   self.assert_lint('void operator delete(void* x) throw();', '')
    404     #   self.assert_lint('void Method(char* x)\n{', '')
    405     #   self.assert_lint('void Method(char* /*x*/)\n{', '')
    406     #   self.assert_lint('void Method(char* x);', '')
    407     #   self.assert_lint('typedef void (*Method)(int32 x);', '')
    408     #   self.assert_lint('static void operator delete[](void* x) throw();', '')
    409     #   self.assert_lint('static void operator delete[](void* /*x*/) throw();', '')
    410     # 
    411     #   # This one should technically warn, but doesn't because the function
    412     #   # pointer is confusing.
    413     #   self.assert_lint('virtual void E(void (*fn)(int* p));', '')
    414 
    415     # Test deprecated casts such as int(d)
    416     def test_deprecated_cast(self):
    417         self.assert_lint(
    418             'int a = int(2.2);',
    419             'Using deprecated casting style.  '
    420             'Use static_cast<int>(...) instead'
    421             '  [readability/casting] [4]')
    422         # Checks for false positives...
    423         self.assert_lint(
    424             'int a = int(); // Constructor, o.k.',
    425             '')
    426         self.assert_lint(
    427             'X::X() : a(int()) {} // default Constructor, o.k.',
    428             '')
    429         self.assert_lint(
    430             'operator bool(); // Conversion operator, o.k.',
    431             '')
    432 
    433     # The second parameter to a gMock method definition is a function signature
    434     # that often looks like a bad cast but should not picked up by lint.
    435     def test_mock_method(self):
    436         self.assert_lint(
    437             'MOCK_METHOD0(method, int());',
    438             '')
    439         self.assert_lint(
    440             'MOCK_CONST_METHOD1(method, float(string));',
    441             '')
    442         self.assert_lint(
    443             'MOCK_CONST_METHOD2_T(method, double(float, float));',
    444             '')
    445 
    446     # Test sizeof(type) cases.
    447     def test_sizeof_type(self):
    448         self.assert_lint(
    449             'sizeof(int);',
    450             'Using sizeof(type).  Use sizeof(varname) instead if possible'
    451             '  [runtime/sizeof] [1]')
    452         self.assert_lint(
    453             'sizeof(int *);',
    454             'Using sizeof(type).  Use sizeof(varname) instead if possible'
    455             '  [runtime/sizeof] [1]')
    456 
    457     # Test typedef cases.  There was a bug that cpp_style misidentified
    458     # typedef for pointer to function as C-style cast and produced
    459     # false-positive error messages.
    460     def test_typedef_for_pointer_to_function(self):
    461         self.assert_lint(
    462             'typedef void (*Func)(int x);',
    463             '')
    464         self.assert_lint(
    465             'typedef void (*Func)(int *x);',
    466             '')
    467         self.assert_lint(
    468             'typedef void Func(int x);',
    469             '')
    470         self.assert_lint(
    471             'typedef void Func(int *x);',
    472             '')
    473 
    474     def test_include_what_you_use_no_implementation_files(self):
    475         code = 'std::vector<int> foo;'
    476         self.assertEquals('Add #include <vector> for vector<>'
    477                           '  [build/include_what_you_use] [4]',
    478                           self.perform_include_what_you_use(code, 'foo.h'))
    479         self.assertEquals('',
    480                           self.perform_include_what_you_use(code, 'foo.cpp'))
    481 
    482     def test_include_what_you_use(self):
    483         self.assert_include_what_you_use(
    484             '''#include <vector>
    485                std::vector<int> foo;
    486             ''',
    487             '')
    488         self.assert_include_what_you_use(
    489             '''#include <map>
    490                std::pair<int,int> foo;
    491             ''',
    492             '')
    493         self.assert_include_what_you_use(
    494             '''#include <multimap>
    495                std::pair<int,int> foo;
    496             ''',
    497             '')
    498         self.assert_include_what_you_use(
    499             '''#include <hash_map>
    500                std::pair<int,int> foo;
    501             ''',
    502             '')
    503         self.assert_include_what_you_use(
    504             '''#include <utility>
    505                std::pair<int,int> foo;
    506             ''',
    507             '')
    508         self.assert_include_what_you_use(
    509             '''#include <vector>
    510                DECLARE_string(foobar);
    511             ''',
    512             '')
    513         self.assert_include_what_you_use(
    514             '''#include <vector>
    515                DEFINE_string(foobar, "", "");
    516             ''',
    517             '')
    518         self.assert_include_what_you_use(
    519             '''#include <vector>
    520                std::pair<int,int> foo;
    521             ''',
    522             'Add #include <utility> for pair<>'
    523             '  [build/include_what_you_use] [4]')
    524         self.assert_include_what_you_use(
    525             '''#include "base/foobar.h"
    526                std::vector<int> foo;
    527             ''',
    528             'Add #include <vector> for vector<>'
    529             '  [build/include_what_you_use] [4]')
    530         self.assert_include_what_you_use(
    531             '''#include <vector>
    532                std::set<int> foo;
    533             ''',
    534             'Add #include <set> for set<>'
    535             '  [build/include_what_you_use] [4]')
    536         self.assert_include_what_you_use(
    537             '''#include "base/foobar.h"
    538               hash_map<int, int> foobar;
    539             ''',
    540             'Add #include <hash_map> for hash_map<>'
    541             '  [build/include_what_you_use] [4]')
    542         self.assert_include_what_you_use(
    543             '''#include "base/foobar.h"
    544                bool foobar = std::less<int>(0,1);
    545             ''',
    546             'Add #include <functional> for less<>'
    547             '  [build/include_what_you_use] [4]')
    548         self.assert_include_what_you_use(
    549             '''#include "base/foobar.h"
    550                bool foobar = min<int>(0,1);
    551             ''',
    552             'Add #include <algorithm> for min  [build/include_what_you_use] [4]')
    553         self.assert_include_what_you_use(
    554             'void a(const string &foobar);',
    555             'Add #include <string> for string  [build/include_what_you_use] [4]')
    556         self.assert_include_what_you_use(
    557             '''#include "base/foobar.h"
    558                bool foobar = swap(0,1);
    559             ''',
    560             'Add #include <algorithm> for swap  [build/include_what_you_use] [4]')
    561         self.assert_include_what_you_use(
    562             '''#include "base/foobar.h"
    563                bool foobar = transform(a.begin(), a.end(), b.start(), Foo);
    564             ''',
    565             'Add #include <algorithm> for transform  '
    566             '[build/include_what_you_use] [4]')
    567         self.assert_include_what_you_use(
    568             '''#include "base/foobar.h"
    569                bool foobar = min_element(a.begin(), a.end());
    570             ''',
    571             'Add #include <algorithm> for min_element  '
    572             '[build/include_what_you_use] [4]')
    573         self.assert_include_what_you_use(
    574             '''foo->swap(0,1);
    575                foo.swap(0,1);
    576             ''',
    577             '')
    578         self.assert_include_what_you_use(
    579             '''#include <string>
    580                void a(const std::multimap<int,string> &foobar);
    581             ''',
    582             'Add #include <map> for multimap<>'
    583             '  [build/include_what_you_use] [4]')
    584         self.assert_include_what_you_use(
    585             '''#include <queue>
    586                void a(const std::priority_queue<int> &foobar);
    587             ''',
    588             '')
    589         self.assert_include_what_you_use(
    590              '''#include "base/basictypes.h"
    591                 #include "base/port.h"
    592                 #include <assert.h>
    593                 #include <string>
    594                 #include <vector>
    595                 vector<string> hajoa;''', '')
    596         self.assert_include_what_you_use(
    597             '''#include <string>
    598                int i = numeric_limits<int>::max()
    599             ''',
    600             'Add #include <limits> for numeric_limits<>'
    601             '  [build/include_what_you_use] [4]')
    602         self.assert_include_what_you_use(
    603             '''#include <limits>
    604                int i = numeric_limits<int>::max()
    605             ''',
    606             '')
    607 
    608         # Test the UpdateIncludeState code path.
    609         mock_header_contents = ['#include "blah/foo.h"', '#include "blah/bar.h"']
    610         message = self.perform_include_what_you_use(
    611             '#include "config.h"\n'
    612             '#include "blah/a.h"\n',
    613             filename='blah/a.cpp',
    614             io=MockIo(mock_header_contents))
    615         self.assertEquals(message, '')
    616 
    617         mock_header_contents = ['#include <set>']
    618         message = self.perform_include_what_you_use(
    619             '''#include "config.h"
    620                #include "blah/a.h"
    621 
    622                std::set<int> foo;''',
    623             filename='blah/a.cpp',
    624             io=MockIo(mock_header_contents))
    625         self.assertEquals(message, '')
    626 
    627         # If there's just a .cpp and the header can't be found then it's ok.
    628         message = self.perform_include_what_you_use(
    629             '''#include "config.h"
    630                #include "blah/a.h"
    631 
    632                std::set<int> foo;''',
    633             filename='blah/a.cpp')
    634         self.assertEquals(message, '')
    635 
    636         # Make sure we find the headers with relative paths.
    637         mock_header_contents = ['']
    638         message = self.perform_include_what_you_use(
    639             '''#include "config.h"
    640                #include "%s/a.h"
    641 
    642                std::set<int> foo;''' % os.path.basename(os.getcwd()),
    643             filename='a.cpp',
    644             io=MockIo(mock_header_contents))
    645         self.assertEquals(message, 'Add #include <set> for set<>  '
    646                                    '[build/include_what_you_use] [4]')
    647 
    648     def test_files_belong_to_same_module(self):
    649         f = cpp_style.files_belong_to_same_module
    650         self.assertEquals((True, ''), f('a.cpp', 'a.h'))
    651         self.assertEquals((True, ''), f('base/google.cpp', 'base/google.h'))
    652         self.assertEquals((True, ''), f('base/google_test.cpp', 'base/google.h'))
    653         self.assertEquals((True, ''),
    654                           f('base/google_unittest.cpp', 'base/google.h'))
    655         self.assertEquals((True, ''),
    656                           f('base/internal/google_unittest.cpp',
    657                             'base/public/google.h'))
    658         self.assertEquals((True, 'xxx/yyy/'),
    659                           f('xxx/yyy/base/internal/google_unittest.cpp',
    660                             'base/public/google.h'))
    661         self.assertEquals((True, 'xxx/yyy/'),
    662                           f('xxx/yyy/base/google_unittest.cpp',
    663                             'base/public/google.h'))
    664         self.assertEquals((True, ''),
    665                           f('base/google_unittest.cpp', 'base/google-inl.h'))
    666         self.assertEquals((True, '/home/build/google3/'),
    667                           f('/home/build/google3/base/google.cpp', 'base/google.h'))
    668 
    669         self.assertEquals((False, ''),
    670                           f('/home/build/google3/base/google.cpp', 'basu/google.h'))
    671         self.assertEquals((False, ''), f('a.cpp', 'b.h'))
    672 
    673     def test_cleanse_line(self):
    674         self.assertEquals('int foo = 0;  ',
    675                           cpp_style.cleanse_comments('int foo = 0;  // danger!'))
    676         self.assertEquals('int o = 0;',
    677                           cpp_style.cleanse_comments('int /* foo */ o = 0;'))
    678         self.assertEquals('foo(int a, int b);',
    679                           cpp_style.cleanse_comments('foo(int a /* abc */, int b);'))
    680         self.assertEqual('f(a, b);',
    681                          cpp_style.cleanse_comments('f(a, /* name */ b);'))
    682         self.assertEqual('f(a, b);',
    683                          cpp_style.cleanse_comments('f(a /* name */, b);'))
    684         self.assertEqual('f(a, b);',
    685                          cpp_style.cleanse_comments('f(a, /* name */b);'))
    686 
    687     def test_multi_line_comments(self):
    688         # missing explicit is bad
    689         self.assert_multi_line_lint(
    690             r'''int a = 0;
    691                 /* multi-liner
    692                 class Foo {
    693                 Foo(int f);  // should cause a lint warning in code
    694                 }
    695             */ ''',
    696         '')
    697         self.assert_multi_line_lint(
    698             r'''/* int a = 0; multi-liner
    699             static const int b = 0;''',
    700       'Could not find end of multi-line comment'
    701       '  [readability/multiline_comment] [5]')
    702         self.assert_multi_line_lint(r'''    /* multi-line comment''',
    703                                     'Could not find end of multi-line comment'
    704                                     '  [readability/multiline_comment] [5]')
    705         self.assert_multi_line_lint(r'''    // /* comment, but not multi-line''', '')
    706 
    707     def test_multiline_strings(self):
    708         multiline_string_error_message = (
    709             'Multi-line string ("...") found.  This lint script doesn\'t '
    710             'do well with such strings, and may give bogus warnings.  They\'re '
    711             'ugly and unnecessary, and you should use concatenation instead".'
    712             '  [readability/multiline_string] [5]')
    713 
    714         file_path = 'mydir/foo.cpp'
    715 
    716         error_collector = ErrorCollector(self.assert_)
    717         self.process_file_data(file_path, 'cpp',
    718                                ['const char* str = "This is a\\',
    719                                 ' multiline string.";'],
    720                                error_collector)
    721         self.assertEquals(
    722             2,  # One per line.
    723             error_collector.result_list().count(multiline_string_error_message))
    724 
    725     # Test non-explicit single-argument constructors
    726     def test_explicit_single_argument_constructors(self):
    727         # missing explicit is bad
    728         self.assert_multi_line_lint(
    729             '''class Foo {
    730                  Foo(int f);
    731                };''',
    732             'Single-argument constructors should be marked explicit.'
    733             '  [runtime/explicit] [5]')
    734         # missing explicit is bad, even with whitespace
    735         self.assert_multi_line_lint(
    736             '''class Foo {
    737                  Foo (int f);
    738                };''',
    739             ['Extra space before ( in function call  [whitespace/parens] [4]',
    740              'Single-argument constructors should be marked explicit.'
    741              '  [runtime/explicit] [5]'])
    742         # missing explicit, with distracting comment, is still bad
    743         self.assert_multi_line_lint(
    744             '''class Foo {
    745                  Foo(int f); // simpler than Foo(blargh, blarg)
    746                };''',
    747             'Single-argument constructors should be marked explicit.'
    748             '  [runtime/explicit] [5]')
    749         # missing explicit, with qualified classname
    750         self.assert_multi_line_lint(
    751             '''class Qualifier::AnotherOne::Foo {
    752                  Foo(int f);
    753                };''',
    754             'Single-argument constructors should be marked explicit.'
    755             '  [runtime/explicit] [5]')
    756         # structs are caught as well.
    757         self.assert_multi_line_lint(
    758             '''struct Foo {
    759                  Foo(int f);
    760                };''',
    761             'Single-argument constructors should be marked explicit.'
    762             '  [runtime/explicit] [5]')
    763         # Templatized classes are caught as well.
    764         self.assert_multi_line_lint(
    765             '''template<typename T> class Foo {
    766                  Foo(int f);
    767                };''',
    768             'Single-argument constructors should be marked explicit.'
    769             '  [runtime/explicit] [5]')
    770         # proper style is okay
    771         self.assert_multi_line_lint(
    772             '''class Foo {
    773                  explicit Foo(int f);
    774                };''',
    775             '')
    776         # two argument constructor is okay
    777         self.assert_multi_line_lint(
    778             '''class Foo {
    779                  Foo(int f, int b);
    780                };''',
    781             '')
    782         # two argument constructor, across two lines, is okay
    783         self.assert_multi_line_lint(
    784             '''class Foo {
    785                  Foo(int f,
    786                      int b);
    787                };''',
    788             '')
    789         # non-constructor (but similar name), is okay
    790         self.assert_multi_line_lint(
    791             '''class Foo {
    792                  aFoo(int f);
    793                };''',
    794             '')
    795         # constructor with void argument is okay
    796         self.assert_multi_line_lint(
    797             '''class Foo {
    798                  Foo(void);
    799                };''',
    800             '')
    801         # single argument method is okay
    802         self.assert_multi_line_lint(
    803             '''class Foo {
    804                  Bar(int b);
    805                };''',
    806             '')
    807         # comments should be ignored
    808         self.assert_multi_line_lint(
    809             '''class Foo {
    810                // Foo(int f);
    811                };''',
    812             '')
    813         # single argument function following class definition is okay
    814         # (okay, it's not actually valid, but we don't want a false positive)
    815         self.assert_multi_line_lint(
    816             '''class Foo {
    817                  Foo(int f, int b);
    818                };
    819                Foo(int f);''',
    820             '')
    821         # single argument function is okay
    822         self.assert_multi_line_lint(
    823             '''static Foo(int f);''',
    824             '')
    825         # single argument copy constructor is okay.
    826         self.assert_multi_line_lint(
    827             '''class Foo {
    828                  Foo(const Foo&);
    829                };''',
    830             '')
    831         self.assert_multi_line_lint(
    832             '''class Foo {
    833                  Foo(Foo&);
    834                };''',
    835             '')
    836 
    837     def test_slash_star_comment_on_single_line(self):
    838         self.assert_multi_line_lint(
    839             '''/* static */ Foo(int f);''',
    840             '')
    841         self.assert_multi_line_lint(
    842             '''/*/ static */  Foo(int f);''',
    843             '')
    844         self.assert_multi_line_lint(
    845             '''/*/ static Foo(int f);''',
    846             'Could not find end of multi-line comment'
    847             '  [readability/multiline_comment] [5]')
    848         self.assert_multi_line_lint(
    849             '''    /*/ static Foo(int f);''',
    850             'Could not find end of multi-line comment'
    851             '  [readability/multiline_comment] [5]')
    852         self.assert_multi_line_lint(
    853             '''    /**/ static Foo(int f);''',
    854             '')
    855 
    856     # Test suspicious usage of "if" like this:
    857     # if (a == b) {
    858     #   DoSomething();
    859     # } if (a == c) {   // Should be "else if".
    860     #   DoSomething();  // This gets called twice if a == b && a == c.
    861     # }
    862     def test_suspicious_usage_of_if(self):
    863         self.assert_lint(
    864             '    if (a == b) {',
    865             '')
    866         self.assert_lint(
    867             '    } if (a == b) {',
    868             'Did you mean "else if"? If not, start a new line for "if".'
    869             '  [readability/braces] [4]')
    870 
    871     # Test suspicious usage of memset. Specifically, a 0
    872     # as the final argument is almost certainly an error.
    873     def test_suspicious_usage_of_memset(self):
    874         # Normal use is okay.
    875         self.assert_lint(
    876             '    memset(buf, 0, sizeof(buf))',
    877             '')
    878 
    879         # A 0 as the final argument is almost certainly an error.
    880         self.assert_lint(
    881             '    memset(buf, sizeof(buf), 0)',
    882             'Did you mean "memset(buf, 0, sizeof(buf))"?'
    883             '  [runtime/memset] [4]')
    884         self.assert_lint(
    885             '    memset(buf, xsize * ysize, 0)',
    886             'Did you mean "memset(buf, 0, xsize * ysize)"?'
    887             '  [runtime/memset] [4]')
    888 
    889         # There is legitimate test code that uses this form.
    890         # This is okay since the second argument is a literal.
    891         self.assert_lint(
    892             "    memset(buf, 'y', 0)",
    893             '')
    894         self.assert_lint(
    895             '    memset(buf, 4, 0)',
    896             '')
    897         self.assert_lint(
    898             '    memset(buf, -1, 0)',
    899             '')
    900         self.assert_lint(
    901             '    memset(buf, 0xF1, 0)',
    902             '')
    903         self.assert_lint(
    904             '    memset(buf, 0xcd, 0)',
    905             '')
    906 
    907     def test_check_posix_threading(self):
    908         self.assert_lint('sctime_r()', '')
    909         self.assert_lint('strtok_r()', '')
    910         self.assert_lint('    strtok_r(foo, ba, r)', '')
    911         self.assert_lint('brand()', '')
    912         self.assert_lint('_rand()', '')
    913         self.assert_lint('.rand()', '')
    914         self.assert_lint('>rand()', '')
    915         self.assert_lint('rand()',
    916                          'Consider using rand_r(...) instead of rand(...)'
    917                          ' for improved thread safety.'
    918                          '  [runtime/threadsafe_fn] [2]')
    919         self.assert_lint('strtok()',
    920                          'Consider using strtok_r(...) '
    921                          'instead of strtok(...)'
    922                          ' for improved thread safety.'
    923                          '  [runtime/threadsafe_fn] [2]')
    924 
    925     # Test potential format string bugs like printf(foo).
    926     def test_format_strings(self):
    927         self.assert_lint('printf("foo")', '')
    928         self.assert_lint('printf("foo: %s", foo)', '')
    929         self.assert_lint('DocidForPrintf(docid)', '')  # Should not trigger.
    930         self.assert_lint(
    931             'printf(foo)',
    932             'Potential format string bug. Do printf("%s", foo) instead.'
    933             '  [runtime/printf] [4]')
    934         self.assert_lint(
    935             'printf(foo.c_str())',
    936             'Potential format string bug. '
    937             'Do printf("%s", foo.c_str()) instead.'
    938             '  [runtime/printf] [4]')
    939         self.assert_lint(
    940             'printf(foo->c_str())',
    941             'Potential format string bug. '
    942             'Do printf("%s", foo->c_str()) instead.'
    943             '  [runtime/printf] [4]')
    944         self.assert_lint(
    945             'StringPrintf(foo)',
    946             'Potential format string bug. Do StringPrintf("%s", foo) instead.'
    947             ''
    948             '  [runtime/printf] [4]')
    949 
    950     # Variable-length arrays are not permitted.
    951     def test_variable_length_array_detection(self):
    952         errmsg = ('Do not use variable-length arrays.  Use an appropriately named '
    953                   "('k' followed by CamelCase) compile-time constant for the size."
    954                   '  [runtime/arrays] [1]')
    955 
    956         self.assert_lint('int a[any_old_variable];', errmsg)
    957         self.assert_lint('int doublesize[some_var * 2];', errmsg)
    958         self.assert_lint('int a[afunction()];', errmsg)
    959         self.assert_lint('int a[function(kMaxFooBars)];', errmsg)
    960         self.assert_lint('bool aList[items_->size()];', errmsg)
    961         self.assert_lint('namespace::Type buffer[len+1];', errmsg)
    962 
    963         self.assert_lint('int a[64];', '')
    964         self.assert_lint('int a[0xFF];', '')
    965         self.assert_lint('int first[256], second[256];', '')
    966         self.assert_lint('int arrayName[kCompileTimeConstant];', '')
    967         self.assert_lint('char buf[somenamespace::kBufSize];', '')
    968         self.assert_lint('int arrayName[ALL_CAPS];', '')
    969         self.assert_lint('AClass array1[foo::bar::ALL_CAPS];', '')
    970         self.assert_lint('int a[kMaxStrLen + 1];', '')
    971         self.assert_lint('int a[sizeof(foo)];', '')
    972         self.assert_lint('int a[sizeof(*foo)];', '')
    973         self.assert_lint('int a[sizeof foo];', '')
    974         self.assert_lint('int a[sizeof(struct Foo)];', '')
    975         self.assert_lint('int a[128 - sizeof(const bar)];', '')
    976         self.assert_lint('int a[(sizeof(foo) * 4)];', '')
    977         self.assert_lint('int a[(arraysize(fixed_size_array)/2) << 1];', 'Missing spaces around /  [whitespace/operators] [3]')
    978         self.assert_lint('delete a[some_var];', '')
    979         self.assert_lint('return a[some_var];', '')
    980 
    981     # Brace usage
    982     def test_braces(self):
    983         # Braces shouldn't be followed by a ; unless they're defining a struct
    984         # or initializing an array
    985         self.assert_lint('int a[3] = { 1, 2, 3 };', '')
    986         self.assert_lint(
    987             '''const int foo[] =
    988                    {1, 2, 3 };''',
    989             '')
    990         # For single line, unmatched '}' with a ';' is ignored (not enough context)
    991         self.assert_multi_line_lint(
    992             '''int a[3] = { 1,
    993                             2,
    994                             3 };''',
    995             '')
    996         self.assert_multi_line_lint(
    997             '''int a[2][3] = { { 1, 2 },
    998                              { 3, 4 } };''',
    999             '')
   1000         self.assert_multi_line_lint(
   1001             '''int a[2][3] =
   1002                    { { 1, 2 },
   1003                      { 3, 4 } };''',
   1004             '')
   1005 
   1006     # CHECK/EXPECT_TRUE/EXPECT_FALSE replacements
   1007     def test_check_check(self):
   1008         self.assert_lint('CHECK(x == 42)',
   1009                          'Consider using CHECK_EQ instead of CHECK(a == b)'
   1010                          '  [readability/check] [2]')
   1011         self.assert_lint('CHECK(x != 42)',
   1012                          'Consider using CHECK_NE instead of CHECK(a != b)'
   1013                          '  [readability/check] [2]')
   1014         self.assert_lint('CHECK(x >= 42)',
   1015                          'Consider using CHECK_GE instead of CHECK(a >= b)'
   1016                          '  [readability/check] [2]')
   1017         self.assert_lint('CHECK(x > 42)',
   1018                          'Consider using CHECK_GT instead of CHECK(a > b)'
   1019                          '  [readability/check] [2]')
   1020         self.assert_lint('CHECK(x <= 42)',
   1021                          'Consider using CHECK_LE instead of CHECK(a <= b)'
   1022                          '  [readability/check] [2]')
   1023         self.assert_lint('CHECK(x < 42)',
   1024                          'Consider using CHECK_LT instead of CHECK(a < b)'
   1025                          '  [readability/check] [2]')
   1026 
   1027         self.assert_lint('DCHECK(x == 42)',
   1028                          'Consider using DCHECK_EQ instead of DCHECK(a == b)'
   1029                          '  [readability/check] [2]')
   1030         self.assert_lint('DCHECK(x != 42)',
   1031                          'Consider using DCHECK_NE instead of DCHECK(a != b)'
   1032                          '  [readability/check] [2]')
   1033         self.assert_lint('DCHECK(x >= 42)',
   1034                          'Consider using DCHECK_GE instead of DCHECK(a >= b)'
   1035                          '  [readability/check] [2]')
   1036         self.assert_lint('DCHECK(x > 42)',
   1037                          'Consider using DCHECK_GT instead of DCHECK(a > b)'
   1038                          '  [readability/check] [2]')
   1039         self.assert_lint('DCHECK(x <= 42)',
   1040                          'Consider using DCHECK_LE instead of DCHECK(a <= b)'
   1041                          '  [readability/check] [2]')
   1042         self.assert_lint('DCHECK(x < 42)',
   1043                          'Consider using DCHECK_LT instead of DCHECK(a < b)'
   1044                          '  [readability/check] [2]')
   1045 
   1046         self.assert_lint(
   1047             'EXPECT_TRUE("42" == x)',
   1048             'Consider using EXPECT_EQ instead of EXPECT_TRUE(a == b)'
   1049             '  [readability/check] [2]')
   1050         self.assert_lint(
   1051             'EXPECT_TRUE("42" != x)',
   1052             'Consider using EXPECT_NE instead of EXPECT_TRUE(a != b)'
   1053             '  [readability/check] [2]')
   1054         self.assert_lint(
   1055             'EXPECT_TRUE(+42 >= x)',
   1056             'Consider using EXPECT_GE instead of EXPECT_TRUE(a >= b)'
   1057             '  [readability/check] [2]')
   1058         self.assert_lint(
   1059             'EXPECT_TRUE_M(-42 > x)',
   1060             'Consider using EXPECT_GT_M instead of EXPECT_TRUE_M(a > b)'
   1061             '  [readability/check] [2]')
   1062         self.assert_lint(
   1063             'EXPECT_TRUE_M(42U <= x)',
   1064             'Consider using EXPECT_LE_M instead of EXPECT_TRUE_M(a <= b)'
   1065             '  [readability/check] [2]')
   1066         self.assert_lint(
   1067             'EXPECT_TRUE_M(42L < x)',
   1068             'Consider using EXPECT_LT_M instead of EXPECT_TRUE_M(a < b)'
   1069             '  [readability/check] [2]')
   1070 
   1071         self.assert_lint(
   1072             'EXPECT_FALSE(x == 42)',
   1073             'Consider using EXPECT_NE instead of EXPECT_FALSE(a == b)'
   1074             '  [readability/check] [2]')
   1075         self.assert_lint(
   1076             'EXPECT_FALSE(x != 42)',
   1077             'Consider using EXPECT_EQ instead of EXPECT_FALSE(a != b)'
   1078             '  [readability/check] [2]')
   1079         self.assert_lint(
   1080             'EXPECT_FALSE(x >= 42)',
   1081             'Consider using EXPECT_LT instead of EXPECT_FALSE(a >= b)'
   1082             '  [readability/check] [2]')
   1083         self.assert_lint(
   1084             'ASSERT_FALSE(x > 42)',
   1085             'Consider using ASSERT_LE instead of ASSERT_FALSE(a > b)'
   1086             '  [readability/check] [2]')
   1087         self.assert_lint(
   1088             'ASSERT_FALSE(x <= 42)',
   1089             'Consider using ASSERT_GT instead of ASSERT_FALSE(a <= b)'
   1090             '  [readability/check] [2]')
   1091         self.assert_lint(
   1092             'ASSERT_FALSE_M(x < 42)',
   1093             'Consider using ASSERT_GE_M instead of ASSERT_FALSE_M(a < b)'
   1094             '  [readability/check] [2]')
   1095 
   1096         self.assert_lint('CHECK(some_iterator == obj.end())', '')
   1097         self.assert_lint('EXPECT_TRUE(some_iterator == obj.end())', '')
   1098         self.assert_lint('EXPECT_FALSE(some_iterator == obj.end())', '')
   1099 
   1100         self.assert_lint('CHECK(CreateTestFile(dir, (1 << 20)));', '')
   1101         self.assert_lint('CHECK(CreateTestFile(dir, (1 >> 20)));', '')
   1102 
   1103         self.assert_lint('CHECK(x<42)',
   1104                          ['Missing spaces around <'
   1105                           '  [whitespace/operators] [3]',
   1106                           'Consider using CHECK_LT instead of CHECK(a < b)'
   1107                           '  [readability/check] [2]'])
   1108         self.assert_lint('CHECK(x>42)',
   1109                          'Consider using CHECK_GT instead of CHECK(a > b)'
   1110                          '  [readability/check] [2]')
   1111 
   1112         self.assert_lint(
   1113             '    EXPECT_TRUE(42 < x) // Random comment.',
   1114             'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)'
   1115             '  [readability/check] [2]')
   1116         self.assert_lint(
   1117             'EXPECT_TRUE( 42 < x )',
   1118             ['Extra space after ( in function call'
   1119              '  [whitespace/parens] [4]',
   1120              'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)'
   1121              '  [readability/check] [2]'])
   1122         self.assert_lint(
   1123             'CHECK("foo" == "foo")',
   1124             'Consider using CHECK_EQ instead of CHECK(a == b)'
   1125             '  [readability/check] [2]')
   1126 
   1127         self.assert_lint('CHECK_EQ("foo", "foo")', '')
   1128 
   1129     def test_brace_at_begin_of_line(self):
   1130         self.assert_lint('{',
   1131                          'This { should be at the end of the previous line'
   1132                          '  [whitespace/braces] [4]')
   1133         self.assert_multi_line_lint(
   1134             '#endif\n'
   1135             '{\n'
   1136             '}\n',
   1137             '')
   1138         self.assert_multi_line_lint(
   1139             'if (condition) {',
   1140             '')
   1141         self.assert_multi_line_lint(
   1142             '    MACRO1(macroArg) {',
   1143             '')
   1144         self.assert_multi_line_lint(
   1145             'ACCESSOR_GETTER(MessageEventPorts) {',
   1146             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
   1147         self.assert_multi_line_lint(
   1148             'int foo() {',
   1149             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
   1150         self.assert_multi_line_lint(
   1151             'int foo() const {',
   1152             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
   1153         self.assert_multi_line_lint(
   1154             'int foo() const\n'
   1155             '{\n'
   1156             '}\n',
   1157             '')
   1158         self.assert_multi_line_lint(
   1159             'if (condition\n'
   1160             '    && condition2\n'
   1161             '    && condition3) {\n'
   1162             '}\n',
   1163             '')
   1164 
   1165     def test_mismatching_spaces_in_parens(self):
   1166         self.assert_lint('if (foo ) {', 'Mismatching spaces inside () in if'
   1167                          '  [whitespace/parens] [5]')
   1168         self.assert_lint('switch ( foo) {', 'Mismatching spaces inside () in switch'
   1169                          '  [whitespace/parens] [5]')
   1170         self.assert_lint('for (foo; ba; bar ) {', 'Mismatching spaces inside () in for'
   1171                          '  [whitespace/parens] [5]')
   1172         self.assert_lint('for ((foo); (ba); (bar) ) {', 'Mismatching spaces inside () in for'
   1173                          '  [whitespace/parens] [5]')
   1174         self.assert_lint('for (; foo; bar) {', '')
   1175         self.assert_lint('for (; (foo); (bar)) {', '')
   1176         self.assert_lint('for ( ; foo; bar) {', '')
   1177         self.assert_lint('for ( ; (foo); (bar)) {', '')
   1178         self.assert_lint('for ( ; foo; bar ) {', '')
   1179         self.assert_lint('for ( ; (foo); (bar) ) {', '')
   1180         self.assert_lint('for (foo; bar; ) {', '')
   1181         self.assert_lint('for ((foo); (bar); ) {', '')
   1182         self.assert_lint('foreach (foo, foos ) {', 'Mismatching spaces inside () in foreach'
   1183                          '  [whitespace/parens] [5]')
   1184         self.assert_lint('foreach ( foo, foos) {', 'Mismatching spaces inside () in foreach'
   1185                          '  [whitespace/parens] [5]')
   1186         self.assert_lint('while (  foo  ) {', 'Should have zero or one spaces inside'
   1187                          ' ( and ) in while  [whitespace/parens] [5]')
   1188 
   1189     def test_spacing_for_fncall(self):
   1190         self.assert_lint('if (foo) {', '')
   1191         self.assert_lint('for (foo;bar;baz) {', '')
   1192         self.assert_lint('foreach (foo, foos) {', '')
   1193         self.assert_lint('while (foo) {', '')
   1194         self.assert_lint('switch (foo) {', '')
   1195         self.assert_lint('new (RenderArena()) RenderInline(document())', '')
   1196         self.assert_lint('foo( bar)', 'Extra space after ( in function call'
   1197                          '  [whitespace/parens] [4]')
   1198         self.assert_lint('foobar( \\', '')
   1199         self.assert_lint('foobar(     \\', '')
   1200         self.assert_lint('( a + b)', 'Extra space after ('
   1201                          '  [whitespace/parens] [2]')
   1202         self.assert_lint('((a+b))', '')
   1203         self.assert_lint('foo (foo)', 'Extra space before ( in function call'
   1204                          '  [whitespace/parens] [4]')
   1205         self.assert_lint('typedef foo (*foo)(foo)', '')
   1206         self.assert_lint('typedef foo (*foo12bar_)(foo)', '')
   1207         self.assert_lint('typedef foo (Foo::*bar)(foo)', '')
   1208         self.assert_lint('foo (Foo::*bar)(',
   1209                          'Extra space before ( in function call'
   1210                          '  [whitespace/parens] [4]')
   1211         self.assert_lint('typedef foo (Foo::*bar)(', '')
   1212         self.assert_lint('(foo)(bar)', '')
   1213         self.assert_lint('Foo (*foo)(bar)', '')
   1214         self.assert_lint('Foo (*foo)(Bar bar,', '')
   1215         self.assert_lint('char (*p)[sizeof(foo)] = &foo', '')
   1216         self.assert_lint('char (&ref)[sizeof(foo)] = &foo', '')
   1217         self.assert_lint('const char32 (*table[])[6];', '')
   1218 
   1219     def test_spacing_before_braces(self):
   1220         self.assert_lint('if (foo){', 'Missing space before {'
   1221                          '  [whitespace/braces] [5]')
   1222         self.assert_lint('for{', 'Missing space before {'
   1223                          '  [whitespace/braces] [5]')
   1224         self.assert_lint('for {', '')
   1225         self.assert_lint('EXPECT_DEBUG_DEATH({', '')
   1226 
   1227     def test_spacing_around_else(self):
   1228         self.assert_lint('}else {', 'Missing space before else'
   1229                          '  [whitespace/braces] [5]')
   1230         self.assert_lint('} else{', 'Missing space before {'
   1231                          '  [whitespace/braces] [5]')
   1232         self.assert_lint('} else {', '')
   1233         self.assert_lint('} else if', '')
   1234 
   1235     def test_spacing_for_binary_ops(self):
   1236         self.assert_lint('if (foo<=bar) {', 'Missing spaces around <='
   1237                          '  [whitespace/operators] [3]')
   1238         self.assert_lint('if (foo<bar) {', 'Missing spaces around <'
   1239                          '  [whitespace/operators] [3]')
   1240         self.assert_lint('if (foo<bar->baz) {', 'Missing spaces around <'
   1241                          '  [whitespace/operators] [3]')
   1242         self.assert_lint('if (foo<bar->bar) {', 'Missing spaces around <'
   1243                          '  [whitespace/operators] [3]')
   1244         self.assert_lint('typedef hash_map<Foo, Bar', 'Missing spaces around <'
   1245                          '  [whitespace/operators] [3]')
   1246         self.assert_lint('typedef hash_map<FoooooType, BaaaaarType,', '')
   1247         self.assert_lint('a<Foo> t+=b;', 'Missing spaces around +='
   1248                          '  [whitespace/operators] [3]')
   1249         self.assert_lint('a<Foo> t-=b;', 'Missing spaces around -='
   1250                          '  [whitespace/operators] [3]')
   1251         self.assert_lint('a<Foo*> t*=b;', 'Missing spaces around *='
   1252                          '  [whitespace/operators] [3]')
   1253         self.assert_lint('a<Foo*> t/=b;', 'Missing spaces around /='
   1254                          '  [whitespace/operators] [3]')
   1255         self.assert_lint('a<Foo*> t|=b;', 'Missing spaces around |='
   1256                          '  [whitespace/operators] [3]')
   1257         self.assert_lint('a<Foo*> t&=b;', 'Missing spaces around &='
   1258                          '  [whitespace/operators] [3]')
   1259         self.assert_lint('a<Foo*> t<<=b;', 'Missing spaces around <<='
   1260                          '  [whitespace/operators] [3]')
   1261         self.assert_lint('a<Foo*> t>>=b;', 'Missing spaces around >>='
   1262                          '  [whitespace/operators] [3]')
   1263         self.assert_lint('a<Foo*> t>>=&b|c;', 'Missing spaces around >>='
   1264                          '  [whitespace/operators] [3]')
   1265         self.assert_lint('a<Foo*> t<<=*b/c;', 'Missing spaces around <<='
   1266                          '  [whitespace/operators] [3]')
   1267         self.assert_lint('a<Foo> t -= b;', '')
   1268         self.assert_lint('a<Foo> t += b;', '')
   1269         self.assert_lint('a<Foo*> t *= b;', '')
   1270         self.assert_lint('a<Foo*> t /= b;', '')
   1271         self.assert_lint('a<Foo*> t |= b;', '')
   1272         self.assert_lint('a<Foo*> t &= b;', '')
   1273         self.assert_lint('a<Foo*> t <<= b;', '')
   1274         self.assert_lint('a<Foo*> t >>= b;', '')
   1275         self.assert_lint('a<Foo*> t >>= &b|c;', 'Missing spaces around |'
   1276                          '  [whitespace/operators] [3]')
   1277         self.assert_lint('a<Foo*> t <<= *b/c;', 'Missing spaces around /'
   1278                          '  [whitespace/operators] [3]')
   1279         self.assert_lint('a<Foo*> t <<= b/c; //Test', [
   1280                          'Should have a space between // and comment  '
   1281                          '[whitespace/comments] [4]', 'Missing'
   1282                          ' spaces around /  [whitespace/operators] [3]'])
   1283         self.assert_lint('a<Foo*> t <<= b||c;  //Test', ['One space before end'
   1284                          ' of line comments  [whitespace/comments] [5]',
   1285                          'Should have a space between // and comment  '
   1286                          '[whitespace/comments] [4]',
   1287                          'Missing spaces around ||  [whitespace/operators] [3]'])
   1288         self.assert_lint('a<Foo*> t <<= b&&c; // Test', 'Missing spaces around'
   1289                          ' &&  [whitespace/operators] [3]')
   1290         self.assert_lint('a<Foo*> t <<= b&&&c; // Test', 'Missing spaces around'
   1291                          ' &&  [whitespace/operators] [3]')
   1292         self.assert_lint('a<Foo*> t <<= b&&*c; // Test', 'Missing spaces around'
   1293                          ' &&  [whitespace/operators] [3]')
   1294         self.assert_lint('a<Foo*> t <<= b && *c; // Test', '')
   1295         self.assert_lint('a<Foo*> t <<= b && &c; // Test', '')
   1296         self.assert_lint('a<Foo*> t <<= b || &c;  /*Test', 'Complex multi-line '
   1297                          '/*...*/-style comment found. Lint may give bogus '
   1298                          'warnings.  Consider replacing these with //-style'
   1299                          ' comments, with #if 0...#endif, or with more clearly'
   1300                          ' structured multi-line comments.  [readability/multiline_comment] [5]')
   1301         self.assert_lint('a<Foo&> t <<= &b | &c;', '')
   1302         self.assert_lint('a<Foo*> t <<= &b & &c; // Test', '')
   1303         self.assert_lint('a<Foo*> t <<= *b / &c; // Test', '')
   1304         self.assert_lint('if (a=b == 1)', 'Missing spaces around =  [whitespace/operators] [4]')
   1305         self.assert_lint('a = 1<<20', 'Missing spaces around <<  [whitespace/operators] [3]')
   1306         self.assert_lint('if (a = b == 1)', '')
   1307         self.assert_lint('a = 1 << 20', '')
   1308         self.assert_multi_line_lint('#include "config.h"\n#include <sys/io.h>\n',
   1309                                     '')
   1310         self.assert_multi_line_lint('#include "config.h"\n#import <foo/bar.h>\n',
   1311                                     '')
   1312 
   1313     def test_spacing_before_last_semicolon(self):
   1314         self.assert_lint('call_function() ;',
   1315                          'Extra space before last semicolon. If this should be an '
   1316                          'empty statement, use { } instead.'
   1317                          '  [whitespace/semicolon] [5]')
   1318         self.assert_lint('while (true) ;',
   1319                          'Extra space before last semicolon. If this should be an '
   1320                          'empty statement, use { } instead.'
   1321                          '  [whitespace/semicolon] [5]')
   1322         self.assert_lint('default:;',
   1323                          'Semicolon defining empty statement. Use { } instead.'
   1324                          '  [whitespace/semicolon] [5]')
   1325         self.assert_lint('      ;',
   1326                          'Line contains only semicolon. If this should be an empty '
   1327                          'statement, use { } instead.'
   1328                          '  [whitespace/semicolon] [5]')
   1329         self.assert_lint('for (int i = 0; ;', '')
   1330 
   1331     # Static or global STL strings.
   1332     def test_static_or_global_stlstrings(self):
   1333         self.assert_lint('string foo;',
   1334                          'For a static/global string constant, use a C style '
   1335                          'string instead: "char foo[]".'
   1336                          '  [runtime/string] [4]')
   1337         self.assert_lint('string kFoo = "hello"; // English',
   1338                          'For a static/global string constant, use a C style '
   1339                          'string instead: "char kFoo[]".'
   1340                          '  [runtime/string] [4]')
   1341         self.assert_lint('static string foo;',
   1342                          'For a static/global string constant, use a C style '
   1343                          'string instead: "static char foo[]".'
   1344                          '  [runtime/string] [4]')
   1345         self.assert_lint('static const string foo;',
   1346                          'For a static/global string constant, use a C style '
   1347                          'string instead: "static const char foo[]".'
   1348                          '  [runtime/string] [4]')
   1349         self.assert_lint('string Foo::bar;',
   1350                          'For a static/global string constant, use a C style '
   1351                          'string instead: "char Foo::bar[]".'
   1352                          '  [runtime/string] [4]')
   1353         # Rare case.
   1354         self.assert_lint('string foo("foobar");',
   1355                          'For a static/global string constant, use a C style '
   1356                          'string instead: "char foo[]".'
   1357                          '  [runtime/string] [4]')
   1358         # Should not catch local or member variables.
   1359         self.assert_lint('    string foo', '')
   1360         # Should not catch functions.
   1361         self.assert_lint('string EmptyString() { return ""; }', '')
   1362         self.assert_lint('string EmptyString () { return ""; }', '')
   1363         self.assert_lint('string VeryLongNameFunctionSometimesEndsWith(\n'
   1364                          '    VeryLongNameType very_long_name_variable) {}', '')
   1365         self.assert_lint('template<>\n'
   1366                          'string FunctionTemplateSpecialization<SomeType>(\n'
   1367                          '      int x) { return ""; }', '')
   1368         self.assert_lint('template<>\n'
   1369                          'string FunctionTemplateSpecialization<vector<A::B>* >(\n'
   1370                          '      int x) { return ""; }', '')
   1371 
   1372         # should not catch methods of template classes.
   1373         self.assert_lint('string Class<Type>::Method() const\n'
   1374                          '{\n'
   1375                          '  return "";\n'
   1376                          '}\n', '')
   1377         self.assert_lint('string Class<Type>::Method(\n'
   1378                          '   int arg) const\n'
   1379                          '{\n'
   1380                          '  return "";\n'
   1381                          '}\n', '')
   1382 
   1383     def test_no_spaces_in_function_calls(self):
   1384         self.assert_lint('TellStory(1, 3);',
   1385                          '')
   1386         self.assert_lint('TellStory(1, 3 );',
   1387                          'Extra space before )'
   1388                          '  [whitespace/parens] [2]')
   1389         self.assert_lint('TellStory(1 /* wolf */, 3 /* pigs */);',
   1390                          '')
   1391         self.assert_multi_line_lint('#endif\n    );',
   1392                                     '')
   1393 
   1394     def test_two_spaces_between_code_and_comments(self):
   1395         self.assert_lint('} // namespace foo',
   1396                          '')
   1397         self.assert_lint('}// namespace foo',
   1398                          'One space before end of line comments'
   1399                          '  [whitespace/comments] [5]')
   1400         self.assert_lint('printf("foo"); // Outside quotes.',
   1401                          '')
   1402         self.assert_lint('int i = 0; // Having one space is fine.','')
   1403         self.assert_lint('int i = 0;  // Having two spaces is bad.',
   1404                          'One space before end of line comments'
   1405                          '  [whitespace/comments] [5]')
   1406         self.assert_lint('int i = 0;   // Having three spaces is bad.',
   1407                          'One space before end of line comments'
   1408                          '  [whitespace/comments] [5]')
   1409         self.assert_lint('// Top level comment', '')
   1410         self.assert_lint('    // Line starts with four spaces.', '')
   1411         self.assert_lint('foo();\n'
   1412                          '{ // A scope is opening.', '')
   1413         self.assert_lint('    foo();\n'
   1414                          '    { // An indented scope is opening.', '')
   1415         self.assert_lint('if (foo) { // not a pure scope',
   1416                          '')
   1417         self.assert_lint('printf("// In quotes.")', '')
   1418         self.assert_lint('printf("\\"%s // In quotes.")', '')
   1419         self.assert_lint('printf("%s", "// In quotes.")', '')
   1420 
   1421     def test_space_after_comment_marker(self):
   1422         self.assert_lint('//', '')
   1423         self.assert_lint('//x', 'Should have a space between // and comment'
   1424                          '  [whitespace/comments] [4]')
   1425         self.assert_lint('// x', '')
   1426         self.assert_lint('//----', '')
   1427         self.assert_lint('//====', '')
   1428         self.assert_lint('//////', '')
   1429         self.assert_lint('////// x', '')
   1430         self.assert_lint('/// x', '')
   1431         self.assert_lint('////x', 'Should have a space between // and comment'
   1432                          '  [whitespace/comments] [4]')
   1433 
   1434     def test_newline_at_eof(self):
   1435         def do_test(self, data, is_missing_eof):
   1436             error_collector = ErrorCollector(self.assert_)
   1437             self.process_file_data('foo.cpp', 'cpp', data.split('\n'),
   1438                                    error_collector)
   1439             # The warning appears only once.
   1440             self.assertEquals(
   1441                 int(is_missing_eof),
   1442                 error_collector.results().count(
   1443                     'Could not find a newline character at the end of the file.'
   1444                     '  [whitespace/ending_newline] [5]'))
   1445 
   1446         do_test(self, '// Newline\n// at EOF\n', False)
   1447         do_test(self, '// No newline\n// at EOF', True)
   1448 
   1449     def test_invalid_utf8(self):
   1450         def do_test(self, raw_bytes, has_invalid_utf8):
   1451             error_collector = ErrorCollector(self.assert_)
   1452             self.process_file_data('foo.cpp', 'cpp',
   1453                                    unicode(raw_bytes, 'utf8', 'replace').split('\n'),
   1454                                    error_collector)
   1455             # The warning appears only once.
   1456             self.assertEquals(
   1457                 int(has_invalid_utf8),
   1458                 error_collector.results().count(
   1459                     'Line contains invalid UTF-8'
   1460                     ' (or Unicode replacement character).'
   1461                     '  [readability/utf8] [5]'))
   1462 
   1463         do_test(self, 'Hello world\n', False)
   1464         do_test(self, '\xe9\x8e\xbd\n', False)
   1465         do_test(self, '\xe9x\x8e\xbd\n', True)
   1466         # This is the encoding of the replacement character itself (which
   1467         # you can see by evaluating codecs.getencoder('utf8')(u'\ufffd')).
   1468         do_test(self, '\xef\xbf\xbd\n', True)
   1469 
   1470     def test_is_blank_line(self):
   1471         self.assert_(cpp_style.is_blank_line(''))
   1472         self.assert_(cpp_style.is_blank_line(' '))
   1473         self.assert_(cpp_style.is_blank_line(' \t\r\n'))
   1474         self.assert_(not cpp_style.is_blank_line('int a;'))
   1475         self.assert_(not cpp_style.is_blank_line('{'))
   1476 
   1477     def test_blank_lines_check(self):
   1478         self.assert_blank_lines_check(['{\n', '\n', '\n', '}\n'], 1, 1)
   1479         self.assert_blank_lines_check(['  if (foo) {\n', '\n', '  }\n'], 1, 1)
   1480         self.assert_blank_lines_check(
   1481             ['\n', '// {\n', '\n', '\n', '// Comment\n', '{\n', '}\n'], 0, 0)
   1482         self.assert_blank_lines_check(['\n', 'run("{");\n', '\n'], 0, 0)
   1483         self.assert_blank_lines_check(['\n', '  if (foo) { return 0; }\n', '\n'], 0, 0)
   1484 
   1485     def test_allow_blank_line_before_closing_namespace(self):
   1486         error_collector = ErrorCollector(self.assert_)
   1487         self.process_file_data('foo.cpp', 'cpp',
   1488                                ['namespace {', '', '}  // namespace'],
   1489                                error_collector)
   1490         self.assertEquals(0, error_collector.results().count(
   1491             'Blank line at the end of a code block.  Is this needed?'
   1492             '  [whitespace/blank_line] [3]'))
   1493 
   1494     def test_allow_blank_line_before_if_else_chain(self):
   1495         error_collector = ErrorCollector(self.assert_)
   1496         self.process_file_data('foo.cpp', 'cpp',
   1497                                ['if (hoge) {',
   1498                                 '',  # No warning
   1499                                 '} else if (piyo) {',
   1500                                 '',  # No warning
   1501                                 '} else if (piyopiyo) {',
   1502                                 '  hoge = true;',  # No warning
   1503                                 '} else {',
   1504                                 '',  # Warning on this line
   1505                                 '}'],
   1506                                error_collector)
   1507         self.assertEquals(1, error_collector.results().count(
   1508             'Blank line at the end of a code block.  Is this needed?'
   1509             '  [whitespace/blank_line] [3]'))
   1510 
   1511     def test_else_on_same_line_as_closing_braces(self):
   1512         error_collector = ErrorCollector(self.assert_)
   1513         self.process_file_data('foo.cpp', 'cpp',
   1514                                ['if (hoge) {',
   1515                                 '',
   1516                                 '}',
   1517                                 ' else {'  # Warning on this line
   1518                                 '',
   1519                                 '}'],
   1520                                error_collector)
   1521         self.assertEquals(1, error_collector.results().count(
   1522             'An else should appear on the same line as the preceding }'
   1523             '  [whitespace/newline] [4]'))
   1524 
   1525     def test_else_clause_not_on_same_line_as_else(self):
   1526         self.assert_lint('    else DoSomethingElse();',
   1527                          'Else clause should never be on same line as else '
   1528                          '(use 2 lines)  [whitespace/newline] [4]')
   1529         self.assert_lint('    else ifDoSomethingElse();',
   1530                          'Else clause should never be on same line as else '
   1531                          '(use 2 lines)  [whitespace/newline] [4]')
   1532         self.assert_lint('    else if (blah) {', '')
   1533         self.assert_lint('    variable_ends_in_else = true;', '')
   1534 
   1535     def test_comma(self):
   1536         self.assert_lint('a = f(1,2);',
   1537                          'Missing space after ,  [whitespace/comma] [3]')
   1538         self.assert_lint('int tmp=a,a=b,b=tmp;',
   1539                          ['Missing spaces around =  [whitespace/operators] [4]',
   1540                           'Missing space after ,  [whitespace/comma] [3]'])
   1541         self.assert_lint('f(a, /* name */ b);', '')
   1542         self.assert_lint('f(a, /* name */b);', '')
   1543 
   1544     def test_pointer_reference_marker_location(self):
   1545         self.assert_lint('int* b;', '', 'foo.cpp')
   1546         self.assert_lint('int *b;',
   1547                          'Declaration has space between type name and * in int *b  [whitespace/declaration] [3]',
   1548                          'foo.cpp')
   1549         self.assert_lint('return *b;', '', 'foo.cpp')
   1550         self.assert_lint('int *b;', '', 'foo.c')
   1551         self.assert_lint('int* b;',
   1552                          'Declaration has space between * and variable name in int* b  [whitespace/declaration] [3]',
   1553                          'foo.c')
   1554         self.assert_lint('int& b;', '', 'foo.cpp')
   1555         self.assert_lint('int &b;',
   1556                          'Declaration has space between type name and & in int &b  [whitespace/declaration] [3]',
   1557                          'foo.cpp')
   1558         self.assert_lint('return &b;', '', 'foo.cpp')
   1559 
   1560     def test_indent(self):
   1561         self.assert_lint('static int noindent;', '')
   1562         self.assert_lint('    int fourSpaceIndent;', '')
   1563         self.assert_lint(' int oneSpaceIndent;',
   1564                          'Weird number of spaces at line-start.  '
   1565                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
   1566         self.assert_lint('   int threeSpaceIndent;',
   1567                          'Weird number of spaces at line-start.  '
   1568                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
   1569         self.assert_lint(' char* oneSpaceIndent = "public:";',
   1570                          'Weird number of spaces at line-start.  '
   1571                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
   1572         self.assert_lint(' public:', '')
   1573         self.assert_lint('  public:', '')
   1574         self.assert_lint('   public:', '')
   1575 
   1576     def test_label(self):
   1577         self.assert_lint('public:',
   1578                          'Labels should always be indented at least one space.  '
   1579                          'If this is a member-initializer list in a constructor, '
   1580                          'the colon should be on the line after the definition '
   1581                          'header.  [whitespace/labels] [4]')
   1582         self.assert_lint('  public:', '')
   1583         self.assert_lint('   public:', '')
   1584         self.assert_lint(' public:', '')
   1585         self.assert_lint('  public:', '')
   1586         self.assert_lint('   public:', '')
   1587 
   1588     def test_not_alabel(self):
   1589         self.assert_lint('MyVeryLongNamespace::MyVeryLongClassName::', '')
   1590 
   1591     def test_tab(self):
   1592         self.assert_lint('\tint a;',
   1593                          'Tab found; better to use spaces  [whitespace/tab] [1]')
   1594         self.assert_lint('int a = 5;\t// set a to 5',
   1595                          'Tab found; better to use spaces  [whitespace/tab] [1]')
   1596 
   1597     def test_unnamed_namespaces_in_headers(self):
   1598         self.assert_language_rules_check(
   1599             'foo.h', 'namespace {',
   1600             'Do not use unnamed namespaces in header files.  See'
   1601             ' http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
   1602             ' for more information.  [build/namespaces] [4]')
   1603         # namespace registration macros are OK.
   1604         self.assert_language_rules_check('foo.h', 'namespace {  \\', '')
   1605         # named namespaces are OK.
   1606         self.assert_language_rules_check('foo.h', 'namespace foo {', '')
   1607         self.assert_language_rules_check('foo.h', 'namespace foonamespace {', '')
   1608         self.assert_language_rules_check('foo.cpp', 'namespace {', '')
   1609         self.assert_language_rules_check('foo.cpp', 'namespace foo {', '')
   1610 
   1611     def test_build_class(self):
   1612         # Test that the linter can parse to the end of class definitions,
   1613         # and that it will report when it can't.
   1614         # Use multi-line linter because it performs the ClassState check.
   1615         self.assert_multi_line_lint(
   1616             'class Foo {',
   1617             'Failed to find complete declaration of class Foo'
   1618             '  [build/class] [5]')
   1619         # Don't warn on forward declarations of various types.
   1620         self.assert_multi_line_lint(
   1621             'class Foo;',
   1622             '')
   1623         self.assert_multi_line_lint(
   1624             '''struct Foo*
   1625                  foo = NewFoo();''',
   1626             '')
   1627         # Here is an example where the linter gets confused, even though
   1628         # the code doesn't violate the style guide.
   1629         self.assert_multi_line_lint(
   1630             '''class Foo
   1631             #ifdef DERIVE_FROM_GOO
   1632               : public Goo {
   1633             #else
   1634               : public Hoo {
   1635             #endif
   1636               };''',
   1637             'Failed to find complete declaration of class Foo'
   1638             '  [build/class] [5]')
   1639 
   1640     def test_build_end_comment(self):
   1641         # The crosstool compiler we currently use will fail to compile the
   1642         # code in this test, so we might consider removing the lint check.
   1643         self.assert_lint('#endif Not a comment',
   1644                          'Uncommented text after #endif is non-standard.'
   1645                          '  Use a comment.'
   1646                          '  [build/endif_comment] [5]')
   1647 
   1648     def test_build_forward_decl(self):
   1649         # The crosstool compiler we currently use will fail to compile the
   1650         # code in this test, so we might consider removing the lint check.
   1651         self.assert_lint('class Foo::Goo;',
   1652                          'Inner-style forward declarations are invalid.'
   1653                          '  Remove this line.'
   1654                          '  [build/forward_decl] [5]')
   1655 
   1656     def test_build_header_guard(self):
   1657         file_path = 'mydir/Foo.h'
   1658 
   1659         # We can't rely on our internal stuff to get a sane path on the open source
   1660         # side of things, so just parse out the suggested header guard. This
   1661         # doesn't allow us to test the suggested header guard, but it does let us
   1662         # test all the other header tests.
   1663         error_collector = ErrorCollector(self.assert_)
   1664         self.process_file_data(file_path, 'h', [], error_collector)
   1665         expected_guard = ''
   1666         matcher = re.compile(
   1667             'No \#ifndef header guard found\, suggested CPP variable is\: ([A-Za-z_0-9]+) ')
   1668         for error in error_collector.result_list():
   1669             matches = matcher.match(error)
   1670             if matches:
   1671                 expected_guard = matches.group(1)
   1672                 break
   1673 
   1674         # Make sure we extracted something for our header guard.
   1675         self.assertNotEqual(expected_guard, '')
   1676 
   1677         # Wrong guard
   1678         error_collector = ErrorCollector(self.assert_)
   1679         self.process_file_data(file_path, 'h',
   1680                                ['#ifndef FOO_H', '#define FOO_H'], error_collector)
   1681         self.assertEquals(
   1682             1,
   1683             error_collector.result_list().count(
   1684                 '#ifndef header guard has wrong style, please use: %s'
   1685                 '  [build/header_guard] [5]' % expected_guard),
   1686             error_collector.result_list())
   1687 
   1688         # No define
   1689         error_collector = ErrorCollector(self.assert_)
   1690         self.process_file_data(file_path, 'h',
   1691                                ['#ifndef %s' % expected_guard], error_collector)
   1692         self.assertEquals(
   1693             1,
   1694             error_collector.result_list().count(
   1695                 'No #ifndef header guard found, suggested CPP variable is: %s'
   1696                 '  [build/header_guard] [5]' % expected_guard),
   1697             error_collector.result_list())
   1698 
   1699         # Mismatched define
   1700         error_collector = ErrorCollector(self.assert_)
   1701         self.process_file_data(file_path, 'h',
   1702                                ['#ifndef %s' % expected_guard,
   1703                                 '#define FOO_H'],
   1704                                error_collector)
   1705         self.assertEquals(
   1706             1,
   1707             error_collector.result_list().count(
   1708                 'No #ifndef header guard found, suggested CPP variable is: %s'
   1709                 '  [build/header_guard] [5]' % expected_guard),
   1710             error_collector.result_list())
   1711 
   1712         # No header guard errors
   1713         error_collector = ErrorCollector(self.assert_)
   1714         self.process_file_data(file_path, 'h',
   1715                                ['#ifndef %s' % expected_guard,
   1716                                 '#define %s' % expected_guard,
   1717                                 '#endif // %s' % expected_guard],
   1718                                error_collector)
   1719         for line in error_collector.result_list():
   1720             if line.find('build/header_guard') != -1:
   1721                 self.fail('Unexpected error: %s' % line)
   1722 
   1723         # Completely incorrect header guard
   1724         error_collector = ErrorCollector(self.assert_)
   1725         self.process_file_data(file_path, 'h',
   1726                                ['#ifndef FOO',
   1727                                 '#define FOO',
   1728                                 '#endif  // FOO'],
   1729                                error_collector)
   1730         self.assertEquals(
   1731             1,
   1732             error_collector.result_list().count(
   1733                 '#ifndef header guard has wrong style, please use: %s'
   1734                 '  [build/header_guard] [5]' % expected_guard),
   1735             error_collector.result_list())
   1736 
   1737     def test_build_printf_format(self):
   1738         self.assert_lint(
   1739             r'printf("\%%d", value);',
   1740             '%, [, (, and { are undefined character escapes.  Unescape them.'
   1741             '  [build/printf_format] [3]')
   1742 
   1743         self.assert_lint(
   1744             r'snprintf(buffer, sizeof(buffer), "\[%d", value);',
   1745             '%, [, (, and { are undefined character escapes.  Unescape them.'
   1746             '  [build/printf_format] [3]')
   1747 
   1748         self.assert_lint(
   1749             r'fprintf(file, "\(%d", value);',
   1750             '%, [, (, and { are undefined character escapes.  Unescape them.'
   1751             '  [build/printf_format] [3]')
   1752 
   1753         self.assert_lint(
   1754             r'vsnprintf(buffer, sizeof(buffer), "\\\{%d", ap);',
   1755             '%, [, (, and { are undefined character escapes.  Unescape them.'
   1756             '  [build/printf_format] [3]')
   1757 
   1758         # Don't warn if double-slash precedes the symbol
   1759         self.assert_lint(r'printf("\\%%%d", value);',
   1760                          '')
   1761 
   1762     def test_runtime_printf_format(self):
   1763         self.assert_lint(
   1764             r'fprintf(file, "%q", value);',
   1765             '%q in format strings is deprecated.  Use %ll instead.'
   1766             '  [runtime/printf_format] [3]')
   1767 
   1768         self.assert_lint(
   1769             r'aprintf(file, "The number is %12q", value);',
   1770             '%q in format strings is deprecated.  Use %ll instead.'
   1771             '  [runtime/printf_format] [3]')
   1772 
   1773         self.assert_lint(
   1774             r'printf(file, "The number is" "%-12q", value);',
   1775             '%q in format strings is deprecated.  Use %ll instead.'
   1776             '  [runtime/printf_format] [3]')
   1777 
   1778         self.assert_lint(
   1779             r'printf(file, "The number is" "%+12q", value);',
   1780             '%q in format strings is deprecated.  Use %ll instead.'
   1781             '  [runtime/printf_format] [3]')
   1782 
   1783         self.assert_lint(
   1784             r'printf(file, "The number is" "% 12q", value);',
   1785             '%q in format strings is deprecated.  Use %ll instead.'
   1786             '  [runtime/printf_format] [3]')
   1787 
   1788         self.assert_lint(
   1789             r'snprintf(file, "Never mix %d and %1$d parmaeters!", value);',
   1790             '%N$ formats are unconventional.  Try rewriting to avoid them.'
   1791             '  [runtime/printf_format] [2]')
   1792 
   1793     def assert_lintLogCodeOnError(self, code, expected_message):
   1794         # Special assert_lint which logs the input code on error.
   1795         result = self.perform_single_line_lint(code, 'foo.cpp')
   1796         if result != expected_message:
   1797             self.fail('For code: "%s"\nGot: "%s"\nExpected: "%s"'
   1798                       % (code, result, expected_message))
   1799 
   1800     def test_build_storage_class(self):
   1801         qualifiers = [None, 'const', 'volatile']
   1802         signs = [None, 'signed', 'unsigned']
   1803         types = ['void', 'char', 'int', 'float', 'double',
   1804                  'schar', 'int8', 'uint8', 'int16', 'uint16',
   1805                  'int32', 'uint32', 'int64', 'uint64']
   1806         storage_classes = ['auto', 'extern', 'register', 'static', 'typedef']
   1807 
   1808         build_storage_class_error_message = (
   1809             'Storage class (static, extern, typedef, etc) should be first.'
   1810             '  [build/storage_class] [5]')
   1811 
   1812         # Some explicit cases. Legal in C++, deprecated in C99.
   1813         self.assert_lint('const int static foo = 5;',
   1814                          build_storage_class_error_message)
   1815 
   1816         self.assert_lint('char static foo;',
   1817                          build_storage_class_error_message)
   1818 
   1819         self.assert_lint('double const static foo = 2.0;',
   1820                          build_storage_class_error_message)
   1821 
   1822         self.assert_lint('uint64 typedef unsignedLongLong;',
   1823                          build_storage_class_error_message)
   1824 
   1825         self.assert_lint('int register foo = 0;',
   1826                          build_storage_class_error_message)
   1827 
   1828         # Since there are a very large number of possibilities, randomly
   1829         # construct declarations.
   1830         # Make sure that the declaration is logged if there's an error.
   1831         # Seed generator with an integer for absolute reproducibility.
   1832         random.seed(25)
   1833         for unused_i in range(10):
   1834             # Build up random list of non-storage-class declaration specs.
   1835             other_decl_specs = [random.choice(qualifiers), random.choice(signs),
   1836                                 random.choice(types)]
   1837             # remove None
   1838             other_decl_specs = filter(lambda x: x is not None, other_decl_specs)
   1839 
   1840             # shuffle
   1841             random.shuffle(other_decl_specs)
   1842 
   1843             # insert storage class after the first
   1844             storage_class = random.choice(storage_classes)
   1845             insertion_point = random.randint(1, len(other_decl_specs))
   1846             decl_specs = (other_decl_specs[0:insertion_point]
   1847                           + [storage_class]
   1848                           + other_decl_specs[insertion_point:])
   1849 
   1850             self.assert_lintLogCodeOnError(
   1851                 ' '.join(decl_specs) + ';',
   1852                 build_storage_class_error_message)
   1853 
   1854             # but no error if storage class is first
   1855             self.assert_lintLogCodeOnError(
   1856                 storage_class + ' ' + ' '.join(other_decl_specs),
   1857                 '')
   1858 
   1859     def test_legal_copyright(self):
   1860         legal_copyright_message = (
   1861             'No copyright message found.  '
   1862             'You should have a line: "Copyright [year] <Copyright Owner>"'
   1863             '  [legal/copyright] [5]')
   1864 
   1865         copyright_line = '// Copyright 2008 Google Inc. All Rights Reserved.'
   1866 
   1867         file_path = 'mydir/googleclient/foo.cpp'
   1868 
   1869         # There should be a copyright message in the first 10 lines
   1870         error_collector = ErrorCollector(self.assert_)
   1871         self.process_file_data(file_path, 'cpp', [], error_collector)
   1872         self.assertEquals(
   1873             1,
   1874             error_collector.result_list().count(legal_copyright_message))
   1875 
   1876         error_collector = ErrorCollector(self.assert_)
   1877         self.process_file_data(
   1878             file_path, 'cpp',
   1879             ['' for unused_i in range(10)] + [copyright_line],
   1880             error_collector)
   1881         self.assertEquals(
   1882             1,
   1883             error_collector.result_list().count(legal_copyright_message))
   1884 
   1885         # Test that warning isn't issued if Copyright line appears early enough.
   1886         error_collector = ErrorCollector(self.assert_)
   1887         self.process_file_data(file_path, 'cpp', [copyright_line], error_collector)
   1888         for message in error_collector.result_list():
   1889             if message.find('legal/copyright') != -1:
   1890                 self.fail('Unexpected error: %s' % message)
   1891 
   1892         error_collector = ErrorCollector(self.assert_)
   1893         self.process_file_data(
   1894             file_path, 'cpp',
   1895             ['' for unused_i in range(9)] + [copyright_line],
   1896             error_collector)
   1897         for message in error_collector.result_list():
   1898             if message.find('legal/copyright') != -1:
   1899                 self.fail('Unexpected error: %s' % message)
   1900 
   1901     def test_invalid_increment(self):
   1902         self.assert_lint('*count++;',
   1903                          'Changing pointer instead of value (or unused value of '
   1904                          'operator*).  [runtime/invalid_increment] [5]')
   1905 
   1906 
   1907 class CleansedLinesTest(unittest.TestCase):
   1908     def test_init(self):
   1909         lines = ['Line 1',
   1910                  'Line 2',
   1911                  'Line 3 // Comment test',
   1912                  'Line 4 "foo"']
   1913 
   1914         clean_lines = cpp_style.CleansedLines(lines)
   1915         self.assertEquals(lines, clean_lines.raw_lines)
   1916         self.assertEquals(4, clean_lines.num_lines())
   1917 
   1918         self.assertEquals(['Line 1',
   1919                            'Line 2',
   1920                            'Line 3 ',
   1921                            'Line 4 "foo"'],
   1922                           clean_lines.lines)
   1923 
   1924         self.assertEquals(['Line 1',
   1925                            'Line 2',
   1926                            'Line 3 ',
   1927                            'Line 4 ""'],
   1928                           clean_lines.elided)
   1929 
   1930     def test_init_empty(self):
   1931         clean_lines = cpp_style.CleansedLines([])
   1932         self.assertEquals([], clean_lines.raw_lines)
   1933         self.assertEquals(0, clean_lines.num_lines())
   1934 
   1935     def test_collapse_strings(self):
   1936         collapse = cpp_style.CleansedLines.collapse_strings
   1937         self.assertEquals('""', collapse('""'))             # ""     (empty)
   1938         self.assertEquals('"""', collapse('"""'))           # """    (bad)
   1939         self.assertEquals('""', collapse('"xyz"'))          # "xyz"  (string)
   1940         self.assertEquals('""', collapse('"\\\""'))         # "\""   (string)
   1941         self.assertEquals('""', collapse('"\'"'))           # "'"    (string)
   1942         self.assertEquals('"\"', collapse('"\"'))           # "\"    (bad)
   1943         self.assertEquals('""', collapse('"\\\\"'))         # "\\"   (string)
   1944         self.assertEquals('"', collapse('"\\\\\\"'))        # "\\\"  (bad)
   1945         self.assertEquals('""', collapse('"\\\\\\\\"'))     # "\\\\" (string)
   1946 
   1947         self.assertEquals('\'\'', collapse('\'\''))         # ''     (empty)
   1948         self.assertEquals('\'\'', collapse('\'a\''))        # 'a'    (char)
   1949         self.assertEquals('\'\'', collapse('\'\\\'\''))     # '\''   (char)
   1950         self.assertEquals('\'', collapse('\'\\\''))         # '\'    (bad)
   1951         self.assertEquals('', collapse('\\012'))            # '\012' (char)
   1952         self.assertEquals('', collapse('\\xfF0'))           # '\xfF0' (char)
   1953         self.assertEquals('', collapse('\\n'))              # '\n' (char)
   1954         self.assertEquals('\#', collapse('\\#'))            # '\#' (bad)
   1955 
   1956         self.assertEquals('StringReplace(body, "", "");',
   1957                           collapse('StringReplace(body, "\\\\", "\\\\\\\\");'))
   1958         self.assertEquals('\'\' ""',
   1959                           collapse('\'"\' "foo"'))
   1960 
   1961 
   1962 class OrderOfIncludesTest(CppStyleTestBase):
   1963     def setUp(self):
   1964         self.include_state = cpp_style._IncludeState()
   1965 
   1966         # Cheat os.path.abspath called in FileInfo class.
   1967         self.os_path_abspath_orig = os.path.abspath
   1968         os.path.abspath = lambda value: value
   1969 
   1970     def tearDown(self):
   1971         os.path.abspath = self.os_path_abspath_orig
   1972 
   1973     def test_try_drop_common_suffixes(self):
   1974         self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo-inl.h'))
   1975         self.assertEqual('foo/bar/foo',
   1976                          cpp_style._drop_common_suffixes('foo/bar/foo_inl.h'))
   1977         self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo.cpp'))
   1978         self.assertEqual('foo/foo_unusualinternal',
   1979                          cpp_style._drop_common_suffixes('foo/foo_unusualinternal.h'))
   1980         self.assertEqual('',
   1981                          cpp_style._drop_common_suffixes('_test.cpp'))
   1982         self.assertEqual('test',
   1983                          cpp_style._drop_common_suffixes('test.cpp'))
   1984 
   1985 
   1986 class OrderOfIncludesTest(CppStyleTestBase):
   1987     def setUp(self):
   1988         self.include_state = cpp_style._IncludeState()
   1989 
   1990         # Cheat os.path.abspath called in FileInfo class.
   1991         self.os_path_abspath_orig = os.path.abspath
   1992         os.path.abspath = lambda value: value
   1993 
   1994     def tearDown(self):
   1995         os.path.abspath = self.os_path_abspath_orig
   1996 
   1997     def test_check_next_include_order__no_config(self):
   1998         self.assertEqual('Header file should not contain WebCore config.h.',
   1999                          self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, True))
   2000 
   2001     def test_check_next_include_order__no_self(self):
   2002         self.assertEqual('Header file should not contain itself.',
   2003                          self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, True))
   2004         # Test actual code to make sure that header types are correctly assigned.
   2005         self.assert_language_rules_check('Foo.h',
   2006                                          '#include "Foo.h"\n',
   2007                                          'Header file should not contain itself. Should be: alphabetically sorted.'
   2008                                          '  [build/include_order] [4]')
   2009         self.assert_language_rules_check('FooBar.h',
   2010                                          '#include "Foo.h"\n',
   2011                                          '')
   2012 
   2013     def test_check_next_include_order__likely_then_config(self):
   2014         self.assertEqual('Found header this file implements before WebCore config.h.',
   2015                          self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, False))
   2016         self.assertEqual('Found WebCore config.h after a header this file implements.',
   2017                          self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, False))
   2018 
   2019     def test_check_next_include_order__other_then_config(self):
   2020         self.assertEqual('Found other header before WebCore config.h.',
   2021                          self.include_state.check_next_include_order(cpp_style._OTHER_HEADER, False))
   2022         self.assertEqual('Found WebCore config.h after other header.',
   2023                          self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, False))
   2024 
   2025     def test_check_next_include_order__config_then_other_then_likely(self):
   2026         self.assertEqual('', self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, False))
   2027         self.assertEqual('Found other header before a header this file implements.',
   2028                          self.include_state.check_next_include_order(cpp_style._OTHER_HEADER, False))
   2029         self.assertEqual('Found header this file implements after other header.',
   2030                          self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, False))
   2031 
   2032     def test_check_alphabetical_include_order(self):
   2033         self.assert_language_rules_check('foo.h',
   2034                                          '#include "a.h"\n'
   2035                                          '#include "c.h"\n'
   2036                                          '#include "b.h"\n',
   2037                                          'Alphabetical sorting problem.  [build/include_order] [4]')
   2038 
   2039         self.assert_language_rules_check('foo.h',
   2040                                          '#include "a.h"\n'
   2041                                          '#include "b.h"\n'
   2042                                          '#include "c.h"\n',
   2043                                          '')
   2044 
   2045         self.assert_language_rules_check('foo.h',
   2046                                          '#include <assert.h>\n'
   2047                                          '#include "bar.h"\n',
   2048                                          'Alphabetical sorting problem.  [build/include_order] [4]')
   2049 
   2050         self.assert_language_rules_check('foo.h',
   2051                                          '#include "bar.h"\n'
   2052                                          '#include <assert.h>\n',
   2053                                          '')
   2054 
   2055     def test_check_line_break_after_own_header(self):
   2056         self.assert_language_rules_check('foo.cpp',
   2057                                          '#include "config.h"\n'
   2058                                          '#include "foo.h"\n'
   2059                                          '#include "bar.h"\n',
   2060                                          'You should add a blank line after implementation file\'s own header.  [build/include_order] [4]')
   2061 
   2062         self.assert_language_rules_check('foo.cpp',
   2063                                          '#include "config.h"\n'
   2064                                          '#include "foo.h"\n'
   2065                                          '\n'
   2066                                          '#include "bar.h"\n',
   2067                                          '')
   2068 
   2069     def test_check_preprocessor_in_include_section(self):
   2070         self.assert_language_rules_check('foo.cpp',
   2071                                          '#include "config.h"\n'
   2072                                          '#include "foo.h"\n'
   2073                                          '\n'
   2074                                          '#ifdef BAZ\n'
   2075                                          '#include "baz.h"\n'
   2076                                          '#else\n'
   2077                                          '#include "foobar.h"\n'
   2078                                          '#endif"\n'
   2079                                          '#include "bar.h"\n', # No flag because previous is in preprocessor section
   2080                                          '')
   2081 
   2082         self.assert_language_rules_check('foo.cpp',
   2083                                          '#include "config.h"\n'
   2084                                          '#include "foo.h"\n'
   2085                                          '\n'
   2086                                          '#ifdef BAZ\n'
   2087                                          '#include "baz.h"\n'
   2088                                          '#endif"\n'
   2089                                          '#include "bar.h"\n'
   2090                                          '#include "a.h"\n', # Should still flag this.
   2091                                          'Alphabetical sorting problem.  [build/include_order] [4]')
   2092 
   2093         self.assert_language_rules_check('foo.cpp',
   2094                                          '#include "config.h"\n'
   2095                                          '#include "foo.h"\n'
   2096                                          '\n'
   2097                                          '#ifdef BAZ\n'
   2098                                          '#include "baz.h"\n'
   2099                                          '#include "bar.h"\n' #Should still flag this
   2100                                          '#endif"\n',
   2101                                          'Alphabetical sorting problem.  [build/include_order] [4]')
   2102 
   2103         self.assert_language_rules_check('foo.cpp',
   2104                                          '#include "config.h"\n'
   2105                                          '#include "foo.h"\n'
   2106                                          '\n'
   2107                                          '#ifdef BAZ\n'
   2108                                          '#include "baz.h"\n'
   2109                                          '#endif"\n'
   2110                                          '#ifdef FOOBAR\n'
   2111                                          '#include "foobar.h"\n'
   2112                                          '#endif"\n'
   2113                                          '#include "bar.h"\n'
   2114                                          '#include "a.h"\n', # Should still flag this.
   2115                                          'Alphabetical sorting problem.  [build/include_order] [4]')
   2116 
   2117         # Check that after an already included error, the sorting rules still work.
   2118         self.assert_language_rules_check('foo.cpp',
   2119                                          '#include "config.h"\n'
   2120                                          '#include "foo.h"\n'
   2121                                          '\n'
   2122                                          '#include "foo.h"\n'
   2123                                          '#include "g.h"\n',
   2124                                          '"foo.h" already included at foo.cpp:1  [build/include] [4]')
   2125 
   2126     def test_check_wtf_includes(self):
   2127         self.assert_language_rules_check('foo.cpp',
   2128                                          '#include "config.h"\n'
   2129                                          '#include "foo.h"\n'
   2130                                          '\n'
   2131                                          '#include <wtf/Assertions.h>\n',
   2132                                          '')
   2133         self.assert_language_rules_check('foo.cpp',
   2134                                          '#include "config.h"\n'
   2135                                          '#include "foo.h"\n'
   2136                                          '\n'
   2137                                          '#include "wtf/Assertions.h"\n',
   2138                                          'wtf includes should be <wtf/file.h> instead of "wtf/file.h".'
   2139                                          '  [build/include] [4]')
   2140 
   2141     def test_classify_include(self):
   2142         classify_include = cpp_style._classify_include
   2143         include_state = cpp_style._IncludeState()
   2144         self.assertEqual(cpp_style._CONFIG_HEADER,
   2145                          classify_include('foo/foo.cpp',
   2146                                           'config.h',
   2147                                           False, include_state))
   2148         self.assertEqual(cpp_style._PRIMARY_HEADER,
   2149                          classify_include('foo/internal/foo.cpp',
   2150                                           'foo/public/foo.h',
   2151                                           False, include_state))
   2152         self.assertEqual(cpp_style._PRIMARY_HEADER,
   2153                          classify_include('foo/internal/foo.cpp',
   2154                                           'foo/other/public/foo.h',
   2155                                           False, include_state))
   2156         self.assertEqual(cpp_style._OTHER_HEADER,
   2157                          classify_include('foo/internal/foo.cpp',
   2158                                           'foo/other/public/foop.h',
   2159                                           False, include_state))
   2160         self.assertEqual(cpp_style._OTHER_HEADER,
   2161                          classify_include('foo/foo.cpp',
   2162                                           'string',
   2163                                           True, include_state))
   2164         self.assertEqual(cpp_style._PRIMARY_HEADER,
   2165                          classify_include('fooCustom.cpp',
   2166                                           'foo.h',
   2167                                           False, include_state))
   2168         self.assertEqual(cpp_style._PRIMARY_HEADER,
   2169                          classify_include('PrefixFooCustom.cpp',
   2170                                           'Foo.h',
   2171                                           False, include_state))
   2172         self.assertEqual(cpp_style._MOC_HEADER,
   2173                          classify_include('foo.cpp',
   2174                                           'foo.moc',
   2175                                           False, include_state))
   2176         self.assertEqual(cpp_style._MOC_HEADER,
   2177                          classify_include('foo.cpp',
   2178                                           'moc_foo.cpp',
   2179                                           False, include_state))
   2180         # Tricky example where both includes might be classified as primary.
   2181         self.assert_language_rules_check('ScrollbarThemeWince.cpp',
   2182                                          '#include "config.h"\n'
   2183                                          '#include "ScrollbarThemeWince.h"\n'
   2184                                          '\n'
   2185                                          '#include "Scrollbar.h"\n',
   2186                                          '')
   2187         self.assert_language_rules_check('ScrollbarThemeWince.cpp',
   2188                                          '#include "config.h"\n'
   2189                                          '#include "Scrollbar.h"\n'
   2190                                          '\n'
   2191                                          '#include "ScrollbarThemeWince.h"\n',
   2192                                          'Found header this file implements after a header this file implements.'
   2193                                          ' Should be: config.h, primary header, blank line, and then alphabetically sorted.'
   2194                                          '  [build/include_order] [4]')
   2195         self.assert_language_rules_check('ResourceHandleWin.cpp',
   2196                                          '#include "config.h"\n'
   2197                                          '#include "ResourceHandle.h"\n'
   2198                                          '\n'
   2199                                          '#include "ResourceHandleWin.h"\n',
   2200                                          '')
   2201 
   2202     def test_try_drop_common_suffixes(self):
   2203         self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo-inl.h'))
   2204         self.assertEqual('foo/bar/foo',
   2205                          cpp_style._drop_common_suffixes('foo/bar/foo_inl.h'))
   2206         self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo.cpp'))
   2207         self.assertEqual('foo/foo_unusualinternal',
   2208                          cpp_style._drop_common_suffixes('foo/foo_unusualinternal.h'))
   2209         self.assertEqual('',
   2210                          cpp_style._drop_common_suffixes('_test.cpp'))
   2211         self.assertEqual('test',
   2212                          cpp_style._drop_common_suffixes('test.cpp'))
   2213         self.assertEqual('test',
   2214                          cpp_style._drop_common_suffixes('test.cpp'))
   2215 
   2216 class CheckForFunctionLengthsTest(CppStyleTestBase):
   2217     def setUp(self):
   2218         # Reducing these thresholds for the tests speeds up tests significantly.
   2219         self.old_normal_trigger = cpp_style._FunctionState._NORMAL_TRIGGER
   2220         self.old_test_trigger = cpp_style._FunctionState._TEST_TRIGGER
   2221 
   2222         cpp_style._FunctionState._NORMAL_TRIGGER = 10
   2223         cpp_style._FunctionState._TEST_TRIGGER = 25
   2224 
   2225     def tearDown(self):
   2226         cpp_style._FunctionState._NORMAL_TRIGGER = self.old_normal_trigger
   2227         cpp_style._FunctionState._TEST_TRIGGER = self.old_test_trigger
   2228 
   2229     # FIXME: Eliminate the need for this function.
   2230     def set_verbosity(self, verbosity):
   2231         """Set new test verbosity and return old test verbosity."""
   2232         old_verbosity = self.verbosity
   2233         self.verbosity = verbosity
   2234         return old_verbosity
   2235 
   2236     def assert_function_lengths_check(self, code, expected_message):
   2237         """Check warnings for long function bodies are as expected.
   2238 
   2239         Args:
   2240           code: C++ source code expected to generate a warning message.
   2241           expected_message: Message expected to be generated by the C++ code.
   2242         """
   2243         self.assertEquals(expected_message,
   2244                           self.perform_function_lengths_check(code))
   2245 
   2246     def trigger_lines(self, error_level):
   2247         """Return number of lines needed to trigger a function length warning.
   2248 
   2249         Args:
   2250           error_level: --v setting for cpp_style.
   2251 
   2252         Returns:
   2253           Number of lines needed to trigger a function length warning.
   2254         """
   2255         return cpp_style._FunctionState._NORMAL_TRIGGER * 2 ** error_level
   2256 
   2257     def trigger_test_lines(self, error_level):
   2258         """Return number of lines needed to trigger a test function length warning.
   2259 
   2260         Args:
   2261           error_level: --v setting for cpp_style.
   2262 
   2263         Returns:
   2264           Number of lines needed to trigger a test function length warning.
   2265         """
   2266         return cpp_style._FunctionState._TEST_TRIGGER * 2 ** error_level
   2267 
   2268     def assert_function_length_check_definition(self, lines, error_level):
   2269         """Generate long function definition and check warnings are as expected.
   2270 
   2271         Args:
   2272           lines: Number of lines to generate.
   2273           error_level:  --v setting for cpp_style.
   2274         """
   2275         trigger_level = self.trigger_lines(self.verbosity)
   2276         self.assert_function_lengths_check(
   2277             'void test(int x)' + self.function_body(lines),
   2278             ('Small and focused functions are preferred: '
   2279              'test() has %d non-comment lines '
   2280              '(error triggered by exceeding %d lines).'
   2281              '  [readability/fn_size] [%d]'
   2282              % (lines, trigger_level, error_level)))
   2283 
   2284     def assert_function_length_check_definition_ok(self, lines):
   2285         """Generate shorter function definition and check no warning is produced.
   2286 
   2287         Args:
   2288           lines: Number of lines to generate.
   2289         """
   2290         self.assert_function_lengths_check(
   2291             'void test(int x)' + self.function_body(lines),
   2292             '')
   2293 
   2294     def assert_function_length_check_at_error_level(self, error_level):
   2295         """Generate and check function at the trigger level for --v setting.
   2296 
   2297         Args:
   2298           error_level: --v setting for cpp_style.
   2299         """
   2300         self.assert_function_length_check_definition(self.trigger_lines(error_level),
   2301                                                      error_level)
   2302 
   2303     def assert_function_length_check_below_error_level(self, error_level):
   2304         """Generate and check function just below the trigger level for --v setting.
   2305 
   2306         Args:
   2307           error_level: --v setting for cpp_style.
   2308         """
   2309         self.assert_function_length_check_definition(self.trigger_lines(error_level) - 1,
   2310                                                      error_level - 1)
   2311 
   2312     def assert_function_length_check_above_error_level(self, error_level):
   2313         """Generate and check function just above the trigger level for --v setting.
   2314 
   2315         Args:
   2316           error_level: --v setting for cpp_style.
   2317         """
   2318         self.assert_function_length_check_definition(self.trigger_lines(error_level) + 1,
   2319                                                      error_level)
   2320 
   2321     def function_body(self, number_of_lines):
   2322         return ' {\n' + '    this_is_just_a_test();\n' * number_of_lines + '}'
   2323 
   2324     def function_body_with_blank_lines(self, number_of_lines):
   2325         return ' {\n' + '    this_is_just_a_test();\n\n' * number_of_lines + '}'
   2326 
   2327     def function_body_with_no_lints(self, number_of_lines):
   2328         return ' {\n' + '    this_is_just_a_test();  // NOLINT\n' * number_of_lines + '}'
   2329 
   2330     # Test line length checks.
   2331     def test_function_length_check_declaration(self):
   2332         self.assert_function_lengths_check(
   2333             'void test();',  # Not a function definition
   2334             '')
   2335 
   2336     def test_function_length_check_declaration_with_block_following(self):
   2337         self.assert_function_lengths_check(
   2338             ('void test();\n'
   2339              + self.function_body(66)),  # Not a function definition
   2340             '')
   2341 
   2342     def test_function_length_check_class_definition(self):
   2343         self.assert_function_lengths_check(  # Not a function definition
   2344             'class Test' + self.function_body(66) + ';',
   2345             '')
   2346 
   2347     def test_function_length_check_trivial(self):
   2348         self.assert_function_lengths_check(
   2349             'void test() {}',  # Not counted
   2350             '')
   2351 
   2352     def test_function_length_check_empty(self):
   2353         self.assert_function_lengths_check(
   2354             'void test() {\n}',
   2355             '')
   2356 
   2357     def test_function_length_check_definition_below_severity0(self):
   2358         old_verbosity = self.set_verbosity(0)
   2359         self.assert_function_length_check_definition_ok(self.trigger_lines(0) - 1)
   2360         self.set_verbosity(old_verbosity)
   2361 
   2362     def test_function_length_check_definition_at_severity0(self):
   2363         old_verbosity = self.set_verbosity(0)
   2364         self.assert_function_length_check_definition_ok(self.trigger_lines(0))
   2365         self.set_verbosity(old_verbosity)
   2366 
   2367     def test_function_length_check_definition_above_severity0(self):
   2368         old_verbosity = self.set_verbosity(0)
   2369         self.assert_function_length_check_above_error_level(0)
   2370         self.set_verbosity(old_verbosity)
   2371 
   2372     def test_function_length_check_definition_below_severity1v0(self):
   2373         old_verbosity = self.set_verbosity(0)
   2374         self.assert_function_length_check_below_error_level(1)
   2375         self.set_verbosity(old_verbosity)
   2376 
   2377     def test_function_length_check_definition_at_severity1v0(self):
   2378         old_verbosity = self.set_verbosity(0)
   2379         self.assert_function_length_check_at_error_level(1)
   2380         self.set_verbosity(old_verbosity)
   2381 
   2382     def test_function_length_check_definition_below_severity1(self):
   2383         self.assert_function_length_check_definition_ok(self.trigger_lines(1) - 1)
   2384 
   2385     def test_function_length_check_definition_at_severity1(self):
   2386         self.assert_function_length_check_definition_ok(self.trigger_lines(1))
   2387 
   2388     def test_function_length_check_definition_above_severity1(self):
   2389         self.assert_function_length_check_above_error_level(1)
   2390 
   2391     def test_function_length_check_definition_severity1_plus_blanks(self):
   2392         error_level = 1
   2393         error_lines = self.trigger_lines(error_level) + 1
   2394         trigger_level = self.trigger_lines(self.verbosity)
   2395         self.assert_function_lengths_check(
   2396             'void test_blanks(int x)' + self.function_body(error_lines),
   2397             ('Small and focused functions are preferred: '
   2398              'test_blanks() has %d non-comment lines '
   2399              '(error triggered by exceeding %d lines).'
   2400              '  [readability/fn_size] [%d]')
   2401             % (error_lines, trigger_level, error_level))
   2402 
   2403     def test_function_length_check_complex_definition_severity1(self):
   2404         error_level = 1
   2405         error_lines = self.trigger_lines(error_level) + 1
   2406         trigger_level = self.trigger_lines(self.verbosity)
   2407         self.assert_function_lengths_check(
   2408             ('my_namespace::my_other_namespace::MyVeryLongTypeName*\n'
   2409              'my_namespace::my_other_namespace::MyFunction(int arg1, char* arg2)'
   2410              + self.function_body(error_lines)),
   2411             ('Small and focused functions are preferred: '
   2412              'my_namespace::my_other_namespace::MyFunction()'
   2413              ' has %d non-comment lines '
   2414              '(error triggered by exceeding %d lines).'
   2415              '  [readability/fn_size] [%d]')
   2416             % (error_lines, trigger_level, error_level))
   2417 
   2418     def test_function_length_check_definition_severity1_for_test(self):
   2419         error_level = 1
   2420         error_lines = self.trigger_test_lines(error_level) + 1
   2421         trigger_level = self.trigger_test_lines(self.verbosity)
   2422         self.assert_function_lengths_check(
   2423             'TEST_F(Test, Mutator)' + self.function_body(error_lines),
   2424             ('Small and focused functions are preferred: '
   2425              'TEST_F(Test, Mutator) has %d non-comment lines '
   2426              '(error triggered by exceeding %d lines).'
   2427              '  [readability/fn_size] [%d]')
   2428             % (error_lines, trigger_level, error_level))
   2429 
   2430     def test_function_length_check_definition_severity1_for_split_line_test(self):
   2431         error_level = 1
   2432         error_lines = self.trigger_test_lines(error_level) + 1
   2433         trigger_level = self.trigger_test_lines(self.verbosity)
   2434         self.assert_function_lengths_check(
   2435             ('TEST_F(GoogleUpdateRecoveryRegistryProtectedTest,\n'
   2436              '    FixGoogleUpdate_AllValues_MachineApp)'  # note: 4 spaces
   2437              + self.function_body(error_lines)),
   2438             ('Small and focused functions are preferred: '
   2439              'TEST_F(GoogleUpdateRecoveryRegistryProtectedTest, '  # 1 space
   2440              'FixGoogleUpdate_AllValues_MachineApp) has %d non-comment lines '
   2441              '(error triggered by exceeding %d lines).'
   2442              '  [readability/fn_size] [%d]')
   2443             % (error_lines+1, trigger_level, error_level))
   2444 
   2445     def test_function_length_check_definition_severity1_for_bad_test_doesnt_break(self):
   2446         error_level = 1
   2447         error_lines = self.trigger_test_lines(error_level) + 1
   2448         trigger_level = self.trigger_test_lines(self.verbosity)
   2449         self.assert_function_lengths_check(
   2450             ('TEST_F('
   2451              + self.function_body(error_lines)),
   2452             ('Small and focused functions are preferred: '
   2453              'TEST_F has %d non-comment lines '
   2454              '(error triggered by exceeding %d lines).'
   2455              '  [readability/fn_size] [%d]')
   2456             % (error_lines, trigger_level, error_level))
   2457 
   2458     def test_function_length_check_definition_severity1_with_embedded_no_lints(self):
   2459         error_level = 1
   2460         error_lines = self.trigger_lines(error_level) + 1
   2461         trigger_level = self.trigger_lines(self.verbosity)
   2462         self.assert_function_lengths_check(
   2463             'void test(int x)' + self.function_body_with_no_lints(error_lines),
   2464             ('Small and focused functions are preferred: '
   2465              'test() has %d non-comment lines '
   2466              '(error triggered by exceeding %d lines).'
   2467              '  [readability/fn_size] [%d]')
   2468             % (error_lines, trigger_level, error_level))
   2469 
   2470     def test_function_length_check_definition_severity1_with_no_lint(self):
   2471         self.assert_function_lengths_check(
   2472             ('void test(int x)' + self.function_body(self.trigger_lines(1))
   2473              + '  // NOLINT -- long function'),
   2474             '')
   2475 
   2476     def test_function_length_check_definition_below_severity2(self):
   2477         self.assert_function_length_check_below_error_level(2)
   2478 
   2479     def test_function_length_check_definition_severity2(self):
   2480         self.assert_function_length_check_at_error_level(2)
   2481 
   2482     def test_function_length_check_definition_above_severity2(self):
   2483         self.assert_function_length_check_above_error_level(2)
   2484 
   2485     def test_function_length_check_definition_below_severity3(self):
   2486         self.assert_function_length_check_below_error_level(3)
   2487 
   2488     def test_function_length_check_definition_severity3(self):
   2489         self.assert_function_length_check_at_error_level(3)
   2490 
   2491     def test_function_length_check_definition_above_severity3(self):
   2492         self.assert_function_length_check_above_error_level(3)
   2493 
   2494     def test_function_length_check_definition_below_severity4(self):
   2495         self.assert_function_length_check_below_error_level(4)
   2496 
   2497     def test_function_length_check_definition_severity4(self):
   2498         self.assert_function_length_check_at_error_level(4)
   2499 
   2500     def test_function_length_check_definition_above_severity4(self):
   2501         self.assert_function_length_check_above_error_level(4)
   2502 
   2503     def test_function_length_check_definition_below_severity5(self):
   2504         self.assert_function_length_check_below_error_level(5)
   2505 
   2506     def test_function_length_check_definition_at_severity5(self):
   2507         self.assert_function_length_check_at_error_level(5)
   2508 
   2509     def test_function_length_check_definition_above_severity5(self):
   2510         self.assert_function_length_check_above_error_level(5)
   2511 
   2512     def test_function_length_check_definition_huge_lines(self):
   2513         # 5 is the limit
   2514         self.assert_function_length_check_definition(self.trigger_lines(10), 5)
   2515 
   2516     def test_function_length_not_determinable(self):
   2517         # Macro invocation without terminating semicolon.
   2518         self.assert_function_lengths_check(
   2519             'MACRO(arg)',
   2520             '')
   2521 
   2522         # Macro with underscores
   2523         self.assert_function_lengths_check(
   2524             'MACRO_WITH_UNDERSCORES(arg1, arg2, arg3)',
   2525             '')
   2526 
   2527         self.assert_function_lengths_check(
   2528             'NonMacro(arg)',
   2529             'Lint failed to find start of function body.'
   2530             '  [readability/fn_size] [5]')
   2531 
   2532 
   2533 class NoNonVirtualDestructorsTest(CppStyleTestBase):
   2534 
   2535     def test_no_error(self):
   2536         self.assert_multi_line_lint(
   2537             '''class Foo {
   2538                    virtual ~Foo();
   2539                    virtual void foo();
   2540                };''',
   2541             '')
   2542 
   2543         self.assert_multi_line_lint(
   2544             '''class Foo {
   2545                    virtual inline ~Foo();
   2546                    virtual void foo();
   2547                };''',
   2548             '')
   2549 
   2550         self.assert_multi_line_lint(
   2551             '''class Foo {
   2552                    inline virtual ~Foo();
   2553                    virtual void foo();
   2554                };''',
   2555             '')
   2556 
   2557         self.assert_multi_line_lint(
   2558             '''class Foo::Goo {
   2559                    virtual ~Goo();
   2560                    virtual void goo();
   2561                };''',
   2562             '')
   2563         self.assert_multi_line_lint(
   2564             'class Foo { void foo(); };',
   2565             'More than one command on the same line  [whitespace/newline] [4]')
   2566 
   2567         self.assert_multi_line_lint(
   2568             '''class Qualified::Goo : public Foo {
   2569                    virtual void goo();
   2570                };''',
   2571             '')
   2572 
   2573         self.assert_multi_line_lint(
   2574             # Line-ending :
   2575             '''class Goo :
   2576                public Foo {
   2577                     virtual void goo();
   2578                };''',
   2579             'Labels should always be indented at least one space.  If this is a '
   2580             'member-initializer list in a constructor, the colon should be on the '
   2581             'line after the definition header.  [whitespace/labels] [4]')
   2582 
   2583     def test_no_destructor_when_virtual_needed(self):
   2584         self.assert_multi_line_lint_re(
   2585             '''class Foo {
   2586                    virtual void foo();
   2587                };''',
   2588             'The class Foo probably needs a virtual destructor')
   2589 
   2590     def test_destructor_non_virtual_when_virtual_needed(self):
   2591         self.assert_multi_line_lint_re(
   2592             '''class Foo {
   2593                    ~Foo();
   2594                    virtual void foo();
   2595                };''',
   2596             'The class Foo probably needs a virtual destructor')
   2597 
   2598     def test_no_warn_when_derived(self):
   2599         self.assert_multi_line_lint(
   2600             '''class Foo : public Goo {
   2601                    virtual void foo();
   2602                };''',
   2603             '')
   2604 
   2605     def test_internal_braces(self):
   2606         self.assert_multi_line_lint_re(
   2607             '''class Foo {
   2608                    enum Goo {
   2609                        GOO
   2610                    };
   2611                    virtual void foo();
   2612                };''',
   2613             'The class Foo probably needs a virtual destructor')
   2614 
   2615     def test_inner_class_needs_virtual_destructor(self):
   2616         self.assert_multi_line_lint_re(
   2617             '''class Foo {
   2618                    class Goo {
   2619                        virtual void goo();
   2620                    };
   2621                };''',
   2622             'The class Goo probably needs a virtual destructor')
   2623 
   2624     def test_outer_class_needs_virtual_destructor(self):
   2625         self.assert_multi_line_lint_re(
   2626             '''class Foo {
   2627                    class Goo {
   2628                    };
   2629                    virtual void foo();
   2630                };''',
   2631             'The class Foo probably needs a virtual destructor')
   2632 
   2633     def test_qualified_class_needs_virtual_destructor(self):
   2634         self.assert_multi_line_lint_re(
   2635             '''class Qualified::Foo {
   2636                    virtual void foo();
   2637                };''',
   2638             'The class Qualified::Foo probably needs a virtual destructor')
   2639 
   2640     def test_multi_line_declaration_no_error(self):
   2641         self.assert_multi_line_lint_re(
   2642             '''class Foo
   2643                    : public Goo {
   2644                    virtual void foo();
   2645                };''',
   2646             '')
   2647 
   2648     def test_multi_line_declaration_with_error(self):
   2649         self.assert_multi_line_lint(
   2650             '''class Foo
   2651                {
   2652                    virtual void foo();
   2653                };''',
   2654             ['This { should be at the end of the previous line  '
   2655              '[whitespace/braces] [4]',
   2656              'The class Foo probably needs a virtual destructor due to having '
   2657              'virtual method(s), one declared at line 2.  [runtime/virtual] [4]'])
   2658 
   2659 
   2660 class WebKitStyleTest(CppStyleTestBase):
   2661 
   2662     # for http://webkit.org/coding/coding-style.html
   2663     def test_indentation(self):
   2664         # 1. Use spaces, not tabs. Tabs should only appear in files that
   2665         #    require them for semantic meaning, like Makefiles.
   2666         self.assert_multi_line_lint(
   2667             'class Foo {\n'
   2668             '    int goo;\n'
   2669             '};',
   2670             '')
   2671         self.assert_multi_line_lint(
   2672             'class Foo {\n'
   2673             '\tint goo;\n'
   2674             '};',
   2675             'Tab found; better to use spaces  [whitespace/tab] [1]')
   2676 
   2677         # 2. The indent size is 4 spaces.
   2678         self.assert_multi_line_lint(
   2679             'class Foo {\n'
   2680             '    int goo;\n'
   2681             '};',
   2682             '')
   2683         self.assert_multi_line_lint(
   2684             'class Foo {\n'
   2685             '   int goo;\n'
   2686             '};',
   2687             'Weird number of spaces at line-start.  Are you using a 4-space indent?  [whitespace/indent] [3]')
   2688         # FIXME: No tests for 8-spaces.
   2689 
   2690         # 3. In a header, code inside a namespace should not be indented.
   2691         self.assert_multi_line_lint(
   2692             'namespace WebCore {\n\n'
   2693             'class Document {\n'
   2694             '    int myVariable;\n'
   2695             '};\n'
   2696             '}',
   2697             '',
   2698             'foo.h')
   2699         self.assert_multi_line_lint(
   2700             'namespace OuterNamespace {\n'
   2701             '    namespace InnerNamespace {\n'
   2702             '    class Document {\n'
   2703             '};\n'
   2704             '};\n'
   2705             '}',
   2706             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2707             'foo.h')
   2708         self.assert_multi_line_lint(
   2709             'namespace OuterNamespace {\n'
   2710             '    class Document {\n'
   2711             '    namespace InnerNamespace {\n'
   2712             '};\n'
   2713             '};\n'
   2714             '}',
   2715             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2716             'foo.h')
   2717         self.assert_multi_line_lint(
   2718             'namespace WebCore {\n'
   2719             '#if 0\n'
   2720             '    class Document {\n'
   2721             '};\n'
   2722             '#endif\n'
   2723             '}',
   2724             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2725             'foo.h')
   2726         self.assert_multi_line_lint(
   2727             'namespace WebCore {\n'
   2728             'class Document {\n'
   2729             '};\n'
   2730             '}',
   2731             '',
   2732             'foo.h')
   2733 
   2734         # 4. In an implementation file (files with the extension .cpp, .c
   2735         #    or .mm), code inside a namespace should not be indented.
   2736         self.assert_multi_line_lint(
   2737             'namespace WebCore {\n\n'
   2738             'Document::Foo()\n'
   2739             '    : foo(bar)\n'
   2740             '    , boo(far)\n'
   2741             '{\n'
   2742             '    stuff();\n'
   2743             '}',
   2744             '',
   2745             'foo.cpp')
   2746         self.assert_multi_line_lint(
   2747             'namespace OuterNamespace {\n'
   2748             'namespace InnerNamespace {\n'
   2749             'Document::Foo() { }\n'
   2750             '    void* p;\n'
   2751             '}\n'
   2752             '}\n',
   2753             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2754             'foo.cpp')
   2755         self.assert_multi_line_lint(
   2756             'namespace OuterNamespace {\n'
   2757             'namespace InnerNamespace {\n'
   2758             'Document::Foo() { }\n'
   2759             '}\n'
   2760             '    void* p;\n'
   2761             '}\n',
   2762             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2763             'foo.cpp')
   2764         self.assert_multi_line_lint(
   2765             'namespace WebCore {\n\n'
   2766             '    const char* foo = "start:;"\n'
   2767             '        "dfsfsfs";\n'
   2768             '}\n',
   2769             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2770             'foo.cpp')
   2771         self.assert_multi_line_lint(
   2772             'namespace WebCore {\n\n'
   2773             'const char* foo(void* a = ";", // ;\n'
   2774             '    void* b);\n'
   2775             '    void* p;\n'
   2776             '}\n',
   2777             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2778             'foo.cpp')
   2779         self.assert_multi_line_lint(
   2780             'namespace WebCore {\n\n'
   2781             'const char* foo[] = {\n'
   2782             '    "void* b);", // ;\n'
   2783             '    "asfdf",\n'
   2784             '    }\n'
   2785             '    void* p;\n'
   2786             '}\n',
   2787             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2788             'foo.cpp')
   2789         self.assert_multi_line_lint(
   2790             'namespace WebCore {\n\n'
   2791             'const char* foo[] = {\n'
   2792             '    "void* b);", // }\n'
   2793             '    "asfdf",\n'
   2794             '    }\n'
   2795             '}\n',
   2796             '',
   2797             'foo.cpp')
   2798         self.assert_multi_line_lint(
   2799             '    namespace WebCore {\n\n'
   2800             '    void Document::Foo()\n'
   2801             '    {\n'
   2802             'start: // infinite loops are fun!\n'
   2803             '        goto start;\n'
   2804             '    }',
   2805             'namespace should never be indented.  [whitespace/indent] [4]',
   2806             'foo.cpp')
   2807         self.assert_multi_line_lint(
   2808             'namespace WebCore {\n'
   2809             '    Document::Foo() { }\n'
   2810             '}',
   2811             'Code inside a namespace should not be indented.'
   2812             '  [whitespace/indent] [4]',
   2813             'foo.cpp')
   2814         self.assert_multi_line_lint(
   2815             'namespace WebCore {\n'
   2816             '#define abc(x) x; \\\n'
   2817             '    x\n'
   2818             '}',
   2819             '',
   2820             'foo.cpp')
   2821         self.assert_multi_line_lint(
   2822             'namespace WebCore {\n'
   2823             '#define abc(x) x; \\\n'
   2824             '    x\n'
   2825             '    void* x;'
   2826             '}',
   2827             'Code inside a namespace should not be indented.  [whitespace/indent] [4]',
   2828             'foo.cpp')
   2829 
   2830         # 5. A case label should line up with its switch statement. The
   2831         #    case statement is indented.
   2832         self.assert_multi_line_lint(
   2833             '    switch (condition) {\n'
   2834             '    case fooCondition:\n'
   2835             '    case barCondition:\n'
   2836             '        i++;\n'
   2837             '        break;\n'
   2838             '    default:\n'
   2839             '        i--;\n'
   2840             '    }\n',
   2841             '')
   2842         self.assert_multi_line_lint(
   2843             '    switch (condition) {\n'
   2844             '    case fooCondition:\n'
   2845             '        switch (otherCondition) {\n'
   2846             '        default:\n'
   2847             '            return;\n'
   2848             '        }\n'
   2849             '    default:\n'
   2850             '        i--;\n'
   2851             '    }\n',
   2852             '')
   2853         self.assert_multi_line_lint(
   2854             '    switch (condition) {\n'
   2855             '    case fooCondition: break;\n'
   2856             '    default: return;\n'
   2857             '    }\n',
   2858             '')
   2859         self.assert_multi_line_lint(
   2860             '    switch (condition) {\n'
   2861             '        case fooCondition:\n'
   2862             '        case barCondition:\n'
   2863             '            i++;\n'
   2864             '            break;\n'
   2865             '        default:\n'
   2866             '            i--;\n'
   2867             '    }\n',
   2868             'A case label should not be indented, but line up with its switch statement.'
   2869             '  [whitespace/indent] [4]')
   2870         self.assert_multi_line_lint(
   2871             '    switch (condition) {\n'
   2872             '        case fooCondition:\n'
   2873             '            break;\n'
   2874             '    default:\n'
   2875             '            i--;\n'
   2876             '    }\n',
   2877             'A case label should not be indented, but line up with its switch statement.'
   2878             '  [whitespace/indent] [4]')
   2879         self.assert_multi_line_lint(
   2880             '    switch (condition) {\n'
   2881             '    case fooCondition:\n'
   2882             '    case barCondition:\n'
   2883             '        switch (otherCondition) {\n'
   2884             '            default:\n'
   2885             '            return;\n'
   2886             '        }\n'
   2887             '    default:\n'
   2888             '        i--;\n'
   2889             '    }\n',
   2890             'A case label should not be indented, but line up with its switch statement.'
   2891             '  [whitespace/indent] [4]')
   2892         self.assert_multi_line_lint(
   2893             '    switch (condition) {\n'
   2894             '    case fooCondition:\n'
   2895             '    case barCondition:\n'
   2896             '    i++;\n'
   2897             '    break;\n\n'
   2898             '    default:\n'
   2899             '    i--;\n'
   2900             '    }\n',
   2901             'Non-label code inside switch statements should be indented.'
   2902             '  [whitespace/indent] [4]')
   2903         self.assert_multi_line_lint(
   2904             '    switch (condition) {\n'
   2905             '    case fooCondition:\n'
   2906             '    case barCondition:\n'
   2907             '        switch (otherCondition) {\n'
   2908             '        default:\n'
   2909             '        return;\n'
   2910             '        }\n'
   2911             '    default:\n'
   2912             '        i--;\n'
   2913             '    }\n',
   2914             'Non-label code inside switch statements should be indented.'
   2915             '  [whitespace/indent] [4]')
   2916 
   2917         # 6. Boolean expressions at the same nesting level that span
   2918         #   multiple lines should have their operators on the left side of
   2919         #   the line instead of the right side.
   2920         self.assert_multi_line_lint(
   2921             '    return attr->name() == srcAttr\n'
   2922             '        || attr->name() == lowsrcAttr;\n',
   2923             '')
   2924         self.assert_multi_line_lint(
   2925             '    return attr->name() == srcAttr ||\n'
   2926             '        attr->name() == lowsrcAttr;\n',
   2927             'Boolean expressions that span multiple lines should have their '
   2928             'operators on the left side of the line instead of the right side.'
   2929             '  [whitespace/operators] [4]')
   2930 
   2931     def test_spacing(self):
   2932         # 1. Do not place spaces around unary operators.
   2933         self.assert_multi_line_lint(
   2934             'i++;',
   2935             '')
   2936         self.assert_multi_line_lint(
   2937             'i ++;',
   2938             'Extra space for operator  ++;  [whitespace/operators] [4]')
   2939 
   2940         # 2. Do place spaces around binary and ternary operators.
   2941         self.assert_multi_line_lint(
   2942             'y = m * x + b;',
   2943             '')
   2944         self.assert_multi_line_lint(
   2945             'f(a, b);',
   2946             '')
   2947         self.assert_multi_line_lint(
   2948             'c = a | b;',
   2949             '')
   2950         self.assert_multi_line_lint(
   2951             'return condition ? 1 : 0;',
   2952             '')
   2953         self.assert_multi_line_lint(
   2954             'y=m*x+b;',
   2955             'Missing spaces around =  [whitespace/operators] [4]')
   2956         self.assert_multi_line_lint(
   2957             'f(a,b);',
   2958             'Missing space after ,  [whitespace/comma] [3]')
   2959         self.assert_multi_line_lint(
   2960             'c = a|b;',
   2961             'Missing spaces around |  [whitespace/operators] [3]')
   2962         # FIXME: We cannot catch this lint error.
   2963         # self.assert_multi_line_lint(
   2964         #     'return condition ? 1:0;',
   2965         #     '')
   2966 
   2967         # 3. Place spaces between control statements and their parentheses.
   2968         self.assert_multi_line_lint(
   2969             '    if (condition)\n'
   2970             '        doIt();\n',
   2971             '')
   2972         self.assert_multi_line_lint(
   2973             '    if(condition)\n'
   2974             '        doIt();\n',
   2975             'Missing space before ( in if(  [whitespace/parens] [5]')
   2976 
   2977         # 4. Do not place spaces between a function and its parentheses,
   2978         #    or between a parenthesis and its content.
   2979         self.assert_multi_line_lint(
   2980             'f(a, b);',
   2981             '')
   2982         self.assert_multi_line_lint(
   2983             'f (a, b);',
   2984             'Extra space before ( in function call  [whitespace/parens] [4]')
   2985         self.assert_multi_line_lint(
   2986             'f( a, b );',
   2987             ['Extra space after ( in function call  [whitespace/parens] [4]',
   2988              'Extra space before )  [whitespace/parens] [2]'])
   2989 
   2990     def test_line_breaking(self):
   2991         # 1. Each statement should get its own line.
   2992         self.assert_multi_line_lint(
   2993             '    x++;\n'
   2994             '    y++;\n'
   2995             '    if (condition);\n'
   2996             '        doIt();\n',
   2997             '')
   2998         self.assert_multi_line_lint(
   2999             '    if (condition) \\\n'
   3000             '        doIt();\n',
   3001             '')
   3002         self.assert_multi_line_lint(
   3003             '    x++; y++;',
   3004             'More than one command on the same line  [whitespace/newline] [4]')
   3005         self.assert_multi_line_lint(
   3006             '    if (condition) doIt();\n',
   3007             'More than one command on the same line in if  [whitespace/parens] [4]')
   3008 
   3009         # 2. An else statement should go on the same line as a preceding
   3010         #   close brace if one is present, else it should line up with the
   3011         #   if statement.
   3012         self.assert_multi_line_lint(
   3013             'if (condition) {\n'
   3014             '    doSomething();\n'
   3015             '    doSomethingAgain();\n'
   3016             '} else {\n'
   3017             '    doSomethingElse();\n'
   3018             '    doSomethingElseAgain();\n'
   3019             '}\n',
   3020             '')
   3021         self.assert_multi_line_lint(
   3022             'if (condition)\n'
   3023             '    doSomething();\n'
   3024             'else\n'
   3025             '    doSomethingElse();\n',
   3026             '')
   3027         self.assert_multi_line_lint(
   3028             'if (condition)\n'
   3029             '    doSomething();\n'
   3030             'else {\n'
   3031             '    doSomethingElse();\n'
   3032             '    doSomethingElseAgain();\n'
   3033             '}\n',
   3034             '')
   3035         self.assert_multi_line_lint(
   3036             '#define TEST_ASSERT(expression) do { if (!(expression)) { TestsController::shared().testFailed(__FILE__, __LINE__, #expression); return; } } while (0)\n',
   3037             '')
   3038         self.assert_multi_line_lint(
   3039             '#define TEST_ASSERT(expression) do { if ( !(expression)) { TestsController::shared().testFailed(__FILE__, __LINE__, #expression); return; } } while (0)\n',
   3040             'Mismatching spaces inside () in if  [whitespace/parens] [5]')
   3041         # FIXME: currently we only check first conditional, so we cannot detect errors in next ones.
   3042         # self.assert_multi_line_lint(
   3043         #     '#define TEST_ASSERT(expression) do { if (!(expression)) { TestsController::shared().testFailed(__FILE__, __LINE__, #expression); return; } } while (0 )\n',
   3044         #     'Mismatching spaces inside () in if  [whitespace/parens] [5]')
   3045         self.assert_multi_line_lint(
   3046             'if (condition) {\n'
   3047             '    doSomething();\n'
   3048             '    doSomethingAgain();\n'
   3049             '}\n'
   3050             'else {\n'
   3051             '    doSomethingElse();\n'
   3052             '    doSomethingElseAgain();\n'
   3053             '}\n',
   3054             'An else should appear on the same line as the preceding }  [whitespace/newline] [4]')
   3055         self.assert_multi_line_lint(
   3056             'if (condition) doSomething(); else doSomethingElse();\n',
   3057             ['More than one command on the same line  [whitespace/newline] [4]',
   3058              'Else clause should never be on same line as else (use 2 lines)  [whitespace/newline] [4]',
   3059              'More than one command on the same line in if  [whitespace/parens] [4]'])
   3060         self.assert_multi_line_lint(
   3061             'if (condition) doSomething(); else {\n'
   3062             '    doSomethingElse();\n'
   3063             '}\n',
   3064             ['More than one command on the same line in if  [whitespace/parens] [4]',
   3065              'One line control clauses should not use braces.  [whitespace/braces] [4]'])
   3066 
   3067         # 3. An else if statement should be written as an if statement
   3068         #    when the prior if concludes with a return statement.
   3069         self.assert_multi_line_lint(
   3070             'if (motivated) {\n'
   3071             '    if (liquid)\n'
   3072             '        return money;\n'
   3073             '} else if (tired)\n'
   3074             '    break;\n',
   3075             '')
   3076         self.assert_multi_line_lint(
   3077             'if (condition)\n'
   3078             '    doSomething();\n'
   3079             'else if (otherCondition)\n'
   3080             '    doSomethingElse();\n',
   3081             '')
   3082         self.assert_multi_line_lint(
   3083             'if (condition)\n'
   3084             '    doSomething();\n'
   3085             'else\n'
   3086             '    doSomethingElse();\n',
   3087             '')
   3088         self.assert_multi_line_lint(
   3089             'if (condition)\n'
   3090             '    returnValue = foo;\n'
   3091             'else if (otherCondition)\n'
   3092             '    returnValue = bar;\n',
   3093             '')
   3094         self.assert_multi_line_lint(
   3095             'if (condition)\n'
   3096             '    returnValue = foo;\n'
   3097             'else\n'
   3098             '    returnValue = bar;\n',
   3099             '')
   3100         self.assert_multi_line_lint(
   3101             'if (condition)\n'
   3102             '    doSomething();\n'
   3103             'else if (liquid)\n'
   3104             '    return money;\n'
   3105             'else if (broke)\n'
   3106             '    return favor;\n'
   3107             'else\n'
   3108             '    sleep(28800);\n',
   3109             '')
   3110         self.assert_multi_line_lint(
   3111             'if (liquid) {\n'
   3112             '    prepare();\n'
   3113             '    return money;\n'
   3114             '} else if (greedy) {\n'
   3115             '    keep();\n'
   3116             '    return nothing;\n'
   3117             '}\n',
   3118             'An else if statement should be written as an if statement when the '
   3119             'prior "if" concludes with a return, break, continue or goto statement.'
   3120             '  [readability/control_flow] [4]')
   3121         self.assert_multi_line_lint(
   3122             '    if (stupid) {\n'
   3123             'infiniteLoop:\n'
   3124             '        goto infiniteLoop;\n'
   3125             '    } else if (evil)\n'
   3126             '        goto hell;\n',
   3127             'An else if statement should be written as an if statement when the '
   3128             'prior "if" concludes with a return, break, continue or goto statement.'
   3129             '  [readability/control_flow] [4]')
   3130         self.assert_multi_line_lint(
   3131             'if (liquid)\n'
   3132             '{\n'
   3133             '    prepare();\n'
   3134             '    return money;\n'
   3135             '}\n'
   3136             'else if (greedy)\n'
   3137             '    keep();\n',
   3138             ['This { should be at the end of the previous line  [whitespace/braces] [4]',
   3139             'An else should appear on the same line as the preceding }  [whitespace/newline] [4]',
   3140             'An else if statement should be written as an if statement when the '
   3141             'prior "if" concludes with a return, break, continue or goto statement.'
   3142             '  [readability/control_flow] [4]'])
   3143         self.assert_multi_line_lint(
   3144             'if (gone)\n'
   3145             '    return;\n'
   3146             'else if (here)\n'
   3147             '    go();\n',
   3148             'An else if statement should be written as an if statement when the '
   3149             'prior "if" concludes with a return, break, continue or goto statement.'
   3150             '  [readability/control_flow] [4]')
   3151         self.assert_multi_line_lint(
   3152             'if (gone)\n'
   3153             '    return;\n'
   3154             'else\n'
   3155             '    go();\n',
   3156             'An else statement can be removed when the prior "if" concludes '
   3157             'with a return, break, continue or goto statement.'
   3158             '  [readability/control_flow] [4]')
   3159         self.assert_multi_line_lint(
   3160             'if (motivated) {\n'
   3161             '    prepare();\n'
   3162             '    continue;\n'
   3163             '} else {\n'
   3164             '    cleanUp();\n'
   3165             '    break;\n'
   3166             '}\n',
   3167             'An else statement can be removed when the prior "if" concludes '
   3168             'with a return, break, continue or goto statement.'
   3169             '  [readability/control_flow] [4]')
   3170         self.assert_multi_line_lint(
   3171             'if (tired)\n'
   3172             '    break;\n'
   3173             'else {\n'
   3174             '    prepare();\n'
   3175             '    continue;\n'
   3176             '}\n',
   3177             'An else statement can be removed when the prior "if" concludes '
   3178             'with a return, break, continue or goto statement.'
   3179             '  [readability/control_flow] [4]')
   3180 
   3181     def test_braces(self):
   3182         # 1. Function definitions: place each brace on its own line.
   3183         self.assert_multi_line_lint(
   3184             'int main()\n'
   3185             '{\n'
   3186             '    doSomething();\n'
   3187             '}\n',
   3188             '')
   3189         self.assert_multi_line_lint(
   3190             'int main() {\n'
   3191             '    doSomething();\n'
   3192             '}\n',
   3193             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
   3194 
   3195         # 2. Other braces: place the open brace on the line preceding the
   3196         #    code block; place the close brace on its own line.
   3197         self.assert_multi_line_lint(
   3198             'class MyClass {\n'
   3199             '    int foo;\n'
   3200             '};\n',
   3201             '')
   3202         self.assert_multi_line_lint(
   3203             'namespace WebCore {\n'
   3204             'int foo;\n'
   3205             '};\n',
   3206             '')
   3207         self.assert_multi_line_lint(
   3208             'for (int i = 0; i < 10; i++) {\n'
   3209             '    DoSomething();\n'
   3210             '};\n',
   3211             '')
   3212         self.assert_multi_line_lint(
   3213             'class MyClass\n'
   3214             '{\n'
   3215             '    int foo;\n'
   3216             '};\n',
   3217             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3218         self.assert_multi_line_lint(
   3219             'if (condition)\n'
   3220             '{\n'
   3221             '    int foo;\n'
   3222             '}\n',
   3223             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3224         self.assert_multi_line_lint(
   3225             'for (int i = 0; i < 10; i++)\n'
   3226             '{\n'
   3227             '    int foo;\n'
   3228             '}\n',
   3229             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3230         self.assert_multi_line_lint(
   3231             'while (true)\n'
   3232             '{\n'
   3233             '    int foo;\n'
   3234             '}\n',
   3235             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3236         self.assert_multi_line_lint(
   3237             'foreach (Foo* foo, foos)\n'
   3238             '{\n'
   3239             '    int bar;\n'
   3240             '}\n',
   3241             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3242         self.assert_multi_line_lint(
   3243             'switch (type)\n'
   3244             '{\n'
   3245             'case foo: return;\n'
   3246             '}\n',
   3247             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3248         self.assert_multi_line_lint(
   3249             'if (condition)\n'
   3250             '{\n'
   3251             '    int foo;\n'
   3252             '}\n',
   3253             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3254         self.assert_multi_line_lint(
   3255             'for (int i = 0; i < 10; i++)\n'
   3256             '{\n'
   3257             '    int foo;\n'
   3258             '}\n',
   3259             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3260         self.assert_multi_line_lint(
   3261             'while (true)\n'
   3262             '{\n'
   3263             '    int foo;\n'
   3264             '}\n',
   3265             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3266         self.assert_multi_line_lint(
   3267             'switch (type)\n'
   3268             '{\n'
   3269             'case foo: return;\n'
   3270             '}\n',
   3271             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3272         self.assert_multi_line_lint(
   3273             'else if (type)\n'
   3274             '{\n'
   3275             'case foo: return;\n'
   3276             '}\n',
   3277             'This { should be at the end of the previous line  [whitespace/braces] [4]')
   3278 
   3279         # 3. One-line control clauses should not use braces unless
   3280         #    comments are included or a single statement spans multiple
   3281         #    lines.
   3282         self.assert_multi_line_lint(
   3283             'if (true) {\n'
   3284             '    int foo;\n'
   3285             '}\n',
   3286             'One line control clauses should not use braces.  [whitespace/braces] [4]')
   3287 
   3288         self.assert_multi_line_lint(
   3289             'for (; foo; bar) {\n'
   3290             '    int foo;\n'
   3291             '}\n',
   3292             'One line control clauses should not use braces.  [whitespace/braces] [4]')
   3293 
   3294         self.assert_multi_line_lint(
   3295             'foreach (foo, foos) {\n'
   3296             '    int bar;\n'
   3297             '}\n',
   3298             'One line control clauses should not use braces.  [whitespace/braces] [4]')
   3299 
   3300         self.assert_multi_line_lint(
   3301             'while (true) {\n'
   3302             '    int foo;\n'
   3303             '}\n',
   3304             'One line control clauses should not use braces.  [whitespace/braces] [4]')
   3305 
   3306         self.assert_multi_line_lint(
   3307             'if (true)\n'
   3308             '    int foo;\n'
   3309             'else {\n'
   3310             '    int foo;\n'
   3311             '}\n',
   3312             'One line control clauses should not use braces.  [whitespace/braces] [4]')
   3313 
   3314         self.assert_multi_line_lint(
   3315             'if (true) {\n'
   3316             '    int foo;\n'
   3317             '} else\n'
   3318             '    int foo;\n',
   3319             'One line control clauses should not use braces.  [whitespace/braces] [4]')
   3320 
   3321         self.assert_multi_line_lint(
   3322             'if (true) {\n'
   3323             '    // Some comment\n'
   3324             '    int foo;\n'
   3325             '}\n',
   3326             '')
   3327 
   3328         self.assert_multi_line_lint(
   3329             'if (true) {\n'
   3330             '    myFunction(reallyLongParam1, reallyLongParam2,\n'
   3331             '               reallyLongParam3);\n'
   3332             '}\n',
   3333             '')
   3334 
   3335         # 4. Control clauses without a body should use empty braces.
   3336         self.assert_multi_line_lint(
   3337             'for ( ; current; current = current->next) { }\n',
   3338             '')
   3339         self.assert_multi_line_lint(
   3340             'for ( ; current;\n'
   3341             '     current = current->next) {}\n',
   3342             '')
   3343         self.assert_multi_line_lint(
   3344             'for ( ; current; current = current->next);\n',
   3345             'Semicolon defining empty statement for this loop. Use { } instead.  [whitespace/semicolon] [5]')
   3346         self.assert_multi_line_lint(
   3347             'while (true);\n',
   3348             'Semicolon defining empty statement for this loop. Use { } instead.  [whitespace/semicolon] [5]')
   3349         self.assert_multi_line_lint(
   3350             '} while (true);\n',
   3351             '')
   3352 
   3353     def test_null_false_zero(self):
   3354         # 1. In C++, the null pointer value should be written as 0. In C,
   3355         #    it should be written as NULL. In Objective-C and Objective-C++,
   3356         #    follow the guideline for C or C++, respectively, but use nil to
   3357         #    represent a null Objective-C object.
   3358         self.assert_lint(
   3359             'functionCall(NULL)',
   3360             'Use 0 instead of NULL.'
   3361             '  [readability/null] [5]',
   3362             'foo.cpp')
   3363         self.assert_lint(
   3364             "// Don't use NULL in comments since it isn't in code.",
   3365             'Use 0 instead of NULL.'
   3366             '  [readability/null] [4]',
   3367             'foo.cpp')
   3368         self.assert_lint(
   3369             '"A string with NULL" // and a comment with NULL is tricky to flag correctly in cpp_style.',
   3370             'Use 0 instead of NULL.'
   3371             '  [readability/null] [4]',
   3372             'foo.cpp')
   3373         self.assert_lint(
   3374             '"A string containing NULL is ok"',
   3375             '',
   3376             'foo.cpp')
   3377         self.assert_lint(
   3378             'if (aboutNULL)',
   3379             '',
   3380             'foo.cpp')
   3381         self.assert_lint(
   3382             'myVariable = NULLify',
   3383             '',
   3384             'foo.cpp')
   3385         # Make sure that the NULL check does not apply to C and Objective-C files.
   3386         self.assert_lint(
   3387             'functionCall(NULL)',
   3388             '',
   3389             'foo.c')
   3390         self.assert_lint(
   3391             'functionCall(NULL)',
   3392             '',
   3393             'foo.m')
   3394 
   3395         # Make sure that the NULL check does not apply to g_object_{set,get}
   3396         self.assert_lint(
   3397             'g_object_get(foo, "prop", &bar, NULL);',
   3398             '')
   3399         self.assert_lint(
   3400             'g_object_set(foo, "prop", bar, NULL);',
   3401             '')
   3402 
   3403         # 2. C++ and C bool values should be written as true and
   3404         #    false. Objective-C BOOL values should be written as YES and NO.
   3405         # FIXME: Implement this.
   3406 
   3407         # 3. Tests for true/false, null/non-null, and zero/non-zero should
   3408         #    all be done without equality comparisons.
   3409         self.assert_lint(
   3410             'if (count == 0)',
   3411             'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
   3412             '  [readability/comparison_to_zero] [5]')
   3413         self.assert_lint_one_of_many_errors_re(
   3414             'if (string != NULL)',
   3415             r'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons\.')
   3416         self.assert_lint(
   3417             'if (condition == true)',
   3418             'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
   3419             '  [readability/comparison_to_zero] [5]')
   3420         self.assert_lint(
   3421             'if (myVariable != /* Why would anyone put a comment here? */ false)',
   3422             'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
   3423             '  [readability/comparison_to_zero] [5]')
   3424 
   3425         self.assert_lint(
   3426             'if (0 /* This comment also looks odd to me. */ != aLongerVariableName)',
   3427             'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
   3428             '  [readability/comparison_to_zero] [5]')
   3429         self.assert_lint_one_of_many_errors_re(
   3430             'if (NULL == thisMayBeNull)',
   3431             r'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons\.')
   3432         self.assert_lint(
   3433             'if (true != anotherCondition)',
   3434             'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
   3435             '  [readability/comparison_to_zero] [5]')
   3436         self.assert_lint(
   3437             'if (false == myBoolValue)',
   3438             'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
   3439             '  [readability/comparison_to_zero] [5]')
   3440 
   3441         self.assert_lint(
   3442             'if (fontType == trueType)',
   3443             '')
   3444         self.assert_lint(
   3445             'if (othertrue == fontType)',
   3446             '')
   3447 
   3448     def test_using_std(self):
   3449         self.assert_lint(
   3450             'using std::min;',
   3451             "Use 'using namespace std;' instead of 'using std::min;'."
   3452             "  [build/using_std] [4]",
   3453             'foo.cpp')
   3454 
   3455     def test_max_macro(self):
   3456         self.assert_lint(
   3457             'int i = MAX(0, 1);',
   3458             '',
   3459             'foo.c')
   3460 
   3461         self.assert_lint(
   3462             'int i = MAX(0, 1);',
   3463             'Use std::max() or std::max<type>() instead of the MAX() macro.'
   3464             '  [runtime/max_min_macros] [4]',
   3465             'foo.cpp')
   3466 
   3467         self.assert_lint(
   3468             'inline int foo() { return MAX(0, 1); }',
   3469             'Use std::max() or std::max<type>() instead of the MAX() macro.'
   3470             '  [runtime/max_min_macros] [4]',
   3471             'foo.h')
   3472 
   3473     def test_min_macro(self):
   3474         self.assert_lint(
   3475             'int i = MIN(0, 1);',
   3476             '',
   3477             'foo.c')
   3478 
   3479         self.assert_lint(
   3480             'int i = MIN(0, 1);',
   3481             'Use std::min() or std::min<type>() instead of the MIN() macro.'
   3482             '  [runtime/max_min_macros] [4]',
   3483             'foo.cpp')
   3484 
   3485         self.assert_lint(
   3486             'inline int foo() { return MIN(0, 1); }',
   3487             'Use std::min() or std::min<type>() instead of the MIN() macro.'
   3488             '  [runtime/max_min_macros] [4]',
   3489             'foo.h')
   3490 
   3491     def test_names(self):
   3492         name_error_message = " is incorrectly named. Don't use underscores in your identifier names.  [readability/naming] [4]"
   3493 
   3494         # Basic cases from WebKit style guide.
   3495         self.assert_lint('struct Data;', '')
   3496         self.assert_lint('size_t bufferSize;', '')
   3497         self.assert_lint('class HTMLDocument;', '')
   3498         self.assert_lint('String mimeType();', '')
   3499         self.assert_lint('size_t buffer_size;',
   3500                          'buffer_size' + name_error_message)
   3501         self.assert_lint('short m_length;', '')
   3502         self.assert_lint('short _length;',
   3503                          '_length' + name_error_message)
   3504         self.assert_lint('short length_;',
   3505                          'length_' + name_error_message)
   3506 
   3507         # Pointers, references, functions, templates, and adjectives.
   3508         self.assert_lint('char* under_score;',
   3509                          'under_score' + name_error_message)
   3510         self.assert_lint('const int UNDER_SCORE;',
   3511                          'UNDER_SCORE' + name_error_message)
   3512         self.assert_lint('static inline const char const& const under_score;',
   3513                          'under_score' + name_error_message)
   3514         self.assert_lint('WebCore::RenderObject* under_score;',
   3515                          'under_score' + name_error_message)
   3516         self.assert_lint('int func_name();',
   3517                          'func_name' + name_error_message)
   3518         self.assert_lint('RefPtr<RenderObject*> under_score;',
   3519                          'under_score' + name_error_message)
   3520         self.assert_lint('WTF::Vector<WTF::RefPtr<const RenderObject* const> > under_score;',
   3521                          'under_score' + name_error_message)
   3522         self.assert_lint('int under_score[];',
   3523                          'under_score' + name_error_message)
   3524         self.assert_lint('struct dirent* under_score;',
   3525                          'under_score' + name_error_message)
   3526         self.assert_lint('long under_score;',
   3527                          'under_score' + name_error_message)
   3528         self.assert_lint('long long under_score;',
   3529                          'under_score' + name_error_message)
   3530         self.assert_lint('long double under_score;',
   3531                          'under_score' + name_error_message)
   3532         self.assert_lint('long long int under_score;',
   3533                          'under_score' + name_error_message)
   3534 
   3535         # Declarations in control statement.
   3536         self.assert_lint('if (int under_score = 42) {',
   3537                          'under_score' + name_error_message)
   3538         self.assert_lint('else if (int under_score = 42) {',
   3539                          'under_score' + name_error_message)
   3540         self.assert_lint('for (int under_score = 42; cond; i++) {',
   3541                          'under_score' + name_error_message)
   3542         self.assert_lint('while (foo & under_score = bar) {',
   3543                          'under_score' + name_error_message)
   3544         self.assert_lint('for (foo * under_score = p; cond; i++) {',
   3545                          'under_score' + name_error_message)
   3546         self.assert_lint('for (foo * under_score; cond; i++) {',
   3547                          'under_score' + name_error_message)
   3548         self.assert_lint('while (foo & value_in_thirdparty_library) {', '')
   3549         self.assert_lint('while (foo * value_in_thirdparty_library) {', '')
   3550         self.assert_lint('if (mli && S_OK == mli->foo()) {', '')
   3551 
   3552         # More member variables and functions.
   3553         self.assert_lint('int SomeClass::s_validName', '')
   3554         self.assert_lint('int m_under_score;',
   3555                          'm_under_score' + name_error_message)
   3556         self.assert_lint('int SomeClass::s_under_score = 0;',
   3557                          'SomeClass::s_under_score' + name_error_message)
   3558         self.assert_lint('int SomeClass::under_score = 0;',
   3559                          'SomeClass::under_score' + name_error_message)
   3560 
   3561         # Other statements.
   3562         self.assert_lint('return INT_MAX;', '')
   3563         self.assert_lint('return_t under_score;',
   3564                          'under_score' + name_error_message)
   3565         self.assert_lint('goto under_score;',
   3566                          'under_score' + name_error_message)
   3567         self.assert_lint('delete static_cast<Foo*>(p);', '')
   3568 
   3569         # Multiple variables in one line.
   3570         self.assert_lint('void myFunction(int variable1, int another_variable);',
   3571                          'another_variable' + name_error_message)
   3572         self.assert_lint('int variable1, another_variable;',
   3573                          'another_variable' + name_error_message)
   3574         self.assert_lint('int first_variable, secondVariable;',
   3575                          'first_variable' + name_error_message)
   3576         self.assert_lint('void my_function(int variable_1, int variable_2);',
   3577                          ['my_function' + name_error_message,
   3578                           'variable_1' + name_error_message,
   3579                           'variable_2' + name_error_message])
   3580         self.assert_lint('for (int variable_1, variable_2;;) {',
   3581                          ['variable_1' + name_error_message,
   3582                           'variable_2' + name_error_message])
   3583 
   3584         # There is an exception for op code functions but only in the JavaScriptCore directory.
   3585         self.assert_lint('void this_op_code(int var1, int var2)', '', 'JavaScriptCore/foo.cpp')
   3586         self.assert_lint('void this_op_code(int var1, int var2)', 'this_op_code' + name_error_message)
   3587 
   3588         # GObject requires certain magical names in class declarations.
   3589         self.assert_lint('void webkit_dom_object_init();', '')
   3590         self.assert_lint('void webkit_dom_object_class_init();', '')
   3591 
   3592         # There is an exception for some unit tests that begin with "tst_".
   3593         self.assert_lint('void tst_QWebFrame::arrayObjectEnumerable(int var1, int var2)', '')
   3594 
   3595         # The Qt API uses names that begin with "qt_".
   3596         self.assert_lint('void QTFrame::qt_drt_is_awesome(int var1, int var2)', '')
   3597         self.assert_lint('void qt_drt_is_awesome(int var1, int var2);', '')
   3598 
   3599         # const_iterator is allowed as well.
   3600         self.assert_lint('typedef VectorType::const_iterator const_iterator;', '')
   3601 
   3602 
   3603     def test_comments(self):
   3604         # A comment at the beginning of a line is ok.
   3605         self.assert_lint('// comment', '')
   3606         self.assert_lint('    // comment', '')
   3607 
   3608         self.assert_lint('}  // namespace WebCore',
   3609                          'One space before end of line comments'
   3610                          '  [whitespace/comments] [5]')
   3611 
   3612     def test_other(self):
   3613         # FIXME: Implement this.
   3614         pass
   3615 
   3616 
   3617 class CppProcessorTest(unittest.TestCase):
   3618 
   3619     """Tests CppProcessor class."""
   3620 
   3621     def mock_handle_style_error(self):
   3622         pass
   3623 
   3624     def _processor(self):
   3625         return CppProcessor("foo", "h", self.mock_handle_style_error, 3)
   3626 
   3627     def test_init(self):
   3628         """Test __init__ constructor."""
   3629         processor = self._processor()
   3630         self.assertEquals(processor.file_extension, "h")
   3631         self.assertEquals(processor.file_path, "foo")
   3632         self.assertEquals(processor.handle_style_error, self.mock_handle_style_error)
   3633         self.assertEquals(processor.verbosity, 3)
   3634 
   3635     def test_eq(self):
   3636         """Test __eq__ equality function."""
   3637         processor1 = self._processor()
   3638         processor2 = self._processor()
   3639 
   3640         # == calls __eq__.
   3641         self.assertTrue(processor1 == processor2)
   3642 
   3643         def mock_handle_style_error2(self):
   3644             pass
   3645 
   3646         # Verify that a difference in any argument cause equality to fail.
   3647         processor = CppProcessor("foo", "h", self.mock_handle_style_error, 3)
   3648         self.assertFalse(processor == CppProcessor("bar", "h", self.mock_handle_style_error, 3))
   3649         self.assertFalse(processor == CppProcessor("foo", "c", self.mock_handle_style_error, 3))
   3650         self.assertFalse(processor == CppProcessor("foo", "h", mock_handle_style_error2, 3))
   3651         self.assertFalse(processor == CppProcessor("foo", "h", self.mock_handle_style_error, 4))
   3652 
   3653     def test_ne(self):
   3654         """Test __ne__ inequality function."""
   3655         processor1 = self._processor()
   3656         processor2 = self._processor()
   3657 
   3658         # != calls __ne__.
   3659         # By default, __ne__ always returns true on different objects.
   3660         # Thus, just check the distinguishing case to verify that the
   3661         # code defines __ne__.
   3662         self.assertFalse(processor1 != processor2)
   3663 
   3664 
   3665 def tearDown():
   3666     """A global check to make sure all error-categories have been tested.
   3667 
   3668     The main tearDown() routine is the only code we can guarantee will be
   3669     run after all other tests have been executed.
   3670     """
   3671     try:
   3672         if _run_verifyallcategoriesseen:
   3673             ErrorCollector(None).verify_all_categories_are_seen()
   3674     except NameError:
   3675         # If nobody set the global _run_verifyallcategoriesseen, then
   3676         # we assume we shouldn't run the test
   3677         pass
   3678 
   3679 if __name__ == '__main__':
   3680     import sys
   3681     # We don't want to run the verify_all_categories_are_seen() test unless
   3682     # we're running the full test suite: if we only run one test,
   3683     # obviously we're not going to see all the error categories.  So we
   3684     # only run verify_all_categories_are_seen() when no commandline flags
   3685     # are passed in.
   3686     global _run_verifyallcategoriesseen
   3687     _run_verifyallcategoriesseen = (len(sys.argv) == 1)
   3688 
   3689     unittest.main()
   3690