blob: 14921eadd270ba3d054d7511258f63fb6df62192 [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
Saagar Sanghavifceeaae2020-08-12 16:40:3611
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3912from PRESUBMIT_test_mocks import MockFile, MockAffectedFile
gayane3dff8c22014-12-04 17:09:5113from PRESUBMIT_test_mocks import MockInputApi, MockOutputApi
[email protected]2299dcf2012-11-15 19:56:2414
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3915
[email protected]99171a92014-06-03 08:44:4716_TEST_DATA_DIR = 'base/test/data/presubmit'
17
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3918
[email protected]b00342e7f2013-03-26 16:21:5419class VersionControlConflictsTest(unittest.TestCase):
[email protected]70ca77752012-11-20 03:45:0320 def testTypicalConflict(self):
21 lines = ['<<<<<<< HEAD',
22 ' base::ScopedTempDir temp_dir_;',
23 '=======',
24 ' ScopedTempDir temp_dir_;',
25 '>>>>>>> master']
26 errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
27 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
28 self.assertEqual(3, len(errors))
29 self.assertTrue('1' in errors[0])
30 self.assertTrue('3' in errors[1])
31 self.assertTrue('5' in errors[2])
32
dbeam95c35a2f2015-06-02 01:40:2333 def testIgnoresReadmes(self):
34 lines = ['A First Level Header',
35 '====================',
36 '',
37 'A Second Level Header',
38 '---------------------']
39 errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
40 MockInputApi(), MockFile('some/polymer/README.md', lines))
41 self.assertEqual(0, len(errors))
42
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3943
[email protected]b8079ae4a2012-12-05 19:56:4944class BadExtensionsTest(unittest.TestCase):
45 def testBadRejFile(self):
46 mock_input_api = MockInputApi()
47 mock_input_api.files = [
48 MockFile('some/path/foo.cc', ''),
49 MockFile('some/path/foo.cc.rej', ''),
50 MockFile('some/path2/bar.h.rej', ''),
51 ]
52
Saagar Sanghavifceeaae2020-08-12 16:40:3653 results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
[email protected]b8079ae4a2012-12-05 19:56:4954 self.assertEqual(1, len(results))
55 self.assertEqual(2, len(results[0].items))
56 self.assertTrue('foo.cc.rej' in results[0].items[0])
57 self.assertTrue('bar.h.rej' in results[0].items[1])
58
59 def testBadOrigFile(self):
60 mock_input_api = MockInputApi()
61 mock_input_api.files = [
62 MockFile('other/path/qux.h.orig', ''),
63 MockFile('other/path/qux.h', ''),
64 MockFile('other/path/qux.cc', ''),
65 ]
66
Saagar Sanghavifceeaae2020-08-12 16:40:3667 results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
[email protected]b8079ae4a2012-12-05 19:56:4968 self.assertEqual(1, len(results))
69 self.assertEqual(1, len(results[0].items))
70 self.assertTrue('qux.h.orig' in results[0].items[0])
71
72 def testGoodFiles(self):
73 mock_input_api = MockInputApi()
74 mock_input_api.files = [
75 MockFile('other/path/qux.h', ''),
76 MockFile('other/path/qux.cc', ''),
77 ]
Saagar Sanghavifceeaae2020-08-12 16:40:3678 results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
[email protected]b8079ae4a2012-12-05 19:56:4979 self.assertEqual(0, len(results))
80
81
glidere61efad2015-02-18 17:39:4382class CheckSingletonInHeadersTest(unittest.TestCase):
83 def testSingletonInArbitraryHeader(self):
84 diff_singleton_h = ['base::subtle::AtomicWord '
olli.raula36aa8be2015-09-10 11:14:2285 'base::Singleton<Type, Traits, DifferentiatingType>::']
86 diff_foo_h = ['// base::Singleton<Foo> in comment.',
87 'friend class base::Singleton<Foo>']
oysteinec430ad42015-10-22 20:55:2488 diff_foo2_h = [' //Foo* bar = base::Singleton<Foo>::get();']
olli.raula36aa8be2015-09-10 11:14:2289 diff_bad_h = ['Foo* foo = base::Singleton<Foo>::get();']
glidere61efad2015-02-18 17:39:4390 mock_input_api = MockInputApi()
91 mock_input_api.files = [MockAffectedFile('base/memory/singleton.h',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3992 diff_singleton_h),
glidere61efad2015-02-18 17:39:4393 MockAffectedFile('foo.h', diff_foo_h),
oysteinec430ad42015-10-22 20:55:2494 MockAffectedFile('foo2.h', diff_foo2_h),
glidere61efad2015-02-18 17:39:4395 MockAffectedFile('bad.h', diff_bad_h)]
Saagar Sanghavifceeaae2020-08-12 16:40:3696 warnings = PRESUBMIT.CheckSingletonInHeaders(mock_input_api,
glidere61efad2015-02-18 17:39:4397 MockOutputApi())
98 self.assertEqual(1, len(warnings))
Sylvain Defresnea8b73d252018-02-28 15:45:5499 self.assertEqual(1, len(warnings[0].items))
glidere61efad2015-02-18 17:39:43100 self.assertEqual('error', warnings[0].type)
olli.raula36aa8be2015-09-10 11:14:22101 self.assertTrue('Found base::Singleton<T>' in warnings[0].message)
glidere61efad2015-02-18 17:39:43102
103 def testSingletonInCC(self):
olli.raula36aa8be2015-09-10 11:14:22104 diff_cc = ['Foo* foo = base::Singleton<Foo>::get();']
glidere61efad2015-02-18 17:39:43105 mock_input_api = MockInputApi()
106 mock_input_api.files = [MockAffectedFile('some/path/foo.cc', diff_cc)]
Saagar Sanghavifceeaae2020-08-12 16:40:36107 warnings = PRESUBMIT.CheckSingletonInHeaders(mock_input_api,
glidere61efad2015-02-18 17:39:43108 MockOutputApi())
109 self.assertEqual(0, len(warnings))
110
111
[email protected]b00342e7f2013-03-26 16:21:54112class InvalidOSMacroNamesTest(unittest.TestCase):
113 def testInvalidOSMacroNames(self):
114 lines = ['#if defined(OS_WINDOWS)',
115 ' #elif defined(OS_WINDOW)',
Avi Drissman34594e902020-07-25 05:35:44116 ' # if defined(OS_MAC) || defined(OS_CHROME)',
Avi Drissman32967a9e2020-07-30 04:10:32117 '# else // defined(OS_MACOSX)',
[email protected]b00342e7f2013-03-26 16:21:54118 '#endif // defined(OS_MACOS)']
119 errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
120 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
121 self.assertEqual(len(lines), len(errors))
122 self.assertTrue(':1 OS_WINDOWS' in errors[0])
123 self.assertTrue('(did you mean OS_WIN?)' in errors[0])
124
125 def testValidOSMacroNames(self):
126 lines = ['#if defined(%s)' % m for m in PRESUBMIT._VALID_OS_MACROS]
127 errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
128 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
129 self.assertEqual(0, len(errors))
130
131
lliabraa35bab3932014-10-01 12:16:44132class InvalidIfDefinedMacroNamesTest(unittest.TestCase):
133 def testInvalidIfDefinedMacroNames(self):
134 lines = ['#if defined(TARGET_IPHONE_SIMULATOR)',
135 '#if !defined(TARGET_IPHONE_SIMULATOR)',
136 '#elif defined(TARGET_IPHONE_SIMULATOR)',
137 '#ifdef TARGET_IPHONE_SIMULATOR',
138 ' # ifdef TARGET_IPHONE_SIMULATOR',
139 '# if defined(VALID) || defined(TARGET_IPHONE_SIMULATOR)',
140 '# else // defined(TARGET_IPHONE_SIMULATOR)',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39141 '#endif // defined(TARGET_IPHONE_SIMULATOR)']
lliabraa35bab3932014-10-01 12:16:44142 errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
143 MockInputApi(), MockFile('some/path/source.mm', lines))
144 self.assertEqual(len(lines), len(errors))
145
146 def testValidIfDefinedMacroNames(self):
147 lines = ['#if defined(FOO)',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39148 '#ifdef BAR']
lliabraa35bab3932014-10-01 12:16:44149 errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
150 MockInputApi(), MockFile('some/path/source.cc', lines))
151 self.assertEqual(0, len(errors))
152
153
Samuel Huang0db2ea22019-12-09 16:42:47154class CheckAddedDepsHaveTestApprovalsTest(unittest.TestCase):
Daniel Cheng4dcdb6b2017-04-13 08:30:17155
156 def calculate(self, old_include_rules, old_specific_include_rules,
157 new_include_rules, new_specific_include_rules):
158 return PRESUBMIT._CalculateAddedDeps(
159 os.path, 'include_rules = %r\nspecific_include_rules = %r' % (
160 old_include_rules, old_specific_include_rules),
161 'include_rules = %r\nspecific_include_rules = %r' % (
162 new_include_rules, new_specific_include_rules))
163
164 def testCalculateAddedDeps(self):
165 old_include_rules = [
166 '+base',
167 '-chrome',
168 '+content',
169 '-grit',
170 '-grit/",',
171 '+jni/fooblat.h',
172 '!sandbox',
[email protected]f32e2d1e2013-07-26 21:39:08173 ]
Daniel Cheng4dcdb6b2017-04-13 08:30:17174 old_specific_include_rules = {
175 'compositor\.*': {
176 '+cc',
177 },
178 }
179
180 new_include_rules = [
181 '-ash',
182 '+base',
183 '+chrome',
184 '+components',
185 '+content',
186 '+grit',
187 '+grit/generated_resources.h",',
188 '+grit/",',
189 '+jni/fooblat.h',
190 '+policy',
manzagop85e629e2017-05-09 22:11:48191 '+' + os.path.join('third_party', 'WebKit'),
Daniel Cheng4dcdb6b2017-04-13 08:30:17192 ]
193 new_specific_include_rules = {
194 'compositor\.*': {
195 '+cc',
196 },
197 'widget\.*': {
198 '+gpu',
199 },
200 }
201
[email protected]f32e2d1e2013-07-26 21:39:08202 expected = set([
manzagop85e629e2017-05-09 22:11:48203 os.path.join('chrome', 'DEPS'),
204 os.path.join('gpu', 'DEPS'),
205 os.path.join('components', 'DEPS'),
206 os.path.join('policy', 'DEPS'),
207 os.path.join('third_party', 'WebKit', 'DEPS'),
[email protected]f32e2d1e2013-07-26 21:39:08208 ])
Daniel Cheng4dcdb6b2017-04-13 08:30:17209 self.assertEqual(
210 expected,
211 self.calculate(old_include_rules, old_specific_include_rules,
212 new_include_rules, new_specific_include_rules))
213
214 def testCalculateAddedDepsIgnoresPermutations(self):
215 old_include_rules = [
216 '+base',
217 '+chrome',
218 ]
219 new_include_rules = [
220 '+chrome',
221 '+base',
222 ]
223 self.assertEqual(set(),
224 self.calculate(old_include_rules, {}, new_include_rules,
225 {}))
[email protected]f32e2d1e2013-07-26 21:39:08226
227
[email protected]99171a92014-06-03 08:44:47228class JSONParsingTest(unittest.TestCase):
229 def testSuccess(self):
230 input_api = MockInputApi()
231 filename = 'valid_json.json'
232 contents = ['// This is a comment.',
233 '{',
234 ' "key1": ["value1", "value2"],',
235 ' "key2": 3 // This is an inline comment.',
236 '}'
237 ]
238 input_api.files = [MockFile(filename, contents)]
239 self.assertEqual(None,
240 PRESUBMIT._GetJSONParseError(input_api, filename))
241
242 def testFailure(self):
243 input_api = MockInputApi()
244 test_data = [
245 ('invalid_json_1.json',
246 ['{ x }'],
[email protected]a3343272014-06-17 11:41:53247 'Expecting property name:'),
[email protected]99171a92014-06-03 08:44:47248 ('invalid_json_2.json',
249 ['// Hello world!',
250 '{ "hello": "world }'],
[email protected]a3343272014-06-17 11:41:53251 'Unterminated string starting at:'),
[email protected]99171a92014-06-03 08:44:47252 ('invalid_json_3.json',
253 ['{ "a": "b", "c": "d", }'],
[email protected]a3343272014-06-17 11:41:53254 'Expecting property name:'),
[email protected]99171a92014-06-03 08:44:47255 ('invalid_json_4.json',
256 ['{ "a": "b" "c": "d" }'],
[email protected]a3343272014-06-17 11:41:53257 'Expecting , delimiter:'),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39258 ]
[email protected]99171a92014-06-03 08:44:47259
260 input_api.files = [MockFile(filename, contents)
261 for (filename, contents, _) in test_data]
262
263 for (filename, _, expected_error) in test_data:
264 actual_error = PRESUBMIT._GetJSONParseError(input_api, filename)
[email protected]a3343272014-06-17 11:41:53265 self.assertTrue(expected_error in str(actual_error),
266 "'%s' not found in '%s'" % (expected_error, actual_error))
[email protected]99171a92014-06-03 08:44:47267
268 def testNoEatComments(self):
269 input_api = MockInputApi()
270 file_with_comments = 'file_with_comments.json'
271 contents_with_comments = ['// This is a comment.',
272 '{',
273 ' "key1": ["value1", "value2"],',
274 ' "key2": 3 // This is an inline comment.',
275 '}'
276 ]
277 file_without_comments = 'file_without_comments.json'
278 contents_without_comments = ['{',
279 ' "key1": ["value1", "value2"],',
280 ' "key2": 3',
281 '}'
282 ]
283 input_api.files = [MockFile(file_with_comments, contents_with_comments),
284 MockFile(file_without_comments,
285 contents_without_comments)]
286
287 self.assertEqual('No JSON object could be decoded',
288 str(PRESUBMIT._GetJSONParseError(input_api,
289 file_with_comments,
290 eat_comments=False)))
291 self.assertEqual(None,
292 PRESUBMIT._GetJSONParseError(input_api,
293 file_without_comments,
294 eat_comments=False))
295
296
297class IDLParsingTest(unittest.TestCase):
298 def testSuccess(self):
299 input_api = MockInputApi()
300 filename = 'valid_idl_basics.idl'
301 contents = ['// Tests a valid IDL file.',
302 'namespace idl_basics {',
303 ' enum EnumType {',
304 ' name1,',
305 ' name2',
306 ' };',
307 '',
308 ' dictionary MyType1 {',
309 ' DOMString a;',
310 ' };',
311 '',
312 ' callback Callback1 = void();',
313 ' callback Callback2 = void(long x);',
314 ' callback Callback3 = void(MyType1 arg);',
315 ' callback Callback4 = void(EnumType type);',
316 '',
317 ' interface Functions {',
318 ' static void function1();',
319 ' static void function2(long x);',
320 ' static void function3(MyType1 arg);',
321 ' static void function4(Callback1 cb);',
322 ' static void function5(Callback2 cb);',
323 ' static void function6(Callback3 cb);',
324 ' static void function7(Callback4 cb);',
325 ' };',
326 '',
327 ' interface Events {',
328 ' static void onFoo1();',
329 ' static void onFoo2(long x);',
330 ' static void onFoo2(MyType1 arg);',
331 ' static void onFoo3(EnumType type);',
332 ' };',
333 '};'
334 ]
335 input_api.files = [MockFile(filename, contents)]
336 self.assertEqual(None,
337 PRESUBMIT._GetIDLParseError(input_api, filename))
338
339 def testFailure(self):
340 input_api = MockInputApi()
341 test_data = [
342 ('invalid_idl_1.idl',
343 ['//',
344 'namespace test {',
345 ' dictionary {',
346 ' DOMString s;',
347 ' };',
348 '};'],
349 'Unexpected "{" after keyword "dictionary".\n'),
350 # TODO(yoz): Disabled because it causes the IDL parser to hang.
351 # See crbug.com/363830.
352 # ('invalid_idl_2.idl',
353 # (['namespace test {',
354 # ' dictionary MissingSemicolon {',
355 # ' DOMString a',
356 # ' DOMString b;',
357 # ' };',
358 # '};'],
359 # 'Unexpected symbol DOMString after symbol a.'),
360 ('invalid_idl_3.idl',
361 ['//',
362 'namespace test {',
363 ' enum MissingComma {',
364 ' name1',
365 ' name2',
366 ' };',
367 '};'],
368 'Unexpected symbol name2 after symbol name1.'),
369 ('invalid_idl_4.idl',
370 ['//',
371 'namespace test {',
372 ' enum TrailingComma {',
373 ' name1,',
374 ' name2,',
375 ' };',
376 '};'],
377 'Trailing comma in block.'),
378 ('invalid_idl_5.idl',
379 ['//',
380 'namespace test {',
381 ' callback Callback1 = void(;',
382 '};'],
383 'Unexpected ";" after "(".'),
384 ('invalid_idl_6.idl',
385 ['//',
386 'namespace test {',
387 ' callback Callback1 = void(long );',
388 '};'],
389 'Unexpected ")" after symbol long.'),
390 ('invalid_idl_7.idl',
391 ['//',
392 'namespace test {',
393 ' interace Events {',
394 ' static void onFoo1();',
395 ' };',
396 '};'],
397 'Unexpected symbol Events after symbol interace.'),
398 ('invalid_idl_8.idl',
399 ['//',
400 'namespace test {',
401 ' interface NotEvent {',
402 ' static void onFoo1();',
403 ' };',
404 '};'],
405 'Did not process Interface Interface(NotEvent)'),
406 ('invalid_idl_9.idl',
407 ['//',
408 'namespace test {',
409 ' interface {',
410 ' static void function1();',
411 ' };',
412 '};'],
413 'Interface missing name.'),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39414 ]
[email protected]99171a92014-06-03 08:44:47415
416 input_api.files = [MockFile(filename, contents)
417 for (filename, contents, _) in test_data]
418
419 for (filename, _, expected_error) in test_data:
420 actual_error = PRESUBMIT._GetIDLParseError(input_api, filename)
421 self.assertTrue(expected_error in str(actual_error),
422 "'%s' not found in '%s'" % (expected_error, actual_error))
423
424
[email protected]0bb112362014-07-26 04:38:32425class TryServerMasterTest(unittest.TestCase):
426 def testTryServerMasters(self):
427 bots = {
tandriie5587792016-07-14 00:34:50428 'master.tryserver.chromium.android': [
jbudorick3ae7a772016-05-20 02:36:04429 'android_archive_rel_ng',
430 'android_arm64_dbg_recipe',
431 'android_blink_rel',
jbudorick3ae7a772016-05-20 02:36:04432 'android_clang_dbg_recipe',
433 'android_compile_dbg',
jbudorick3ae7a772016-05-20 02:36:04434 'android_compile_x64_dbg',
435 'android_compile_x86_dbg',
436 'android_coverage',
437 'android_cronet_tester'
438 'android_swarming_rel',
439 'cast_shell_android',
440 'linux_android_dbg_ng',
441 'linux_android_rel_ng',
442 ],
tandriie5587792016-07-14 00:34:50443 'master.tryserver.chromium.mac': [
[email protected]0bb112362014-07-26 04:38:32444 'ios_dbg_simulator',
445 'ios_rel_device',
446 'ios_rel_device_ninja',
447 'mac_asan',
448 'mac_asan_64',
449 'mac_chromium_compile_dbg',
450 'mac_chromium_compile_rel',
451 'mac_chromium_dbg',
452 'mac_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32453 'mac_nacl_sdk',
454 'mac_nacl_sdk_build',
455 'mac_rel_naclmore',
[email protected]0bb112362014-07-26 04:38:32456 'mac_x64_rel',
457 'mac_xcodebuild',
458 ],
tandriie5587792016-07-14 00:34:50459 'master.tryserver.chromium.linux': [
[email protected]0bb112362014-07-26 04:38:32460 'chromium_presubmit',
461 'linux_arm_cross_compile',
462 'linux_arm_tester',
[email protected]0bb112362014-07-26 04:38:32463 'linux_chromeos_asan',
464 'linux_chromeos_browser_asan',
465 'linux_chromeos_valgrind',
[email protected]0bb112362014-07-26 04:38:32466 'linux_chromium_chromeos_dbg',
467 'linux_chromium_chromeos_rel',
[email protected]0bb112362014-07-26 04:38:32468 'linux_chromium_compile_dbg',
469 'linux_chromium_compile_rel',
470 'linux_chromium_dbg',
471 'linux_chromium_gn_dbg',
472 'linux_chromium_gn_rel',
473 'linux_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32474 'linux_chromium_trusty32_dbg',
475 'linux_chromium_trusty32_rel',
476 'linux_chromium_trusty_dbg',
477 'linux_chromium_trusty_rel',
478 'linux_clang_tsan',
479 'linux_ecs_ozone',
480 'linux_layout',
481 'linux_layout_asan',
482 'linux_layout_rel',
483 'linux_layout_rel_32',
484 'linux_nacl_sdk',
485 'linux_nacl_sdk_bionic',
486 'linux_nacl_sdk_bionic_build',
487 'linux_nacl_sdk_build',
488 'linux_redux',
489 'linux_rel_naclmore',
490 'linux_rel_precise32',
491 'linux_valgrind',
492 'tools_build_presubmit',
493 ],
tandriie5587792016-07-14 00:34:50494 'master.tryserver.chromium.win': [
[email protected]0bb112362014-07-26 04:38:32495 'win8_aura',
496 'win8_chromium_dbg',
497 'win8_chromium_rel',
498 'win_chromium_compile_dbg',
499 'win_chromium_compile_rel',
500 'win_chromium_dbg',
501 'win_chromium_rel',
502 'win_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32503 'win_chromium_x64_dbg',
504 'win_chromium_x64_rel',
[email protected]0bb112362014-07-26 04:38:32505 'win_nacl_sdk',
506 'win_nacl_sdk_build',
507 'win_rel_naclmore',
508 ],
509 }
510 for master, bots in bots.iteritems():
511 for bot in bots:
512 self.assertEqual(master, PRESUBMIT.GetTryServerMasterForBot(bot),
513 'bot=%s: expected %s, computed %s' % (
514 bot, master, PRESUBMIT.GetTryServerMasterForBot(bot)))
515
516
davileene0426252015-03-02 21:10:41517class UserMetricsActionTest(unittest.TestCase):
518 def testUserMetricsActionInActions(self):
519 input_api = MockInputApi()
520 file_with_user_action = 'file_with_user_action.cc'
521 contents_with_user_action = [
522 'base::UserMetricsAction("AboutChrome")'
523 ]
524
525 input_api.files = [MockFile(file_with_user_action,
526 contents_with_user_action)]
527
528 self.assertEqual(
Saagar Sanghavifceeaae2020-08-12 16:40:36529 [], PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi()))
davileene0426252015-03-02 21:10:41530
davileene0426252015-03-02 21:10:41531 def testUserMetricsActionNotAddedToActions(self):
532 input_api = MockInputApi()
533 file_with_user_action = 'file_with_user_action.cc'
534 contents_with_user_action = [
535 'base::UserMetricsAction("NotInActionsXml")'
536 ]
537
538 input_api.files = [MockFile(file_with_user_action,
539 contents_with_user_action)]
540
Saagar Sanghavifceeaae2020-08-12 16:40:36541 output = PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi())
davileene0426252015-03-02 21:10:41542 self.assertEqual(
543 ('File %s line %d: %s is missing in '
544 'tools/metrics/actions/actions.xml. Please run '
545 'tools/metrics/actions/extract_actions.py to update.'
546 % (file_with_user_action, 1, 'NotInActionsXml')),
547 output[0].message)
548
549
agrievef32bcc72016-04-04 14:57:40550class PydepsNeedsUpdatingTest(unittest.TestCase):
551
552 class MockSubprocess(object):
553 CalledProcessError = subprocess.CalledProcessError
554
Mohamed Heikal7cd4d8312020-06-16 16:49:40555 def _MockParseGclientArgs(self, is_android=True):
556 return lambda: {'checkout_android': 'true' if is_android else 'false' }
557
agrievef32bcc72016-04-04 14:57:40558 def setUp(self):
Mohamed Heikal7cd4d8312020-06-16 16:49:40559 mock_all_pydeps = ['A.pydeps', 'B.pydeps', 'D.pydeps']
agrievef32bcc72016-04-04 14:57:40560 self.old_ALL_PYDEPS_FILES = PRESUBMIT._ALL_PYDEPS_FILES
561 PRESUBMIT._ALL_PYDEPS_FILES = mock_all_pydeps
Mohamed Heikal7cd4d8312020-06-16 16:49:40562 mock_android_pydeps = ['D.pydeps']
563 self.old_ANDROID_SPECIFIC_PYDEPS_FILES = (
564 PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES)
565 PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES = mock_android_pydeps
566 self.old_ParseGclientArgs = PRESUBMIT._ParseGclientArgs
567 PRESUBMIT._ParseGclientArgs = self._MockParseGclientArgs()
agrievef32bcc72016-04-04 14:57:40568 self.mock_input_api = MockInputApi()
569 self.mock_output_api = MockOutputApi()
570 self.mock_input_api.subprocess = PydepsNeedsUpdatingTest.MockSubprocess()
571 self.checker = PRESUBMIT.PydepsChecker(self.mock_input_api, mock_all_pydeps)
572 self.checker._file_cache = {
Andrew Grieve5bb4cf702020-10-22 20:21:39573 'A.pydeps': '# Generated by:\n# CMD --output A.pydeps A\nA.py\nC.py\n',
574 'B.pydeps': '# Generated by:\n# CMD --output B.pydeps B\nB.py\nC.py\n',
575 'D.pydeps': '# Generated by:\n# CMD --output D.pydeps D\nD.py\n',
agrievef32bcc72016-04-04 14:57:40576 }
577
578 def tearDown(self):
579 PRESUBMIT._ALL_PYDEPS_FILES = self.old_ALL_PYDEPS_FILES
Mohamed Heikal7cd4d8312020-06-16 16:49:40580 PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES = (
581 self.old_ANDROID_SPECIFIC_PYDEPS_FILES)
582 PRESUBMIT._ParseGclientArgs = self.old_ParseGclientArgs
agrievef32bcc72016-04-04 14:57:40583
584 def _RunCheck(self):
Saagar Sanghavifceeaae2020-08-12 16:40:36585 return PRESUBMIT.CheckPydepsNeedsUpdating(self.mock_input_api,
agrievef32bcc72016-04-04 14:57:40586 self.mock_output_api,
587 checker_for_tests=self.checker)
588
589 def testAddedPydep(self):
Saagar Sanghavifceeaae2020-08-12 16:40:36590 # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
pastarmovj89f7ee12016-09-20 14:58:13591 if self.mock_input_api.platform != 'linux2':
592 return []
593
agrievef32bcc72016-04-04 14:57:40594 self.mock_input_api.files = [
595 MockAffectedFile('new.pydeps', [], action='A'),
596 ]
597
Zhiling Huang45cabf32018-03-10 00:50:03598 self.mock_input_api.CreateMockFileInPath(
599 [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
600 include_deletes=True)])
agrievef32bcc72016-04-04 14:57:40601 results = self._RunCheck()
602 self.assertEqual(1, len(results))
Andrew Grieve5bb4cf702020-10-22 20:21:39603 self.assertIn('PYDEPS_FILES', str(results[0]))
agrievef32bcc72016-04-04 14:57:40604
Zhiling Huang45cabf32018-03-10 00:50:03605 def testPydepNotInSrc(self):
606 self.mock_input_api.files = [
607 MockAffectedFile('new.pydeps', [], action='A'),
608 ]
609 self.mock_input_api.CreateMockFileInPath([])
610 results = self._RunCheck()
611 self.assertEqual(0, len(results))
612
agrievef32bcc72016-04-04 14:57:40613 def testRemovedPydep(self):
Saagar Sanghavifceeaae2020-08-12 16:40:36614 # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
pastarmovj89f7ee12016-09-20 14:58:13615 if self.mock_input_api.platform != 'linux2':
616 return []
617
agrievef32bcc72016-04-04 14:57:40618 self.mock_input_api.files = [
619 MockAffectedFile(PRESUBMIT._ALL_PYDEPS_FILES[0], [], action='D'),
620 ]
Zhiling Huang45cabf32018-03-10 00:50:03621 self.mock_input_api.CreateMockFileInPath(
622 [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
623 include_deletes=True)])
agrievef32bcc72016-04-04 14:57:40624 results = self._RunCheck()
625 self.assertEqual(1, len(results))
Andrew Grieve5bb4cf702020-10-22 20:21:39626 self.assertIn('PYDEPS_FILES', str(results[0]))
agrievef32bcc72016-04-04 14:57:40627
628 def testRandomPyIgnored(self):
Saagar Sanghavifceeaae2020-08-12 16:40:36629 # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
pastarmovj89f7ee12016-09-20 14:58:13630 if self.mock_input_api.platform != 'linux2':
631 return []
632
agrievef32bcc72016-04-04 14:57:40633 self.mock_input_api.files = [
634 MockAffectedFile('random.py', []),
635 ]
636
637 results = self._RunCheck()
638 self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
639
640 def testRelevantPyNoChange(self):
Saagar Sanghavifceeaae2020-08-12 16:40:36641 # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
pastarmovj89f7ee12016-09-20 14:58:13642 if self.mock_input_api.platform != 'linux2':
643 return []
644
agrievef32bcc72016-04-04 14:57:40645 self.mock_input_api.files = [
646 MockAffectedFile('A.py', []),
647 ]
648
John Budorickab2fa102017-10-06 16:59:49649 def mock_check_output(cmd, shell=False, env=None):
Andrew Grieve5bb4cf702020-10-22 20:21:39650 self.assertEqual('CMD --output A.pydeps A --output ""', cmd)
agrievef32bcc72016-04-04 14:57:40651 return self.checker._file_cache['A.pydeps']
652
653 self.mock_input_api.subprocess.check_output = mock_check_output
654
655 results = self._RunCheck()
656 self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
657
658 def testRelevantPyOneChange(self):
Saagar Sanghavifceeaae2020-08-12 16:40:36659 # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
pastarmovj89f7ee12016-09-20 14:58:13660 if self.mock_input_api.platform != 'linux2':
661 return []
662
agrievef32bcc72016-04-04 14:57:40663 self.mock_input_api.files = [
664 MockAffectedFile('A.py', []),
665 ]
666
John Budorickab2fa102017-10-06 16:59:49667 def mock_check_output(cmd, shell=False, env=None):
Andrew Grieve5bb4cf702020-10-22 20:21:39668 self.assertEqual('CMD --output A.pydeps A --output ""', cmd)
agrievef32bcc72016-04-04 14:57:40669 return 'changed data'
670
671 self.mock_input_api.subprocess.check_output = mock_check_output
672
673 results = self._RunCheck()
674 self.assertEqual(1, len(results))
Andrew Grieve5bb4cf702020-10-22 20:21:39675 self.assertIn('File is stale', str(results[0]))
agrievef32bcc72016-04-04 14:57:40676
677 def testRelevantPyTwoChanges(self):
Saagar Sanghavifceeaae2020-08-12 16:40:36678 # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
pastarmovj89f7ee12016-09-20 14:58:13679 if self.mock_input_api.platform != 'linux2':
680 return []
681
agrievef32bcc72016-04-04 14:57:40682 self.mock_input_api.files = [
683 MockAffectedFile('C.py', []),
684 ]
685
John Budorickab2fa102017-10-06 16:59:49686 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40687 return 'changed data'
688
689 self.mock_input_api.subprocess.check_output = mock_check_output
690
691 results = self._RunCheck()
692 self.assertEqual(2, len(results))
Andrew Grieve5bb4cf702020-10-22 20:21:39693 self.assertIn('File is stale', str(results[0]))
694 self.assertIn('File is stale', str(results[1]))
agrievef32bcc72016-04-04 14:57:40695
Mohamed Heikal7cd4d8312020-06-16 16:49:40696 def testRelevantAndroidPyInNonAndroidCheckout(self):
Saagar Sanghavifceeaae2020-08-12 16:40:36697 # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
Mohamed Heikal7cd4d8312020-06-16 16:49:40698 if self.mock_input_api.platform != 'linux2':
699 return []
700
701 self.mock_input_api.files = [
702 MockAffectedFile('D.py', []),
703 ]
704
705 def mock_check_output(cmd, shell=False, env=None):
Andrew Grieve5bb4cf702020-10-22 20:21:39706 self.assertEqual('CMD --output D.pydeps D --output ""', cmd)
Mohamed Heikal7cd4d8312020-06-16 16:49:40707 return 'changed data'
708
709 self.mock_input_api.subprocess.check_output = mock_check_output
710 PRESUBMIT._ParseGclientArgs = self._MockParseGclientArgs(is_android=False)
711
712 results = self._RunCheck()
713 self.assertEqual(1, len(results))
Andrew Grieve5bb4cf702020-10-22 20:21:39714 self.assertIn('Android', str(results[0]))
715 self.assertIn('D.pydeps', str(results[0]))
716
717 def testGnPathsAndMissingOutputFlag(self):
718 # PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
719 if self.mock_input_api.platform != 'linux2':
720 return []
721
722 self.checker._file_cache = {
723 'A.pydeps': '# Generated by:\n# CMD --gn-paths A\n//A.py\n//C.py\n',
724 'B.pydeps': '# Generated by:\n# CMD --gn-paths B\n//B.py\n//C.py\n',
725 'D.pydeps': '# Generated by:\n# CMD --gn-paths D\n//D.py\n',
726 }
727
728 self.mock_input_api.files = [
729 MockAffectedFile('A.py', []),
730 ]
731
732 def mock_check_output(cmd, shell=False, env=None):
733 self.assertEqual('CMD --gn-paths A --output A.pydeps --output ""', cmd)
734 return 'changed data'
735
736 self.mock_input_api.subprocess.check_output = mock_check_output
737
738 results = self._RunCheck()
739 self.assertEqual(1, len(results))
740 self.assertIn('File is stale', str(results[0]))
Mohamed Heikal7cd4d8312020-06-16 16:49:40741
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39742
Daniel Bratell8ba52722018-03-02 16:06:14743class IncludeGuardTest(unittest.TestCase):
744 def testIncludeGuardChecks(self):
745 mock_input_api = MockInputApi()
746 mock_output_api = MockOutputApi()
747 mock_input_api.files = [
748 MockAffectedFile('content/browser/thing/foo.h', [
749 '// Comment',
750 '#ifndef CONTENT_BROWSER_THING_FOO_H_',
751 '#define CONTENT_BROWSER_THING_FOO_H_',
752 'struct McBoatFace;',
753 '#endif // CONTENT_BROWSER_THING_FOO_H_',
754 ]),
755 MockAffectedFile('content/browser/thing/bar.h', [
756 '#ifndef CONTENT_BROWSER_THING_BAR_H_',
757 '#define CONTENT_BROWSER_THING_BAR_H_',
758 'namespace content {',
759 '#endif // CONTENT_BROWSER_THING_BAR_H_',
760 '} // namespace content',
761 ]),
762 MockAffectedFile('content/browser/test1.h', [
763 'namespace content {',
764 '} // namespace content',
765 ]),
766 MockAffectedFile('content\\browser\\win.h', [
767 '#ifndef CONTENT_BROWSER_WIN_H_',
768 '#define CONTENT_BROWSER_WIN_H_',
769 'struct McBoatFace;',
770 '#endif // CONTENT_BROWSER_WIN_H_',
771 ]),
772 MockAffectedFile('content/browser/test2.h', [
773 '// Comment',
774 '#ifndef CONTENT_BROWSER_TEST2_H_',
775 'struct McBoatFace;',
776 '#endif // CONTENT_BROWSER_TEST2_H_',
777 ]),
778 MockAffectedFile('content/browser/internal.h', [
779 '// Comment',
780 '#ifndef CONTENT_BROWSER_INTERNAL_H_',
781 '#define CONTENT_BROWSER_INTERNAL_H_',
782 '// Comment',
783 '#ifndef INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
784 '#define INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
785 'namespace internal {',
786 '} // namespace internal',
787 '#endif // INTERNAL_CONTENT_BROWSER_THING_BAR_H_',
788 'namespace content {',
789 '} // namespace content',
790 '#endif // CONTENT_BROWSER_THING_BAR_H_',
791 ]),
792 MockAffectedFile('content/browser/thing/foo.cc', [
793 '// This is a non-header.',
794 ]),
795 MockAffectedFile('content/browser/disabled.h', [
796 '// no-include-guard-because-multiply-included',
797 'struct McBoatFace;',
798 ]),
799 # New files don't allow misspelled include guards.
800 MockAffectedFile('content/browser/spleling.h', [
801 '#ifndef CONTENT_BROWSER_SPLLEING_H_',
802 '#define CONTENT_BROWSER_SPLLEING_H_',
803 'struct McBoatFace;',
804 '#endif // CONTENT_BROWSER_SPLLEING_H_',
805 ]),
Olivier Robinbba137492018-07-30 11:31:34806 # New files don't allow + in include guards.
807 MockAffectedFile('content/browser/foo+bar.h', [
808 '#ifndef CONTENT_BROWSER_FOO+BAR_H_',
809 '#define CONTENT_BROWSER_FOO+BAR_H_',
810 'struct McBoatFace;',
811 '#endif // CONTENT_BROWSER_FOO+BAR_H_',
812 ]),
Daniel Bratell8ba52722018-03-02 16:06:14813 # Old files allow misspelled include guards (for now).
814 MockAffectedFile('chrome/old.h', [
815 '// New contents',
816 '#ifndef CHROME_ODL_H_',
817 '#define CHROME_ODL_H_',
818 '#endif // CHROME_ODL_H_',
819 ], [
820 '// Old contents',
821 '#ifndef CHROME_ODL_H_',
822 '#define CHROME_ODL_H_',
823 '#endif // CHROME_ODL_H_',
824 ]),
825 # Using a Blink style include guard outside Blink is wrong.
826 MockAffectedFile('content/NotInBlink.h', [
827 '#ifndef NotInBlink_h',
828 '#define NotInBlink_h',
829 'struct McBoatFace;',
830 '#endif // NotInBlink_h',
831 ]),
Daniel Bratell39b5b062018-05-16 18:09:57832 # Using a Blink style include guard in Blink is no longer ok.
833 MockAffectedFile('third_party/blink/InBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14834 '#ifndef InBlink_h',
835 '#define InBlink_h',
836 'struct McBoatFace;',
837 '#endif // InBlink_h',
838 ]),
839 # Using a bad include guard in Blink is not ok.
Daniel Bratell39b5b062018-05-16 18:09:57840 MockAffectedFile('third_party/blink/AlsoInBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14841 '#ifndef WrongInBlink_h',
842 '#define WrongInBlink_h',
843 'struct McBoatFace;',
844 '#endif // WrongInBlink_h',
845 ]),
Daniel Bratell39b5b062018-05-16 18:09:57846 # Using a bad include guard in Blink is not accepted even if
847 # it's an old file.
848 MockAffectedFile('third_party/blink/StillInBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14849 '// New contents',
850 '#ifndef AcceptedInBlink_h',
851 '#define AcceptedInBlink_h',
852 'struct McBoatFace;',
853 '#endif // AcceptedInBlink_h',
854 ], [
855 '// Old contents',
856 '#ifndef AcceptedInBlink_h',
857 '#define AcceptedInBlink_h',
858 'struct McBoatFace;',
859 '#endif // AcceptedInBlink_h',
860 ]),
Daniel Bratell39b5b062018-05-16 18:09:57861 # Using a non-Chromium include guard in third_party
862 # (outside blink) is accepted.
863 MockAffectedFile('third_party/foo/some_file.h', [
864 '#ifndef REQUIRED_RPCNDR_H_',
865 '#define REQUIRED_RPCNDR_H_',
866 'struct SomeFileFoo;',
867 '#endif // REQUIRED_RPCNDR_H_',
868 ]),
Kinuko Yasuda0cdb3da2019-07-31 21:50:32869 # Not having proper include guard in *_message_generator.h
870 # for old IPC messages is allowed.
871 MockAffectedFile('content/common/content_message_generator.h', [
872 '#undef CONTENT_COMMON_FOO_MESSAGES_H_',
873 '#include "content/common/foo_messages.h"',
874 '#ifndef CONTENT_COMMON_FOO_MESSAGES_H_',
875 '#error "Failed to include content/common/foo_messages.h"',
876 '#endif',
877 ]),
Daniel Bratell8ba52722018-03-02 16:06:14878 ]
Saagar Sanghavifceeaae2020-08-12 16:40:36879 msgs = PRESUBMIT.CheckForIncludeGuards(
Daniel Bratell8ba52722018-03-02 16:06:14880 mock_input_api, mock_output_api)
Olivier Robinbba137492018-07-30 11:31:34881 expected_fail_count = 8
Daniel Bratell8ba52722018-03-02 16:06:14882 self.assertEqual(expected_fail_count, len(msgs),
883 'Expected %d items, found %d: %s'
884 % (expected_fail_count, len(msgs), msgs))
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39885 self.assertEqual(msgs[0].items, ['content/browser/thing/bar.h'])
Daniel Bratell8ba52722018-03-02 16:06:14886 self.assertEqual(msgs[0].message,
887 'Include guard CONTENT_BROWSER_THING_BAR_H_ '
888 'not covering the whole file')
889
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39890 self.assertEqual(msgs[1].items, ['content/browser/test1.h'])
Daniel Bratell8ba52722018-03-02 16:06:14891 self.assertEqual(msgs[1].message,
892 'Missing include guard CONTENT_BROWSER_TEST1_H_')
893
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39894 self.assertEqual(msgs[2].items, ['content/browser/test2.h:3'])
Daniel Bratell8ba52722018-03-02 16:06:14895 self.assertEqual(msgs[2].message,
896 'Missing "#define CONTENT_BROWSER_TEST2_H_" for '
897 'include guard')
898
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39899 self.assertEqual(msgs[3].items, ['content/browser/spleling.h:1'])
Daniel Bratell8ba52722018-03-02 16:06:14900 self.assertEqual(msgs[3].message,
901 'Header using the wrong include guard name '
902 'CONTENT_BROWSER_SPLLEING_H_')
903
Olivier Robinbba137492018-07-30 11:31:34904 self.assertEqual(msgs[4].items, ['content/browser/foo+bar.h'])
Daniel Bratell8ba52722018-03-02 16:06:14905 self.assertEqual(msgs[4].message,
Olivier Robinbba137492018-07-30 11:31:34906 'Missing include guard CONTENT_BROWSER_FOO_BAR_H_')
907
908 self.assertEqual(msgs[5].items, ['content/NotInBlink.h:1'])
909 self.assertEqual(msgs[5].message,
Daniel Bratell8ba52722018-03-02 16:06:14910 'Header using the wrong include guard name '
911 'NotInBlink_h')
912
Olivier Robinbba137492018-07-30 11:31:34913 self.assertEqual(msgs[6].items, ['third_party/blink/InBlink.h:1'])
914 self.assertEqual(msgs[6].message,
Daniel Bratell8ba52722018-03-02 16:06:14915 'Header using the wrong include guard name '
Daniel Bratell39b5b062018-05-16 18:09:57916 'InBlink_h')
917
Olivier Robinbba137492018-07-30 11:31:34918 self.assertEqual(msgs[7].items, ['third_party/blink/AlsoInBlink.h:1'])
919 self.assertEqual(msgs[7].message,
Daniel Bratell39b5b062018-05-16 18:09:57920 'Header using the wrong include guard name '
Daniel Bratell8ba52722018-03-02 16:06:14921 'WrongInBlink_h')
922
Chris Hall59f8d0c72020-05-01 07:31:19923class AccessibilityRelnotesFieldTest(unittest.TestCase):
924 def testRelnotesPresent(self):
925 mock_input_api = MockInputApi()
926 mock_output_api = MockOutputApi()
927
928 mock_input_api.files = [MockAffectedFile('ui/accessibility/foo.bar', [''])]
Akihiro Ota08108e542020-05-20 15:30:53929 mock_input_api.change.DescriptionText = lambda : 'Commit description'
Chris Hall59f8d0c72020-05-01 07:31:19930 mock_input_api.change.footers['AX-Relnotes'] = [
931 'Important user facing change']
932
Saagar Sanghavifceeaae2020-08-12 16:40:36933 msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
Chris Hall59f8d0c72020-05-01 07:31:19934 mock_input_api, mock_output_api)
935 self.assertEqual(0, len(msgs),
936 'Expected %d messages, found %d: %s'
937 % (0, len(msgs), msgs))
938
939 def testRelnotesMissingFromAccessibilityChange(self):
940 mock_input_api = MockInputApi()
941 mock_output_api = MockOutputApi()
942
943 mock_input_api.files = [
944 MockAffectedFile('some/file', ['']),
945 MockAffectedFile('ui/accessibility/foo.bar', ['']),
946 MockAffectedFile('some/other/file', [''])
947 ]
Akihiro Ota08108e542020-05-20 15:30:53948 mock_input_api.change.DescriptionText = lambda : 'Commit description'
Chris Hall59f8d0c72020-05-01 07:31:19949
Saagar Sanghavifceeaae2020-08-12 16:40:36950 msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
Chris Hall59f8d0c72020-05-01 07:31:19951 mock_input_api, mock_output_api)
952 self.assertEqual(1, len(msgs),
953 'Expected %d messages, found %d: %s'
954 % (1, len(msgs), msgs))
955 self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
956 'Missing AX-Relnotes field message not found in errors')
957
958 # The relnotes footer is not required for changes which do not touch any
959 # accessibility directories.
960 def testIgnoresNonAccesssibilityCode(self):
961 mock_input_api = MockInputApi()
962 mock_output_api = MockOutputApi()
963
964 mock_input_api.files = [
965 MockAffectedFile('some/file', ['']),
966 MockAffectedFile('some/other/file', [''])
967 ]
Akihiro Ota08108e542020-05-20 15:30:53968 mock_input_api.change.DescriptionText = lambda : 'Commit description'
Chris Hall59f8d0c72020-05-01 07:31:19969
Saagar Sanghavifceeaae2020-08-12 16:40:36970 msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
Chris Hall59f8d0c72020-05-01 07:31:19971 mock_input_api, mock_output_api)
972 self.assertEqual(0, len(msgs),
973 'Expected %d messages, found %d: %s'
974 % (0, len(msgs), msgs))
975
976 # Test that our presubmit correctly raises an error for a set of known paths.
977 def testExpectedPaths(self):
978 filesToTest = [
979 "chrome/browser/accessibility/foo.py",
980 "chrome/browser/chromeos/arc/accessibility/foo.cc",
981 "chrome/browser/ui/views/accessibility/foo.h",
982 "chrome/browser/extensions/api/automation/foo.h",
983 "chrome/browser/extensions/api/automation_internal/foo.cc",
984 "chrome/renderer/extensions/accessibility_foo.h",
985 "chrome/tests/data/accessibility/foo.html",
986 "content/browser/accessibility/foo.cc",
987 "content/renderer/accessibility/foo.h",
988 "content/tests/data/accessibility/foo.cc",
989 "extensions/renderer/api/automation/foo.h",
990 "ui/accessibility/foo/bar/baz.cc",
991 "ui/views/accessibility/foo/bar/baz.h",
992 ]
993
994 for testFile in filesToTest:
995 mock_input_api = MockInputApi()
996 mock_output_api = MockOutputApi()
997
998 mock_input_api.files = [
999 MockAffectedFile(testFile, [''])
1000 ]
Akihiro Ota08108e542020-05-20 15:30:531001 mock_input_api.change.DescriptionText = lambda : 'Commit description'
Chris Hall59f8d0c72020-05-01 07:31:191002
Saagar Sanghavifceeaae2020-08-12 16:40:361003 msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
Chris Hall59f8d0c72020-05-01 07:31:191004 mock_input_api, mock_output_api)
1005 self.assertEqual(1, len(msgs),
1006 'Expected %d messages, found %d: %s, for file %s'
1007 % (1, len(msgs), msgs, testFile))
1008 self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
1009 ('Missing AX-Relnotes field message not found in errors '
1010 ' for file %s' % (testFile)))
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391011
Akihiro Ota08108e542020-05-20 15:30:531012 # Test that AX-Relnotes field can appear in the commit description (as long
1013 # as it appears at the beginning of a line).
1014 def testRelnotesInCommitDescription(self):
1015 mock_input_api = MockInputApi()
1016 mock_output_api = MockOutputApi()
1017
1018 mock_input_api.files = [
1019 MockAffectedFile('ui/accessibility/foo.bar', ['']),
1020 ]
1021 mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
1022 'AX-Relnotes: solves all accessibility issues forever')
1023
Saagar Sanghavifceeaae2020-08-12 16:40:361024 msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
Akihiro Ota08108e542020-05-20 15:30:531025 mock_input_api, mock_output_api)
1026 self.assertEqual(0, len(msgs),
1027 'Expected %d messages, found %d: %s'
1028 % (0, len(msgs), msgs))
1029
1030 # Test that we don't match AX-Relnotes if it appears in the middle of a line.
1031 def testRelnotesMustAppearAtBeginningOfLine(self):
1032 mock_input_api = MockInputApi()
1033 mock_output_api = MockOutputApi()
1034
1035 mock_input_api.files = [
1036 MockAffectedFile('ui/accessibility/foo.bar', ['']),
1037 ]
1038 mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
1039 'This change has no AX-Relnotes: we should print a warning')
1040
Saagar Sanghavifceeaae2020-08-12 16:40:361041 msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
Akihiro Ota08108e542020-05-20 15:30:531042 mock_input_api, mock_output_api)
1043 self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
1044 'Missing AX-Relnotes field message not found in errors')
1045
1046 # Tests that the AX-Relnotes field can be lowercase and use a '=' in place
1047 # of a ':'.
1048 def testRelnotesLowercaseWithEqualSign(self):
1049 mock_input_api = MockInputApi()
1050 mock_output_api = MockOutputApi()
1051
1052 mock_input_api.files = [
1053 MockAffectedFile('ui/accessibility/foo.bar', ['']),
1054 ]
1055 mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
1056 'ax-relnotes= this is a valid format for accessibiliy relnotes')
1057
Saagar Sanghavifceeaae2020-08-12 16:40:361058 msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
Akihiro Ota08108e542020-05-20 15:30:531059 mock_input_api, mock_output_api)
1060 self.assertEqual(0, len(msgs),
1061 'Expected %d messages, found %d: %s'
1062 % (0, len(msgs), msgs))
1063
yolandyan45001472016-12-21 21:12:421064class AndroidDeprecatedTestAnnotationTest(unittest.TestCase):
1065 def testCheckAndroidTestAnnotationUsage(self):
1066 mock_input_api = MockInputApi()
1067 mock_output_api = MockOutputApi()
1068
1069 mock_input_api.files = [
1070 MockAffectedFile('LalaLand.java', [
1071 'random stuff'
1072 ]),
1073 MockAffectedFile('CorrectUsage.java', [
1074 'import android.support.test.filters.LargeTest;',
1075 'import android.support.test.filters.MediumTest;',
1076 'import android.support.test.filters.SmallTest;',
1077 ]),
1078 MockAffectedFile('UsedDeprecatedLargeTestAnnotation.java', [
1079 'import android.test.suitebuilder.annotation.LargeTest;',
1080 ]),
1081 MockAffectedFile('UsedDeprecatedMediumTestAnnotation.java', [
1082 'import android.test.suitebuilder.annotation.MediumTest;',
1083 ]),
1084 MockAffectedFile('UsedDeprecatedSmallTestAnnotation.java', [
1085 'import android.test.suitebuilder.annotation.SmallTest;',
1086 ]),
1087 MockAffectedFile('UsedDeprecatedSmokeAnnotation.java', [
1088 'import android.test.suitebuilder.annotation.Smoke;',
1089 ])
1090 ]
1091 msgs = PRESUBMIT._CheckAndroidTestAnnotationUsage(
1092 mock_input_api, mock_output_api)
1093 self.assertEqual(1, len(msgs),
1094 'Expected %d items, found %d: %s'
1095 % (1, len(msgs), msgs))
1096 self.assertEqual(4, len(msgs[0].items),
1097 'Expected %d items, found %d: %s'
1098 % (4, len(msgs[0].items), msgs[0].items))
1099 self.assertTrue('UsedDeprecatedLargeTestAnnotation.java:1' in msgs[0].items,
1100 'UsedDeprecatedLargeTestAnnotation not found in errors')
1101 self.assertTrue('UsedDeprecatedMediumTestAnnotation.java:1'
1102 in msgs[0].items,
1103 'UsedDeprecatedMediumTestAnnotation not found in errors')
1104 self.assertTrue('UsedDeprecatedSmallTestAnnotation.java:1' in msgs[0].items,
1105 'UsedDeprecatedSmallTestAnnotation not found in errors')
1106 self.assertTrue('UsedDeprecatedSmokeAnnotation.java:1' in msgs[0].items,
1107 'UsedDeprecatedSmokeAnnotation not found in errors')
1108
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391109
Mohamed Heikal5e5b7922020-10-29 18:57:591110class CheckNoDownstreamDepsTest(unittest.TestCase):
1111 def testInvalidDepFromUpstream(self):
1112 mock_input_api = MockInputApi()
1113 mock_output_api = MockOutputApi()
1114
1115 mock_input_api.files = [
1116 MockAffectedFile('BUILD.gn', [
1117 'deps = [',
1118 ' "//clank/target:test",',
1119 ']'
1120 ]),
1121 MockAffectedFile('chrome/android/BUILD.gn', [
1122 'deps = [ "//clank/target:test" ]'
1123 ]),
1124 MockAffectedFile('chrome/chrome_java_deps.gni', [
1125 'java_deps = [',
1126 ' "//clank/target:test",',
1127 ']'
1128 ]),
1129 ]
1130 mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
1131 msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
1132 mock_input_api, mock_output_api)
1133 self.assertEqual(1, len(msgs),
1134 'Expected %d items, found %d: %s'
1135 % (1, len(msgs), msgs))
1136 self.assertEqual(3, len(msgs[0].items),
1137 'Expected %d items, found %d: %s'
1138 % (3, len(msgs[0].items), msgs[0].items))
1139 self.assertTrue(any('BUILD.gn:2' in item for item in msgs[0].items),
1140 'BUILD.gn not found in errors')
1141 self.assertTrue(
1142 any('chrome/android/BUILD.gn:1' in item for item in msgs[0].items),
1143 'chrome/android/BUILD.gn:1 not found in errors')
1144 self.assertTrue(
1145 any('chrome/chrome_java_deps.gni:2' in item for item in msgs[0].items),
1146 'chrome/chrome_java_deps.gni:2 not found in errors')
1147
1148 def testAllowsComments(self):
1149 mock_input_api = MockInputApi()
1150 mock_output_api = MockOutputApi()
1151
1152 mock_input_api.files = [
1153 MockAffectedFile('BUILD.gn', [
1154 '# real implementation in //clank/target:test',
1155 ]),
1156 ]
1157 mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
1158 msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
1159 mock_input_api, mock_output_api)
1160 self.assertEqual(0, len(msgs),
1161 'Expected %d items, found %d: %s'
1162 % (0, len(msgs), msgs))
1163
1164 def testOnlyChecksBuildFiles(self):
1165 mock_input_api = MockInputApi()
1166 mock_output_api = MockOutputApi()
1167
1168 mock_input_api.files = [
1169 MockAffectedFile('README.md', [
1170 'DEPS = [ "//clank/target:test" ]'
1171 ]),
1172 MockAffectedFile('chrome/android/java/file.java', [
1173 '//clank/ only function'
1174 ]),
1175 ]
1176 mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
1177 msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
1178 mock_input_api, mock_output_api)
1179 self.assertEqual(0, len(msgs),
1180 'Expected %d items, found %d: %s'
1181 % (0, len(msgs), msgs))
1182
1183 def testValidDepFromDownstream(self):
1184 mock_input_api = MockInputApi()
1185 mock_output_api = MockOutputApi()
1186
1187 mock_input_api.files = [
1188 MockAffectedFile('BUILD.gn', [
1189 'DEPS = [',
1190 ' "//clank/target:test",',
1191 ']'
1192 ]),
1193 MockAffectedFile('java/BUILD.gn', [
1194 'DEPS = [ "//clank/target:test" ]'
1195 ]),
1196 ]
1197 mock_input_api.change.RepositoryRoot = lambda: 'chromium/src/clank'
1198 msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(
1199 mock_input_api, mock_output_api)
1200 self.assertEqual(0, len(msgs),
1201 'Expected %d items, found %d: %s'
1202 % (0, len(msgs), msgs))
1203
Yoland Yanb92fa522017-08-28 17:37:061204class AndroidDeprecatedJUnitFrameworkTest(unittest.TestCase):
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271205 def testCheckAndroidTestJUnitFramework(self):
Yoland Yanb92fa522017-08-28 17:37:061206 mock_input_api = MockInputApi()
1207 mock_output_api = MockOutputApi()
yolandyan45001472016-12-21 21:12:421208
Yoland Yanb92fa522017-08-28 17:37:061209 mock_input_api.files = [
1210 MockAffectedFile('LalaLand.java', [
1211 'random stuff'
1212 ]),
1213 MockAffectedFile('CorrectUsage.java', [
1214 'import org.junit.ABC',
1215 'import org.junit.XYZ;',
1216 ]),
1217 MockAffectedFile('UsedDeprecatedJUnit.java', [
1218 'import junit.framework.*;',
1219 ]),
1220 MockAffectedFile('UsedDeprecatedJUnitAssert.java', [
1221 'import junit.framework.Assert;',
1222 ]),
1223 ]
1224 msgs = PRESUBMIT._CheckAndroidTestJUnitFrameworkImport(
1225 mock_input_api, mock_output_api)
1226 self.assertEqual(1, len(msgs),
1227 'Expected %d items, found %d: %s'
1228 % (1, len(msgs), msgs))
1229 self.assertEqual(2, len(msgs[0].items),
1230 'Expected %d items, found %d: %s'
1231 % (2, len(msgs[0].items), msgs[0].items))
1232 self.assertTrue('UsedDeprecatedJUnit.java:1' in msgs[0].items,
1233 'UsedDeprecatedJUnit.java not found in errors')
1234 self.assertTrue('UsedDeprecatedJUnitAssert.java:1'
1235 in msgs[0].items,
1236 'UsedDeprecatedJUnitAssert not found in errors')
1237
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391238
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271239class AndroidJUnitBaseClassTest(unittest.TestCase):
1240 def testCheckAndroidTestJUnitBaseClass(self):
Yoland Yanb92fa522017-08-28 17:37:061241 mock_input_api = MockInputApi()
1242 mock_output_api = MockOutputApi()
1243
1244 mock_input_api.files = [
1245 MockAffectedFile('LalaLand.java', [
1246 'random stuff'
1247 ]),
1248 MockAffectedFile('CorrectTest.java', [
1249 '@RunWith(ABC.class);'
1250 'public class CorrectTest {',
1251 '}',
1252 ]),
1253 MockAffectedFile('HistoricallyIncorrectTest.java', [
1254 'public class Test extends BaseCaseA {',
1255 '}',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391256 ], old_contents=[
Yoland Yanb92fa522017-08-28 17:37:061257 'public class Test extends BaseCaseB {',
1258 '}',
1259 ]),
1260 MockAffectedFile('CorrectTestWithInterface.java', [
1261 '@RunWith(ABC.class);'
1262 'public class CorrectTest implement Interface {',
1263 '}',
1264 ]),
1265 MockAffectedFile('IncorrectTest.java', [
1266 'public class IncorrectTest extends TestCase {',
1267 '}',
1268 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241269 MockAffectedFile('IncorrectWithInterfaceTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061270 'public class Test implements X extends BaseClass {',
1271 '}',
1272 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241273 MockAffectedFile('IncorrectMultiLineTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061274 'public class Test implements X, Y, Z',
1275 ' extends TestBase {',
1276 '}',
1277 ]),
1278 ]
1279 msgs = PRESUBMIT._CheckAndroidTestJUnitInheritance(
1280 mock_input_api, mock_output_api)
1281 self.assertEqual(1, len(msgs),
1282 'Expected %d items, found %d: %s'
1283 % (1, len(msgs), msgs))
1284 self.assertEqual(3, len(msgs[0].items),
1285 'Expected %d items, found %d: %s'
1286 % (3, len(msgs[0].items), msgs[0].items))
1287 self.assertTrue('IncorrectTest.java:1' in msgs[0].items,
1288 'IncorrectTest not found in errors')
Vaclav Brozekf01ed502018-03-16 19:38:241289 self.assertTrue('IncorrectWithInterfaceTest.java:1'
Yoland Yanb92fa522017-08-28 17:37:061290 in msgs[0].items,
Vaclav Brozekf01ed502018-03-16 19:38:241291 'IncorrectWithInterfaceTest not found in errors')
1292 self.assertTrue('IncorrectMultiLineTest.java:2' in msgs[0].items,
1293 'IncorrectMultiLineTest not found in errors')
yolandyan45001472016-12-21 21:12:421294
Jinsong Fan91ebbbd2019-04-16 14:57:171295class AndroidDebuggableBuildTest(unittest.TestCase):
1296
1297 def testCheckAndroidDebuggableBuild(self):
1298 mock_input_api = MockInputApi()
1299 mock_output_api = MockOutputApi()
1300
1301 mock_input_api.files = [
1302 MockAffectedFile('RandomStuff.java', [
1303 'random stuff'
1304 ]),
1305 MockAffectedFile('CorrectUsage.java', [
1306 'import org.chromium.base.BuildInfo;',
1307 'some random stuff',
1308 'boolean isOsDebuggable = BuildInfo.isDebugAndroid();',
1309 ]),
1310 MockAffectedFile('JustCheckUserdebugBuild.java', [
1311 'import android.os.Build;',
1312 'some random stuff',
1313 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")',
1314 ]),
1315 MockAffectedFile('JustCheckEngineeringBuild.java', [
1316 'import android.os.Build;',
1317 'some random stuff',
1318 'boolean isOsDebuggable = "eng".equals(Build.TYPE)',
1319 ]),
1320 MockAffectedFile('UsedBuildType.java', [
1321 'import android.os.Build;',
1322 'some random stuff',
1323 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")'
1324 '|| "eng".equals(Build.TYPE)',
1325 ]),
1326 MockAffectedFile('UsedExplicitBuildType.java', [
1327 'some random stuff',
1328 'boolean isOsDebuggable = android.os.Build.TYPE.equals("userdebug")'
1329 '|| "eng".equals(android.os.Build.TYPE)',
1330 ]),
1331 ]
1332
1333 msgs = PRESUBMIT._CheckAndroidDebuggableBuild(
1334 mock_input_api, mock_output_api)
1335 self.assertEqual(1, len(msgs),
1336 'Expected %d items, found %d: %s'
1337 % (1, len(msgs), msgs))
1338 self.assertEqual(4, len(msgs[0].items),
1339 'Expected %d items, found %d: %s'
1340 % (4, len(msgs[0].items), msgs[0].items))
1341 self.assertTrue('JustCheckUserdebugBuild.java:3' in msgs[0].items)
1342 self.assertTrue('JustCheckEngineeringBuild.java:3' in msgs[0].items)
1343 self.assertTrue('UsedBuildType.java:3' in msgs[0].items)
1344 self.assertTrue('UsedExplicitBuildType.java:2' in msgs[0].items)
1345
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391346
dgn4401aa52015-04-29 16:26:171347class LogUsageTest(unittest.TestCase):
1348
dgnaa68d5e2015-06-10 10:08:221349 def testCheckAndroidCrLogUsage(self):
1350 mock_input_api = MockInputApi()
1351 mock_output_api = MockOutputApi()
1352
1353 mock_input_api.files = [
1354 MockAffectedFile('RandomStuff.java', [
1355 'random stuff'
1356 ]),
dgn87d9fb62015-06-12 09:15:121357 MockAffectedFile('HasAndroidLog.java', [
1358 'import android.util.Log;',
1359 'some random stuff',
1360 'Log.d("TAG", "foo");',
1361 ]),
1362 MockAffectedFile('HasExplicitUtilLog.java', [
1363 'some random stuff',
1364 'android.util.Log.d("TAG", "foo");',
1365 ]),
1366 MockAffectedFile('IsInBasePackage.java', [
1367 'package org.chromium.base;',
dgn38736db2015-09-18 19:20:511368 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121369 'Log.d(TAG, "foo");',
1370 ]),
1371 MockAffectedFile('IsInBasePackageButImportsLog.java', [
1372 'package org.chromium.base;',
1373 'import android.util.Log;',
dgn38736db2015-09-18 19:20:511374 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121375 'Log.d(TAG, "foo");',
1376 ]),
1377 MockAffectedFile('HasBothLog.java', [
1378 'import org.chromium.base.Log;',
1379 'some random stuff',
dgn38736db2015-09-18 19:20:511380 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121381 'Log.d(TAG, "foo");',
1382 'android.util.Log.d("TAG", "foo");',
1383 ]),
dgnaa68d5e2015-06-10 10:08:221384 MockAffectedFile('HasCorrectTag.java', [
1385 'import org.chromium.base.Log;',
1386 'some random stuff',
dgn38736db2015-09-18 19:20:511387 'private static final String TAG = "cr_Foo";',
1388 'Log.d(TAG, "foo");',
1389 ]),
1390 MockAffectedFile('HasOldTag.java', [
1391 'import org.chromium.base.Log;',
1392 'some random stuff',
dgnaa68d5e2015-06-10 10:08:221393 'private static final String TAG = "cr.Foo";',
1394 'Log.d(TAG, "foo");',
1395 ]),
dgn38736db2015-09-18 19:20:511396 MockAffectedFile('HasDottedTag.java', [
dgnaa68d5e2015-06-10 10:08:221397 'import org.chromium.base.Log;',
1398 'some random stuff',
dgn38736db2015-09-18 19:20:511399 'private static final String TAG = "cr_foo.bar";',
dgnaa68d5e2015-06-10 10:08:221400 'Log.d(TAG, "foo");',
1401 ]),
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461402 MockAffectedFile('HasDottedTagPublic.java', [
1403 'import org.chromium.base.Log;',
1404 'some random stuff',
1405 'public static final String TAG = "cr_foo.bar";',
1406 'Log.d(TAG, "foo");',
1407 ]),
dgnaa68d5e2015-06-10 10:08:221408 MockAffectedFile('HasNoTagDecl.java', [
1409 'import org.chromium.base.Log;',
1410 'some random stuff',
1411 'Log.d(TAG, "foo");',
1412 ]),
1413 MockAffectedFile('HasIncorrectTagDecl.java', [
1414 'import org.chromium.base.Log;',
dgn38736db2015-09-18 19:20:511415 'private static final String TAHG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221416 'some random stuff',
1417 'Log.d(TAG, "foo");',
1418 ]),
1419 MockAffectedFile('HasInlineTag.java', [
1420 'import org.chromium.base.Log;',
1421 'some random stuff',
dgn38736db2015-09-18 19:20:511422 'private static final String TAG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221423 'Log.d("TAG", "foo");',
1424 ]),
Tomasz Śniatowski3ae2f102020-03-23 15:35:551425 MockAffectedFile('HasInlineTagWithSpace.java', [
1426 'import org.chromium.base.Log;',
1427 'some random stuff',
1428 'private static final String TAG = "cr_Foo";',
1429 'Log.d("log message", "foo");',
1430 ]),
dgn38736db2015-09-18 19:20:511431 MockAffectedFile('HasUnprefixedTag.java', [
dgnaa68d5e2015-06-10 10:08:221432 'import org.chromium.base.Log;',
1433 'some random stuff',
1434 'private static final String TAG = "rubbish";',
1435 'Log.d(TAG, "foo");',
1436 ]),
1437 MockAffectedFile('HasTooLongTag.java', [
1438 'import org.chromium.base.Log;',
1439 'some random stuff',
dgn38736db2015-09-18 19:20:511440 'private static final String TAG = "21_charachers_long___";',
dgnaa68d5e2015-06-10 10:08:221441 'Log.d(TAG, "foo");',
1442 ]),
Tomasz Śniatowski3ae2f102020-03-23 15:35:551443 MockAffectedFile('HasTooLongTagWithNoLogCallsInDiff.java', [
1444 'import org.chromium.base.Log;',
1445 'some random stuff',
1446 'private static final String TAG = "21_charachers_long___";',
1447 ]),
dgnaa68d5e2015-06-10 10:08:221448 ]
1449
1450 msgs = PRESUBMIT._CheckAndroidCrLogUsage(
1451 mock_input_api, mock_output_api)
1452
dgn38736db2015-09-18 19:20:511453 self.assertEqual(5, len(msgs),
1454 'Expected %d items, found %d: %s' % (5, len(msgs), msgs))
dgnaa68d5e2015-06-10 10:08:221455
1456 # Declaration format
dgn38736db2015-09-18 19:20:511457 nb = len(msgs[0].items)
1458 self.assertEqual(2, nb,
1459 'Expected %d items, found %d: %s' % (2, nb, msgs[0].items))
dgnaa68d5e2015-06-10 10:08:221460 self.assertTrue('HasNoTagDecl.java' in msgs[0].items)
1461 self.assertTrue('HasIncorrectTagDecl.java' in msgs[0].items)
dgnaa68d5e2015-06-10 10:08:221462
1463 # Tag length
dgn38736db2015-09-18 19:20:511464 nb = len(msgs[1].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551465 self.assertEqual(2, nb,
1466 'Expected %d items, found %d: %s' % (2, nb, msgs[1].items))
dgnaa68d5e2015-06-10 10:08:221467 self.assertTrue('HasTooLongTag.java' in msgs[1].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551468 self.assertTrue('HasTooLongTagWithNoLogCallsInDiff.java' in msgs[1].items)
dgnaa68d5e2015-06-10 10:08:221469
1470 # Tag must be a variable named TAG
dgn38736db2015-09-18 19:20:511471 nb = len(msgs[2].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551472 self.assertEqual(3, nb,
1473 'Expected %d items, found %d: %s' % (3, nb, msgs[2].items))
1474 self.assertTrue('HasBothLog.java:5' in msgs[2].items)
dgnaa68d5e2015-06-10 10:08:221475 self.assertTrue('HasInlineTag.java:4' in msgs[2].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551476 self.assertTrue('HasInlineTagWithSpace.java:4' in msgs[2].items)
dgnaa68d5e2015-06-10 10:08:221477
dgn87d9fb62015-06-12 09:15:121478 # Util Log usage
dgn38736db2015-09-18 19:20:511479 nb = len(msgs[3].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551480 self.assertEqual(3, nb,
1481 'Expected %d items, found %d: %s' % (3, nb, msgs[3].items))
dgn87d9fb62015-06-12 09:15:121482 self.assertTrue('HasAndroidLog.java:3' in msgs[3].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551483 self.assertTrue('HasExplicitUtilLog.java:2' in msgs[3].items)
dgn87d9fb62015-06-12 09:15:121484 self.assertTrue('IsInBasePackageButImportsLog.java:4' in msgs[3].items)
dgnaa68d5e2015-06-10 10:08:221485
dgn38736db2015-09-18 19:20:511486 # Tag must not contain
1487 nb = len(msgs[4].items)
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461488 self.assertEqual(3, nb,
dgn38736db2015-09-18 19:20:511489 'Expected %d items, found %d: %s' % (2, nb, msgs[4].items))
1490 self.assertTrue('HasDottedTag.java' in msgs[4].items)
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461491 self.assertTrue('HasDottedTagPublic.java' in msgs[4].items)
dgn38736db2015-09-18 19:20:511492 self.assertTrue('HasOldTag.java' in msgs[4].items)
1493
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391494
estadee17314a02017-01-12 16:22:161495class GoogleAnswerUrlFormatTest(unittest.TestCase):
1496
1497 def testCatchAnswerUrlId(self):
1498 input_api = MockInputApi()
1499 input_api.files = [
1500 MockFile('somewhere/file.cc',
1501 ['char* host = '
1502 ' "https://support.google.com/chrome/answer/123456";']),
1503 MockFile('somewhere_else/file.cc',
1504 ['char* host = '
1505 ' "https://support.google.com/chrome/a/answer/123456";']),
1506 ]
1507
Saagar Sanghavifceeaae2020-08-12 16:40:361508 warnings = PRESUBMIT.CheckGoogleSupportAnswerUrlOnUpload(
estadee17314a02017-01-12 16:22:161509 input_api, MockOutputApi())
1510 self.assertEqual(1, len(warnings))
1511 self.assertEqual(2, len(warnings[0].items))
1512
1513 def testAllowAnswerUrlParam(self):
1514 input_api = MockInputApi()
1515 input_api.files = [
1516 MockFile('somewhere/file.cc',
1517 ['char* host = '
1518 ' "https://support.google.com/chrome/?p=cpn_crash_reports";']),
1519 ]
1520
Saagar Sanghavifceeaae2020-08-12 16:40:361521 warnings = PRESUBMIT.CheckGoogleSupportAnswerUrlOnUpload(
estadee17314a02017-01-12 16:22:161522 input_api, MockOutputApi())
1523 self.assertEqual(0, len(warnings))
1524
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391525
reillyi38965732015-11-16 18:27:331526class HardcodedGoogleHostsTest(unittest.TestCase):
1527
1528 def testWarnOnAssignedLiterals(self):
1529 input_api = MockInputApi()
1530 input_api.files = [
1531 MockFile('content/file.cc',
1532 ['char* host = "https://www.google.com";']),
1533 MockFile('content/file.cc',
1534 ['char* host = "https://www.googleapis.com";']),
1535 MockFile('content/file.cc',
1536 ['char* host = "https://clients1.google.com";']),
1537 ]
1538
Saagar Sanghavifceeaae2020-08-12 16:40:361539 warnings = PRESUBMIT.CheckHardcodedGoogleHostsInLowerLayers(
reillyi38965732015-11-16 18:27:331540 input_api, MockOutputApi())
1541 self.assertEqual(1, len(warnings))
1542 self.assertEqual(3, len(warnings[0].items))
1543
1544 def testAllowInComment(self):
1545 input_api = MockInputApi()
1546 input_api.files = [
1547 MockFile('content/file.cc',
1548 ['char* host = "https://www.aol.com"; // google.com'])
1549 ]
1550
Saagar Sanghavifceeaae2020-08-12 16:40:361551 warnings = PRESUBMIT.CheckHardcodedGoogleHostsInLowerLayers(
reillyi38965732015-11-16 18:27:331552 input_api, MockOutputApi())
1553 self.assertEqual(0, len(warnings))
1554
dgn4401aa52015-04-29 16:26:171555
James Cook6b6597c2019-11-06 22:05:291556class ChromeOsSyncedPrefRegistrationTest(unittest.TestCase):
1557
1558 def testWarnsOnChromeOsDirectories(self):
1559 input_api = MockInputApi()
1560 input_api.files = [
1561 MockFile('ash/file.cc',
1562 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1563 MockFile('chrome/browser/chromeos/file.cc',
1564 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1565 MockFile('chromeos/file.cc',
1566 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1567 MockFile('components/arc/file.cc',
1568 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1569 MockFile('components/exo/file.cc',
1570 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1571 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361572 warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
James Cook6b6597c2019-11-06 22:05:291573 input_api, MockOutputApi())
1574 self.assertEqual(1, len(warnings))
1575
1576 def testDoesNotWarnOnSyncOsPref(self):
1577 input_api = MockInputApi()
1578 input_api.files = [
1579 MockFile('chromeos/file.cc',
1580 ['PrefRegistrySyncable::SYNCABLE_OS_PREF']),
1581 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361582 warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
James Cook6b6597c2019-11-06 22:05:291583 input_api, MockOutputApi())
1584 self.assertEqual(0, len(warnings))
1585
1586 def testDoesNotWarnOnCrossPlatformDirectories(self):
1587 input_api = MockInputApi()
1588 input_api.files = [
1589 MockFile('chrome/browser/ui/file.cc',
1590 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1591 MockFile('components/sync/file.cc',
1592 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1593 MockFile('content/browser/file.cc',
1594 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1595 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361596 warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
James Cook6b6597c2019-11-06 22:05:291597 input_api, MockOutputApi())
1598 self.assertEqual(0, len(warnings))
1599
1600 def testSeparateWarningForPriorityPrefs(self):
1601 input_api = MockInputApi()
1602 input_api.files = [
1603 MockFile('chromeos/file.cc',
1604 ['PrefRegistrySyncable::SYNCABLE_PREF',
1605 'PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF']),
1606 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361607 warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
James Cook6b6597c2019-11-06 22:05:291608 input_api, MockOutputApi())
1609 self.assertEqual(2, len(warnings))
1610
1611
jbriance9e12f162016-11-25 07:57:501612class ForwardDeclarationTest(unittest.TestCase):
jbriance2c51e821a2016-12-12 08:24:311613 def testCheckHeadersOnlyOutsideThirdParty(self):
jbriance9e12f162016-11-25 07:57:501614 mock_input_api = MockInputApi()
1615 mock_input_api.files = [
1616 MockAffectedFile('somewhere/file.cc', [
1617 'class DummyClass;'
jbriance2c51e821a2016-12-12 08:24:311618 ]),
1619 MockAffectedFile('third_party/header.h', [
1620 'class DummyClass;'
jbriance9e12f162016-11-25 07:57:501621 ])
1622 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361623 warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391624 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501625 self.assertEqual(0, len(warnings))
1626
1627 def testNoNestedDeclaration(self):
1628 mock_input_api = MockInputApi()
1629 mock_input_api.files = [
1630 MockAffectedFile('somewhere/header.h', [
jbriance2c51e821a2016-12-12 08:24:311631 'class SomeClass {',
1632 ' protected:',
1633 ' class NotAMatch;',
jbriance9e12f162016-11-25 07:57:501634 '};'
1635 ])
1636 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361637 warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391638 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501639 self.assertEqual(0, len(warnings))
1640
1641 def testSubStrings(self):
1642 mock_input_api = MockInputApi()
1643 mock_input_api.files = [
1644 MockAffectedFile('somewhere/header.h', [
1645 'class NotUsefulClass;',
1646 'struct SomeStruct;',
1647 'UsefulClass *p1;',
1648 'SomeStructPtr *p2;'
1649 ])
1650 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361651 warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391652 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501653 self.assertEqual(2, len(warnings))
1654
1655 def testUselessForwardDeclaration(self):
1656 mock_input_api = MockInputApi()
1657 mock_input_api.files = [
1658 MockAffectedFile('somewhere/header.h', [
1659 'class DummyClass;',
1660 'struct DummyStruct;',
1661 'class UsefulClass;',
1662 'std::unique_ptr<UsefulClass> p;'
jbriance2c51e821a2016-12-12 08:24:311663 ])
jbriance9e12f162016-11-25 07:57:501664 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361665 warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391666 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501667 self.assertEqual(2, len(warnings))
1668
jbriance2c51e821a2016-12-12 08:24:311669 def testBlinkHeaders(self):
1670 mock_input_api = MockInputApi()
1671 mock_input_api.files = [
Kent Tamura32dbbcb2018-11-30 12:28:491672 MockAffectedFile('third_party/blink/header.h', [
jbriance2c51e821a2016-12-12 08:24:311673 'class DummyClass;',
1674 'struct DummyStruct;',
1675 ]),
Kent Tamura32dbbcb2018-11-30 12:28:491676 MockAffectedFile('third_party\\blink\\header.h', [
jbriance2c51e821a2016-12-12 08:24:311677 'class DummyClass;',
1678 'struct DummyStruct;',
1679 ])
1680 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361681 warnings = PRESUBMIT.CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391682 MockOutputApi())
jbriance2c51e821a2016-12-12 08:24:311683 self.assertEqual(4, len(warnings))
1684
jbriance9e12f162016-11-25 07:57:501685
rlanday6802cf632017-05-30 17:48:361686class RelativeIncludesTest(unittest.TestCase):
1687 def testThirdPartyNotWebKitIgnored(self):
1688 mock_input_api = MockInputApi()
1689 mock_input_api.files = [
1690 MockAffectedFile('third_party/test.cpp', '#include "../header.h"'),
1691 MockAffectedFile('third_party/test/test.cpp', '#include "../header.h"'),
1692 ]
1693
1694 mock_output_api = MockOutputApi()
1695
Saagar Sanghavifceeaae2020-08-12 16:40:361696 errors = PRESUBMIT.CheckForRelativeIncludes(
rlanday6802cf632017-05-30 17:48:361697 mock_input_api, mock_output_api)
1698 self.assertEqual(0, len(errors))
1699
1700 def testNonCppFileIgnored(self):
1701 mock_input_api = MockInputApi()
1702 mock_input_api.files = [
1703 MockAffectedFile('test.py', '#include "../header.h"'),
1704 ]
1705
1706 mock_output_api = MockOutputApi()
1707
Saagar Sanghavifceeaae2020-08-12 16:40:361708 errors = PRESUBMIT.CheckForRelativeIncludes(
rlanday6802cf632017-05-30 17:48:361709 mock_input_api, mock_output_api)
1710 self.assertEqual(0, len(errors))
1711
1712 def testInnocuousChangesAllowed(self):
1713 mock_input_api = MockInputApi()
1714 mock_input_api.files = [
1715 MockAffectedFile('test.cpp', '#include "header.h"'),
1716 MockAffectedFile('test2.cpp', '../'),
1717 ]
1718
1719 mock_output_api = MockOutputApi()
1720
Saagar Sanghavifceeaae2020-08-12 16:40:361721 errors = PRESUBMIT.CheckForRelativeIncludes(
rlanday6802cf632017-05-30 17:48:361722 mock_input_api, mock_output_api)
1723 self.assertEqual(0, len(errors))
1724
1725 def testRelativeIncludeNonWebKitProducesError(self):
1726 mock_input_api = MockInputApi()
1727 mock_input_api.files = [
1728 MockAffectedFile('test.cpp', ['#include "../header.h"']),
1729 ]
1730
1731 mock_output_api = MockOutputApi()
1732
Saagar Sanghavifceeaae2020-08-12 16:40:361733 errors = PRESUBMIT.CheckForRelativeIncludes(
rlanday6802cf632017-05-30 17:48:361734 mock_input_api, mock_output_api)
1735 self.assertEqual(1, len(errors))
1736
1737 def testRelativeIncludeWebKitProducesError(self):
1738 mock_input_api = MockInputApi()
1739 mock_input_api.files = [
Kent Tamura32dbbcb2018-11-30 12:28:491740 MockAffectedFile('third_party/blink/test.cpp',
rlanday6802cf632017-05-30 17:48:361741 ['#include "../header.h']),
1742 ]
1743
1744 mock_output_api = MockOutputApi()
1745
Saagar Sanghavifceeaae2020-08-12 16:40:361746 errors = PRESUBMIT.CheckForRelativeIncludes(
rlanday6802cf632017-05-30 17:48:361747 mock_input_api, mock_output_api)
1748 self.assertEqual(1, len(errors))
dbeam1ec68ac2016-12-15 05:22:241749
Daniel Cheng13ca61a882017-08-25 15:11:251750
Daniel Bratell65b033262019-04-23 08:17:061751class CCIncludeTest(unittest.TestCase):
1752 def testThirdPartyNotBlinkIgnored(self):
1753 mock_input_api = MockInputApi()
1754 mock_input_api.files = [
1755 MockAffectedFile('third_party/test.cpp', '#include "file.cc"'),
1756 ]
1757
1758 mock_output_api = MockOutputApi()
1759
Saagar Sanghavifceeaae2020-08-12 16:40:361760 errors = PRESUBMIT.CheckForCcIncludes(
Daniel Bratell65b033262019-04-23 08:17:061761 mock_input_api, mock_output_api)
1762 self.assertEqual(0, len(errors))
1763
1764 def testPythonFileIgnored(self):
1765 mock_input_api = MockInputApi()
1766 mock_input_api.files = [
1767 MockAffectedFile('test.py', '#include "file.cc"'),
1768 ]
1769
1770 mock_output_api = MockOutputApi()
1771
Saagar Sanghavifceeaae2020-08-12 16:40:361772 errors = PRESUBMIT.CheckForCcIncludes(
Daniel Bratell65b033262019-04-23 08:17:061773 mock_input_api, mock_output_api)
1774 self.assertEqual(0, len(errors))
1775
1776 def testIncFilesAccepted(self):
1777 mock_input_api = MockInputApi()
1778 mock_input_api.files = [
1779 MockAffectedFile('test.py', '#include "file.inc"'),
1780 ]
1781
1782 mock_output_api = MockOutputApi()
1783
Saagar Sanghavifceeaae2020-08-12 16:40:361784 errors = PRESUBMIT.CheckForCcIncludes(
Daniel Bratell65b033262019-04-23 08:17:061785 mock_input_api, mock_output_api)
1786 self.assertEqual(0, len(errors))
1787
1788 def testInnocuousChangesAllowed(self):
1789 mock_input_api = MockInputApi()
1790 mock_input_api.files = [
1791 MockAffectedFile('test.cpp', '#include "header.h"'),
1792 MockAffectedFile('test2.cpp', 'Something "file.cc"'),
1793 ]
1794
1795 mock_output_api = MockOutputApi()
1796
Saagar Sanghavifceeaae2020-08-12 16:40:361797 errors = PRESUBMIT.CheckForCcIncludes(
Daniel Bratell65b033262019-04-23 08:17:061798 mock_input_api, mock_output_api)
1799 self.assertEqual(0, len(errors))
1800
1801 def testCcIncludeNonBlinkProducesError(self):
1802 mock_input_api = MockInputApi()
1803 mock_input_api.files = [
1804 MockAffectedFile('test.cpp', ['#include "file.cc"']),
1805 ]
1806
1807 mock_output_api = MockOutputApi()
1808
Saagar Sanghavifceeaae2020-08-12 16:40:361809 errors = PRESUBMIT.CheckForCcIncludes(
Daniel Bratell65b033262019-04-23 08:17:061810 mock_input_api, mock_output_api)
1811 self.assertEqual(1, len(errors))
1812
1813 def testCppIncludeBlinkProducesError(self):
1814 mock_input_api = MockInputApi()
1815 mock_input_api.files = [
1816 MockAffectedFile('third_party/blink/test.cpp',
1817 ['#include "foo/file.cpp"']),
1818 ]
1819
1820 mock_output_api = MockOutputApi()
1821
Saagar Sanghavifceeaae2020-08-12 16:40:361822 errors = PRESUBMIT.CheckForCcIncludes(
Daniel Bratell65b033262019-04-23 08:17:061823 mock_input_api, mock_output_api)
1824 self.assertEqual(1, len(errors))
1825
1826
Andrew Grieve1b290e4a22020-11-24 20:07:011827class GnGlobForwardTest(unittest.TestCase):
1828 def testAddBareGlobs(self):
1829 mock_input_api = MockInputApi()
1830 mock_input_api.files = [
1831 MockAffectedFile('base/stuff.gni', [
1832 'forward_variables_from(invoker, "*")']),
1833 MockAffectedFile('base/BUILD.gn', [
1834 'forward_variables_from(invoker, "*")']),
1835 ]
1836 warnings = PRESUBMIT.CheckGnGlobForward(mock_input_api, MockOutputApi())
1837 self.assertEqual(1, len(warnings))
1838 msg = '\n'.join(warnings[0].items)
1839 self.assertIn('base/stuff.gni', msg)
1840 # Should not check .gn files. Local templates don't need to care about
1841 # visibility / testonly.
1842 self.assertNotIn('base/BUILD.gn', msg)
1843
1844 def testValidUses(self):
1845 mock_input_api = MockInputApi()
1846 mock_input_api.files = [
1847 MockAffectedFile('base/stuff.gni', [
1848 'forward_variables_from(invoker, "*", [])']),
1849 MockAffectedFile('base/stuff2.gni', [
1850 'forward_variables_from(invoker, "*", TESTONLY_AND_VISIBILITY)']),
1851 MockAffectedFile('base/stuff3.gni', [
1852 'forward_variables_from(invoker, [ "testonly" ])']),
1853 ]
1854 warnings = PRESUBMIT.CheckGnGlobForward(mock_input_api, MockOutputApi())
1855 self.assertEqual([], warnings)
1856
1857
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191858class NewHeaderWithoutGnChangeTest(unittest.TestCase):
1859 def testAddHeaderWithoutGn(self):
1860 mock_input_api = MockInputApi()
1861 mock_input_api.files = [
1862 MockAffectedFile('base/stuff.h', ''),
1863 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361864 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191865 mock_input_api, MockOutputApi())
1866 self.assertEqual(1, len(warnings))
1867 self.assertTrue('base/stuff.h' in warnings[0].items)
1868
1869 def testModifyHeader(self):
1870 mock_input_api = MockInputApi()
1871 mock_input_api.files = [
1872 MockAffectedFile('base/stuff.h', '', action='M'),
1873 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361874 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191875 mock_input_api, MockOutputApi())
1876 self.assertEqual(0, len(warnings))
1877
1878 def testDeleteHeader(self):
1879 mock_input_api = MockInputApi()
1880 mock_input_api.files = [
1881 MockAffectedFile('base/stuff.h', '', action='D'),
1882 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361883 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191884 mock_input_api, MockOutputApi())
1885 self.assertEqual(0, len(warnings))
1886
1887 def testAddHeaderWithGn(self):
1888 mock_input_api = MockInputApi()
1889 mock_input_api.files = [
1890 MockAffectedFile('base/stuff.h', ''),
1891 MockAffectedFile('base/BUILD.gn', 'stuff.h'),
1892 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361893 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191894 mock_input_api, MockOutputApi())
1895 self.assertEqual(0, len(warnings))
1896
1897 def testAddHeaderWithGni(self):
1898 mock_input_api = MockInputApi()
1899 mock_input_api.files = [
1900 MockAffectedFile('base/stuff.h', ''),
1901 MockAffectedFile('base/files.gni', 'stuff.h'),
1902 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361903 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191904 mock_input_api, MockOutputApi())
1905 self.assertEqual(0, len(warnings))
1906
1907 def testAddHeaderWithOther(self):
1908 mock_input_api = MockInputApi()
1909 mock_input_api.files = [
1910 MockAffectedFile('base/stuff.h', ''),
1911 MockAffectedFile('base/stuff.cc', 'stuff.h'),
1912 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361913 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191914 mock_input_api, MockOutputApi())
1915 self.assertEqual(1, len(warnings))
1916
1917 def testAddHeaderWithWrongGn(self):
1918 mock_input_api = MockInputApi()
1919 mock_input_api.files = [
1920 MockAffectedFile('base/stuff.h', ''),
1921 MockAffectedFile('base/BUILD.gn', 'stuff_h'),
1922 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361923 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191924 mock_input_api, MockOutputApi())
1925 self.assertEqual(1, len(warnings))
1926
1927 def testAddHeadersWithGn(self):
1928 mock_input_api = MockInputApi()
1929 mock_input_api.files = [
1930 MockAffectedFile('base/stuff.h', ''),
1931 MockAffectedFile('base/another.h', ''),
1932 MockAffectedFile('base/BUILD.gn', 'another.h\nstuff.h'),
1933 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361934 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191935 mock_input_api, MockOutputApi())
1936 self.assertEqual(0, len(warnings))
1937
1938 def testAddHeadersWithWrongGn(self):
1939 mock_input_api = MockInputApi()
1940 mock_input_api.files = [
1941 MockAffectedFile('base/stuff.h', ''),
1942 MockAffectedFile('base/another.h', ''),
1943 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff.h'),
1944 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361945 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191946 mock_input_api, MockOutputApi())
1947 self.assertEqual(1, len(warnings))
1948 self.assertFalse('base/stuff.h' in warnings[0].items)
1949 self.assertTrue('base/another.h' in warnings[0].items)
1950
1951 def testAddHeadersWithWrongGn2(self):
1952 mock_input_api = MockInputApi()
1953 mock_input_api.files = [
1954 MockAffectedFile('base/stuff.h', ''),
1955 MockAffectedFile('base/another.h', ''),
1956 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff_h'),
1957 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361958 warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191959 mock_input_api, MockOutputApi())
1960 self.assertEqual(1, len(warnings))
1961 self.assertTrue('base/stuff.h' in warnings[0].items)
1962 self.assertTrue('base/another.h' in warnings[0].items)
1963
1964
Michael Giuffridad3bc8672018-10-25 22:48:021965class CorrectProductNameInMessagesTest(unittest.TestCase):
1966 def testProductNameInDesc(self):
1967 mock_input_api = MockInputApi()
1968 mock_input_api.files = [
1969 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
1970 '<message name="Foo" desc="Welcome to Chrome">',
1971 ' Welcome to Chrome!',
1972 '</message>',
1973 ]),
1974 MockAffectedFile('chrome/app/chromium_strings.grd', [
1975 '<message name="Bar" desc="Welcome to Chrome">',
1976 ' Welcome to Chromium!',
1977 '</message>',
1978 ]),
1979 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361980 warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
Michael Giuffridad3bc8672018-10-25 22:48:021981 mock_input_api, MockOutputApi())
1982 self.assertEqual(0, len(warnings))
1983
1984 def testChromeInChromium(self):
1985 mock_input_api = MockInputApi()
1986 mock_input_api.files = [
1987 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
1988 '<message name="Foo" desc="Welcome to Chrome">',
1989 ' Welcome to Chrome!',
1990 '</message>',
1991 ]),
1992 MockAffectedFile('chrome/app/chromium_strings.grd', [
1993 '<message name="Bar" desc="Welcome to Chrome">',
1994 ' Welcome to Chrome!',
1995 '</message>',
1996 ]),
1997 ]
Saagar Sanghavifceeaae2020-08-12 16:40:361998 warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
Michael Giuffridad3bc8672018-10-25 22:48:021999 mock_input_api, MockOutputApi())
2000 self.assertEqual(1, len(warnings))
2001 self.assertTrue('chrome/app/chromium_strings.grd' in warnings[0].items[0])
2002
2003 def testChromiumInChrome(self):
2004 mock_input_api = MockInputApi()
2005 mock_input_api.files = [
2006 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
2007 '<message name="Foo" desc="Welcome to Chrome">',
2008 ' Welcome to Chromium!',
2009 '</message>',
2010 ]),
2011 MockAffectedFile('chrome/app/chromium_strings.grd', [
2012 '<message name="Bar" desc="Welcome to Chrome">',
2013 ' Welcome to Chromium!',
2014 '</message>',
2015 ]),
2016 ]
Saagar Sanghavifceeaae2020-08-12 16:40:362017 warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
Michael Giuffridad3bc8672018-10-25 22:48:022018 mock_input_api, MockOutputApi())
2019 self.assertEqual(1, len(warnings))
2020 self.assertTrue(
2021 'chrome/app/google_chrome_strings.grd:2' in warnings[0].items[0])
2022
2023 def testMultipleInstances(self):
2024 mock_input_api = MockInputApi()
2025 mock_input_api.files = [
2026 MockAffectedFile('chrome/app/chromium_strings.grd', [
2027 '<message name="Bar" desc="Welcome to Chrome">',
2028 ' Welcome to Chrome!',
2029 '</message>',
2030 '<message name="Baz" desc="A correct message">',
2031 ' Chromium is the software you are using.',
2032 '</message>',
2033 '<message name="Bat" desc="An incorrect message">',
2034 ' Google Chrome is the software you are using.',
2035 '</message>',
2036 ]),
2037 ]
Saagar Sanghavifceeaae2020-08-12 16:40:362038 warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
Michael Giuffridad3bc8672018-10-25 22:48:022039 mock_input_api, MockOutputApi())
2040 self.assertEqual(1, len(warnings))
2041 self.assertTrue(
2042 'chrome/app/chromium_strings.grd:2' in warnings[0].items[0])
2043 self.assertTrue(
2044 'chrome/app/chromium_strings.grd:8' in warnings[0].items[1])
2045
2046 def testMultipleWarnings(self):
2047 mock_input_api = MockInputApi()
2048 mock_input_api.files = [
2049 MockAffectedFile('chrome/app/chromium_strings.grd', [
2050 '<message name="Bar" desc="Welcome to Chrome">',
2051 ' Welcome to Chrome!',
2052 '</message>',
2053 '<message name="Baz" desc="A correct message">',
2054 ' Chromium is the software you are using.',
2055 '</message>',
2056 '<message name="Bat" desc="An incorrect message">',
2057 ' Google Chrome is the software you are using.',
2058 '</message>',
2059 ]),
2060 MockAffectedFile('components/components_google_chrome_strings.grd', [
2061 '<message name="Bar" desc="Welcome to Chrome">',
2062 ' Welcome to Chrome!',
2063 '</message>',
2064 '<message name="Baz" desc="A correct message">',
2065 ' Chromium is the software you are using.',
2066 '</message>',
2067 '<message name="Bat" desc="An incorrect message">',
2068 ' Google Chrome is the software you are using.',
2069 '</message>',
2070 ]),
2071 ]
Saagar Sanghavifceeaae2020-08-12 16:40:362072 warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
Michael Giuffridad3bc8672018-10-25 22:48:022073 mock_input_api, MockOutputApi())
2074 self.assertEqual(2, len(warnings))
2075 self.assertTrue(
2076 'components/components_google_chrome_strings.grd:5'
2077 in warnings[0].items[0])
2078 self.assertTrue(
2079 'chrome/app/chromium_strings.grd:2' in warnings[1].items[0])
2080 self.assertTrue(
2081 'chrome/app/chromium_strings.grd:8' in warnings[1].items[1])
2082
2083
Ken Rockot9f668262018-12-21 18:56:362084class ServiceManifestOwnerTest(unittest.TestCase):
Ken Rockot9f668262018-12-21 18:56:362085 def testServiceManifestChangeNeedsSecurityOwner(self):
2086 mock_input_api = MockInputApi()
2087 mock_input_api.files = [
2088 MockAffectedFile('services/goat/public/cpp/manifest.cc',
2089 [
2090 '#include "services/goat/public/cpp/manifest.h"',
2091 'const service_manager::Manifest& GetManifest() {}',
2092 ])]
2093 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:362094 errors = PRESUBMIT.CheckSecurityOwners(
Ken Rockot9f668262018-12-21 18:56:362095 mock_input_api, mock_output_api)
2096 self.assertEqual(1, len(errors))
2097 self.assertEqual(
2098 'Found OWNERS files that need to be updated for IPC security review ' +
2099 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
2100
2101 def testNonServiceManifestSourceChangesDoNotRequireSecurityOwner(self):
2102 mock_input_api = MockInputApi()
2103 mock_input_api.files = [
2104 MockAffectedFile('some/non/service/thing/foo_manifest.cc',
2105 [
2106 'const char kNoEnforcement[] = "not a manifest!";',
2107 ])]
2108 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:362109 errors = PRESUBMIT.CheckSecurityOwners(
Wez17c66962020-04-29 15:26:032110 mock_input_api, mock_output_api)
2111 self.assertEqual([], errors)
2112
2113
2114class FuchsiaSecurityOwnerTest(unittest.TestCase):
2115 def testFidlChangeNeedsSecurityOwner(self):
2116 mock_input_api = MockInputApi()
2117 mock_input_api.files = [
2118 MockAffectedFile('potentially/scary/ipc.fidl',
2119 [
2120 'library test.fidl'
2121 ])]
2122 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:362123 errors = PRESUBMIT.CheckSecurityOwners(
Wez17c66962020-04-29 15:26:032124 mock_input_api, mock_output_api)
2125 self.assertEqual(1, len(errors))
2126 self.assertEqual(
2127 'Found OWNERS files that need to be updated for IPC security review ' +
2128 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
2129
2130 def testComponentManifestV1ChangeNeedsSecurityOwner(self):
2131 mock_input_api = MockInputApi()
2132 mock_input_api.files = [
2133 MockAffectedFile('potentially/scary/v2_manifest.cmx',
2134 [
2135 '{ "that is no": "manifest!" }'
2136 ])]
2137 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:362138 errors = PRESUBMIT.CheckSecurityOwners(
Wez17c66962020-04-29 15:26:032139 mock_input_api, mock_output_api)
2140 self.assertEqual(1, len(errors))
2141 self.assertEqual(
2142 'Found OWNERS files that need to be updated for IPC security review ' +
2143 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
2144
2145 def testComponentManifestV2NeedsSecurityOwner(self):
2146 mock_input_api = MockInputApi()
2147 mock_input_api.files = [
2148 MockAffectedFile('potentially/scary/v2_manifest.cml',
2149 [
2150 '{ "that is no": "manifest!" }'
2151 ])]
2152 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:362153 errors = PRESUBMIT.CheckSecurityOwners(
Wez17c66962020-04-29 15:26:032154 mock_input_api, mock_output_api)
2155 self.assertEqual(1, len(errors))
2156 self.assertEqual(
2157 'Found OWNERS files that need to be updated for IPC security review ' +
2158 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
2159
Joshua Peraza1ca6d392020-12-08 00:14:092160 def testThirdPartyTestsDoNotRequireSecurityOwner(self):
2161 mock_input_api = MockInputApi()
2162 mock_input_api.files = [
2163 MockAffectedFile('third_party/crashpad/test/tests.cmx',
2164 [
2165 'const char kNoEnforcement[] = "Security?!? Pah!";',
2166 ])]
2167 mock_output_api = MockOutputApi()
2168 errors = PRESUBMIT.CheckSecurityOwners(
2169 mock_input_api, mock_output_api)
2170 self.assertEqual([], errors)
2171
Wez17c66962020-04-29 15:26:032172 def testOtherFuchsiaChangesDoNotRequireSecurityOwner(self):
2173 mock_input_api = MockInputApi()
2174 mock_input_api.files = [
2175 MockAffectedFile('some/non/service/thing/fuchsia_fidl_cml_cmx_magic.cc',
2176 [
2177 'const char kNoEnforcement[] = "Security?!? Pah!";',
2178 ])]
2179 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:362180 errors = PRESUBMIT.CheckSecurityOwners(
Ken Rockot9f668262018-12-21 18:56:362181 mock_input_api, mock_output_api)
2182 self.assertEqual([], errors)
2183
Daniel Cheng13ca61a882017-08-25 15:11:252184
Robert Sesek2c905332020-05-06 23:17:132185class SecurityChangeTest(unittest.TestCase):
Edward Lesmes1e9fade2021-02-08 20:31:122186 class _MockOwnersClient(object):
2187 def ListOwners(self, f):
Robert Sesek2c905332020-05-06 23:17:132188 return ['[email protected]', '[email protected]']
2189
2190 def _mockChangeOwnerAndReviewers(self, input_api, owner, reviewers):
2191 def __MockOwnerAndReviewers(input_api, email_regexp, approval_needed=False):
2192 return [owner, reviewers]
2193 input_api.canned_checks.GetCodereviewOwnerAndReviewers = \
2194 __MockOwnerAndReviewers
2195
Alex Goughbc964dd2020-06-15 17:52:372196 def testDiffGetServiceSandboxType(self):
Robert Sesek2c905332020-05-06 23:17:132197 mock_input_api = MockInputApi()
2198 mock_input_api.files = [
2199 MockAffectedFile(
2200 'services/goat/teleporter_host.cc',
2201 [
Alex Goughbc964dd2020-06-15 17:52:372202 'template <>',
2203 'inline content::SandboxType',
2204 'content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {',
2205 '#if defined(OS_WIN)',
2206 ' return SandboxType::kGoaty;',
2207 '#else',
2208 ' return SandboxType::kNoSandbox;',
2209 '#endif // !defined(OS_WIN)',
2210 '}'
Robert Sesek2c905332020-05-06 23:17:132211 ]
2212 ),
2213 ]
2214 files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
2215 mock_input_api)
2216 self.assertEqual({
2217 'services/goat/teleporter_host.cc': set([
Alex Goughbc964dd2020-06-15 17:52:372218 'content::GetServiceSandboxType<>()'
Robert Sesek2c905332020-05-06 23:17:132219 ])},
2220 files_to_functions)
2221
2222 def testDiffRemovingLine(self):
2223 mock_input_api = MockInputApi()
2224 mock_file = MockAffectedFile('services/goat/teleporter_host.cc', '')
2225 mock_file._scm_diff = """--- old 2020-05-04 14:08:25.000000000 -0400
2226+++ new 2020-05-04 14:08:32.000000000 -0400
2227@@ -1,5 +1,4 @@
Alex Goughbc964dd2020-06-15 17:52:372228 template <>
2229 inline content::SandboxType
2230-content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {
2231 #if defined(OS_WIN)
2232 return SandboxType::kGoaty;
Robert Sesek2c905332020-05-06 23:17:132233"""
2234 mock_input_api.files = [mock_file]
2235 files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
2236 mock_input_api)
2237 self.assertEqual({
2238 'services/goat/teleporter_host.cc': set([
Alex Goughbc964dd2020-06-15 17:52:372239 'content::GetServiceSandboxType<>()'
Robert Sesek2c905332020-05-06 23:17:132240 ])},
2241 files_to_functions)
2242
2243 def testChangeOwnersMissing(self):
2244 mock_input_api = MockInputApi()
Edward Lesmes1e9fade2021-02-08 20:31:122245 mock_input_api.owners_client = self._MockOwnersClient()
Robert Sesek2c905332020-05-06 23:17:132246 mock_input_api.is_committing = False
2247 mock_input_api.files = [
Alex Goughbc964dd2020-06-15 17:52:372248 MockAffectedFile('file.cc', ['GetServiceSandboxType<Goat>(Sandbox)'])
Robert Sesek2c905332020-05-06 23:17:132249 ]
2250 mock_output_api = MockOutputApi()
2251 self._mockChangeOwnerAndReviewers(
2252 mock_input_api, '[email protected]', ['[email protected]'])
Saagar Sanghavifceeaae2020-08-12 16:40:362253 result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
Robert Sesek2c905332020-05-06 23:17:132254 self.assertEquals(1, len(result))
2255 self.assertEquals(result[0].type, 'notify')
2256 self.assertEquals(result[0].message,
2257 'The following files change calls to security-sensive functions\n' \
2258 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
2259 ' file.cc\n'
Alex Goughbc964dd2020-06-15 17:52:372260 ' content::GetServiceSandboxType<>()\n\n')
Robert Sesek2c905332020-05-06 23:17:132261
2262 def testChangeOwnersMissingAtCommit(self):
2263 mock_input_api = MockInputApi()
Edward Lesmes1e9fade2021-02-08 20:31:122264 mock_input_api.owners_client = self._MockOwnersClient()
Robert Sesek2c905332020-05-06 23:17:132265 mock_input_api.is_committing = True
2266 mock_input_api.files = [
Alex Goughbc964dd2020-06-15 17:52:372267 MockAffectedFile('file.cc', ['GetServiceSandboxType<mojom::Goat>()'])
Robert Sesek2c905332020-05-06 23:17:132268 ]
2269 mock_output_api = MockOutputApi()
2270 self._mockChangeOwnerAndReviewers(
2271 mock_input_api, '[email protected]', ['[email protected]'])
Saagar Sanghavifceeaae2020-08-12 16:40:362272 result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
Robert Sesek2c905332020-05-06 23:17:132273 self.assertEquals(1, len(result))
2274 self.assertEquals(result[0].type, 'error')
2275 self.assertEquals(result[0].message,
2276 'The following files change calls to security-sensive functions\n' \
2277 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
2278 ' file.cc\n'
Alex Goughbc964dd2020-06-15 17:52:372279 ' content::GetServiceSandboxType<>()\n\n')
Robert Sesek2c905332020-05-06 23:17:132280
2281 def testChangeOwnersPresent(self):
2282 mock_input_api = MockInputApi()
Edward Lesmes1e9fade2021-02-08 20:31:122283 mock_input_api.owners_client = self._MockOwnersClient()
Robert Sesek2c905332020-05-06 23:17:132284 mock_input_api.files = [
2285 MockAffectedFile('file.cc', ['WithSandboxType(Sandbox)'])
2286 ]
2287 mock_output_api = MockOutputApi()
2288 self._mockChangeOwnerAndReviewers(
2289 mock_input_api, '[email protected]',
2290 ['[email protected]', '[email protected]'])
Saagar Sanghavifceeaae2020-08-12 16:40:362291 result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
Robert Sesek2c905332020-05-06 23:17:132292 self.assertEquals(0, len(result))
2293
2294 def testChangeOwnerIsSecurityOwner(self):
2295 mock_input_api = MockInputApi()
Edward Lesmes1e9fade2021-02-08 20:31:122296 mock_input_api.owners_client = self._MockOwnersClient()
Robert Sesek2c905332020-05-06 23:17:132297 mock_input_api.files = [
Alex Goughbc964dd2020-06-15 17:52:372298 MockAffectedFile('file.cc', ['GetServiceSandboxType<T>(Sandbox)'])
Robert Sesek2c905332020-05-06 23:17:132299 ]
2300 mock_output_api = MockOutputApi()
2301 self._mockChangeOwnerAndReviewers(
2302 mock_input_api, '[email protected]', ['[email protected]'])
Saagar Sanghavifceeaae2020-08-12 16:40:362303 result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
Robert Sesek2c905332020-05-06 23:17:132304 self.assertEquals(1, len(result))
2305
2306
Mario Sanchez Prada2472cab2019-09-18 10:58:312307class BannedTypeCheckTest(unittest.TestCase):
Sylvain Defresnea8b73d252018-02-28 15:45:542308
Peter Kasting94a56c42019-10-25 21:54:042309 def testBannedCppFunctions(self):
2310 input_api = MockInputApi()
2311 input_api.files = [
2312 MockFile('some/cpp/problematic/file.cc',
2313 ['using namespace std;']),
Oksana Zhuravlovac8222d22019-12-19 19:21:162314 MockFile('third_party/blink/problematic/file.cc',
2315 ['GetInterfaceProvider()']),
Peter Kasting94a56c42019-10-25 21:54:042316 MockFile('some/cpp/ok/file.cc',
2317 ['using std::string;']),
Allen Bauer53b43fb12020-03-12 17:21:472318 MockFile('some/cpp/problematic/file2.cc',
2319 ['set_owned_by_client()']),
danakjd18e8892020-12-17 17:42:012320 MockFile('some/cpp/nocheck/file.cc',
2321 ['using namespace std; // nocheck']),
2322 MockFile('some/cpp/comment/file.cc',
2323 [' // A comment about `using namespace std;`']),
Peter Kasting94a56c42019-10-25 21:54:042324 ]
2325
Saagar Sanghavifceeaae2020-08-12 16:40:362326 results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
Oksana Zhuravlovac8222d22019-12-19 19:21:162327
2328 # warnings are results[0], errors are results[1]
2329 self.assertEqual(2, len(results))
2330 self.assertTrue('some/cpp/problematic/file.cc' in results[1].message)
2331 self.assertTrue(
2332 'third_party/blink/problematic/file.cc' in results[0].message)
2333 self.assertTrue('some/cpp/ok/file.cc' not in results[1].message)
Allen Bauer53b43fb12020-03-12 17:21:472334 self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
danakjd18e8892020-12-17 17:42:012335 self.assertFalse('some/cpp/nocheck/file.cc' in results[0].message)
2336 self.assertFalse('some/cpp/nocheck/file.cc' in results[1].message)
2337 self.assertFalse('some/cpp/comment/file.cc' in results[0].message)
2338 self.assertFalse('some/cpp/comment/file.cc' in results[1].message)
Peter Kasting94a56c42019-10-25 21:54:042339
Peter K. Lee6c03ccff2019-07-15 14:40:052340 def testBannedIosObjcFunctions(self):
Sylvain Defresnea8b73d252018-02-28 15:45:542341 input_api = MockInputApi()
2342 input_api.files = [
2343 MockFile('some/ios/file.mm',
2344 ['TEST(SomeClassTest, SomeInteraction) {',
2345 '}']),
2346 MockFile('some/mac/file.mm',
2347 ['TEST(SomeClassTest, SomeInteraction) {',
2348 '}']),
2349 MockFile('another/ios_file.mm',
2350 ['class SomeTest : public testing::Test {};']),
Peter K. Lee6c03ccff2019-07-15 14:40:052351 MockFile('some/ios/file_egtest.mm',
2352 ['- (void)testSomething { EXPECT_OCMOCK_VERIFY(aMock); }']),
2353 MockFile('some/ios/file_unittest.mm',
2354 ['TEST_F(SomeTest, TestThis) { EXPECT_OCMOCK_VERIFY(aMock); }']),
Sylvain Defresnea8b73d252018-02-28 15:45:542355 ]
2356
Saagar Sanghavifceeaae2020-08-12 16:40:362357 errors = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
Sylvain Defresnea8b73d252018-02-28 15:45:542358 self.assertEqual(1, len(errors))
2359 self.assertTrue('some/ios/file.mm' in errors[0].message)
2360 self.assertTrue('another/ios_file.mm' in errors[0].message)
2361 self.assertTrue('some/mac/file.mm' not in errors[0].message)
Peter K. Lee6c03ccff2019-07-15 14:40:052362 self.assertTrue('some/ios/file_egtest.mm' in errors[0].message)
2363 self.assertTrue('some/ios/file_unittest.mm' not in errors[0].message)
Sylvain Defresnea8b73d252018-02-28 15:45:542364
Carlos Knippschildab192b8c2019-04-08 20:02:382365 def testBannedMojoFunctions(self):
2366 input_api = MockInputApi()
2367 input_api.files = [
Oksana Zhuravlovafd247772019-05-16 16:57:292368 MockFile('some/cpp/problematic/file2.cc',
2369 ['mojo::ConvertTo<>']),
Oksana Zhuravlovafd247772019-05-16 16:57:292370 MockFile('third_party/blink/ok/file3.cc',
2371 ['mojo::ConvertTo<>']),
2372 MockFile('content/renderer/ok/file3.cc',
2373 ['mojo::ConvertTo<>']),
Carlos Knippschildab192b8c2019-04-08 20:02:382374 ]
2375
Saagar Sanghavifceeaae2020-08-12 16:40:362376 results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
Oksana Zhuravlova1d3b59de2019-05-17 00:08:222377
2378 # warnings are results[0], errors are results[1]
Robert Sesek351d2d52021-02-02 01:47:072379 self.assertEqual(1, len(results))
Oksana Zhuravlova1d3b59de2019-05-17 00:08:222380 self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
Oksana Zhuravlova1d3b59de2019-05-17 00:08:222381 self.assertTrue('third_party/blink/ok/file3.cc' not in results[0].message)
2382 self.assertTrue('content/renderer/ok/file3.cc' not in results[0].message)
Carlos Knippschildab192b8c2019-04-08 20:02:382383
Mario Sanchez Prada2472cab2019-09-18 10:58:312384 def testDeprecatedMojoTypes(self):
Mario Sanchez Pradacec9cef2019-12-15 11:54:572385 ok_paths = ['components/arc']
2386 warning_paths = ['some/cpp']
Mario Sanchez Pradaaab91382019-12-19 08:57:092387 error_paths = ['third_party/blink', 'content']
Mario Sanchez Prada2472cab2019-09-18 10:58:312388 test_cases = [
2389 {
2390 'type': 'mojo::AssociatedBinding<>;',
2391 'file': 'file1.c'
2392 },
2393 {
2394 'type': 'mojo::AssociatedBindingSet<>;',
2395 'file': 'file2.c'
2396 },
2397 {
2398 'type': 'mojo::AssociatedInterfacePtr<>',
2399 'file': 'file3.cc'
2400 },
2401 {
2402 'type': 'mojo::AssociatedInterfacePtrInfo<>',
2403 'file': 'file4.cc'
2404 },
2405 {
2406 'type': 'mojo::AssociatedInterfaceRequest<>',
2407 'file': 'file5.cc'
2408 },
2409 {
2410 'type': 'mojo::Binding<>',
2411 'file': 'file6.cc'
2412 },
2413 {
2414 'type': 'mojo::BindingSet<>',
2415 'file': 'file7.cc'
2416 },
2417 {
2418 'type': 'mojo::InterfacePtr<>',
2419 'file': 'file8.cc'
2420 },
2421 {
2422 'type': 'mojo::InterfacePtrInfo<>',
2423 'file': 'file9.cc'
2424 },
2425 {
2426 'type': 'mojo::InterfaceRequest<>',
2427 'file': 'file10.cc'
2428 },
2429 {
2430 'type': 'mojo::MakeRequest()',
2431 'file': 'file11.cc'
2432 },
2433 {
2434 'type': 'mojo::MakeRequestAssociatedWithDedicatedPipe()',
2435 'file': 'file12.cc'
2436 },
2437 {
2438 'type': 'mojo::MakeStrongBinding()<>',
2439 'file': 'file13.cc'
2440 },
2441 {
2442 'type': 'mojo::MakeStrongAssociatedBinding()<>',
2443 'file': 'file14.cc'
2444 },
2445 {
Gyuyoung Kim4952ba62020-07-07 07:33:442446 'type': 'mojo::StrongAssociatedBinding<>',
Mario Sanchez Prada2472cab2019-09-18 10:58:312447 'file': 'file15.cc'
2448 },
2449 {
Gyuyoung Kim4952ba62020-07-07 07:33:442450 'type': 'mojo::StrongBinding<>',
Mario Sanchez Prada2472cab2019-09-18 10:58:312451 'file': 'file16.cc'
2452 },
Gyuyoung Kim4952ba62020-07-07 07:33:442453 {
2454 'type': 'mojo::StrongAssociatedBindingSet<>',
2455 'file': 'file17.cc'
2456 },
2457 {
2458 'type': 'mojo::StrongBindingSet<>',
2459 'file': 'file18.cc'
2460 },
Mario Sanchez Prada2472cab2019-09-18 10:58:312461 ]
2462
2463 # Build the list of MockFiles considering paths that should trigger warnings
Mario Sanchez Pradacec9cef2019-12-15 11:54:572464 # as well as paths that should trigger errors.
Mario Sanchez Prada2472cab2019-09-18 10:58:312465 input_api = MockInputApi()
2466 input_api.files = []
2467 for test_case in test_cases:
2468 for path in ok_paths:
2469 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2470 [test_case['type']]))
2471 for path in warning_paths:
2472 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2473 [test_case['type']]))
Mario Sanchez Pradacec9cef2019-12-15 11:54:572474 for path in error_paths:
2475 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2476 [test_case['type']]))
Mario Sanchez Prada2472cab2019-09-18 10:58:312477
Saagar Sanghavifceeaae2020-08-12 16:40:362478 results = PRESUBMIT.CheckNoDeprecatedMojoTypes(input_api, MockOutputApi())
Mario Sanchez Prada2472cab2019-09-18 10:58:312479
Mario Sanchez Pradacec9cef2019-12-15 11:54:572480 # warnings are results[0], errors are results[1]
2481 self.assertEqual(2, len(results))
Mario Sanchez Prada2472cab2019-09-18 10:58:312482
2483 for test_case in test_cases:
Mario Sanchez Pradacec9cef2019-12-15 11:54:572484 # Check that no warnings nor errors have been triggered for these paths.
Mario Sanchez Prada2472cab2019-09-18 10:58:312485 for path in ok_paths:
2486 self.assertFalse(path in results[0].message)
Mario Sanchez Pradacec9cef2019-12-15 11:54:572487 self.assertFalse(path in results[1].message)
Mario Sanchez Prada2472cab2019-09-18 10:58:312488
2489 # Check warnings have been triggered for these paths.
2490 for path in warning_paths:
2491 self.assertTrue(path in results[0].message)
Mario Sanchez Pradacec9cef2019-12-15 11:54:572492 self.assertFalse(path in results[1].message)
2493
2494 # Check errors have been triggered for these paths.
2495 for path in error_paths:
2496 self.assertFalse(path in results[0].message)
2497 self.assertTrue(path in results[1].message)
Mario Sanchez Prada2472cab2019-09-18 10:58:312498
Sylvain Defresnea8b73d252018-02-28 15:45:542499
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272500class NoProductionCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozekf01ed502018-03-16 19:38:242501 def testTruePositives(self):
2502 mock_input_api = MockInputApi()
2503 mock_input_api.files = [
2504 MockFile('some/path/foo.cc', ['foo_for_testing();']),
2505 MockFile('some/path/foo.mm', ['FooForTesting();']),
2506 MockFile('some/path/foo.cxx', ['FooForTests();']),
2507 MockFile('some/path/foo.cpp', ['foo_for_test();']),
2508 ]
2509
Saagar Sanghavifceeaae2020-08-12 16:40:362510 results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
Vaclav Brozekf01ed502018-03-16 19:38:242511 mock_input_api, MockOutputApi())
2512 self.assertEqual(1, len(results))
2513 self.assertEqual(4, len(results[0].items))
2514 self.assertTrue('foo.cc' in results[0].items[0])
2515 self.assertTrue('foo.mm' in results[0].items[1])
2516 self.assertTrue('foo.cxx' in results[0].items[2])
2517 self.assertTrue('foo.cpp' in results[0].items[3])
2518
2519 def testFalsePositives(self):
2520 mock_input_api = MockInputApi()
2521 mock_input_api.files = [
2522 MockFile('some/path/foo.h', ['foo_for_testing();']),
2523 MockFile('some/path/foo.mm', ['FooForTesting() {']),
2524 MockFile('some/path/foo.cc', ['::FooForTests();']),
2525 MockFile('some/path/foo.cpp', ['// foo_for_test();']),
2526 ]
2527
Saagar Sanghavifceeaae2020-08-12 16:40:362528 results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
Vaclav Brozekf01ed502018-03-16 19:38:242529 mock_input_api, MockOutputApi())
2530 self.assertEqual(0, len(results))
2531
2532
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272533class NoProductionJavaCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozek7dbc28c2018-03-27 08:35:232534 def testTruePositives(self):
2535 mock_input_api = MockInputApi()
2536 mock_input_api.files = [
2537 MockFile('dir/java/src/foo.java', ['FooForTesting();']),
2538 MockFile('dir/java/src/bar.java', ['FooForTests(x);']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392539 MockFile('dir/java/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:232540 MockFile('dir/java/src/mult.java', [
2541 'int x = SomethingLongHere()',
2542 ' * SomethingLongHereForTesting();'
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392543 ])
Vaclav Brozek7dbc28c2018-03-27 08:35:232544 ]
2545
Saagar Sanghavifceeaae2020-08-12 16:40:362546 results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctionsJava(
Vaclav Brozek7dbc28c2018-03-27 08:35:232547 mock_input_api, MockOutputApi())
2548 self.assertEqual(1, len(results))
2549 self.assertEqual(4, len(results[0].items))
2550 self.assertTrue('foo.java' in results[0].items[0])
2551 self.assertTrue('bar.java' in results[0].items[1])
2552 self.assertTrue('baz.java' in results[0].items[2])
2553 self.assertTrue('mult.java' in results[0].items[3])
2554
2555 def testFalsePositives(self):
2556 mock_input_api = MockInputApi()
2557 mock_input_api.files = [
2558 MockFile('dir/java/src/foo.xml', ['FooForTesting();']),
2559 MockFile('dir/java/src/foo.java', ['FooForTests() {']),
2560 MockFile('dir/java/src/bar.java', ['// FooForTest();']),
2561 MockFile('dir/java/src/bar2.java', ['x = 1; // FooForTest();']),
Sky Malice9e6d6032020-10-15 22:49:552562 MockFile('dir/java/src/bar3.java', ['@VisibleForTesting']),
2563 MockFile('dir/java/src/bar4.java', ['@VisibleForTesting()']),
2564 MockFile('dir/java/src/bar5.java', [
2565 '@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)'
2566 ]),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392567 MockFile('dir/javatests/src/baz.java', ['FooForTest(', 'y', ');']),
2568 MockFile('dir/junit/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:232569 MockFile('dir/junit/src/javadoc.java', [
2570 '/** Use FooForTest(); to obtain foo in tests.'
2571 ' */'
2572 ]),
2573 MockFile('dir/junit/src/javadoc2.java', [
2574 '/** ',
2575 ' * Use FooForTest(); to obtain foo in tests.'
2576 ' */'
2577 ]),
2578 ]
2579
Saagar Sanghavifceeaae2020-08-12 16:40:362580 results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctionsJava(
Vaclav Brozek7dbc28c2018-03-27 08:35:232581 mock_input_api, MockOutputApi())
2582 self.assertEqual(0, len(results))
2583
2584
Mohamed Heikald048240a2019-11-12 16:57:372585class NewImagesWarningTest(unittest.TestCase):
2586 def testTruePositives(self):
2587 mock_input_api = MockInputApi()
2588 mock_input_api.files = [
2589 MockFile('dir/android/res/drawable/foo.png', []),
2590 MockFile('dir/android/res/drawable-v21/bar.svg', []),
2591 MockFile('dir/android/res/mipmap-v21-en/baz.webp', []),
2592 MockFile('dir/android/res_gshoe/drawable-mdpi/foobar.png', []),
2593 ]
2594
2595 results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
2596 self.assertEqual(1, len(results))
2597 self.assertEqual(4, len(results[0].items))
2598 self.assertTrue('foo.png' in results[0].items[0].LocalPath())
2599 self.assertTrue('bar.svg' in results[0].items[1].LocalPath())
2600 self.assertTrue('baz.webp' in results[0].items[2].LocalPath())
2601 self.assertTrue('foobar.png' in results[0].items[3].LocalPath())
2602
2603 def testFalsePositives(self):
2604 mock_input_api = MockInputApi()
2605 mock_input_api.files = [
2606 MockFile('dir/pngs/README.md', []),
2607 MockFile('java/test/res/drawable/foo.png', []),
2608 MockFile('third_party/blink/foo.png', []),
2609 MockFile('dir/third_party/libpng/src/foo.cc', ['foobar']),
2610 MockFile('dir/resources.webp/.gitignore', ['foo.png']),
2611 ]
2612
2613 results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
2614 self.assertEqual(0, len(results))
2615
2616
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272617class CheckUniquePtrTest(unittest.TestCase):
Vaclav Brozek851d9602018-04-04 16:13:052618 def testTruePositivesNullptr(self):
2619 mock_input_api = MockInputApi()
2620 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162621 MockFile('dir/baz.cc', ['std::unique_ptr<T>()']),
2622 MockFile('dir/baz-p.cc', ['std::unique_ptr<T<P>>()']),
Vaclav Brozek851d9602018-04-04 16:13:052623 ]
2624
Saagar Sanghavifceeaae2020-08-12 16:40:362625 results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
Vaclav Brozek851d9602018-04-04 16:13:052626 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:162627 self.assertTrue('nullptr' in results[0].message)
Vaclav Brozek851d9602018-04-04 16:13:052628 self.assertEqual(2, len(results[0].items))
2629 self.assertTrue('baz.cc' in results[0].items[0])
2630 self.assertTrue('baz-p.cc' in results[0].items[1])
2631
2632 def testTruePositivesConstructor(self):
Vaclav Brozek52e18bf2018-04-03 07:05:242633 mock_input_api = MockInputApi()
2634 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162635 MockFile('dir/foo.cc', ['return std::unique_ptr<T>(foo);']),
2636 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T>(foo)']),
2637 MockFile('dir/mult.cc', [
Vaclav Brozek95face62018-04-04 14:15:112638 'return',
2639 ' std::unique_ptr<T>(barVeryVeryLongFooSoThatItWouldNotFitAbove);'
2640 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:162641 MockFile('dir/mult2.cc', [
Vaclav Brozek95face62018-04-04 14:15:112642 'barVeryVeryLongLongBaaaaaarSoThatTheLineLimitIsAlmostReached =',
2643 ' std::unique_ptr<T>(foo);'
2644 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:162645 MockFile('dir/mult3.cc', [
Vaclav Brozek95face62018-04-04 14:15:112646 'bar = std::unique_ptr<T>(',
2647 ' fooVeryVeryVeryLongStillGoingWellThisWillTakeAWhileFinallyThere);'
2648 ]),
Vaclav Brozekb7fadb692018-08-30 06:39:532649 MockFile('dir/multi_arg.cc', [
2650 'auto p = std::unique_ptr<std::pair<T, D>>(new std::pair(T, D));']),
Vaclav Brozek52e18bf2018-04-03 07:05:242651 ]
2652
Saagar Sanghavifceeaae2020-08-12 16:40:362653 results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
Vaclav Brozek851d9602018-04-04 16:13:052654 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:162655 self.assertTrue('std::make_unique' in results[0].message)
Vaclav Brozekb7fadb692018-08-30 06:39:532656 self.assertEqual(6, len(results[0].items))
Vaclav Brozek851d9602018-04-04 16:13:052657 self.assertTrue('foo.cc' in results[0].items[0])
2658 self.assertTrue('bar.mm' in results[0].items[1])
2659 self.assertTrue('mult.cc' in results[0].items[2])
2660 self.assertTrue('mult2.cc' in results[0].items[3])
2661 self.assertTrue('mult3.cc' in results[0].items[4])
Vaclav Brozekb7fadb692018-08-30 06:39:532662 self.assertTrue('multi_arg.cc' in results[0].items[5])
Vaclav Brozek52e18bf2018-04-03 07:05:242663
2664 def testFalsePositives(self):
2665 mock_input_api = MockInputApi()
2666 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162667 MockFile('dir/foo.cc', ['return std::unique_ptr<T[]>(foo);']),
2668 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T[]>(foo)']),
2669 MockFile('dir/file.cc', ['std::unique_ptr<T> p = Foo();']),
2670 MockFile('dir/baz.cc', [
Vaclav Brozek52e18bf2018-04-03 07:05:242671 'std::unique_ptr<T> result = std::make_unique<T>();'
2672 ]),
Vaclav Brozeka54c528b2018-04-06 19:23:552673 MockFile('dir/baz2.cc', [
2674 'std::unique_ptr<T> result = std::make_unique<T>('
2675 ]),
2676 MockFile('dir/nested.cc', ['set<std::unique_ptr<T>>();']),
2677 MockFile('dir/nested2.cc', ['map<U, std::unique_ptr<T>>();']),
Vaclav Brozekb7fadb692018-08-30 06:39:532678
2679 # Two-argument invocation of std::unique_ptr is exempt because there is
2680 # no equivalent using std::make_unique.
2681 MockFile('dir/multi_arg.cc', [
2682 'auto p = std::unique_ptr<T, D>(new T(), D());']),
Vaclav Brozek52e18bf2018-04-03 07:05:242683 ]
2684
Saagar Sanghavifceeaae2020-08-12 16:40:362685 results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
Vaclav Brozek52e18bf2018-04-03 07:05:242686 self.assertEqual(0, len(results))
2687
Danil Chapovalov3518f362018-08-11 16:13:432688class CheckNoDirectIncludesHeadersWhichRedefineStrCat(unittest.TestCase):
2689 def testBlocksDirectIncludes(self):
2690 mock_input_api = MockInputApi()
2691 mock_input_api.files = [
2692 MockFile('dir/foo_win.cc', ['#include "shlwapi.h"']),
2693 MockFile('dir/bar.h', ['#include <propvarutil.h>']),
2694 MockFile('dir/baz.h', ['#include <atlbase.h>']),
2695 MockFile('dir/jumbo.h', ['#include "sphelper.h"']),
2696 ]
2697 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2698 self.assertEquals(1, len(results))
2699 self.assertEquals(4, len(results[0].items))
2700 self.assertTrue('StrCat' in results[0].message)
2701 self.assertTrue('foo_win.cc' in results[0].items[0])
2702 self.assertTrue('bar.h' in results[0].items[1])
2703 self.assertTrue('baz.h' in results[0].items[2])
2704 self.assertTrue('jumbo.h' in results[0].items[3])
2705
2706 def testAllowsToIncludeWrapper(self):
2707 mock_input_api = MockInputApi()
2708 mock_input_api.files = [
2709 MockFile('dir/baz_win.cc', ['#include "base/win/shlwapi.h"']),
2710 MockFile('dir/baz-win.h', ['#include "base/win/atl.h"']),
2711 ]
2712 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2713 self.assertEquals(0, len(results))
2714
2715 def testAllowsToCreateWrapper(self):
2716 mock_input_api = MockInputApi()
2717 mock_input_api.files = [
2718 MockFile('base/win/shlwapi.h', [
2719 '#include <shlwapi.h>',
2720 '#include "base/win/windows_defines.inc"']),
2721 ]
2722 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2723 self.assertEquals(0, len(results))
Vaclav Brozek52e18bf2018-04-03 07:05:242724
Mustafa Emre Acer51f2f742020-03-09 19:41:122725
Rainhard Findlingfc31844c52020-05-15 09:58:262726class StringTest(unittest.TestCase):
2727 """Tests ICU syntax check and translation screenshots check."""
2728
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142729 # An empty grd file.
2730 OLD_GRD_CONTENTS = """<?xml version="1.0" encoding="UTF-8"?>
2731 <grit latest_public_release="1" current_release="1">
2732 <release seq="1">
2733 <messages></messages>
2734 </release>
2735 </grit>
2736 """.splitlines()
2737 # A grd file with a single message.
2738 NEW_GRD_CONTENTS1 = """<?xml version="1.0" encoding="UTF-8"?>
2739 <grit latest_public_release="1" current_release="1">
2740 <release seq="1">
2741 <messages>
2742 <message name="IDS_TEST1">
2743 Test string 1
2744 </message>
Mustafa Emre Acere4b349c2020-06-03 23:42:482745 <message name="IDS_TEST_STRING_NON_TRANSLATEABLE1"
2746 translateable="false">
2747 Non translateable message 1, should be ignored
2748 </message>
Mustafa Emre Acered1a48962020-06-30 19:15:392749 <message name="IDS_TEST_STRING_ACCESSIBILITY"
Mustafa Emre Acerd3ca8be2020-07-07 22:35:342750 is_accessibility_with_no_ui="true">
Mustafa Emre Acered1a48962020-06-30 19:15:392751 Accessibility label 1, should be ignored
2752 </message>
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142753 </messages>
2754 </release>
2755 </grit>
2756 """.splitlines()
2757 # A grd file with two messages.
2758 NEW_GRD_CONTENTS2 = """<?xml version="1.0" encoding="UTF-8"?>
2759 <grit latest_public_release="1" current_release="1">
2760 <release seq="1">
2761 <messages>
2762 <message name="IDS_TEST1">
2763 Test string 1
2764 </message>
2765 <message name="IDS_TEST2">
2766 Test string 2
2767 </message>
Mustafa Emre Acere4b349c2020-06-03 23:42:482768 <message name="IDS_TEST_STRING_NON_TRANSLATEABLE2"
2769 translateable="false">
2770 Non translateable message 2, should be ignored
2771 </message>
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142772 </messages>
2773 </release>
2774 </grit>
2775 """.splitlines()
Rainhard Findlingfc31844c52020-05-15 09:58:262776 # A grd file with one ICU syntax message without syntax errors.
2777 NEW_GRD_CONTENTS_ICU_SYNTAX_OK1 = """<?xml version="1.0" encoding="UTF-8"?>
2778 <grit latest_public_release="1" current_release="1">
2779 <release seq="1">
2780 <messages>
2781 <message name="IDS_TEST1">
2782 {NUM, plural,
2783 =1 {Test text for numeric one}
2784 other {Test text for plural with {NUM} as number}}
2785 </message>
2786 </messages>
2787 </release>
2788 </grit>
2789 """.splitlines()
2790 # A grd file with one ICU syntax message without syntax errors.
2791 NEW_GRD_CONTENTS_ICU_SYNTAX_OK2 = """<?xml version="1.0" encoding="UTF-8"?>
2792 <grit latest_public_release="1" current_release="1">
2793 <release seq="1">
2794 <messages>
2795 <message name="IDS_TEST1">
2796 {NUM, plural,
2797 =1 {Different test text for numeric one}
2798 other {Different test text for plural with {NUM} as number}}
2799 </message>
2800 </messages>
2801 </release>
2802 </grit>
2803 """.splitlines()
2804 # A grd file with one ICU syntax message with syntax errors (misses a comma).
2805 NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR = """<?xml version="1.0" encoding="UTF-8"?>
2806 <grit latest_public_release="1" current_release="1">
2807 <release seq="1">
2808 <messages>
2809 <message name="IDS_TEST1">
2810 {NUM, plural
2811 =1 {Test text for numeric one}
2812 other {Test text for plural with {NUM} as number}}
2813 </message>
2814 </messages>
2815 </release>
2816 </grit>
2817 """.splitlines()
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142818
meacerff8a9b62019-12-10 19:43:582819 OLD_GRDP_CONTENTS = (
2820 '<?xml version="1.0" encoding="utf-8"?>',
2821 '<grit-part>',
2822 '</grit-part>'
2823 )
2824
2825 NEW_GRDP_CONTENTS1 = (
2826 '<?xml version="1.0" encoding="utf-8"?>',
2827 '<grit-part>',
2828 '<message name="IDS_PART_TEST1">',
2829 'Part string 1',
2830 '</message>',
2831 '</grit-part>')
2832
2833 NEW_GRDP_CONTENTS2 = (
2834 '<?xml version="1.0" encoding="utf-8"?>',
2835 '<grit-part>',
2836 '<message name="IDS_PART_TEST1">',
2837 'Part string 1',
2838 '</message>',
2839 '<message name="IDS_PART_TEST2">',
2840 'Part string 2',
2841 '</message>',
2842 '</grit-part>')
2843
Rainhard Findlingd8d04372020-08-13 13:30:092844 NEW_GRDP_CONTENTS3 = (
2845 '<?xml version="1.0" encoding="utf-8"?>',
2846 '<grit-part>',
2847 '<message name="IDS_PART_TEST1" desc="Description with typo.">',
2848 'Part string 1',
2849 '</message>',
2850 '</grit-part>')
2851
2852 NEW_GRDP_CONTENTS4 = (
2853 '<?xml version="1.0" encoding="utf-8"?>',
2854 '<grit-part>',
2855 '<message name="IDS_PART_TEST1" desc="Description with typo fixed.">',
2856 'Part string 1',
2857 '</message>',
2858 '</grit-part>')
2859
Rainhard Findling1a3e71e2020-09-21 07:33:352860 NEW_GRDP_CONTENTS5 = (
2861 '<?xml version="1.0" encoding="utf-8"?>',
2862 '<grit-part>',
2863 '<message name="IDS_PART_TEST1" meaning="Meaning with typo.">',
2864 'Part string 1',
2865 '</message>',
2866 '</grit-part>')
2867
2868 NEW_GRDP_CONTENTS6 = (
2869 '<?xml version="1.0" encoding="utf-8"?>',
2870 '<grit-part>',
2871 '<message name="IDS_PART_TEST1" meaning="Meaning with typo fixed.">',
2872 'Part string 1',
2873 '</message>',
2874 '</grit-part>')
2875
Rainhard Findlingfc31844c52020-05-15 09:58:262876 # A grdp file with one ICU syntax message without syntax errors.
2877 NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1 = (
2878 '<?xml version="1.0" encoding="utf-8"?>',
2879 '<grit-part>',
2880 '<message name="IDS_PART_TEST1">',
2881 '{NUM, plural,',
2882 '=1 {Test text for numeric one}',
2883 'other {Test text for plural with {NUM} as number}}',
2884 '</message>',
2885 '</grit-part>')
2886 # A grdp file with one ICU syntax message without syntax errors.
2887 NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2 = (
2888 '<?xml version="1.0" encoding="utf-8"?>',
2889 '<grit-part>',
2890 '<message name="IDS_PART_TEST1">',
2891 '{NUM, plural,',
2892 '=1 {Different test text for numeric one}',
2893 'other {Different test text for plural with {NUM} as number}}',
2894 '</message>',
2895 '</grit-part>')
2896
2897 # A grdp file with one ICU syntax message with syntax errors (superfluent
2898 # whitespace).
2899 NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR = (
2900 '<?xml version="1.0" encoding="utf-8"?>',
2901 '<grit-part>',
2902 '<message name="IDS_PART_TEST1">',
2903 '{NUM, plural,',
2904 '= 1 {Test text for numeric one}',
2905 'other {Test text for plural with {NUM} as number}}',
2906 '</message>',
2907 '</grit-part>')
2908
Mustafa Emre Acerc8a012d2018-07-31 00:00:392909 DO_NOT_UPLOAD_PNG_MESSAGE = ('Do not include actual screenshots in the '
2910 'changelist. Run '
2911 'tools/translate/upload_screenshots.py to '
2912 'upload them instead:')
2913 GENERATE_SIGNATURES_MESSAGE = ('You are adding or modifying UI strings.\n'
2914 'To ensure the best translations, take '
2915 'screenshots of the relevant UI '
2916 '(https://g.co/chrome/translation) and add '
2917 'these files to your changelist:')
2918 REMOVE_SIGNATURES_MESSAGE = ('You removed strings associated with these '
2919 'files. Remove:')
Rainhard Findlingfc31844c52020-05-15 09:58:262920 ICU_SYNTAX_ERROR_MESSAGE = ('ICU syntax errors were found in the following '
2921 'strings (problems or feedback? Contact '
2922 '[email protected]):')
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142923
2924 def makeInputApi(self, files):
2925 input_api = MockInputApi()
2926 input_api.files = files
meacere7be7532019-10-02 17:41:032927 # Override os_path.exists because the presubmit uses the actual
2928 # os.path.exists.
2929 input_api.CreateMockFileInPath(
2930 [x.LocalPath() for x in input_api.AffectedFiles(include_deletes=True)])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142931 return input_api
2932
meacerff8a9b62019-12-10 19:43:582933 """ CL modified and added messages, but didn't add any screenshots."""
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142934 def testNoScreenshots(self):
meacerff8a9b62019-12-10 19:43:582935 # No new strings (file contents same). Should not warn.
2936 input_api = self.makeInputApi([
2937 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS1,
2938 self.NEW_GRD_CONTENTS1, action='M'),
2939 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS1,
2940 self.NEW_GRDP_CONTENTS1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:362941 warnings = PRESUBMIT.CheckStrings(input_api,
meacerff8a9b62019-12-10 19:43:582942 MockOutputApi())
2943 self.assertEqual(0, len(warnings))
2944
2945 # Add two new strings. Should have two warnings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142946 input_api = self.makeInputApi([
2947 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
meacerff8a9b62019-12-10 19:43:582948 self.NEW_GRD_CONTENTS1, action='M'),
2949 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
2950 self.NEW_GRDP_CONTENTS1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:362951 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142952 MockOutputApi())
2953 self.assertEqual(1, len(warnings))
2954 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acerc6ed2682020-07-07 07:24:002955 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012956 self.assertEqual([
meacerff8a9b62019-12-10 19:43:582957 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2958 os.path.join('test_grd', 'IDS_TEST2.png.sha1')],
2959 warnings[0].items)
Mustafa Emre Acer36eaad52019-11-12 23:03:342960
meacerff8a9b62019-12-10 19:43:582961 # Add four new strings. Should have four warnings.
Mustafa Emre Acerad8fb082019-11-19 04:24:212962 input_api = self.makeInputApi([
2963 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
meacerff8a9b62019-12-10 19:43:582964 self.OLD_GRD_CONTENTS, action='M'),
2965 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
2966 self.OLD_GRDP_CONTENTS, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:362967 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acerad8fb082019-11-19 04:24:212968 MockOutputApi())
2969 self.assertEqual(1, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:002970 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acerad8fb082019-11-19 04:24:212971 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:582972 self.assertEqual([
2973 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2974 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2975 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2976 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2977 ], warnings[0].items)
Mustafa Emre Acerad8fb082019-11-19 04:24:212978
Rainhard Findlingd8d04372020-08-13 13:30:092979 def testModifiedMessageDescription(self):
2980 # CL modified a message description for a message that does not yet have a
Rainhard Findling1a3e71e2020-09-21 07:33:352981 # screenshot. Should not warn.
Rainhard Findlingd8d04372020-08-13 13:30:092982 input_api = self.makeInputApi([
2983 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS3,
2984 self.NEW_GRDP_CONTENTS4, action='M')])
2985 warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findling1a3e71e2020-09-21 07:33:352986 self.assertEqual(0, len(warnings))
Rainhard Findlingd8d04372020-08-13 13:30:092987
2988 # CL modified a message description for a message that already has a
2989 # screenshot. Should not warn.
2990 input_api = self.makeInputApi([
2991 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS3,
2992 self.NEW_GRDP_CONTENTS4, action='M'),
2993 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2994 'binary', action='A')])
2995 warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
2996 self.assertEqual(0, len(warnings))
2997
Rainhard Findling1a3e71e2020-09-21 07:33:352998 def testModifiedMessageMeaning(self):
2999 # CL modified a message meaning for a message that does not yet have a
3000 # screenshot. Should warn.
3001 input_api = self.makeInputApi([
3002 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS5,
3003 self.NEW_GRDP_CONTENTS6, action='M')])
3004 warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
3005 self.assertEqual(1, len(warnings))
3006
3007 # CL modified a message meaning for a message that already has a
3008 # screenshot. Should not warn.
3009 input_api = self.makeInputApi([
3010 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS5,
3011 self.NEW_GRDP_CONTENTS6, action='M'),
3012 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3013 'binary', action='A')])
3014 warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
3015 self.assertEqual(0, len(warnings))
3016
meacerff8a9b62019-12-10 19:43:583017 def testPngAddedSha1NotAdded(self):
3018 # CL added one new message in a grd file and added the png file associated
3019 # with it, but did not add the corresponding sha1 file. This should warn
3020 # twice:
3021 # - Once for the added png file (because we don't want developers to upload
3022 # actual images)
3023 # - Once for the missing .sha1 file
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143024 input_api = self.makeInputApi([
Mustafa Emre Acerea3e57a2018-12-17 23:51:013025 MockAffectedFile(
3026 'test.grd',
3027 self.NEW_GRD_CONTENTS1,
3028 self.OLD_GRD_CONTENTS,
3029 action='M'),
3030 MockAffectedFile(
3031 os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A')
3032 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363033 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143034 MockOutputApi())
3035 self.assertEqual(2, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:003036 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143037 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:013038 self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png')],
3039 warnings[0].items)
Mustafa Emre Acerc6ed2682020-07-07 07:24:003040 self.assertEqual('error', warnings[1].type)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143041 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:013042 self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
3043 warnings[1].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143044
meacerff8a9b62019-12-10 19:43:583045 # CL added two messages (one in grd, one in grdp) and added the png files
3046 # associated with the messages, but did not add the corresponding sha1
3047 # files. This should warn twice:
3048 # - Once for the added png files (because we don't want developers to upload
3049 # actual images)
3050 # - Once for the missing .sha1 files
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143051 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583052 # Modified files:
Mustafa Emre Acer36eaad52019-11-12 23:03:343053 MockAffectedFile(
3054 'test.grd',
meacerff8a9b62019-12-10 19:43:583055 self.NEW_GRD_CONTENTS1,
Mustafa Emre Acer36eaad52019-11-12 23:03:343056 self.OLD_GRD_CONTENTS,
meacer2308d0742019-11-12 18:15:423057 action='M'),
Mustafa Emre Acer12e7fee2019-11-18 18:49:553058 MockAffectedFile(
meacerff8a9b62019-12-10 19:43:583059 'part.grdp',
3060 self.NEW_GRDP_CONTENTS1,
3061 self.OLD_GRDP_CONTENTS,
3062 action='M'),
3063 # Added files:
3064 MockAffectedFile(
3065 os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A'),
3066 MockAffectedFile(
3067 os.path.join('part_grdp', 'IDS_PART_TEST1.png'), 'binary',
3068 action='A')
Mustafa Emre Acerad8fb082019-11-19 04:24:213069 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363070 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acerad8fb082019-11-19 04:24:213071 MockOutputApi())
3072 self.assertEqual(2, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:003073 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acerad8fb082019-11-19 04:24:213074 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:583075 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png'),
3076 os.path.join('test_grd', 'IDS_TEST1.png')],
Mustafa Emre Acerad8fb082019-11-19 04:24:213077 warnings[0].items)
Mustafa Emre Acerc6ed2682020-07-07 07:24:003078 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acerad8fb082019-11-19 04:24:213079 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
meacerff8a9b62019-12-10 19:43:583080 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3081 os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
3082 warnings[1].items)
Mustafa Emre Acerad8fb082019-11-19 04:24:213083
3084 def testScreenshotsWithSha1(self):
meacerff8a9b62019-12-10 19:43:583085 # CL added four messages (two each in a grd and grdp) and their
3086 # corresponding .sha1 files. No warnings.
Mustafa Emre Acerad8fb082019-11-19 04:24:213087 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583088 # Modified files:
Mustafa Emre Acerad8fb082019-11-19 04:24:213089 MockAffectedFile(
3090 'test.grd',
3091 self.NEW_GRD_CONTENTS2,
3092 self.OLD_GRD_CONTENTS,
Mustafa Emre Acer12e7fee2019-11-18 18:49:553093 action='M'),
meacerff8a9b62019-12-10 19:43:583094 MockAffectedFile(
3095 'part.grdp',
3096 self.NEW_GRDP_CONTENTS2,
3097 self.OLD_GRDP_CONTENTS,
3098 action='M'),
3099 # Added files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013100 MockFile(
3101 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
3102 'binary',
3103 action='A'),
3104 MockFile(
3105 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
3106 'binary',
meacerff8a9b62019-12-10 19:43:583107 action='A'),
3108 MockFile(
3109 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3110 'binary',
3111 action='A'),
3112 MockFile(
3113 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
3114 'binary',
3115 action='A'),
Mustafa Emre Acerea3e57a2018-12-17 23:51:013116 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363117 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143118 MockOutputApi())
3119 self.assertEqual([], warnings)
3120
3121 def testScreenshotsRemovedWithSha1(self):
meacerff8a9b62019-12-10 19:43:583122 # Replace new contents with old contents in grd and grp files, removing
3123 # IDS_TEST1, IDS_TEST2, IDS_PART_TEST1 and IDS_PART_TEST2.
3124 # Should warn to remove the sha1 files associated with these strings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143125 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583126 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013127 MockAffectedFile(
3128 'test.grd',
meacerff8a9b62019-12-10 19:43:583129 self.OLD_GRD_CONTENTS, # new_contents
3130 self.NEW_GRD_CONTENTS2, # old_contents
Mustafa Emre Acerea3e57a2018-12-17 23:51:013131 action='M'),
meacerff8a9b62019-12-10 19:43:583132 MockAffectedFile(
3133 'part.grdp',
3134 self.OLD_GRDP_CONTENTS, # new_contents
3135 self.NEW_GRDP_CONTENTS2, # old_contents
3136 action='M'),
3137 # Unmodified files:
3138 MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
3139 MockFile(os.path.join('test_grd', 'IDS_TEST2.png.sha1'), 'binary', ''),
3140 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3141 'binary', ''),
3142 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
3143 'binary', '')
Mustafa Emre Acerea3e57a2018-12-17 23:51:013144 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363145 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143146 MockOutputApi())
3147 self.assertEqual(1, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:003148 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143149 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:013150 self.assertEqual([
meacerff8a9b62019-12-10 19:43:583151 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3152 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
Mustafa Emre Acerea3e57a2018-12-17 23:51:013153 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
3154 os.path.join('test_grd', 'IDS_TEST2.png.sha1')
3155 ], warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143156
meacerff8a9b62019-12-10 19:43:583157 # Same as above, but this time one of the .sha1 files is also removed.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143158 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583159 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013160 MockAffectedFile(
3161 'test.grd',
meacerff8a9b62019-12-10 19:43:583162 self.OLD_GRD_CONTENTS, # new_contents
3163 self.NEW_GRD_CONTENTS2, # old_contents
Mustafa Emre Acerea3e57a2018-12-17 23:51:013164 action='M'),
meacerff8a9b62019-12-10 19:43:583165 MockAffectedFile(
3166 'part.grdp',
3167 self.OLD_GRDP_CONTENTS, # new_contents
3168 self.NEW_GRDP_CONTENTS2, # old_contents
3169 action='M'),
3170 # Unmodified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013171 MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
meacerff8a9b62019-12-10 19:43:583172 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3173 'binary', ''),
3174 # Deleted files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013175 MockAffectedFile(
3176 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
3177 '',
3178 'old_contents',
meacerff8a9b62019-12-10 19:43:583179 action='D'),
3180 MockAffectedFile(
3181 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
3182 '',
3183 'old_contents',
Mustafa Emre Acerea3e57a2018-12-17 23:51:013184 action='D')
3185 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363186 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143187 MockOutputApi())
3188 self.assertEqual(1, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:003189 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143190 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:583191 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3192 os.path.join('test_grd', 'IDS_TEST1.png.sha1')
3193 ], warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143194
meacerff8a9b62019-12-10 19:43:583195 # Remove all sha1 files. There should be no warnings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143196 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583197 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013198 MockAffectedFile(
3199 'test.grd',
3200 self.OLD_GRD_CONTENTS,
3201 self.NEW_GRD_CONTENTS2,
3202 action='M'),
meacerff8a9b62019-12-10 19:43:583203 MockAffectedFile(
3204 'part.grdp',
3205 self.OLD_GRDP_CONTENTS,
3206 self.NEW_GRDP_CONTENTS2,
3207 action='M'),
3208 # Deleted files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013209 MockFile(
3210 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
3211 'binary',
3212 action='D'),
3213 MockFile(
3214 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
3215 'binary',
meacerff8a9b62019-12-10 19:43:583216 action='D'),
3217 MockFile(
3218 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3219 'binary',
3220 action='D'),
3221 MockFile(
3222 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
3223 'binary',
Mustafa Emre Acerea3e57a2018-12-17 23:51:013224 action='D')
3225 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363226 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143227 MockOutputApi())
3228 self.assertEqual([], warnings)
3229
Rainhard Findlingfc31844c52020-05-15 09:58:263230 def testIcuSyntax(self):
3231 # Add valid ICU syntax string. Should not raise an error.
3232 input_api = self.makeInputApi([
3233 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK2,
3234 self.NEW_GRD_CONTENTS1, action='M'),
3235 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2,
3236 self.NEW_GRDP_CONTENTS1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:363237 results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findlingfc31844c52020-05-15 09:58:263238 # We expect no ICU syntax errors.
3239 icu_errors = [e for e in results
3240 if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
3241 self.assertEqual(0, len(icu_errors))
3242
3243 # Valid changes in ICU syntax. Should not raise an error.
3244 input_api = self.makeInputApi([
3245 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK2,
3246 self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK1, action='M'),
3247 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2,
3248 self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:363249 results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findlingfc31844c52020-05-15 09:58:263250 # We expect no ICU syntax errors.
3251 icu_errors = [e for e in results
3252 if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
3253 self.assertEqual(0, len(icu_errors))
3254
3255 # Add invalid ICU syntax strings. Should raise two errors.
3256 input_api = self.makeInputApi([
3257 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR,
3258 self.NEW_GRD_CONTENTS1, action='M'),
3259 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR,
3260 self.NEW_GRD_CONTENTS1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:363261 results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findlingfc31844c52020-05-15 09:58:263262 # We expect 2 ICU syntax errors.
3263 icu_errors = [e for e in results
3264 if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
3265 self.assertEqual(1, len(icu_errors))
3266 self.assertEqual([
3267 'IDS_TEST1: This message looks like an ICU plural, but does not follow '
3268 'ICU syntax.',
3269 'IDS_PART_TEST1: Variant "= 1" is not valid for plural message'
3270 ], icu_errors[0].items)
3271
3272 # Change two strings to have ICU syntax errors. Should raise two errors.
3273 input_api = self.makeInputApi([
3274 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR,
3275 self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK1, action='M'),
3276 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR,
3277 self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:363278 results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findlingfc31844c52020-05-15 09:58:263279 # We expect 2 ICU syntax errors.
3280 icu_errors = [e for e in results
3281 if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
3282 self.assertEqual(1, len(icu_errors))
3283 self.assertEqual([
3284 'IDS_TEST1: This message looks like an ICU plural, but does not follow '
3285 'ICU syntax.',
3286 'IDS_PART_TEST1: Variant "= 1" is not valid for plural message'
3287 ], icu_errors[0].items)
3288
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143289
Mustafa Emre Acer51f2f742020-03-09 19:41:123290class TranslationExpectationsTest(unittest.TestCase):
3291 ERROR_MESSAGE_FORMAT = (
3292 "Failed to get a list of translatable grd files. "
3293 "This happens when:\n"
3294 " - One of the modified grd or grdp files cannot be parsed or\n"
3295 " - %s is not updated.\n"
3296 "Stack:\n"
3297 )
3298 REPO_ROOT = os.path.join('tools', 'translation', 'testdata')
3299 # This lists all .grd files under REPO_ROOT.
3300 EXPECTATIONS = os.path.join(REPO_ROOT,
3301 "translation_expectations.pyl")
3302 # This lists all .grd files under REPO_ROOT except unlisted.grd.
3303 EXPECTATIONS_WITHOUT_UNLISTED_FILE = os.path.join(
3304 REPO_ROOT, "translation_expectations_without_unlisted_file.pyl")
3305
3306 # Tests that the presubmit doesn't return when no grd or grdp files are
3307 # modified.
3308 def testExpectationsNoModifiedGrd(self):
3309 input_api = MockInputApi()
3310 input_api.files = [
3311 MockAffectedFile('not_used.txt', 'not used', 'not used', action='M')
3312 ]
3313 # Fake list of all grd files in the repo. This list is missing all grd/grdps
3314 # under tools/translation/testdata. This is OK because the presubmit won't
3315 # run in the first place since there are no modified grd/grps in input_api.
3316 grd_files = ['doesnt_exist_doesnt_matter.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363317 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123318 input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
3319 grd_files)
3320 self.assertEqual(0, len(warnings))
3321
3322
3323 # Tests that the list of files passed to the presubmit matches the list of
3324 # files in the expectations.
3325 def testExpectationsSuccess(self):
3326 # Mock input file list needs a grd or grdp file in order to run the
3327 # presubmit. The file itself doesn't matter.
3328 input_api = MockInputApi()
3329 input_api.files = [
3330 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3331 ]
3332 # List of all grd files in the repo.
3333 grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
3334 'internal.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363335 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123336 input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
3337 grd_files)
3338 self.assertEqual(0, len(warnings))
3339
3340 # Tests that the presubmit warns when a file is listed in expectations, but
3341 # does not actually exist.
3342 def testExpectationsMissingFile(self):
3343 # Mock input file list needs a grd or grdp file in order to run the
3344 # presubmit.
3345 input_api = MockInputApi()
3346 input_api.files = [
3347 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3348 ]
3349 # unlisted.grd is listed under tools/translation/testdata but is not
3350 # included in translation expectations.
3351 grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363352 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123353 input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
3354 grd_files)
3355 self.assertEqual(1, len(warnings))
3356 self.assertTrue(warnings[0].message.startswith(
3357 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS))
3358 self.assertTrue(
3359 ("test.grd is listed in the translation expectations, "
3360 "but this grd file does not exist")
3361 in warnings[0].message)
3362
3363 # Tests that the presubmit warns when a file is not listed in expectations but
3364 # does actually exist.
3365 def testExpectationsUnlistedFile(self):
3366 # Mock input file list needs a grd or grdp file in order to run the
3367 # presubmit.
3368 input_api = MockInputApi()
3369 input_api.files = [
3370 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3371 ]
3372 # unlisted.grd is listed under tools/translation/testdata but is not
3373 # included in translation expectations.
3374 grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
3375 'internal.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363376 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123377 input_api, MockOutputApi(), self.REPO_ROOT,
3378 self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
3379 self.assertEqual(1, len(warnings))
3380 self.assertTrue(warnings[0].message.startswith(
3381 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
3382 self.assertTrue(
3383 ("unlisted.grd appears to be translatable "
3384 "(because it contains <file> or <message> elements), "
3385 "but is not listed in the translation expectations.")
3386 in warnings[0].message)
3387
3388 # Tests that the presubmit warns twice:
3389 # - for a non-existing file listed in expectations
3390 # - for an existing file not listed in expectations
3391 def testMultipleWarnings(self):
3392 # Mock input file list needs a grd or grdp file in order to run the
3393 # presubmit.
3394 input_api = MockInputApi()
3395 input_api.files = [
3396 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3397 ]
3398 # unlisted.grd is listed under tools/translation/testdata but is not
3399 # included in translation expectations.
3400 # test.grd is not listed under tools/translation/testdata but is included
3401 # in translation expectations.
3402 grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363403 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123404 input_api, MockOutputApi(), self.REPO_ROOT,
3405 self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
3406 self.assertEqual(1, len(warnings))
3407 self.assertTrue(warnings[0].message.startswith(
3408 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
3409 self.assertTrue(
3410 ("unlisted.grd appears to be translatable "
3411 "(because it contains <file> or <message> elements), "
3412 "but is not listed in the translation expectations.")
3413 in warnings[0].message)
3414 self.assertTrue(
3415 ("test.grd is listed in the translation expectations, "
3416 "but this grd file does not exist")
3417 in warnings[0].message)
3418
3419
Dominic Battre033531052018-09-24 15:45:343420class DISABLETypoInTest(unittest.TestCase):
3421
3422 def testPositive(self):
3423 # Verify the typo "DISABLE_" instead of "DISABLED_" in various contexts
3424 # where the desire is to disable a test.
3425 tests = [
3426 # Disabled on one platform:
3427 '#if defined(OS_WIN)\n'
3428 '#define MAYBE_FoobarTest DISABLE_FoobarTest\n'
3429 '#else\n'
3430 '#define MAYBE_FoobarTest FoobarTest\n'
3431 '#endif\n',
3432 # Disabled on one platform spread cross lines:
3433 '#if defined(OS_WIN)\n'
3434 '#define MAYBE_FoobarTest \\\n'
3435 ' DISABLE_FoobarTest\n'
3436 '#else\n'
3437 '#define MAYBE_FoobarTest FoobarTest\n'
3438 '#endif\n',
3439 # Disabled on all platforms:
3440 ' TEST_F(FoobarTest, DISABLE_Foo)\n{\n}',
3441 # Disabled on all platforms but multiple lines
3442 ' TEST_F(FoobarTest,\n DISABLE_foo){\n}\n',
3443 ]
3444
3445 for test in tests:
3446 mock_input_api = MockInputApi()
3447 mock_input_api.files = [
3448 MockFile('some/path/foo_unittest.cc', test.splitlines()),
3449 ]
3450
Saagar Sanghavifceeaae2020-08-12 16:40:363451 results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
Dominic Battre033531052018-09-24 15:45:343452 MockOutputApi())
3453 self.assertEqual(
3454 1,
3455 len(results),
3456 msg=('expected len(results) == 1 but got %d in test: %s' %
3457 (len(results), test)))
3458 self.assertTrue(
3459 'foo_unittest.cc' in results[0].message,
3460 msg=('expected foo_unittest.cc in message but got %s in test %s' %
3461 (results[0].message, test)))
3462
3463 def testIngoreNotTestFiles(self):
3464 mock_input_api = MockInputApi()
3465 mock_input_api.files = [
3466 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, DISABLE_Foo)'),
3467 ]
3468
Saagar Sanghavifceeaae2020-08-12 16:40:363469 results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
Dominic Battre033531052018-09-24 15:45:343470 MockOutputApi())
3471 self.assertEqual(0, len(results))
3472
Katie Df13948e2018-09-25 07:33:443473 def testIngoreDeletedFiles(self):
3474 mock_input_api = MockInputApi()
3475 mock_input_api.files = [
3476 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, Foo)', action='D'),
3477 ]
3478
Saagar Sanghavifceeaae2020-08-12 16:40:363479 results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
Katie Df13948e2018-09-25 07:33:443480 MockOutputApi())
3481 self.assertEqual(0, len(results))
Dominic Battre033531052018-09-24 15:45:343482
Dirk Pranke3c18a382019-03-15 01:07:513483
3484class BuildtoolsRevisionsAreInSyncTest(unittest.TestCase):
3485 # TODO(crbug.com/941824): We need to make sure the entries in
3486 # //buildtools/DEPS are kept in sync with the entries in //DEPS
3487 # so that users of //buildtools in other projects get the same tooling
3488 # Chromium gets. If we ever fix the referenced bug and add 'includedeps'
3489 # support to gclient, we can eliminate the duplication and delete
3490 # these tests for the corresponding presubmit check.
3491
3492 def _check(self, files):
3493 mock_input_api = MockInputApi()
3494 mock_input_api.files = []
3495 for fname, contents in files.items():
3496 mock_input_api.files.append(MockFile(fname, contents.splitlines()))
Saagar Sanghavifceeaae2020-08-12 16:40:363497 return PRESUBMIT.CheckBuildtoolsRevisionsAreInSync(mock_input_api,
Dirk Pranke3c18a382019-03-15 01:07:513498 MockOutputApi())
3499
3500 def testOneFileChangedButNotTheOther(self):
3501 results = self._check({
Nico Weber94da3c12021-02-22 21:39:023502 "DEPS": "'libcxx_revision': 'onerev'",
Dirk Pranke3c18a382019-03-15 01:07:513503 })
3504 self.assertNotEqual(results, [])
3505
3506 def testNeitherFileChanged(self):
3507 results = self._check({
3508 "OWNERS": "[email protected]",
3509 })
3510 self.assertEqual(results, [])
3511
3512 def testBothFilesChangedAndMatch(self):
3513 results = self._check({
Nico Weber94da3c12021-02-22 21:39:023514 "DEPS": "'libcxx_revision': 'onerev'",
3515 os.path.join("buildtools", "DEPS"): "'libcxx_revision': 'onerev'",
Dirk Pranke3c18a382019-03-15 01:07:513516 })
3517 self.assertEqual(results, [])
3518
3519 def testBothFilesWereChangedAndDontMatch(self):
3520 results = self._check({
Nico Weber94da3c12021-02-22 21:39:023521 "DEPS": "'libcxx_revision': 'rev1'",
3522 os.path.join("buildtools", "DEPS"): "'libcxx_revision': 'rev2'",
Dirk Pranke3c18a382019-03-15 01:07:513523 })
3524 self.assertNotEqual(results, [])
3525
3526
Max Morozb47503b2019-08-08 21:03:273527class CheckFuzzTargetsTest(unittest.TestCase):
3528
3529 def _check(self, files):
3530 mock_input_api = MockInputApi()
3531 mock_input_api.files = []
3532 for fname, contents in files.items():
3533 mock_input_api.files.append(MockFile(fname, contents.splitlines()))
Saagar Sanghavifceeaae2020-08-12 16:40:363534 return PRESUBMIT.CheckFuzzTargetsOnUpload(mock_input_api, MockOutputApi())
Max Morozb47503b2019-08-08 21:03:273535
3536 def testLibFuzzerSourcesIgnored(self):
3537 results = self._check({
3538 "third_party/lib/Fuzzer/FuzzerDriver.cpp": "LLVMFuzzerInitialize",
3539 })
3540 self.assertEqual(results, [])
3541
3542 def testNonCodeFilesIgnored(self):
3543 results = self._check({
3544 "README.md": "LLVMFuzzerInitialize",
3545 })
3546 self.assertEqual(results, [])
3547
3548 def testNoErrorHeaderPresent(self):
3549 results = self._check({
3550 "fuzzer.cc": (
3551 "#include \"testing/libfuzzer/libfuzzer_exports.h\"\n" +
3552 "LLVMFuzzerInitialize"
3553 )
3554 })
3555 self.assertEqual(results, [])
3556
3557 def testErrorMissingHeader(self):
3558 results = self._check({
3559 "fuzzer.cc": "LLVMFuzzerInitialize"
3560 })
3561 self.assertEqual(len(results), 1)
3562 self.assertEqual(results[0].items, ['fuzzer.cc'])
3563
3564
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263565class SetNoParentTest(unittest.TestCase):
John Abd-El-Malekdfd1edc2021-02-24 22:22:403566 def testSetNoParentTopLevelAllowed(self):
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263567 mock_input_api = MockInputApi()
3568 mock_input_api.files = [
3569 MockAffectedFile('goat/OWNERS',
3570 [
3571 'set noparent',
3572 '[email protected]',
John Abd-El-Malekdfd1edc2021-02-24 22:22:403573 ])
3574 ]
3575 mock_output_api = MockOutputApi()
3576 errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
3577 self.assertEqual([], errors)
3578
3579 def testSetNoParentMissing(self):
3580 mock_input_api = MockInputApi()
3581 mock_input_api.files = [
3582 MockAffectedFile('services/goat/OWNERS',
3583 [
3584 'set noparent',
3585 '[email protected]',
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263586 'per-file *.json=set noparent',
3587 'per-file *[email protected]',
3588 ])
3589 ]
3590 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:363591 errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263592 self.assertEqual(1, len(errors))
3593 self.assertTrue('goat/OWNERS:1' in errors[0].long_text)
3594 self.assertTrue('goat/OWNERS:3' in errors[0].long_text)
3595
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263596 def testSetNoParentWithCorrectRule(self):
3597 mock_input_api = MockInputApi()
3598 mock_input_api.files = [
John Abd-El-Malekdfd1edc2021-02-24 22:22:403599 MockAffectedFile('services/goat/OWNERS',
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263600 [
3601 'set noparent',
3602 'file://ipc/SECURITY_OWNERS',
3603 'per-file *.json=set noparent',
3604 'per-file *.json=file://ipc/SECURITY_OWNERS',
3605 ])
3606 ]
3607 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:363608 errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263609 self.assertEqual([], errors)
3610
3611
Ken Rockotc31f4832020-05-29 18:58:513612class MojomStabilityCheckTest(unittest.TestCase):
3613 def runTestWithAffectedFiles(self, affected_files):
3614 mock_input_api = MockInputApi()
3615 mock_input_api.files = affected_files
3616 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:363617 return PRESUBMIT.CheckStableMojomChanges(
Ken Rockotc31f4832020-05-29 18:58:513618 mock_input_api, mock_output_api)
3619
3620 def testSafeChangePasses(self):
3621 errors = self.runTestWithAffectedFiles([
3622 MockAffectedFile('foo/foo.mojom',
3623 ['[Stable] struct S { [MinVersion=1] int32 x; };'],
3624 old_contents=['[Stable] struct S {};'])
3625 ])
3626 self.assertEqual([], errors)
3627
3628 def testBadChangeFails(self):
3629 errors = self.runTestWithAffectedFiles([
3630 MockAffectedFile('foo/foo.mojom',
3631 ['[Stable] struct S { int32 x; };'],
3632 old_contents=['[Stable] struct S {};'])
3633 ])
3634 self.assertEqual(1, len(errors))
3635 self.assertTrue('not backward-compatible' in errors[0].message)
3636
Ken Rockotad7901f942020-06-04 20:17:093637 def testDeletedFile(self):
3638 """Regression test for https://crbug.com/1091407."""
3639 errors = self.runTestWithAffectedFiles([
3640 MockAffectedFile('a.mojom', [], old_contents=['struct S {};'],
3641 action='D'),
3642 MockAffectedFile('b.mojom',
3643 ['struct S {}; struct T { S s; };'],
3644 old_contents=['import "a.mojom"; struct T { S s; };'])
3645 ])
3646 self.assertEqual([], errors)
3647
Ken Rockotc31f4832020-05-29 18:58:513648
Dominic Battre645d42342020-12-04 16:14:103649class CheckDeprecationOfPreferencesTest(unittest.TestCase):
3650 # Test that a warning is generated if a preference registration is removed
3651 # from a random file.
3652 def testWarning(self):
3653 mock_input_api = MockInputApi()
3654 mock_input_api.files = [
3655 MockAffectedFile(
3656 'foo.cc',
3657 ['A', 'B'],
3658 ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
3659 scm_diff='\n'.join([
3660 '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
3661 '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
3662 '@@ -1,3 +1,2 @@',
3663 ' A',
3664 '-prefs->RegisterStringPref("foo", "default");',
3665 ' B']),
3666 action='M')
3667 ]
3668 mock_output_api = MockOutputApi()
3669 errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
3670 mock_output_api)
3671 self.assertEqual(1, len(errors))
3672 self.assertTrue(
3673 'Discovered possible removal of preference registrations' in
3674 errors[0].message)
3675
3676 # Test that a warning is inhibited if the preference registration was moved
3677 # to the deprecation functions in browser prefs.
3678 def testNoWarningForMigration(self):
3679 mock_input_api = MockInputApi()
3680 mock_input_api.files = [
3681 # RegisterStringPref was removed from foo.cc.
3682 MockAffectedFile(
3683 'foo.cc',
3684 ['A', 'B'],
3685 ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
3686 scm_diff='\n'.join([
3687 '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
3688 '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
3689 '@@ -1,3 +1,2 @@',
3690 ' A',
3691 '-prefs->RegisterStringPref("foo", "default");',
3692 ' B']),
3693 action='M'),
3694 # But the preference was properly migrated.
3695 MockAffectedFile(
3696 'chrome/browser/prefs/browser_prefs.cc',
3697 [
3698 '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3699 '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3700 '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
3701 'prefs->RegisterStringPref("foo", "default");',
3702 '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
3703 ],
3704 [
3705 '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3706 '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3707 '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
3708 '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
3709 ],
3710 scm_diff='\n'.join([
3711 '--- browser_prefs.cc.old 2020-12-02 20:51:40.812686731 +0100',
3712 '+++ browser_prefs.cc.new 2020-12-02 20:52:02.936755539 +0100',
3713 '@@ -2,3 +2,4 @@',
3714 ' // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3715 ' // BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
3716 '+prefs->RegisterStringPref("foo", "default");',
3717 ' // END_MIGRATE_OBSOLETE_PROFILE_PREFS']),
3718 action='M'),
3719 ]
3720 mock_output_api = MockOutputApi()
3721 errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
3722 mock_output_api)
3723 self.assertEqual(0, len(errors))
3724
3725 # Test that a warning is NOT inhibited if the preference registration was
3726 # moved to a place outside of the migration functions in browser_prefs.cc
3727 def testWarningForImproperMigration(self):
3728 mock_input_api = MockInputApi()
3729 mock_input_api.files = [
3730 # RegisterStringPref was removed from foo.cc.
3731 MockAffectedFile(
3732 'foo.cc',
3733 ['A', 'B'],
3734 ['A', 'prefs->RegisterStringPref("foo", "default");', 'B'],
3735 scm_diff='\n'.join([
3736 '--- foo.cc.old 2020-12-02 20:40:54.430676385 +0100',
3737 '+++ foo.cc.new 2020-12-02 20:41:02.086700197 +0100',
3738 '@@ -1,3 +1,2 @@',
3739 ' A',
3740 '-prefs->RegisterStringPref("foo", "default");',
3741 ' B']),
3742 action='M'),
3743 # The registration call was moved to a place in browser_prefs.cc that
3744 # is outside the migration functions.
3745 MockAffectedFile(
3746 'chrome/browser/prefs/browser_prefs.cc',
3747 [
3748 'prefs->RegisterStringPref("foo", "default");',
3749 '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3750 '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3751 '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
3752 '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
3753 ],
3754 [
3755 '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3756 '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3757 '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
3758 '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
3759 ],
3760 scm_diff='\n'.join([
3761 '--- browser_prefs.cc.old 2020-12-02 20:51:40.812686731 +0100',
3762 '+++ browser_prefs.cc.new 2020-12-02 20:52:02.936755539 +0100',
3763 '@@ -1,2 +1,3 @@',
3764 '+prefs->RegisterStringPref("foo", "default");',
3765 ' // BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3766 ' // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS']),
3767 action='M'),
3768 ]
3769 mock_output_api = MockOutputApi()
3770 errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
3771 mock_output_api)
3772 self.assertEqual(1, len(errors))
3773 self.assertTrue(
3774 'Discovered possible removal of preference registrations' in
3775 errors[0].message)
3776
3777 # Check that the presubmit fails if a marker line in brower_prefs.cc is
3778 # deleted.
3779 def testDeletedMarkerRaisesError(self):
3780 mock_input_api = MockInputApi()
3781 mock_input_api.files = [
3782 MockAffectedFile('chrome/browser/prefs/browser_prefs.cc',
3783 [
3784 '// BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3785 '// END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS',
3786 '// BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS',
3787 # The following line is deleted for this test
3788 # '// END_MIGRATE_OBSOLETE_PROFILE_PREFS',
3789 ])
3790 ]
3791 mock_output_api = MockOutputApi()
3792 errors = PRESUBMIT.CheckDeprecationOfPreferences(mock_input_api,
3793 mock_output_api)
3794 self.assertEqual(1, len(errors))
3795 self.assertEqual(
3796 'Broken .*MIGRATE_OBSOLETE_.*_PREFS markers in browser_prefs.cc.',
3797 errors[0].message)
3798
3799
[email protected]2299dcf2012-11-15 19:56:243800if __name__ == '__main__':
3801 unittest.main()