blob: 711de2cc545963fa0501dc2baeef308372a36800 [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
[email protected]f32e2d1e2013-07-26 21:39:08315class CheckAddedDepsHaveTetsApprovalsTest(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
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391025
yolandyan45001472016-12-21 21:12:421026class AndroidDeprecatedTestAnnotationTest(unittest.TestCase):
1027 def testCheckAndroidTestAnnotationUsage(self):
1028 mock_input_api = MockInputApi()
1029 mock_output_api = MockOutputApi()
1030
1031 mock_input_api.files = [
1032 MockAffectedFile('LalaLand.java', [
1033 'random stuff'
1034 ]),
1035 MockAffectedFile('CorrectUsage.java', [
1036 'import android.support.test.filters.LargeTest;',
1037 'import android.support.test.filters.MediumTest;',
1038 'import android.support.test.filters.SmallTest;',
1039 ]),
1040 MockAffectedFile('UsedDeprecatedLargeTestAnnotation.java', [
1041 'import android.test.suitebuilder.annotation.LargeTest;',
1042 ]),
1043 MockAffectedFile('UsedDeprecatedMediumTestAnnotation.java', [
1044 'import android.test.suitebuilder.annotation.MediumTest;',
1045 ]),
1046 MockAffectedFile('UsedDeprecatedSmallTestAnnotation.java', [
1047 'import android.test.suitebuilder.annotation.SmallTest;',
1048 ]),
1049 MockAffectedFile('UsedDeprecatedSmokeAnnotation.java', [
1050 'import android.test.suitebuilder.annotation.Smoke;',
1051 ])
1052 ]
1053 msgs = PRESUBMIT._CheckAndroidTestAnnotationUsage(
1054 mock_input_api, mock_output_api)
1055 self.assertEqual(1, len(msgs),
1056 'Expected %d items, found %d: %s'
1057 % (1, len(msgs), msgs))
1058 self.assertEqual(4, len(msgs[0].items),
1059 'Expected %d items, found %d: %s'
1060 % (4, len(msgs[0].items), msgs[0].items))
1061 self.assertTrue('UsedDeprecatedLargeTestAnnotation.java:1' in msgs[0].items,
1062 'UsedDeprecatedLargeTestAnnotation not found in errors')
1063 self.assertTrue('UsedDeprecatedMediumTestAnnotation.java:1'
1064 in msgs[0].items,
1065 'UsedDeprecatedMediumTestAnnotation not found in errors')
1066 self.assertTrue('UsedDeprecatedSmallTestAnnotation.java:1' in msgs[0].items,
1067 'UsedDeprecatedSmallTestAnnotation not found in errors')
1068 self.assertTrue('UsedDeprecatedSmokeAnnotation.java:1' in msgs[0].items,
1069 'UsedDeprecatedSmokeAnnotation not found in errors')
1070
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391071
Yoland Yanb92fa522017-08-28 17:37:061072class AndroidDeprecatedJUnitFrameworkTest(unittest.TestCase):
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271073 def testCheckAndroidTestJUnitFramework(self):
Yoland Yanb92fa522017-08-28 17:37:061074 mock_input_api = MockInputApi()
1075 mock_output_api = MockOutputApi()
yolandyan45001472016-12-21 21:12:421076
Yoland Yanb92fa522017-08-28 17:37:061077 mock_input_api.files = [
1078 MockAffectedFile('LalaLand.java', [
1079 'random stuff'
1080 ]),
1081 MockAffectedFile('CorrectUsage.java', [
1082 'import org.junit.ABC',
1083 'import org.junit.XYZ;',
1084 ]),
1085 MockAffectedFile('UsedDeprecatedJUnit.java', [
1086 'import junit.framework.*;',
1087 ]),
1088 MockAffectedFile('UsedDeprecatedJUnitAssert.java', [
1089 'import junit.framework.Assert;',
1090 ]),
1091 ]
1092 msgs = PRESUBMIT._CheckAndroidTestJUnitFrameworkImport(
1093 mock_input_api, mock_output_api)
1094 self.assertEqual(1, len(msgs),
1095 'Expected %d items, found %d: %s'
1096 % (1, len(msgs), msgs))
1097 self.assertEqual(2, len(msgs[0].items),
1098 'Expected %d items, found %d: %s'
1099 % (2, len(msgs[0].items), msgs[0].items))
1100 self.assertTrue('UsedDeprecatedJUnit.java:1' in msgs[0].items,
1101 'UsedDeprecatedJUnit.java not found in errors')
1102 self.assertTrue('UsedDeprecatedJUnitAssert.java:1'
1103 in msgs[0].items,
1104 'UsedDeprecatedJUnitAssert not found in errors')
1105
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391106
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271107class AndroidJUnitBaseClassTest(unittest.TestCase):
1108 def testCheckAndroidTestJUnitBaseClass(self):
Yoland Yanb92fa522017-08-28 17:37:061109 mock_input_api = MockInputApi()
1110 mock_output_api = MockOutputApi()
1111
1112 mock_input_api.files = [
1113 MockAffectedFile('LalaLand.java', [
1114 'random stuff'
1115 ]),
1116 MockAffectedFile('CorrectTest.java', [
1117 '@RunWith(ABC.class);'
1118 'public class CorrectTest {',
1119 '}',
1120 ]),
1121 MockAffectedFile('HistoricallyIncorrectTest.java', [
1122 'public class Test extends BaseCaseA {',
1123 '}',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391124 ], old_contents=[
Yoland Yanb92fa522017-08-28 17:37:061125 'public class Test extends BaseCaseB {',
1126 '}',
1127 ]),
1128 MockAffectedFile('CorrectTestWithInterface.java', [
1129 '@RunWith(ABC.class);'
1130 'public class CorrectTest implement Interface {',
1131 '}',
1132 ]),
1133 MockAffectedFile('IncorrectTest.java', [
1134 'public class IncorrectTest extends TestCase {',
1135 '}',
1136 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241137 MockAffectedFile('IncorrectWithInterfaceTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061138 'public class Test implements X extends BaseClass {',
1139 '}',
1140 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241141 MockAffectedFile('IncorrectMultiLineTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061142 'public class Test implements X, Y, Z',
1143 ' extends TestBase {',
1144 '}',
1145 ]),
1146 ]
1147 msgs = PRESUBMIT._CheckAndroidTestJUnitInheritance(
1148 mock_input_api, mock_output_api)
1149 self.assertEqual(1, len(msgs),
1150 'Expected %d items, found %d: %s'
1151 % (1, len(msgs), msgs))
1152 self.assertEqual(3, len(msgs[0].items),
1153 'Expected %d items, found %d: %s'
1154 % (3, len(msgs[0].items), msgs[0].items))
1155 self.assertTrue('IncorrectTest.java:1' in msgs[0].items,
1156 'IncorrectTest not found in errors')
Vaclav Brozekf01ed502018-03-16 19:38:241157 self.assertTrue('IncorrectWithInterfaceTest.java:1'
Yoland Yanb92fa522017-08-28 17:37:061158 in msgs[0].items,
Vaclav Brozekf01ed502018-03-16 19:38:241159 'IncorrectWithInterfaceTest not found in errors')
1160 self.assertTrue('IncorrectMultiLineTest.java:2' in msgs[0].items,
1161 'IncorrectMultiLineTest not found in errors')
yolandyan45001472016-12-21 21:12:421162
Jinsong Fan91ebbbd2019-04-16 14:57:171163class AndroidDebuggableBuildTest(unittest.TestCase):
1164
1165 def testCheckAndroidDebuggableBuild(self):
1166 mock_input_api = MockInputApi()
1167 mock_output_api = MockOutputApi()
1168
1169 mock_input_api.files = [
1170 MockAffectedFile('RandomStuff.java', [
1171 'random stuff'
1172 ]),
1173 MockAffectedFile('CorrectUsage.java', [
1174 'import org.chromium.base.BuildInfo;',
1175 'some random stuff',
1176 'boolean isOsDebuggable = BuildInfo.isDebugAndroid();',
1177 ]),
1178 MockAffectedFile('JustCheckUserdebugBuild.java', [
1179 'import android.os.Build;',
1180 'some random stuff',
1181 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")',
1182 ]),
1183 MockAffectedFile('JustCheckEngineeringBuild.java', [
1184 'import android.os.Build;',
1185 'some random stuff',
1186 'boolean isOsDebuggable = "eng".equals(Build.TYPE)',
1187 ]),
1188 MockAffectedFile('UsedBuildType.java', [
1189 'import android.os.Build;',
1190 'some random stuff',
1191 'boolean isOsDebuggable = Build.TYPE.equals("userdebug")'
1192 '|| "eng".equals(Build.TYPE)',
1193 ]),
1194 MockAffectedFile('UsedExplicitBuildType.java', [
1195 'some random stuff',
1196 'boolean isOsDebuggable = android.os.Build.TYPE.equals("userdebug")'
1197 '|| "eng".equals(android.os.Build.TYPE)',
1198 ]),
1199 ]
1200
1201 msgs = PRESUBMIT._CheckAndroidDebuggableBuild(
1202 mock_input_api, mock_output_api)
1203 self.assertEqual(1, len(msgs),
1204 'Expected %d items, found %d: %s'
1205 % (1, len(msgs), msgs))
1206 self.assertEqual(4, len(msgs[0].items),
1207 'Expected %d items, found %d: %s'
1208 % (4, len(msgs[0].items), msgs[0].items))
1209 self.assertTrue('JustCheckUserdebugBuild.java:3' in msgs[0].items)
1210 self.assertTrue('JustCheckEngineeringBuild.java:3' in msgs[0].items)
1211 self.assertTrue('UsedBuildType.java:3' in msgs[0].items)
1212 self.assertTrue('UsedExplicitBuildType.java:2' in msgs[0].items)
1213
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391214
dgn4401aa52015-04-29 16:26:171215class LogUsageTest(unittest.TestCase):
1216
dgnaa68d5e2015-06-10 10:08:221217 def testCheckAndroidCrLogUsage(self):
1218 mock_input_api = MockInputApi()
1219 mock_output_api = MockOutputApi()
1220
1221 mock_input_api.files = [
1222 MockAffectedFile('RandomStuff.java', [
1223 'random stuff'
1224 ]),
dgn87d9fb62015-06-12 09:15:121225 MockAffectedFile('HasAndroidLog.java', [
1226 'import android.util.Log;',
1227 'some random stuff',
1228 'Log.d("TAG", "foo");',
1229 ]),
1230 MockAffectedFile('HasExplicitUtilLog.java', [
1231 'some random stuff',
1232 'android.util.Log.d("TAG", "foo");',
1233 ]),
1234 MockAffectedFile('IsInBasePackage.java', [
1235 'package org.chromium.base;',
dgn38736db2015-09-18 19:20:511236 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121237 'Log.d(TAG, "foo");',
1238 ]),
1239 MockAffectedFile('IsInBasePackageButImportsLog.java', [
1240 'package org.chromium.base;',
1241 'import android.util.Log;',
dgn38736db2015-09-18 19:20:511242 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121243 'Log.d(TAG, "foo");',
1244 ]),
1245 MockAffectedFile('HasBothLog.java', [
1246 'import org.chromium.base.Log;',
1247 'some random stuff',
dgn38736db2015-09-18 19:20:511248 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121249 'Log.d(TAG, "foo");',
1250 'android.util.Log.d("TAG", "foo");',
1251 ]),
dgnaa68d5e2015-06-10 10:08:221252 MockAffectedFile('HasCorrectTag.java', [
1253 'import org.chromium.base.Log;',
1254 'some random stuff',
dgn38736db2015-09-18 19:20:511255 'private static final String TAG = "cr_Foo";',
1256 'Log.d(TAG, "foo");',
1257 ]),
1258 MockAffectedFile('HasOldTag.java', [
1259 'import org.chromium.base.Log;',
1260 'some random stuff',
dgnaa68d5e2015-06-10 10:08:221261 'private static final String TAG = "cr.Foo";',
1262 'Log.d(TAG, "foo");',
1263 ]),
dgn38736db2015-09-18 19:20:511264 MockAffectedFile('HasDottedTag.java', [
dgnaa68d5e2015-06-10 10:08:221265 'import org.chromium.base.Log;',
1266 'some random stuff',
dgn38736db2015-09-18 19:20:511267 'private static final String TAG = "cr_foo.bar";',
dgnaa68d5e2015-06-10 10:08:221268 'Log.d(TAG, "foo");',
1269 ]),
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461270 MockAffectedFile('HasDottedTagPublic.java', [
1271 'import org.chromium.base.Log;',
1272 'some random stuff',
1273 'public static final String TAG = "cr_foo.bar";',
1274 'Log.d(TAG, "foo");',
1275 ]),
dgnaa68d5e2015-06-10 10:08:221276 MockAffectedFile('HasNoTagDecl.java', [
1277 'import org.chromium.base.Log;',
1278 'some random stuff',
1279 'Log.d(TAG, "foo");',
1280 ]),
1281 MockAffectedFile('HasIncorrectTagDecl.java', [
1282 'import org.chromium.base.Log;',
dgn38736db2015-09-18 19:20:511283 'private static final String TAHG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221284 'some random stuff',
1285 'Log.d(TAG, "foo");',
1286 ]),
1287 MockAffectedFile('HasInlineTag.java', [
1288 'import org.chromium.base.Log;',
1289 'some random stuff',
dgn38736db2015-09-18 19:20:511290 'private static final String TAG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221291 'Log.d("TAG", "foo");',
1292 ]),
dgn38736db2015-09-18 19:20:511293 MockAffectedFile('HasUnprefixedTag.java', [
dgnaa68d5e2015-06-10 10:08:221294 'import org.chromium.base.Log;',
1295 'some random stuff',
1296 'private static final String TAG = "rubbish";',
1297 'Log.d(TAG, "foo");',
1298 ]),
1299 MockAffectedFile('HasTooLongTag.java', [
1300 'import org.chromium.base.Log;',
1301 'some random stuff',
dgn38736db2015-09-18 19:20:511302 'private static final String TAG = "21_charachers_long___";',
dgnaa68d5e2015-06-10 10:08:221303 'Log.d(TAG, "foo");',
1304 ]),
1305 ]
1306
1307 msgs = PRESUBMIT._CheckAndroidCrLogUsage(
1308 mock_input_api, mock_output_api)
1309
dgn38736db2015-09-18 19:20:511310 self.assertEqual(5, len(msgs),
1311 'Expected %d items, found %d: %s' % (5, len(msgs), msgs))
dgnaa68d5e2015-06-10 10:08:221312
1313 # Declaration format
dgn38736db2015-09-18 19:20:511314 nb = len(msgs[0].items)
1315 self.assertEqual(2, nb,
1316 'Expected %d items, found %d: %s' % (2, nb, msgs[0].items))
dgnaa68d5e2015-06-10 10:08:221317 self.assertTrue('HasNoTagDecl.java' in msgs[0].items)
1318 self.assertTrue('HasIncorrectTagDecl.java' in msgs[0].items)
dgnaa68d5e2015-06-10 10:08:221319
1320 # Tag length
dgn38736db2015-09-18 19:20:511321 nb = len(msgs[1].items)
1322 self.assertEqual(1, nb,
1323 'Expected %d items, found %d: %s' % (1, nb, msgs[1].items))
dgnaa68d5e2015-06-10 10:08:221324 self.assertTrue('HasTooLongTag.java' in msgs[1].items)
1325
1326 # Tag must be a variable named TAG
dgn38736db2015-09-18 19:20:511327 nb = len(msgs[2].items)
1328 self.assertEqual(1, nb,
1329 'Expected %d items, found %d: %s' % (1, nb, msgs[2].items))
dgnaa68d5e2015-06-10 10:08:221330 self.assertTrue('HasInlineTag.java:4' in msgs[2].items)
1331
dgn87d9fb62015-06-12 09:15:121332 # Util Log usage
dgn38736db2015-09-18 19:20:511333 nb = len(msgs[3].items)
1334 self.assertEqual(2, nb,
1335 'Expected %d items, found %d: %s' % (2, nb, msgs[3].items))
dgn87d9fb62015-06-12 09:15:121336 self.assertTrue('HasAndroidLog.java:3' in msgs[3].items)
1337 self.assertTrue('IsInBasePackageButImportsLog.java:4' in msgs[3].items)
dgnaa68d5e2015-06-10 10:08:221338
dgn38736db2015-09-18 19:20:511339 # Tag must not contain
1340 nb = len(msgs[4].items)
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461341 self.assertEqual(3, nb,
dgn38736db2015-09-18 19:20:511342 'Expected %d items, found %d: %s' % (2, nb, msgs[4].items))
1343 self.assertTrue('HasDottedTag.java' in msgs[4].items)
Torne (Richard Coles)3bd7ad02019-10-22 21:20:461344 self.assertTrue('HasDottedTagPublic.java' in msgs[4].items)
dgn38736db2015-09-18 19:20:511345 self.assertTrue('HasOldTag.java' in msgs[4].items)
1346
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391347
estadee17314a02017-01-12 16:22:161348class GoogleAnswerUrlFormatTest(unittest.TestCase):
1349
1350 def testCatchAnswerUrlId(self):
1351 input_api = MockInputApi()
1352 input_api.files = [
1353 MockFile('somewhere/file.cc',
1354 ['char* host = '
1355 ' "https://support.google.com/chrome/answer/123456";']),
1356 MockFile('somewhere_else/file.cc',
1357 ['char* host = '
1358 ' "https://support.google.com/chrome/a/answer/123456";']),
1359 ]
1360
1361 warnings = PRESUBMIT._CheckGoogleSupportAnswerUrl(
1362 input_api, MockOutputApi())
1363 self.assertEqual(1, len(warnings))
1364 self.assertEqual(2, len(warnings[0].items))
1365
1366 def testAllowAnswerUrlParam(self):
1367 input_api = MockInputApi()
1368 input_api.files = [
1369 MockFile('somewhere/file.cc',
1370 ['char* host = '
1371 ' "https://support.google.com/chrome/?p=cpn_crash_reports";']),
1372 ]
1373
1374 warnings = PRESUBMIT._CheckGoogleSupportAnswerUrl(
1375 input_api, MockOutputApi())
1376 self.assertEqual(0, len(warnings))
1377
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391378
reillyi38965732015-11-16 18:27:331379class HardcodedGoogleHostsTest(unittest.TestCase):
1380
1381 def testWarnOnAssignedLiterals(self):
1382 input_api = MockInputApi()
1383 input_api.files = [
1384 MockFile('content/file.cc',
1385 ['char* host = "https://www.google.com";']),
1386 MockFile('content/file.cc',
1387 ['char* host = "https://www.googleapis.com";']),
1388 MockFile('content/file.cc',
1389 ['char* host = "https://clients1.google.com";']),
1390 ]
1391
1392 warnings = PRESUBMIT._CheckHardcodedGoogleHostsInLowerLayers(
1393 input_api, MockOutputApi())
1394 self.assertEqual(1, len(warnings))
1395 self.assertEqual(3, len(warnings[0].items))
1396
1397 def testAllowInComment(self):
1398 input_api = MockInputApi()
1399 input_api.files = [
1400 MockFile('content/file.cc',
1401 ['char* host = "https://www.aol.com"; // google.com'])
1402 ]
1403
1404 warnings = PRESUBMIT._CheckHardcodedGoogleHostsInLowerLayers(
1405 input_api, MockOutputApi())
1406 self.assertEqual(0, len(warnings))
1407
dgn4401aa52015-04-29 16:26:171408
James Cook6b6597c2019-11-06 22:05:291409class ChromeOsSyncedPrefRegistrationTest(unittest.TestCase):
1410
1411 def testWarnsOnChromeOsDirectories(self):
1412 input_api = MockInputApi()
1413 input_api.files = [
1414 MockFile('ash/file.cc',
1415 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1416 MockFile('chrome/browser/chromeos/file.cc',
1417 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1418 MockFile('chromeos/file.cc',
1419 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1420 MockFile('components/arc/file.cc',
1421 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1422 MockFile('components/exo/file.cc',
1423 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1424 ]
1425 warnings = PRESUBMIT._CheckChromeOsSyncedPrefRegistration(
1426 input_api, MockOutputApi())
1427 self.assertEqual(1, len(warnings))
1428
1429 def testDoesNotWarnOnSyncOsPref(self):
1430 input_api = MockInputApi()
1431 input_api.files = [
1432 MockFile('chromeos/file.cc',
1433 ['PrefRegistrySyncable::SYNCABLE_OS_PREF']),
1434 ]
1435 warnings = PRESUBMIT._CheckChromeOsSyncedPrefRegistration(
1436 input_api, MockOutputApi())
1437 self.assertEqual(0, len(warnings))
1438
1439 def testDoesNotWarnOnCrossPlatformDirectories(self):
1440 input_api = MockInputApi()
1441 input_api.files = [
1442 MockFile('chrome/browser/ui/file.cc',
1443 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1444 MockFile('components/sync/file.cc',
1445 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1446 MockFile('content/browser/file.cc',
1447 ['PrefRegistrySyncable::SYNCABLE_PREF']),
1448 ]
1449 warnings = PRESUBMIT._CheckChromeOsSyncedPrefRegistration(
1450 input_api, MockOutputApi())
1451 self.assertEqual(0, len(warnings))
1452
1453 def testSeparateWarningForPriorityPrefs(self):
1454 input_api = MockInputApi()
1455 input_api.files = [
1456 MockFile('chromeos/file.cc',
1457 ['PrefRegistrySyncable::SYNCABLE_PREF',
1458 'PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF']),
1459 ]
1460 warnings = PRESUBMIT._CheckChromeOsSyncedPrefRegistration(
1461 input_api, MockOutputApi())
1462 self.assertEqual(2, len(warnings))
1463
1464
jbriance9e12f162016-11-25 07:57:501465class ForwardDeclarationTest(unittest.TestCase):
jbriance2c51e821a2016-12-12 08:24:311466 def testCheckHeadersOnlyOutsideThirdParty(self):
jbriance9e12f162016-11-25 07:57:501467 mock_input_api = MockInputApi()
1468 mock_input_api.files = [
1469 MockAffectedFile('somewhere/file.cc', [
1470 'class DummyClass;'
jbriance2c51e821a2016-12-12 08:24:311471 ]),
1472 MockAffectedFile('third_party/header.h', [
1473 'class DummyClass;'
jbriance9e12f162016-11-25 07:57:501474 ])
1475 ]
1476 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391477 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501478 self.assertEqual(0, len(warnings))
1479
1480 def testNoNestedDeclaration(self):
1481 mock_input_api = MockInputApi()
1482 mock_input_api.files = [
1483 MockAffectedFile('somewhere/header.h', [
jbriance2c51e821a2016-12-12 08:24:311484 'class SomeClass {',
1485 ' protected:',
1486 ' class NotAMatch;',
jbriance9e12f162016-11-25 07:57:501487 '};'
1488 ])
1489 ]
1490 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391491 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501492 self.assertEqual(0, len(warnings))
1493
1494 def testSubStrings(self):
1495 mock_input_api = MockInputApi()
1496 mock_input_api.files = [
1497 MockAffectedFile('somewhere/header.h', [
1498 'class NotUsefulClass;',
1499 'struct SomeStruct;',
1500 'UsefulClass *p1;',
1501 'SomeStructPtr *p2;'
1502 ])
1503 ]
1504 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391505 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501506 self.assertEqual(2, len(warnings))
1507
1508 def testUselessForwardDeclaration(self):
1509 mock_input_api = MockInputApi()
1510 mock_input_api.files = [
1511 MockAffectedFile('somewhere/header.h', [
1512 'class DummyClass;',
1513 'struct DummyStruct;',
1514 'class UsefulClass;',
1515 'std::unique_ptr<UsefulClass> p;'
jbriance2c51e821a2016-12-12 08:24:311516 ])
jbriance9e12f162016-11-25 07:57:501517 ]
1518 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391519 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501520 self.assertEqual(2, len(warnings))
1521
jbriance2c51e821a2016-12-12 08:24:311522 def testBlinkHeaders(self):
1523 mock_input_api = MockInputApi()
1524 mock_input_api.files = [
Kent Tamura32dbbcb2018-11-30 12:28:491525 MockAffectedFile('third_party/blink/header.h', [
jbriance2c51e821a2016-12-12 08:24:311526 'class DummyClass;',
1527 'struct DummyStruct;',
1528 ]),
Kent Tamura32dbbcb2018-11-30 12:28:491529 MockAffectedFile('third_party\\blink\\header.h', [
jbriance2c51e821a2016-12-12 08:24:311530 'class DummyClass;',
1531 'struct DummyStruct;',
1532 ])
1533 ]
1534 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391535 MockOutputApi())
jbriance2c51e821a2016-12-12 08:24:311536 self.assertEqual(4, len(warnings))
1537
jbriance9e12f162016-11-25 07:57:501538
rlanday6802cf632017-05-30 17:48:361539class RelativeIncludesTest(unittest.TestCase):
1540 def testThirdPartyNotWebKitIgnored(self):
1541 mock_input_api = MockInputApi()
1542 mock_input_api.files = [
1543 MockAffectedFile('third_party/test.cpp', '#include "../header.h"'),
1544 MockAffectedFile('third_party/test/test.cpp', '#include "../header.h"'),
1545 ]
1546
1547 mock_output_api = MockOutputApi()
1548
1549 errors = PRESUBMIT._CheckForRelativeIncludes(
1550 mock_input_api, mock_output_api)
1551 self.assertEqual(0, len(errors))
1552
1553 def testNonCppFileIgnored(self):
1554 mock_input_api = MockInputApi()
1555 mock_input_api.files = [
1556 MockAffectedFile('test.py', '#include "../header.h"'),
1557 ]
1558
1559 mock_output_api = MockOutputApi()
1560
1561 errors = PRESUBMIT._CheckForRelativeIncludes(
1562 mock_input_api, mock_output_api)
1563 self.assertEqual(0, len(errors))
1564
1565 def testInnocuousChangesAllowed(self):
1566 mock_input_api = MockInputApi()
1567 mock_input_api.files = [
1568 MockAffectedFile('test.cpp', '#include "header.h"'),
1569 MockAffectedFile('test2.cpp', '../'),
1570 ]
1571
1572 mock_output_api = MockOutputApi()
1573
1574 errors = PRESUBMIT._CheckForRelativeIncludes(
1575 mock_input_api, mock_output_api)
1576 self.assertEqual(0, len(errors))
1577
1578 def testRelativeIncludeNonWebKitProducesError(self):
1579 mock_input_api = MockInputApi()
1580 mock_input_api.files = [
1581 MockAffectedFile('test.cpp', ['#include "../header.h"']),
1582 ]
1583
1584 mock_output_api = MockOutputApi()
1585
1586 errors = PRESUBMIT._CheckForRelativeIncludes(
1587 mock_input_api, mock_output_api)
1588 self.assertEqual(1, len(errors))
1589
1590 def testRelativeIncludeWebKitProducesError(self):
1591 mock_input_api = MockInputApi()
1592 mock_input_api.files = [
Kent Tamura32dbbcb2018-11-30 12:28:491593 MockAffectedFile('third_party/blink/test.cpp',
rlanday6802cf632017-05-30 17:48:361594 ['#include "../header.h']),
1595 ]
1596
1597 mock_output_api = MockOutputApi()
1598
1599 errors = PRESUBMIT._CheckForRelativeIncludes(
1600 mock_input_api, mock_output_api)
1601 self.assertEqual(1, len(errors))
dbeam1ec68ac2016-12-15 05:22:241602
Daniel Cheng13ca61a882017-08-25 15:11:251603
Daniel Bratell65b033262019-04-23 08:17:061604class CCIncludeTest(unittest.TestCase):
1605 def testThirdPartyNotBlinkIgnored(self):
1606 mock_input_api = MockInputApi()
1607 mock_input_api.files = [
1608 MockAffectedFile('third_party/test.cpp', '#include "file.cc"'),
1609 ]
1610
1611 mock_output_api = MockOutputApi()
1612
1613 errors = PRESUBMIT._CheckForCcIncludes(
1614 mock_input_api, mock_output_api)
1615 self.assertEqual(0, len(errors))
1616
1617 def testPythonFileIgnored(self):
1618 mock_input_api = MockInputApi()
1619 mock_input_api.files = [
1620 MockAffectedFile('test.py', '#include "file.cc"'),
1621 ]
1622
1623 mock_output_api = MockOutputApi()
1624
1625 errors = PRESUBMIT._CheckForCcIncludes(
1626 mock_input_api, mock_output_api)
1627 self.assertEqual(0, len(errors))
1628
1629 def testIncFilesAccepted(self):
1630 mock_input_api = MockInputApi()
1631 mock_input_api.files = [
1632 MockAffectedFile('test.py', '#include "file.inc"'),
1633 ]
1634
1635 mock_output_api = MockOutputApi()
1636
1637 errors = PRESUBMIT._CheckForCcIncludes(
1638 mock_input_api, mock_output_api)
1639 self.assertEqual(0, len(errors))
1640
1641 def testInnocuousChangesAllowed(self):
1642 mock_input_api = MockInputApi()
1643 mock_input_api.files = [
1644 MockAffectedFile('test.cpp', '#include "header.h"'),
1645 MockAffectedFile('test2.cpp', 'Something "file.cc"'),
1646 ]
1647
1648 mock_output_api = MockOutputApi()
1649
1650 errors = PRESUBMIT._CheckForCcIncludes(
1651 mock_input_api, mock_output_api)
1652 self.assertEqual(0, len(errors))
1653
1654 def testCcIncludeNonBlinkProducesError(self):
1655 mock_input_api = MockInputApi()
1656 mock_input_api.files = [
1657 MockAffectedFile('test.cpp', ['#include "file.cc"']),
1658 ]
1659
1660 mock_output_api = MockOutputApi()
1661
1662 errors = PRESUBMIT._CheckForCcIncludes(
1663 mock_input_api, mock_output_api)
1664 self.assertEqual(1, len(errors))
1665
1666 def testCppIncludeBlinkProducesError(self):
1667 mock_input_api = MockInputApi()
1668 mock_input_api.files = [
1669 MockAffectedFile('third_party/blink/test.cpp',
1670 ['#include "foo/file.cpp"']),
1671 ]
1672
1673 mock_output_api = MockOutputApi()
1674
1675 errors = PRESUBMIT._CheckForCcIncludes(
1676 mock_input_api, mock_output_api)
1677 self.assertEqual(1, len(errors))
1678
1679
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191680class NewHeaderWithoutGnChangeTest(unittest.TestCase):
1681 def testAddHeaderWithoutGn(self):
1682 mock_input_api = MockInputApi()
1683 mock_input_api.files = [
1684 MockAffectedFile('base/stuff.h', ''),
1685 ]
1686 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1687 mock_input_api, MockOutputApi())
1688 self.assertEqual(1, len(warnings))
1689 self.assertTrue('base/stuff.h' in warnings[0].items)
1690
1691 def testModifyHeader(self):
1692 mock_input_api = MockInputApi()
1693 mock_input_api.files = [
1694 MockAffectedFile('base/stuff.h', '', action='M'),
1695 ]
1696 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1697 mock_input_api, MockOutputApi())
1698 self.assertEqual(0, len(warnings))
1699
1700 def testDeleteHeader(self):
1701 mock_input_api = MockInputApi()
1702 mock_input_api.files = [
1703 MockAffectedFile('base/stuff.h', '', action='D'),
1704 ]
1705 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1706 mock_input_api, MockOutputApi())
1707 self.assertEqual(0, len(warnings))
1708
1709 def testAddHeaderWithGn(self):
1710 mock_input_api = MockInputApi()
1711 mock_input_api.files = [
1712 MockAffectedFile('base/stuff.h', ''),
1713 MockAffectedFile('base/BUILD.gn', 'stuff.h'),
1714 ]
1715 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1716 mock_input_api, MockOutputApi())
1717 self.assertEqual(0, len(warnings))
1718
1719 def testAddHeaderWithGni(self):
1720 mock_input_api = MockInputApi()
1721 mock_input_api.files = [
1722 MockAffectedFile('base/stuff.h', ''),
1723 MockAffectedFile('base/files.gni', 'stuff.h'),
1724 ]
1725 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1726 mock_input_api, MockOutputApi())
1727 self.assertEqual(0, len(warnings))
1728
1729 def testAddHeaderWithOther(self):
1730 mock_input_api = MockInputApi()
1731 mock_input_api.files = [
1732 MockAffectedFile('base/stuff.h', ''),
1733 MockAffectedFile('base/stuff.cc', 'stuff.h'),
1734 ]
1735 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1736 mock_input_api, MockOutputApi())
1737 self.assertEqual(1, len(warnings))
1738
1739 def testAddHeaderWithWrongGn(self):
1740 mock_input_api = MockInputApi()
1741 mock_input_api.files = [
1742 MockAffectedFile('base/stuff.h', ''),
1743 MockAffectedFile('base/BUILD.gn', 'stuff_h'),
1744 ]
1745 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1746 mock_input_api, MockOutputApi())
1747 self.assertEqual(1, len(warnings))
1748
1749 def testAddHeadersWithGn(self):
1750 mock_input_api = MockInputApi()
1751 mock_input_api.files = [
1752 MockAffectedFile('base/stuff.h', ''),
1753 MockAffectedFile('base/another.h', ''),
1754 MockAffectedFile('base/BUILD.gn', 'another.h\nstuff.h'),
1755 ]
1756 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1757 mock_input_api, MockOutputApi())
1758 self.assertEqual(0, len(warnings))
1759
1760 def testAddHeadersWithWrongGn(self):
1761 mock_input_api = MockInputApi()
1762 mock_input_api.files = [
1763 MockAffectedFile('base/stuff.h', ''),
1764 MockAffectedFile('base/another.h', ''),
1765 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff.h'),
1766 ]
1767 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1768 mock_input_api, MockOutputApi())
1769 self.assertEqual(1, len(warnings))
1770 self.assertFalse('base/stuff.h' in warnings[0].items)
1771 self.assertTrue('base/another.h' in warnings[0].items)
1772
1773 def testAddHeadersWithWrongGn2(self):
1774 mock_input_api = MockInputApi()
1775 mock_input_api.files = [
1776 MockAffectedFile('base/stuff.h', ''),
1777 MockAffectedFile('base/another.h', ''),
1778 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff_h'),
1779 ]
1780 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1781 mock_input_api, MockOutputApi())
1782 self.assertEqual(1, len(warnings))
1783 self.assertTrue('base/stuff.h' in warnings[0].items)
1784 self.assertTrue('base/another.h' in warnings[0].items)
1785
1786
Michael Giuffridad3bc8672018-10-25 22:48:021787class CorrectProductNameInMessagesTest(unittest.TestCase):
1788 def testProductNameInDesc(self):
1789 mock_input_api = MockInputApi()
1790 mock_input_api.files = [
1791 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
1792 '<message name="Foo" desc="Welcome to Chrome">',
1793 ' Welcome to Chrome!',
1794 '</message>',
1795 ]),
1796 MockAffectedFile('chrome/app/chromium_strings.grd', [
1797 '<message name="Bar" desc="Welcome to Chrome">',
1798 ' Welcome to Chromium!',
1799 '</message>',
1800 ]),
1801 ]
1802 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1803 mock_input_api, MockOutputApi())
1804 self.assertEqual(0, len(warnings))
1805
1806 def testChromeInChromium(self):
1807 mock_input_api = MockInputApi()
1808 mock_input_api.files = [
1809 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
1810 '<message name="Foo" desc="Welcome to Chrome">',
1811 ' Welcome to Chrome!',
1812 '</message>',
1813 ]),
1814 MockAffectedFile('chrome/app/chromium_strings.grd', [
1815 '<message name="Bar" desc="Welcome to Chrome">',
1816 ' Welcome to Chrome!',
1817 '</message>',
1818 ]),
1819 ]
1820 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1821 mock_input_api, MockOutputApi())
1822 self.assertEqual(1, len(warnings))
1823 self.assertTrue('chrome/app/chromium_strings.grd' in warnings[0].items[0])
1824
1825 def testChromiumInChrome(self):
1826 mock_input_api = MockInputApi()
1827 mock_input_api.files = [
1828 MockAffectedFile('chrome/app/google_chrome_strings.grd', [
1829 '<message name="Foo" desc="Welcome to Chrome">',
1830 ' Welcome to Chromium!',
1831 '</message>',
1832 ]),
1833 MockAffectedFile('chrome/app/chromium_strings.grd', [
1834 '<message name="Bar" desc="Welcome to Chrome">',
1835 ' Welcome to Chromium!',
1836 '</message>',
1837 ]),
1838 ]
1839 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1840 mock_input_api, MockOutputApi())
1841 self.assertEqual(1, len(warnings))
1842 self.assertTrue(
1843 'chrome/app/google_chrome_strings.grd:2' in warnings[0].items[0])
1844
1845 def testMultipleInstances(self):
1846 mock_input_api = MockInputApi()
1847 mock_input_api.files = [
1848 MockAffectedFile('chrome/app/chromium_strings.grd', [
1849 '<message name="Bar" desc="Welcome to Chrome">',
1850 ' Welcome to Chrome!',
1851 '</message>',
1852 '<message name="Baz" desc="A correct message">',
1853 ' Chromium is the software you are using.',
1854 '</message>',
1855 '<message name="Bat" desc="An incorrect message">',
1856 ' Google Chrome is the software you are using.',
1857 '</message>',
1858 ]),
1859 ]
1860 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1861 mock_input_api, MockOutputApi())
1862 self.assertEqual(1, len(warnings))
1863 self.assertTrue(
1864 'chrome/app/chromium_strings.grd:2' in warnings[0].items[0])
1865 self.assertTrue(
1866 'chrome/app/chromium_strings.grd:8' in warnings[0].items[1])
1867
1868 def testMultipleWarnings(self):
1869 mock_input_api = MockInputApi()
1870 mock_input_api.files = [
1871 MockAffectedFile('chrome/app/chromium_strings.grd', [
1872 '<message name="Bar" desc="Welcome to Chrome">',
1873 ' Welcome to Chrome!',
1874 '</message>',
1875 '<message name="Baz" desc="A correct message">',
1876 ' Chromium is the software you are using.',
1877 '</message>',
1878 '<message name="Bat" desc="An incorrect message">',
1879 ' Google Chrome is the software you are using.',
1880 '</message>',
1881 ]),
1882 MockAffectedFile('components/components_google_chrome_strings.grd', [
1883 '<message name="Bar" desc="Welcome to Chrome">',
1884 ' Welcome to Chrome!',
1885 '</message>',
1886 '<message name="Baz" desc="A correct message">',
1887 ' Chromium is the software you are using.',
1888 '</message>',
1889 '<message name="Bat" desc="An incorrect message">',
1890 ' Google Chrome is the software you are using.',
1891 '</message>',
1892 ]),
1893 ]
1894 warnings = PRESUBMIT._CheckCorrectProductNameInMessages(
1895 mock_input_api, MockOutputApi())
1896 self.assertEqual(2, len(warnings))
1897 self.assertTrue(
1898 'components/components_google_chrome_strings.grd:5'
1899 in warnings[0].items[0])
1900 self.assertTrue(
1901 'chrome/app/chromium_strings.grd:2' in warnings[1].items[0])
1902 self.assertTrue(
1903 'chrome/app/chromium_strings.grd:8' in warnings[1].items[1])
1904
1905
Ken Rockot9f668262018-12-21 18:56:361906class ServiceManifestOwnerTest(unittest.TestCase):
1907 def testServiceManifestJsonChangeNeedsSecurityOwner(self):
Daniel Cheng13ca61a882017-08-25 15:11:251908 mock_input_api = MockInputApi()
1909 mock_input_api.files = [
1910 MockAffectedFile('services/goat/manifest.json',
1911 [
1912 '{',
1913 ' "name": "teleporter",',
1914 ' "display_name": "Goat Teleporter",'
1915 ' "interface_provider_specs": {',
1916 ' }',
1917 '}',
1918 ])
1919 ]
1920 mock_output_api = MockOutputApi()
1921 errors = PRESUBMIT._CheckIpcOwners(
1922 mock_input_api, mock_output_api)
1923 self.assertEqual(1, len(errors))
1924 self.assertEqual(
1925 'Found OWNERS files that need to be updated for IPC security review ' +
1926 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
1927
1928 # No warning if already covered by an OWNERS rule.
1929
Ken Rockot9f668262018-12-21 18:56:361930 def testNonManifestJsonChangesDoNotRequireSecurityOwner(self):
Daniel Cheng13ca61a882017-08-25 15:11:251931 mock_input_api = MockInputApi()
1932 mock_input_api.files = [
1933 MockAffectedFile('services/goat/species.json',
1934 [
1935 '[',
1936 ' "anglo-nubian",',
1937 ' "angora"',
1938 ']',
1939 ])
1940 ]
1941 mock_output_api = MockOutputApi()
1942 errors = PRESUBMIT._CheckIpcOwners(
1943 mock_input_api, mock_output_api)
1944 self.assertEqual([], errors)
1945
Ken Rockot9f668262018-12-21 18:56:361946 def testServiceManifestChangeNeedsSecurityOwner(self):
1947 mock_input_api = MockInputApi()
1948 mock_input_api.files = [
1949 MockAffectedFile('services/goat/public/cpp/manifest.cc',
1950 [
1951 '#include "services/goat/public/cpp/manifest.h"',
1952 'const service_manager::Manifest& GetManifest() {}',
1953 ])]
1954 mock_output_api = MockOutputApi()
1955 errors = PRESUBMIT._CheckIpcOwners(
1956 mock_input_api, mock_output_api)
1957 self.assertEqual(1, len(errors))
1958 self.assertEqual(
1959 'Found OWNERS files that need to be updated for IPC security review ' +
1960 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
1961
1962 def testNonServiceManifestSourceChangesDoNotRequireSecurityOwner(self):
1963 mock_input_api = MockInputApi()
1964 mock_input_api.files = [
1965 MockAffectedFile('some/non/service/thing/foo_manifest.cc',
1966 [
1967 'const char kNoEnforcement[] = "not a manifest!";',
1968 ])]
1969 mock_output_api = MockOutputApi()
1970 errors = PRESUBMIT._CheckIpcOwners(
1971 mock_input_api, mock_output_api)
1972 self.assertEqual([], errors)
1973
Daniel Cheng13ca61a882017-08-25 15:11:251974
Mario Sanchez Prada2472cab2019-09-18 10:58:311975class BannedTypeCheckTest(unittest.TestCase):
Sylvain Defresnea8b73d252018-02-28 15:45:541976
Peter Kasting94a56c42019-10-25 21:54:041977 def testBannedCppFunctions(self):
1978 input_api = MockInputApi()
1979 input_api.files = [
1980 MockFile('some/cpp/problematic/file.cc',
1981 ['using namespace std;']),
1982 MockFile('some/cpp/ok/file.cc',
1983 ['using std::string;']),
1984 ]
1985
1986 errors = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
1987 self.assertEqual(1, len(errors))
1988 self.assertTrue('some/cpp/problematic/file.c' in errors[0].message)
1989 self.assertTrue('some/cpp/ok/file.cc' not in errors[0].message)
1990
Abhijeet Kandalkar1e7c2502019-10-29 15:05:451991 def testBannedBlinkDowncastHelpers(self):
1992 input_api = MockInputApi()
1993 input_api.files = [
1994 MockFile('some/cpp/problematic/file1.cc',
1995 ['DEFINE_TYPE_CASTS(ToType, FromType, from_argument,'
1996 'PointerPredicate(), ReferencePredicate());']),
1997 MockFile('some/cpp/problematic/file2.cc',
1998 ['bool is_test_ele = IsHTMLTestElement(n);']),
1999 MockFile('some/cpp/problematic/file3.cc',
2000 ['auto* html_test_ele = ToHTMLTestElement(n);']),
2001 MockFile('some/cpp/problematic/file4.cc',
2002 ['auto* html_test_ele_or_null = ToHTMLTestElementOrNull(n);']),
2003 MockFile('some/cpp/ok/file1.cc',
2004 ['bool is_test_ele = IsA<HTMLTestElement>(n);']),
2005 MockFile('some/cpp/ok/file2.cc',
2006 ['auto* html_test_ele = To<HTMLTestElement>(n);']),
2007 MockFile('some/cpp/ok/file3.cc',
2008 ['auto* html_test_ele_or_null = ',
2009 'DynamicTo<HTMLTestElement>(n);']),
2010 ]
2011
2012 # warnings are errors[0], errors are errors[1]
2013 errors = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
2014 self.assertEqual(2, len(errors))
2015 self.assertTrue('some/cpp/problematic/file1.cc' in errors[1].message)
2016 self.assertTrue('some/cpp/problematic/file2.cc' in errors[0].message)
2017 self.assertTrue('some/cpp/problematic/file3.cc' in errors[0].message)
2018 self.assertTrue('some/cpp/problematic/file4.cc' in errors[0].message)
2019 self.assertTrue('some/cpp/ok/file1.cc' not in errors[0].message)
2020 self.assertTrue('some/cpp/ok/file2.cc' not in errors[0].message)
2021 self.assertTrue('some/cpp/ok/file3.cc' not in errors[0].message)
2022
Peter K. Lee6c03ccff2019-07-15 14:40:052023 def testBannedIosObjcFunctions(self):
Sylvain Defresnea8b73d252018-02-28 15:45:542024 input_api = MockInputApi()
2025 input_api.files = [
2026 MockFile('some/ios/file.mm',
2027 ['TEST(SomeClassTest, SomeInteraction) {',
2028 '}']),
2029 MockFile('some/mac/file.mm',
2030 ['TEST(SomeClassTest, SomeInteraction) {',
2031 '}']),
2032 MockFile('another/ios_file.mm',
2033 ['class SomeTest : public testing::Test {};']),
Peter K. Lee6c03ccff2019-07-15 14:40:052034 MockFile('some/ios/file_egtest.mm',
2035 ['- (void)testSomething { EXPECT_OCMOCK_VERIFY(aMock); }']),
2036 MockFile('some/ios/file_unittest.mm',
2037 ['TEST_F(SomeTest, TestThis) { EXPECT_OCMOCK_VERIFY(aMock); }']),
Sylvain Defresnea8b73d252018-02-28 15:45:542038 ]
2039
2040 errors = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
2041 self.assertEqual(1, len(errors))
2042 self.assertTrue('some/ios/file.mm' in errors[0].message)
2043 self.assertTrue('another/ios_file.mm' in errors[0].message)
2044 self.assertTrue('some/mac/file.mm' not in errors[0].message)
Peter K. Lee6c03ccff2019-07-15 14:40:052045 self.assertTrue('some/ios/file_egtest.mm' in errors[0].message)
2046 self.assertTrue('some/ios/file_unittest.mm' not in errors[0].message)
Sylvain Defresnea8b73d252018-02-28 15:45:542047
Carlos Knippschildab192b8c2019-04-08 20:02:382048 def testBannedMojoFunctions(self):
2049 input_api = MockInputApi()
2050 input_api.files = [
2051 MockFile('some/cpp/problematic/file.cc',
2052 ['mojo::DataPipe();']),
Oksana Zhuravlovafd247772019-05-16 16:57:292053 MockFile('some/cpp/problematic/file2.cc',
2054 ['mojo::ConvertTo<>']),
Carlos Knippschildab192b8c2019-04-08 20:02:382055 MockFile('some/cpp/ok/file.cc',
2056 ['CreateDataPipe();']),
Kinuko Yasuda376c2ce12019-04-16 01:20:372057 MockFile('some/cpp/ok/file2.cc',
2058 ['mojo::DataPipeDrainer();']),
Oksana Zhuravlovafd247772019-05-16 16:57:292059 MockFile('third_party/blink/ok/file3.cc',
2060 ['mojo::ConvertTo<>']),
2061 MockFile('content/renderer/ok/file3.cc',
2062 ['mojo::ConvertTo<>']),
Carlos Knippschildab192b8c2019-04-08 20:02:382063 ]
2064
Oksana Zhuravlova1d3b59de2019-05-17 00:08:222065 results = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
2066
2067 # warnings are results[0], errors are results[1]
2068 self.assertEqual(2, len(results))
2069 self.assertTrue('some/cpp/problematic/file.cc' in results[1].message)
2070 self.assertTrue('some/cpp/problematic/file2.cc' in results[0].message)
2071 self.assertTrue('some/cpp/ok/file.cc' not in results[1].message)
2072 self.assertTrue('some/cpp/ok/file2.cc' not in results[1].message)
2073 self.assertTrue('third_party/blink/ok/file3.cc' not in results[0].message)
2074 self.assertTrue('content/renderer/ok/file3.cc' not in results[0].message)
Carlos Knippschildab192b8c2019-04-08 20:02:382075
Mario Sanchez Prada2472cab2019-09-18 10:58:312076 def testDeprecatedMojoTypes(self):
2077 ok_paths = ['some/cpp']
2078 warning_paths = ['third_party/blink']
2079 test_cases = [
2080 {
2081 'type': 'mojo::AssociatedBinding<>;',
2082 'file': 'file1.c'
2083 },
2084 {
2085 'type': 'mojo::AssociatedBindingSet<>;',
2086 'file': 'file2.c'
2087 },
2088 {
2089 'type': 'mojo::AssociatedInterfacePtr<>',
2090 'file': 'file3.cc'
2091 },
2092 {
2093 'type': 'mojo::AssociatedInterfacePtrInfo<>',
2094 'file': 'file4.cc'
2095 },
2096 {
2097 'type': 'mojo::AssociatedInterfaceRequest<>',
2098 'file': 'file5.cc'
2099 },
2100 {
2101 'type': 'mojo::Binding<>',
2102 'file': 'file6.cc'
2103 },
2104 {
2105 'type': 'mojo::BindingSet<>',
2106 'file': 'file7.cc'
2107 },
2108 {
2109 'type': 'mojo::InterfacePtr<>',
2110 'file': 'file8.cc'
2111 },
2112 {
2113 'type': 'mojo::InterfacePtrInfo<>',
2114 'file': 'file9.cc'
2115 },
2116 {
2117 'type': 'mojo::InterfaceRequest<>',
2118 'file': 'file10.cc'
2119 },
2120 {
2121 'type': 'mojo::MakeRequest()',
2122 'file': 'file11.cc'
2123 },
2124 {
2125 'type': 'mojo::MakeRequestAssociatedWithDedicatedPipe()',
2126 'file': 'file12.cc'
2127 },
2128 {
2129 'type': 'mojo::MakeStrongBinding()<>',
2130 'file': 'file13.cc'
2131 },
2132 {
2133 'type': 'mojo::MakeStrongAssociatedBinding()<>',
2134 'file': 'file14.cc'
2135 },
2136 {
2137 'type': 'mojo::StrongAssociatedBindingSet<>',
2138 'file': 'file15.cc'
2139 },
2140 {
2141 'type': 'mojo::StrongBindingSet<>',
2142 'file': 'file16.cc'
2143 },
2144 ]
2145
2146 # Build the list of MockFiles considering paths that should trigger warnings
2147 # as well as paths that should not trigger anything.
2148 input_api = MockInputApi()
2149 input_api.files = []
2150 for test_case in test_cases:
2151 for path in ok_paths:
2152 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2153 [test_case['type']]))
2154 for path in warning_paths:
2155 input_api.files.append(MockFile(os.path.join(path, test_case['file']),
2156 [test_case['type']]))
2157
2158 results = PRESUBMIT._CheckNoDeprecatedMojoTypes(input_api, MockOutputApi())
2159
2160 # Only warnings for now for all deprecated Mojo types.
2161 self.assertEqual(1, len(results))
2162
2163 for test_case in test_cases:
2164 # Check that no warnings or errors have been triggered for these paths.
2165 for path in ok_paths:
2166 self.assertFalse(path in results[0].message)
2167
2168 # Check warnings have been triggered for these paths.
2169 for path in warning_paths:
2170 self.assertTrue(path in results[0].message)
2171
Sylvain Defresnea8b73d252018-02-28 15:45:542172
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272173class NoProductionCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozekf01ed502018-03-16 19:38:242174 def testTruePositives(self):
2175 mock_input_api = MockInputApi()
2176 mock_input_api.files = [
2177 MockFile('some/path/foo.cc', ['foo_for_testing();']),
2178 MockFile('some/path/foo.mm', ['FooForTesting();']),
2179 MockFile('some/path/foo.cxx', ['FooForTests();']),
2180 MockFile('some/path/foo.cpp', ['foo_for_test();']),
2181 ]
2182
2183 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctions(
2184 mock_input_api, MockOutputApi())
2185 self.assertEqual(1, len(results))
2186 self.assertEqual(4, len(results[0].items))
2187 self.assertTrue('foo.cc' in results[0].items[0])
2188 self.assertTrue('foo.mm' in results[0].items[1])
2189 self.assertTrue('foo.cxx' in results[0].items[2])
2190 self.assertTrue('foo.cpp' in results[0].items[3])
2191
2192 def testFalsePositives(self):
2193 mock_input_api = MockInputApi()
2194 mock_input_api.files = [
2195 MockFile('some/path/foo.h', ['foo_for_testing();']),
2196 MockFile('some/path/foo.mm', ['FooForTesting() {']),
2197 MockFile('some/path/foo.cc', ['::FooForTests();']),
2198 MockFile('some/path/foo.cpp', ['// foo_for_test();']),
2199 ]
2200
2201 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctions(
2202 mock_input_api, MockOutputApi())
2203 self.assertEqual(0, len(results))
2204
2205
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272206class NoProductionJavaCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozek7dbc28c2018-03-27 08:35:232207 def testTruePositives(self):
2208 mock_input_api = MockInputApi()
2209 mock_input_api.files = [
2210 MockFile('dir/java/src/foo.java', ['FooForTesting();']),
2211 MockFile('dir/java/src/bar.java', ['FooForTests(x);']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392212 MockFile('dir/java/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:232213 MockFile('dir/java/src/mult.java', [
2214 'int x = SomethingLongHere()',
2215 ' * SomethingLongHereForTesting();'
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392216 ])
Vaclav Brozek7dbc28c2018-03-27 08:35:232217 ]
2218
2219 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctionsJava(
2220 mock_input_api, MockOutputApi())
2221 self.assertEqual(1, len(results))
2222 self.assertEqual(4, len(results[0].items))
2223 self.assertTrue('foo.java' in results[0].items[0])
2224 self.assertTrue('bar.java' in results[0].items[1])
2225 self.assertTrue('baz.java' in results[0].items[2])
2226 self.assertTrue('mult.java' in results[0].items[3])
2227
2228 def testFalsePositives(self):
2229 mock_input_api = MockInputApi()
2230 mock_input_api.files = [
2231 MockFile('dir/java/src/foo.xml', ['FooForTesting();']),
2232 MockFile('dir/java/src/foo.java', ['FooForTests() {']),
2233 MockFile('dir/java/src/bar.java', ['// FooForTest();']),
2234 MockFile('dir/java/src/bar2.java', ['x = 1; // FooForTest();']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:392235 MockFile('dir/javatests/src/baz.java', ['FooForTest(', 'y', ');']),
2236 MockFile('dir/junit/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:232237 MockFile('dir/junit/src/javadoc.java', [
2238 '/** Use FooForTest(); to obtain foo in tests.'
2239 ' */'
2240 ]),
2241 MockFile('dir/junit/src/javadoc2.java', [
2242 '/** ',
2243 ' * Use FooForTest(); to obtain foo in tests.'
2244 ' */'
2245 ]),
2246 ]
2247
2248 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctionsJava(
2249 mock_input_api, MockOutputApi())
2250 self.assertEqual(0, len(results))
2251
2252
Mohamed Heikald048240a2019-11-12 16:57:372253class NewImagesWarningTest(unittest.TestCase):
2254 def testTruePositives(self):
2255 mock_input_api = MockInputApi()
2256 mock_input_api.files = [
2257 MockFile('dir/android/res/drawable/foo.png', []),
2258 MockFile('dir/android/res/drawable-v21/bar.svg', []),
2259 MockFile('dir/android/res/mipmap-v21-en/baz.webp', []),
2260 MockFile('dir/android/res_gshoe/drawable-mdpi/foobar.png', []),
2261 ]
2262
2263 results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
2264 self.assertEqual(1, len(results))
2265 self.assertEqual(4, len(results[0].items))
2266 self.assertTrue('foo.png' in results[0].items[0].LocalPath())
2267 self.assertTrue('bar.svg' in results[0].items[1].LocalPath())
2268 self.assertTrue('baz.webp' in results[0].items[2].LocalPath())
2269 self.assertTrue('foobar.png' in results[0].items[3].LocalPath())
2270
2271 def testFalsePositives(self):
2272 mock_input_api = MockInputApi()
2273 mock_input_api.files = [
2274 MockFile('dir/pngs/README.md', []),
2275 MockFile('java/test/res/drawable/foo.png', []),
2276 MockFile('third_party/blink/foo.png', []),
2277 MockFile('dir/third_party/libpng/src/foo.cc', ['foobar']),
2278 MockFile('dir/resources.webp/.gitignore', ['foo.png']),
2279 ]
2280
2281 results = PRESUBMIT._CheckNewImagesWarning(mock_input_api, MockOutputApi())
2282 self.assertEqual(0, len(results))
2283
2284
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:272285class CheckUniquePtrTest(unittest.TestCase):
Vaclav Brozek851d9602018-04-04 16:13:052286 def testTruePositivesNullptr(self):
2287 mock_input_api = MockInputApi()
2288 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162289 MockFile('dir/baz.cc', ['std::unique_ptr<T>()']),
2290 MockFile('dir/baz-p.cc', ['std::unique_ptr<T<P>>()']),
Vaclav Brozek851d9602018-04-04 16:13:052291 ]
2292
2293 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
2294 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:162295 self.assertTrue('nullptr' in results[0].message)
Vaclav Brozek851d9602018-04-04 16:13:052296 self.assertEqual(2, len(results[0].items))
2297 self.assertTrue('baz.cc' in results[0].items[0])
2298 self.assertTrue('baz-p.cc' in results[0].items[1])
2299
2300 def testTruePositivesConstructor(self):
Vaclav Brozek52e18bf2018-04-03 07:05:242301 mock_input_api = MockInputApi()
2302 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162303 MockFile('dir/foo.cc', ['return std::unique_ptr<T>(foo);']),
2304 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T>(foo)']),
2305 MockFile('dir/mult.cc', [
Vaclav Brozek95face62018-04-04 14:15:112306 'return',
2307 ' std::unique_ptr<T>(barVeryVeryLongFooSoThatItWouldNotFitAbove);'
2308 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:162309 MockFile('dir/mult2.cc', [
Vaclav Brozek95face62018-04-04 14:15:112310 'barVeryVeryLongLongBaaaaaarSoThatTheLineLimitIsAlmostReached =',
2311 ' std::unique_ptr<T>(foo);'
2312 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:162313 MockFile('dir/mult3.cc', [
Vaclav Brozek95face62018-04-04 14:15:112314 'bar = std::unique_ptr<T>(',
2315 ' fooVeryVeryVeryLongStillGoingWellThisWillTakeAWhileFinallyThere);'
2316 ]),
Vaclav Brozekb7fadb692018-08-30 06:39:532317 MockFile('dir/multi_arg.cc', [
2318 'auto p = std::unique_ptr<std::pair<T, D>>(new std::pair(T, D));']),
Vaclav Brozek52e18bf2018-04-03 07:05:242319 ]
2320
2321 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
Vaclav Brozek851d9602018-04-04 16:13:052322 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:162323 self.assertTrue('std::make_unique' in results[0].message)
Vaclav Brozekb7fadb692018-08-30 06:39:532324 self.assertEqual(6, len(results[0].items))
Vaclav Brozek851d9602018-04-04 16:13:052325 self.assertTrue('foo.cc' in results[0].items[0])
2326 self.assertTrue('bar.mm' in results[0].items[1])
2327 self.assertTrue('mult.cc' in results[0].items[2])
2328 self.assertTrue('mult2.cc' in results[0].items[3])
2329 self.assertTrue('mult3.cc' in results[0].items[4])
Vaclav Brozekb7fadb692018-08-30 06:39:532330 self.assertTrue('multi_arg.cc' in results[0].items[5])
Vaclav Brozek52e18bf2018-04-03 07:05:242331
2332 def testFalsePositives(self):
2333 mock_input_api = MockInputApi()
2334 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:162335 MockFile('dir/foo.cc', ['return std::unique_ptr<T[]>(foo);']),
2336 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T[]>(foo)']),
2337 MockFile('dir/file.cc', ['std::unique_ptr<T> p = Foo();']),
2338 MockFile('dir/baz.cc', [
Vaclav Brozek52e18bf2018-04-03 07:05:242339 'std::unique_ptr<T> result = std::make_unique<T>();'
2340 ]),
Vaclav Brozeka54c528b2018-04-06 19:23:552341 MockFile('dir/baz2.cc', [
2342 'std::unique_ptr<T> result = std::make_unique<T>('
2343 ]),
2344 MockFile('dir/nested.cc', ['set<std::unique_ptr<T>>();']),
2345 MockFile('dir/nested2.cc', ['map<U, std::unique_ptr<T>>();']),
Vaclav Brozekb7fadb692018-08-30 06:39:532346
2347 # Two-argument invocation of std::unique_ptr is exempt because there is
2348 # no equivalent using std::make_unique.
2349 MockFile('dir/multi_arg.cc', [
2350 'auto p = std::unique_ptr<T, D>(new T(), D());']),
Vaclav Brozek52e18bf2018-04-03 07:05:242351 ]
2352
2353 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
2354 self.assertEqual(0, len(results))
2355
Danil Chapovalov3518f362018-08-11 16:13:432356class CheckNoDirectIncludesHeadersWhichRedefineStrCat(unittest.TestCase):
2357 def testBlocksDirectIncludes(self):
2358 mock_input_api = MockInputApi()
2359 mock_input_api.files = [
2360 MockFile('dir/foo_win.cc', ['#include "shlwapi.h"']),
2361 MockFile('dir/bar.h', ['#include <propvarutil.h>']),
2362 MockFile('dir/baz.h', ['#include <atlbase.h>']),
2363 MockFile('dir/jumbo.h', ['#include "sphelper.h"']),
2364 ]
2365 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2366 self.assertEquals(1, len(results))
2367 self.assertEquals(4, len(results[0].items))
2368 self.assertTrue('StrCat' in results[0].message)
2369 self.assertTrue('foo_win.cc' in results[0].items[0])
2370 self.assertTrue('bar.h' in results[0].items[1])
2371 self.assertTrue('baz.h' in results[0].items[2])
2372 self.assertTrue('jumbo.h' in results[0].items[3])
2373
2374 def testAllowsToIncludeWrapper(self):
2375 mock_input_api = MockInputApi()
2376 mock_input_api.files = [
2377 MockFile('dir/baz_win.cc', ['#include "base/win/shlwapi.h"']),
2378 MockFile('dir/baz-win.h', ['#include "base/win/atl.h"']),
2379 ]
2380 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2381 self.assertEquals(0, len(results))
2382
2383 def testAllowsToCreateWrapper(self):
2384 mock_input_api = MockInputApi()
2385 mock_input_api.files = [
2386 MockFile('base/win/shlwapi.h', [
2387 '#include <shlwapi.h>',
2388 '#include "base/win/windows_defines.inc"']),
2389 ]
2390 results = PRESUBMIT._CheckNoStrCatRedefines(mock_input_api, MockOutputApi())
2391 self.assertEquals(0, len(results))
Vaclav Brozek52e18bf2018-04-03 07:05:242392
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142393class TranslationScreenshotsTest(unittest.TestCase):
2394 # An empty grd file.
2395 OLD_GRD_CONTENTS = """<?xml version="1.0" encoding="UTF-8"?>
2396 <grit latest_public_release="1" current_release="1">
2397 <release seq="1">
2398 <messages></messages>
2399 </release>
2400 </grit>
2401 """.splitlines()
2402 # A grd file with a single message.
2403 NEW_GRD_CONTENTS1 = """<?xml version="1.0" encoding="UTF-8"?>
2404 <grit latest_public_release="1" current_release="1">
2405 <release seq="1">
2406 <messages>
2407 <message name="IDS_TEST1">
2408 Test string 1
2409 </message>
2410 </messages>
2411 </release>
2412 </grit>
2413 """.splitlines()
2414 # A grd file with two messages.
2415 NEW_GRD_CONTENTS2 = """<?xml version="1.0" encoding="UTF-8"?>
2416 <grit latest_public_release="1" current_release="1">
2417 <release seq="1">
2418 <messages>
2419 <message name="IDS_TEST1">
2420 Test string 1
2421 </message>
2422 <message name="IDS_TEST2">
2423 Test string 2
2424 </message>
2425 </messages>
2426 </release>
2427 </grit>
2428 """.splitlines()
2429
Mustafa Emre Acer12e7fee2019-11-18 18:49:552430 OLD_GRDP_CONTENTS = (
2431 '<?xml version="1.0" encoding="utf-8"?>',
2432 '<grit-part>',
2433 '</grit-part>'
2434 )
2435
2436 NEW_GRDP_CONTENTS1 = (
2437 '<?xml version="1.0" encoding="utf-8"?>',
2438 '<grit-part>',
2439 '<message name="IDS_PART_TEST1">',
2440 'Part string 1',
2441 '</message>',
2442 '</grit-part>')
2443
2444 NEW_GRDP_CONTENTS2 = (
2445 '<?xml version="1.0" encoding="utf-8"?>',
2446 '<grit-part>',
2447 '<message name="IDS_PART_TEST1">',
2448 'Part string 1',
2449 '</message>',
2450 '<message name="IDS_PART_TEST2">',
2451 'Part string 2',
2452 '</message>',
2453 '</grit-part>')
2454
Mustafa Emre Acerc8a012d2018-07-31 00:00:392455 DO_NOT_UPLOAD_PNG_MESSAGE = ('Do not include actual screenshots in the '
2456 'changelist. Run '
2457 'tools/translate/upload_screenshots.py to '
2458 'upload them instead:')
2459 GENERATE_SIGNATURES_MESSAGE = ('You are adding or modifying UI strings.\n'
2460 'To ensure the best translations, take '
2461 'screenshots of the relevant UI '
2462 '(https://g.co/chrome/translation) and add '
2463 'these files to your changelist:')
2464 REMOVE_SIGNATURES_MESSAGE = ('You removed strings associated with these '
2465 'files. Remove:')
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142466
2467 def makeInputApi(self, files):
2468 input_api = MockInputApi()
2469 input_api.files = files
meacere7be7532019-10-02 17:41:032470 # Override os_path.exists because the presubmit uses the actual
2471 # os.path.exists.
2472 input_api.CreateMockFileInPath(
2473 [x.LocalPath() for x in input_api.AffectedFiles(include_deletes=True)])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142474 return input_api
2475
Mustafa Emre Acer12e7fee2019-11-18 18:49:552476 """ CL modified and added messages, but didn't add any screenshots."""
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142477 def testNoScreenshots(self):
Mustafa Emre Acer12e7fee2019-11-18 18:49:552478 # No new strings (file contents same). Should not warn.
2479 input_api = self.makeInputApi([
2480 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS1,
2481 self.NEW_GRD_CONTENTS1, action='M'),
2482 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS1,
2483 self.NEW_GRDP_CONTENTS1, action='M')])
2484 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2485 MockOutputApi())
2486 self.assertEqual(0, len(warnings))
2487
2488 # Add two new strings. Should have two warnings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142489 input_api = self.makeInputApi([
2490 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
Mustafa Emre Acer12e7fee2019-11-18 18:49:552491 self.NEW_GRD_CONTENTS1, action='M'),
2492 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
2493 self.NEW_GRDP_CONTENTS1, action='M')])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142494 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2495 MockOutputApi())
2496 self.assertEqual(1, len(warnings))
2497 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012498 self.assertEqual([
Mustafa Emre Acer12e7fee2019-11-18 18:49:552499 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2500 os.path.join('test_grd', 'IDS_TEST2.png.sha1')],
2501 warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142502
Mustafa Emre Acer12e7fee2019-11-18 18:49:552503 # Add four new strings. Should have four warnings.
Mustafa Emre Acer36eaad52019-11-12 23:03:342504 input_api = self.makeInputApi([
2505 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
Mustafa Emre Acer12e7fee2019-11-18 18:49:552506 self.OLD_GRD_CONTENTS, action='M'),
2507 MockAffectedFile('part.grdp', self.NEW_GRDP_CONTENTS2,
2508 self.OLD_GRDP_CONTENTS, action='M')])
Mustafa Emre Acer36eaad52019-11-12 23:03:342509 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2510 MockOutputApi())
2511 self.assertEqual(1, len(warnings))
2512 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acer12e7fee2019-11-18 18:49:552513 self.assertEqual([
2514 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2515 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2516 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2517 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2518 ], warnings[0].items)
Mustafa Emre Acer36eaad52019-11-12 23:03:342519
Mustafa Emre Acer12e7fee2019-11-18 18:49:552520 def testPngAddedSha1NotAdded(self):
2521 # CL added one new message in a grd file and added the png file associated
2522 # with it, but did not add the corresponding sha1 file. This should warn
2523 # twice:
2524 # - Once for the added png file (because we don't want developers to upload
2525 # actual images)
2526 # - Once for the missing .sha1 file
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142527 input_api = self.makeInputApi([
Mustafa Emre Acerea3e57a2018-12-17 23:51:012528 MockAffectedFile(
2529 'test.grd',
2530 self.NEW_GRD_CONTENTS1,
2531 self.OLD_GRD_CONTENTS,
2532 action='M'),
2533 MockAffectedFile(
2534 os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A')
2535 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142536 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2537 MockOutputApi())
2538 self.assertEqual(2, len(warnings))
2539 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012540 self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png')],
2541 warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142542 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012543 self.assertEqual([os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
2544 warnings[1].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142545
Mustafa Emre Acer12e7fee2019-11-18 18:49:552546 # CL added two messages (one in grd, one in grdp) and added the png files
2547 # associated with the messages, but did not add the corresponding sha1
2548 # files. This should warn twice:
2549 # - Once for the added png files (because we don't want developers to upload
2550 # actual images)
2551 # - Once for the missing .sha1 files
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142552 input_api = self.makeInputApi([
Mustafa Emre Acer12e7fee2019-11-18 18:49:552553 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012554 MockAffectedFile(
2555 'test.grd',
Mustafa Emre Acer12e7fee2019-11-18 18:49:552556 self.NEW_GRD_CONTENTS1,
Mustafa Emre Acerea3e57a2018-12-17 23:51:012557 self.OLD_GRD_CONTENTS,
2558 action='M'),
meacer2308d0742019-11-12 18:15:422559 MockAffectedFile(
Mustafa Emre Acer12e7fee2019-11-18 18:49:552560 'part.grdp',
2561 self.NEW_GRDP_CONTENTS1,
2562 self.OLD_GRDP_CONTENTS,
2563 action='M'),
2564 # Added files:
2565 MockAffectedFile(
2566 os.path.join('test_grd', 'IDS_TEST1.png'), 'binary', action='A'),
2567 MockAffectedFile(
2568 os.path.join('part_grdp', 'IDS_PART_TEST1.png'), 'binary',
2569 action='A')
Mustafa Emre Acer36eaad52019-11-12 23:03:342570 ])
2571 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2572 MockOutputApi())
2573 self.assertEqual(2, len(warnings))
2574 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
Mustafa Emre Acer12e7fee2019-11-18 18:49:552575 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png'),
2576 os.path.join('test_grd', 'IDS_TEST1.png')],
Mustafa Emre Acer36eaad52019-11-12 23:03:342577 warnings[0].items)
2578 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
Mustafa Emre Acer12e7fee2019-11-18 18:49:552579 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2580 os.path.join('test_grd', 'IDS_TEST1.png.sha1')],
2581 warnings[1].items)
Mustafa Emre Acer36eaad52019-11-12 23:03:342582
2583 def testScreenshotsWithSha1(self):
Mustafa Emre Acer12e7fee2019-11-18 18:49:552584 # CL added four messages (two each in a grd and grdp) and their
2585 # corresponding .sha1 files. No warnings.
Mustafa Emre Acer36eaad52019-11-12 23:03:342586 input_api = self.makeInputApi([
Mustafa Emre Acer12e7fee2019-11-18 18:49:552587 # Modified files:
Mustafa Emre Acer36eaad52019-11-12 23:03:342588 MockAffectedFile(
2589 'test.grd',
2590 self.NEW_GRD_CONTENTS2,
2591 self.OLD_GRD_CONTENTS,
meacer2308d0742019-11-12 18:15:422592 action='M'),
Mustafa Emre Acer12e7fee2019-11-18 18:49:552593 MockAffectedFile(
2594 'part.grdp',
2595 self.NEW_GRDP_CONTENTS2,
2596 self.OLD_GRDP_CONTENTS,
2597 action='M'),
2598 # Added files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012599 MockFile(
2600 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2601 'binary',
2602 action='A'),
2603 MockFile(
2604 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2605 'binary',
Mustafa Emre Acer12e7fee2019-11-18 18:49:552606 action='A'),
2607 MockFile(
2608 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2609 'binary',
2610 action='A'),
2611 MockFile(
2612 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2613 'binary',
2614 action='A'),
Mustafa Emre Acerea3e57a2018-12-17 23:51:012615 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142616 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2617 MockOutputApi())
2618 self.assertEqual([], warnings)
2619
2620 def testScreenshotsRemovedWithSha1(self):
Mustafa Emre Acer12e7fee2019-11-18 18:49:552621 # Replace new contents with old contents in grd and grp files, removing
2622 # IDS_TEST1, IDS_TEST2, IDS_PART_TEST1 and IDS_PART_TEST2.
2623 # Should warn to remove the sha1 files associated with these strings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142624 input_api = self.makeInputApi([
Mustafa Emre Acer12e7fee2019-11-18 18:49:552625 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012626 MockAffectedFile(
2627 'test.grd',
Mustafa Emre Acer12e7fee2019-11-18 18:49:552628 self.OLD_GRD_CONTENTS, # new_contents
2629 self.NEW_GRD_CONTENTS2, # old_contents
Mustafa Emre Acerea3e57a2018-12-17 23:51:012630 action='M'),
Mustafa Emre Acer12e7fee2019-11-18 18:49:552631 MockAffectedFile(
2632 'part.grdp',
2633 self.OLD_GRDP_CONTENTS, # new_contents
2634 self.NEW_GRDP_CONTENTS2, # old_contents
2635 action='M'),
2636 # Unmodified files:
2637 MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
2638 MockFile(os.path.join('test_grd', 'IDS_TEST2.png.sha1'), 'binary', ''),
2639 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2640 'binary', ''),
2641 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2642 'binary', '')
Mustafa Emre Acerea3e57a2018-12-17 23:51:012643 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142644 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2645 MockOutputApi())
2646 self.assertEqual(1, len(warnings))
2647 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acerea3e57a2018-12-17 23:51:012648 self.assertEqual([
Mustafa Emre Acer12e7fee2019-11-18 18:49:552649 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2650 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
Mustafa Emre Acerea3e57a2018-12-17 23:51:012651 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2652 os.path.join('test_grd', 'IDS_TEST2.png.sha1')
2653 ], warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142654
Mustafa Emre Acer12e7fee2019-11-18 18:49:552655 # Same as above, but this time one of the .sha1 files is also removed.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142656 input_api = self.makeInputApi([
Mustafa Emre Acer12e7fee2019-11-18 18:49:552657 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012658 MockAffectedFile(
2659 'test.grd',
Mustafa Emre Acer12e7fee2019-11-18 18:49:552660 self.OLD_GRD_CONTENTS, # new_contents
2661 self.NEW_GRD_CONTENTS2, # old_contents
Mustafa Emre Acerea3e57a2018-12-17 23:51:012662 action='M'),
Mustafa Emre Acer12e7fee2019-11-18 18:49:552663 MockAffectedFile(
2664 'part.grdp',
2665 self.OLD_GRDP_CONTENTS, # new_contents
2666 self.NEW_GRDP_CONTENTS2, # old_contents
2667 action='M'),
2668 # Unmodified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012669 MockFile(os.path.join('test_grd', 'IDS_TEST1.png.sha1'), 'binary', ''),
Mustafa Emre Acer12e7fee2019-11-18 18:49:552670 MockFile(os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2671 'binary', ''),
2672 # Deleted files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012673 MockAffectedFile(
2674 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2675 '',
2676 'old_contents',
Mustafa Emre Acer12e7fee2019-11-18 18:49:552677 action='D'),
2678 MockAffectedFile(
2679 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2680 '',
2681 'old_contents',
Mustafa Emre Acerea3e57a2018-12-17 23:51:012682 action='D')
2683 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142684 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2685 MockOutputApi())
2686 self.assertEqual(1, len(warnings))
2687 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
Mustafa Emre Acer12e7fee2019-11-18 18:49:552688 self.assertEqual([os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2689 os.path.join('test_grd', 'IDS_TEST1.png.sha1')
2690 ], warnings[0].items)
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142691
Mustafa Emre Acer12e7fee2019-11-18 18:49:552692 # Remove all sha1 files. There should be no warnings.
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142693 input_api = self.makeInputApi([
Mustafa Emre Acer12e7fee2019-11-18 18:49:552694 # Modified files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012695 MockAffectedFile(
2696 'test.grd',
2697 self.OLD_GRD_CONTENTS,
2698 self.NEW_GRD_CONTENTS2,
2699 action='M'),
Mustafa Emre Acer12e7fee2019-11-18 18:49:552700 MockAffectedFile(
2701 'part.grdp',
2702 self.OLD_GRDP_CONTENTS,
2703 self.NEW_GRDP_CONTENTS2,
2704 action='M'),
2705 # Deleted files:
Mustafa Emre Acerea3e57a2018-12-17 23:51:012706 MockFile(
2707 os.path.join('test_grd', 'IDS_TEST1.png.sha1'),
2708 'binary',
2709 action='D'),
2710 MockFile(
2711 os.path.join('test_grd', 'IDS_TEST2.png.sha1'),
2712 'binary',
Mustafa Emre Acer12e7fee2019-11-18 18:49:552713 action='D'),
2714 MockFile(
2715 os.path.join('part_grdp', 'IDS_PART_TEST1.png.sha1'),
2716 'binary',
2717 action='D'),
2718 MockFile(
2719 os.path.join('part_grdp', 'IDS_PART_TEST2.png.sha1'),
2720 'binary',
Mustafa Emre Acerea3e57a2018-12-17 23:51:012721 action='D')
2722 ])
Mustafa Emre Acer29bf6ac92018-07-30 21:42:142723 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2724 MockOutputApi())
2725 self.assertEqual([], warnings)
2726
2727
Dominic Battre033531052018-09-24 15:45:342728class DISABLETypoInTest(unittest.TestCase):
2729
2730 def testPositive(self):
2731 # Verify the typo "DISABLE_" instead of "DISABLED_" in various contexts
2732 # where the desire is to disable a test.
2733 tests = [
2734 # Disabled on one platform:
2735 '#if defined(OS_WIN)\n'
2736 '#define MAYBE_FoobarTest DISABLE_FoobarTest\n'
2737 '#else\n'
2738 '#define MAYBE_FoobarTest FoobarTest\n'
2739 '#endif\n',
2740 # Disabled on one platform spread cross lines:
2741 '#if defined(OS_WIN)\n'
2742 '#define MAYBE_FoobarTest \\\n'
2743 ' DISABLE_FoobarTest\n'
2744 '#else\n'
2745 '#define MAYBE_FoobarTest FoobarTest\n'
2746 '#endif\n',
2747 # Disabled on all platforms:
2748 ' TEST_F(FoobarTest, DISABLE_Foo)\n{\n}',
2749 # Disabled on all platforms but multiple lines
2750 ' TEST_F(FoobarTest,\n DISABLE_foo){\n}\n',
2751 ]
2752
2753 for test in tests:
2754 mock_input_api = MockInputApi()
2755 mock_input_api.files = [
2756 MockFile('some/path/foo_unittest.cc', test.splitlines()),
2757 ]
2758
2759 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
2760 MockOutputApi())
2761 self.assertEqual(
2762 1,
2763 len(results),
2764 msg=('expected len(results) == 1 but got %d in test: %s' %
2765 (len(results), test)))
2766 self.assertTrue(
2767 'foo_unittest.cc' in results[0].message,
2768 msg=('expected foo_unittest.cc in message but got %s in test %s' %
2769 (results[0].message, test)))
2770
2771 def testIngoreNotTestFiles(self):
2772 mock_input_api = MockInputApi()
2773 mock_input_api.files = [
2774 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, DISABLE_Foo)'),
2775 ]
2776
2777 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
2778 MockOutputApi())
2779 self.assertEqual(0, len(results))
2780
Katie Df13948e2018-09-25 07:33:442781 def testIngoreDeletedFiles(self):
2782 mock_input_api = MockInputApi()
2783 mock_input_api.files = [
2784 MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, Foo)', action='D'),
2785 ]
2786
2787 results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api,
2788 MockOutputApi())
2789 self.assertEqual(0, len(results))
Dominic Battre033531052018-09-24 15:45:342790
Dirk Pranke3c18a382019-03-15 01:07:512791
2792class BuildtoolsRevisionsAreInSyncTest(unittest.TestCase):
2793 # TODO(crbug.com/941824): We need to make sure the entries in
2794 # //buildtools/DEPS are kept in sync with the entries in //DEPS
2795 # so that users of //buildtools in other projects get the same tooling
2796 # Chromium gets. If we ever fix the referenced bug and add 'includedeps'
2797 # support to gclient, we can eliminate the duplication and delete
2798 # these tests for the corresponding presubmit check.
2799
2800 def _check(self, files):
2801 mock_input_api = MockInputApi()
2802 mock_input_api.files = []
2803 for fname, contents in files.items():
2804 mock_input_api.files.append(MockFile(fname, contents.splitlines()))
2805 return PRESUBMIT._CheckBuildtoolsRevisionsAreInSync(mock_input_api,
2806 MockOutputApi())
2807
2808 def testOneFileChangedButNotTheOther(self):
2809 results = self._check({
2810 "DEPS": "'libunwind_revision': 'onerev'",
2811 })
2812 self.assertNotEqual(results, [])
2813
2814 def testNeitherFileChanged(self):
2815 results = self._check({
2816 "OWNERS": "[email protected]",
2817 })
2818 self.assertEqual(results, [])
2819
2820 def testBothFilesChangedAndMatch(self):
2821 results = self._check({
2822 "DEPS": "'libunwind_revision': 'onerev'",
2823 "buildtools/DEPS": "'libunwind_revision': 'onerev'",
2824 })
2825 self.assertEqual(results, [])
2826
2827 def testBothFilesWereChangedAndDontMatch(self):
2828 results = self._check({
2829 "DEPS": "'libunwind_revision': 'onerev'",
2830 "buildtools/DEPS": "'libunwind_revision': 'anotherrev'",
2831 })
2832 self.assertNotEqual(results, [])
2833
2834
Max Morozb47503b2019-08-08 21:03:272835class CheckFuzzTargetsTest(unittest.TestCase):
2836
2837 def _check(self, files):
2838 mock_input_api = MockInputApi()
2839 mock_input_api.files = []
2840 for fname, contents in files.items():
2841 mock_input_api.files.append(MockFile(fname, contents.splitlines()))
2842 return PRESUBMIT._CheckFuzzTargets(mock_input_api, MockOutputApi())
2843
2844 def testLibFuzzerSourcesIgnored(self):
2845 results = self._check({
2846 "third_party/lib/Fuzzer/FuzzerDriver.cpp": "LLVMFuzzerInitialize",
2847 })
2848 self.assertEqual(results, [])
2849
2850 def testNonCodeFilesIgnored(self):
2851 results = self._check({
2852 "README.md": "LLVMFuzzerInitialize",
2853 })
2854 self.assertEqual(results, [])
2855
2856 def testNoErrorHeaderPresent(self):
2857 results = self._check({
2858 "fuzzer.cc": (
2859 "#include \"testing/libfuzzer/libfuzzer_exports.h\"\n" +
2860 "LLVMFuzzerInitialize"
2861 )
2862 })
2863 self.assertEqual(results, [])
2864
2865 def testErrorMissingHeader(self):
2866 results = self._check({
2867 "fuzzer.cc": "LLVMFuzzerInitialize"
2868 })
2869 self.assertEqual(len(results), 1)
2870 self.assertEqual(results[0].items, ['fuzzer.cc'])
2871
2872
Jochen Eisingerf9fbe7b6c32019-11-18 09:37:262873class SetNoParentTest(unittest.TestCase):
2874 def testSetNoParentMissing(self):
2875 mock_input_api = MockInputApi()
2876 mock_input_api.files = [
2877 MockAffectedFile('goat/OWNERS',
2878 [
2879 'set noparent',
2880 '[email protected]',
2881 'per-file *.json=set noparent',
2882 'per-file *[email protected]',
2883 ])
2884 ]
2885 mock_output_api = MockOutputApi()
2886 errors = PRESUBMIT._CheckSetNoParent(mock_input_api, mock_output_api)
2887 self.assertEqual(1, len(errors))
2888 self.assertTrue('goat/OWNERS:1' in errors[0].long_text)
2889 self.assertTrue('goat/OWNERS:3' in errors[0].long_text)
2890
2891
2892 def testSetNoParentWithCorrectRule(self):
2893 mock_input_api = MockInputApi()
2894 mock_input_api.files = [
2895 MockAffectedFile('goat/OWNERS',
2896 [
2897 'set noparent',
2898 'file://ipc/SECURITY_OWNERS',
2899 'per-file *.json=set noparent',
2900 'per-file *.json=file://ipc/SECURITY_OWNERS',
2901 ])
2902 ]
2903 mock_output_api = MockOutputApi()
2904 errors = PRESUBMIT._CheckSetNoParent(mock_input_api, mock_output_api)
2905 self.assertEqual([], errors)
2906
2907
[email protected]2299dcf2012-11-15 19:56:242908if __name__ == '__main__':
2909 unittest.main()