blob: 0fbda0c302b0cc51642f4e064709f0e7e301be1f [file] [log] [blame]
[email protected]2299dcf2012-11-15 19:56:241#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Daniel Cheng4dcdb6b2017-04-13 08:30:176import os.path
[email protected]99171a92014-06-03 08:44:477import subprocess
[email protected]2299dcf2012-11-15 19:56:248import unittest
9
10import PRESUBMIT
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3911from PRESUBMIT_test_mocks import MockFile, MockAffectedFile
gayane3dff8c22014-12-04 17:09:5112from PRESUBMIT_test_mocks import MockInputApi, MockOutputApi
[email protected]2299dcf2012-11-15 19:56:2413
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3914
[email protected]99171a92014-06-03 08:44:4715_TEST_DATA_DIR = 'base/test/data/presubmit'
16
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3917
[email protected]b00342e7f2013-03-26 16:21:5418class VersionControlConflictsTest(unittest.TestCase):
[email protected]70ca77752012-11-20 03:45:0319 def testTypicalConflict(self):
20 lines = ['<<<<<<< HEAD',
21 ' base::ScopedTempDir temp_dir_;',
22 '=======',
23 ' ScopedTempDir temp_dir_;',
24 '>>>>>>> master']
25 errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
26 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
27 self.assertEqual(3, len(errors))
28 self.assertTrue('1' in errors[0])
29 self.assertTrue('3' in errors[1])
30 self.assertTrue('5' in errors[2])
31
dbeam95c35a2f2015-06-02 01:40:2332 def testIgnoresReadmes(self):
33 lines = ['A First Level Header',
34 '====================',
35 '',
36 'A Second Level Header',
37 '---------------------']
38 errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
39 MockInputApi(), MockFile('some/polymer/README.md', lines))
40 self.assertEqual(0, len(errors))
41
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3942
mcasasb7440c282015-02-04 14:52:1943class UmaHistogramChangeMatchedOrNotTest(unittest.TestCase):
44 def testTypicalCorrectlyMatchedChange(self):
45 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4746 diff_java = [
47 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1948 diff_xml = ['<histogram name="Bla.Foo.Dummy"> </histogram>']
49 mock_input_api = MockInputApi()
50 mock_input_api.files = [
51 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:4752 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:1953 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
54 ]
55 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
56 MockOutputApi())
57 self.assertEqual(0, len(warnings))
58
59 def testTypicalNotMatchedChange(self):
60 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4761 diff_java = [
62 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1963 mock_input_api = MockInputApi()
Vaclav Brozekbdac817c2018-03-24 06:30:4764 mock_input_api.files = [
65 MockFile('some/path/foo.cc', diff_cc),
66 MockFile('some/path/foo.java', diff_java),
67 ]
mcasasb7440c282015-02-04 14:52:1968 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
69 MockOutputApi())
70 self.assertEqual(1, len(warnings))
71 self.assertEqual('warning', warnings[0].type)
Vaclav Brozekbdac817c2018-03-24 06:30:4772 self.assertTrue('foo.cc' in warnings[0].items[0])
73 self.assertTrue('foo.java' in warnings[0].items[1])
mcasasb7440c282015-02-04 14:52:1974
75 def testTypicalNotMatchedChangeViaSuffixes(self):
76 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4777 diff_java = [
78 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1979 diff_xml = ['<histogram_suffixes name="SuperHistogram">',
80 ' <suffix name="Dummy"/>',
81 ' <affected-histogram name="Snafu.Dummy"/>',
82 '</histogram>']
83 mock_input_api = MockInputApi()
84 mock_input_api.files = [
85 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:4786 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:1987 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
88 ]
89 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
90 MockOutputApi())
91 self.assertEqual(1, len(warnings))
92 self.assertEqual('warning', warnings[0].type)
Vaclav Brozekbdac817c2018-03-24 06:30:4793 self.assertTrue('foo.cc' in warnings[0].items[0])
94 self.assertTrue('foo.java' in warnings[0].items[1])
mcasasb7440c282015-02-04 14:52:1995
96 def testTypicalCorrectlyMatchedChangeViaSuffixes(self):
97 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4798 diff_java = [
99 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:19100 diff_xml = ['<histogram_suffixes name="SuperHistogram">',
101 ' <suffix name="Dummy"/>',
102 ' <affected-histogram name="Bla.Foo"/>',
103 '</histogram>']
104 mock_input_api = MockInputApi()
105 mock_input_api.files = [
106 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47107 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:19108 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
109 ]
110 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
111 MockOutputApi())
112 self.assertEqual(0, len(warnings))
113
114 def testTypicalCorrectlyMatchedChangeViaSuffixesWithSeparator(self):
115 diff_cc = ['UMA_HISTOGRAM_BOOL("Snafu_Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:47116 diff_java = ['RecordHistogram.recordBooleanHistogram("Snafu_Dummy", true)']
mcasasb7440c282015-02-04 14:52:19117 diff_xml = ['<histogram_suffixes name="SuperHistogram" separator="_">',
118 ' <suffix name="Dummy"/>',
119 ' <affected-histogram name="Snafu"/>',
120 '</histogram>']
121 mock_input_api = MockInputApi()
122 mock_input_api.files = [
123 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47124 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:19125 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
126 ]
127 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
128 MockOutputApi())
129 self.assertEqual(0, len(warnings))
[email protected]70ca77752012-11-20 03:45:03130
Vaclav Brozek8a8e2e202018-03-23 22:01:06131 def testNameMatch(self):
132 # Check that the detected histogram name is "Dummy" and not, e.g.,
133 # "Dummy\", true); // The \"correct"
134 diff_cc = ['UMA_HISTOGRAM_BOOL("Dummy", true); // The "correct" histogram']
Vaclav Brozekbdac817c2018-03-24 06:30:47135 diff_java = [
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39136 'RecordHistogram.recordBooleanHistogram("Dummy", true);' +
137 ' // The "correct" histogram']
Vaclav Brozek8a8e2e202018-03-23 22:01:06138 diff_xml = ['<histogram name="Dummy"> </histogram>']
139 mock_input_api = MockInputApi()
140 mock_input_api.files = [
141 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47142 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek8a8e2e202018-03-23 22:01:06143 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
144 ]
145 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
146 MockOutputApi())
147 self.assertEqual(0, len(warnings))
148
149 def testSimilarMacroNames(self):
Vaclav Brozekbdac817c2018-03-24 06:30:47150 diff_cc = ['PUMA_HISTOGRAM_COOL("Mountain Lion", 42)']
151 diff_java = [
152 'FakeRecordHistogram.recordFakeHistogram("Mountain Lion", 42)']
Vaclav Brozek8a8e2e202018-03-23 22:01:06153 mock_input_api = MockInputApi()
154 mock_input_api.files = [
155 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47156 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek8a8e2e202018-03-23 22:01:06157 ]
158 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
159 MockOutputApi())
160 self.assertEqual(0, len(warnings))
161
Vaclav Brozek0e730cbd2018-03-24 06:18:17162 def testMultiLine(self):
163 diff_cc = ['UMA_HISTOGRAM_BOOLEAN(', ' "Multi.Line", true)']
164 diff_cc2 = ['UMA_HISTOGRAM_BOOLEAN(', ' "Multi.Line"', ' , true)']
Vaclav Brozekbdac817c2018-03-24 06:30:47165 diff_java = [
166 'RecordHistogram.recordBooleanHistogram(',
167 ' "Multi.Line", true);',
168 ]
Vaclav Brozek0e730cbd2018-03-24 06:18:17169 mock_input_api = MockInputApi()
170 mock_input_api.files = [
171 MockFile('some/path/foo.cc', diff_cc),
172 MockFile('some/path/foo2.cc', diff_cc2),
Vaclav Brozekbdac817c2018-03-24 06:30:47173 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek0e730cbd2018-03-24 06:18:17174 ]
175 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
176 MockOutputApi())
177 self.assertEqual(1, len(warnings))
178 self.assertEqual('warning', warnings[0].type)
179 self.assertTrue('foo.cc' in warnings[0].items[0])
180 self.assertTrue('foo2.cc' in warnings[0].items[1])
181
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39182
[email protected]b8079ae4a2012-12-05 19:56:49183class BadExtensionsTest(unittest.TestCase):
184 def testBadRejFile(self):
185 mock_input_api = MockInputApi()
186 mock_input_api.files = [
187 MockFile('some/path/foo.cc', ''),
188 MockFile('some/path/foo.cc.rej', ''),
189 MockFile('some/path2/bar.h.rej', ''),
190 ]
191
192 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
193 self.assertEqual(1, len(results))
194 self.assertEqual(2, len(results[0].items))
195 self.assertTrue('foo.cc.rej' in results[0].items[0])
196 self.assertTrue('bar.h.rej' in results[0].items[1])
197
198 def testBadOrigFile(self):
199 mock_input_api = MockInputApi()
200 mock_input_api.files = [
201 MockFile('other/path/qux.h.orig', ''),
202 MockFile('other/path/qux.h', ''),
203 MockFile('other/path/qux.cc', ''),
204 ]
205
206 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
207 self.assertEqual(1, len(results))
208 self.assertEqual(1, len(results[0].items))
209 self.assertTrue('qux.h.orig' in results[0].items[0])
210
211 def testGoodFiles(self):
212 mock_input_api = MockInputApi()
213 mock_input_api.files = [
214 MockFile('other/path/qux.h', ''),
215 MockFile('other/path/qux.cc', ''),
216 ]
217 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
218 self.assertEqual(0, len(results))
219
220
glidere61efad2015-02-18 17:39:43221class CheckSingletonInHeadersTest(unittest.TestCase):
222 def testSingletonInArbitraryHeader(self):
223 diff_singleton_h = ['base::subtle::AtomicWord '
olli.raula36aa8be2015-09-10 11:14:22224 'base::Singleton<Type, Traits, DifferentiatingType>::']
225 diff_foo_h = ['// base::Singleton<Foo> in comment.',
226 'friend class base::Singleton<Foo>']
oysteinec430ad42015-10-22 20:55:24227 diff_foo2_h = [' //Foo* bar = base::Singleton<Foo>::get();']
olli.raula36aa8be2015-09-10 11:14:22228 diff_bad_h = ['Foo* foo = base::Singleton<Foo>::get();']
glidere61efad2015-02-18 17:39:43229 mock_input_api = MockInputApi()
230 mock_input_api.files = [MockAffectedFile('base/memory/singleton.h',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39231 diff_singleton_h),
glidere61efad2015-02-18 17:39:43232 MockAffectedFile('foo.h', diff_foo_h),
oysteinec430ad42015-10-22 20:55:24233 MockAffectedFile('foo2.h', diff_foo2_h),
glidere61efad2015-02-18 17:39:43234 MockAffectedFile('bad.h', diff_bad_h)]
235 warnings = PRESUBMIT._CheckSingletonInHeaders(mock_input_api,
236 MockOutputApi())
237 self.assertEqual(1, len(warnings))
Sylvain Defresnea8b73d252018-02-28 15:45:54238 self.assertEqual(1, len(warnings[0].items))
glidere61efad2015-02-18 17:39:43239 self.assertEqual('error', warnings[0].type)
olli.raula36aa8be2015-09-10 11:14:22240 self.assertTrue('Found base::Singleton<T>' in warnings[0].message)
glidere61efad2015-02-18 17:39:43241
242 def testSingletonInCC(self):
olli.raula36aa8be2015-09-10 11:14:22243 diff_cc = ['Foo* foo = base::Singleton<Foo>::get();']
glidere61efad2015-02-18 17:39:43244 mock_input_api = MockInputApi()
245 mock_input_api.files = [MockAffectedFile('some/path/foo.cc', diff_cc)]
246 warnings = PRESUBMIT._CheckSingletonInHeaders(mock_input_api,
247 MockOutputApi())
248 self.assertEqual(0, len(warnings))
249
250
[email protected]b00342e7f2013-03-26 16:21:54251class InvalidOSMacroNamesTest(unittest.TestCase):
252 def testInvalidOSMacroNames(self):
253 lines = ['#if defined(OS_WINDOWS)',
254 ' #elif defined(OS_WINDOW)',
255 ' # if defined(OS_MACOSX) || defined(OS_CHROME)',
256 '# else // defined(OS_MAC)',
257 '#endif // defined(OS_MACOS)']
258 errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
259 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
260 self.assertEqual(len(lines), len(errors))
261 self.assertTrue(':1 OS_WINDOWS' in errors[0])
262 self.assertTrue('(did you mean OS_WIN?)' in errors[0])
263
264 def testValidOSMacroNames(self):
265 lines = ['#if defined(%s)' % m for m in PRESUBMIT._VALID_OS_MACROS]
266 errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
267 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
268 self.assertEqual(0, len(errors))
269
270
lliabraa35bab3932014-10-01 12:16:44271class InvalidIfDefinedMacroNamesTest(unittest.TestCase):
272 def testInvalidIfDefinedMacroNames(self):
273 lines = ['#if defined(TARGET_IPHONE_SIMULATOR)',
274 '#if !defined(TARGET_IPHONE_SIMULATOR)',
275 '#elif defined(TARGET_IPHONE_SIMULATOR)',
276 '#ifdef TARGET_IPHONE_SIMULATOR',
277 ' # ifdef TARGET_IPHONE_SIMULATOR',
278 '# if defined(VALID) || defined(TARGET_IPHONE_SIMULATOR)',
279 '# else // defined(TARGET_IPHONE_SIMULATOR)',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39280 '#endif // defined(TARGET_IPHONE_SIMULATOR)']
lliabraa35bab3932014-10-01 12:16:44281 errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
282 MockInputApi(), MockFile('some/path/source.mm', lines))
283 self.assertEqual(len(lines), len(errors))
284
285 def testValidIfDefinedMacroNames(self):
286 lines = ['#if defined(FOO)',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39287 '#ifdef BAR']
lliabraa35bab3932014-10-01 12:16:44288 errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
289 MockInputApi(), MockFile('some/path/source.cc', lines))
290 self.assertEqual(0, len(errors))
291
292
[email protected]f32e2d1e2013-07-26 21:39:08293class CheckAddedDepsHaveTetsApprovalsTest(unittest.TestCase):
Daniel Cheng4dcdb6b2017-04-13 08:30:17294
295 def calculate(self, old_include_rules, old_specific_include_rules,
296 new_include_rules, new_specific_include_rules):
297 return PRESUBMIT._CalculateAddedDeps(
298 os.path, 'include_rules = %r\nspecific_include_rules = %r' % (
299 old_include_rules, old_specific_include_rules),
300 'include_rules = %r\nspecific_include_rules = %r' % (
301 new_include_rules, new_specific_include_rules))
302
303 def testCalculateAddedDeps(self):
304 old_include_rules = [
305 '+base',
306 '-chrome',
307 '+content',
308 '-grit',
309 '-grit/",',
310 '+jni/fooblat.h',
311 '!sandbox',
[email protected]f32e2d1e2013-07-26 21:39:08312 ]
Daniel Cheng4dcdb6b2017-04-13 08:30:17313 old_specific_include_rules = {
314 'compositor\.*': {
315 '+cc',
316 },
317 }
318
319 new_include_rules = [
320 '-ash',
321 '+base',
322 '+chrome',
323 '+components',
324 '+content',
325 '+grit',
326 '+grit/generated_resources.h",',
327 '+grit/",',
328 '+jni/fooblat.h',
329 '+policy',
manzagop85e629e2017-05-09 22:11:48330 '+' + os.path.join('third_party', 'WebKit'),
Daniel Cheng4dcdb6b2017-04-13 08:30:17331 ]
332 new_specific_include_rules = {
333 'compositor\.*': {
334 '+cc',
335 },
336 'widget\.*': {
337 '+gpu',
338 },
339 }
340
[email protected]f32e2d1e2013-07-26 21:39:08341 expected = set([
manzagop85e629e2017-05-09 22:11:48342 os.path.join('chrome', 'DEPS'),
343 os.path.join('gpu', 'DEPS'),
344 os.path.join('components', 'DEPS'),
345 os.path.join('policy', 'DEPS'),
346 os.path.join('third_party', 'WebKit', 'DEPS'),
[email protected]f32e2d1e2013-07-26 21:39:08347 ])
Daniel Cheng4dcdb6b2017-04-13 08:30:17348 self.assertEqual(
349 expected,
350 self.calculate(old_include_rules, old_specific_include_rules,
351 new_include_rules, new_specific_include_rules))
352
353 def testCalculateAddedDepsIgnoresPermutations(self):
354 old_include_rules = [
355 '+base',
356 '+chrome',
357 ]
358 new_include_rules = [
359 '+chrome',
360 '+base',
361 ]
362 self.assertEqual(set(),
363 self.calculate(old_include_rules, {}, new_include_rules,
364 {}))
[email protected]f32e2d1e2013-07-26 21:39:08365
366
[email protected]99171a92014-06-03 08:44:47367class JSONParsingTest(unittest.TestCase):
368 def testSuccess(self):
369 input_api = MockInputApi()
370 filename = 'valid_json.json'
371 contents = ['// This is a comment.',
372 '{',
373 ' "key1": ["value1", "value2"],',
374 ' "key2": 3 // This is an inline comment.',
375 '}'
376 ]
377 input_api.files = [MockFile(filename, contents)]
378 self.assertEqual(None,
379 PRESUBMIT._GetJSONParseError(input_api, filename))
380
381 def testFailure(self):
382 input_api = MockInputApi()
383 test_data = [
384 ('invalid_json_1.json',
385 ['{ x }'],
[email protected]a3343272014-06-17 11:41:53386 'Expecting property name:'),
[email protected]99171a92014-06-03 08:44:47387 ('invalid_json_2.json',
388 ['// Hello world!',
389 '{ "hello": "world }'],
[email protected]a3343272014-06-17 11:41:53390 'Unterminated string starting at:'),
[email protected]99171a92014-06-03 08:44:47391 ('invalid_json_3.json',
392 ['{ "a": "b", "c": "d", }'],
[email protected]a3343272014-06-17 11:41:53393 'Expecting property name:'),
[email protected]99171a92014-06-03 08:44:47394 ('invalid_json_4.json',
395 ['{ "a": "b" "c": "d" }'],
[email protected]a3343272014-06-17 11:41:53396 'Expecting , delimiter:'),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39397 ]
[email protected]99171a92014-06-03 08:44:47398
399 input_api.files = [MockFile(filename, contents)
400 for (filename, contents, _) in test_data]
401
402 for (filename, _, expected_error) in test_data:
403 actual_error = PRESUBMIT._GetJSONParseError(input_api, filename)
[email protected]a3343272014-06-17 11:41:53404 self.assertTrue(expected_error in str(actual_error),
405 "'%s' not found in '%s'" % (expected_error, actual_error))
[email protected]99171a92014-06-03 08:44:47406
407 def testNoEatComments(self):
408 input_api = MockInputApi()
409 file_with_comments = 'file_with_comments.json'
410 contents_with_comments = ['// This is a comment.',
411 '{',
412 ' "key1": ["value1", "value2"],',
413 ' "key2": 3 // This is an inline comment.',
414 '}'
415 ]
416 file_without_comments = 'file_without_comments.json'
417 contents_without_comments = ['{',
418 ' "key1": ["value1", "value2"],',
419 ' "key2": 3',
420 '}'
421 ]
422 input_api.files = [MockFile(file_with_comments, contents_with_comments),
423 MockFile(file_without_comments,
424 contents_without_comments)]
425
426 self.assertEqual('No JSON object could be decoded',
427 str(PRESUBMIT._GetJSONParseError(input_api,
428 file_with_comments,
429 eat_comments=False)))
430 self.assertEqual(None,
431 PRESUBMIT._GetJSONParseError(input_api,
432 file_without_comments,
433 eat_comments=False))
434
435
436class IDLParsingTest(unittest.TestCase):
437 def testSuccess(self):
438 input_api = MockInputApi()
439 filename = 'valid_idl_basics.idl'
440 contents = ['// Tests a valid IDL file.',
441 'namespace idl_basics {',
442 ' enum EnumType {',
443 ' name1,',
444 ' name2',
445 ' };',
446 '',
447 ' dictionary MyType1 {',
448 ' DOMString a;',
449 ' };',
450 '',
451 ' callback Callback1 = void();',
452 ' callback Callback2 = void(long x);',
453 ' callback Callback3 = void(MyType1 arg);',
454 ' callback Callback4 = void(EnumType type);',
455 '',
456 ' interface Functions {',
457 ' static void function1();',
458 ' static void function2(long x);',
459 ' static void function3(MyType1 arg);',
460 ' static void function4(Callback1 cb);',
461 ' static void function5(Callback2 cb);',
462 ' static void function6(Callback3 cb);',
463 ' static void function7(Callback4 cb);',
464 ' };',
465 '',
466 ' interface Events {',
467 ' static void onFoo1();',
468 ' static void onFoo2(long x);',
469 ' static void onFoo2(MyType1 arg);',
470 ' static void onFoo3(EnumType type);',
471 ' };',
472 '};'
473 ]
474 input_api.files = [MockFile(filename, contents)]
475 self.assertEqual(None,
476 PRESUBMIT._GetIDLParseError(input_api, filename))
477
478 def testFailure(self):
479 input_api = MockInputApi()
480 test_data = [
481 ('invalid_idl_1.idl',
482 ['//',
483 'namespace test {',
484 ' dictionary {',
485 ' DOMString s;',
486 ' };',
487 '};'],
488 'Unexpected "{" after keyword "dictionary".\n'),
489 # TODO(yoz): Disabled because it causes the IDL parser to hang.
490 # See crbug.com/363830.
491 # ('invalid_idl_2.idl',
492 # (['namespace test {',
493 # ' dictionary MissingSemicolon {',
494 # ' DOMString a',
495 # ' DOMString b;',
496 # ' };',
497 # '};'],
498 # 'Unexpected symbol DOMString after symbol a.'),
499 ('invalid_idl_3.idl',
500 ['//',
501 'namespace test {',
502 ' enum MissingComma {',
503 ' name1',
504 ' name2',
505 ' };',
506 '};'],
507 'Unexpected symbol name2 after symbol name1.'),
508 ('invalid_idl_4.idl',
509 ['//',
510 'namespace test {',
511 ' enum TrailingComma {',
512 ' name1,',
513 ' name2,',
514 ' };',
515 '};'],
516 'Trailing comma in block.'),
517 ('invalid_idl_5.idl',
518 ['//',
519 'namespace test {',
520 ' callback Callback1 = void(;',
521 '};'],
522 'Unexpected ";" after "(".'),
523 ('invalid_idl_6.idl',
524 ['//',
525 'namespace test {',
526 ' callback Callback1 = void(long );',
527 '};'],
528 'Unexpected ")" after symbol long.'),
529 ('invalid_idl_7.idl',
530 ['//',
531 'namespace test {',
532 ' interace Events {',
533 ' static void onFoo1();',
534 ' };',
535 '};'],
536 'Unexpected symbol Events after symbol interace.'),
537 ('invalid_idl_8.idl',
538 ['//',
539 'namespace test {',
540 ' interface NotEvent {',
541 ' static void onFoo1();',
542 ' };',
543 '};'],
544 'Did not process Interface Interface(NotEvent)'),
545 ('invalid_idl_9.idl',
546 ['//',
547 'namespace test {',
548 ' interface {',
549 ' static void function1();',
550 ' };',
551 '};'],
552 'Interface missing name.'),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39553 ]
[email protected]99171a92014-06-03 08:44:47554
555 input_api.files = [MockFile(filename, contents)
556 for (filename, contents, _) in test_data]
557
558 for (filename, _, expected_error) in test_data:
559 actual_error = PRESUBMIT._GetIDLParseError(input_api, filename)
560 self.assertTrue(expected_error in str(actual_error),
561 "'%s' not found in '%s'" % (expected_error, actual_error))
562
563
[email protected]0bb112362014-07-26 04:38:32564class TryServerMasterTest(unittest.TestCase):
565 def testTryServerMasters(self):
566 bots = {
tandriie5587792016-07-14 00:34:50567 'master.tryserver.chromium.android': [
jbudorick3ae7a772016-05-20 02:36:04568 'android_archive_rel_ng',
569 'android_arm64_dbg_recipe',
570 'android_blink_rel',
jbudorick3ae7a772016-05-20 02:36:04571 'android_clang_dbg_recipe',
572 'android_compile_dbg',
jbudorick3ae7a772016-05-20 02:36:04573 'android_compile_x64_dbg',
574 'android_compile_x86_dbg',
575 'android_coverage',
576 'android_cronet_tester'
577 'android_swarming_rel',
578 'cast_shell_android',
579 'linux_android_dbg_ng',
580 'linux_android_rel_ng',
581 ],
tandriie5587792016-07-14 00:34:50582 'master.tryserver.chromium.mac': [
[email protected]0bb112362014-07-26 04:38:32583 'ios_dbg_simulator',
584 'ios_rel_device',
585 'ios_rel_device_ninja',
586 'mac_asan',
587 'mac_asan_64',
588 'mac_chromium_compile_dbg',
589 'mac_chromium_compile_rel',
590 'mac_chromium_dbg',
591 'mac_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32592 'mac_nacl_sdk',
593 'mac_nacl_sdk_build',
594 'mac_rel_naclmore',
[email protected]0bb112362014-07-26 04:38:32595 'mac_x64_rel',
596 'mac_xcodebuild',
597 ],
tandriie5587792016-07-14 00:34:50598 'master.tryserver.chromium.linux': [
[email protected]0bb112362014-07-26 04:38:32599 'chromium_presubmit',
600 'linux_arm_cross_compile',
601 'linux_arm_tester',
[email protected]0bb112362014-07-26 04:38:32602 'linux_chromeos_asan',
603 'linux_chromeos_browser_asan',
604 'linux_chromeos_valgrind',
[email protected]0bb112362014-07-26 04:38:32605 'linux_chromium_chromeos_dbg',
606 'linux_chromium_chromeos_rel',
[email protected]0bb112362014-07-26 04:38:32607 'linux_chromium_compile_dbg',
608 'linux_chromium_compile_rel',
609 'linux_chromium_dbg',
610 'linux_chromium_gn_dbg',
611 'linux_chromium_gn_rel',
612 'linux_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32613 'linux_chromium_trusty32_dbg',
614 'linux_chromium_trusty32_rel',
615 'linux_chromium_trusty_dbg',
616 'linux_chromium_trusty_rel',
617 'linux_clang_tsan',
618 'linux_ecs_ozone',
619 'linux_layout',
620 'linux_layout_asan',
621 'linux_layout_rel',
622 'linux_layout_rel_32',
623 'linux_nacl_sdk',
624 'linux_nacl_sdk_bionic',
625 'linux_nacl_sdk_bionic_build',
626 'linux_nacl_sdk_build',
627 'linux_redux',
628 'linux_rel_naclmore',
629 'linux_rel_precise32',
630 'linux_valgrind',
631 'tools_build_presubmit',
632 ],
tandriie5587792016-07-14 00:34:50633 'master.tryserver.chromium.win': [
[email protected]0bb112362014-07-26 04:38:32634 'win8_aura',
635 'win8_chromium_dbg',
636 'win8_chromium_rel',
637 'win_chromium_compile_dbg',
638 'win_chromium_compile_rel',
639 'win_chromium_dbg',
640 'win_chromium_rel',
641 'win_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32642 'win_chromium_x64_dbg',
643 'win_chromium_x64_rel',
[email protected]0bb112362014-07-26 04:38:32644 'win_nacl_sdk',
645 'win_nacl_sdk_build',
646 'win_rel_naclmore',
647 ],
648 }
649 for master, bots in bots.iteritems():
650 for bot in bots:
651 self.assertEqual(master, PRESUBMIT.GetTryServerMasterForBot(bot),
652 'bot=%s: expected %s, computed %s' % (
653 bot, master, PRESUBMIT.GetTryServerMasterForBot(bot)))
654
655
davileene0426252015-03-02 21:10:41656class UserMetricsActionTest(unittest.TestCase):
657 def testUserMetricsActionInActions(self):
658 input_api = MockInputApi()
659 file_with_user_action = 'file_with_user_action.cc'
660 contents_with_user_action = [
661 'base::UserMetricsAction("AboutChrome")'
662 ]
663
664 input_api.files = [MockFile(file_with_user_action,
665 contents_with_user_action)]
666
667 self.assertEqual(
668 [], PRESUBMIT._CheckUserActionUpdate(input_api, MockOutputApi()))
669
davileene0426252015-03-02 21:10:41670 def testUserMetricsActionNotAddedToActions(self):
671 input_api = MockInputApi()
672 file_with_user_action = 'file_with_user_action.cc'
673 contents_with_user_action = [
674 'base::UserMetricsAction("NotInActionsXml")'
675 ]
676
677 input_api.files = [MockFile(file_with_user_action,
678 contents_with_user_action)]
679
680 output = PRESUBMIT._CheckUserActionUpdate(input_api, MockOutputApi())
681 self.assertEqual(
682 ('File %s line %d: %s is missing in '
683 'tools/metrics/actions/actions.xml. Please run '
684 'tools/metrics/actions/extract_actions.py to update.'
685 % (file_with_user_action, 1, 'NotInActionsXml')),
686 output[0].message)
687
688
agrievef32bcc72016-04-04 14:57:40689class PydepsNeedsUpdatingTest(unittest.TestCase):
690
691 class MockSubprocess(object):
692 CalledProcessError = subprocess.CalledProcessError
693
694 def setUp(self):
695 mock_all_pydeps = ['A.pydeps', 'B.pydeps']
696 self.old_ALL_PYDEPS_FILES = PRESUBMIT._ALL_PYDEPS_FILES
697 PRESUBMIT._ALL_PYDEPS_FILES = mock_all_pydeps
698 self.mock_input_api = MockInputApi()
699 self.mock_output_api = MockOutputApi()
700 self.mock_input_api.subprocess = PydepsNeedsUpdatingTest.MockSubprocess()
701 self.checker = PRESUBMIT.PydepsChecker(self.mock_input_api, mock_all_pydeps)
702 self.checker._file_cache = {
703 'A.pydeps': '# Generated by:\n# CMD A\nA.py\nC.py\n',
704 'B.pydeps': '# Generated by:\n# CMD B\nB.py\nC.py\n',
705 }
706
707 def tearDown(self):
708 PRESUBMIT._ALL_PYDEPS_FILES = self.old_ALL_PYDEPS_FILES
709
710 def _RunCheck(self):
711 return PRESUBMIT._CheckPydepsNeedsUpdating(self.mock_input_api,
712 self.mock_output_api,
713 checker_for_tests=self.checker)
714
715 def testAddedPydep(self):
pastarmovj89f7ee12016-09-20 14:58:13716 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
717 if self.mock_input_api.platform != 'linux2':
718 return []
719
agrievef32bcc72016-04-04 14:57:40720 self.mock_input_api.files = [
721 MockAffectedFile('new.pydeps', [], action='A'),
722 ]
723
Zhiling Huang45cabf32018-03-10 00:50:03724 self.mock_input_api.CreateMockFileInPath(
725 [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
726 include_deletes=True)])
agrievef32bcc72016-04-04 14:57:40727 results = self._RunCheck()
728 self.assertEqual(1, len(results))
729 self.assertTrue('PYDEPS_FILES' in str(results[0]))
730
Zhiling Huang45cabf32018-03-10 00:50:03731 def testPydepNotInSrc(self):
732 self.mock_input_api.files = [
733 MockAffectedFile('new.pydeps', [], action='A'),
734 ]
735 self.mock_input_api.CreateMockFileInPath([])
736 results = self._RunCheck()
737 self.assertEqual(0, len(results))
738
agrievef32bcc72016-04-04 14:57:40739 def testRemovedPydep(self):
pastarmovj89f7ee12016-09-20 14:58:13740 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
741 if self.mock_input_api.platform != 'linux2':
742 return []
743
agrievef32bcc72016-04-04 14:57:40744 self.mock_input_api.files = [
745 MockAffectedFile(PRESUBMIT._ALL_PYDEPS_FILES[0], [], action='D'),
746 ]
Zhiling Huang45cabf32018-03-10 00:50:03747 self.mock_input_api.CreateMockFileInPath(
748 [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
749 include_deletes=True)])
agrievef32bcc72016-04-04 14:57:40750 results = self._RunCheck()
751 self.assertEqual(1, len(results))
752 self.assertTrue('PYDEPS_FILES' in str(results[0]))
753
754 def testRandomPyIgnored(self):
pastarmovj89f7ee12016-09-20 14:58:13755 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
756 if self.mock_input_api.platform != 'linux2':
757 return []
758
agrievef32bcc72016-04-04 14:57:40759 self.mock_input_api.files = [
760 MockAffectedFile('random.py', []),
761 ]
762
763 results = self._RunCheck()
764 self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
765
766 def testRelevantPyNoChange(self):
pastarmovj89f7ee12016-09-20 14:58:13767 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
768 if self.mock_input_api.platform != 'linux2':
769 return []
770
agrievef32bcc72016-04-04 14:57:40771 self.mock_input_api.files = [
772 MockAffectedFile('A.py', []),
773 ]
774
John Budorickab2fa102017-10-06 16:59:49775 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40776 self.assertEqual('CMD A --output ""', cmd)
777 return self.checker._file_cache['A.pydeps']
778
779 self.mock_input_api.subprocess.check_output = mock_check_output
780
781 results = self._RunCheck()
782 self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
783
784 def testRelevantPyOneChange(self):
pastarmovj89f7ee12016-09-20 14:58:13785 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
786 if self.mock_input_api.platform != 'linux2':
787 return []
788
agrievef32bcc72016-04-04 14:57:40789 self.mock_input_api.files = [
790 MockAffectedFile('A.py', []),
791 ]
792
John Budorickab2fa102017-10-06 16:59:49793 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40794 self.assertEqual('CMD A --output ""', cmd)
795 return 'changed data'
796
797 self.mock_input_api.subprocess.check_output = mock_check_output
798
799 results = self._RunCheck()
800 self.assertEqual(1, len(results))
801 self.assertTrue('File is stale' in str(results[0]))
802
803 def testRelevantPyTwoChanges(self):
pastarmovj89f7ee12016-09-20 14:58:13804 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
805 if self.mock_input_api.platform != 'linux2':
806 return []
807
agrievef32bcc72016-04-04 14:57:40808 self.mock_input_api.files = [
809 MockAffectedFile('C.py', []),
810 ]
811
John Budorickab2fa102017-10-06 16:59:49812 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40813 return 'changed data'
814
815 self.mock_input_api.subprocess.check_output = mock_check_output
816
817 results = self._RunCheck()
818 self.assertEqual(2, len(results))
819 self.assertTrue('File is stale' in str(results[0]))
820 self.assertTrue('File is stale' in str(results[1]))
821
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39822
Daniel Bratell8ba52722018-03-02 16:06:14823class IncludeGuardTest(unittest.TestCase):
824 def testIncludeGuardChecks(self):
825 mock_input_api = MockInputApi()
826 mock_output_api = MockOutputApi()
827 mock_input_api.files = [
828 MockAffectedFile('content/browser/thing/foo.h', [
829 '// Comment',
830 '#ifndef CONTENT_BROWSER_THING_FOO_H_',
831 '#define CONTENT_BROWSER_THING_FOO_H_',
832 'struct McBoatFace;',
833 '#endif // CONTENT_BROWSER_THING_FOO_H_',
834 ]),
835 MockAffectedFile('content/browser/thing/bar.h', [
836 '#ifndef CONTENT_BROWSER_THING_BAR_H_',
837 '#define CONTENT_BROWSER_THING_BAR_H_',
838 'namespace content {',
839 '#endif // CONTENT_BROWSER_THING_BAR_H_',
840 '} // namespace content',
841 ]),
842 MockAffectedFile('content/browser/test1.h', [
843 'namespace content {',
844 '} // namespace content',
845 ]),
846 MockAffectedFile('content\\browser\\win.h', [
847 '#ifndef CONTENT_BROWSER_WIN_H_',
848 '#define CONTENT_BROWSER_WIN_H_',
849 'struct McBoatFace;',
850 '#endif // CONTENT_BROWSER_WIN_H_',
851 ]),
852 MockAffectedFile('content/browser/test2.h', [
853 '// Comment',
854 '#ifndef CONTENT_BROWSER_TEST2_H_',
855 'struct McBoatFace;',
856 '#endif // CONTENT_BROWSER_TEST2_H_',
857 ]),
858 MockAffectedFile('content/browser/internal.h', [
859 '// Comment',
860 '#ifndef CONTENT_BROWSER_INTERNAL_H_',
861 '#define CONTENT_BROWSER_INTERNAL_H_',
862 '// Comment',
863 '#ifndef INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
864 '#define INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
865 'namespace internal {',
866 '} // namespace internal',
867 '#endif // INTERNAL_CONTENT_BROWSER_THING_BAR_H_',
868 'namespace content {',
869 '} // namespace content',
870 '#endif // CONTENT_BROWSER_THING_BAR_H_',
871 ]),
872 MockAffectedFile('content/browser/thing/foo.cc', [
873 '// This is a non-header.',
874 ]),
875 MockAffectedFile('content/browser/disabled.h', [
876 '// no-include-guard-because-multiply-included',
877 'struct McBoatFace;',
878 ]),
879 # New files don't allow misspelled include guards.
880 MockAffectedFile('content/browser/spleling.h', [
881 '#ifndef CONTENT_BROWSER_SPLLEING_H_',
882 '#define CONTENT_BROWSER_SPLLEING_H_',
883 'struct McBoatFace;',
884 '#endif // CONTENT_BROWSER_SPLLEING_H_',
885 ]),
Olivier Robinbba137492018-07-30 11:31:34886 # New files don't allow + in include guards.
887 MockAffectedFile('content/browser/foo+bar.h', [
888 '#ifndef CONTENT_BROWSER_FOO+BAR_H_',
889 '#define CONTENT_BROWSER_FOO+BAR_H_',
890 'struct McBoatFace;',
891 '#endif // CONTENT_BROWSER_FOO+BAR_H_',
892 ]),
Daniel Bratell8ba52722018-03-02 16:06:14893 # Old files allow misspelled include guards (for now).
894 MockAffectedFile('chrome/old.h', [
895 '// New contents',
896 '#ifndef CHROME_ODL_H_',
897 '#define CHROME_ODL_H_',
898 '#endif // CHROME_ODL_H_',
899 ], [
900 '// Old contents',
901 '#ifndef CHROME_ODL_H_',
902 '#define CHROME_ODL_H_',
903 '#endif // CHROME_ODL_H_',
904 ]),
905 # Using a Blink style include guard outside Blink is wrong.
906 MockAffectedFile('content/NotInBlink.h', [
907 '#ifndef NotInBlink_h',
908 '#define NotInBlink_h',
909 'struct McBoatFace;',
910 '#endif // NotInBlink_h',
911 ]),
Daniel Bratell39b5b062018-05-16 18:09:57912 # Using a Blink style include guard in Blink is no longer ok.
913 MockAffectedFile('third_party/blink/InBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14914 '#ifndef InBlink_h',
915 '#define InBlink_h',
916 'struct McBoatFace;',
917 '#endif // InBlink_h',
918 ]),
919 # Using a bad include guard in Blink is not ok.
Daniel Bratell39b5b062018-05-16 18:09:57920 MockAffectedFile('third_party/blink/AlsoInBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14921 '#ifndef WrongInBlink_h',
922 '#define WrongInBlink_h',
923 'struct McBoatFace;',
924 '#endif // WrongInBlink_h',
925 ]),
Daniel Bratell39b5b062018-05-16 18:09:57926 # Using a bad include guard in Blink is not accepted even if
927 # it's an old file.
928 MockAffectedFile('third_party/blink/StillInBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14929 '// New contents',
930 '#ifndef AcceptedInBlink_h',
931 '#define AcceptedInBlink_h',
932 'struct McBoatFace;',
933 '#endif // AcceptedInBlink_h',
934 ], [
935 '// Old contents',
936 '#ifndef AcceptedInBlink_h',
937 '#define AcceptedInBlink_h',
938 'struct McBoatFace;',
939 '#endif // AcceptedInBlink_h',
940 ]),
Daniel Bratell39b5b062018-05-16 18:09:57941 # Using a non-Chromium include guard in third_party
942 # (outside blink) is accepted.
943 MockAffectedFile('third_party/foo/some_file.h', [
944 '#ifndef REQUIRED_RPCNDR_H_',
945 '#define REQUIRED_RPCNDR_H_',
946 'struct SomeFileFoo;',
947 '#endif // REQUIRED_RPCNDR_H_',
948 ]),
Daniel Bratell8ba52722018-03-02 16:06:14949 ]
950 msgs = PRESUBMIT._CheckForIncludeGuards(
951 mock_input_api, mock_output_api)
Olivier Robinbba137492018-07-30 11:31:34952 expected_fail_count = 8
Daniel Bratell8ba52722018-03-02 16:06:14953 self.assertEqual(expected_fail_count, len(msgs),
954 'Expected %d items, found %d: %s'
955 % (expected_fail_count, len(msgs), msgs))
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39956 self.assertEqual(msgs[0].items, ['content/browser/thing/bar.h'])
Daniel Bratell8ba52722018-03-02 16:06:14957 self.assertEqual(msgs[0].message,
958 'Include guard CONTENT_BROWSER_THING_BAR_H_ '
959 'not covering the whole file')
960
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39961 self.assertEqual(msgs[1].items, ['content/browser/test1.h'])
Daniel Bratell8ba52722018-03-02 16:06:14962 self.assertEqual(msgs[1].message,
963 'Missing include guard CONTENT_BROWSER_TEST1_H_')
964
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39965 self.assertEqual(msgs[2].items, ['content/browser/test2.h:3'])
Daniel Bratell8ba52722018-03-02 16:06:14966 self.assertEqual(msgs[2].message,
967 'Missing "#define CONTENT_BROWSER_TEST2_H_" for '
968 'include guard')
969
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39970 self.assertEqual(msgs[3].items, ['content/browser/spleling.h:1'])
Daniel Bratell8ba52722018-03-02 16:06:14971 self.assertEqual(msgs[3].message,
972 'Header using the wrong include guard name '
973 'CONTENT_BROWSER_SPLLEING_H_')
974
Olivier Robinbba137492018-07-30 11:31:34975 self.assertEqual(msgs[4].items, ['content/browser/foo+bar.h'])
Daniel Bratell8ba52722018-03-02 16:06:14976 self.assertEqual(msgs[4].message,
Olivier Robinbba137492018-07-30 11:31:34977 'Missing include guard CONTENT_BROWSER_FOO_BAR_H_')
978
979 self.assertEqual(msgs[5].items, ['content/NotInBlink.h:1'])
980 self.assertEqual(msgs[5].message,
Daniel Bratell8ba52722018-03-02 16:06:14981 'Header using the wrong include guard name '
982 'NotInBlink_h')
983
Olivier Robinbba137492018-07-30 11:31:34984 self.assertEqual(msgs[6].items, ['third_party/blink/InBlink.h:1'])
985 self.assertEqual(msgs[6].message,
Daniel Bratell8ba52722018-03-02 16:06:14986 'Header using the wrong include guard name '
Daniel Bratell39b5b062018-05-16 18:09:57987 'InBlink_h')
988
Olivier Robinbba137492018-07-30 11:31:34989 self.assertEqual(msgs[7].items, ['third_party/blink/AlsoInBlink.h:1'])
990 self.assertEqual(msgs[7].message,
Daniel Bratell39b5b062018-05-16 18:09:57991 'Header using the wrong include guard name '
Daniel Bratell8ba52722018-03-02 16:06:14992 'WrongInBlink_h')
993
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39994
yolandyan45001472016-12-21 21:12:42995class AndroidDeprecatedTestAnnotationTest(unittest.TestCase):
996 def testCheckAndroidTestAnnotationUsage(self):
997 mock_input_api = MockInputApi()
998 mock_output_api = MockOutputApi()
999
1000 mock_input_api.files = [
1001 MockAffectedFile('LalaLand.java', [
1002 'random stuff'
1003 ]),
1004 MockAffectedFile('CorrectUsage.java', [
1005 'import android.support.test.filters.LargeTest;',
1006 'import android.support.test.filters.MediumTest;',
1007 'import android.support.test.filters.SmallTest;',
1008 ]),
1009 MockAffectedFile('UsedDeprecatedLargeTestAnnotation.java', [
1010 'import android.test.suitebuilder.annotation.LargeTest;',
1011 ]),
1012 MockAffectedFile('UsedDeprecatedMediumTestAnnotation.java', [
1013 'import android.test.suitebuilder.annotation.MediumTest;',
1014 ]),
1015 MockAffectedFile('UsedDeprecatedSmallTestAnnotation.java', [
1016 'import android.test.suitebuilder.annotation.SmallTest;',
1017 ]),
1018 MockAffectedFile('UsedDeprecatedSmokeAnnotation.java', [
1019 'import android.test.suitebuilder.annotation.Smoke;',
1020 ])
1021 ]
1022 msgs = PRESUBMIT._CheckAndroidTestAnnotationUsage(
1023 mock_input_api, mock_output_api)
1024 self.assertEqual(1, len(msgs),
1025 'Expected %d items, found %d: %s'
1026 % (1, len(msgs), msgs))
1027 self.assertEqual(4, len(msgs[0].items),
1028 'Expected %d items, found %d: %s'
1029 % (4, len(msgs[0].items), msgs[0].items))
1030 self.assertTrue('UsedDeprecatedLargeTestAnnotation.java:1' in msgs[0].items,
1031 'UsedDeprecatedLargeTestAnnotation not found in errors')
1032 self.assertTrue('UsedDeprecatedMediumTestAnnotation.java:1'
1033 in msgs[0].items,
1034 'UsedDeprecatedMediumTestAnnotation not found in errors')
1035 self.assertTrue('UsedDeprecatedSmallTestAnnotation.java:1' in msgs[0].items,
1036 'UsedDeprecatedSmallTestAnnotation not found in errors')
1037 self.assertTrue('UsedDeprecatedSmokeAnnotation.java:1' in msgs[0].items,
1038 'UsedDeprecatedSmokeAnnotation not found in errors')
1039
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391040
Yoland Yanb92fa522017-08-28 17:37:061041class AndroidDeprecatedJUnitFrameworkTest(unittest.TestCase):
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271042 def testCheckAndroidTestJUnitFramework(self):
Yoland Yanb92fa522017-08-28 17:37:061043 mock_input_api = MockInputApi()
1044 mock_output_api = MockOutputApi()
yolandyan45001472016-12-21 21:12:421045
Yoland Yanb92fa522017-08-28 17:37:061046 mock_input_api.files = [
1047 MockAffectedFile('LalaLand.java', [
1048 'random stuff'
1049 ]),
1050 MockAffectedFile('CorrectUsage.java', [
1051 'import org.junit.ABC',
1052 'import org.junit.XYZ;',
1053 ]),
1054 MockAffectedFile('UsedDeprecatedJUnit.java', [
1055 'import junit.framework.*;',
1056 ]),
1057 MockAffectedFile('UsedDeprecatedJUnitAssert.java', [
1058 'import junit.framework.Assert;',
1059 ]),
1060 ]
1061 msgs = PRESUBMIT._CheckAndroidTestJUnitFrameworkImport(
1062 mock_input_api, mock_output_api)
1063 self.assertEqual(1, len(msgs),
1064 'Expected %d items, found %d: %s'
1065 % (1, len(msgs), msgs))
1066 self.assertEqual(2, len(msgs[0].items),
1067 'Expected %d items, found %d: %s'
1068 % (2, len(msgs[0].items), msgs[0].items))
1069 self.assertTrue('UsedDeprecatedJUnit.java:1' in msgs[0].items,
1070 'UsedDeprecatedJUnit.java not found in errors')
1071 self.assertTrue('UsedDeprecatedJUnitAssert.java:1'
1072 in msgs[0].items,
1073 'UsedDeprecatedJUnitAssert not found in errors')
1074
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391075
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271076class AndroidJUnitBaseClassTest(unittest.TestCase):
1077 def testCheckAndroidTestJUnitBaseClass(self):
Yoland Yanb92fa522017-08-28 17:37:061078 mock_input_api = MockInputApi()
1079 mock_output_api = MockOutputApi()
1080
1081 mock_input_api.files = [
1082 MockAffectedFile('LalaLand.java', [
1083 'random stuff'
1084 ]),
1085 MockAffectedFile('CorrectTest.java', [
1086 '@RunWith(ABC.class);'
1087 'public class CorrectTest {',
1088 '}',
1089 ]),
1090 MockAffectedFile('HistoricallyIncorrectTest.java', [
1091 'public class Test extends BaseCaseA {',
1092 '}',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391093 ], old_contents=[
Yoland Yanb92fa522017-08-28 17:37:061094 'public class Test extends BaseCaseB {',
1095 '}',
1096 ]),
1097 MockAffectedFile('CorrectTestWithInterface.java', [
1098 '@RunWith(ABC.class);'
1099 'public class CorrectTest implement Interface {',
1100 '}',
1101 ]),
1102 MockAffectedFile('IncorrectTest.java', [
1103 'public class IncorrectTest extends TestCase {',
1104 '}',
1105 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241106 MockAffectedFile('IncorrectWithInterfaceTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061107 'public class Test implements X extends BaseClass {',
1108 '}',
1109 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241110 MockAffectedFile('IncorrectMultiLineTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061111 'public class Test implements X, Y, Z',
1112 ' extends TestBase {',
1113 '}',
1114 ]),
1115 ]
1116 msgs = PRESUBMIT._CheckAndroidTestJUnitInheritance(
1117 mock_input_api, mock_output_api)
1118 self.assertEqual(1, len(msgs),
1119 'Expected %d items, found %d: %s'
1120 % (1, len(msgs), msgs))
1121 self.assertEqual(3, len(msgs[0].items),
1122 'Expected %d items, found %d: %s'
1123 % (3, len(msgs[0].items), msgs[0].items))
1124 self.assertTrue('IncorrectTest.java:1' in msgs[0].items,
1125 'IncorrectTest not found in errors')
Vaclav Brozekf01ed502018-03-16 19:38:241126 self.assertTrue('IncorrectWithInterfaceTest.java:1'
Yoland Yanb92fa522017-08-28 17:37:061127 in msgs[0].items,
Vaclav Brozekf01ed502018-03-16 19:38:241128 'IncorrectWithInterfaceTest not found in errors')
1129 self.assertTrue('IncorrectMultiLineTest.java:2' in msgs[0].items,
1130 'IncorrectMultiLineTest not found in errors')
yolandyan45001472016-12-21 21:12:421131
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391132
dgn4401aa52015-04-29 16:26:171133class LogUsageTest(unittest.TestCase):
1134
dgnaa68d5e2015-06-10 10:08:221135 def testCheckAndroidCrLogUsage(self):
1136 mock_input_api = MockInputApi()
1137 mock_output_api = MockOutputApi()
1138
1139 mock_input_api.files = [
1140 MockAffectedFile('RandomStuff.java', [
1141 'random stuff'
1142 ]),
dgn87d9fb62015-06-12 09:15:121143 MockAffectedFile('HasAndroidLog.java', [
1144 'import android.util.Log;',
1145 'some random stuff',
1146 'Log.d("TAG", "foo");',
1147 ]),
1148 MockAffectedFile('HasExplicitUtilLog.java', [
1149 'some random stuff',
1150 'android.util.Log.d("TAG", "foo");',
1151 ]),
1152 MockAffectedFile('IsInBasePackage.java', [
1153 'package org.chromium.base;',
dgn38736db2015-09-18 19:20:511154 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121155 'Log.d(TAG, "foo");',
1156 ]),
1157 MockAffectedFile('IsInBasePackageButImportsLog.java', [
1158 'package org.chromium.base;',
1159 'import android.util.Log;',
dgn38736db2015-09-18 19:20:511160 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121161 'Log.d(TAG, "foo");',
1162 ]),
1163 MockAffectedFile('HasBothLog.java', [
1164 'import org.chromium.base.Log;',
1165 'some random stuff',
dgn38736db2015-09-18 19:20:511166 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121167 'Log.d(TAG, "foo");',
1168 'android.util.Log.d("TAG", "foo");',
1169 ]),
dgnaa68d5e2015-06-10 10:08:221170 MockAffectedFile('HasCorrectTag.java', [
1171 'import org.chromium.base.Log;',
1172 'some random stuff',
dgn38736db2015-09-18 19:20:511173 'private static final String TAG = "cr_Foo";',
1174 'Log.d(TAG, "foo");',
1175 ]),
1176 MockAffectedFile('HasOldTag.java', [
1177 'import org.chromium.base.Log;',
1178 'some random stuff',
dgnaa68d5e2015-06-10 10:08:221179 'private static final String TAG = "cr.Foo";',
1180 'Log.d(TAG, "foo");',
1181 ]),
dgn38736db2015-09-18 19:20:511182 MockAffectedFile('HasDottedTag.java', [
dgnaa68d5e2015-06-10 10:08:221183 'import org.chromium.base.Log;',
1184 'some random stuff',
dgn38736db2015-09-18 19:20:511185 'private static final String TAG = "cr_foo.bar";',
dgnaa68d5e2015-06-10 10:08:221186 'Log.d(TAG, "foo");',
1187 ]),
1188 MockAffectedFile('HasNoTagDecl.java', [
1189 'import org.chromium.base.Log;',
1190 'some random stuff',
1191 'Log.d(TAG, "foo");',
1192 ]),
1193 MockAffectedFile('HasIncorrectTagDecl.java', [
1194 'import org.chromium.base.Log;',
dgn38736db2015-09-18 19:20:511195 'private static final String TAHG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221196 'some random stuff',
1197 'Log.d(TAG, "foo");',
1198 ]),
1199 MockAffectedFile('HasInlineTag.java', [
1200 'import org.chromium.base.Log;',
1201 'some random stuff',
dgn38736db2015-09-18 19:20:511202 'private static final String TAG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221203 'Log.d("TAG", "foo");',
1204 ]),
dgn38736db2015-09-18 19:20:511205 MockAffectedFile('HasUnprefixedTag.java', [
dgnaa68d5e2015-06-10 10:08:221206 'import org.chromium.base.Log;',
1207 'some random stuff',
1208 'private static final String TAG = "rubbish";',
1209 'Log.d(TAG, "foo");',
1210 ]),
1211 MockAffectedFile('HasTooLongTag.java', [
1212 'import org.chromium.base.Log;',
1213 'some random stuff',
dgn38736db2015-09-18 19:20:511214 'private static final String TAG = "21_charachers_long___";',
dgnaa68d5e2015-06-10 10:08:221215 'Log.d(TAG, "foo");',
1216 ]),
1217 ]
1218
1219 msgs = PRESUBMIT._CheckAndroidCrLogUsage(
1220 mock_input_api, mock_output_api)
1221
dgn38736db2015-09-18 19:20:511222 self.assertEqual(5, len(msgs),
1223 'Expected %d items, found %d: %s' % (5, len(msgs), msgs))
dgnaa68d5e2015-06-10 10:08:221224
1225 # Declaration format
dgn38736db2015-09-18 19:20:511226 nb = len(msgs[0].items)
1227 self.assertEqual(2, nb,
1228 'Expected %d items, found %d: %s' % (2, nb, msgs[0].items))
dgnaa68d5e2015-06-10 10:08:221229 self.assertTrue('HasNoTagDecl.java' in msgs[0].items)
1230 self.assertTrue('HasIncorrectTagDecl.java' in msgs[0].items)
dgnaa68d5e2015-06-10 10:08:221231
1232 # Tag length
dgn38736db2015-09-18 19:20:511233 nb = len(msgs[1].items)
1234 self.assertEqual(1, nb,
1235 'Expected %d items, found %d: %s' % (1, nb, msgs[1].items))
dgnaa68d5e2015-06-10 10:08:221236 self.assertTrue('HasTooLongTag.java' in msgs[1].items)
1237
1238 # Tag must be a variable named TAG
dgn38736db2015-09-18 19:20:511239 nb = len(msgs[2].items)
1240 self.assertEqual(1, nb,
1241 'Expected %d items, found %d: %s' % (1, nb, msgs[2].items))
dgnaa68d5e2015-06-10 10:08:221242 self.assertTrue('HasInlineTag.java:4' in msgs[2].items)
1243
dgn87d9fb62015-06-12 09:15:121244 # Util Log usage
dgn38736db2015-09-18 19:20:511245 nb = len(msgs[3].items)
1246 self.assertEqual(2, nb,
1247 'Expected %d items, found %d: %s' % (2, nb, msgs[3].items))
dgn87d9fb62015-06-12 09:15:121248 self.assertTrue('HasAndroidLog.java:3' in msgs[3].items)
1249 self.assertTrue('IsInBasePackageButImportsLog.java:4' in msgs[3].items)
dgnaa68d5e2015-06-10 10:08:221250
dgn38736db2015-09-18 19:20:511251 # Tag must not contain
1252 nb = len(msgs[4].items)
1253 self.assertEqual(2, nb,
1254 'Expected %d items, found %d: %s' % (2, nb, msgs[4].items))
1255 self.assertTrue('HasDottedTag.java' in msgs[4].items)
1256 self.assertTrue('HasOldTag.java' in msgs[4].items)
1257
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391258
estadee17314a02017-01-12 16:22:161259class GoogleAnswerUrlFormatTest(unittest.TestCase):
1260
1261 def testCatchAnswerUrlId(self):
1262 input_api = MockInputApi()
1263 input_api.files = [
1264 MockFile('somewhere/file.cc',
1265 ['char* host = '
1266 ' "https://support.google.com/chrome/answer/123456";']),
1267 MockFile('somewhere_else/file.cc',
1268 ['char* host = '
1269 ' "https://support.google.com/chrome/a/answer/123456";']),
1270 ]
1271
1272 warnings = PRESUBMIT._CheckGoogleSupportAnswerUrl(
1273 input_api, MockOutputApi())
1274 self.assertEqual(1, len(warnings))
1275 self.assertEqual(2, len(warnings[0].items))
1276
1277 def testAllowAnswerUrlParam(self):
1278 input_api = MockInputApi()
1279 input_api.files = [
1280 MockFile('somewhere/file.cc',
1281 ['char* host = '
1282 ' "https://support.google.com/chrome/?p=cpn_crash_reports";']),
1283 ]
1284
1285 warnings = PRESUBMIT._CheckGoogleSupportAnswerUrl(
1286 input_api, MockOutputApi())
1287 self.assertEqual(0, len(warnings))
1288
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391289
reillyi38965732015-11-16 18:27:331290class HardcodedGoogleHostsTest(unittest.TestCase):
1291
1292 def testWarnOnAssignedLiterals(self):
1293 input_api = MockInputApi()
1294 input_api.files = [
1295 MockFile('content/file.cc',
1296 ['char* host = "https://www.google.com";']),
1297 MockFile('content/file.cc',
1298 ['char* host = "https://www.googleapis.com";']),
1299 MockFile('content/file.cc',
1300 ['char* host = "https://clients1.google.com";']),
1301 ]
1302
1303 warnings = PRESUBMIT._CheckHardcodedGoogleHostsInLowerLayers(
1304 input_api, MockOutputApi())
1305 self.assertEqual(1, len(warnings))
1306 self.assertEqual(3, len(warnings[0].items))
1307
1308 def testAllowInComment(self):
1309 input_api = MockInputApi()
1310 input_api.files = [
1311 MockFile('content/file.cc',
1312 ['char* host = "https://www.aol.com"; // google.com'])
1313 ]
1314
1315 warnings = PRESUBMIT._CheckHardcodedGoogleHostsInLowerLayers(
1316 input_api, MockOutputApi())
1317 self.assertEqual(0, len(warnings))
1318
dgn4401aa52015-04-29 16:26:171319
jbriance9e12f162016-11-25 07:57:501320class ForwardDeclarationTest(unittest.TestCase):
jbriance2c51e821a2016-12-12 08:24:311321 def testCheckHeadersOnlyOutsideThirdParty(self):
jbriance9e12f162016-11-25 07:57:501322 mock_input_api = MockInputApi()
1323 mock_input_api.files = [
1324 MockAffectedFile('somewhere/file.cc', [
1325 'class DummyClass;'
jbriance2c51e821a2016-12-12 08:24:311326 ]),
1327 MockAffectedFile('third_party/header.h', [
1328 'class DummyClass;'
jbriance9e12f162016-11-25 07:57:501329 ])
1330 ]
1331 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391332 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501333 self.assertEqual(0, len(warnings))
1334
1335 def testNoNestedDeclaration(self):
1336 mock_input_api = MockInputApi()
1337 mock_input_api.files = [
1338 MockAffectedFile('somewhere/header.h', [
jbriance2c51e821a2016-12-12 08:24:311339 'class SomeClass {',
1340 ' protected:',
1341 ' class NotAMatch;',
jbriance9e12f162016-11-25 07:57:501342 '};'
1343 ])
1344 ]
1345 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391346 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501347 self.assertEqual(0, len(warnings))
1348
1349 def testSubStrings(self):
1350 mock_input_api = MockInputApi()
1351 mock_input_api.files = [
1352 MockAffectedFile('somewhere/header.h', [
1353 'class NotUsefulClass;',
1354 'struct SomeStruct;',
1355 'UsefulClass *p1;',
1356 'SomeStructPtr *p2;'
1357 ])
1358 ]
1359 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391360 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501361 self.assertEqual(2, len(warnings))
1362
1363 def testUselessForwardDeclaration(self):
1364 mock_input_api = MockInputApi()
1365 mock_input_api.files = [
1366 MockAffectedFile('somewhere/header.h', [
1367 'class DummyClass;',
1368 'struct DummyStruct;',
1369 'class UsefulClass;',
1370 'std::unique_ptr<UsefulClass> p;'
jbriance2c51e821a2016-12-12 08:24:311371 ])
jbriance9e12f162016-11-25 07:57:501372 ]
1373 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391374 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501375 self.assertEqual(2, len(warnings))
1376
jbriance2c51e821a2016-12-12 08:24:311377 def testBlinkHeaders(self):
1378 mock_input_api = MockInputApi()
1379 mock_input_api.files = [
1380 MockAffectedFile('third_party/WebKit/header.h', [
1381 'class DummyClass;',
1382 'struct DummyStruct;',
1383 ]),
1384 MockAffectedFile('third_party\\WebKit\\header.h', [
1385 'class DummyClass;',
1386 'struct DummyStruct;',
1387 ])
1388 ]
1389 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391390 MockOutputApi())
jbriance2c51e821a2016-12-12 08:24:311391 self.assertEqual(4, len(warnings))
1392
jbriance9e12f162016-11-25 07:57:501393
dbeam1ec68ac2016-12-15 05:22:241394class RiskyJsTest(unittest.TestCase):
1395 def testArrowWarnInIos9Code(self):
1396 mock_input_api = MockInputApi()
1397 mock_output_api = MockOutputApi()
1398
1399 mock_input_api.files = [
1400 MockAffectedFile('components/blah.js', ["shouldn't use => here"]),
1401 ]
1402 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1403 mock_input_api, mock_output_api)
1404 self.assertEqual(1, len(warnings))
1405
1406 mock_input_api.files = [
1407 MockAffectedFile('ios/blee.js', ['might => break folks']),
1408 ]
1409 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1410 mock_input_api, mock_output_api)
1411 self.assertEqual(1, len(warnings))
1412
1413 mock_input_api.files = [
1414 MockAffectedFile('ui/webui/resources/blarg.js', ['on => iOS9']),
1415 ]
1416 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1417 mock_input_api, mock_output_api)
1418 self.assertEqual(1, len(warnings))
1419
1420 def testArrowsAllowedInChromeCode(self):
1421 mock_input_api = MockInputApi()
1422 mock_input_api.files = [
1423 MockAffectedFile('chrome/browser/resources/blah.js', 'arrow => OK here'),
1424 ]
1425 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1426 mock_input_api, MockOutputApi())
1427 self.assertEqual(0, len(warnings))
1428
dpapadd651231d82017-07-21 02:44:471429 def testConstLetWarningIos9Code(self):
1430 mock_input_api = MockInputApi()
1431 mock_output_api = MockOutputApi()
1432
1433 mock_input_api.files = [
1434 MockAffectedFile('components/blah.js', [" const foo = 'bar';"]),
1435 MockAffectedFile('ui/webui/resources/blah.js', [" let foo = 3;"]),
1436 ]
1437 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1438 mock_input_api, mock_output_api)
1439 self.assertEqual(2, len(warnings))
1440
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391441
rlanday6802cf632017-05-30 17:48:361442class RelativeIncludesTest(unittest.TestCase):
1443 def testThirdPartyNotWebKitIgnored(self):
1444 mock_input_api = MockInputApi()
1445 mock_input_api.files = [
1446 MockAffectedFile('third_party/test.cpp', '#include "../header.h"'),
1447 MockAffectedFile('third_party/test/test.cpp', '#include "../header.h"'),
1448 ]
1449
1450 mock_output_api = MockOutputApi()
1451
1452 errors = PRESUBMIT._CheckForRelativeIncludes(
1453 mock_input_api, mock_output_api)
1454 self.assertEqual(0, len(errors))
1455
1456 def testNonCppFileIgnored(self):
1457 mock_input_api = MockInputApi()
1458 mock_input_api.files = [
1459 MockAffectedFile('test.py', '#include "../header.h"'),
1460 ]
1461
1462 mock_output_api = MockOutputApi()
1463
1464 errors = PRESUBMIT._CheckForRelativeIncludes(
1465 mock_input_api, mock_output_api)
1466 self.assertEqual(0, len(errors))
1467
1468 def testInnocuousChangesAllowed(self):
1469 mock_input_api = MockInputApi()
1470 mock_input_api.files = [
1471 MockAffectedFile('test.cpp', '#include "header.h"'),
1472 MockAffectedFile('test2.cpp', '../'),
1473 ]
1474
1475 mock_output_api = MockOutputApi()
1476
1477 errors = PRESUBMIT._CheckForRelativeIncludes(
1478 mock_input_api, mock_output_api)
1479 self.assertEqual(0, len(errors))
1480
1481 def testRelativeIncludeNonWebKitProducesError(self):
1482 mock_input_api = MockInputApi()
1483 mock_input_api.files = [
1484 MockAffectedFile('test.cpp', ['#include "../header.h"']),
1485 ]
1486
1487 mock_output_api = MockOutputApi()
1488
1489 errors = PRESUBMIT._CheckForRelativeIncludes(
1490 mock_input_api, mock_output_api)
1491 self.assertEqual(1, len(errors))
1492
1493 def testRelativeIncludeWebKitProducesError(self):
1494 mock_input_api = MockInputApi()
1495 mock_input_api.files = [
1496 MockAffectedFile('third_party/WebKit/test.cpp',
1497 ['#include "../header.h']),
1498 ]
1499
1500 mock_output_api = MockOutputApi()
1501
1502 errors = PRESUBMIT._CheckForRelativeIncludes(
1503 mock_input_api, mock_output_api)
1504 self.assertEqual(1, len(errors))
dbeam1ec68ac2016-12-15 05:22:241505
Daniel Cheng13ca61a882017-08-25 15:11:251506
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191507class NewHeaderWithoutGnChangeTest(unittest.TestCase):
1508 def testAddHeaderWithoutGn(self):
1509 mock_input_api = MockInputApi()
1510 mock_input_api.files = [
1511 MockAffectedFile('base/stuff.h', ''),
1512 ]
1513 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1514 mock_input_api, MockOutputApi())
1515 self.assertEqual(1, len(warnings))
1516 self.assertTrue('base/stuff.h' in warnings[0].items)
1517
1518 def testModifyHeader(self):
1519 mock_input_api = MockInputApi()
1520 mock_input_api.files = [
1521 MockAffectedFile('base/stuff.h', '', action='M'),
1522 ]
1523 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1524 mock_input_api, MockOutputApi())
1525 self.assertEqual(0, len(warnings))
1526
1527 def testDeleteHeader(self):
1528 mock_input_api = MockInputApi()
1529 mock_input_api.files = [
1530 MockAffectedFile('base/stuff.h', '', action='D'),
1531 ]
1532 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1533 mock_input_api, MockOutputApi())
1534 self.assertEqual(0, len(warnings))
1535
1536 def testAddHeaderWithGn(self):
1537 mock_input_api = MockInputApi()
1538 mock_input_api.files = [
1539 MockAffectedFile('base/stuff.h', ''),
1540 MockAffectedFile('base/BUILD.gn', 'stuff.h'),
1541 ]
1542 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1543 mock_input_api, MockOutputApi())
1544 self.assertEqual(0, len(warnings))
1545
1546 def testAddHeaderWithGni(self):
1547 mock_input_api = MockInputApi()
1548 mock_input_api.files = [
1549 MockAffectedFile('base/stuff.h', ''),
1550 MockAffectedFile('base/files.gni', 'stuff.h'),
1551 ]
1552 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1553 mock_input_api, MockOutputApi())
1554 self.assertEqual(0, len(warnings))
1555
1556 def testAddHeaderWithOther(self):
1557 mock_input_api = MockInputApi()
1558 mock_input_api.files = [
1559 MockAffectedFile('base/stuff.h', ''),
1560 MockAffectedFile('base/stuff.cc', 'stuff.h'),
1561 ]
1562 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1563 mock_input_api, MockOutputApi())
1564 self.assertEqual(1, len(warnings))
1565
1566 def testAddHeaderWithWrongGn(self):
1567 mock_input_api = MockInputApi()
1568 mock_input_api.files = [
1569 MockAffectedFile('base/stuff.h', ''),
1570 MockAffectedFile('base/BUILD.gn', 'stuff_h'),
1571 ]
1572 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1573 mock_input_api, MockOutputApi())
1574 self.assertEqual(1, len(warnings))
1575
1576 def testAddHeadersWithGn(self):
1577 mock_input_api = MockInputApi()
1578 mock_input_api.files = [
1579 MockAffectedFile('base/stuff.h', ''),
1580 MockAffectedFile('base/another.h', ''),
1581 MockAffectedFile('base/BUILD.gn', 'another.h\nstuff.h'),
1582 ]
1583 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1584 mock_input_api, MockOutputApi())
1585 self.assertEqual(0, len(warnings))
1586
1587 def testAddHeadersWithWrongGn(self):
1588 mock_input_api = MockInputApi()
1589 mock_input_api.files = [
1590 MockAffectedFile('base/stuff.h', ''),
1591 MockAffectedFile('base/another.h', ''),
1592 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff.h'),
1593 ]
1594 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1595 mock_input_api, MockOutputApi())
1596 self.assertEqual(1, len(warnings))
1597 self.assertFalse('base/stuff.h' in warnings[0].items)
1598 self.assertTrue('base/another.h' in warnings[0].items)
1599
1600 def testAddHeadersWithWrongGn2(self):
1601 mock_input_api = MockInputApi()
1602 mock_input_api.files = [
1603 MockAffectedFile('base/stuff.h', ''),
1604 MockAffectedFile('base/another.h', ''),
1605 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff_h'),
1606 ]
1607 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1608 mock_input_api, MockOutputApi())
1609 self.assertEqual(1, len(warnings))
1610 self.assertTrue('base/stuff.h' in warnings[0].items)
1611 self.assertTrue('base/another.h' in warnings[0].items)
1612
1613
Daniel Cheng13ca61a882017-08-25 15:11:251614class MojoManifestOwnerTest(unittest.TestCase):
1615 def testMojoManifestChangeNeedsSecurityOwner(self):
1616 mock_input_api = MockInputApi()
1617 mock_input_api.files = [
1618 MockAffectedFile('services/goat/manifest.json',
1619 [
1620 '{',
1621 ' "name": "teleporter",',
1622 ' "display_name": "Goat Teleporter",'
1623 ' "interface_provider_specs": {',
1624 ' }',
1625 '}',
1626 ])
1627 ]
1628 mock_output_api = MockOutputApi()
1629 errors = PRESUBMIT._CheckIpcOwners(
1630 mock_input_api, mock_output_api)
1631 self.assertEqual(1, len(errors))
1632 self.assertEqual(
1633 'Found OWNERS files that need to be updated for IPC security review ' +
1634 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
1635
1636 # No warning if already covered by an OWNERS rule.
1637
1638 def testNonManifestChangesDoNotRequireSecurityOwner(self):
1639 mock_input_api = MockInputApi()
1640 mock_input_api.files = [
1641 MockAffectedFile('services/goat/species.json',
1642 [
1643 '[',
1644 ' "anglo-nubian",',
1645 ' "angora"',
1646 ']',
1647 ])
1648 ]
1649 mock_output_api = MockOutputApi()
1650 errors = PRESUBMIT._CheckIpcOwners(
1651 mock_input_api, mock_output_api)
1652 self.assertEqual([], errors)
1653
1654
Sylvain Defresnea8b73d252018-02-28 15:45:541655class BannedFunctionCheckTest(unittest.TestCase):
1656
1657 def testBannedIosObcjFunctions(self):
1658 input_api = MockInputApi()
1659 input_api.files = [
1660 MockFile('some/ios/file.mm',
1661 ['TEST(SomeClassTest, SomeInteraction) {',
1662 '}']),
1663 MockFile('some/mac/file.mm',
1664 ['TEST(SomeClassTest, SomeInteraction) {',
1665 '}']),
1666 MockFile('another/ios_file.mm',
1667 ['class SomeTest : public testing::Test {};']),
1668 ]
1669
1670 errors = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
1671 self.assertEqual(1, len(errors))
1672 self.assertTrue('some/ios/file.mm' in errors[0].message)
1673 self.assertTrue('another/ios_file.mm' in errors[0].message)
1674 self.assertTrue('some/mac/file.mm' not in errors[0].message)
1675
1676
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271677class NoProductionCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozekf01ed502018-03-16 19:38:241678 def testTruePositives(self):
1679 mock_input_api = MockInputApi()
1680 mock_input_api.files = [
1681 MockFile('some/path/foo.cc', ['foo_for_testing();']),
1682 MockFile('some/path/foo.mm', ['FooForTesting();']),
1683 MockFile('some/path/foo.cxx', ['FooForTests();']),
1684 MockFile('some/path/foo.cpp', ['foo_for_test();']),
1685 ]
1686
1687 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctions(
1688 mock_input_api, MockOutputApi())
1689 self.assertEqual(1, len(results))
1690 self.assertEqual(4, len(results[0].items))
1691 self.assertTrue('foo.cc' in results[0].items[0])
1692 self.assertTrue('foo.mm' in results[0].items[1])
1693 self.assertTrue('foo.cxx' in results[0].items[2])
1694 self.assertTrue('foo.cpp' in results[0].items[3])
1695
1696 def testFalsePositives(self):
1697 mock_input_api = MockInputApi()
1698 mock_input_api.files = [
1699 MockFile('some/path/foo.h', ['foo_for_testing();']),
1700 MockFile('some/path/foo.mm', ['FooForTesting() {']),
1701 MockFile('some/path/foo.cc', ['::FooForTests();']),
1702 MockFile('some/path/foo.cpp', ['// foo_for_test();']),
1703 ]
1704
1705 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctions(
1706 mock_input_api, MockOutputApi())
1707 self.assertEqual(0, len(results))
1708
1709
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271710class NoProductionJavaCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozek7dbc28c2018-03-27 08:35:231711 def testTruePositives(self):
1712 mock_input_api = MockInputApi()
1713 mock_input_api.files = [
1714 MockFile('dir/java/src/foo.java', ['FooForTesting();']),
1715 MockFile('dir/java/src/bar.java', ['FooForTests(x);']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391716 MockFile('dir/java/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:231717 MockFile('dir/java/src/mult.java', [
1718 'int x = SomethingLongHere()',
1719 ' * SomethingLongHereForTesting();'
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391720 ])
Vaclav Brozek7dbc28c2018-03-27 08:35:231721 ]
1722
1723 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctionsJava(
1724 mock_input_api, MockOutputApi())
1725 self.assertEqual(1, len(results))
1726 self.assertEqual(4, len(results[0].items))
1727 self.assertTrue('foo.java' in results[0].items[0])
1728 self.assertTrue('bar.java' in results[0].items[1])
1729 self.assertTrue('baz.java' in results[0].items[2])
1730 self.assertTrue('mult.java' in results[0].items[3])
1731
1732 def testFalsePositives(self):
1733 mock_input_api = MockInputApi()
1734 mock_input_api.files = [
1735 MockFile('dir/java/src/foo.xml', ['FooForTesting();']),
1736 MockFile('dir/java/src/foo.java', ['FooForTests() {']),
1737 MockFile('dir/java/src/bar.java', ['// FooForTest();']),
1738 MockFile('dir/java/src/bar2.java', ['x = 1; // FooForTest();']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391739 MockFile('dir/javatests/src/baz.java', ['FooForTest(', 'y', ');']),
1740 MockFile('dir/junit/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:231741 MockFile('dir/junit/src/javadoc.java', [
1742 '/** Use FooForTest(); to obtain foo in tests.'
1743 ' */'
1744 ]),
1745 MockFile('dir/junit/src/javadoc2.java', [
1746 '/** ',
1747 ' * Use FooForTest(); to obtain foo in tests.'
1748 ' */'
1749 ]),
1750 ]
1751
1752 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctionsJava(
1753 mock_input_api, MockOutputApi())
1754 self.assertEqual(0, len(results))
1755
1756
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271757class CheckUniquePtrTest(unittest.TestCase):
Vaclav Brozek851d9602018-04-04 16:13:051758 def testTruePositivesNullptr(self):
1759 mock_input_api = MockInputApi()
1760 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:161761 MockFile('dir/baz.cc', ['std::unique_ptr<T>()']),
1762 MockFile('dir/baz-p.cc', ['std::unique_ptr<T<P>>()']),
Vaclav Brozek851d9602018-04-04 16:13:051763 ]
1764
1765 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
1766 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:161767 self.assertTrue('nullptr' in results[0].message)
Vaclav Brozek851d9602018-04-04 16:13:051768 self.assertEqual(2, len(results[0].items))
1769 self.assertTrue('baz.cc' in results[0].items[0])
1770 self.assertTrue('baz-p.cc' in results[0].items[1])
1771
1772 def testTruePositivesConstructor(self):
Vaclav Brozek52e18bf2018-04-03 07:05:241773 mock_input_api = MockInputApi()
1774 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:161775 MockFile('dir/foo.cc', ['return std::unique_ptr<T>(foo);']),
1776 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T>(foo)']),
1777 MockFile('dir/mult.cc', [
Vaclav Brozek95face62018-04-04 14:15:111778 'return',
1779 ' std::unique_ptr<T>(barVeryVeryLongFooSoThatItWouldNotFitAbove);'
1780 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:161781 MockFile('dir/mult2.cc', [
Vaclav Brozek95face62018-04-04 14:15:111782 'barVeryVeryLongLongBaaaaaarSoThatTheLineLimitIsAlmostReached =',
1783 ' std::unique_ptr<T>(foo);'
1784 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:161785 MockFile('dir/mult3.cc', [
Vaclav Brozek95face62018-04-04 14:15:111786 'bar = std::unique_ptr<T>(',
1787 ' fooVeryVeryVeryLongStillGoingWellThisWillTakeAWhileFinallyThere);'
1788 ]),
Vaclav Brozekb7fadb692018-08-30 06:39:531789 MockFile('dir/multi_arg.cc', [
1790 'auto p = std::unique_ptr<std::pair<T, D>>(new std::pair(T, D));']),
Vaclav Brozek52e18bf2018-04-03 07:05:241791 ]
1792
1793 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
Vaclav Brozek851d9602018-04-04 16:13:051794 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:161795 self.assertTrue('std::make_unique' in results[0].message)
Vaclav Brozekb7fadb692018-08-30 06:39:531796 self.assertEqual(6, len(results[0].items))
Vaclav Brozek851d9602018-04-04 16:13:051797 self.assertTrue('foo.cc' in results[0].items[0])
1798 self.assertTrue('bar.mm' in results[0].items[1])
1799 self.assertTrue('mult.cc' in results[0].items[2])
1800 self.assertTrue('mult2.cc' in results[0].items[3])
1801 self.assertTrue('mult3.cc' in results[0].items[4])
Vaclav Brozekb7fadb692018-08-30 06:39:531802 self.assertTrue('multi_arg.cc' in results[0].items[5])
Vaclav Brozek52e18bf2018-04-03 07:05:241803
1804 def testFalsePositives(self):
1805 mock_input_api = MockInputApi()
1806 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:161807 MockFile('dir/foo.cc', ['return std::unique_ptr<T[]>(foo);']),
1808 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T[]>(foo)']),
1809 MockFile('dir/file.cc', ['std::unique_ptr<T> p = Foo();']),
1810 MockFile('dir/baz.cc', [
Vaclav Brozek52e18bf2018-04-03 07:05:241811 'std::unique_ptr<T> result = std::make_unique<T>();'
1812 ]),
Vaclav Brozeka54c528b2018-04-06 19:23:551813 MockFile('dir/baz2.cc', [
1814 'std::unique_ptr<T> result = std::make_unique<T>('
1815 ]),
1816 MockFile('dir/nested.cc', ['set<std::unique_ptr<T>>();']),
1817 MockFile('dir/nested2.cc', ['map<U, std::unique_ptr<T>>();']),
Vaclav Brozekb7fadb692018-08-30 06:39:531818
1819 # Two-argument invocation of std::unique_ptr is exempt because there is
1820 # no equivalent using std::make_unique.
1821 MockFile('dir/multi_arg.cc', [
1822 'auto p = std::unique_ptr<T, D>(new T(), D());']),
Vaclav Brozek52e18bf2018-04-03 07:05:241823 ]
1824
1825 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
1826 self.assertEqual(0, len(results))
1827
Danil Chapovalov3518f362018-08-11 16:13:431828class CheckNoDirectIncludesHeadersWhichRedefineStrCat(unittest.TestCase):
1829 def testBlocksDirectIncludes(self):
1830 mock_input_api = MockInputApi()
1831 mock_input_api.files = [
1832 MockFile('dir/foo_win.cc', ['#include "shlwapi.h"']),
1833 MockFile('dir/bar.h', ['#include <propvarutil.h>']),
1834 MockFile('dir/baz.h', ['#include <atlbase.h>']),
1835 MockFile('dir/jumbo.h', ['#include "sphelper.h"']),
1836 ]
1837 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
1838 self.assertEquals(1, len(results))
1839 self.assertEquals(4, len(results[0].items))
1840 self.assertTrue('StrCat' in results[0].message)
1841 self.assertTrue('foo_win.cc' in results[0].items[0])
1842 self.assertTrue('bar.h' in results[0].items[1])
1843 self.assertTrue('baz.h' in results[0].items[2])
1844 self.assertTrue('jumbo.h' in results[0].items[3])
1845
1846 def testAllowsToIncludeWrapper(self):
1847 mock_input_api = MockInputApi()
1848 mock_input_api.files = [
1849 MockFile('dir/baz_win.cc', ['#include "base/win/shlwapi.h"']),
1850 MockFile('dir/baz-win.h', ['#include "base/win/atl.h"']),
1851 ]
1852 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
1853 self.assertEquals(0, len(results))
1854
1855 def testAllowsToCreateWrapper(self):
1856 mock_input_api = MockInputApi()
1857 mock_input_api.files = [
1858 MockFile('base/win/shlwapi.h', [
1859 '#include <shlwapi.h>',
1860 '#include "base/win/windows_defines.inc"']),
1861 ]
1862 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
1863 self.assertEquals(0, len(results))
Vaclav Brozek52e18bf2018-04-03 07:05:241864
Mustafa Emre Acer29bf6ac92018-07-30 21:42:141865class TranslationScreenshotsTest(unittest.TestCase):
1866 # An empty grd file.
1867 OLD_GRD_CONTENTS = """<?xml version="1.0" encoding="UTF-8"?>
1868 <grit latest_public_release="1" current_release="1">
1869 <release seq="1">
1870 <messages></messages>
1871 </release>
1872 </grit>
1873 """.splitlines()
1874 # A grd file with a single message.
1875 NEW_GRD_CONTENTS1 = """<?xml version="1.0" encoding="UTF-8"?>
1876 <grit latest_public_release="1" current_release="1">
1877 <release seq="1">
1878 <messages>
1879 <message name="IDS_TEST1">
1880 Test string 1
1881 </message>
1882 </messages>
1883 </release>
1884 </grit>
1885 """.splitlines()
1886 # A grd file with two messages.
1887 NEW_GRD_CONTENTS2 = """<?xml version="1.0" encoding="UTF-8"?>
1888 <grit latest_public_release="1" current_release="1">
1889 <release seq="1">
1890 <messages>
1891 <message name="IDS_TEST1">
1892 Test string 1
1893 </message>
1894 <message name="IDS_TEST2">
1895 Test string 2
1896 </message>
1897 </messages>
1898 </release>
1899 </grit>
1900 """.splitlines()
1901
Mustafa Emre Acerc8a012d2018-07-31 00:00:391902 DO_NOT_UPLOAD_PNG_MESSAGE = ('Do not include actual screenshots in the '
1903 'changelist. Run '
1904 'tools/translate/upload_screenshots.py to '
1905 'upload them instead:')
1906 GENERATE_SIGNATURES_MESSAGE = ('You are adding or modifying UI strings.\n'
1907 'To ensure the best translations, take '
1908 'screenshots of the relevant UI '
1909 '(https://g.co/chrome/translation) and add '
1910 'these files to your changelist:')
1911 REMOVE_SIGNATURES_MESSAGE = ('You removed strings associated with these '
1912 'files. Remove:')
Mustafa Emre Acer29bf6ac92018-07-30 21:42:141913
1914 def makeInputApi(self, files):
1915 input_api = MockInputApi()
1916 input_api.files = files
1917 return input_api
1918
1919 def testNoScreenshots(self):
1920 # CL modified and added messages, but didn't add any screenshots.
1921 input_api = self.makeInputApi([
1922 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
1923 self.OLD_GRD_CONTENTS, action='M')])
1924 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1925 MockOutputApi())
1926 self.assertEqual(1, len(warnings))
1927 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
1928 self.assertEqual(
1929 ['test_grd/IDS_TEST1.png.sha1', 'test_grd/IDS_TEST2.png.sha1'],
1930 warnings[0].items)
1931
1932 input_api = self.makeInputApi([
1933 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
1934 self.NEW_GRD_CONTENTS1, action='M')])
1935 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1936 MockOutputApi())
1937 self.assertEqual(1, len(warnings))
1938 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
1939 self.assertEqual(['test_grd/IDS_TEST2.png.sha1'], warnings[0].items)
1940
1941
1942 def testUnnecessaryScreenshots(self):
1943 # CL added a single message and added the png file, but not the sha1 file.
1944 input_api = self.makeInputApi([
1945 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS1,
1946 self.OLD_GRD_CONTENTS, action='M'),
1947 MockAffectedFile('test_grd/IDS_TEST1.png', 'binary', action='A')])
1948 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1949 MockOutputApi())
1950 self.assertEqual(2, len(warnings))
1951 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
1952 self.assertEqual(['test_grd/IDS_TEST1.png'], warnings[0].items)
1953 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
1954 self.assertEqual(['test_grd/IDS_TEST1.png.sha1'], warnings[1].items)
1955
1956 # CL added two messages, one has a png. Expect two messages:
1957 # - One for the unnecessary png.
1958 # - Another one for missing .sha1 files.
1959 input_api = self.makeInputApi([
1960 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
1961 self.OLD_GRD_CONTENTS, action='M'),
1962 MockAffectedFile('test_grd/IDS_TEST1.png', 'binary', action='A')])
1963 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1964 MockOutputApi())
1965 self.assertEqual(2, len(warnings))
1966 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
1967 self.assertEqual(['test_grd/IDS_TEST1.png'], warnings[0].items)
1968 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
1969 self.assertEqual(['test_grd/IDS_TEST1.png.sha1',
1970 'test_grd/IDS_TEST2.png.sha1'], warnings[1].items)
1971
1972 def testScreenshotsWithSha1(self):
1973 # CL added two messages and their corresponding .sha1 files. No warnings.
1974 input_api = self.makeInputApi([
1975 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
1976 self.OLD_GRD_CONTENTS, action='M'),
1977 MockFile('test_grd/IDS_TEST1.png.sha1', 'binary', action='A'),
1978 MockFile('test_grd/IDS_TEST2.png.sha1', 'binary', action='A')])
1979 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1980 MockOutputApi())
1981 self.assertEqual([], warnings)
1982
1983 def testScreenshotsRemovedWithSha1(self):
1984 # Swap old contents with new contents, remove IDS_TEST1 and IDS_TEST2. The
1985 # sha1 files associated with the messages should also be removed by the CL.
1986 input_api = self.makeInputApi([
1987 MockAffectedFile('test.grd', self.OLD_GRD_CONTENTS,
1988 self.NEW_GRD_CONTENTS2, action='M'),
1989 MockFile('test_grd/IDS_TEST1.png.sha1', 'binary', ""),
1990 MockFile('test_grd/IDS_TEST2.png.sha1', 'binary', "")])
1991 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1992 MockOutputApi())
1993 self.assertEqual(1, len(warnings))
1994 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
1995 self.assertEqual(['test_grd/IDS_TEST1.png.sha1',
1996 'test_grd/IDS_TEST2.png.sha1'], warnings[0].items)
1997
1998 # Same as above, but this time one of the .sha1 files is removed.
1999 input_api = self.makeInputApi([
2000 MockAffectedFile('test.grd', self.OLD_GRD_CONTENTS,
2001 self.NEW_GRD_CONTENTS2, action='M'),
2002 MockFile('test_grd/IDS_TEST1.png.sha1', 'binary', ''),
2003 MockAffectedFile('test_grd/IDS_TEST2.png.sha1',
2004 '', 'old_contents', action='D')])
2005 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2006 MockOutputApi())
2007 self.assertEqual(1, len(warnings))
2008 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
2009 self.assertEqual(['test_grd/IDS_TEST1.png.sha1'], warnings[0].items)
2010
2011 # Remove both sha1 files. No presubmit warnings.
2012 input_api = self.makeInputApi([
2013 MockAffectedFile('test.grd', self.OLD_GRD_CONTENTS,
2014 self.NEW_GRD_CONTENTS2, action='M'),
2015 MockFile('test_grd/IDS_TEST1.png.sha1', 'binary', action='D'),
2016 MockFile('test_grd/IDS_TEST2.png.sha1', 'binary', action='D')])
2017 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2018 MockOutputApi())
2019 self.assertEqual([], warnings)
2020
2021
Dominic Battre033531052018-09-24 15:45:342022class DISABLETypoInTest(unittest.TestCase):
2023
2024 def testPositive(self):
2025 # Verify the typo "DISABLE_" instead of "DISABLED_" in various contexts
2026 # where the desire is to disable a test.
2027 tests = [
2028 # Disabled on one platform:
2029 '#if defined(OS_WIN)\n'
2030 '#define MAYBE_FoobarTest DISABLE_FoobarTest\n'
2031 '#else\n'
2032 '#define MAYBE_FoobarTest FoobarTest\n'
2033 '#endif\n',
2034 # Disabled on one platform spread cross lines:
2035 '#if defined(OS_WIN)\n'
2036 '#define MAYBE_FoobarTest \\\n'
2037 ' DISABLE_FoobarTest\n'
2038 '#else\n'
2039 '#define MAYBE_FoobarTest FoobarTest\n'
2040 '#endif\n',
2041 # Disabled on all platforms:
2042 ' TEST_F(FoobarTest, DISABLE_Foo)\n{\n}',
2043 # Disabled on all platforms but multiple lines
2044 ' TEST_F(FoobarTest,\n DISABLE_foo){\n}\n',
2045 ]
2046
2047 for test in tests:
2048 mock_input_api = MockInputApi()
2049 mock_input_api.files = [
2050 MockFile('some/path/foo_unittest.cc', test.splitlines()),
2051 ]
2052
2053 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
2054 MockOutputApi())
2055 self.assertEqual(
2056 1,
2057 len(results),
2058 msg=('expected len(results) == 1 but got %d in test: %s' %
2059 (len(results), test)))
2060 self.assertTrue(
2061 'foo_unittest.cc' in results[0].message,
2062 msg=('expected foo_unittest.cc in message but got %s in test %s' %
2063 (results[0].message, test)))
2064
2065 def testIngoreNotTestFiles(self):
2066 mock_input_api = MockInputApi()
2067 mock_input_api.files = [
2068 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, DISABLE_Foo)'),
2069 ]
2070
2071 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
2072 MockOutputApi())
2073 self.assertEqual(0, len(results))
2074
Katie Df13948e2018-09-25 07:33:442075 def testIngoreDeletedFiles(self):
2076 mock_input_api = MockInputApi()
2077 mock_input_api.files = [
2078 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, Foo)', action='D'),
2079 ]
2080
2081 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
2082 MockOutputApi())
2083 self.assertEqual(0, len(results))
Dominic Battre033531052018-09-24 15:45:342084
[email protected]2299dcf2012-11-15 19:56:242085if __name__ == '__main__':
2086 unittest.main()