blob: a15c15fa029b5bdfed4244eae14bc80302b8b005 [file] [log] [blame]
[email protected]2299dcf2012-11-15 19:56:241#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Daniel Cheng4dcdb6b2017-04-13 08:30:176import os.path
[email protected]99171a92014-06-03 08:44:477import subprocess
[email protected]2299dcf2012-11-15 19:56:248import unittest
9
10import PRESUBMIT
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3911from PRESUBMIT_test_mocks import MockFile, MockAffectedFile
gayane3dff8c22014-12-04 17:09:5112from PRESUBMIT_test_mocks import MockInputApi, MockOutputApi
[email protected]2299dcf2012-11-15 19:56:2413
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3914
[email protected]99171a92014-06-03 08:44:4715_TEST_DATA_DIR = 'base/test/data/presubmit'
16
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3917
[email protected]b00342e7f2013-03-26 16:21:5418class VersionControlConflictsTest(unittest.TestCase):
[email protected]70ca77752012-11-20 03:45:0319 def testTypicalConflict(self):
20 lines = ['<<<<<<< HEAD',
21 ' base::ScopedTempDir temp_dir_;',
22 '=======',
23 ' ScopedTempDir temp_dir_;',
24 '>>>>>>> master']
25 errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
26 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
27 self.assertEqual(3, len(errors))
28 self.assertTrue('1' in errors[0])
29 self.assertTrue('3' in errors[1])
30 self.assertTrue('5' in errors[2])
31
dbeam95c35a2f2015-06-02 01:40:2332 def testIgnoresReadmes(self):
33 lines = ['A First Level Header',
34 '====================',
35 '',
36 'A Second Level Header',
37 '---------------------']
38 errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
39 MockInputApi(), MockFile('some/polymer/README.md', lines))
40 self.assertEqual(0, len(errors))
41
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3942
mcasasb7440c282015-02-04 14:52:1943class UmaHistogramChangeMatchedOrNotTest(unittest.TestCase):
44 def testTypicalCorrectlyMatchedChange(self):
45 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4746 diff_java = [
47 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1948 diff_xml = ['<histogram name="Bla.Foo.Dummy"> </histogram>']
49 mock_input_api = MockInputApi()
50 mock_input_api.files = [
51 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:4752 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:1953 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
54 ]
55 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
56 MockOutputApi())
57 self.assertEqual(0, len(warnings))
58
59 def testTypicalNotMatchedChange(self):
60 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4761 diff_java = [
62 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1963 mock_input_api = MockInputApi()
Vaclav Brozekbdac817c2018-03-24 06:30:4764 mock_input_api.files = [
65 MockFile('some/path/foo.cc', diff_cc),
66 MockFile('some/path/foo.java', diff_java),
67 ]
mcasasb7440c282015-02-04 14:52:1968 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
69 MockOutputApi())
70 self.assertEqual(1, len(warnings))
71 self.assertEqual('warning', warnings[0].type)
Vaclav Brozekbdac817c2018-03-24 06:30:4772 self.assertTrue('foo.cc' in warnings[0].items[0])
73 self.assertTrue('foo.java' in warnings[0].items[1])
mcasasb7440c282015-02-04 14:52:1974
75 def testTypicalNotMatchedChangeViaSuffixes(self):
76 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4777 diff_java = [
78 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1979 diff_xml = ['<histogram_suffixes name="SuperHistogram">',
80 ' <suffix name="Dummy"/>',
81 ' <affected-histogram name="Snafu.Dummy"/>',
82 '</histogram>']
83 mock_input_api = MockInputApi()
84 mock_input_api.files = [
85 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:4786 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:1987 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
88 ]
89 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
90 MockOutputApi())
91 self.assertEqual(1, len(warnings))
92 self.assertEqual('warning', warnings[0].type)
Vaclav Brozekbdac817c2018-03-24 06:30:4793 self.assertTrue('foo.cc' in warnings[0].items[0])
94 self.assertTrue('foo.java' in warnings[0].items[1])
mcasasb7440c282015-02-04 14:52:1995
96 def testTypicalCorrectlyMatchedChangeViaSuffixes(self):
97 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4798 diff_java = [
99 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:19100 diff_xml = ['<histogram_suffixes name="SuperHistogram">',
101 ' <suffix name="Dummy"/>',
102 ' <affected-histogram name="Bla.Foo"/>',
103 '</histogram>']
104 mock_input_api = MockInputApi()
105 mock_input_api.files = [
106 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47107 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:19108 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
109 ]
110 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
111 MockOutputApi())
112 self.assertEqual(0, len(warnings))
113
114 def testTypicalCorrectlyMatchedChangeViaSuffixesWithSeparator(self):
115 diff_cc = ['UMA_HISTOGRAM_BOOL("Snafu_Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:47116 diff_java = ['RecordHistogram.recordBooleanHistogram("Snafu_Dummy", true)']
mcasasb7440c282015-02-04 14:52:19117 diff_xml = ['<histogram_suffixes name="SuperHistogram" separator="_">',
118 ' <suffix name="Dummy"/>',
119 ' <affected-histogram name="Snafu"/>',
120 '</histogram>']
121 mock_input_api = MockInputApi()
122 mock_input_api.files = [
123 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47124 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:19125 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
126 ]
127 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
128 MockOutputApi())
129 self.assertEqual(0, len(warnings))
[email protected]70ca77752012-11-20 03:45:03130
Makoto Shimazu3ad422cd2019-05-08 02:35:14131 def testCorrectlyMatchedChangeViaSuffixesWithLineWrapping(self):
132 diff_cc = [
133 'UMA_HISTOGRAM_BOOL("LongHistogramNameNeedsLineWrapping.Dummy", true)']
134 diff_java = ['RecordHistogram.recordBooleanHistogram(' +
135 '"LongHistogramNameNeedsLineWrapping.Dummy", true)']
136 diff_xml = ['<histogram_suffixes',
137 ' name="LongHistogramNameNeedsLineWrapping"',
138 ' separator=".">',
139 ' <suffix name="Dummy"/>',
140 ' <affected-histogram',
141 ' name="LongHistogramNameNeedsLineWrapping"/>',
142 '</histogram>']
143 mock_input_api = MockInputApi()
144 mock_input_api.files = [
145 MockFile('some/path/foo.cc', diff_cc),
146 MockFile('some/path/foo.java', diff_java),
147 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
148 ]
149 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
150 MockOutputApi())
151 self.assertEqual(0, len(warnings))
152
Vaclav Brozek8a8e2e202018-03-23 22:01:06153 def testNameMatch(self):
154 # Check that the detected histogram name is "Dummy" and not, e.g.,
155 # "Dummy\", true); // The \"correct"
156 diff_cc = ['UMA_HISTOGRAM_BOOL("Dummy", true); // The "correct" histogram']
Vaclav Brozekbdac817c2018-03-24 06:30:47157 diff_java = [
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39158 'RecordHistogram.recordBooleanHistogram("Dummy", true);' +
159 ' // The "correct" histogram']
Vaclav Brozek8a8e2e202018-03-23 22:01:06160 diff_xml = ['<histogram name="Dummy"> </histogram>']
161 mock_input_api = MockInputApi()
162 mock_input_api.files = [
163 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47164 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek8a8e2e202018-03-23 22:01:06165 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
166 ]
167 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
168 MockOutputApi())
169 self.assertEqual(0, len(warnings))
170
171 def testSimilarMacroNames(self):
Vaclav Brozekbdac817c2018-03-24 06:30:47172 diff_cc = ['PUMA_HISTOGRAM_COOL("Mountain Lion", 42)']
173 diff_java = [
174 'FakeRecordHistogram.recordFakeHistogram("Mountain Lion", 42)']
Vaclav Brozek8a8e2e202018-03-23 22:01:06175 mock_input_api = MockInputApi()
176 mock_input_api.files = [
177 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47178 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek8a8e2e202018-03-23 22:01:06179 ]
180 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
181 MockOutputApi())
182 self.assertEqual(0, len(warnings))
183
Vaclav Brozek0e730cbd2018-03-24 06:18:17184 def testMultiLine(self):
185 diff_cc = ['UMA_HISTOGRAM_BOOLEAN(', ' "Multi.Line", true)']
186 diff_cc2 = ['UMA_HISTOGRAM_BOOLEAN(', ' "Multi.Line"', ' , true)']
Vaclav Brozekbdac817c2018-03-24 06:30:47187 diff_java = [
188 'RecordHistogram.recordBooleanHistogram(',
189 ' "Multi.Line", true);',
190 ]
Vaclav Brozek0e730cbd2018-03-24 06:18:17191 mock_input_api = MockInputApi()
192 mock_input_api.files = [
193 MockFile('some/path/foo.cc', diff_cc),
194 MockFile('some/path/foo2.cc', diff_cc2),
Vaclav Brozekbdac817c2018-03-24 06:30:47195 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek0e730cbd2018-03-24 06:18:17196 ]
197 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
198 MockOutputApi())
199 self.assertEqual(1, len(warnings))
200 self.assertEqual('warning', warnings[0].type)
201 self.assertTrue('foo.cc' in warnings[0].items[0])
202 self.assertTrue('foo2.cc' in warnings[0].items[1])
203
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39204
[email protected]b8079ae4a2012-12-05 19:56:49205class BadExtensionsTest(unittest.TestCase):
206 def testBadRejFile(self):
207 mock_input_api = MockInputApi()
208 mock_input_api.files = [
209 MockFile('some/path/foo.cc', ''),
210 MockFile('some/path/foo.cc.rej', ''),
211 MockFile('some/path2/bar.h.rej', ''),
212 ]
213
214 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
215 self.assertEqual(1, len(results))
216 self.assertEqual(2, len(results[0].items))
217 self.assertTrue('foo.cc.rej' in results[0].items[0])
218 self.assertTrue('bar.h.rej' in results[0].items[1])
219
220 def testBadOrigFile(self):
221 mock_input_api = MockInputApi()
222 mock_input_api.files = [
223 MockFile('other/path/qux.h.orig', ''),
224 MockFile('other/path/qux.h', ''),
225 MockFile('other/path/qux.cc', ''),
226 ]
227
228 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
229 self.assertEqual(1, len(results))
230 self.assertEqual(1, len(results[0].items))
231 self.assertTrue('qux.h.orig' in results[0].items[0])
232
233 def testGoodFiles(self):
234 mock_input_api = MockInputApi()
235 mock_input_api.files = [
236 MockFile('other/path/qux.h', ''),
237 MockFile('other/path/qux.cc', ''),
238 ]
239 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
240 self.assertEqual(0, len(results))
241
242
glidere61efad2015-02-18 17:39:43243class CheckSingletonInHeadersTest(unittest.TestCase):
244 def testSingletonInArbitraryHeader(self):
245 diff_singleton_h = ['base::subtle::AtomicWord '
olli.raula36aa8be2015-09-10 11:14:22246 'base::Singleton<Type, Traits, DifferentiatingType>::']
247 diff_foo_h = ['// base::Singleton<Foo> in comment.',
248 'friend class base::Singleton<Foo>']
oysteinec430ad42015-10-22 20:55:24249 diff_foo2_h = [' //Foo* bar = base::Singleton<Foo>::get();']
olli.raula36aa8be2015-09-10 11:14:22250 diff_bad_h = ['Foo* foo = base::Singleton<Foo>::get();']
glidere61efad2015-02-18 17:39:43251 mock_input_api = MockInputApi()
252 mock_input_api.files = [MockAffectedFile('base/memory/singleton.h',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39253 diff_singleton_h),
glidere61efad2015-02-18 17:39:43254 MockAffectedFile('foo.h', diff_foo_h),
oysteinec430ad42015-10-22 20:55:24255 MockAffectedFile('foo2.h', diff_foo2_h),
glidere61efad2015-02-18 17:39:43256 MockAffectedFile('bad.h', diff_bad_h)]
257 warnings = PRESUBMIT._CheckSingletonInHeaders(mock_input_api,
258 MockOutputApi())
259 self.assertEqual(1, len(warnings))
Sylvain Defresnea8b73d252018-02-28 15:45:54260 self.assertEqual(1, len(warnings[0].items))
glidere61efad2015-02-18 17:39:43261 self.assertEqual('error', warnings[0].type)
olli.raula36aa8be2015-09-10 11:14:22262 self.assertTrue('Found base::Singleton<T>' in warnings[0].message)
glidere61efad2015-02-18 17:39:43263
264 def testSingletonInCC(self):
olli.raula36aa8be2015-09-10 11:14:22265 diff_cc = ['Foo* foo = base::Singleton<Foo>::get();']
glidere61efad2015-02-18 17:39:43266 mock_input_api = MockInputApi()
267 mock_input_api.files = [MockAffectedFile('some/path/foo.cc', diff_cc)]
268 warnings = PRESUBMIT._CheckSingletonInHeaders(mock_input_api,
269 MockOutputApi())
270 self.assertEqual(0, len(warnings))
271
272
[email protected]b00342e7f2013-03-26 16:21:54273class InvalidOSMacroNamesTest(unittest.TestCase):
274 def testInvalidOSMacroNames(self):
275 lines = ['#if defined(OS_WINDOWS)',
276 ' #elif defined(OS_WINDOW)',
277 ' # if defined(OS_MACOSX) || defined(OS_CHROME)',
278 '# else // defined(OS_MAC)',
279 '#endif // defined(OS_MACOS)']
280 errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
281 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
282 self.assertEqual(len(lines), len(errors))
283 self.assertTrue(':1 OS_WINDOWS' in errors[0])
284 self.assertTrue('(did you mean OS_WIN?)' in errors[0])
285
286 def testValidOSMacroNames(self):
287 lines = ['#if defined(%s)' % m for m in PRESUBMIT._VALID_OS_MACROS]
288 errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
289 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
290 self.assertEqual(0, len(errors))
291
292
lliabraa35bab3932014-10-01 12:16:44293class InvalidIfDefinedMacroNamesTest(unittest.TestCase):
294 def testInvalidIfDefinedMacroNames(self):
295 lines = ['#if defined(TARGET_IPHONE_SIMULATOR)',
296 '#if !defined(TARGET_IPHONE_SIMULATOR)',
297 '#elif defined(TARGET_IPHONE_SIMULATOR)',
298 '#ifdef TARGET_IPHONE_SIMULATOR',
299 ' # ifdef TARGET_IPHONE_SIMULATOR',
300 '# if defined(VALID) || defined(TARGET_IPHONE_SIMULATOR)',
301 '# else // defined(TARGET_IPHONE_SIMULATOR)',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39302 '#endif // defined(TARGET_IPHONE_SIMULATOR)']
lliabraa35bab3932014-10-01 12:16:44303 errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
304 MockInputApi(), MockFile('some/path/source.mm', lines))
305 self.assertEqual(len(lines), len(errors))
306
307 def testValidIfDefinedMacroNames(self):
308 lines = ['#if defined(FOO)',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39309 '#ifdef BAR']
lliabraa35bab3932014-10-01 12:16:44310 errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
311 MockInputApi(), MockFile('some/path/source.cc', lines))
312 self.assertEqual(0, len(errors))
313
314
Samuel Huang0db2ea22019-12-09 16:42:47315class CheckAddedDepsHaveTestApprovalsTest(unittest.TestCase):
Daniel Cheng4dcdb6b2017-04-13 08:30:17316
317 def calculate(self, old_include_rules, old_specific_include_rules,
318 new_include_rules, new_specific_include_rules):
319 return PRESUBMIT._CalculateAddedDeps(
320 os.path, 'include_rules = %r\nspecific_include_rules = %r' % (
321 old_include_rules, old_specific_include_rules),
322 'include_rules = %r\nspecific_include_rules = %r' % (
323 new_include_rules, new_specific_include_rules))
324
325 def testCalculateAddedDeps(self):
326 old_include_rules = [
327 '+base',
328 '-chrome',
329 '+content',
330 '-grit',
331 '-grit/",',
332 '+jni/fooblat.h',
333 '!sandbox',
[email protected]f32e2d1e2013-07-26 21:39:08334 ]
Daniel Cheng4dcdb6b2017-04-13 08:30:17335 old_specific_include_rules = {
336 'compositor\.*': {
337 '+cc',
338 },
339 }
340
341 new_include_rules = [
342 '-ash',
343 '+base',
344 '+chrome',
345 '+components',
346 '+content',
347 '+grit',
348 '+grit/generated_resources.h",',
349 '+grit/",',
350 '+jni/fooblat.h',
351 '+policy',
manzagop85e629e2017-05-09 22:11:48352 '+' + os.path.join('third_party', 'WebKit'),
Daniel Cheng4dcdb6b2017-04-13 08:30:17353 ]
354 new_specific_include_rules = {
355 'compositor\.*': {
356 '+cc',
357 },
358 'widget\.*': {
359 '+gpu',
360 },
361 }
362
[email protected]f32e2d1e2013-07-26 21:39:08363 expected = set([
manzagop85e629e2017-05-09 22:11:48364 os.path.join('chrome', 'DEPS'),
365 os.path.join('gpu', 'DEPS'),
366 os.path.join('components', 'DEPS'),
367 os.path.join('policy', 'DEPS'),
368 os.path.join('third_party', 'WebKit', 'DEPS'),
[email protected]f32e2d1e2013-07-26 21:39:08369 ])
Daniel Cheng4dcdb6b2017-04-13 08:30:17370 self.assertEqual(
371 expected,
372 self.calculate(old_include_rules, old_specific_include_rules,
373 new_include_rules, new_specific_include_rules))
374
375 def testCalculateAddedDepsIgnoresPermutations(self):
376 old_include_rules = [
377 '+base',
378 '+chrome',
379 ]
380 new_include_rules = [
381 '+chrome',
382 '+base',
383 ]
384 self.assertEqual(set(),
385 self.calculate(old_include_rules, {}, new_include_rules,
386 {}))
[email protected]f32e2d1e2013-07-26 21:39:08387
388
[email protected]99171a92014-06-03 08:44:47389class JSONParsingTest(unittest.TestCase):
390 def testSuccess(self):
391 input_api = MockInputApi()
392 filename = 'valid_json.json'
393 contents = ['// This is a comment.',
394 '{',
395 ' "key1": ["value1", "value2"],',
396 ' "key2": 3 // This is an inline comment.',
397 '}'
398 ]
399 input_api.files = [MockFile(filename, contents)]
400 self.assertEqual(None,
401 PRESUBMIT._GetJSONParseError(input_api, filename))
402
403 def testFailure(self):
404 input_api = MockInputApi()
405 test_data = [
406 ('invalid_json_1.json',
407 ['{ x }'],
[email protected]a3343272014-06-17 11:41:53408 'Expecting property name:'),
[email protected]99171a92014-06-03 08:44:47409 ('invalid_json_2.json',
410 ['// Hello world!',
411 '{ "hello": "world }'],
[email protected]a3343272014-06-17 11:41:53412 'Unterminated string starting at:'),
[email protected]99171a92014-06-03 08:44:47413 ('invalid_json_3.json',
414 ['{ "a": "b", "c": "d", }'],
[email protected]a3343272014-06-17 11:41:53415 'Expecting property name:'),
[email protected]99171a92014-06-03 08:44:47416 ('invalid_json_4.json',
417 ['{ "a": "b" "c": "d" }'],
[email protected]a3343272014-06-17 11:41:53418 'Expecting , delimiter:'),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39419 ]
[email protected]99171a92014-06-03 08:44:47420
421 input_api.files = [MockFile(filename, contents)
422 for (filename, contents, _) in test_data]
423
424 for (filename, _, expected_error) in test_data:
425 actual_error = PRESUBMIT._GetJSONParseError(input_api, filename)
[email protected]a3343272014-06-17 11:41:53426 self.assertTrue(expected_error in str(actual_error),
427 "'%s' not found in '%s'" % (expected_error, actual_error))
[email protected]99171a92014-06-03 08:44:47428
429 def testNoEatComments(self):
430 input_api = MockInputApi()
431 file_with_comments = 'file_with_comments.json'
432 contents_with_comments = ['// This is a comment.',
433 '{',
434 ' "key1": ["value1", "value2"],',
435 ' "key2": 3 // This is an inline comment.',
436 '}'
437 ]
438 file_without_comments = 'file_without_comments.json'
439 contents_without_comments = ['{',
440 ' "key1": ["value1", "value2"],',
441 ' "key2": 3',
442 '}'
443 ]
444 input_api.files = [MockFile(file_with_comments, contents_with_comments),
445 MockFile(file_without_comments,
446 contents_without_comments)]
447
448 self.assertEqual('No JSON object could be decoded',
449 str(PRESUBMIT._GetJSONParseError(input_api,
450 file_with_comments,
451 eat_comments=False)))
452 self.assertEqual(None,
453 PRESUBMIT._GetJSONParseError(input_api,
454 file_without_comments,
455 eat_comments=False))
456
457
458class IDLParsingTest(unittest.TestCase):
459 def testSuccess(self):
460 input_api = MockInputApi()
461 filename = 'valid_idl_basics.idl'
462 contents = ['// Tests a valid IDL file.',
463 'namespace idl_basics {',
464 ' enum EnumType {',
465 ' name1,',
466 ' name2',
467 ' };',
468 '',
469 ' dictionary MyType1 {',
470 ' DOMString a;',
471 ' };',
472 '',
473 ' callback Callback1 = void();',
474 ' callback Callback2 = void(long x);',
475 ' callback Callback3 = void(MyType1 arg);',
476 ' callback Callback4 = void(EnumType type);',
477 '',
478 ' interface Functions {',
479 ' static void function1();',
480 ' static void function2(long x);',
481 ' static void function3(MyType1 arg);',
482 ' static void function4(Callback1 cb);',
483 ' static void function5(Callback2 cb);',
484 ' static void function6(Callback3 cb);',
485 ' static void function7(Callback4 cb);',
486 ' };',
487 '',
488 ' interface Events {',
489 ' static void onFoo1();',
490 ' static void onFoo2(long x);',
491 ' static void onFoo2(MyType1 arg);',
492 ' static void onFoo3(EnumType type);',
493 ' };',
494 '};'
495 ]
496 input_api.files = [MockFile(filename, contents)]
497 self.assertEqual(None,
498 PRESUBMIT._GetIDLParseError(input_api, filename))
499
500 def testFailure(self):
501 input_api = MockInputApi()
502 test_data = [
503 ('invalid_idl_1.idl',
504 ['//',
505 'namespace test {',
506 ' dictionary {',
507 ' DOMString s;',
508 ' };',
509 '};'],
510 'Unexpected "{" after keyword "dictionary".\n'),
511 # TODO(yoz): Disabled because it causes the IDL parser to hang.
512 # See crbug.com/363830.
513 # ('invalid_idl_2.idl',
514 # (['namespace test {',
515 # ' dictionary MissingSemicolon {',
516 # ' DOMString a',
517 # ' DOMString b;',
518 # ' };',
519 # '};'],
520 # 'Unexpected symbol DOMString after symbol a.'),
521 ('invalid_idl_3.idl',
522 ['//',
523 'namespace test {',
524 ' enum MissingComma {',
525 ' name1',
526 ' name2',
527 ' };',
528 '};'],
529 'Unexpected symbol name2 after symbol name1.'),
530 ('invalid_idl_4.idl',
531 ['//',
532 'namespace test {',
533 ' enum TrailingComma {',
534 ' name1,',
535 ' name2,',
536 ' };',
537 '};'],
538 'Trailing comma in block.'),
539 ('invalid_idl_5.idl',
540 ['//',
541 'namespace test {',
542 ' callback Callback1 = void(;',
543 '};'],
544 'Unexpected ";" after "(".'),
545 ('invalid_idl_6.idl',
546 ['//',
547 'namespace test {',
548 ' callback Callback1 = void(long );',
549 '};'],
550 'Unexpected ")" after symbol long.'),
551 ('invalid_idl_7.idl',
552 ['//',
553 'namespace test {',
554 ' interace Events {',
555 ' static void onFoo1();',
556 ' };',
557 '};'],
558 'Unexpected symbol Events after symbol interace.'),
559 ('invalid_idl_8.idl',
560 ['//',
561 'namespace test {',
562 ' interface NotEvent {',
563 ' static void onFoo1();',
564 ' };',
565 '};'],
566 'Did not process Interface Interface(NotEvent)'),
567 ('invalid_idl_9.idl',
568 ['//',
569 'namespace test {',
570 ' interface {',
571 ' static void function1();',
572 ' };',
573 '};'],
574 'Interface missing name.'),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39575 ]
[email protected]99171a92014-06-03 08:44:47576
577 input_api.files = [MockFile(filename, contents)
578 for (filename, contents, _) in test_data]
579
580 for (filename, _, expected_error) in test_data:
581 actual_error = PRESUBMIT._GetIDLParseError(input_api, filename)
582 self.assertTrue(expected_error in str(actual_error),
583 "'%s' not found in '%s'" % (expected_error, actual_error))
584
585
[email protected]0bb112362014-07-26 04:38:32586class TryServerMasterTest(unittest.TestCase):
587 def testTryServerMasters(self):
588 bots = {
tandriie5587792016-07-14 00:34:50589 'master.tryserver.chromium.android': [
jbudorick3ae7a772016-05-20 02:36:04590 'android_archive_rel_ng',
591 'android_arm64_dbg_recipe',
592 'android_blink_rel',
jbudorick3ae7a772016-05-20 02:36:04593 'android_clang_dbg_recipe',
594 'android_compile_dbg',
jbudorick3ae7a772016-05-20 02:36:04595 'android_compile_x64_dbg',
596 'android_compile_x86_dbg',
597 'android_coverage',
598 'android_cronet_tester'
599 'android_swarming_rel',
600 'cast_shell_android',
601 'linux_android_dbg_ng',
602 'linux_android_rel_ng',
603 ],
tandriie5587792016-07-14 00:34:50604 'master.tryserver.chromium.mac': [
[email protected]0bb112362014-07-26 04:38:32605 'ios_dbg_simulator',
606 'ios_rel_device',
607 'ios_rel_device_ninja',
608 'mac_asan',
609 'mac_asan_64',
610 'mac_chromium_compile_dbg',
611 'mac_chromium_compile_rel',
612 'mac_chromium_dbg',
613 'mac_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32614 'mac_nacl_sdk',
615 'mac_nacl_sdk_build',
616 'mac_rel_naclmore',
[email protected]0bb112362014-07-26 04:38:32617 'mac_x64_rel',
618 'mac_xcodebuild',
619 ],
tandriie5587792016-07-14 00:34:50620 'master.tryserver.chromium.linux': [
[email protected]0bb112362014-07-26 04:38:32621 'chromium_presubmit',
622 'linux_arm_cross_compile',
623 'linux_arm_tester',
[email protected]0bb112362014-07-26 04:38:32624 'linux_chromeos_asan',
625 'linux_chromeos_browser_asan',
626 'linux_chromeos_valgrind',
[email protected]0bb112362014-07-26 04:38:32627 'linux_chromium_chromeos_dbg',
628 'linux_chromium_chromeos_rel',
[email protected]0bb112362014-07-26 04:38:32629 'linux_chromium_compile_dbg',
630 'linux_chromium_compile_rel',
631 'linux_chromium_dbg',
632 'linux_chromium_gn_dbg',
633 'linux_chromium_gn_rel',
634 'linux_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32635 'linux_chromium_trusty32_dbg',
636 'linux_chromium_trusty32_rel',
637 'linux_chromium_trusty_dbg',
638 'linux_chromium_trusty_rel',
639 'linux_clang_tsan',
640 'linux_ecs_ozone',
641 'linux_layout',
642 'linux_layout_asan',
643 'linux_layout_rel',
644 'linux_layout_rel_32',
645 'linux_nacl_sdk',
646 'linux_nacl_sdk_bionic',
647 'linux_nacl_sdk_bionic_build',
648 'linux_nacl_sdk_build',
649 'linux_redux',
650 'linux_rel_naclmore',
651 'linux_rel_precise32',
652 'linux_valgrind',
653 'tools_build_presubmit',
654 ],
tandriie5587792016-07-14 00:34:50655 'master.tryserver.chromium.win': [
[email protected]0bb112362014-07-26 04:38:32656 'win8_aura',
657 'win8_chromium_dbg',
658 'win8_chromium_rel',
659 'win_chromium_compile_dbg',
660 'win_chromium_compile_rel',
661 'win_chromium_dbg',
662 'win_chromium_rel',
663 'win_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32664 'win_chromium_x64_dbg',
665 'win_chromium_x64_rel',
[email protected]0bb112362014-07-26 04:38:32666 'win_nacl_sdk',
667 'win_nacl_sdk_build',
668 'win_rel_naclmore',
669 ],
670 }
671 for master, bots in bots.iteritems():
672 for bot in bots:
673 self.assertEqual(master, PRESUBMIT.GetTryServerMasterForBot(bot),
674 'bot=%s: expected %s, computed %s' % (
675 bot, master, PRESUBMIT.GetTryServerMasterForBot(bot)))
676
677
davileene0426252015-03-02 21:10:41678class UserMetricsActionTest(unittest.TestCase):
679 def testUserMetricsActionInActions(self):
680 input_api = MockInputApi()
681 file_with_user_action = 'file_with_user_action.cc'
682 contents_with_user_action = [
683 'base::UserMetricsAction("AboutChrome")'
684 ]
685
686 input_api.files = [MockFile(file_with_user_action,
687 contents_with_user_action)]
688
689 self.assertEqual(
690 [], PRESUBMIT._CheckUserActionUpdate(input_api, MockOutputApi()))
691
davileene0426252015-03-02 21:10:41692 def testUserMetricsActionNotAddedToActions(self):
693 input_api = MockInputApi()
694 file_with_user_action = 'file_with_user_action.cc'
695 contents_with_user_action = [
696 'base::UserMetricsAction("NotInActionsXml")'
697 ]
698
699 input_api.files = [MockFile(file_with_user_action,
700 contents_with_user_action)]
701
702 output = PRESUBMIT._CheckUserActionUpdate(input_api, MockOutputApi())
703 self.assertEqual(
704 ('File %s line %d: %s is missing in '
705 'tools/metrics/actions/actions.xml. Please run '
706 'tools/metrics/actions/extract_actions.py to update.'
707 % (file_with_user_action, 1, 'NotInActionsXml')),
708 output[0].message)
709
710
agrievef32bcc72016-04-04 14:57:40711class PydepsNeedsUpdatingTest(unittest.TestCase):
712
713 class MockSubprocess(object):
714 CalledProcessError = subprocess.CalledProcessError
715
716 def setUp(self):
717 mock_all_pydeps = ['A.pydeps', 'B.pydeps']
718 self.old_ALL_PYDEPS_FILES = PRESUBMIT._ALL_PYDEPS_FILES
719 PRESUBMIT._ALL_PYDEPS_FILES = mock_all_pydeps
720 self.mock_input_api = MockInputApi()
721 self.mock_output_api = MockOutputApi()
722 self.mock_input_api.subprocess = PydepsNeedsUpdatingTest.MockSubprocess()
723 self.checker = PRESUBMIT.PydepsChecker(self.mock_input_api, mock_all_pydeps)
724 self.checker._file_cache = {
725 'A.pydeps': '# Generated by:\n# CMD A\nA.py\nC.py\n',
726 'B.pydeps': '# Generated by:\n# CMD B\nB.py\nC.py\n',
727 }
728
729 def tearDown(self):
730 PRESUBMIT._ALL_PYDEPS_FILES = self.old_ALL_PYDEPS_FILES
731
732 def _RunCheck(self):
733 return PRESUBMIT._CheckPydepsNeedsUpdating(self.mock_input_api,
734 self.mock_output_api,
735 checker_for_tests=self.checker)
736
737 def testAddedPydep(self):
pastarmovj89f7ee12016-09-20 14:58:13738 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
739 if self.mock_input_api.platform != 'linux2':
740 return []
741
agrievef32bcc72016-04-04 14:57:40742 self.mock_input_api.files = [
743 MockAffectedFile('new.pydeps', [], action='A'),
744 ]
745
Zhiling Huang45cabf32018-03-10 00:50:03746 self.mock_input_api.CreateMockFileInPath(
747 [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
748 include_deletes=True)])
agrievef32bcc72016-04-04 14:57:40749 results = self._RunCheck()
750 self.assertEqual(1, len(results))
751 self.assertTrue('PYDEPS_FILES' in str(results[0]))
752
Zhiling Huang45cabf32018-03-10 00:50:03753 def testPydepNotInSrc(self):
754 self.mock_input_api.files = [
755 MockAffectedFile('new.pydeps', [], action='A'),
756 ]
757 self.mock_input_api.CreateMockFileInPath([])
758 results = self._RunCheck()
759 self.assertEqual(0, len(results))
760
agrievef32bcc72016-04-04 14:57:40761 def testRemovedPydep(self):
pastarmovj89f7ee12016-09-20 14:58:13762 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
763 if self.mock_input_api.platform != 'linux2':
764 return []
765
agrievef32bcc72016-04-04 14:57:40766 self.mock_input_api.files = [
767 MockAffectedFile(PRESUBMIT._ALL_PYDEPS_FILES[0], [], action='D'),
768 ]
Zhiling Huang45cabf32018-03-10 00:50:03769 self.mock_input_api.CreateMockFileInPath(
770 [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
771 include_deletes=True)])
agrievef32bcc72016-04-04 14:57:40772 results = self._RunCheck()
773 self.assertEqual(1, len(results))
774 self.assertTrue('PYDEPS_FILES' in str(results[0]))
775
776 def testRandomPyIgnored(self):
pastarmovj89f7ee12016-09-20 14:58:13777 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
778 if self.mock_input_api.platform != 'linux2':
779 return []
780
agrievef32bcc72016-04-04 14:57:40781 self.mock_input_api.files = [
782 MockAffectedFile('random.py', []),
783 ]
784
785 results = self._RunCheck()
786 self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
787
788 def testRelevantPyNoChange(self):
pastarmovj89f7ee12016-09-20 14:58:13789 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
790 if self.mock_input_api.platform != 'linux2':
791 return []
792
agrievef32bcc72016-04-04 14:57:40793 self.mock_input_api.files = [
794 MockAffectedFile('A.py', []),
795 ]
796
John Budorickab2fa102017-10-06 16:59:49797 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40798 self.assertEqual('CMD A --output ""', cmd)
799 return self.checker._file_cache['A.pydeps']
800
801 self.mock_input_api.subprocess.check_output = mock_check_output
802
803 results = self._RunCheck()
804 self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
805
806 def testRelevantPyOneChange(self):
pastarmovj89f7ee12016-09-20 14:58:13807 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
808 if self.mock_input_api.platform != 'linux2':
809 return []
810
agrievef32bcc72016-04-04 14:57:40811 self.mock_input_api.files = [
812 MockAffectedFile('A.py', []),
813 ]
814
John Budorickab2fa102017-10-06 16:59:49815 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40816 self.assertEqual('CMD A --output ""', cmd)
817 return 'changed data'
818
819 self.mock_input_api.subprocess.check_output = mock_check_output
820
821 results = self._RunCheck()
822 self.assertEqual(1, len(results))
823 self.assertTrue('File is stale' in str(results[0]))
824
825 def testRelevantPyTwoChanges(self):
pastarmovj89f7ee12016-09-20 14:58:13826 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
827 if self.mock_input_api.platform != 'linux2':
828 return []
829
agrievef32bcc72016-04-04 14:57:40830 self.mock_input_api.files = [
831 MockAffectedFile('C.py', []),
832 ]
833
John Budorickab2fa102017-10-06 16:59:49834 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40835 return 'changed data'
836
837 self.mock_input_api.subprocess.check_output = mock_check_output
838
839 results = self._RunCheck()
840 self.assertEqual(2, len(results))
841 self.assertTrue('File is stale' in str(results[0]))
842 self.assertTrue('File is stale' in str(results[1]))
843
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39844
Daniel Bratell8ba52722018-03-02 16:06:14845class IncludeGuardTest(unittest.TestCase):
846 def testIncludeGuardChecks(self):
847 mock_input_api = MockInputApi()
848 mock_output_api = MockOutputApi()
849 mock_input_api.files = [
850 MockAffectedFile('content/browser/thing/foo.h', [
851 '// Comment',
852 '#ifndef CONTENT_BROWSER_THING_FOO_H_',
853 '#define CONTENT_BROWSER_THING_FOO_H_',
854 'struct McBoatFace;',
855 '#endif // CONTENT_BROWSER_THING_FOO_H_',
856 ]),
857 MockAffectedFile('content/browser/thing/bar.h', [
858 '#ifndef CONTENT_BROWSER_THING_BAR_H_',
859 '#define CONTENT_BROWSER_THING_BAR_H_',
860 'namespace content {',
861 '#endif // CONTENT_BROWSER_THING_BAR_H_',
862 '} // namespace content',
863 ]),
864 MockAffectedFile('content/browser/test1.h', [
865 'namespace content {',
866 '} // namespace content',
867 ]),
868 MockAffectedFile('content\\browser\\win.h', [
869 '#ifndef CONTENT_BROWSER_WIN_H_',
870 '#define CONTENT_BROWSER_WIN_H_',
871 'struct McBoatFace;',
872 '#endif // CONTENT_BROWSER_WIN_H_',
873 ]),
874 MockAffectedFile('content/browser/test2.h', [
875 '// Comment',
876 '#ifndef CONTENT_BROWSER_TEST2_H_',
877 'struct McBoatFace;',
878 '#endif // CONTENT_BROWSER_TEST2_H_',
879 ]),
880 MockAffectedFile('content/browser/internal.h', [
881 '// Comment',
882 '#ifndef CONTENT_BROWSER_INTERNAL_H_',
883 '#define CONTENT_BROWSER_INTERNAL_H_',
884 '// Comment',
885 '#ifndef INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
886 '#define INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
887 'namespace internal {',
888 '} // namespace internal',
889 '#endif // INTERNAL_CONTENT_BROWSER_THING_BAR_H_',
890 'namespace content {',
891 '} // namespace content',
892 '#endif // CONTENT_BROWSER_THING_BAR_H_',
893 ]),
894 MockAffectedFile('content/browser/thing/foo.cc', [
895 '// This is a non-header.',
896 ]),
897 MockAffectedFile('content/browser/disabled.h', [
898 '// no-include-guard-because-multiply-included',
899 'struct McBoatFace;',
900 ]),
901 # New files don't allow misspelled include guards.
902 MockAffectedFile('content/browser/spleling.h', [
903 '#ifndef CONTENT_BROWSER_SPLLEING_H_',
904 '#define CONTENT_BROWSER_SPLLEING_H_',
905 'struct McBoatFace;',
906 '#endif // CONTENT_BROWSER_SPLLEING_H_',
907 ]),
Olivier Robinbba137492018-07-30 11:31:34908 # New files don't allow + in include guards.
909 MockAffectedFile('content/browser/foo+bar.h', [
910 '#ifndef CONTENT_BROWSER_FOO+BAR_H_',
911 '#define CONTENT_BROWSER_FOO+BAR_H_',
912 'struct McBoatFace;',
913 '#endif // CONTENT_BROWSER_FOO+BAR_H_',
914 ]),
Daniel Bratell8ba52722018-03-02 16:06:14915 # Old files allow misspelled include guards (for now).
916 MockAffectedFile('chrome/old.h', [
917 '// New contents',
918 '#ifndef CHROME_ODL_H_',
919 '#define CHROME_ODL_H_',
920 '#endif // CHROME_ODL_H_',
921 ], [
922 '// Old contents',
923 '#ifndef CHROME_ODL_H_',
924 '#define CHROME_ODL_H_',
925 '#endif // CHROME_ODL_H_',
926 ]),
927 # Using a Blink style include guard outside Blink is wrong.
928 MockAffectedFile('content/NotInBlink.h', [
929 '#ifndef NotInBlink_h',
930 '#define NotInBlink_h',
931 'struct McBoatFace;',
932 '#endif // NotInBlink_h',
933 ]),
Daniel Bratell39b5b062018-05-16 18:09:57934 # Using a Blink style include guard in Blink is no longer ok.
935 MockAffectedFile('third_party/blink/InBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14936 '#ifndef InBlink_h',
937 '#define InBlink_h',
938 'struct McBoatFace;',
939 '#endif // InBlink_h',
940 ]),
941 # Using a bad include guard in Blink is not ok.
Daniel Bratell39b5b062018-05-16 18:09:57942 MockAffectedFile('third_party/blink/AlsoInBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14943 '#ifndef WrongInBlink_h',
944 '#define WrongInBlink_h',
945 'struct McBoatFace;',
946 '#endif // WrongInBlink_h',
947 ]),
Daniel Bratell39b5b062018-05-16 18:09:57948 # Using a bad include guard in Blink is not accepted even if
949 # it's an old file.
950 MockAffectedFile('third_party/blink/StillInBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14951 '// New contents',
952 '#ifndef AcceptedInBlink_h',
953 '#define AcceptedInBlink_h',
954 'struct McBoatFace;',
955 '#endif // AcceptedInBlink_h',
956 ], [
957 '// Old contents',
958 '#ifndef AcceptedInBlink_h',
959 '#define AcceptedInBlink_h',
960 'struct McBoatFace;',
961 '#endif // AcceptedInBlink_h',
962 ]),
Daniel Bratell39b5b062018-05-16 18:09:57963 # Using a non-Chromium include guard in third_party
964 # (outside blink) is accepted.
965 MockAffectedFile('third_party/foo/some_file.h', [
966 '#ifndef REQUIRED_RPCNDR_H_',
967 '#define REQUIRED_RPCNDR_H_',
968 'struct SomeFileFoo;',
969 '#endif // REQUIRED_RPCNDR_H_',
970 ]),
Kinuko Yasuda0cdb3da2019-07-31 21:50:32971 # Not having proper include guard in *_message_generator.h
972 # for old IPC messages is allowed.
973 MockAffectedFile('content/common/content_message_generator.h', [
974 '#undef CONTENT_COMMON_FOO_MESSAGES_H_',
975 '#include "content/common/foo_messages.h"',
976 '#ifndef CONTENT_COMMON_FOO_MESSAGES_H_',
977 '#error "Failed to include content/common/foo_messages.h"',
978 '#endif',
979 ]),
Daniel Bratell8ba52722018-03-02 16:06:14980 ]
981 msgs = PRESUBMIT._CheckForIncludeGuards(
982 mock_input_api, mock_output_api)
Olivier Robinbba137492018-07-30 11:31:34983 expected_fail_count = 8
Daniel Bratell8ba52722018-03-02 16:06:14984 self.assertEqual(expected_fail_count, len(msgs),
985 'Expected %d items, found %d: %s'
986 % (expected_fail_count, len(msgs), msgs))
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39987 self.assertEqual(msgs[0].items, ['content/browser/thing/bar.h'])
Daniel Bratell8ba52722018-03-02 16:06:14988 self.assertEqual(msgs[0].message,
989 'Include guard CONTENT_BROWSER_THING_BAR_H_ '
990 'not covering the whole file')
991
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39992 self.assertEqual(msgs[1].items, ['content/browser/test1.h'])
Daniel Bratell8ba52722018-03-02 16:06:14993 self.assertEqual(msgs[1].message,
994 'Missing include guard CONTENT_BROWSER_TEST1_H_')
995
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39996 self.assertEqual(msgs[2].items, ['content/browser/test2.h:3'])
Daniel Bratell8ba52722018-03-02 16:06:14997 self.assertEqual(msgs[2].message,
998 'Missing "#define CONTENT_BROWSER_TEST2_H_" for '
999 'include guard')
1000
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391001 self.assertEqual(msgs[3].items, ['content/browser/spleling.h:1'])
Daniel Bratell8ba52722018-03-02 16:06:141002 self.assertEqual(msgs[3].message,
1003 'Header using the wrong include guard name '
1004 'CONTENT_BROWSER_SPLLEING_H_')
1005
Olivier Robinbba137492018-07-30 11:31:341006 self.assertEqual(msgs[4].items, ['content/browser/foo+bar.h'])
Daniel Bratell8ba52722018-03-02 16:06:141007 self.assertEqual(msgs[4].message,
Olivier Robinbba137492018-07-30 11:31:341008 'Missing include guard CONTENT_BROWSER_FOO_BAR_H_')
1009
1010 self.assertEqual(msgs[5].items, ['content/NotInBlink.h:1'])
1011 self.assertEqual(msgs[5].message,
Daniel Bratell8ba52722018-03-02 16:06:141012 'Header using the wrong include guard name '
1013 'NotInBlink_h')
1014
Olivier Robinbba137492018-07-30 11:31:341015 self.assertEqual(msgs[6].items, ['third_party/blink/InBlink.h:1'])
1016 self.assertEqual(msgs[6].message,
Daniel Bratell8ba52722018-03-02 16:06:141017 'Header using the wrong include guard name '
Daniel Bratell39b5b062018-05-16 18:09:571018 'InBlink_h')
1019
Olivier Robinbba137492018-07-30 11:31:341020 self.assertEqual(msgs[7].items, ['third_party/blink/AlsoInBlink.h:1'])
1021 self.assertEqual(msgs[7].message,
Daniel Bratell39b5b062018-05-16 18:09:571022 'Header using the wrong include guard name '
Daniel Bratell8ba52722018-03-02 16:06:141023 'WrongInBlink_h')
1024
Chris Hall59f8d0c72020-05-01 07:31:191025class AccessibilityRelnotesFieldTest(unittest.TestCase):
1026 def testRelnotesPresent(self):
1027 mock_input_api = MockInputApi()
1028 mock_output_api = MockOutputApi()
1029
1030 mock_input_api.files = [MockAffectedFile('ui/accessibility/foo.bar', [''])]
1031 mock_input_api.change.footers['AX-Relnotes'] = [
1032 'Important user facing change']
1033
1034 msgs = PRESUBMIT._CheckAccessibilityRelnotesField(
1035 mock_input_api, mock_output_api)
1036 self.assertEqual(0, len(msgs),
1037 'Expected %d messages, found %d: %s'
1038 % (0, len(msgs), msgs))
1039
1040 def testRelnotesMissingFromAccessibilityChange(self):
1041 mock_input_api = MockInputApi()
1042 mock_output_api = MockOutputApi()
1043
1044 mock_input_api.files = [
1045 MockAffectedFile('some/file', ['']),
1046 MockAffectedFile('ui/accessibility/foo.bar', ['']),
1047 MockAffectedFile('some/other/file', [''])
1048 ]
1049
1050 msgs = PRESUBMIT._CheckAccessibilityRelnotesField(
1051 mock_input_api, mock_output_api)
1052 self.assertEqual(1, len(msgs),
1053 'Expected %d messages, found %d: %s'
1054 % (1, len(msgs), msgs))
1055 self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
1056 'Missing AX-Relnotes field message not found in errors')
1057
1058 # The relnotes footer is not required for changes which do not touch any
1059 # accessibility directories.
1060 def testIgnoresNonAccesssibilityCode(self):
1061 mock_input_api = MockInputApi()
1062 mock_output_api = MockOutputApi()
1063
1064 mock_input_api.files = [
1065 MockAffectedFile('some/file', ['']),
1066 MockAffectedFile('some/other/file', [''])
1067 ]
1068
1069 msgs = PRESUBMIT._CheckAccessibilityRelnotesField(
1070 mock_input_api, mock_output_api)
1071 self.assertEqual(0, len(msgs),
1072 'Expected %d messages, found %d: %s'
1073 % (0, len(msgs), msgs))
1074
1075 # Test that our presubmit correctly raises an error for a set of known paths.
1076 def testExpectedPaths(self):
1077 filesToTest = [
1078 "chrome/browser/accessibility/foo.py",
1079 "chrome/browser/chromeos/arc/accessibility/foo.cc",
1080 "chrome/browser/ui/views/accessibility/foo.h",
1081 "chrome/browser/extensions/api/automation/foo.h",
1082 "chrome/browser/extensions/api/automation_internal/foo.cc",
1083 "chrome/renderer/extensions/accessibility_foo.h",
1084 "chrome/tests/data/accessibility/foo.html",
1085 "content/browser/accessibility/foo.cc",
1086 "content/renderer/accessibility/foo.h",
1087 "content/tests/data/accessibility/foo.cc",
1088 "extensions/renderer/api/automation/foo.h",
1089 "ui/accessibility/foo/bar/baz.cc",
1090 "ui/views/accessibility/foo/bar/baz.h",
1091 ]
1092
1093 for testFile in filesToTest:
1094 mock_input_api = MockInputApi()
1095 mock_output_api = MockOutputApi()
1096
1097 mock_input_api.files = [
1098 MockAffectedFile(testFile, [''])
1099 ]
1100
1101 msgs = PRESUBMIT._CheckAccessibilityRelnotesField(
1102 mock_input_api, mock_output_api)
1103 self.assertEqual(1, len(msgs),
1104 'Expected %d messages, found %d: %s, for file %s'
1105 % (1, len(msgs), msgs, testFile))
1106 self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
1107 ('Missing AX-Relnotes field message not found in errors '
1108 ' for file %s' % (testFile)))
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391109
yolandyan45001472016-12-21 21:12:421110class AndroidDeprecatedTestAnnotationTest(unittest.TestCase):
1111 def testCheckAndroidTestAnnotationUsage(self):
1112 mock_input_api = MockInputApi()
1113 mock_output_api = MockOutputApi()
1114
1115 mock_input_api.files = [
1116 MockAffectedFile('LalaLand.java', [
1117 'random stuff'
1118 ]),
1119 MockAffectedFile('CorrectUsage.java', [
1120 'import android.support.test.filters.LargeTest;',
1121 'import android.support.test.filters.MediumTest;',
1122 'import android.support.test.filters.SmallTest;',
1123 ]),
1124 MockAffectedFile('UsedDeprecatedLargeTestAnnotation.java', [
1125 'import android.test.suitebuilder.annotation.LargeTest;',
1126 ]),
1127 MockAffectedFile('UsedDeprecatedMediumTestAnnotation.java', [
1128 'import android.test.suitebuilder.annotation.MediumTest;',
1129 ]),
1130 MockAffectedFile('UsedDeprecatedSmallTestAnnotation.java', [
1131 'import android.test.suitebuilder.annotation.SmallTest;',
1132 ]),
1133 MockAffectedFile('UsedDeprecatedSmokeAnnotation.java', [
1134 'import android.test.suitebuilder.annotation.Smoke;',
1135 ])
1136 ]
1137 msgs = PRESUBMIT._CheckAndroidTestAnnotationUsage(
1138 mock_input_api, mock_output_api)
1139 self.assertEqual(1, len(msgs),
1140 'Expected %d items, found %d: %s'
1141 % (1, len(msgs), msgs))
1142 self.assertEqual(4, len(msgs[0].items),
1143 'Expected %d items, found %d: %s'
1144 % (4, len(msgs[0].items), msgs[0].items))
1145 self.assertTrue('UsedDeprecatedLargeTestAnnotation.java:1' in msgs[0].items,
1146 'UsedDeprecatedLargeTestAnnotation not found in errors')
1147 self.assertTrue('UsedDeprecatedMediumTestAnnotation.java:1'
1148 in msgs[0].items,
1149 'UsedDeprecatedMediumTestAnnotation not found in errors')
1150 self.assertTrue('UsedDeprecatedSmallTestAnnotation.java:1' in msgs[0].items,
1151 'UsedDeprecatedSmallTestAnnotation not found in errors')
1152 self.assertTrue('UsedDeprecatedSmokeAnnotation.java:1' in msgs[0].items,
1153 'UsedDeprecatedSmokeAnnotation not found in errors')
1154
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391155
Yoland Yanb92fa522017-08-28 17:37:061156class AndroidDeprecatedJUnitFrameworkTest(unittest.TestCase):
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271157 def testCheckAndroidTestJUnitFramework(self):
Yoland Yanb92fa522017-08-28 17:37:061158 mock_input_api = MockInputApi()
1159 mock_output_api = MockOutputApi()
yolandyan45001472016-12-21 21:12:421160
Yoland Yanb92fa522017-08-28 17:37:061161 mock_input_api.files = [
1162 MockAffectedFile('LalaLand.java', [
1163 'random stuff'
1164 ]),
1165 MockAffectedFile('CorrectUsage.java', [
1166 'import org.junit.ABC',
1167 'import org.junit.XYZ;',
1168 ]),
1169 MockAffectedFile('UsedDeprecatedJUnit.java', [
1170 'import junit.framework.*;',
1171 ]),
1172 MockAffectedFile('UsedDeprecatedJUnitAssert.java', [
1173 'import junit.framework.Assert;',
1174 ]),
1175 ]
1176 msgs = PRESUBMIT._CheckAndroidTestJUnitFrameworkImport(
1177 mock_input_api, mock_output_api)
1178 self.assertEqual(1, len(msgs),
1179 'Expected %d items, found %d: %s'
1180 % (1, len(msgs), msgs))
1181 self.assertEqual(2, len(msgs[0].items),
1182 'Expected %d items, found %d: %s'
1183 % (2, len(msgs[0].items), msgs[0].items))
1184 self.assertTrue('UsedDeprecatedJUnit.java:1' in msgs[0].items,
1185 'UsedDeprecatedJUnit.java not found in errors')
1186 self.assertTrue('UsedDeprecatedJUnitAssert.java:1'
1187 in msgs[0].items,
1188 'UsedDeprecatedJUnitAssert not found in errors')
1189
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391190
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271191class AndroidJUnitBaseClassTest(unittest.TestCase):
1192 def testCheckAndroidTestJUnitBaseClass(self):
Yoland Yanb92fa522017-08-28 17:37:061193 mock_input_api = MockInputApi()
1194 mock_output_api = MockOutputApi()
1195
1196 mock_input_api.files = [
1197 MockAffectedFile('LalaLand.java', [
1198 'random stuff'
1199 ]),
1200 MockAffectedFile('CorrectTest.java', [
1201 '@RunWith(ABC.class);'
1202 'public class CorrectTest {',
1203 '}',
1204 ]),
1205 MockAffectedFile('HistoricallyIncorrectTest.java', [
1206 'public class Test extends BaseCaseA {',
1207 '}',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391208 ], old_contents=[
Yoland Yanb92fa522017-08-28 17:37:061209 'public class Test extends BaseCaseB {',
1210 '}',
1211 ]),
1212 MockAffectedFile('CorrectTestWithInterface.java', [
1213 '@RunWith(ABC.class);'
1214 'public class CorrectTest implement Interface {',
1215 '}',
1216 ]),
1217 MockAffectedFile('IncorrectTest.java', [
1218 'public class IncorrectTest extends TestCase {',
1219 '}',
1220 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241221 MockAffectedFile('IncorrectWithInterfaceTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061222 'public class Test implements X extends BaseClass {',
1223 '}',
1224 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241225 MockAffectedFile('IncorrectMultiLineTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061226 'public class Test implements X, Y, Z',
1227 ' extends TestBase {',
1228 '}',
1229 ]),
1230 ]
1231 msgs = PRESUBMIT._CheckAndroidTestJUnitInheritance(
1232 mock_input_api, mock_output_api)
1233 self.assertEqual(1, len(msgs),
1234 'Expected %d items, found %d: %s'
1235 % (1, len(msgs), msgs))
1236 self.assertEqual(3, len(msgs[0].items),
1237 'Expected %d items, found %d: %s'
1238 % (3, len(msgs[0].items), msgs[0].items))
1239 self.assertTrue('IncorrectTest.java:1' in msgs[0].items,
1240 'IncorrectTest not found in errors')
Vaclav Brozekf01ed502018-03-16 19:38:241241 self.assertTrue('IncorrectWithInterfaceTest.java:1'
Yoland Yanb92fa522017-08-28 17:37:061242 in msgs[0].items,
Vaclav Brozekf01ed502018-03-16 19:38:241243 'IncorrectWithInterfaceTest not found in errors')
1244 self.assertTrue('IncorrectMultiLineTest.java:2' in msgs[0].items,
1245 'IncorrectMultiLineTest not found in errors')
yolandyan45001472016-12-21 21:12:421246
Jinsong Fan91ebbbd2019-04-16 14:57:171247class AndroidDebuggableBuildTest(unittest.TestCase):
1248
1249 def testCheckAndroidDebuggableBuild(self):
1250 mock_input_api = MockInputApi()
1251 mock_output_api = MockOutputApi()
1252
1253 mock_input_api.files = [
1254 MockAffectedFile('RandomStuff.java', [
1255 'random stuff'
1256 ]),
1257 MockAffectedFile('CorrectUsage.java', [
1258 'import org.chromium.base.BuildInfo;',
1259 'some random stuff',
1260 'boolean isOsDebuggable = BuildInfo.isDebugAndroid();',
1261 ]),
1262 MockAffectedFile('JustCheckUserdebugBuild.java', [
1263 'import android.os.Build;',
1264 'some random stuff',
1265 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")',
1266 ]),
1267 MockAffectedFile('JustCheckEngineeringBuild.java', [
1268 'import android.os.Build;',
1269 'some random stuff',
1270 'boolean isOsDebuggable = "eng".equals(Build.TYPE)',
1271 ]),
1272 MockAffectedFile('UsedBuildType.java', [
1273 'import android.os.Build;',
1274 'some random stuff',
1275 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")'
1276 '|| "eng".equals(Build.TYPE)',
1277 ]),
1278 MockAffectedFile('UsedExplicitBuildType.java', [
1279 'some random stuff',
1280 'boolean isOsDebuggable = android.os.Build.TYPE.equals("userdebug")'
1281 '|| "eng".equals(android.os.Build.TYPE)',
1282 ]),
1283 ]
1284
1285 msgs = PRESUBMIT._CheckAndroidDebuggableBuild(
1286 mock_input_api, mock_output_api)
1287 self.assertEqual(1, len(msgs),
1288 'Expected %d items, found %d: %s'
1289 % (1, len(msgs), msgs))
1290 self.assertEqual(4, len(msgs[0].items),
1291 'Expected %d items, found %d: %s'
1292 % (4, len(msgs[0].items), msgs[0].items))
1293 self.assertTrue('JustCheckUserdebugBuild.java:3' in msgs[0].items)
1294 self.assertTrue('JustCheckEngineeringBuild.java:3' in msgs[0].items)
1295 self.assertTrue('UsedBuildType.java:3' in msgs[0].items)
1296 self.assertTrue('UsedExplicitBuildType.java:2' in msgs[0].items)
1297
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391298
dgn4401aa52015-04-29 16:26:171299class LogUsageTest(unittest.TestCase):
1300
dgnaa68d5e2015-06-10 10:08:221301 def testCheckAndroidCrLogUsage(self):
1302 mock_input_api = MockInputApi()
1303 mock_output_api = MockOutputApi()
1304
1305 mock_input_api.files = [
1306 MockAffectedFile('RandomStuff.java', [
1307 'random stuff'
1308 ]),
dgn87d9fb62015-06-12 09:15:121309 MockAffectedFile('HasAndroidLog.java', [
1310 'import android.util.Log;',
1311 'some random stuff',
1312 'Log.d("TAG", "foo");',
1313 ]),
1314 MockAffectedFile('HasExplicitUtilLog.java', [
1315 'some random stuff',
1316 'android.util.Log.d("TAG", "foo");',
1317 ]),
1318 MockAffectedFile('IsInBasePackage.java', [
1319 'package org.chromium.base;',
dgn38736db2015-09-18 19:20:511320 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121321 'Log.d(TAG, "foo");',
1322 ]),
1323 MockAffectedFile('IsInBasePackageButImportsLog.java', [
1324 'package org.chromium.base;',
1325 'import android.util.Log;',
dgn38736db2015-09-18 19:20:511326 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121327 'Log.d(TAG, "foo");',
1328 ]),
1329 MockAffectedFile('HasBothLog.java', [
1330 'import org.chromium.base.Log;',
1331 'some random stuff',
dgn38736db2015-09-18 19:20:511332 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121333 'Log.d(TAG, "foo");',
1334 'android.util.Log.d("TAG", "foo");',
1335 ]),
dgnaa68d5e2015-06-10 10:08:221336 MockAffectedFile('HasCorrectTag.java', [
1337 'import org.chromium.base.Log;',
1338 'some random stuff',
dgn38736db2015-09-18 19:20:511339 'private static final String TAG = "cr_Foo";',
1340 'Log.d(TAG, "foo");',
1341 ]),
1342 MockAffectedFile('HasOldTag.java', [
1343 'import org.chromium.base.Log;',
1344 'some random stuff',
dgnaa68d5e2015-06-10 10:08:221345 'private static final String TAG = "cr.Foo";',
1346 'Log.d(TAG, "foo");',
1347 ]),
dgn38736db2015-09-18 19:20:511348 MockAffectedFile('HasDottedTag.java', [
dgnaa68d5e2015-06-10 10:08:221349 'import org.chromium.base.Log;',
1350 'some random stuff',
dgn38736db2015-09-18 19:20:511351 'private static final String TAG = "cr_foo.bar";',
dgnaa68d5e2015-06-10 10:08:221352 'Log.d(TAG, "foo");',
1353 ]),
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461354 MockAffectedFile('HasDottedTagPublic.java', [
1355 'import org.chromium.base.Log;',
1356 'some random stuff',
1357 'public static final String TAG = "cr_foo.bar";',
1358 'Log.d(TAG, "foo");',
1359 ]),
dgnaa68d5e2015-06-10 10:08:221360 MockAffectedFile('HasNoTagDecl.java', [
1361 'import org.chromium.base.Log;',
1362 'some random stuff',
1363 'Log.d(TAG, "foo");',
1364 ]),
1365 MockAffectedFile('HasIncorrectTagDecl.java', [
1366 'import org.chromium.base.Log;',
dgn38736db2015-09-18 19:20:511367 'private static final String TAHG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221368 'some random stuff',
1369 'Log.d(TAG, "foo");',
1370 ]),
1371 MockAffectedFile('HasInlineTag.java', [
1372 'import org.chromium.base.Log;',
1373 'some random stuff',
dgn38736db2015-09-18 19:20:511374 'private static final String TAG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221375 'Log.d("TAG", "foo");',
1376 ]),
Tomasz Śniatowski3ae2f102020-03-23 15:35:551377 MockAffectedFile('HasInlineTagWithSpace.java', [
1378 'import org.chromium.base.Log;',
1379 'some random stuff',
1380 'private static final String TAG = "cr_Foo";',
1381 'Log.d("log message", "foo");',
1382 ]),
dgn38736db2015-09-18 19:20:511383 MockAffectedFile('HasUnprefixedTag.java', [
dgnaa68d5e2015-06-10 10:08:221384 'import org.chromium.base.Log;',
1385 'some random stuff',
1386 'private static final String TAG = "rubbish";',
1387 'Log.d(TAG, "foo");',
1388 ]),
1389 MockAffectedFile('HasTooLongTag.java', [
1390 'import org.chromium.base.Log;',
1391 'some random stuff',
dgn38736db2015-09-18 19:20:511392 'private static final String TAG = "21_charachers_long___";',
dgnaa68d5e2015-06-10 10:08:221393 'Log.d(TAG, "foo");',
1394 ]),
Tomasz Śniatowski3ae2f102020-03-23 15:35:551395 MockAffectedFile('HasTooLongTagWithNoLogCallsInDiff.java', [
1396 'import org.chromium.base.Log;',
1397 'some random stuff',
1398 'private static final String TAG = "21_charachers_long___";',
1399 ]),
dgnaa68d5e2015-06-10 10:08:221400 ]
1401
1402 msgs = PRESUBMIT._CheckAndroidCrLogUsage(
1403 mock_input_api, mock_output_api)
1404
dgn38736db2015-09-18 19:20:511405 self.assertEqual(5, len(msgs),
1406 'Expected %d items, found %d: %s' % (5, len(msgs), msgs))
dgnaa68d5e2015-06-10 10:08:221407
1408 # Declaration format
dgn38736db2015-09-18 19:20:511409 nb = len(msgs[0].items)
1410 self.assertEqual(2, nb,
1411 'Expected %d items, found %d: %s' % (2, nb, msgs[0].items))
dgnaa68d5e2015-06-10 10:08:221412 self.assertTrue('HasNoTagDecl.java' in msgs[0].items)
1413 self.assertTrue('HasIncorrectTagDecl.java' in msgs[0].items)
dgnaa68d5e2015-06-10 10:08:221414
1415 # Tag length
dgn38736db2015-09-18 19:20:511416 nb = len(msgs[1].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551417 self.assertEqual(2, nb,
1418 'Expected %d items, found %d: %s' % (2, nb, msgs[1].items))
dgnaa68d5e2015-06-10 10:08:221419 self.assertTrue('HasTooLongTag.java' in msgs[1].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551420 self.assertTrue('HasTooLongTagWithNoLogCallsInDiff.java' in msgs[1].items)
dgnaa68d5e2015-06-10 10:08:221421
1422 # Tag must be a variable named TAG
dgn38736db2015-09-18 19:20:511423 nb = len(msgs[2].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551424 self.assertEqual(3, nb,
1425 'Expected %d items, found %d: %s' % (3, nb, msgs[2].items))
1426 self.assertTrue('HasBothLog.java:5' in msgs[2].items)
dgnaa68d5e2015-06-10 10:08:221427 self.assertTrue('HasInlineTag.java:4' in msgs[2].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551428 self.assertTrue('HasInlineTagWithSpace.java:4' in msgs[2].items)
dgnaa68d5e2015-06-10 10:08:221429
dgn87d9fb62015-06-12 09:15:121430 # Util Log usage
dgn38736db2015-09-18 19:20:511431 nb = len(msgs[3].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551432 self.assertEqual(3, nb,
1433 'Expected %d items, found %d: %s' % (3, nb, msgs[3].items))
dgn87d9fb62015-06-12 09:15:121434 self.assertTrue('HasAndroidLog.java:3' in msgs[3].items)
Tomasz Śniatowski3ae2f102020-03-23 15:35:551435 self.assertTrue('HasExplicitUtilLog.java:2' in msgs[3].items)
dgn87d9fb62015-06-12 09:15:121436 self.assertTrue('IsInBasePackageButImportsLog.java:4' in msgs[3].items)
dgnaa68d5e2015-06-10 10:08:221437
dgn38736db2015-09-18 19:20:511438 # Tag must not contain
1439 nb = len(msgs[4].items)
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461440 self.assertEqual(3, nb,
dgn38736db2015-09-18 19:20:511441 'Expected %d items, found %d: %s' % (2, nb, msgs[4].items))
1442 self.assertTrue('HasDottedTag.java' in msgs[4].items)
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461443 self.assertTrue('HasDottedTagPublic.java' in msgs[4].items)
dgn38736db2015-09-18 19:20:511444 self.assertTrue('HasOldTag.java' in msgs[4].items)
1445
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391446
estadee17314a02017-01-12 16:22:161447class GoogleAnswerUrlFormatTest(unittest.TestCase):
1448
1449 def testCatchAnswerUrlId(self):
1450 input_api = MockInputApi()
1451 input_api.files = [
1452 MockFile('somewhere/file.cc',
1453 ['char* host = '
1454 ' "https://support.google.com/chrome/answer/123456";']),
1455 MockFile('somewhere_else/file.cc',
1456 ['char* host = '
1457 ' "https://support.google.com/chrome/a/answer/123456";']),
1458 ]
1459
1460 warnings = PRESUBMIT._CheckGoogleSupportAnswerUrl(
1461 input_api, MockOutputApi())
1462 self.assertEqual(1, len(warnings))
1463 self.assertEqual(2, len(warnings[0].items))
1464
1465 def testAllowAnswerUrlParam(self):
1466 input_api = MockInputApi()
1467 input_api.files = [
1468 MockFile('somewhere/file.cc',
1469 ['char* host = '
1470 ' "https://support.google.com/chrome/?p=cpn_crash_reports";']),
1471 ]
1472
1473 warnings = PRESUBMIT._CheckGoogleSupportAnswerUrl(
1474 input_api, MockOutputApi())
1475 self.assertEqual(0, len(warnings))
1476
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391477
reillyi38965732015-11-16 18:27:331478class HardcodedGoogleHostsTest(unittest.TestCase):
1479
1480 def testWarnOnAssignedLiterals(self):
1481 input_api = MockInputApi()
1482 input_api.files = [
1483 MockFile('content/file.cc',
1484 ['char* host = "https://www.google.com";']),
1485 MockFile('content/file.cc',
1486 ['char* host = "https://www.googleapis.com";']),
1487 MockFile('content/file.cc',
1488 ['char* host = "https://clients1.google.com";']),
1489 ]
1490
1491 warnings = PRESUBMIT._CheckHardcodedGoogleHostsInLowerLayers(
1492 input_api, MockOutputApi())
1493 self.assertEqual(1, len(warnings))
1494 self.assertEqual(3, len(warnings[0].items))
1495
1496 def testAllowInComment(self):
1497 input_api = MockInputApi()
1498 input_api.files = [
1499 MockFile('content/file.cc',
1500 ['char* host = "https://www.aol.com"; // google.com'])
1501 ]
1502
1503 warnings = PRESUBMIT._CheckHardcodedGoogleHostsInLowerLayers(
1504 input_api, MockOutputApi())
1505 self.assertEqual(0, len(warnings))
1506
dgn4401aa52015-04-29 16:26:171507
James Cook6b6597c2019-11-06 22:05:291508class ChromeOsSyncedPrefRegistrationTest(unittest.TestCase):
1509
1510 def testWarnsOnChromeOsDirectories(self):
1511 input_api = MockInputApi()
1512 input_api.files = [
1513 MockFile('ash/file.cc',
1514 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1515 MockFile('chrome/browser/chromeos/file.cc',
1516 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1517 MockFile('chromeos/file.cc',
1518 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1519 MockFile('components/arc/file.cc',
1520 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1521 MockFile('components/exo/file.cc',
1522 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1523 ]
1524 warnings = PRESUBMIT._CheckChromeOsSyncedPrefRegistration(
1525 input_api, MockOutputApi())
1526 self.assertEqual(1, len(warnings))
1527
1528 def testDoesNotWarnOnSyncOsPref(self):
1529 input_api = MockInputApi()
1530 input_api.files = [
1531 MockFile('chromeos/file.cc',
1532 ['PrefRegistrySyncable::SYNCABLE_OS_PREF']),
1533 ]
1534 warnings = PRESUBMIT._CheckChromeOsSyncedPrefRegistration(
1535 input_api, MockOutputApi())
1536 self.assertEqual(0, len(warnings))
1537
1538 def testDoesNotWarnOnCrossPlatformDirectories(self):
1539 input_api = MockInputApi()
1540 input_api.files = [
1541 MockFile('chrome/browser/ui/file.cc',
1542 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1543 MockFile('components/sync/file.cc',
1544 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1545 MockFile('content/browser/file.cc',
1546 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1547 ]
1548 warnings = PRESUBMIT._CheckChromeOsSyncedPrefRegistration(
1549 input_api, MockOutputApi())
1550 self.assertEqual(0, len(warnings))
1551
1552 def testSeparateWarningForPriorityPrefs(self):
1553 input_api = MockInputApi()
1554 input_api.files = [
1555 MockFile('chromeos/file.cc',
1556 ['PrefRegistrySyncable::SYNCABLE_PREF',
1557 'PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF']),
1558 ]
1559 warnings = PRESUBMIT._CheckChromeOsSyncedPrefRegistration(
1560 input_api, MockOutputApi())
1561 self.assertEqual(2, len(warnings))
1562
1563
jbriance9e12f162016-11-25 07:57:501564class ForwardDeclarationTest(unittest.TestCase):
jbriance2c51e821a2016-12-12 08:24:311565 def testCheckHeadersOnlyOutsideThirdParty(self):
jbriance9e12f162016-11-25 07:57:501566 mock_input_api = MockInputApi()
1567 mock_input_api.files = [
1568 MockAffectedFile('somewhere/file.cc', [
1569 'class DummyClass;'
jbriance2c51e821a2016-12-12 08:24:311570 ]),
1571 MockAffectedFile('third_party/header.h', [
1572 'class DummyClass;'
jbriance9e12f162016-11-25 07:57:501573 ])
1574 ]
1575 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391576 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501577 self.assertEqual(0, len(warnings))
1578
1579 def testNoNestedDeclaration(self):
1580 mock_input_api = MockInputApi()
1581 mock_input_api.files = [
1582 MockAffectedFile('somewhere/header.h', [
jbriance2c51e821a2016-12-12 08:24:311583 'class SomeClass {',
1584 ' protected:',
1585 ' class NotAMatch;',
jbriance9e12f162016-11-25 07:57:501586 '};'
1587 ])
1588 ]
1589 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391590 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501591 self.assertEqual(0, len(warnings))
1592
1593 def testSubStrings(self):
1594 mock_input_api = MockInputApi()
1595 mock_input_api.files = [
1596 MockAffectedFile('somewhere/header.h', [
1597 'class NotUsefulClass;',
1598 'struct SomeStruct;',
1599 'UsefulClass *p1;',
1600 'SomeStructPtr *p2;'
1601 ])
1602 ]
1603 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391604 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501605 self.assertEqual(2, len(warnings))
1606
1607 def testUselessForwardDeclaration(self):
1608 mock_input_api = MockInputApi()
1609 mock_input_api.files = [
1610 MockAffectedFile('somewhere/header.h', [
1611 'class DummyClass;',
1612 'struct DummyStruct;',
1613 'class UsefulClass;',
1614 'std::unique_ptr<UsefulClass> p;'
jbriance2c51e821a2016-12-12 08:24:311615 ])
jbriance9e12f162016-11-25 07:57:501616 ]
1617 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391618 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501619 self.assertEqual(2, len(warnings))
1620
jbriance2c51e821a2016-12-12 08:24:311621 def testBlinkHeaders(self):
1622 mock_input_api = MockInputApi()
1623 mock_input_api.files = [
Kent Tamura32dbbcb2018-11-30 12:28:491624 MockAffectedFile('third_party/blink/header.h', [
jbriance2c51e821a2016-12-12 08:24:311625 'class DummyClass;',
1626 'struct DummyStruct;',
1627 ]),
Kent Tamura32dbbcb2018-11-30 12:28:491628 MockAffectedFile('third_party\\blink\\header.h', [
jbriance2c51e821a2016-12-12 08:24:311629 'class DummyClass;',
1630 'struct DummyStruct;',
1631 ])
1632 ]
1633 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391634 MockOutputApi())
jbriance2c51e821a2016-12-12 08:24:311635 self.assertEqual(4, len(warnings))
1636
jbriance9e12f162016-11-25 07:57:501637
rlanday6802cf632017-05-30 17:48:361638class RelativeIncludesTest(unittest.TestCase):
1639 def testThirdPartyNotWebKitIgnored(self):
1640 mock_input_api = MockInputApi()
1641 mock_input_api.files = [
1642 MockAffectedFile('third_party/test.cpp', '#include "../header.h"'),
1643 MockAffectedFile('third_party/test/test.cpp', '#include "../header.h"'),
1644 ]
1645
1646 mock_output_api = MockOutputApi()
1647
1648 errors = PRESUBMIT._CheckForRelativeIncludes(
1649 mock_input_api, mock_output_api)
1650 self.assertEqual(0, len(errors))
1651
1652 def testNonCppFileIgnored(self):
1653 mock_input_api = MockInputApi()
1654 mock_input_api.files = [
1655 MockAffectedFile('test.py', '#include "../header.h"'),
1656 ]
1657
1658 mock_output_api = MockOutputApi()
1659
1660 errors = PRESUBMIT._CheckForRelativeIncludes(
1661 mock_input_api, mock_output_api)
1662 self.assertEqual(0, len(errors))
1663
1664 def testInnocuousChangesAllowed(self):
1665 mock_input_api = MockInputApi()
1666 mock_input_api.files = [
1667 MockAffectedFile('test.cpp', '#include "header.h"'),
1668 MockAffectedFile('test2.cpp', '../'),
1669 ]
1670
1671 mock_output_api = MockOutputApi()
1672
1673 errors = PRESUBMIT._CheckForRelativeIncludes(
1674 mock_input_api, mock_output_api)
1675 self.assertEqual(0, len(errors))
1676
1677 def testRelativeIncludeNonWebKitProducesError(self):
1678 mock_input_api = MockInputApi()
1679 mock_input_api.files = [
1680 MockAffectedFile('test.cpp', ['#include "../header.h"']),
1681 ]
1682
1683 mock_output_api = MockOutputApi()
1684
1685 errors = PRESUBMIT._CheckForRelativeIncludes(
1686 mock_input_api, mock_output_api)
1687 self.assertEqual(1, len(errors))
1688
1689 def testRelativeIncludeWebKitProducesError(self):
1690 mock_input_api = MockInputApi()
1691 mock_input_api.files = [
Kent Tamura32dbbcb2018-11-30 12:28:491692 MockAffectedFile('third_party/blink/test.cpp',
rlanday6802cf632017-05-30 17:48:361693 ['#include "../header.h']),
1694 ]
1695
1696 mock_output_api = MockOutputApi()
1697
1698 errors = PRESUBMIT._CheckForRelativeIncludes(
1699 mock_input_api, mock_output_api)
1700 self.assertEqual(1, len(errors))
dbeam1ec68ac2016-12-15 05:22:241701
Daniel Cheng13ca61a882017-08-25 15:11:251702
Daniel Bratell65b033262019-04-23 08:17:061703class CCIncludeTest(unittest.TestCase):
1704 def testThirdPartyNotBlinkIgnored(self):
1705 mock_input_api = MockInputApi()
1706 mock_input_api.files = [
1707 MockAffectedFile('third_party/test.cpp', '#include "file.cc"'),
1708 ]
1709
1710 mock_output_api = MockOutputApi()
1711
1712 errors = PRESUBMIT._CheckForCcIncludes(
1713 mock_input_api, mock_output_api)
1714 self.assertEqual(0, len(errors))
1715
1716 def testPythonFileIgnored(self):
1717 mock_input_api = MockInputApi()
1718 mock_input_api.files = [
1719 MockAffectedFile('test.py', '#include "file.cc"'),
1720 ]
1721
1722 mock_output_api = MockOutputApi()
1723
1724 errors = PRESUBMIT._CheckForCcIncludes(
1725 mock_input_api, mock_output_api)
1726 self.assertEqual(0, len(errors))
1727
1728 def testIncFilesAccepted(self):
1729 mock_input_api = MockInputApi()
1730 mock_input_api.files = [
1731 MockAffectedFile('test.py', '#include "file.inc"'),
1732 ]
1733
1734 mock_output_api = MockOutputApi()
1735
1736 errors = PRESUBMIT._CheckForCcIncludes(
1737 mock_input_api, mock_output_api)
1738 self.assertEqual(0, len(errors))
1739
1740 def testInnocuousChangesAllowed(self):
1741 mock_input_api = MockInputApi()
1742 mock_input_api.files = [
1743 MockAffectedFile('test.cpp', '#include "header.h"'),
1744 MockAffectedFile('test2.cpp', 'Something "file.cc"'),
1745 ]
1746
1747 mock_output_api = MockOutputApi()
1748
1749 errors = PRESUBMIT._CheckForCcIncludes(
1750 mock_input_api, mock_output_api)
1751 self.assertEqual(0, len(errors))
1752
1753 def testCcIncludeNonBlinkProducesError(self):
1754 mock_input_api = MockInputApi()
1755 mock_input_api.files = [
1756 MockAffectedFile('test.cpp', ['#include "file.cc"']),
1757 ]
1758
1759 mock_output_api = MockOutputApi()
1760
1761 errors = PRESUBMIT._CheckForCcIncludes(
1762 mock_input_api, mock_output_api)
1763 self.assertEqual(1, len(errors))
1764
1765 def testCppIncludeBlinkProducesError(self):
1766 mock_input_api = MockInputApi()
1767 mock_input_api.files = [
1768 MockAffectedFile('third_party/blink/test.cpp',
1769 ['#include "foo/file.cpp"']),
1770 ]
1771
1772 mock_output_api = MockOutputApi()
1773
1774 errors = PRESUBMIT._CheckForCcIncludes(
1775 mock_input_api, mock_output_api)
1776 self.assertEqual(1, len(errors))
1777
1778
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191779class NewHeaderWithoutGnChangeTest(unittest.TestCase):
1780 def testAddHeaderWithoutGn(self):
1781 mock_input_api = MockInputApi()
1782 mock_input_api.files = [
1783 MockAffectedFile('base/stuff.h', ''),
1784 ]
1785 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1786 mock_input_api, MockOutputApi())
1787 self.assertEqual(1, len(warnings))
1788 self.assertTrue('base/stuff.h' in warnings[0].items)
1789
1790 def testModifyHeader(self):
1791 mock_input_api = MockInputApi()
1792 mock_input_api.files = [
1793 MockAffectedFile('base/stuff.h', '', action='M'),
1794 ]
1795 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1796 mock_input_api, MockOutputApi())
1797 self.assertEqual(0, len(warnings))
1798
1799 def testDeleteHeader(self):
1800 mock_input_api = MockInputApi()
1801 mock_input_api.files = [
1802 MockAffectedFile('base/stuff.h', '', action='D'),
1803 ]
1804 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1805 mock_input_api, MockOutputApi())
1806 self.assertEqual(0, len(warnings))
1807
1808 def testAddHeaderWithGn(self):
1809 mock_input_api = MockInputApi()
1810 mock_input_api.files = [
1811 MockAffectedFile('base/stuff.h', ''),
1812 MockAffectedFile('base/BUILD.gn', 'stuff.h'),
1813 ]
1814 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1815 mock_input_api, MockOutputApi())
1816 self.assertEqual(0, len(warnings))
1817
1818 def testAddHeaderWithGni(self):
1819 mock_input_api = MockInputApi()
1820 mock_input_api.files = [
1821 MockAffectedFile('base/stuff.h', ''),
1822 MockAffectedFile('base/files.gni', 'stuff.h'),
1823 ]
1824 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1825 mock_input_api, MockOutputApi())
1826 self.assertEqual(0, len(warnings))
1827
1828 def testAddHeaderWithOther(self):
1829 mock_input_api = MockInputApi()
1830 mock_input_api.files = [
1831 MockAffectedFile('base/stuff.h', ''),
1832 MockAffectedFile('base/stuff.cc', 'stuff.h'),
1833 ]
1834 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1835 mock_input_api, MockOutputApi())
1836 self.assertEqual(1, len(warnings))
1837
1838 def testAddHeaderWithWrongGn(self):
1839 mock_input_api = MockInputApi()
1840 mock_input_api.files = [
1841 MockAffectedFile('base/stuff.h', ''),
1842 MockAffectedFile('base/BUILD.gn', 'stuff_h'),
1843 ]
1844 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1845 mock_input_api, MockOutputApi())
1846 self.assertEqual(1, len(warnings))
1847
1848 def testAddHeadersWithGn(self):
1849 mock_input_api = MockInputApi()
1850 mock_input_api.files = [
1851 MockAffectedFile('base/stuff.h', ''),
1852 MockAffectedFile('base/another.h', ''),
1853 MockAffectedFile('base/BUILD.gn', 'another.h\nstuff.h'),
1854 ]
1855 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1856 mock_input_api, MockOutputApi())
1857 self.assertEqual(0, len(warnings))
1858
1859 def testAddHeadersWithWrongGn(self):
1860 mock_input_api = MockInputApi()
1861 mock_input_api.files = [
1862 MockAffectedFile('base/stuff.h', ''),
1863 MockAffectedFile('base/another.h', ''),
1864 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff.h'),
1865 ]
1866 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1867 mock_input_api, MockOutputApi())
1868 self.assertEqual(1, len(warnings))
1869 self.assertFalse('base/stuff.h' in warnings[0].items)
1870 self.assertTrue('base/another.h' in warnings[0].items)
1871
1872 def testAddHeadersWithWrongGn2(self):
1873 mock_input_api = MockInputApi()
1874 mock_input_api.files = [
1875 MockAffectedFile('base/stuff.h', ''),
1876 MockAffectedFile('base/another.h', ''),
1877 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff_h'),
1878 ]
1879 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1880 mock_input_api, MockOutputApi())
1881 self.assertEqual(1, len(warnings))
1882 self.assertTrue('base/stuff.h' in warnings[0].items)
1883 self.assertTrue('base/another.h' in warnings[0].items)
1884
1885
Michael Giuffridad3bc8672018-10-25 22:48:021886class CorrectProductNameInMessagesTest(unittest.TestCase):
1887 def testProductNameInDesc(self):
1888 mock_input_api = MockInputApi()
1889 mock_input_api.files = [
1890 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
1891 '<message name="Foo" desc="Welcome to Chrome">',
1892 ' Welcome to Chrome!',
1893 '</message>',
1894 ]),
1895 MockAffectedFile('chrome/app/chromium_strings.grd', [
1896 '<message name="Bar" desc="Welcome to Chrome">',
1897 ' Welcome to Chromium!',
1898 '</message>',
1899 ]),
1900 ]
1901 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1902 mock_input_api, MockOutputApi())
1903 self.assertEqual(0, len(warnings))
1904
1905 def testChromeInChromium(self):
1906 mock_input_api = MockInputApi()
1907 mock_input_api.files = [
1908 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
1909 '<message name="Foo" desc="Welcome to Chrome">',
1910 ' Welcome to Chrome!',
1911 '</message>',
1912 ]),
1913 MockAffectedFile('chrome/app/chromium_strings.grd', [
1914 '<message name="Bar" desc="Welcome to Chrome">',
1915 ' Welcome to Chrome!',
1916 '</message>',
1917 ]),
1918 ]
1919 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1920 mock_input_api, MockOutputApi())
1921 self.assertEqual(1, len(warnings))
1922 self.assertTrue('chrome/app/chromium_strings.grd' in warnings[0].items[0])
1923
1924 def testChromiumInChrome(self):
1925 mock_input_api = MockInputApi()
1926 mock_input_api.files = [
1927 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
1928 '<message name="Foo" desc="Welcome to Chrome">',
1929 ' Welcome to Chromium!',
1930 '</message>',
1931 ]),
1932 MockAffectedFile('chrome/app/chromium_strings.grd', [
1933 '<message name="Bar" desc="Welcome to Chrome">',
1934 ' Welcome to Chromium!',
1935 '</message>',
1936 ]),
1937 ]
1938 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1939 mock_input_api, MockOutputApi())
1940 self.assertEqual(1, len(warnings))
1941 self.assertTrue(
1942 'chrome/app/google_chrome_strings.grd:2' in warnings[0].items[0])
1943
1944 def testMultipleInstances(self):
1945 mock_input_api = MockInputApi()
1946 mock_input_api.files = [
1947 MockAffectedFile('chrome/app/chromium_strings.grd', [
1948 '<message name="Bar" desc="Welcome to Chrome">',
1949 ' Welcome to Chrome!',
1950 '</message>',
1951 '<message name="Baz" desc="A correct message">',
1952 ' Chromium is the software you are using.',
1953 '</message>',
1954 '<message name="Bat" desc="An incorrect message">',
1955 ' Google Chrome is the software you are using.',
1956 '</message>',
1957 ]),
1958 ]
1959 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1960 mock_input_api, MockOutputApi())
1961 self.assertEqual(1, len(warnings))
1962 self.assertTrue(
1963 'chrome/app/chromium_strings.grd:2' in warnings[0].items[0])
1964 self.assertTrue(
1965 'chrome/app/chromium_strings.grd:8' in warnings[0].items[1])
1966
1967 def testMultipleWarnings(self):
1968 mock_input_api = MockInputApi()
1969 mock_input_api.files = [
1970 MockAffectedFile('chrome/app/chromium_strings.grd', [
1971 '<message name="Bar" desc="Welcome to Chrome">',
1972 ' Welcome to Chrome!',
1973 '</message>',
1974 '<message name="Baz" desc="A correct message">',
1975 ' Chromium is the software you are using.',
1976 '</message>',
1977 '<message name="Bat" desc="An incorrect message">',
1978 ' Google Chrome is the software you are using.',
1979 '</message>',
1980 ]),
1981 MockAffectedFile('components/components_google_chrome_strings.grd', [
1982 '<message name="Bar" desc="Welcome to Chrome">',
1983 ' Welcome to Chrome!',
1984 '</message>',
1985 '<message name="Baz" desc="A correct message">',
1986 ' Chromium is the software you are using.',
1987 '</message>',
1988 '<message name="Bat" desc="An incorrect message">',
1989 ' Google Chrome is the software you are using.',
1990 '</message>',
1991 ]),
1992 ]
1993 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1994 mock_input_api, MockOutputApi())
1995 self.assertEqual(2, len(warnings))
1996 self.assertTrue(
1997 'components/components_google_chrome_strings.grd:5'
1998 in warnings[0].items[0])
1999 self.assertTrue(
2000 'chrome/app/chromium_strings.grd:2' in warnings[1].items[0])
2001 self.assertTrue(
2002 'chrome/app/chromium_strings.grd:8' in warnings[1].items[1])
2003
2004
Ken Rockot9f668262018-12-21 18:56:362005class ServiceManifestOwnerTest(unittest.TestCase):
Ken Rockot9f668262018-12-21 18:56:362006 def testServiceManifestChangeNeedsSecurityOwner(self):
2007 mock_input_api = MockInputApi()
2008 mock_input_api.files = [
2009 MockAffectedFile('services/goat/public/cpp/manifest.cc',
2010 [
2011 '#include "services/goat/public/cpp/manifest.h"',
2012 'const service_manager::Manifest& GetManifest() {}',
2013 ])]
2014 mock_output_api = MockOutputApi()
Wez17c66962020-04-29 15:26:032015 errors = PRESUBMIT._CheckSecurityOwners(
Ken Rockot9f668262018-12-21 18:56:362016 mock_input_api, mock_output_api)
2017 self.assertEqual(1, len(errors))
2018 self.assertEqual(
2019 'Found OWNERS files that need to be updated for IPC security review ' +
2020 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
2021
2022 def testNonServiceManifestSourceChangesDoNotRequireSecurityOwner(self):
2023 mock_input_api = MockInputApi()
2024 mock_input_api.files = [
2025 MockAffectedFile('some/non/service/thing/foo_manifest.cc',
2026 [
2027 'const char kNoEnforcement[] = "not a manifest!";',
2028 ])]
2029 mock_output_api = MockOutputApi()
Wez17c66962020-04-29 15:26:032030 errors = PRESUBMIT._CheckSecurityOwners(
2031 mock_input_api, mock_output_api)
2032 self.assertEqual([], errors)
2033
2034
2035class FuchsiaSecurityOwnerTest(unittest.TestCase):
2036 def testFidlChangeNeedsSecurityOwner(self):
2037 mock_input_api = MockInputApi()
2038 mock_input_api.files = [
2039 MockAffectedFile('potentially/scary/ipc.fidl',
2040 [
2041 'library test.fidl'
2042 ])]
2043 mock_output_api = MockOutputApi()
2044 errors = PRESUBMIT._CheckSecurityOwners(
2045 mock_input_api, mock_output_api)
2046 self.assertEqual(1, len(errors))
2047 self.assertEqual(
2048 'Found OWNERS files that need to be updated for IPC security review ' +
2049 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
2050
2051 def testComponentManifestV1ChangeNeedsSecurityOwner(self):
2052 mock_input_api = MockInputApi()
2053 mock_input_api.files = [
2054 MockAffectedFile('potentially/scary/v2_manifest.cmx',
2055 [
2056 '{ "that is no": "manifest!" }'
2057 ])]
2058 mock_output_api = MockOutputApi()
2059 errors = PRESUBMIT._CheckSecurityOwners(
2060 mock_input_api, mock_output_api)
2061 self.assertEqual(1, len(errors))
2062 self.assertEqual(
2063 'Found OWNERS files that need to be updated for IPC security review ' +
2064 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
2065
2066 def testComponentManifestV2NeedsSecurityOwner(self):
2067 mock_input_api = MockInputApi()
2068 mock_input_api.files = [
2069 MockAffectedFile('potentially/scary/v2_manifest.cml',
2070 [
2071 '{ "that is no": "manifest!" }'
2072 ])]
2073 mock_output_api = MockOutputApi()
2074 errors = PRESUBMIT._CheckSecurityOwners(
2075 mock_input_api, mock_output_api)
2076 self.assertEqual(1, len(errors))
2077 self.assertEqual(
2078 'Found OWNERS files that need to be updated for IPC security review ' +
2079 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
2080
2081 def testOtherFuchsiaChangesDoNotRequireSecurityOwner(self):
2082 mock_input_api = MockInputApi()
2083 mock_input_api.files = [
2084 MockAffectedFile('some/non/service/thing/fuchsia_fidl_cml_cmx_magic.cc',
2085 [
2086 'const char kNoEnforcement[] = "Security?!? Pah!";',
2087 ])]
2088 mock_output_api = MockOutputApi()
2089 errors = PRESUBMIT._CheckSecurityOwners(
Ken Rockot9f668262018-12-21 18:56:362090 mock_input_api, mock_output_api)
2091 self.assertEqual([], errors)
2092
Daniel Cheng13ca61a882017-08-25 15:11:252093
Robert Sesek2c905332020-05-06 23:17:132094class SecurityChangeTest(unittest.TestCase):
2095 class _MockOwnersDB(object):
2096 def __init__(self):
2097 self.email_regexp = '.*'
2098
2099 def owners_rooted_at_file(self, f):
2100 return ['[email protected]', '[email protected]']
2101
2102 def _mockChangeOwnerAndReviewers(self, input_api, owner, reviewers):
2103 def __MockOwnerAndReviewers(input_api, email_regexp, approval_needed=False):
2104 return [owner, reviewers]
2105 input_api.canned_checks.GetCodereviewOwnerAndReviewers = \
2106 __MockOwnerAndReviewers
2107
2108 def testDiffWithSandboxType(self):
2109 mock_input_api = MockInputApi()
2110 mock_input_api.files = [
2111 MockAffectedFile(
2112 'services/goat/teleporter_host.cc',
2113 [
2114 'content::ServiceProcessHost::Launch<mojom::GoatTeleporter>(',
2115 ' content::ServiceProcessHost::LaunchOptions()',
2116 ' .WithSandboxType(content::SandboxType::kGoaty)',
2117 ' .WithDisplayName("goat_teleporter")',
2118 ' .Build())'
2119 ]
2120 ),
2121 ]
2122 files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
2123 mock_input_api)
2124 self.assertEqual({
2125 'services/goat/teleporter_host.cc': set([
2126 'content::ServiceProcessHost::LaunchOptions::WithSandboxType'
2127 ])},
2128 files_to_functions)
2129
2130 def testDiffRemovingLine(self):
2131 mock_input_api = MockInputApi()
2132 mock_file = MockAffectedFile('services/goat/teleporter_host.cc', '')
2133 mock_file._scm_diff = """--- old 2020-05-04 14:08:25.000000000 -0400
2134+++ new 2020-05-04 14:08:32.000000000 -0400
2135@@ -1,5 +1,4 @@
2136 content::ServiceProcessHost::Launch<mojom::GoatTeleporter>(
2137 content::ServiceProcessHost::LaunchOptions()
2138- .WithSandboxType(content::SandboxType::kGoaty)
2139 .WithDisplayName("goat_teleporter")
2140 .Build())
2141"""
2142 mock_input_api.files = [mock_file]
2143 files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
2144 mock_input_api)
2145 self.assertEqual({
2146 'services/goat/teleporter_host.cc': set([
2147 'content::ServiceProcessHost::LaunchOptions::WithSandboxType'
2148 ])},
2149 files_to_functions)
2150
2151 def testChangeOwnersMissing(self):
2152 mock_input_api = MockInputApi()
2153 mock_input_api.owners_db = self._MockOwnersDB()
2154 mock_input_api.is_committing = False
2155 mock_input_api.files = [
2156 MockAffectedFile('file.cc', ['WithSandboxType(Sandbox)'])
2157 ]
2158 mock_output_api = MockOutputApi()
2159 self._mockChangeOwnerAndReviewers(
2160 mock_input_api, '[email protected]', ['[email protected]'])
2161 result = PRESUBMIT._CheckSecurityChanges(mock_input_api, mock_output_api)
2162 self.assertEquals(1, len(result))
2163 self.assertEquals(result[0].type, 'notify')
2164 self.assertEquals(result[0].message,
2165 'The following files change calls to security-sensive functions\n' \
2166 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
2167 ' file.cc\n'
2168 ' content::ServiceProcessHost::LaunchOptions::WithSandboxType\n\n')
2169
2170 def testChangeOwnersMissingAtCommit(self):
2171 mock_input_api = MockInputApi()
2172 mock_input_api.owners_db = self._MockOwnersDB()
2173 mock_input_api.is_committing = True
2174 mock_input_api.files = [
2175 MockAffectedFile('file.cc', ['WithSandboxType(Sandbox)'])
2176 ]
2177 mock_output_api = MockOutputApi()
2178 self._mockChangeOwnerAndReviewers(
2179 mock_input_api, '[email protected]', ['[email protected]'])
2180 result = PRESUBMIT._CheckSecurityChanges(mock_input_api, mock_output_api)
2181 self.assertEquals(1, len(result))
2182 self.assertEquals(result[0].type, 'error')
2183 self.assertEquals(result[0].message,
2184 'The following files change calls to security-sensive functions\n' \
2185 'that need to be reviewed by ipc/SECURITY_OWNERS.\n'
2186 ' file.cc\n'
2187 ' content::ServiceProcessHost::LaunchOptions::WithSandboxType\n\n')
2188
2189 def testChangeOwnersPresent(self):
2190 mock_input_api = MockInputApi()
2191 mock_input_api.owners_db = self._MockOwnersDB()
2192 mock_input_api.files = [
2193 MockAffectedFile('file.cc', ['WithSandboxType(Sandbox)'])
2194 ]
2195 mock_output_api = MockOutputApi()
2196 self._mockChangeOwnerAndReviewers(
2197 mock_input_api, '[email protected]',
2198 ['[email protected]', '[email protected]'])
2199 result = PRESUBMIT._CheckSecurityChanges(mock_input_api, mock_output_api)
2200 self.assertEquals(0, len(result))
2201
2202 def testChangeOwnerIsSecurityOwner(self):
2203 mock_input_api = MockInputApi()
2204 mock_input_api.owners_db = self._MockOwnersDB()
2205 mock_input_api.files = [
2206 MockAffectedFile('file.cc', ['WithSandboxType(Sandbox)'])
2207 ]
2208 mock_output_api = MockOutputApi()
2209 self._mockChangeOwnerAndReviewers(
2210 mock_input_api, '[email protected]', ['[email protected]'])
2211 result = PRESUBMIT._CheckSecurityChanges(mock_input_api, mock_output_api)
2212 self.assertEquals(1, len(result))
2213
2214
Mario Sanchez Prada2472cab2019-09-18 10:58:312215class BannedTypeCheckTest(unittest.TestCase):
Sylvain Defresnea8b73d252018-02-28 15:45:542216
Peter Kasting94a56c42019-10-25 21:54:042217 def testBannedCppFunctions(self):
2218 input_api = MockInputApi()
2219 input_api.files = [
2220 MockFile('some/cpp/problematic/file.cc',
2221 ['using namespace std;']),
Oksana Zhuravlovac8222d22019-12-19 19:21:162222 MockFile('third_party/blink/problematic/file.cc',
2223 ['GetInterfaceProvider()']),
Peter Kasting94a56c42019-10-25 21:54:042224 MockFile('some/cpp/ok/file.cc',
2225 ['using std::string;']),
Allen Bauer53b43fb12020-03-12 17:21:472226 MockFile('some/cpp/problematic/file2.cc',
2227 ['set_owned_by_client()']),
Peter Kasting94a56c42019-10-25 21:54:042228 ]
2229
Oksana Zhuravlovac8222d22019-12-19 19:21:162230 results = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
2231
2232 # warnings are results[0], errors are results[1]
2233 self.assertEqual(2, len(results))
2234 self.assertTrue('some/cpp/problematic/file.cc' in results[1].message)
2235 self.assertTrue(
2236 'third_party/blink/problematic/file.cc' in results[0].message)
2237 self.assertTrue('some/cpp/ok/file.cc' not in results[1].message)
Allen Bauer53b43fb12020-03-12 17:21:472238 self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
Peter Kasting94a56c42019-10-25 21:54:042239
Abhijeet Kandalkar1e7c2502019-10-29 15:05:452240 def testBannedBlinkDowncastHelpers(self):
2241 input_api = MockInputApi()
2242 input_api.files = [
2243 MockFile('some/cpp/problematic/file1.cc',
2244 ['DEFINE_TYPE_CASTS(ToType, FromType, from_argument,'
2245 'PointerPredicate(), ReferencePredicate());']),
2246 MockFile('some/cpp/problematic/file2.cc',
2247 ['bool is_test_ele = IsHTMLTestElement(n);']),
2248 MockFile('some/cpp/problematic/file3.cc',
2249 ['auto* html_test_ele = ToHTMLTestElement(n);']),
2250 MockFile('some/cpp/problematic/file4.cc',
2251 ['auto* html_test_ele_or_null = ToHTMLTestElementOrNull(n);']),
2252 MockFile('some/cpp/ok/file1.cc',
2253 ['bool is_test_ele = IsA<HTMLTestElement>(n);']),
2254 MockFile('some/cpp/ok/file2.cc',
2255 ['auto* html_test_ele = To<HTMLTestElement>(n);']),
2256 MockFile('some/cpp/ok/file3.cc',
2257 ['auto* html_test_ele_or_null = ',
2258 'DynamicTo<HTMLTestElement>(n);']),
2259 ]
2260
2261 # warnings are errors[0], errors are errors[1]
2262 errors = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
2263 self.assertEqual(2, len(errors))
2264 self.assertTrue('some/cpp/problematic/file1.cc' in errors[1].message)
2265 self.assertTrue('some/cpp/problematic/file2.cc' in errors[0].message)
2266 self.assertTrue('some/cpp/problematic/file3.cc' in errors[0].message)
2267 self.assertTrue('some/cpp/problematic/file4.cc' in errors[0].message)
2268 self.assertTrue('some/cpp/ok/file1.cc' not in errors[0].message)
2269 self.assertTrue('some/cpp/ok/file2.cc' not in errors[0].message)
2270 self.assertTrue('some/cpp/ok/file3.cc' not in errors[0].message)
2271
Peter K. Lee6c03ccff2019-07-15 14:40:052272 def testBannedIosObjcFunctions(self):
Sylvain Defresnea8b73d252018-02-28 15:45:542273 input_api = MockInputApi()
2274 input_api.files = [
2275 MockFile('some/ios/file.mm',
2276 ['TEST(SomeClassTest, SomeInteraction) {',
2277 '}']),
2278 MockFile('some/mac/file.mm',
2279 ['TEST(SomeClassTest, SomeInteraction) {',
2280 '}']),
2281 MockFile('another/ios_file.mm',
2282 ['class SomeTest : public testing::Test {};']),
Peter K. Lee6c03ccff2019-07-15 14:40:052283 MockFile('some/ios/file_egtest.mm',
2284 ['- (void)testSomething { EXPECT_OCMOCK_VERIFY(aMock); }']),
2285 MockFile('some/ios/file_unittest.mm',
2286 ['TEST_F(SomeTest, TestThis) { EXPECT_OCMOCK_VERIFY(aMock); }']),
Sylvain Defresnea8b73d252018-02-28 15:45:542287 ]
2288
2289 errors = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
2290 self.assertEqual(1, len(errors))
2291 self.assertTrue('some/ios/file.mm' in errors[0].message)
2292 self.assertTrue('another/ios_file.mm' in errors[0].message)
2293 self.assertTrue('some/mac/file.mm' not in errors[0].message)
Peter K. Lee6c03ccff2019-07-15 14:40:052294 self.assertTrue('some/ios/file_egtest.mm' in errors[0].message)
2295 self.assertTrue('some/ios/file_unittest.mm' not in errors[0].message)
Sylvain Defresnea8b73d252018-02-28 15:45:542296
Carlos Knippschildab192b8c2019-04-08 20:02:382297 def testBannedMojoFunctions(self):
2298 input_api = MockInputApi()
2299 input_api.files = [
2300 MockFile('some/cpp/problematic/file.cc',
2301 ['mojo::DataPipe();']),
Oksana Zhuravlovafd247772019-05-16 16:57:292302 MockFile('some/cpp/problematic/file2.cc',
2303 ['mojo::ConvertTo<>']),
Carlos Knippschildab192b8c2019-04-08 20:02:382304 MockFile('some/cpp/ok/file.cc',
2305 ['CreateDataPipe();']),
Kinuko Yasuda376c2ce12019-04-16 01:20:372306 MockFile('some/cpp/ok/file2.cc',
2307 ['mojo::DataPipeDrainer();']),
Oksana Zhuravlovafd247772019-05-16 16:57:292308 MockFile('third_party/blink/ok/file3.cc',
2309 ['mojo::ConvertTo<>']),
2310 MockFile('content/renderer/ok/file3.cc',
2311 ['mojo::ConvertTo<>']),
Carlos Knippschildab192b8c2019-04-08 20:02:382312 ]
2313
Oksana Zhuravlova1d3b59de2019-05-17 00:08:222314 results = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
2315
2316 # warnings are results[0], errors are results[1]
2317 self.assertEqual(2, len(results))
2318 self.assertTrue('some/cpp/problematic/file.cc' in results[1].message)
2319 self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
2320 self.assertTrue('some/cpp/ok/file.cc' not in results[1].message)
2321 self.assertTrue('some/cpp/ok/file2.cc' not in results[1].message)
2322 self.assertTrue('third_party/blink/ok/file3.cc' not in results[0].message)
2323 self.assertTrue('content/renderer/ok/file3.cc' not in results[0].message)
Carlos Knippschildab192b8c2019-04-08 20:02:382324
Mario Sanchez Prada2472cab2019-09-18 10:58:312325 def testDeprecatedMojoTypes(self):
Mario Sanchez Pradacec9cef2019-12-15 11:54:572326 ok_paths = ['components/arc']
2327 warning_paths = ['some/cpp']
Mario Sanchez Pradaaab91382019-12-19 08:57:092328 error_paths = ['third_party/blink', 'content']
Mario Sanchez Prada2472cab2019-09-18 10:58:312329 test_cases = [
2330 {
2331 'type': 'mojo::AssociatedBinding<>;',
2332 'file': 'file1.c'
2333 },
2334 {
2335 'type': 'mojo::AssociatedBindingSet<>;',
2336 'file': 'file2.c'
2337 },
2338 {
2339 'type': 'mojo::AssociatedInterfacePtr<>',
2340 'file': 'file3.cc'
2341 },
2342 {
2343 'type': 'mojo::AssociatedInterfacePtrInfo<>',
2344 'file': 'file4.cc'
2345 },
2346 {
2347 'type': 'mojo::AssociatedInterfaceRequest<>',
2348 'file': 'file5.cc'
2349 },
2350 {
2351 'type': 'mojo::Binding<>',
2352 'file': 'file6.cc'
2353 },
2354 {
2355 'type': 'mojo::BindingSet<>',
2356 'file': 'file7.cc'
2357 },
2358 {
2359 'type': 'mojo::InterfacePtr<>',
2360 'file': 'file8.cc'
2361 },
2362 {
2363 'type': 'mojo::InterfacePtrInfo<>',
2364 'file': 'file9.cc'
2365 },
2366 {
2367 'type': 'mojo::InterfaceRequest<>',
2368 'file': 'file10.cc'
2369 },
2370 {
2371 'type': 'mojo::MakeRequest()',
2372 'file': 'file11.cc'
2373 },
2374 {
2375 'type': 'mojo::MakeRequestAssociatedWithDedicatedPipe()',
2376 'file': 'file12.cc'
2377 },
2378 {
2379 'type': 'mojo::MakeStrongBinding()<>',
2380 'file': 'file13.cc'
2381 },
2382 {
2383 'type': 'mojo::MakeStrongAssociatedBinding()<>',
2384 'file': 'file14.cc'
2385 },
2386 {
2387 'type': 'mojo::StrongAssociatedBindingSet<>',
2388 'file': 'file15.cc'
2389 },
2390 {
2391 'type': 'mojo::StrongBindingSet<>',
2392 'file': 'file16.cc'
2393 },
2394 ]
2395
2396 # Build the list of MockFiles considering paths that should trigger warnings
Mario Sanchez Pradacec9cef2019-12-15 11:54:572397 # as well as paths that should trigger errors.
Mario Sanchez Prada2472cab2019-09-18 10:58:312398 input_api = MockInputApi()
2399 input_api.files = []
2400 for test_case in test_cases:
2401 for path in ok_paths:
2402 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2403 [test_case['type']]))
2404 for path in warning_paths:
2405 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2406 [test_case['type']]))
Mario Sanchez Pradacec9cef2019-12-15 11:54:572407 for path in error_paths:
2408 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2409 [test_case['type']]))
Mario Sanchez Prada2472cab2019-09-18 10:58:312410
2411 results = PRESUBMIT._CheckNoDeprecatedMojoTypes(input_api, MockOutputApi())
2412
Mario Sanchez Pradacec9cef2019-12-15 11:54:572413 # warnings are results[0], errors are results[1]
2414 self.assertEqual(2, len(results))
Mario Sanchez Prada2472cab2019-09-18 10:58:312415
2416 for test_case in test_cases:
Mario Sanchez Pradacec9cef2019-12-15 11:54:572417 # Check that no warnings nor errors have been triggered for these paths.
Mario Sanchez Prada2472cab2019-09-18 10:58:312418 for path in ok_paths:
2419 self.assertFalse(path in results[0].message)
Mario Sanchez Pradacec9cef2019-12-15 11:54:572420 self.assertFalse(path in results[1].message)
Mario Sanchez Prada2472cab2019-09-18 10:58:312421
2422 # Check warnings have been triggered for these paths.
2423 for path in warning_paths:
2424 self.assertTrue(path in results[0].message)
Mario Sanchez Pradacec9cef2019-12-15 11:54:572425 self.assertFalse(path in results[1].message)
2426
2427 # Check errors have been triggered for these paths.
2428 for path in error_paths:
2429 self.assertFalse(path in results[0].message)
2430 self.assertTrue(path in results[1].message)
Mario Sanchez Prada2472cab2019-09-18 10:58:312431
Sylvain Defresnea8b73d252018-02-28 15:45:542432
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272433class NoProductionCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozekf01ed502018-03-16 19:38:242434 def testTruePositives(self):
2435 mock_input_api = MockInputApi()
2436 mock_input_api.files = [
2437 MockFile('some/path/foo.cc', ['foo_for_testing();']),
2438 MockFile('some/path/foo.mm', ['FooForTesting();']),
2439 MockFile('some/path/foo.cxx', ['FooForTests();']),
2440 MockFile('some/path/foo.cpp', ['foo_for_test();']),
2441 ]
2442
2443 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctions(
2444 mock_input_api, MockOutputApi())
2445 self.assertEqual(1, len(results))
2446 self.assertEqual(4, len(results[0].items))
2447 self.assertTrue('foo.cc' in results[0].items[0])
2448 self.assertTrue('foo.mm' in results[0].items[1])
2449 self.assertTrue('foo.cxx' in results[0].items[2])
2450 self.assertTrue('foo.cpp' in results[0].items[3])
2451
2452 def testFalsePositives(self):
2453 mock_input_api = MockInputApi()
2454 mock_input_api.files = [
2455 MockFile('some/path/foo.h', ['foo_for_testing();']),
2456 MockFile('some/path/foo.mm', ['FooForTesting() {']),
2457 MockFile('some/path/foo.cc', ['::FooForTests();']),
2458 MockFile('some/path/foo.cpp', ['// foo_for_test();']),
2459 ]
2460
2461 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctions(
2462 mock_input_api, MockOutputApi())
2463 self.assertEqual(0, len(results))
2464
2465
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272466class NoProductionJavaCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozek7dbc28c2018-03-27 08:35:232467 def testTruePositives(self):
2468 mock_input_api = MockInputApi()
2469 mock_input_api.files = [
2470 MockFile('dir/java/src/foo.java', ['FooForTesting();']),
2471 MockFile('dir/java/src/bar.java', ['FooForTests(x);']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392472 MockFile('dir/java/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:232473 MockFile('dir/java/src/mult.java', [
2474 'int x = SomethingLongHere()',
2475 ' * SomethingLongHereForTesting();'
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392476 ])
Vaclav Brozek7dbc28c2018-03-27 08:35:232477 ]
2478
2479 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctionsJava(
2480 mock_input_api, MockOutputApi())
2481 self.assertEqual(1, len(results))
2482 self.assertEqual(4, len(results[0].items))
2483 self.assertTrue('foo.java' in results[0].items[0])
2484 self.assertTrue('bar.java' in results[0].items[1])
2485 self.assertTrue('baz.java' in results[0].items[2])
2486 self.assertTrue('mult.java' in results[0].items[3])
2487
2488 def testFalsePositives(self):
2489 mock_input_api = MockInputApi()
2490 mock_input_api.files = [
2491 MockFile('dir/java/src/foo.xml', ['FooForTesting();']),
2492 MockFile('dir/java/src/foo.java', ['FooForTests() {']),
2493 MockFile('dir/java/src/bar.java', ['// FooForTest();']),
2494 MockFile('dir/java/src/bar2.java', ['x = 1; // FooForTest();']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392495 MockFile('dir/javatests/src/baz.java', ['FooForTest(', 'y', ');']),
2496 MockFile('dir/junit/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:232497 MockFile('dir/junit/src/javadoc.java', [
2498 '/** Use FooForTest(); to obtain foo in tests.'
2499 ' */'
2500 ]),
2501 MockFile('dir/junit/src/javadoc2.java', [
2502 '/** ',
2503 ' * Use FooForTest(); to obtain foo in tests.'
2504 ' */'
2505 ]),
2506 ]
2507
2508 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctionsJava(
2509 mock_input_api, MockOutputApi())
2510 self.assertEqual(0, len(results))
2511
2512
Mohamed Heikald048240a2019-11-12 16:57:372513class NewImagesWarningTest(unittest.TestCase):
2514 def testTruePositives(self):
2515 mock_input_api = MockInputApi()
2516 mock_input_api.files = [
2517 MockFile('dir/android/res/drawable/foo.png', []),
2518 MockFile('dir/android/res/drawable-v21/bar.svg', []),
2519 MockFile('dir/android/res/mipmap-v21-en/baz.webp', []),
2520 MockFile('dir/android/res_gshoe/drawable-mdpi/foobar.png', []),
2521 ]
2522
2523 results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
2524 self.assertEqual(1, len(results))
2525 self.assertEqual(4, len(results[0].items))
2526 self.assertTrue('foo.png' in results[0].items[0].LocalPath())
2527 self.assertTrue('bar.svg' in results[0].items[1].LocalPath())
2528 self.assertTrue('baz.webp' in results[0].items[2].LocalPath())
2529 self.assertTrue('foobar.png' in results[0].items[3].LocalPath())
2530
2531 def testFalsePositives(self):
2532 mock_input_api = MockInputApi()
2533 mock_input_api.files = [
2534 MockFile('dir/pngs/README.md', []),
2535 MockFile('java/test/res/drawable/foo.png', []),
2536 MockFile('third_party/blink/foo.png', []),
2537 MockFile('dir/third_party/libpng/src/foo.cc', ['foobar']),
2538 MockFile('dir/resources.webp/.gitignore', ['foo.png']),
2539 ]
2540
2541 results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
2542 self.assertEqual(0, len(results))
2543
2544
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272545class CheckUniquePtrTest(unittest.TestCase):
Vaclav Brozek851d9602018-04-04 16:13:052546 def testTruePositivesNullptr(self):
2547 mock_input_api = MockInputApi()
2548 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162549 MockFile('dir/baz.cc', ['std::unique_ptr<T>()']),
2550 MockFile('dir/baz-p.cc', ['std::unique_ptr<T<P>>()']),
Vaclav Brozek851d9602018-04-04 16:13:052551 ]
2552
2553 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
2554 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:162555 self.assertTrue('nullptr' in results[0].message)
Vaclav Brozek851d9602018-04-04 16:13:052556 self.assertEqual(2, len(results[0].items))
2557 self.assertTrue('baz.cc' in results[0].items[0])
2558 self.assertTrue('baz-p.cc' in results[0].items[1])
2559
2560 def testTruePositivesConstructor(self):
Vaclav Brozek52e18bf2018-04-03 07:05:242561 mock_input_api = MockInputApi()
2562 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162563 MockFile('dir/foo.cc', ['return std::unique_ptr<T>(foo);']),
2564 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T>(foo)']),
2565 MockFile('dir/mult.cc', [
Vaclav Brozek95face62018-04-04 14:15:112566 'return',
2567 ' std::unique_ptr<T>(barVeryVeryLongFooSoThatItWouldNotFitAbove);'
2568 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:162569 MockFile('dir/mult2.cc', [
Vaclav Brozek95face62018-04-04 14:15:112570 'barVeryVeryLongLongBaaaaaarSoThatTheLineLimitIsAlmostReached =',
2571 ' std::unique_ptr<T>(foo);'
2572 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:162573 MockFile('dir/mult3.cc', [
Vaclav Brozek95face62018-04-04 14:15:112574 'bar = std::unique_ptr<T>(',
2575 ' fooVeryVeryVeryLongStillGoingWellThisWillTakeAWhileFinallyThere);'
2576 ]),
Vaclav Brozekb7fadb692018-08-30 06:39:532577 MockFile('dir/multi_arg.cc', [
2578 'auto p = std::unique_ptr<std::pair<T, D>>(new std::pair(T, D));']),
Vaclav Brozek52e18bf2018-04-03 07:05:242579 ]
2580
2581 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
Vaclav Brozek851d9602018-04-04 16:13:052582 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:162583 self.assertTrue('std::make_unique' in results[0].message)
Vaclav Brozekb7fadb692018-08-30 06:39:532584 self.assertEqual(6, len(results[0].items))
Vaclav Brozek851d9602018-04-04 16:13:052585 self.assertTrue('foo.cc' in results[0].items[0])
2586 self.assertTrue('bar.mm' in results[0].items[1])
2587 self.assertTrue('mult.cc' in results[0].items[2])
2588 self.assertTrue('mult2.cc' in results[0].items[3])
2589 self.assertTrue('mult3.cc' in results[0].items[4])
Vaclav Brozekb7fadb692018-08-30 06:39:532590 self.assertTrue('multi_arg.cc' in results[0].items[5])
Vaclav Brozek52e18bf2018-04-03 07:05:242591
2592 def testFalsePositives(self):
2593 mock_input_api = MockInputApi()
2594 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162595 MockFile('dir/foo.cc', ['return std::unique_ptr<T[]>(foo);']),
2596 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T[]>(foo)']),
2597 MockFile('dir/file.cc', ['std::unique_ptr<T> p = Foo();']),
2598 MockFile('dir/baz.cc', [
Vaclav Brozek52e18bf2018-04-03 07:05:242599 'std::unique_ptr<T> result = std::make_unique<T>();'
2600 ]),
Vaclav Brozeka54c528b2018-04-06 19:23:552601 MockFile('dir/baz2.cc', [
2602 'std::unique_ptr<T> result = std::make_unique<T>('
2603 ]),
2604 MockFile('dir/nested.cc', ['set<std::unique_ptr<T>>();']),
2605 MockFile('dir/nested2.cc', ['map<U, std::unique_ptr<T>>();']),
Vaclav Brozekb7fadb692018-08-30 06:39:532606
2607 # Two-argument invocation of std::unique_ptr is exempt because there is
2608 # no equivalent using std::make_unique.
2609 MockFile('dir/multi_arg.cc', [
2610 'auto p = std::unique_ptr<T, D>(new T(), D());']),
Vaclav Brozek52e18bf2018-04-03 07:05:242611 ]
2612
2613 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
2614 self.assertEqual(0, len(results))
2615
Danil Chapovalov3518f362018-08-11 16:13:432616class CheckNoDirectIncludesHeadersWhichRedefineStrCat(unittest.TestCase):
2617 def testBlocksDirectIncludes(self):
2618 mock_input_api = MockInputApi()
2619 mock_input_api.files = [
2620 MockFile('dir/foo_win.cc', ['#include "shlwapi.h"']),
2621 MockFile('dir/bar.h', ['#include <propvarutil.h>']),
2622 MockFile('dir/baz.h', ['#include <atlbase.h>']),
2623 MockFile('dir/jumbo.h', ['#include "sphelper.h"']),
2624 ]
2625 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2626 self.assertEquals(1, len(results))
2627 self.assertEquals(4, len(results[0].items))
2628 self.assertTrue('StrCat' in results[0].message)
2629 self.assertTrue('foo_win.cc' in results[0].items[0])
2630 self.assertTrue('bar.h' in results[0].items[1])
2631 self.assertTrue('baz.h' in results[0].items[2])
2632 self.assertTrue('jumbo.h' in results[0].items[3])
2633
2634 def testAllowsToIncludeWrapper(self):
2635 mock_input_api = MockInputApi()
2636 mock_input_api.files = [
2637 MockFile('dir/baz_win.cc', ['#include "base/win/shlwapi.h"']),
2638 MockFile('dir/baz-win.h', ['#include "base/win/atl.h"']),
2639 ]
2640 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2641 self.assertEquals(0, len(results))
2642
2643 def testAllowsToCreateWrapper(self):
2644 mock_input_api = MockInputApi()
2645 mock_input_api.files = [
2646 MockFile('base/win/shlwapi.h', [
2647 '#include <shlwapi.h>',
2648 '#include "base/win/windows_defines.inc"']),
2649 ]
2650 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2651 self.assertEquals(0, len(results))
Vaclav Brozek52e18bf2018-04-03 07:05:242652
Mustafa Emre Acer51f2f742020-03-09 19:41:122653
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142654class TranslationScreenshotsTest(unittest.TestCase):
2655 # An empty grd file.
2656 OLD_GRD_CONTENTS = """<?xml version="1.0" encoding="UTF-8"?>
2657 <grit latest_public_release="1" current_release="1">
2658 <release seq="1">
2659 <messages></messages>
2660 </release>
2661 </grit>
2662 """.splitlines()
2663 # A grd file with a single message.
2664 NEW_GRD_CONTENTS1 = """<?xml version="1.0" encoding="UTF-8"?>
2665 <grit latest_public_release="1" current_release="1">
2666 <release seq="1">
2667 <messages>
2668 <message name="IDS_TEST1">
2669 Test string 1
2670 </message>
2671 </messages>
2672 </release>
2673 </grit>
2674 """.splitlines()
2675 # A grd file with two messages.
2676 NEW_GRD_CONTENTS2 = """<?xml version="1.0" encoding="UTF-8"?>
2677 <grit latest_public_release="1" current_release="1">
2678 <release seq="1">
2679 <messages>
2680 <message name="IDS_TEST1">
2681 Test string 1
2682 </message>
2683 <message name="IDS_TEST2">
2684 Test string 2
2685 </message>
2686 </messages>
2687 </release>
2688 </grit>
2689 """.splitlines()
2690
meacerff8a9b62019-12-10 19:43:582691 OLD_GRDP_CONTENTS = (
2692 '<?xml version="1.0" encoding="utf-8"?>',
2693 '<grit-part>',
2694 '</grit-part>'
2695 )
2696
2697 NEW_GRDP_CONTENTS1 = (
2698 '<?xml version="1.0" encoding="utf-8"?>',
2699 '<grit-part>',
2700 '<message name="IDS_PART_TEST1">',
2701 'Part string 1',
2702 '</message>',
2703 '</grit-part>')
2704
2705 NEW_GRDP_CONTENTS2 = (
2706 '<?xml version="1.0" encoding="utf-8"?>',
2707 '<grit-part>',
2708 '<message name="IDS_PART_TEST1">',
2709 'Part string 1',
2710 '</message>',
2711 '<message name="IDS_PART_TEST2">',
2712 'Part string 2',
2713 '</message>',
2714 '</grit-part>')
2715
Mustafa Emre Acerc8a012d2018-07-31 00:00:392716 DO_NOT_UPLOAD_PNG_MESSAGE = ('Do not include actual screenshots in the '
2717 'changelist. Run '
2718 'tools/translate/upload_screenshots.py to '
2719 'upload them instead:')
2720 GENERATE_SIGNATURES_MESSAGE = ('You are adding or modifying UI strings.\n'
2721 'To ensure the best translations, take '
2722 'screenshots of the relevant UI '
2723 '(https://g.co/chrome/translation) and add '
2724 'these files to your changelist:')
2725 REMOVE_SIGNATURES_MESSAGE = ('You removed strings associated with these '
2726 'files. Remove:')
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142727
2728 def makeInputApi(self, files):
2729 input_api = MockInputApi()
2730 input_api.files = files
meacere7be7532019-10-02 17:41:032731 # Override os_path.exists because the presubmit uses the actual
2732 # os.path.exists.
2733 input_api.CreateMockFileInPath(
2734 [x.LocalPath() for x in input_api.AffectedFiles(include_deletes=True)])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142735 return input_api
2736
meacerff8a9b62019-12-10 19:43:582737 """ CL modified and added messages, but didn't add any screenshots."""
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142738 def testNoScreenshots(self):
meacerff8a9b62019-12-10 19:43:582739 # No new strings (file contents same). Should not warn.
2740 input_api = self.makeInputApi([
2741 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS1,
2742 self.NEW_GRD_CONTENTS1, action='M'),
2743 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS1,
2744 self.NEW_GRDP_CONTENTS1, action='M')])
2745 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2746 MockOutputApi())
2747 self.assertEqual(0, len(warnings))
2748
2749 # Add two new strings. Should have two warnings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142750 input_api = self.makeInputApi([
2751 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
meacerff8a9b62019-12-10 19:43:582752 self.NEW_GRD_CONTENTS1, action='M'),
2753 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
2754 self.NEW_GRDP_CONTENTS1, action='M')])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142755 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2756 MockOutputApi())
2757 self.assertEqual(1, len(warnings))
2758 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012759 self.assertEqual([
meacerff8a9b62019-12-10 19:43:582760 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2761 os.path.join('test_grd', 'IDS_TEST2.png.sha1')],
2762 warnings[0].items)
Mustafa Emre Acer36eaad52019-11-12 23:03:342763
meacerff8a9b62019-12-10 19:43:582764 # Add four new strings. Should have four warnings.
Mustafa Emre Acerad8fb082019-11-19 04:24:212765 input_api = self.makeInputApi([
2766 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
meacerff8a9b62019-12-10 19:43:582767 self.OLD_GRD_CONTENTS, action='M'),
2768 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
2769 self.OLD_GRDP_CONTENTS, action='M')])
Mustafa Emre Acerad8fb082019-11-19 04:24:212770 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2771 MockOutputApi())
2772 self.assertEqual(1, len(warnings))
2773 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:582774 self.assertEqual([
2775 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2776 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2777 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2778 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2779 ], warnings[0].items)
Mustafa Emre Acerad8fb082019-11-19 04:24:212780
meacerff8a9b62019-12-10 19:43:582781 def testPngAddedSha1NotAdded(self):
2782 # CL added one new message in a grd file and added the png file associated
2783 # with it, but did not add the corresponding sha1 file. This should warn
2784 # twice:
2785 # - Once for the added png file (because we don't want developers to upload
2786 # actual images)
2787 # - Once for the missing .sha1 file
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142788 input_api = self.makeInputApi([
Mustafa Emre Acerea3e57a2018-12-17 23:51:012789 MockAffectedFile(
2790 'test.grd',
2791 self.NEW_GRD_CONTENTS1,
2792 self.OLD_GRD_CONTENTS,
2793 action='M'),
2794 MockAffectedFile(
2795 os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A')
2796 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142797 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2798 MockOutputApi())
2799 self.assertEqual(2, len(warnings))
2800 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012801 self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png')],
2802 warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142803 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012804 self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
2805 warnings[1].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142806
meacerff8a9b62019-12-10 19:43:582807 # CL added two messages (one in grd, one in grdp) and added the png files
2808 # associated with the messages, but did not add the corresponding sha1
2809 # files. This should warn twice:
2810 # - Once for the added png files (because we don't want developers to upload
2811 # actual images)
2812 # - Once for the missing .sha1 files
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142813 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:582814 # Modified files:
Mustafa Emre Acer36eaad52019-11-12 23:03:342815 MockAffectedFile(
2816 'test.grd',
meacerff8a9b62019-12-10 19:43:582817 self.NEW_GRD_CONTENTS1,
Mustafa Emre Acer36eaad52019-11-12 23:03:342818 self.OLD_GRD_CONTENTS,
meacer2308d0742019-11-12 18:15:422819 action='M'),
Mustafa Emre Acer12e7fee2019-11-18 18:49:552820 MockAffectedFile(
meacerff8a9b62019-12-10 19:43:582821 'part.grdp',
2822 self.NEW_GRDP_CONTENTS1,
2823 self.OLD_GRDP_CONTENTS,
2824 action='M'),
2825 # Added files:
2826 MockAffectedFile(
2827 os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A'),
2828 MockAffectedFile(
2829 os.path.join('part_grdp', 'IDS_PART_TEST1.png'), 'binary',
2830 action='A')
Mustafa Emre Acerad8fb082019-11-19 04:24:212831 ])
2832 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2833 MockOutputApi())
2834 self.assertEqual(2, len(warnings))
2835 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:582836 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png'),
2837 os.path.join('test_grd', 'IDS_TEST1.png')],
Mustafa Emre Acerad8fb082019-11-19 04:24:212838 warnings[0].items)
2839 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
meacerff8a9b62019-12-10 19:43:582840 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2841 os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
2842 warnings[1].items)
Mustafa Emre Acerad8fb082019-11-19 04:24:212843
2844 def testScreenshotsWithSha1(self):
meacerff8a9b62019-12-10 19:43:582845 # CL added four messages (two each in a grd and grdp) and their
2846 # corresponding .sha1 files. No warnings.
Mustafa Emre Acerad8fb082019-11-19 04:24:212847 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:582848 # Modified files:
Mustafa Emre Acerad8fb082019-11-19 04:24:212849 MockAffectedFile(
2850 'test.grd',
2851 self.NEW_GRD_CONTENTS2,
2852 self.OLD_GRD_CONTENTS,
Mustafa Emre Acer12e7fee2019-11-18 18:49:552853 action='M'),
meacerff8a9b62019-12-10 19:43:582854 MockAffectedFile(
2855 'part.grdp',
2856 self.NEW_GRDP_CONTENTS2,
2857 self.OLD_GRDP_CONTENTS,
2858 action='M'),
2859 # Added files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012860 MockFile(
2861 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2862 'binary',
2863 action='A'),
2864 MockFile(
2865 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2866 'binary',
meacerff8a9b62019-12-10 19:43:582867 action='A'),
2868 MockFile(
2869 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2870 'binary',
2871 action='A'),
2872 MockFile(
2873 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2874 'binary',
2875 action='A'),
Mustafa Emre Acerea3e57a2018-12-17 23:51:012876 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142877 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2878 MockOutputApi())
2879 self.assertEqual([], warnings)
2880
2881 def testScreenshotsRemovedWithSha1(self):
meacerff8a9b62019-12-10 19:43:582882 # Replace new contents with old contents in grd and grp files, removing
2883 # IDS_TEST1, IDS_TEST2, IDS_PART_TEST1 and IDS_PART_TEST2.
2884 # Should warn to remove the sha1 files associated with these strings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142885 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:582886 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012887 MockAffectedFile(
2888 'test.grd',
meacerff8a9b62019-12-10 19:43:582889 self.OLD_GRD_CONTENTS, # new_contents
2890 self.NEW_GRD_CONTENTS2, # old_contents
Mustafa Emre Acerea3e57a2018-12-17 23:51:012891 action='M'),
meacerff8a9b62019-12-10 19:43:582892 MockAffectedFile(
2893 'part.grdp',
2894 self.OLD_GRDP_CONTENTS, # new_contents
2895 self.NEW_GRDP_CONTENTS2, # old_contents
2896 action='M'),
2897 # Unmodified files:
2898 MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
2899 MockFile(os.path.join('test_grd', 'IDS_TEST2.png.sha1'), 'binary', ''),
2900 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2901 'binary', ''),
2902 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2903 'binary', '')
Mustafa Emre Acerea3e57a2018-12-17 23:51:012904 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142905 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2906 MockOutputApi())
2907 self.assertEqual(1, len(warnings))
2908 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012909 self.assertEqual([
meacerff8a9b62019-12-10 19:43:582910 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2911 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
Mustafa Emre Acerea3e57a2018-12-17 23:51:012912 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2913 os.path.join('test_grd', 'IDS_TEST2.png.sha1')
2914 ], warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142915
meacerff8a9b62019-12-10 19:43:582916 # Same as above, but this time one of the .sha1 files is also removed.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142917 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:582918 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012919 MockAffectedFile(
2920 'test.grd',
meacerff8a9b62019-12-10 19:43:582921 self.OLD_GRD_CONTENTS, # new_contents
2922 self.NEW_GRD_CONTENTS2, # old_contents
Mustafa Emre Acerea3e57a2018-12-17 23:51:012923 action='M'),
meacerff8a9b62019-12-10 19:43:582924 MockAffectedFile(
2925 'part.grdp',
2926 self.OLD_GRDP_CONTENTS, # new_contents
2927 self.NEW_GRDP_CONTENTS2, # old_contents
2928 action='M'),
2929 # Unmodified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012930 MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
meacerff8a9b62019-12-10 19:43:582931 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2932 'binary', ''),
2933 # Deleted files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012934 MockAffectedFile(
2935 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2936 '',
2937 'old_contents',
meacerff8a9b62019-12-10 19:43:582938 action='D'),
2939 MockAffectedFile(
2940 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2941 '',
2942 'old_contents',
Mustafa Emre Acerea3e57a2018-12-17 23:51:012943 action='D')
2944 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142945 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2946 MockOutputApi())
2947 self.assertEqual(1, len(warnings))
2948 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
meacerff8a9b62019-12-10 19:43:582949 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2950 os.path.join('test_grd', 'IDS_TEST1.png.sha1')
2951 ], warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142952
meacerff8a9b62019-12-10 19:43:582953 # Remove all sha1 files. There should be no warnings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142954 input_api = self.makeInputApi([
meacerff8a9b62019-12-10 19:43:582955 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012956 MockAffectedFile(
2957 'test.grd',
2958 self.OLD_GRD_CONTENTS,
2959 self.NEW_GRD_CONTENTS2,
2960 action='M'),
meacerff8a9b62019-12-10 19:43:582961 MockAffectedFile(
2962 'part.grdp',
2963 self.OLD_GRDP_CONTENTS,
2964 self.NEW_GRDP_CONTENTS2,
2965 action='M'),
2966 # Deleted files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012967 MockFile(
2968 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2969 'binary',
2970 action='D'),
2971 MockFile(
2972 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2973 'binary',
meacerff8a9b62019-12-10 19:43:582974 action='D'),
2975 MockFile(
2976 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2977 'binary',
2978 action='D'),
2979 MockFile(
2980 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2981 'binary',
Mustafa Emre Acerea3e57a2018-12-17 23:51:012982 action='D')
2983 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142984 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2985 MockOutputApi())
2986 self.assertEqual([], warnings)
2987
2988
Mustafa Emre Acer51f2f742020-03-09 19:41:122989class TranslationExpectationsTest(unittest.TestCase):
2990 ERROR_MESSAGE_FORMAT = (
2991 "Failed to get a list of translatable grd files. "
2992 "This happens when:\n"
2993 " - One of the modified grd or grdp files cannot be parsed or\n"
2994 " - %s is not updated.\n"
2995 "Stack:\n"
2996 )
2997 REPO_ROOT = os.path.join('tools', 'translation', 'testdata')
2998 # This lists all .grd files under REPO_ROOT.
2999 EXPECTATIONS = os.path.join(REPO_ROOT,
3000 "translation_expectations.pyl")
3001 # This lists all .grd files under REPO_ROOT except unlisted.grd.
3002 EXPECTATIONS_WITHOUT_UNLISTED_FILE = os.path.join(
3003 REPO_ROOT, "translation_expectations_without_unlisted_file.pyl")
3004
3005 # Tests that the presubmit doesn't return when no grd or grdp files are
3006 # modified.
3007 def testExpectationsNoModifiedGrd(self):
3008 input_api = MockInputApi()
3009 input_api.files = [
3010 MockAffectedFile('not_used.txt', 'not used', 'not used', action='M')
3011 ]
3012 # Fake list of all grd files in the repo. This list is missing all grd/grdps
3013 # under tools/translation/testdata. This is OK because the presubmit won't
3014 # run in the first place since there are no modified grd/grps in input_api.
3015 grd_files = ['doesnt_exist_doesnt_matter.grd']
3016 warnings = PRESUBMIT._CheckTranslationExpectations(
3017 input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
3018 grd_files)
3019 self.assertEqual(0, len(warnings))
3020
3021
3022 # Tests that the list of files passed to the presubmit matches the list of
3023 # files in the expectations.
3024 def testExpectationsSuccess(self):
3025 # Mock input file list needs a grd or grdp file in order to run the
3026 # presubmit. The file itself doesn't matter.
3027 input_api = MockInputApi()
3028 input_api.files = [
3029 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3030 ]
3031 # List of all grd files in the repo.
3032 grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
3033 'internal.grd']
3034 warnings = PRESUBMIT._CheckTranslationExpectations(
3035 input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
3036 grd_files)
3037 self.assertEqual(0, len(warnings))
3038
3039 # Tests that the presubmit warns when a file is listed in expectations, but
3040 # does not actually exist.
3041 def testExpectationsMissingFile(self):
3042 # Mock input file list needs a grd or grdp file in order to run the
3043 # presubmit.
3044 input_api = MockInputApi()
3045 input_api.files = [
3046 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3047 ]
3048 # unlisted.grd is listed under tools/translation/testdata but is not
3049 # included in translation expectations.
3050 grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
3051 warnings = PRESUBMIT._CheckTranslationExpectations(
3052 input_api, MockOutputApi(), self.REPO_ROOT, self.EXPECTATIONS,
3053 grd_files)
3054 self.assertEqual(1, len(warnings))
3055 self.assertTrue(warnings[0].message.startswith(
3056 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS))
3057 self.assertTrue(
3058 ("test.grd is listed in the translation expectations, "
3059 "but this grd file does not exist")
3060 in warnings[0].message)
3061
3062 # Tests that the presubmit warns when a file is not listed in expectations but
3063 # does actually exist.
3064 def testExpectationsUnlistedFile(self):
3065 # Mock input file list needs a grd or grdp file in order to run the
3066 # presubmit.
3067 input_api = MockInputApi()
3068 input_api.files = [
3069 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3070 ]
3071 # unlisted.grd is listed under tools/translation/testdata but is not
3072 # included in translation expectations.
3073 grd_files = ['test.grd', 'unlisted.grd', 'not_translated.grd',
3074 'internal.grd']
3075 warnings = PRESUBMIT._CheckTranslationExpectations(
3076 input_api, MockOutputApi(), self.REPO_ROOT,
3077 self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
3078 self.assertEqual(1, len(warnings))
3079 self.assertTrue(warnings[0].message.startswith(
3080 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
3081 self.assertTrue(
3082 ("unlisted.grd appears to be translatable "
3083 "(because it contains <file> or <message> elements), "
3084 "but is not listed in the translation expectations.")
3085 in warnings[0].message)
3086
3087 # Tests that the presubmit warns twice:
3088 # - for a non-existing file listed in expectations
3089 # - for an existing file not listed in expectations
3090 def testMultipleWarnings(self):
3091 # Mock input file list needs a grd or grdp file in order to run the
3092 # presubmit.
3093 input_api = MockInputApi()
3094 input_api.files = [
3095 MockAffectedFile('dummy.grd', 'not used', 'not used', action='M')
3096 ]
3097 # unlisted.grd is listed under tools/translation/testdata but is not
3098 # included in translation expectations.
3099 # test.grd is not listed under tools/translation/testdata but is included
3100 # in translation expectations.
3101 grd_files = ['unlisted.grd', 'not_translated.grd', 'internal.grd']
3102 warnings = PRESUBMIT._CheckTranslationExpectations(
3103 input_api, MockOutputApi(), self.REPO_ROOT,
3104 self.EXPECTATIONS_WITHOUT_UNLISTED_FILE, grd_files)
3105 self.assertEqual(1, len(warnings))
3106 self.assertTrue(warnings[0].message.startswith(
3107 self.ERROR_MESSAGE_FORMAT % self.EXPECTATIONS_WITHOUT_UNLISTED_FILE))
3108 self.assertTrue(
3109 ("unlisted.grd appears to be translatable "
3110 "(because it contains <file> or <message> elements), "
3111 "but is not listed in the translation expectations.")
3112 in warnings[0].message)
3113 self.assertTrue(
3114 ("test.grd is listed in the translation expectations, "
3115 "but this grd file does not exist")
3116 in warnings[0].message)
3117
3118
Dominic Battre033531052018-09-24 15:45:343119class DISABLETypoInTest(unittest.TestCase):
3120
3121 def testPositive(self):
3122 # Verify the typo "DISABLE_" instead of "DISABLED_" in various contexts
3123 # where the desire is to disable a test.
3124 tests = [
3125 # Disabled on one platform:
3126 '#if defined(OS_WIN)\n'
3127 '#define MAYBE_FoobarTest DISABLE_FoobarTest\n'
3128 '#else\n'
3129 '#define MAYBE_FoobarTest FoobarTest\n'
3130 '#endif\n',
3131 # Disabled on one platform spread cross lines:
3132 '#if defined(OS_WIN)\n'
3133 '#define MAYBE_FoobarTest \\\n'
3134 ' DISABLE_FoobarTest\n'
3135 '#else\n'
3136 '#define MAYBE_FoobarTest FoobarTest\n'
3137 '#endif\n',
3138 # Disabled on all platforms:
3139 ' TEST_F(FoobarTest, DISABLE_Foo)\n{\n}',
3140 # Disabled on all platforms but multiple lines
3141 ' TEST_F(FoobarTest,\n DISABLE_foo){\n}\n',
3142 ]
3143
3144 for test in tests:
3145 mock_input_api = MockInputApi()
3146 mock_input_api.files = [
3147 MockFile('some/path/foo_unittest.cc', test.splitlines()),
3148 ]
3149
3150 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
3151 MockOutputApi())
3152 self.assertEqual(
3153 1,
3154 len(results),
3155 msg=('expected len(results) == 1 but got %d in test: %s' %
3156 (len(results), test)))
3157 self.assertTrue(
3158 'foo_unittest.cc' in results[0].message,
3159 msg=('expected foo_unittest.cc in message but got %s in test %s' %
3160 (results[0].message, test)))
3161
3162 def testIngoreNotTestFiles(self):
3163 mock_input_api = MockInputApi()
3164 mock_input_api.files = [
3165 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, DISABLE_Foo)'),
3166 ]
3167
3168 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
3169 MockOutputApi())
3170 self.assertEqual(0, len(results))
3171
Katie Df13948e2018-09-25 07:33:443172 def testIngoreDeletedFiles(self):
3173 mock_input_api = MockInputApi()
3174 mock_input_api.files = [
3175 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, Foo)', action='D'),
3176 ]
3177
3178 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
3179 MockOutputApi())
3180 self.assertEqual(0, len(results))
Dominic Battre033531052018-09-24 15:45:343181
Dirk Pranke3c18a382019-03-15 01:07:513182
3183class BuildtoolsRevisionsAreInSyncTest(unittest.TestCase):
3184 # TODO(crbug.com/941824): We need to make sure the entries in
3185 # //buildtools/DEPS are kept in sync with the entries in //DEPS
3186 # so that users of //buildtools in other projects get the same tooling
3187 # Chromium gets. If we ever fix the referenced bug and add 'includedeps'
3188 # support to gclient, we can eliminate the duplication and delete
3189 # these tests for the corresponding presubmit check.
3190
3191 def _check(self, files):
3192 mock_input_api = MockInputApi()
3193 mock_input_api.files = []
3194 for fname, contents in files.items():
3195 mock_input_api.files.append(MockFile(fname, contents.splitlines()))
3196 return PRESUBMIT._CheckBuildtoolsRevisionsAreInSync(mock_input_api,
3197 MockOutputApi())
3198
3199 def testOneFileChangedButNotTheOther(self):
3200 results = self._check({
3201 "DEPS": "'libunwind_revision': 'onerev'",
3202 })
3203 self.assertNotEqual(results, [])
3204
3205 def testNeitherFileChanged(self):
3206 results = self._check({
3207 "OWNERS": "[email protected]",
3208 })
3209 self.assertEqual(results, [])
3210
3211 def testBothFilesChangedAndMatch(self):
3212 results = self._check({
3213 "DEPS": "'libunwind_revision': 'onerev'",
3214 "buildtools/DEPS": "'libunwind_revision': 'onerev'",
3215 })
3216 self.assertEqual(results, [])
3217
3218 def testBothFilesWereChangedAndDontMatch(self):
3219 results = self._check({
3220 "DEPS": "'libunwind_revision': 'onerev'",
3221 "buildtools/DEPS": "'libunwind_revision': 'anotherrev'",
3222 })
3223 self.assertNotEqual(results, [])
3224
3225
Max Morozb47503b2019-08-08 21:03:273226class CheckFuzzTargetsTest(unittest.TestCase):
3227
3228 def _check(self, files):
3229 mock_input_api = MockInputApi()
3230 mock_input_api.files = []
3231 for fname, contents in files.items():
3232 mock_input_api.files.append(MockFile(fname, contents.splitlines()))
3233 return PRESUBMIT._CheckFuzzTargets(mock_input_api, MockOutputApi())
3234
3235 def testLibFuzzerSourcesIgnored(self):
3236 results = self._check({
3237 "third_party/lib/Fuzzer/FuzzerDriver.cpp": "LLVMFuzzerInitialize",
3238 })
3239 self.assertEqual(results, [])
3240
3241 def testNonCodeFilesIgnored(self):
3242 results = self._check({
3243 "README.md": "LLVMFuzzerInitialize",
3244 })
3245 self.assertEqual(results, [])
3246
3247 def testNoErrorHeaderPresent(self):
3248 results = self._check({
3249 "fuzzer.cc": (
3250 "#include \"testing/libfuzzer/libfuzzer_exports.h\"\n" +
3251 "LLVMFuzzerInitialize"
3252 )
3253 })
3254 self.assertEqual(results, [])
3255
3256 def testErrorMissingHeader(self):
3257 results = self._check({
3258 "fuzzer.cc": "LLVMFuzzerInitialize"
3259 })
3260 self.assertEqual(len(results), 1)
3261 self.assertEqual(results[0].items, ['fuzzer.cc'])
3262
3263
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:263264class SetNoParentTest(unittest.TestCase):
3265 def testSetNoParentMissing(self):
3266 mock_input_api = MockInputApi()
3267 mock_input_api.files = [
3268 MockAffectedFile('goat/OWNERS',
3269 [
3270 'set noparent',
3271 '[email protected]',
3272 'per-file *.json=set noparent',
3273 'per-file *[email protected]',
3274 ])
3275 ]
3276 mock_output_api = MockOutputApi()
3277 errors = PRESUBMIT._CheckSetNoParent(mock_input_api, mock_output_api)
3278 self.assertEqual(1, len(errors))
3279 self.assertTrue('goat/OWNERS:1' in errors[0].long_text)
3280 self.assertTrue('goat/OWNERS:3' in errors[0].long_text)
3281
3282
3283 def testSetNoParentWithCorrectRule(self):
3284 mock_input_api = MockInputApi()
3285 mock_input_api.files = [
3286 MockAffectedFile('goat/OWNERS',
3287 [
3288 'set noparent',
3289 'file://ipc/SECURITY_OWNERS',
3290 'per-file *.json=set noparent',
3291 'per-file *.json=file://ipc/SECURITY_OWNERS',
3292 ])
3293 ]
3294 mock_output_api = MockOutputApi()
3295 errors = PRESUBMIT._CheckSetNoParent(mock_input_api, mock_output_api)
3296 self.assertEqual([], errors)
3297
3298
[email protected]2299dcf2012-11-15 19:56:243299if __name__ == '__main__':
3300 unittest.main()