blob: 2dfa78a4e5f771b242ca51a43d2e3f903ab9cf0d [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
2160 def testOtherFuchsiaChangesDoNotRequireSecurityOwner(self):
2161 mock_input_api = MockInputApi()
2162 mock_input_api.files = [
2163 MockAffectedFile('some/non/service/thing/fuchsia_fidl_cml_cmx_magic.cc',
2164 [
2165 'const char kNoEnforcement[] = "Security?!? Pah!";',
2166 ])]
2167 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:362168 errors = PRESUBMIT.CheckSecurityOwners(
Ken Rockot9f668262018-12-21 18:56:362169 mock_input_api, mock_output_api)
2170 self.assertEqual([], errors)
2171
Daniel Cheng13ca61a882017-08-25 15:11:252172
Robert Sesek2c905332020-05-06 23:17:132173class SecurityChangeTest(unittest.TestCase):
2174 class _MockOwnersDB(object):
2175 def __init__(self):
2176 self.email_regexp = '.*'
2177
2178 def owners_rooted_at_file(self, f):
2179 return ['[email protected]', '[email protected]']
2180
2181 def _mockChangeOwnerAndReviewers(self, input_api, owner, reviewers):
2182 def __MockOwnerAndReviewers(input_api, email_regexp, approval_needed=False):
2183 return [owner, reviewers]
2184 input_api.canned_checks.GetCodereviewOwnerAndReviewers = \
2185 __MockOwnerAndReviewers
2186
Alex Goughbc964dd2020-06-15 17:52:372187 def testDiffGetServiceSandboxType(self):
Robert Sesek2c905332020-05-06 23:17:132188 mock_input_api = MockInputApi()
2189 mock_input_api.files = [
2190 MockAffectedFile(
2191 'services/goat/teleporter_host.cc',
2192 [
Alex Goughbc964dd2020-06-15 17:52:372193 'template <>',
2194 'inline content::SandboxType',
2195 'content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {',
2196 '#if defined(OS_WIN)',
2197 ' return SandboxType::kGoaty;',
2198 '#else',
2199 ' return SandboxType::kNoSandbox;',
2200 '#endif // !defined(OS_WIN)',
2201 '}'
Robert Sesek2c905332020-05-06 23:17:132202 ]
2203 ),
2204 ]
2205 files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
2206 mock_input_api)
2207 self.assertEqual({
2208 'services/goat/teleporter_host.cc': set([
Alex Goughbc964dd2020-06-15 17:52:372209 'content::GetServiceSandboxType<>()'
Robert Sesek2c905332020-05-06 23:17:132210 ])},
2211 files_to_functions)
2212
2213 def testDiffRemovingLine(self):
2214 mock_input_api = MockInputApi()
2215 mock_file = MockAffectedFile('services/goat/teleporter_host.cc', '')
2216 mock_file._scm_diff = """--- old 2020-05-04 14:08:25.000000000 -0400
2217+++ new 2020-05-04 14:08:32.000000000 -0400
2218@@ -1,5 +1,4 @@
Alex Goughbc964dd2020-06-15 17:52:372219 template <>
2220 inline content::SandboxType
2221-content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {
2222 #if defined(OS_WIN)
2223 return SandboxType::kGoaty;
Robert Sesek2c905332020-05-06 23:17:132224"""
2225 mock_input_api.files = [mock_file]
2226 files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
2227 mock_input_api)
2228 self.assertEqual({
2229 'services/goat/teleporter_host.cc': set([
Alex Goughbc964dd2020-06-15 17:52:372230 'content::GetServiceSandboxType<>()'
Robert Sesek2c905332020-05-06 23:17:132231 ])},
2232 files_to_functions)
2233
2234 def testChangeOwnersMissing(self):
2235 mock_input_api = MockInputApi()
2236 mock_input_api.owners_db = self._MockOwnersDB()
2237 mock_input_api.is_committing = False
2238 mock_input_api.files = [
Alex Goughbc964dd2020-06-15 17:52:372239 MockAffectedFile('file.cc', ['GetServiceSandboxType<Goat>(Sandbox)'])
Robert Sesek2c905332020-05-06 23:17:132240 ]
2241 mock_output_api = MockOutputApi()
2242 self._mockChangeOwnerAndReviewers(
2243 mock_input_api, '[email protected]', ['[email protected]'])
Saagar Sanghavifceeaae2020-08-12 16:40:362244 result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
Robert Sesek2c905332020-05-06 23:17:132245 self.assertEquals(1, len(result))
2246 self.assertEquals(result[0].type, 'notify')
2247 self.assertEquals(result[0].message,
2248 'The following files change calls to security-sensive functions\n' \
2249 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
2250 ' file.cc\n'
Alex Goughbc964dd2020-06-15 17:52:372251 ' content::GetServiceSandboxType<>()\n\n')
Robert Sesek2c905332020-05-06 23:17:132252
2253 def testChangeOwnersMissingAtCommit(self):
2254 mock_input_api = MockInputApi()
2255 mock_input_api.owners_db = self._MockOwnersDB()
2256 mock_input_api.is_committing = True
2257 mock_input_api.files = [
Alex Goughbc964dd2020-06-15 17:52:372258 MockAffectedFile('file.cc', ['GetServiceSandboxType<mojom::Goat>()'])
Robert Sesek2c905332020-05-06 23:17:132259 ]
2260 mock_output_api = MockOutputApi()
2261 self._mockChangeOwnerAndReviewers(
2262 mock_input_api, '[email protected]', ['[email protected]'])
Saagar Sanghavifceeaae2020-08-12 16:40:362263 result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
Robert Sesek2c905332020-05-06 23:17:132264 self.assertEquals(1, len(result))
2265 self.assertEquals(result[0].type, 'error')
2266 self.assertEquals(result[0].message,
2267 'The following files change calls to security-sensive functions\n' \
2268 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
2269 ' file.cc\n'
Alex Goughbc964dd2020-06-15 17:52:372270 ' content::GetServiceSandboxType<>()\n\n')
Robert Sesek2c905332020-05-06 23:17:132271
2272 def testChangeOwnersPresent(self):
2273 mock_input_api = MockInputApi()
2274 mock_input_api.owners_db = self._MockOwnersDB()
2275 mock_input_api.files = [
2276 MockAffectedFile('file.cc', ['WithSandboxType(Sandbox)'])
2277 ]
2278 mock_output_api = MockOutputApi()
2279 self._mockChangeOwnerAndReviewers(
2280 mock_input_api, '[email protected]',
2281 ['[email protected]', '[email protected]'])
Saagar Sanghavifceeaae2020-08-12 16:40:362282 result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
Robert Sesek2c905332020-05-06 23:17:132283 self.assertEquals(0, len(result))
2284
2285 def testChangeOwnerIsSecurityOwner(self):
2286 mock_input_api = MockInputApi()
2287 mock_input_api.owners_db = self._MockOwnersDB()
2288 mock_input_api.files = [
Alex Goughbc964dd2020-06-15 17:52:372289 MockAffectedFile('file.cc', ['GetServiceSandboxType<T>(Sandbox)'])
Robert Sesek2c905332020-05-06 23:17:132290 ]
2291 mock_output_api = MockOutputApi()
2292 self._mockChangeOwnerAndReviewers(
2293 mock_input_api, '[email protected]', ['[email protected]'])
Saagar Sanghavifceeaae2020-08-12 16:40:362294 result = PRESUBMIT.CheckSecurityChanges(mock_input_api, mock_output_api)
Robert Sesek2c905332020-05-06 23:17:132295 self.assertEquals(1, len(result))
2296
2297
Mario Sanchez Prada2472cab2019-09-18 10:58:312298class BannedTypeCheckTest(unittest.TestCase):
Sylvain Defresnea8b73d252018-02-28 15:45:542299
Peter Kasting94a56c42019-10-25 21:54:042300 def testBannedCppFunctions(self):
2301 input_api = MockInputApi()
2302 input_api.files = [
2303 MockFile('some/cpp/problematic/file.cc',
2304 ['using namespace std;']),
Oksana Zhuravlovac8222d22019-12-19 19:21:162305 MockFile('third_party/blink/problematic/file.cc',
2306 ['GetInterfaceProvider()']),
Peter Kasting94a56c42019-10-25 21:54:042307 MockFile('some/cpp/ok/file.cc',
2308 ['using std::string;']),
Allen Bauer53b43fb12020-03-12 17:21:472309 MockFile('some/cpp/problematic/file2.cc',
2310 ['set_owned_by_client()']),
Peter Kasting94a56c42019-10-25 21:54:042311 ]
2312
Saagar Sanghavifceeaae2020-08-12 16:40:362313 results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
Oksana Zhuravlovac8222d22019-12-19 19:21:162314
2315 # warnings are results[0], errors are results[1]
2316 self.assertEqual(2, len(results))
2317 self.assertTrue('some/cpp/problematic/file.cc' in results[1].message)
2318 self.assertTrue(
2319 'third_party/blink/problematic/file.cc' in results[0].message)
2320 self.assertTrue('some/cpp/ok/file.cc' not in results[1].message)
Allen Bauer53b43fb12020-03-12 17:21:472321 self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
Peter Kasting94a56c42019-10-25 21:54:042322
Abhijeet Kandalkar1e7c2502019-10-29 15:05:452323 def testBannedBlinkDowncastHelpers(self):
2324 input_api = MockInputApi()
2325 input_api.files = [
2326 MockFile('some/cpp/problematic/file1.cc',
2327 ['DEFINE_TYPE_CASTS(ToType, FromType, from_argument,'
2328 'PointerPredicate(), ReferencePredicate());']),
2329 MockFile('some/cpp/problematic/file2.cc',
2330 ['bool is_test_ele = IsHTMLTestElement(n);']),
2331 MockFile('some/cpp/problematic/file3.cc',
2332 ['auto* html_test_ele = ToHTMLTestElement(n);']),
2333 MockFile('some/cpp/problematic/file4.cc',
2334 ['auto* html_test_ele_or_null = ToHTMLTestElementOrNull(n);']),
2335 MockFile('some/cpp/ok/file1.cc',
2336 ['bool is_test_ele = IsA<HTMLTestElement>(n);']),
2337 MockFile('some/cpp/ok/file2.cc',
2338 ['auto* html_test_ele = To<HTMLTestElement>(n);']),
2339 MockFile('some/cpp/ok/file3.cc',
2340 ['auto* html_test_ele_or_null = ',
2341 'DynamicTo<HTMLTestElement>(n);']),
2342 ]
2343
2344 # warnings are errors[0], errors are errors[1]
Saagar Sanghavifceeaae2020-08-12 16:40:362345 errors = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
Abhijeet Kandalkar1e7c2502019-10-29 15:05:452346 self.assertEqual(2, len(errors))
2347 self.assertTrue('some/cpp/problematic/file1.cc' in errors[1].message)
2348 self.assertTrue('some/cpp/problematic/file2.cc' in errors[0].message)
2349 self.assertTrue('some/cpp/problematic/file3.cc' in errors[0].message)
2350 self.assertTrue('some/cpp/problematic/file4.cc' in errors[0].message)
2351 self.assertTrue('some/cpp/ok/file1.cc' not in errors[0].message)
2352 self.assertTrue('some/cpp/ok/file2.cc' not in errors[0].message)
2353 self.assertTrue('some/cpp/ok/file3.cc' not in errors[0].message)
2354
Peter K. Lee6c03ccff2019-07-15 14:40:052355 def testBannedIosObjcFunctions(self):
Sylvain Defresnea8b73d252018-02-28 15:45:542356 input_api = MockInputApi()
2357 input_api.files = [
2358 MockFile('some/ios/file.mm',
2359 ['TEST(SomeClassTest, SomeInteraction) {',
2360 '}']),
2361 MockFile('some/mac/file.mm',
2362 ['TEST(SomeClassTest, SomeInteraction) {',
2363 '}']),
2364 MockFile('another/ios_file.mm',
2365 ['class SomeTest : public testing::Test {};']),
Peter K. Lee6c03ccff2019-07-15 14:40:052366 MockFile('some/ios/file_egtest.mm',
2367 ['- (void)testSomething { EXPECT_OCMOCK_VERIFY(aMock); }']),
2368 MockFile('some/ios/file_unittest.mm',
2369 ['TEST_F(SomeTest, TestThis) { EXPECT_OCMOCK_VERIFY(aMock); }']),
Sylvain Defresnea8b73d252018-02-28 15:45:542370 ]
2371
Saagar Sanghavifceeaae2020-08-12 16:40:362372 errors = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
Sylvain Defresnea8b73d252018-02-28 15:45:542373 self.assertEqual(1, len(errors))
2374 self.assertTrue('some/ios/file.mm' in errors[0].message)
2375 self.assertTrue('another/ios_file.mm' in errors[0].message)
2376 self.assertTrue('some/mac/file.mm' not in errors[0].message)
Peter K. Lee6c03ccff2019-07-15 14:40:052377 self.assertTrue('some/ios/file_egtest.mm' in errors[0].message)
2378 self.assertTrue('some/ios/file_unittest.mm' not in errors[0].message)
Sylvain Defresnea8b73d252018-02-28 15:45:542379
Carlos Knippschildab192b8c2019-04-08 20:02:382380 def testBannedMojoFunctions(self):
2381 input_api = MockInputApi()
2382 input_api.files = [
2383 MockFile('some/cpp/problematic/file.cc',
2384 ['mojo::DataPipe();']),
Oksana Zhuravlovafd247772019-05-16 16:57:292385 MockFile('some/cpp/problematic/file2.cc',
2386 ['mojo::ConvertTo<>']),
Carlos Knippschildab192b8c2019-04-08 20:02:382387 MockFile('some/cpp/ok/file.cc',
2388 ['CreateDataPipe();']),
Kinuko Yasuda376c2ce12019-04-16 01:20:372389 MockFile('some/cpp/ok/file2.cc',
2390 ['mojo::DataPipeDrainer();']),
Oksana Zhuravlovafd247772019-05-16 16:57:292391 MockFile('third_party/blink/ok/file3.cc',
2392 ['mojo::ConvertTo<>']),
2393 MockFile('content/renderer/ok/file3.cc',
2394 ['mojo::ConvertTo<>']),
Carlos Knippschildab192b8c2019-04-08 20:02:382395 ]
2396
Saagar Sanghavifceeaae2020-08-12 16:40:362397 results = PRESUBMIT.CheckNoBannedFunctions(input_api, MockOutputApi())
Oksana Zhuravlova1d3b59de2019-05-17 00:08:222398
2399 # warnings are results[0], errors are results[1]
2400 self.assertEqual(2, len(results))
2401 self.assertTrue('some/cpp/problematic/file.cc' in results[1].message)
2402 self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
2403 self.assertTrue('some/cpp/ok/file.cc' not in results[1].message)
2404 self.assertTrue('some/cpp/ok/file2.cc' not in results[1].message)
2405 self.assertTrue('third_party/blink/ok/file3.cc' not in results[0].message)
2406 self.assertTrue('content/renderer/ok/file3.cc' not in results[0].message)
Carlos Knippschildab192b8c2019-04-08 20:02:382407
Mario Sanchez Prada2472cab2019-09-18 10:58:312408 def testDeprecatedMojoTypes(self):
Mario Sanchez Pradacec9cef2019-12-15 11:54:572409 ok_paths = ['components/arc']
2410 warning_paths = ['some/cpp']
Mario Sanchez Pradaaab91382019-12-19 08:57:092411 error_paths = ['third_party/blink', 'content']
Mario Sanchez Prada2472cab2019-09-18 10:58:312412 test_cases = [
2413 {
2414 'type': 'mojo::AssociatedBinding<>;',
2415 'file': 'file1.c'
2416 },
2417 {
2418 'type': 'mojo::AssociatedBindingSet<>;',
2419 'file': 'file2.c'
2420 },
2421 {
2422 'type': 'mojo::AssociatedInterfacePtr<>',
2423 'file': 'file3.cc'
2424 },
2425 {
2426 'type': 'mojo::AssociatedInterfacePtrInfo<>',
2427 'file': 'file4.cc'
2428 },
2429 {
2430 'type': 'mojo::AssociatedInterfaceRequest<>',
2431 'file': 'file5.cc'
2432 },
2433 {
2434 'type': 'mojo::Binding<>',
2435 'file': 'file6.cc'
2436 },
2437 {
2438 'type': 'mojo::BindingSet<>',
2439 'file': 'file7.cc'
2440 },
2441 {
2442 'type': 'mojo::InterfacePtr<>',
2443 'file': 'file8.cc'
2444 },
2445 {
2446 'type': 'mojo::InterfacePtrInfo<>',
2447 'file': 'file9.cc'
2448 },
2449 {
2450 'type': 'mojo::InterfaceRequest<>',
2451 'file': 'file10.cc'
2452 },
2453 {
2454 'type': 'mojo::MakeRequest()',
2455 'file': 'file11.cc'
2456 },
2457 {
2458 'type': 'mojo::MakeRequestAssociatedWithDedicatedPipe()',
2459 'file': 'file12.cc'
2460 },
2461 {
2462 'type': 'mojo::MakeStrongBinding()<>',
2463 'file': 'file13.cc'
2464 },
2465 {
2466 'type': 'mojo::MakeStrongAssociatedBinding()<>',
2467 'file': 'file14.cc'
2468 },
2469 {
Gyuyoung Kim4952ba62020-07-07 07:33:442470 'type': 'mojo::StrongAssociatedBinding<>',
Mario Sanchez Prada2472cab2019-09-18 10:58:312471 'file': 'file15.cc'
2472 },
2473 {
Gyuyoung Kim4952ba62020-07-07 07:33:442474 'type': 'mojo::StrongBinding<>',
Mario Sanchez Prada2472cab2019-09-18 10:58:312475 'file': 'file16.cc'
2476 },
Gyuyoung Kim4952ba62020-07-07 07:33:442477 {
2478 'type': 'mojo::StrongAssociatedBindingSet<>',
2479 'file': 'file17.cc'
2480 },
2481 {
2482 'type': 'mojo::StrongBindingSet<>',
2483 'file': 'file18.cc'
2484 },
Mario Sanchez Prada2472cab2019-09-18 10:58:312485 ]
2486
2487 # Build the list of MockFiles considering paths that should trigger warnings
Mario Sanchez Pradacec9cef2019-12-15 11:54:572488 # as well as paths that should trigger errors.
Mario Sanchez Prada2472cab2019-09-18 10:58:312489 input_api = MockInputApi()
2490 input_api.files = []
2491 for test_case in test_cases:
2492 for path in ok_paths:
2493 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2494 [test_case['type']]))
2495 for path in warning_paths:
2496 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2497 [test_case['type']]))
Mario Sanchez Pradacec9cef2019-12-15 11:54:572498 for path in error_paths:
2499 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2500 [test_case['type']]))
Mario Sanchez Prada2472cab2019-09-18 10:58:312501
Saagar Sanghavifceeaae2020-08-12 16:40:362502 results = PRESUBMIT.CheckNoDeprecatedMojoTypes(input_api, MockOutputApi())
Mario Sanchez Prada2472cab2019-09-18 10:58:312503
Mario Sanchez Pradacec9cef2019-12-15 11:54:572504 # warnings are results[0], errors are results[1]
2505 self.assertEqual(2, len(results))
Mario Sanchez Prada2472cab2019-09-18 10:58:312506
2507 for test_case in test_cases:
Mario Sanchez Pradacec9cef2019-12-15 11:54:572508 # Check that no warnings nor errors have been triggered for these paths.
Mario Sanchez Prada2472cab2019-09-18 10:58:312509 for path in ok_paths:
2510 self.assertFalse(path in results[0].message)
Mario Sanchez Pradacec9cef2019-12-15 11:54:572511 self.assertFalse(path in results[1].message)
Mario Sanchez Prada2472cab2019-09-18 10:58:312512
2513 # Check warnings have been triggered for these paths.
2514 for path in warning_paths:
2515 self.assertTrue(path in results[0].message)
Mario Sanchez Pradacec9cef2019-12-15 11:54:572516 self.assertFalse(path in results[1].message)
2517
2518 # Check errors have been triggered for these paths.
2519 for path in error_paths:
2520 self.assertFalse(path in results[0].message)
2521 self.assertTrue(path in results[1].message)
Mario Sanchez Prada2472cab2019-09-18 10:58:312522
Sylvain Defresnea8b73d252018-02-28 15:45:542523
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272524class NoProductionCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozekf01ed502018-03-16 19:38:242525 def testTruePositives(self):
2526 mock_input_api = MockInputApi()
2527 mock_input_api.files = [
2528 MockFile('some/path/foo.cc', ['foo_for_testing();']),
2529 MockFile('some/path/foo.mm', ['FooForTesting();']),
2530 MockFile('some/path/foo.cxx', ['FooForTests();']),
2531 MockFile('some/path/foo.cpp', ['foo_for_test();']),
2532 ]
2533
Saagar Sanghavifceeaae2020-08-12 16:40:362534 results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
Vaclav Brozekf01ed502018-03-16 19:38:242535 mock_input_api, MockOutputApi())
2536 self.assertEqual(1, len(results))
2537 self.assertEqual(4, len(results[0].items))
2538 self.assertTrue('foo.cc' in results[0].items[0])
2539 self.assertTrue('foo.mm' in results[0].items[1])
2540 self.assertTrue('foo.cxx' in results[0].items[2])
2541 self.assertTrue('foo.cpp' in results[0].items[3])
2542
2543 def testFalsePositives(self):
2544 mock_input_api = MockInputApi()
2545 mock_input_api.files = [
2546 MockFile('some/path/foo.h', ['foo_for_testing();']),
2547 MockFile('some/path/foo.mm', ['FooForTesting() {']),
2548 MockFile('some/path/foo.cc', ['::FooForTests();']),
2549 MockFile('some/path/foo.cpp', ['// foo_for_test();']),
2550 ]
2551
Saagar Sanghavifceeaae2020-08-12 16:40:362552 results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctions(
Vaclav Brozekf01ed502018-03-16 19:38:242553 mock_input_api, MockOutputApi())
2554 self.assertEqual(0, len(results))
2555
2556
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272557class NoProductionJavaCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozek7dbc28c2018-03-27 08:35:232558 def testTruePositives(self):
2559 mock_input_api = MockInputApi()
2560 mock_input_api.files = [
2561 MockFile('dir/java/src/foo.java', ['FooForTesting();']),
2562 MockFile('dir/java/src/bar.java', ['FooForTests(x);']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392563 MockFile('dir/java/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:232564 MockFile('dir/java/src/mult.java', [
2565 'int x = SomethingLongHere()',
2566 ' * SomethingLongHereForTesting();'
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392567 ])
Vaclav Brozek7dbc28c2018-03-27 08:35:232568 ]
2569
Saagar Sanghavifceeaae2020-08-12 16:40:362570 results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctionsJava(
Vaclav Brozek7dbc28c2018-03-27 08:35:232571 mock_input_api, MockOutputApi())
2572 self.assertEqual(1, len(results))
2573 self.assertEqual(4, len(results[0].items))
2574 self.assertTrue('foo.java' in results[0].items[0])
2575 self.assertTrue('bar.java' in results[0].items[1])
2576 self.assertTrue('baz.java' in results[0].items[2])
2577 self.assertTrue('mult.java' in results[0].items[3])
2578
2579 def testFalsePositives(self):
2580 mock_input_api = MockInputApi()
2581 mock_input_api.files = [
2582 MockFile('dir/java/src/foo.xml', ['FooForTesting();']),
2583 MockFile('dir/java/src/foo.java', ['FooForTests() {']),
2584 MockFile('dir/java/src/bar.java', ['// FooForTest();']),
2585 MockFile('dir/java/src/bar2.java', ['x = 1; // FooForTest();']),
Sky Malice9e6d6032020-10-15 22:49:552586 MockFile('dir/java/src/bar3.java', ['@VisibleForTesting']),
2587 MockFile('dir/java/src/bar4.java', ['@VisibleForTesting()']),
2588 MockFile('dir/java/src/bar5.java', [
2589 '@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)'
2590 ]),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392591 MockFile('dir/javatests/src/baz.java', ['FooForTest(', 'y', ');']),
2592 MockFile('dir/junit/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:232593 MockFile('dir/junit/src/javadoc.java', [
2594 '/** Use FooForTest(); to obtain foo in tests.'
2595 ' */'
2596 ]),
2597 MockFile('dir/junit/src/javadoc2.java', [
2598 '/** ',
2599 ' * Use FooForTest(); to obtain foo in tests.'
2600 ' */'
2601 ]),
2602 ]
2603
Saagar Sanghavifceeaae2020-08-12 16:40:362604 results = PRESUBMIT.CheckNoProductionCodeUsingTestOnlyFunctionsJava(
Vaclav Brozek7dbc28c2018-03-27 08:35:232605 mock_input_api, MockOutputApi())
2606 self.assertEqual(0, len(results))
2607
2608
Mohamed Heikald048240a2019-11-12 16:57:372609class NewImagesWarningTest(unittest.TestCase):
2610 def testTruePositives(self):
2611 mock_input_api = MockInputApi()
2612 mock_input_api.files = [
2613 MockFile('dir/android/res/drawable/foo.png', []),
2614 MockFile('dir/android/res/drawable-v21/bar.svg', []),
2615 MockFile('dir/android/res/mipmap-v21-en/baz.webp', []),
2616 MockFile('dir/android/res_gshoe/drawable-mdpi/foobar.png', []),
2617 ]
2618
2619 results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
2620 self.assertEqual(1, len(results))
2621 self.assertEqual(4, len(results[0].items))
2622 self.assertTrue('foo.png' in results[0].items[0].LocalPath())
2623 self.assertTrue('bar.svg' in results[0].items[1].LocalPath())
2624 self.assertTrue('baz.webp' in results[0].items[2].LocalPath())
2625 self.assertTrue('foobar.png' in results[0].items[3].LocalPath())
2626
2627 def testFalsePositives(self):
2628 mock_input_api = MockInputApi()
2629 mock_input_api.files = [
2630 MockFile('dir/pngs/README.md', []),
2631 MockFile('java/test/res/drawable/foo.png', []),
2632 MockFile('third_party/blink/foo.png', []),
2633 MockFile('dir/third_party/libpng/src/foo.cc', ['foobar']),
2634 MockFile('dir/resources.webp/.gitignore', ['foo.png']),
2635 ]
2636
2637 results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
2638 self.assertEqual(0, len(results))
2639
2640
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272641class CheckUniquePtrTest(unittest.TestCase):
Vaclav Brozek851d9602018-04-04 16:13:052642 def testTruePositivesNullptr(self):
2643 mock_input_api = MockInputApi()
2644 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162645 MockFile('dir/baz.cc', ['std::unique_ptr<T>()']),
2646 MockFile('dir/baz-p.cc', ['std::unique_ptr<T<P>>()']),
Vaclav Brozek851d9602018-04-04 16:13:052647 ]
2648
Saagar Sanghavifceeaae2020-08-12 16:40:362649 results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
Vaclav Brozek851d9602018-04-04 16:13:052650 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:162651 self.assertTrue('nullptr' in results[0].message)
Vaclav Brozek851d9602018-04-04 16:13:052652 self.assertEqual(2, len(results[0].items))
2653 self.assertTrue('baz.cc' in results[0].items[0])
2654 self.assertTrue('baz-p.cc' in results[0].items[1])
2655
2656 def testTruePositivesConstructor(self):
Vaclav Brozek52e18bf2018-04-03 07:05:242657 mock_input_api = MockInputApi()
2658 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162659 MockFile('dir/foo.cc', ['return std::unique_ptr<T>(foo);']),
2660 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T>(foo)']),
2661 MockFile('dir/mult.cc', [
Vaclav Brozek95face62018-04-04 14:15:112662 'return',
2663 ' std::unique_ptr<T>(barVeryVeryLongFooSoThatItWouldNotFitAbove);'
2664 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:162665 MockFile('dir/mult2.cc', [
Vaclav Brozek95face62018-04-04 14:15:112666 'barVeryVeryLongLongBaaaaaarSoThatTheLineLimitIsAlmostReached =',
2667 ' std::unique_ptr<T>(foo);'
2668 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:162669 MockFile('dir/mult3.cc', [
Vaclav Brozek95face62018-04-04 14:15:112670 'bar = std::unique_ptr<T>(',
2671 ' fooVeryVeryVeryLongStillGoingWellThisWillTakeAWhileFinallyThere);'
2672 ]),
Vaclav Brozekb7fadb692018-08-30 06:39:532673 MockFile('dir/multi_arg.cc', [
2674 'auto p = std::unique_ptr<std::pair<T, D>>(new std::pair(T, D));']),
Vaclav Brozek52e18bf2018-04-03 07:05:242675 ]
2676
Saagar Sanghavifceeaae2020-08-12 16:40:362677 results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
Vaclav Brozek851d9602018-04-04 16:13:052678 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:162679 self.assertTrue('std::make_unique' in results[0].message)
Vaclav Brozekb7fadb692018-08-30 06:39:532680 self.assertEqual(6, len(results[0].items))
Vaclav Brozek851d9602018-04-04 16:13:052681 self.assertTrue('foo.cc' in results[0].items[0])
2682 self.assertTrue('bar.mm' in results[0].items[1])
2683 self.assertTrue('mult.cc' in results[0].items[2])
2684 self.assertTrue('mult2.cc' in results[0].items[3])
2685 self.assertTrue('mult3.cc' in results[0].items[4])
Vaclav Brozekb7fadb692018-08-30 06:39:532686 self.assertTrue('multi_arg.cc' in results[0].items[5])
Vaclav Brozek52e18bf2018-04-03 07:05:242687
2688 def testFalsePositives(self):
2689 mock_input_api = MockInputApi()
2690 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162691 MockFile('dir/foo.cc', ['return std::unique_ptr<T[]>(foo);']),
2692 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T[]>(foo)']),
2693 MockFile('dir/file.cc', ['std::unique_ptr<T> p = Foo();']),
2694 MockFile('dir/baz.cc', [
Vaclav Brozek52e18bf2018-04-03 07:05:242695 'std::unique_ptr<T> result = std::make_unique<T>();'
2696 ]),
Vaclav Brozeka54c528b2018-04-06 19:23:552697 MockFile('dir/baz2.cc', [
2698 'std::unique_ptr<T> result = std::make_unique<T>('
2699 ]),
2700 MockFile('dir/nested.cc', ['set<std::unique_ptr<T>>();']),
2701 MockFile('dir/nested2.cc', ['map<U, std::unique_ptr<T>>();']),
Vaclav Brozekb7fadb692018-08-30 06:39:532702
2703 # Two-argument invocation of std::unique_ptr is exempt because there is
2704 # no equivalent using std::make_unique.
2705 MockFile('dir/multi_arg.cc', [
2706 'auto p = std::unique_ptr<T, D>(new T(), D());']),
Vaclav Brozek52e18bf2018-04-03 07:05:242707 ]
2708
Saagar Sanghavifceeaae2020-08-12 16:40:362709 results = PRESUBMIT.CheckUniquePtrOnUpload(mock_input_api, MockOutputApi())
Vaclav Brozek52e18bf2018-04-03 07:05:242710 self.assertEqual(0, len(results))
2711
Danil Chapovalov3518f362018-08-11 16:13:432712class CheckNoDirectIncludesHeadersWhichRedefineStrCat(unittest.TestCase):
2713 def testBlocksDirectIncludes(self):
2714 mock_input_api = MockInputApi()
2715 mock_input_api.files = [
2716 MockFile('dir/foo_win.cc', ['#include "shlwapi.h"']),
2717 MockFile('dir/bar.h', ['#include <propvarutil.h>']),
2718 MockFile('dir/baz.h', ['#include <atlbase.h>']),
2719 MockFile('dir/jumbo.h', ['#include "sphelper.h"']),
2720 ]
2721 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2722 self.assertEquals(1, len(results))
2723 self.assertEquals(4, len(results[0].items))
2724 self.assertTrue('StrCat' in results[0].message)
2725 self.assertTrue('foo_win.cc' in results[0].items[0])
2726 self.assertTrue('bar.h' in results[0].items[1])
2727 self.assertTrue('baz.h' in results[0].items[2])
2728 self.assertTrue('jumbo.h' in results[0].items[3])
2729
2730 def testAllowsToIncludeWrapper(self):
2731 mock_input_api = MockInputApi()
2732 mock_input_api.files = [
2733 MockFile('dir/baz_win.cc', ['#include "base/win/shlwapi.h"']),
2734 MockFile('dir/baz-win.h', ['#include "base/win/atl.h"']),
2735 ]
2736 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2737 self.assertEquals(0, len(results))
2738
2739 def testAllowsToCreateWrapper(self):
2740 mock_input_api = MockInputApi()
2741 mock_input_api.files = [
2742 MockFile('base/win/shlwapi.h', [
2743 '#include <shlwapi.h>',
2744 '#include "base/win/windows_defines.inc"']),
2745 ]
2746 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2747 self.assertEquals(0, len(results))
Vaclav Brozek52e18bf2018-04-03 07:05:242748
Mustafa Emre Acer51f2f742020-03-09 19:41:122749
Rainhard Findlingfc31844c52020-05-15 09:58:262750class StringTest(unittest.TestCase):
2751 """Tests ICU syntax check and translation screenshots check."""
2752
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142753 # An empty grd file.
2754 OLD_GRD_CONTENTS = """<?xml version="1.0" encoding="UTF-8"?>
2755 <grit latest_public_release="1" current_release="1">
2756 <release seq="1">
2757 <messages></messages>
2758 </release>
2759 </grit>
2760 """.splitlines()
2761 # A grd file with a single message.
2762 NEW_GRD_CONTENTS1 = """<?xml version="1.0" encoding="UTF-8"?>
2763 <grit latest_public_release="1" current_release="1">
2764 <release seq="1">
2765 <messages>
2766 <message name="IDS_TEST1">
2767 Test string 1
2768 </message>
Mustafa Emre Acere4b349c2020-06-03 23:42:482769 <message name="IDS_TEST_STRING_NON_TRANSLATEABLE1"
2770 translateable="false">
2771 Non translateable message 1, should be ignored
2772 </message>
Mustafa Emre Acered1a48962020-06-30 19:15:392773 <message name="IDS_TEST_STRING_ACCESSIBILITY"
Mustafa Emre Acerd3ca8be2020-07-07 22:35:342774 is_accessibility_with_no_ui="true">
Mustafa Emre Acered1a48962020-06-30 19:15:392775 Accessibility label 1, should be ignored
2776 </message>
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142777 </messages>
2778 </release>
2779 </grit>
2780 """.splitlines()
2781 # A grd file with two messages.
2782 NEW_GRD_CONTENTS2 = """<?xml version="1.0" encoding="UTF-8"?>
2783 <grit latest_public_release="1" current_release="1">
2784 <release seq="1">
2785 <messages>
2786 <message name="IDS_TEST1">
2787 Test string 1
2788 </message>
2789 <message name="IDS_TEST2">
2790 Test string 2
2791 </message>
Mustafa Emre Acere4b349c2020-06-03 23:42:482792 <message name="IDS_TEST_STRING_NON_TRANSLATEABLE2"
2793 translateable="false">
2794 Non translateable message 2, should be ignored
2795 </message>
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142796 </messages>
2797 </release>
2798 </grit>
2799 """.splitlines()
Rainhard Findlingfc31844c52020-05-15 09:58:262800 # A grd file with one ICU syntax message without syntax errors.
2801 NEW_GRD_CONTENTS_ICU_SYNTAX_OK1 = """<?xml version="1.0" encoding="UTF-8"?>
2802 <grit latest_public_release="1" current_release="1">
2803 <release seq="1">
2804 <messages>
2805 <message name="IDS_TEST1">
2806 {NUM, plural,
2807 =1 {Test text for numeric one}
2808 other {Test text for plural with {NUM} as number}}
2809 </message>
2810 </messages>
2811 </release>
2812 </grit>
2813 """.splitlines()
2814 # A grd file with one ICU syntax message without syntax errors.
2815 NEW_GRD_CONTENTS_ICU_SYNTAX_OK2 = """<?xml version="1.0" encoding="UTF-8"?>
2816 <grit latest_public_release="1" current_release="1">
2817 <release seq="1">
2818 <messages>
2819 <message name="IDS_TEST1">
2820 {NUM, plural,
2821 =1 {Different test text for numeric one}
2822 other {Different test text for plural with {NUM} as number}}
2823 </message>
2824 </messages>
2825 </release>
2826 </grit>
2827 """.splitlines()
2828 # A grd file with one ICU syntax message with syntax errors (misses a comma).
2829 NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR = """<?xml version="1.0" encoding="UTF-8"?>
2830 <grit latest_public_release="1" current_release="1">
2831 <release seq="1">
2832 <messages>
2833 <message name="IDS_TEST1">
2834 {NUM, plural
2835 =1 {Test text for numeric one}
2836 other {Test text for plural with {NUM} as number}}
2837 </message>
2838 </messages>
2839 </release>
2840 </grit>
2841 """.splitlines()
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142842
meacerff8a9b62019-12-10 19:43:582843 OLD_GRDP_CONTENTS = (
2844 '<?xml version="1.0" encoding="utf-8"?>',
2845 '<grit-part>',
2846 '</grit-part>'
2847 )
2848
2849 NEW_GRDP_CONTENTS1 = (
2850 '<?xml version="1.0" encoding="utf-8"?>',
2851 '<grit-part>',
2852 '<message name="IDS_PART_TEST1">',
2853 'Part string 1',
2854 '</message>',
2855 '</grit-part>')
2856
2857 NEW_GRDP_CONTENTS2 = (
2858 '<?xml version="1.0" encoding="utf-8"?>',
2859 '<grit-part>',
2860 '<message name="IDS_PART_TEST1">',
2861 'Part string 1',
2862 '</message>',
2863 '<message name="IDS_PART_TEST2">',
2864 'Part string 2',
2865 '</message>',
2866 '</grit-part>')
2867
Rainhard Findlingd8d04372020-08-13 13:30:092868 NEW_GRDP_CONTENTS3 = (
2869 '<?xml version="1.0" encoding="utf-8"?>',
2870 '<grit-part>',
2871 '<message name="IDS_PART_TEST1" desc="Description with typo.">',
2872 'Part string 1',
2873 '</message>',
2874 '</grit-part>')
2875
2876 NEW_GRDP_CONTENTS4 = (
2877 '<?xml version="1.0" encoding="utf-8"?>',
2878 '<grit-part>',
2879 '<message name="IDS_PART_TEST1" desc="Description with typo fixed.">',
2880 'Part string 1',
2881 '</message>',
2882 '</grit-part>')
2883
Rainhard Findling1a3e71e2020-09-21 07:33:352884 NEW_GRDP_CONTENTS5 = (
2885 '<?xml version="1.0" encoding="utf-8"?>',
2886 '<grit-part>',
2887 '<message name="IDS_PART_TEST1" meaning="Meaning with typo.">',
2888 'Part string 1',
2889 '</message>',
2890 '</grit-part>')
2891
2892 NEW_GRDP_CONTENTS6 = (
2893 '<?xml version="1.0" encoding="utf-8"?>',
2894 '<grit-part>',
2895 '<message name="IDS_PART_TEST1" meaning="Meaning with typo fixed.">',
2896 'Part string 1',
2897 '</message>',
2898 '</grit-part>')
2899
Rainhard Findlingfc31844c52020-05-15 09:58:262900 # A grdp file with one ICU syntax message without syntax errors.
2901 NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1 = (
2902 '<?xml version="1.0" encoding="utf-8"?>',
2903 '<grit-part>',
2904 '<message name="IDS_PART_TEST1">',
2905 '{NUM, plural,',
2906 '=1 {Test text for numeric one}',
2907 'other {Test text for plural with {NUM} as number}}',
2908 '</message>',
2909 '</grit-part>')
2910 # A grdp file with one ICU syntax message without syntax errors.
2911 NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2 = (
2912 '<?xml version="1.0" encoding="utf-8"?>',
2913 '<grit-part>',
2914 '<message name="IDS_PART_TEST1">',
2915 '{NUM, plural,',
2916 '=1 {Different test text for numeric one}',
2917 'other {Different test text for plural with {NUM} as number}}',
2918 '</message>',
2919 '</grit-part>')
2920
2921 # A grdp file with one ICU syntax message with syntax errors (superfluent
2922 # whitespace).
2923 NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR = (
2924 '<?xml version="1.0" encoding="utf-8"?>',
2925 '<grit-part>',
2926 '<message name="IDS_PART_TEST1">',
2927 '{NUM, plural,',
2928 '= 1 {Test text for numeric one}',
2929 'other {Test text for plural with {NUM} as number}}',
2930 '</message>',
2931 '</grit-part>')
2932
Mustafa Emre Acerc8a012d2018-07-31 00:00:392933 DO_NOT_UPLOAD_PNG_MESSAGE = ('Do not include actual screenshots in the '
2934 'changelist. Run '
2935 'tools/translate/upload_screenshots.py to '
2936 'upload them instead:')
2937 GENERATE_SIGNATURES_MESSAGE = ('You are adding or modifying UI strings.\n'
2938 'To ensure the best translations, take '
2939 'screenshots of the relevant UI '
2940 '(https://g.co/chrome/translation) and add '
2941 'these files to your changelist:')
2942 REMOVE_SIGNATURES_MESSAGE = ('You removed strings associated with these '
2943 'files. Remove:')
Rainhard Findlingfc31844c52020-05-15 09:58:262944 ICU_SYNTAX_ERROR_MESSAGE = ('ICU syntax errors were found in the following '
2945 'strings (problems or feedback? Contact '
2946 '[email protected]):')
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142947
2948 def makeInputApi(self, files):
2949 input_api = MockInputApi()
2950 input_api.files = files
meacere7be7532019-10-02 17:41:032951 # Override os_path.exists because the presubmit uses the actual
2952 # os.path.exists.
2953 input_api.CreateMockFileInPath(
2954 [x.LocalPath() for x in input_api.AffectedFiles(include_deletes=True)])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142955 return input_api
2956
meacerff8a9b62019-12-10 19:43:582957 """ CL modified and added messages, but didn't add any screenshots."""
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142958 def testNoScreenshots(self):
meacerff8a9b62019-12-10 19:43:582959 # No new strings (file contents same). Should not warn.
2960 input_api = self.makeInputApi([
2961 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS1,
2962 self.NEW_GRD_CONTENTS1, action='M'),
2963 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS1,
2964 self.NEW_GRDP_CONTENTS1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:362965 warnings = PRESUBMIT.CheckStrings(input_api,
meacerff8a9b62019-12-10 19:43:582966 MockOutputApi())
2967 self.assertEqual(0, len(warnings))
2968
2969 # Add two new strings. Should have two warnings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142970 input_api = self.makeInputApi([
2971 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
meacerff8a9b62019-12-10 19:43:582972 self.NEW_GRD_CONTENTS1, action='M'),
2973 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
2974 self.NEW_GRDP_CONTENTS1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:362975 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142976 MockOutputApi())
2977 self.assertEqual(1, len(warnings))
2978 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acerc6ed2682020-07-07 07:24:002979 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012980 self.assertEqual([
meacerff8a9b62019-12-10 19:43:582981 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2982 os.path.join('test_grd', 'IDS_TEST2.png.sha1')],
2983 warnings[0].items)
Mustafa Emre Acer36eaad52019-11-12 23:03:342984
meacerff8a9b62019-12-10 19:43:582985 # Add four new strings. Should have four warnings.
Mustafa Emre Acerad8fb082019-11-19 04:24:212986 input_api = self.makeInputApi([
2987 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
meacerff8a9b62019-12-10 19:43:582988 self.OLD_GRD_CONTENTS, action='M'),
2989 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
2990 self.OLD_GRDP_CONTENTS, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:362991 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acerad8fb082019-11-19 04:24:212992 MockOutputApi())
2993 self.assertEqual(1, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:002994 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acerad8fb082019-11-19 04:24:212995 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:582996 self.assertEqual([
2997 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2998 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2999 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
3000 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
3001 ], warnings[0].items)
Mustafa Emre Acerad8fb082019-11-19 04:24:213002
Rainhard Findlingd8d04372020-08-13 13:30:093003 def testModifiedMessageDescription(self):
3004 # CL modified a message description for a message that does not yet have a
Rainhard Findling1a3e71e2020-09-21 07:33:353005 # screenshot. Should not warn.
Rainhard Findlingd8d04372020-08-13 13:30:093006 input_api = self.makeInputApi([
3007 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS3,
3008 self.NEW_GRDP_CONTENTS4, action='M')])
3009 warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findling1a3e71e2020-09-21 07:33:353010 self.assertEqual(0, len(warnings))
Rainhard Findlingd8d04372020-08-13 13:30:093011
3012 # CL modified a message description for a message that already has a
3013 # screenshot. Should not warn.
3014 input_api = self.makeInputApi([
3015 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS3,
3016 self.NEW_GRDP_CONTENTS4, action='M'),
3017 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3018 'binary', action='A')])
3019 warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
3020 self.assertEqual(0, len(warnings))
3021
Rainhard Findling1a3e71e2020-09-21 07:33:353022 def testModifiedMessageMeaning(self):
3023 # CL modified a message meaning for a message that does not yet have a
3024 # screenshot. Should warn.
3025 input_api = self.makeInputApi([
3026 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS5,
3027 self.NEW_GRDP_CONTENTS6, action='M')])
3028 warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
3029 self.assertEqual(1, len(warnings))
3030
3031 # CL modified a message meaning for a message that already has a
3032 # screenshot. Should not warn.
3033 input_api = self.makeInputApi([
3034 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS5,
3035 self.NEW_GRDP_CONTENTS6, action='M'),
3036 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3037 'binary', action='A')])
3038 warnings = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
3039 self.assertEqual(0, len(warnings))
3040
meacerff8a9b62019-12-10 19:43:583041 def testPngAddedSha1NotAdded(self):
3042 # CL added one new message in a grd file and added the png file associated
3043 # with it, but did not add the corresponding sha1 file. This should warn
3044 # twice:
3045 # - Once for the added png file (because we don't want developers to upload
3046 # actual images)
3047 # - Once for the missing .sha1 file
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143048 input_api = self.makeInputApi([
Mustafa Emre Acerea3e57a2018-12-17 23:51:013049 MockAffectedFile(
3050 'test.grd',
3051 self.NEW_GRD_CONTENTS1,
3052 self.OLD_GRD_CONTENTS,
3053 action='M'),
3054 MockAffectedFile(
3055 os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A')
3056 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363057 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143058 MockOutputApi())
3059 self.assertEqual(2, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:003060 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143061 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:013062 self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png')],
3063 warnings[0].items)
Mustafa Emre Acerc6ed2682020-07-07 07:24:003064 self.assertEqual('error', warnings[1].type)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143065 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:013066 self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
3067 warnings[1].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143068
meacerff8a9b62019-12-10 19:43:583069 # CL added two messages (one in grd, one in grdp) and added the png files
3070 # associated with the messages, but did not add the corresponding sha1
3071 # files. This should warn twice:
3072 # - Once for the added png files (because we don't want developers to upload
3073 # actual images)
3074 # - Once for the missing .sha1 files
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143075 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583076 # Modified files:
Mustafa Emre Acer36eaad52019-11-12 23:03:343077 MockAffectedFile(
3078 'test.grd',
meacerff8a9b62019-12-10 19:43:583079 self.NEW_GRD_CONTENTS1,
Mustafa Emre Acer36eaad52019-11-12 23:03:343080 self.OLD_GRD_CONTENTS,
meacer2308d0742019-11-12 18:15:423081 action='M'),
Mustafa Emre Acer12e7fee2019-11-18 18:49:553082 MockAffectedFile(
meacerff8a9b62019-12-10 19:43:583083 'part.grdp',
3084 self.NEW_GRDP_CONTENTS1,
3085 self.OLD_GRDP_CONTENTS,
3086 action='M'),
3087 # Added files:
3088 MockAffectedFile(
3089 os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A'),
3090 MockAffectedFile(
3091 os.path.join('part_grdp', 'IDS_PART_TEST1.png'), 'binary',
3092 action='A')
Mustafa Emre Acerad8fb082019-11-19 04:24:213093 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363094 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acerad8fb082019-11-19 04:24:213095 MockOutputApi())
3096 self.assertEqual(2, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:003097 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acerad8fb082019-11-19 04:24:213098 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:583099 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png'),
3100 os.path.join('test_grd', 'IDS_TEST1.png')],
Mustafa Emre Acerad8fb082019-11-19 04:24:213101 warnings[0].items)
Mustafa Emre Acerc6ed2682020-07-07 07:24:003102 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acerad8fb082019-11-19 04:24:213103 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
meacerff8a9b62019-12-10 19:43:583104 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3105 os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
3106 warnings[1].items)
Mustafa Emre Acerad8fb082019-11-19 04:24:213107
3108 def testScreenshotsWithSha1(self):
meacerff8a9b62019-12-10 19:43:583109 # CL added four messages (two each in a grd and grdp) and their
3110 # corresponding .sha1 files. No warnings.
Mustafa Emre Acerad8fb082019-11-19 04:24:213111 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583112 # Modified files:
Mustafa Emre Acerad8fb082019-11-19 04:24:213113 MockAffectedFile(
3114 'test.grd',
3115 self.NEW_GRD_CONTENTS2,
3116 self.OLD_GRD_CONTENTS,
Mustafa Emre Acer12e7fee2019-11-18 18:49:553117 action='M'),
meacerff8a9b62019-12-10 19:43:583118 MockAffectedFile(
3119 'part.grdp',
3120 self.NEW_GRDP_CONTENTS2,
3121 self.OLD_GRDP_CONTENTS,
3122 action='M'),
3123 # Added files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013124 MockFile(
3125 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
3126 'binary',
3127 action='A'),
3128 MockFile(
3129 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
3130 'binary',
meacerff8a9b62019-12-10 19:43:583131 action='A'),
3132 MockFile(
3133 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3134 'binary',
3135 action='A'),
3136 MockFile(
3137 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
3138 'binary',
3139 action='A'),
Mustafa Emre Acerea3e57a2018-12-17 23:51:013140 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363141 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143142 MockOutputApi())
3143 self.assertEqual([], warnings)
3144
3145 def testScreenshotsRemovedWithSha1(self):
meacerff8a9b62019-12-10 19:43:583146 # Replace new contents with old contents in grd and grp files, removing
3147 # IDS_TEST1, IDS_TEST2, IDS_PART_TEST1 and IDS_PART_TEST2.
3148 # Should warn to remove the sha1 files associated with these strings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143149 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583150 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013151 MockAffectedFile(
3152 'test.grd',
meacerff8a9b62019-12-10 19:43:583153 self.OLD_GRD_CONTENTS, # new_contents
3154 self.NEW_GRD_CONTENTS2, # old_contents
Mustafa Emre Acerea3e57a2018-12-17 23:51:013155 action='M'),
meacerff8a9b62019-12-10 19:43:583156 MockAffectedFile(
3157 'part.grdp',
3158 self.OLD_GRDP_CONTENTS, # new_contents
3159 self.NEW_GRDP_CONTENTS2, # old_contents
3160 action='M'),
3161 # Unmodified files:
3162 MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
3163 MockFile(os.path.join('test_grd', 'IDS_TEST2.png.sha1'), 'binary', ''),
3164 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3165 'binary', ''),
3166 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
3167 'binary', '')
Mustafa Emre Acerea3e57a2018-12-17 23:51:013168 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363169 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143170 MockOutputApi())
3171 self.assertEqual(1, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:003172 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143173 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:013174 self.assertEqual([
meacerff8a9b62019-12-10 19:43:583175 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3176 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
Mustafa Emre Acerea3e57a2018-12-17 23:51:013177 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
3178 os.path.join('test_grd', 'IDS_TEST2.png.sha1')
3179 ], warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143180
meacerff8a9b62019-12-10 19:43:583181 # Same as above, but this time one of the .sha1 files is also removed.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143182 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583183 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013184 MockAffectedFile(
3185 'test.grd',
meacerff8a9b62019-12-10 19:43:583186 self.OLD_GRD_CONTENTS, # new_contents
3187 self.NEW_GRD_CONTENTS2, # old_contents
Mustafa Emre Acerea3e57a2018-12-17 23:51:013188 action='M'),
meacerff8a9b62019-12-10 19:43:583189 MockAffectedFile(
3190 'part.grdp',
3191 self.OLD_GRDP_CONTENTS, # new_contents
3192 self.NEW_GRDP_CONTENTS2, # old_contents
3193 action='M'),
3194 # Unmodified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013195 MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
meacerff8a9b62019-12-10 19:43:583196 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3197 'binary', ''),
3198 # Deleted files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013199 MockAffectedFile(
3200 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
3201 '',
3202 'old_contents',
meacerff8a9b62019-12-10 19:43:583203 action='D'),
3204 MockAffectedFile(
3205 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
3206 '',
3207 'old_contents',
Mustafa Emre Acerea3e57a2018-12-17 23:51:013208 action='D')
3209 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363210 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143211 MockOutputApi())
3212 self.assertEqual(1, len(warnings))
Mustafa Emre Acerc6ed2682020-07-07 07:24:003213 self.assertEqual('error', warnings[0].type)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143214 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:583215 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3216 os.path.join('test_grd', 'IDS_TEST1.png.sha1')
3217 ], warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143218
meacerff8a9b62019-12-10 19:43:583219 # Remove all sha1 files. There should be no warnings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143220 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:583221 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013222 MockAffectedFile(
3223 'test.grd',
3224 self.OLD_GRD_CONTENTS,
3225 self.NEW_GRD_CONTENTS2,
3226 action='M'),
meacerff8a9b62019-12-10 19:43:583227 MockAffectedFile(
3228 'part.grdp',
3229 self.OLD_GRDP_CONTENTS,
3230 self.NEW_GRDP_CONTENTS2,
3231 action='M'),
3232 # Deleted files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:013233 MockFile(
3234 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
3235 'binary',
3236 action='D'),
3237 MockFile(
3238 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
3239 'binary',
meacerff8a9b62019-12-10 19:43:583240 action='D'),
3241 MockFile(
3242 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
3243 'binary',
3244 action='D'),
3245 MockFile(
3246 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
3247 'binary',
Mustafa Emre Acerea3e57a2018-12-17 23:51:013248 action='D')
3249 ])
Saagar Sanghavifceeaae2020-08-12 16:40:363250 warnings = PRESUBMIT.CheckStrings(input_api,
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143251 MockOutputApi())
3252 self.assertEqual([], warnings)
3253
Rainhard Findlingfc31844c52020-05-15 09:58:263254 def testIcuSyntax(self):
3255 # Add valid ICU syntax string. Should not raise an error.
3256 input_api = self.makeInputApi([
3257 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK2,
3258 self.NEW_GRD_CONTENTS1, action='M'),
3259 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2,
3260 self.NEW_GRDP_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 no ICU syntax errors.
3263 icu_errors = [e for e in results
3264 if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
3265 self.assertEqual(0, len(icu_errors))
3266
3267 # Valid changes in ICU syntax. Should not raise an error.
3268 input_api = self.makeInputApi([
3269 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK2,
3270 self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK1, action='M'),
3271 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK2,
3272 self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:363273 results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findlingfc31844c52020-05-15 09:58:263274 # We expect no ICU syntax errors.
3275 icu_errors = [e for e in results
3276 if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
3277 self.assertEqual(0, len(icu_errors))
3278
3279 # Add invalid ICU syntax strings. Should raise two errors.
3280 input_api = self.makeInputApi([
3281 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR,
3282 self.NEW_GRD_CONTENTS1, action='M'),
3283 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR,
3284 self.NEW_GRD_CONTENTS1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:363285 results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findlingfc31844c52020-05-15 09:58:263286 # We expect 2 ICU syntax errors.
3287 icu_errors = [e for e in results
3288 if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
3289 self.assertEqual(1, len(icu_errors))
3290 self.assertEqual([
3291 'IDS_TEST1: This message looks like an ICU plural, but does not follow '
3292 'ICU syntax.',
3293 'IDS_PART_TEST1: Variant "= 1" is not valid for plural message'
3294 ], icu_errors[0].items)
3295
3296 # Change two strings to have ICU syntax errors. Should raise two errors.
3297 input_api = self.makeInputApi([
3298 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS_ICU_SYNTAX_ERROR,
3299 self.NEW_GRD_CONTENTS_ICU_SYNTAX_OK1, action='M'),
3300 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS_ICU_SYNTAX_ERROR,
3301 self.NEW_GRDP_CONTENTS_ICU_SYNTAX_OK1, action='M')])
Saagar Sanghavifceeaae2020-08-12 16:40:363302 results = PRESUBMIT.CheckStrings(input_api, MockOutputApi())
Rainhard Findlingfc31844c52020-05-15 09:58:263303 # We expect 2 ICU syntax errors.
3304 icu_errors = [e for e in results
3305 if e.message == self.ICU_SYNTAX_ERROR_MESSAGE]
3306 self.assertEqual(1, len(icu_errors))
3307 self.assertEqual([
3308 'IDS_TEST1: This message looks like an ICU plural, but does not follow '
3309 'ICU syntax.',
3310 'IDS_PART_TEST1: Variant "= 1" is not valid for plural message'
3311 ], icu_errors[0].items)
3312
Mustafa Emre Acer29bf6ac92018-07-30 21:42:143313
Mustafa Emre Acer51f2f742020-03-09 19:41:123314class TranslationExpectationsTest(unittest.TestCase):
3315 ERROR_MESSAGE_FORMAT = (
3316 "Failed to get a list of translatable grd files. "
3317 "This happens when:\n"
3318 " - One of the modified grd or grdp files cannot be parsed or\n"
3319 " - %s is not updated.\n"
3320 "Stack:\n"
3321 )
3322 REPO_ROOT = os.path.join('tools', 'translation', 'testdata')
3323 # This lists all .grd files under REPO_ROOT.
3324 EXPECTATIONS = os.path.join(REPO_ROOT,
3325 "translation_expectations.pyl")
3326 # This lists all .grd files under REPO_ROOT except unlisted.grd.
3327 EXPECTATIONS_WITHOUT_UNLISTED_FILE = os.path.join(
3328 REPO_ROOT, "translation_expectations_without_unlisted_file.pyl")
3329
3330 # Tests that the presubmit doesn't return when no grd or grdp files are
3331 # modified.
3332 def testExpectationsNoModifiedGrd(self):
3333 input_api = MockInputApi()
3334 input_api.files = [
3335 MockAffectedFile('not_used.txt', 'not used', 'not used', action='M')
3336 ]
3337 # Fake list of all grd files in the repo. This list is missing all grd/grdps
3338 # under tools/translation/testdata. This is OK because the presubmit won't
3339 # run in the first place since there are no modified grd/grps in input_api.
3340 grd_files = ['doesnt_exist_doesnt_matter.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363341 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123342 input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
3343 grd_files)
3344 self.assertEqual(0, len(warnings))
3345
3346
3347 # Tests that the list of files passed to the presubmit matches the list of
3348 # files in the expectations.
3349 def testExpectationsSuccess(self):
3350 # Mock input file list needs a grd or grdp file in order to run the
3351 # presubmit. The file itself doesn't matter.
3352 input_api = MockInputApi()
3353 input_api.files = [
3354 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3355 ]
3356 # List of all grd files in the repo.
3357 grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
3358 'internal.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363359 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123360 input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
3361 grd_files)
3362 self.assertEqual(0, len(warnings))
3363
3364 # Tests that the presubmit warns when a file is listed in expectations, but
3365 # does not actually exist.
3366 def testExpectationsMissingFile(self):
3367 # Mock input file list needs a grd or grdp file in order to run the
3368 # presubmit.
3369 input_api = MockInputApi()
3370 input_api.files = [
3371 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3372 ]
3373 # unlisted.grd is listed under tools/translation/testdata but is not
3374 # included in translation expectations.
3375 grd_files = ['unlisted.grd', 'not_translated.grd', '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, self.EXPECTATIONS,
3378 grd_files)
3379 self.assertEqual(1, len(warnings))
3380 self.assertTrue(warnings[0].message.startswith(
3381 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS))
3382 self.assertTrue(
3383 ("test.grd is listed in the translation expectations, "
3384 "but this grd file does not exist")
3385 in warnings[0].message)
3386
3387 # Tests that the presubmit warns when a file is not listed in expectations but
3388 # does actually exist.
3389 def testExpectationsUnlistedFile(self):
3390 # Mock input file list needs a grd or grdp file in order to run the
3391 # presubmit.
3392 input_api = MockInputApi()
3393 input_api.files = [
3394 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3395 ]
3396 # unlisted.grd is listed under tools/translation/testdata but is not
3397 # included in translation expectations.
3398 grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
3399 'internal.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363400 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123401 input_api, MockOutputApi(), self.REPO_ROOT,
3402 self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
3403 self.assertEqual(1, len(warnings))
3404 self.assertTrue(warnings[0].message.startswith(
3405 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
3406 self.assertTrue(
3407 ("unlisted.grd appears to be translatable "
3408 "(because it contains <file> or <message> elements), "
3409 "but is not listed in the translation expectations.")
3410 in warnings[0].message)
3411
3412 # Tests that the presubmit warns twice:
3413 # - for a non-existing file listed in expectations
3414 # - for an existing file not listed in expectations
3415 def testMultipleWarnings(self):
3416 # Mock input file list needs a grd or grdp file in order to run the
3417 # presubmit.
3418 input_api = MockInputApi()
3419 input_api.files = [
3420 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3421 ]
3422 # unlisted.grd is listed under tools/translation/testdata but is not
3423 # included in translation expectations.
3424 # test.grd is not listed under tools/translation/testdata but is included
3425 # in translation expectations.
3426 grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
Saagar Sanghavifceeaae2020-08-12 16:40:363427 warnings = PRESUBMIT.CheckTranslationExpectations(
Mustafa Emre Acer51f2f742020-03-09 19:41:123428 input_api, MockOutputApi(), self.REPO_ROOT,
3429 self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
3430 self.assertEqual(1, len(warnings))
3431 self.assertTrue(warnings[0].message.startswith(
3432 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
3433 self.assertTrue(
3434 ("unlisted.grd appears to be translatable "
3435 "(because it contains <file> or <message> elements), "
3436 "but is not listed in the translation expectations.")
3437 in warnings[0].message)
3438 self.assertTrue(
3439 ("test.grd is listed in the translation expectations, "
3440 "but this grd file does not exist")
3441 in warnings[0].message)
3442
3443
Dominic Battre033531052018-09-24 15:45:343444class DISABLETypoInTest(unittest.TestCase):
3445
3446 def testPositive(self):
3447 # Verify the typo "DISABLE_" instead of "DISABLED_" in various contexts
3448 # where the desire is to disable a test.
3449 tests = [
3450 # Disabled on one platform:
3451 '#if defined(OS_WIN)\n'
3452 '#define MAYBE_FoobarTest DISABLE_FoobarTest\n'
3453 '#else\n'
3454 '#define MAYBE_FoobarTest FoobarTest\n'
3455 '#endif\n',
3456 # Disabled on one platform spread cross lines:
3457 '#if defined(OS_WIN)\n'
3458 '#define MAYBE_FoobarTest \\\n'
3459 ' DISABLE_FoobarTest\n'
3460 '#else\n'
3461 '#define MAYBE_FoobarTest FoobarTest\n'
3462 '#endif\n',
3463 # Disabled on all platforms:
3464 ' TEST_F(FoobarTest, DISABLE_Foo)\n{\n}',
3465 # Disabled on all platforms but multiple lines
3466 ' TEST_F(FoobarTest,\n DISABLE_foo){\n}\n',
3467 ]
3468
3469 for test in tests:
3470 mock_input_api = MockInputApi()
3471 mock_input_api.files = [
3472 MockFile('some/path/foo_unittest.cc', test.splitlines()),
3473 ]
3474
Saagar Sanghavifceeaae2020-08-12 16:40:363475 results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
Dominic Battre033531052018-09-24 15:45:343476 MockOutputApi())
3477 self.assertEqual(
3478 1,
3479 len(results),
3480 msg=('expected len(results) == 1 but got %d in test: %s' %
3481 (len(results), test)))
3482 self.assertTrue(
3483 'foo_unittest.cc' in results[0].message,
3484 msg=('expected foo_unittest.cc in message but got %s in test %s' %
3485 (results[0].message, test)))
3486
3487 def testIngoreNotTestFiles(self):
3488 mock_input_api = MockInputApi()
3489 mock_input_api.files = [
3490 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, DISABLE_Foo)'),
3491 ]
3492
Saagar Sanghavifceeaae2020-08-12 16:40:363493 results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
Dominic Battre033531052018-09-24 15:45:343494 MockOutputApi())
3495 self.assertEqual(0, len(results))
3496
Katie Df13948e2018-09-25 07:33:443497 def testIngoreDeletedFiles(self):
3498 mock_input_api = MockInputApi()
3499 mock_input_api.files = [
3500 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, Foo)', action='D'),
3501 ]
3502
Saagar Sanghavifceeaae2020-08-12 16:40:363503 results = PRESUBMIT.CheckNoDISABLETypoInTests(mock_input_api,
Katie Df13948e2018-09-25 07:33:443504 MockOutputApi())
3505 self.assertEqual(0, len(results))
Dominic Battre033531052018-09-24 15:45:343506
Dirk Pranke3c18a382019-03-15 01:07:513507
3508class BuildtoolsRevisionsAreInSyncTest(unittest.TestCase):
3509 # TODO(crbug.com/941824): We need to make sure the entries in
3510 # //buildtools/DEPS are kept in sync with the entries in //DEPS
3511 # so that users of //buildtools in other projects get the same tooling
3512 # Chromium gets. If we ever fix the referenced bug and add 'includedeps'
3513 # support to gclient, we can eliminate the duplication and delete
3514 # these tests for the corresponding presubmit check.
3515
3516 def _check(self, files):
3517 mock_input_api = MockInputApi()
3518 mock_input_api.files = []
3519 for fname, contents in files.items():
3520 mock_input_api.files.append(MockFile(fname, contents.splitlines()))
Saagar Sanghavifceeaae2020-08-12 16:40:363521 return PRESUBMIT.CheckBuildtoolsRevisionsAreInSync(mock_input_api,
Dirk Pranke3c18a382019-03-15 01:07:513522 MockOutputApi())
3523
3524 def testOneFileChangedButNotTheOther(self):
3525 results = self._check({
3526 "DEPS": "'libunwind_revision': 'onerev'",
3527 })
3528 self.assertNotEqual(results, [])
3529
3530 def testNeitherFileChanged(self):
3531 results = self._check({
3532 "OWNERS": "[email protected]",
3533 })
3534 self.assertEqual(results, [])
3535
3536 def testBothFilesChangedAndMatch(self):
3537 results = self._check({
3538 "DEPS": "'libunwind_revision': 'onerev'",
3539 "buildtools/DEPS": "'libunwind_revision': 'onerev'",
3540 })
3541 self.assertEqual(results, [])
3542
3543 def testBothFilesWereChangedAndDontMatch(self):
3544 results = self._check({
3545 "DEPS": "'libunwind_revision': 'onerev'",
3546 "buildtools/DEPS": "'libunwind_revision': 'anotherrev'",
3547 })
3548 self.assertNotEqual(results, [])
3549
3550
Max Morozb47503b2019-08-08 21:03:273551class CheckFuzzTargetsTest(unittest.TestCase):
3552
3553 def _check(self, files):
3554 mock_input_api = MockInputApi()
3555 mock_input_api.files = []
3556 for fname, contents in files.items():
3557 mock_input_api.files.append(MockFile(fname, contents.splitlines()))
Saagar Sanghavifceeaae2020-08-12 16:40:363558 return PRESUBMIT.CheckFuzzTargetsOnUpload(mock_input_api, MockOutputApi())
Max Morozb47503b2019-08-08 21:03:273559
3560 def testLibFuzzerSourcesIgnored(self):
3561 results = self._check({
3562 "third_party/lib/Fuzzer/FuzzerDriver.cpp": "LLVMFuzzerInitialize",
3563 })
3564 self.assertEqual(results, [])
3565
3566 def testNonCodeFilesIgnored(self):
3567 results = self._check({
3568 "README.md": "LLVMFuzzerInitialize",
3569 })
3570 self.assertEqual(results, [])
3571
3572 def testNoErrorHeaderPresent(self):
3573 results = self._check({
3574 "fuzzer.cc": (
3575 "#include \"testing/libfuzzer/libfuzzer_exports.h\"\n" +
3576 "LLVMFuzzerInitialize"
3577 )
3578 })
3579 self.assertEqual(results, [])
3580
3581 def testErrorMissingHeader(self):
3582 results = self._check({
3583 "fuzzer.cc": "LLVMFuzzerInitialize"
3584 })
3585 self.assertEqual(len(results), 1)
3586 self.assertEqual(results[0].items, ['fuzzer.cc'])
3587
3588
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263589class SetNoParentTest(unittest.TestCase):
3590 def testSetNoParentMissing(self):
3591 mock_input_api = MockInputApi()
3592 mock_input_api.files = [
3593 MockAffectedFile('goat/OWNERS',
3594 [
3595 'set noparent',
3596 '[email protected]',
3597 'per-file *.json=set noparent',
3598 'per-file *[email protected]',
3599 ])
3600 ]
3601 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:363602 errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263603 self.assertEqual(1, len(errors))
3604 self.assertTrue('goat/OWNERS:1' in errors[0].long_text)
3605 self.assertTrue('goat/OWNERS:3' in errors[0].long_text)
3606
3607
3608 def testSetNoParentWithCorrectRule(self):
3609 mock_input_api = MockInputApi()
3610 mock_input_api.files = [
3611 MockAffectedFile('goat/OWNERS',
3612 [
3613 'set noparent',
3614 'file://ipc/SECURITY_OWNERS',
3615 'per-file *.json=set noparent',
3616 'per-file *.json=file://ipc/SECURITY_OWNERS',
3617 ])
3618 ]
3619 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:363620 errors = PRESUBMIT.CheckSetNoParent(mock_input_api, mock_output_api)
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263621 self.assertEqual([], errors)
3622
3623
Ken Rockotc31f4832020-05-29 18:58:513624class MojomStabilityCheckTest(unittest.TestCase):
3625 def runTestWithAffectedFiles(self, affected_files):
3626 mock_input_api = MockInputApi()
3627 mock_input_api.files = affected_files
3628 mock_output_api = MockOutputApi()
Saagar Sanghavifceeaae2020-08-12 16:40:363629 return PRESUBMIT.CheckStableMojomChanges(
Ken Rockotc31f4832020-05-29 18:58:513630 mock_input_api, mock_output_api)
3631
3632 def testSafeChangePasses(self):
3633 errors = self.runTestWithAffectedFiles([
3634 MockAffectedFile('foo/foo.mojom',
3635 ['[Stable] struct S { [MinVersion=1] int32 x; };'],
3636 old_contents=['[Stable] struct S {};'])
3637 ])
3638 self.assertEqual([], errors)
3639
3640 def testBadChangeFails(self):
3641 errors = self.runTestWithAffectedFiles([
3642 MockAffectedFile('foo/foo.mojom',
3643 ['[Stable] struct S { int32 x; };'],
3644 old_contents=['[Stable] struct S {};'])
3645 ])
3646 self.assertEqual(1, len(errors))
3647 self.assertTrue('not backward-compatible' in errors[0].message)
3648
Ken Rockotad7901f942020-06-04 20:17:093649 def testDeletedFile(self):
3650 """Regression test for https://crbug.com/1091407."""
3651 errors = self.runTestWithAffectedFiles([
3652 MockAffectedFile('a.mojom', [], old_contents=['struct S {};'],
3653 action='D'),
3654 MockAffectedFile('b.mojom',
3655 ['struct S {}; struct T { S s; };'],
3656 old_contents=['import "a.mojom"; struct T { S s; };'])
3657 ])
3658 self.assertEqual([], errors)
3659
Ken Rockotc31f4832020-05-29 18:58:513660
[email protected]2299dcf2012-11-15 19:56:243661if __name__ == '__main__':
3662 unittest.main()