blob: f1be4edea2f8e26f3a6dc6fce359e2a5836b76b0 [file] [log] [blame]
[email protected]2299dcf2012-11-15 19:56:241#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Daniel Cheng4dcdb6b2017-04-13 08:30:176import os.path
[email protected]99171a92014-06-03 08:44:477import subprocess
[email protected]2299dcf2012-11-15 19:56:248import unittest
9
10import PRESUBMIT
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3911from PRESUBMIT_test_mocks import MockFile, MockAffectedFile
gayane3dff8c22014-12-04 17:09:5112from PRESUBMIT_test_mocks import MockInputApi, MockOutputApi
[email protected]2299dcf2012-11-15 19:56:2413
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3914
[email protected]99171a92014-06-03 08:44:4715_TEST_DATA_DIR = 'base/test/data/presubmit'
16
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3917
[email protected]b00342e7f2013-03-26 16:21:5418class VersionControlConflictsTest(unittest.TestCase):
[email protected]70ca77752012-11-20 03:45:0319 def testTypicalConflict(self):
20 lines = ['<<<<<<< HEAD',
21 ' base::ScopedTempDir temp_dir_;',
22 '=======',
23 ' ScopedTempDir temp_dir_;',
24 '>>>>>>> master']
25 errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
26 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
27 self.assertEqual(3, len(errors))
28 self.assertTrue('1' in errors[0])
29 self.assertTrue('3' in errors[1])
30 self.assertTrue('5' in errors[2])
31
dbeam95c35a2f2015-06-02 01:40:2332 def testIgnoresReadmes(self):
33 lines = ['A First Level Header',
34 '====================',
35 '',
36 'A Second Level Header',
37 '---------------------']
38 errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
39 MockInputApi(), MockFile('some/polymer/README.md', lines))
40 self.assertEqual(0, len(errors))
41
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:3942
mcasasb7440c282015-02-04 14:52:1943class UmaHistogramChangeMatchedOrNotTest(unittest.TestCase):
44 def testTypicalCorrectlyMatchedChange(self):
45 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4746 diff_java = [
47 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1948 diff_xml = ['<histogram name="Bla.Foo.Dummy"> </histogram>']
49 mock_input_api = MockInputApi()
50 mock_input_api.files = [
51 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:4752 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:1953 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
54 ]
55 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
56 MockOutputApi())
57 self.assertEqual(0, len(warnings))
58
59 def testTypicalNotMatchedChange(self):
60 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4761 diff_java = [
62 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1963 mock_input_api = MockInputApi()
Vaclav Brozekbdac817c2018-03-24 06:30:4764 mock_input_api.files = [
65 MockFile('some/path/foo.cc', diff_cc),
66 MockFile('some/path/foo.java', diff_java),
67 ]
mcasasb7440c282015-02-04 14:52:1968 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
69 MockOutputApi())
70 self.assertEqual(1, len(warnings))
71 self.assertEqual('warning', warnings[0].type)
Vaclav Brozekbdac817c2018-03-24 06:30:4772 self.assertTrue('foo.cc' in warnings[0].items[0])
73 self.assertTrue('foo.java' in warnings[0].items[1])
mcasasb7440c282015-02-04 14:52:1974
75 def testTypicalNotMatchedChangeViaSuffixes(self):
76 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4777 diff_java = [
78 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:1979 diff_xml = ['<histogram_suffixes name="SuperHistogram">',
80 ' <suffix name="Dummy"/>',
81 ' <affected-histogram name="Snafu.Dummy"/>',
82 '</histogram>']
83 mock_input_api = MockInputApi()
84 mock_input_api.files = [
85 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:4786 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:1987 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
88 ]
89 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
90 MockOutputApi())
91 self.assertEqual(1, len(warnings))
92 self.assertEqual('warning', warnings[0].type)
Vaclav Brozekbdac817c2018-03-24 06:30:4793 self.assertTrue('foo.cc' in warnings[0].items[0])
94 self.assertTrue('foo.java' in warnings[0].items[1])
mcasasb7440c282015-02-04 14:52:1995
96 def testTypicalCorrectlyMatchedChangeViaSuffixes(self):
97 diff_cc = ['UMA_HISTOGRAM_BOOL("Bla.Foo.Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:4798 diff_java = [
99 'RecordHistogram.recordBooleanHistogram("Bla.Foo.Dummy", true)']
mcasasb7440c282015-02-04 14:52:19100 diff_xml = ['<histogram_suffixes name="SuperHistogram">',
101 ' <suffix name="Dummy"/>',
102 ' <affected-histogram name="Bla.Foo"/>',
103 '</histogram>']
104 mock_input_api = MockInputApi()
105 mock_input_api.files = [
106 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47107 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:19108 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
109 ]
110 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
111 MockOutputApi())
112 self.assertEqual(0, len(warnings))
113
114 def testTypicalCorrectlyMatchedChangeViaSuffixesWithSeparator(self):
115 diff_cc = ['UMA_HISTOGRAM_BOOL("Snafu_Dummy", true)']
Vaclav Brozekbdac817c2018-03-24 06:30:47116 diff_java = ['RecordHistogram.recordBooleanHistogram("Snafu_Dummy", true)']
mcasasb7440c282015-02-04 14:52:19117 diff_xml = ['<histogram_suffixes name="SuperHistogram" separator="_">',
118 ' <suffix name="Dummy"/>',
119 ' <affected-histogram name="Snafu"/>',
120 '</histogram>']
121 mock_input_api = MockInputApi()
122 mock_input_api.files = [
123 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47124 MockFile('some/path/foo.java', diff_java),
mcasasb7440c282015-02-04 14:52:19125 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
126 ]
127 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
128 MockOutputApi())
129 self.assertEqual(0, len(warnings))
[email protected]70ca77752012-11-20 03:45:03130
Vaclav Brozek8a8e2e202018-03-23 22:01:06131 def testNameMatch(self):
132 # Check that the detected histogram name is "Dummy" and not, e.g.,
133 # "Dummy\", true); // The \"correct"
134 diff_cc = ['UMA_HISTOGRAM_BOOL("Dummy", true); // The "correct" histogram']
Vaclav Brozekbdac817c2018-03-24 06:30:47135 diff_java = [
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39136 'RecordHistogram.recordBooleanHistogram("Dummy", true);' +
137 ' // The "correct" histogram']
Vaclav Brozek8a8e2e202018-03-23 22:01:06138 diff_xml = ['<histogram name="Dummy"> </histogram>']
139 mock_input_api = MockInputApi()
140 mock_input_api.files = [
141 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47142 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek8a8e2e202018-03-23 22:01:06143 MockFile('tools/metrics/histograms/histograms.xml', diff_xml),
144 ]
145 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
146 MockOutputApi())
147 self.assertEqual(0, len(warnings))
148
149 def testSimilarMacroNames(self):
Vaclav Brozekbdac817c2018-03-24 06:30:47150 diff_cc = ['PUMA_HISTOGRAM_COOL("Mountain Lion", 42)']
151 diff_java = [
152 'FakeRecordHistogram.recordFakeHistogram("Mountain Lion", 42)']
Vaclav Brozek8a8e2e202018-03-23 22:01:06153 mock_input_api = MockInputApi()
154 mock_input_api.files = [
155 MockFile('some/path/foo.cc', diff_cc),
Vaclav Brozekbdac817c2018-03-24 06:30:47156 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek8a8e2e202018-03-23 22:01:06157 ]
158 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
159 MockOutputApi())
160 self.assertEqual(0, len(warnings))
161
Vaclav Brozek0e730cbd2018-03-24 06:18:17162 def testMultiLine(self):
163 diff_cc = ['UMA_HISTOGRAM_BOOLEAN(', ' "Multi.Line", true)']
164 diff_cc2 = ['UMA_HISTOGRAM_BOOLEAN(', ' "Multi.Line"', ' , true)']
Vaclav Brozekbdac817c2018-03-24 06:30:47165 diff_java = [
166 'RecordHistogram.recordBooleanHistogram(',
167 ' "Multi.Line", true);',
168 ]
Vaclav Brozek0e730cbd2018-03-24 06:18:17169 mock_input_api = MockInputApi()
170 mock_input_api.files = [
171 MockFile('some/path/foo.cc', diff_cc),
172 MockFile('some/path/foo2.cc', diff_cc2),
Vaclav Brozekbdac817c2018-03-24 06:30:47173 MockFile('some/path/foo.java', diff_java),
Vaclav Brozek0e730cbd2018-03-24 06:18:17174 ]
175 warnings = PRESUBMIT._CheckUmaHistogramChanges(mock_input_api,
176 MockOutputApi())
177 self.assertEqual(1, len(warnings))
178 self.assertEqual('warning', warnings[0].type)
179 self.assertTrue('foo.cc' in warnings[0].items[0])
180 self.assertTrue('foo2.cc' in warnings[0].items[1])
181
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39182
[email protected]b8079ae4a2012-12-05 19:56:49183class BadExtensionsTest(unittest.TestCase):
184 def testBadRejFile(self):
185 mock_input_api = MockInputApi()
186 mock_input_api.files = [
187 MockFile('some/path/foo.cc', ''),
188 MockFile('some/path/foo.cc.rej', ''),
189 MockFile('some/path2/bar.h.rej', ''),
190 ]
191
192 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
193 self.assertEqual(1, len(results))
194 self.assertEqual(2, len(results[0].items))
195 self.assertTrue('foo.cc.rej' in results[0].items[0])
196 self.assertTrue('bar.h.rej' in results[0].items[1])
197
198 def testBadOrigFile(self):
199 mock_input_api = MockInputApi()
200 mock_input_api.files = [
201 MockFile('other/path/qux.h.orig', ''),
202 MockFile('other/path/qux.h', ''),
203 MockFile('other/path/qux.cc', ''),
204 ]
205
206 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
207 self.assertEqual(1, len(results))
208 self.assertEqual(1, len(results[0].items))
209 self.assertTrue('qux.h.orig' in results[0].items[0])
210
211 def testGoodFiles(self):
212 mock_input_api = MockInputApi()
213 mock_input_api.files = [
214 MockFile('other/path/qux.h', ''),
215 MockFile('other/path/qux.cc', ''),
216 ]
217 results = PRESUBMIT._CheckPatchFiles(mock_input_api, MockOutputApi())
218 self.assertEqual(0, len(results))
219
220
glidere61efad2015-02-18 17:39:43221class CheckSingletonInHeadersTest(unittest.TestCase):
222 def testSingletonInArbitraryHeader(self):
223 diff_singleton_h = ['base::subtle::AtomicWord '
olli.raula36aa8be2015-09-10 11:14:22224 'base::Singleton<Type, Traits, DifferentiatingType>::']
225 diff_foo_h = ['// base::Singleton<Foo> in comment.',
226 'friend class base::Singleton<Foo>']
oysteinec430ad42015-10-22 20:55:24227 diff_foo2_h = [' //Foo* bar = base::Singleton<Foo>::get();']
olli.raula36aa8be2015-09-10 11:14:22228 diff_bad_h = ['Foo* foo = base::Singleton<Foo>::get();']
glidere61efad2015-02-18 17:39:43229 mock_input_api = MockInputApi()
230 mock_input_api.files = [MockAffectedFile('base/memory/singleton.h',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39231 diff_singleton_h),
glidere61efad2015-02-18 17:39:43232 MockAffectedFile('foo.h', diff_foo_h),
oysteinec430ad42015-10-22 20:55:24233 MockAffectedFile('foo2.h', diff_foo2_h),
glidere61efad2015-02-18 17:39:43234 MockAffectedFile('bad.h', diff_bad_h)]
235 warnings = PRESUBMIT._CheckSingletonInHeaders(mock_input_api,
236 MockOutputApi())
237 self.assertEqual(1, len(warnings))
Sylvain Defresnea8b73d252018-02-28 15:45:54238 self.assertEqual(1, len(warnings[0].items))
glidere61efad2015-02-18 17:39:43239 self.assertEqual('error', warnings[0].type)
olli.raula36aa8be2015-09-10 11:14:22240 self.assertTrue('Found base::Singleton<T>' in warnings[0].message)
glidere61efad2015-02-18 17:39:43241
242 def testSingletonInCC(self):
olli.raula36aa8be2015-09-10 11:14:22243 diff_cc = ['Foo* foo = base::Singleton<Foo>::get();']
glidere61efad2015-02-18 17:39:43244 mock_input_api = MockInputApi()
245 mock_input_api.files = [MockAffectedFile('some/path/foo.cc', diff_cc)]
246 warnings = PRESUBMIT._CheckSingletonInHeaders(mock_input_api,
247 MockOutputApi())
248 self.assertEqual(0, len(warnings))
249
250
[email protected]b00342e7f2013-03-26 16:21:54251class InvalidOSMacroNamesTest(unittest.TestCase):
252 def testInvalidOSMacroNames(self):
253 lines = ['#if defined(OS_WINDOWS)',
254 ' #elif defined(OS_WINDOW)',
255 ' # if defined(OS_MACOSX) || defined(OS_CHROME)',
256 '# else // defined(OS_MAC)',
257 '#endif // defined(OS_MACOS)']
258 errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
259 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
260 self.assertEqual(len(lines), len(errors))
261 self.assertTrue(':1 OS_WINDOWS' in errors[0])
262 self.assertTrue('(did you mean OS_WIN?)' in errors[0])
263
264 def testValidOSMacroNames(self):
265 lines = ['#if defined(%s)' % m for m in PRESUBMIT._VALID_OS_MACROS]
266 errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
267 MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
268 self.assertEqual(0, len(errors))
269
270
lliabraa35bab3932014-10-01 12:16:44271class InvalidIfDefinedMacroNamesTest(unittest.TestCase):
272 def testInvalidIfDefinedMacroNames(self):
273 lines = ['#if defined(TARGET_IPHONE_SIMULATOR)',
274 '#if !defined(TARGET_IPHONE_SIMULATOR)',
275 '#elif defined(TARGET_IPHONE_SIMULATOR)',
276 '#ifdef TARGET_IPHONE_SIMULATOR',
277 ' # ifdef TARGET_IPHONE_SIMULATOR',
278 '# if defined(VALID) || defined(TARGET_IPHONE_SIMULATOR)',
279 '# else // defined(TARGET_IPHONE_SIMULATOR)',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39280 '#endif // defined(TARGET_IPHONE_SIMULATOR)']
lliabraa35bab3932014-10-01 12:16:44281 errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
282 MockInputApi(), MockFile('some/path/source.mm', lines))
283 self.assertEqual(len(lines), len(errors))
284
285 def testValidIfDefinedMacroNames(self):
286 lines = ['#if defined(FOO)',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39287 '#ifdef BAR']
lliabraa35bab3932014-10-01 12:16:44288 errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
289 MockInputApi(), MockFile('some/path/source.cc', lines))
290 self.assertEqual(0, len(errors))
291
292
[email protected]f32e2d1e2013-07-26 21:39:08293class CheckAddedDepsHaveTetsApprovalsTest(unittest.TestCase):
Daniel Cheng4dcdb6b2017-04-13 08:30:17294
295 def calculate(self, old_include_rules, old_specific_include_rules,
296 new_include_rules, new_specific_include_rules):
297 return PRESUBMIT._CalculateAddedDeps(
298 os.path, 'include_rules = %r\nspecific_include_rules = %r' % (
299 old_include_rules, old_specific_include_rules),
300 'include_rules = %r\nspecific_include_rules = %r' % (
301 new_include_rules, new_specific_include_rules))
302
303 def testCalculateAddedDeps(self):
304 old_include_rules = [
305 '+base',
306 '-chrome',
307 '+content',
308 '-grit',
309 '-grit/",',
310 '+jni/fooblat.h',
311 '!sandbox',
[email protected]f32e2d1e2013-07-26 21:39:08312 ]
Daniel Cheng4dcdb6b2017-04-13 08:30:17313 old_specific_include_rules = {
314 'compositor\.*': {
315 '+cc',
316 },
317 }
318
319 new_include_rules = [
320 '-ash',
321 '+base',
322 '+chrome',
323 '+components',
324 '+content',
325 '+grit',
326 '+grit/generated_resources.h",',
327 '+grit/",',
328 '+jni/fooblat.h',
329 '+policy',
manzagop85e629e2017-05-09 22:11:48330 '+' + os.path.join('third_party', 'WebKit'),
Daniel Cheng4dcdb6b2017-04-13 08:30:17331 ]
332 new_specific_include_rules = {
333 'compositor\.*': {
334 '+cc',
335 },
336 'widget\.*': {
337 '+gpu',
338 },
339 }
340
[email protected]f32e2d1e2013-07-26 21:39:08341 expected = set([
manzagop85e629e2017-05-09 22:11:48342 os.path.join('chrome', 'DEPS'),
343 os.path.join('gpu', 'DEPS'),
344 os.path.join('components', 'DEPS'),
345 os.path.join('policy', 'DEPS'),
346 os.path.join('third_party', 'WebKit', 'DEPS'),
[email protected]f32e2d1e2013-07-26 21:39:08347 ])
Daniel Cheng4dcdb6b2017-04-13 08:30:17348 self.assertEqual(
349 expected,
350 self.calculate(old_include_rules, old_specific_include_rules,
351 new_include_rules, new_specific_include_rules))
352
353 def testCalculateAddedDepsIgnoresPermutations(self):
354 old_include_rules = [
355 '+base',
356 '+chrome',
357 ]
358 new_include_rules = [
359 '+chrome',
360 '+base',
361 ]
362 self.assertEqual(set(),
363 self.calculate(old_include_rules, {}, new_include_rules,
364 {}))
[email protected]f32e2d1e2013-07-26 21:39:08365
366
[email protected]99171a92014-06-03 08:44:47367class JSONParsingTest(unittest.TestCase):
368 def testSuccess(self):
369 input_api = MockInputApi()
370 filename = 'valid_json.json'
371 contents = ['// This is a comment.',
372 '{',
373 ' "key1": ["value1", "value2"],',
374 ' "key2": 3 // This is an inline comment.',
375 '}'
376 ]
377 input_api.files = [MockFile(filename, contents)]
378 self.assertEqual(None,
379 PRESUBMIT._GetJSONParseError(input_api, filename))
380
381 def testFailure(self):
382 input_api = MockInputApi()
383 test_data = [
384 ('invalid_json_1.json',
385 ['{ x }'],
[email protected]a3343272014-06-17 11:41:53386 'Expecting property name:'),
[email protected]99171a92014-06-03 08:44:47387 ('invalid_json_2.json',
388 ['// Hello world!',
389 '{ "hello": "world }'],
[email protected]a3343272014-06-17 11:41:53390 'Unterminated string starting at:'),
[email protected]99171a92014-06-03 08:44:47391 ('invalid_json_3.json',
392 ['{ "a": "b", "c": "d", }'],
[email protected]a3343272014-06-17 11:41:53393 'Expecting property name:'),
[email protected]99171a92014-06-03 08:44:47394 ('invalid_json_4.json',
395 ['{ "a": "b" "c": "d" }'],
[email protected]a3343272014-06-17 11:41:53396 'Expecting , delimiter:'),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39397 ]
[email protected]99171a92014-06-03 08:44:47398
399 input_api.files = [MockFile(filename, contents)
400 for (filename, contents, _) in test_data]
401
402 for (filename, _, expected_error) in test_data:
403 actual_error = PRESUBMIT._GetJSONParseError(input_api, filename)
[email protected]a3343272014-06-17 11:41:53404 self.assertTrue(expected_error in str(actual_error),
405 "'%s' not found in '%s'" % (expected_error, actual_error))
[email protected]99171a92014-06-03 08:44:47406
407 def testNoEatComments(self):
408 input_api = MockInputApi()
409 file_with_comments = 'file_with_comments.json'
410 contents_with_comments = ['// This is a comment.',
411 '{',
412 ' "key1": ["value1", "value2"],',
413 ' "key2": 3 // This is an inline comment.',
414 '}'
415 ]
416 file_without_comments = 'file_without_comments.json'
417 contents_without_comments = ['{',
418 ' "key1": ["value1", "value2"],',
419 ' "key2": 3',
420 '}'
421 ]
422 input_api.files = [MockFile(file_with_comments, contents_with_comments),
423 MockFile(file_without_comments,
424 contents_without_comments)]
425
426 self.assertEqual('No JSON object could be decoded',
427 str(PRESUBMIT._GetJSONParseError(input_api,
428 file_with_comments,
429 eat_comments=False)))
430 self.assertEqual(None,
431 PRESUBMIT._GetJSONParseError(input_api,
432 file_without_comments,
433 eat_comments=False))
434
435
436class IDLParsingTest(unittest.TestCase):
437 def testSuccess(self):
438 input_api = MockInputApi()
439 filename = 'valid_idl_basics.idl'
440 contents = ['// Tests a valid IDL file.',
441 'namespace idl_basics {',
442 ' enum EnumType {',
443 ' name1,',
444 ' name2',
445 ' };',
446 '',
447 ' dictionary MyType1 {',
448 ' DOMString a;',
449 ' };',
450 '',
451 ' callback Callback1 = void();',
452 ' callback Callback2 = void(long x);',
453 ' callback Callback3 = void(MyType1 arg);',
454 ' callback Callback4 = void(EnumType type);',
455 '',
456 ' interface Functions {',
457 ' static void function1();',
458 ' static void function2(long x);',
459 ' static void function3(MyType1 arg);',
460 ' static void function4(Callback1 cb);',
461 ' static void function5(Callback2 cb);',
462 ' static void function6(Callback3 cb);',
463 ' static void function7(Callback4 cb);',
464 ' };',
465 '',
466 ' interface Events {',
467 ' static void onFoo1();',
468 ' static void onFoo2(long x);',
469 ' static void onFoo2(MyType1 arg);',
470 ' static void onFoo3(EnumType type);',
471 ' };',
472 '};'
473 ]
474 input_api.files = [MockFile(filename, contents)]
475 self.assertEqual(None,
476 PRESUBMIT._GetIDLParseError(input_api, filename))
477
478 def testFailure(self):
479 input_api = MockInputApi()
480 test_data = [
481 ('invalid_idl_1.idl',
482 ['//',
483 'namespace test {',
484 ' dictionary {',
485 ' DOMString s;',
486 ' };',
487 '};'],
488 'Unexpected "{" after keyword "dictionary".\n'),
489 # TODO(yoz): Disabled because it causes the IDL parser to hang.
490 # See crbug.com/363830.
491 # ('invalid_idl_2.idl',
492 # (['namespace test {',
493 # ' dictionary MissingSemicolon {',
494 # ' DOMString a',
495 # ' DOMString b;',
496 # ' };',
497 # '};'],
498 # 'Unexpected symbol DOMString after symbol a.'),
499 ('invalid_idl_3.idl',
500 ['//',
501 'namespace test {',
502 ' enum MissingComma {',
503 ' name1',
504 ' name2',
505 ' };',
506 '};'],
507 'Unexpected symbol name2 after symbol name1.'),
508 ('invalid_idl_4.idl',
509 ['//',
510 'namespace test {',
511 ' enum TrailingComma {',
512 ' name1,',
513 ' name2,',
514 ' };',
515 '};'],
516 'Trailing comma in block.'),
517 ('invalid_idl_5.idl',
518 ['//',
519 'namespace test {',
520 ' callback Callback1 = void(;',
521 '};'],
522 'Unexpected ";" after "(".'),
523 ('invalid_idl_6.idl',
524 ['//',
525 'namespace test {',
526 ' callback Callback1 = void(long );',
527 '};'],
528 'Unexpected ")" after symbol long.'),
529 ('invalid_idl_7.idl',
530 ['//',
531 'namespace test {',
532 ' interace Events {',
533 ' static void onFoo1();',
534 ' };',
535 '};'],
536 'Unexpected symbol Events after symbol interace.'),
537 ('invalid_idl_8.idl',
538 ['//',
539 'namespace test {',
540 ' interface NotEvent {',
541 ' static void onFoo1();',
542 ' };',
543 '};'],
544 'Did not process Interface Interface(NotEvent)'),
545 ('invalid_idl_9.idl',
546 ['//',
547 'namespace test {',
548 ' interface {',
549 ' static void function1();',
550 ' };',
551 '};'],
552 'Interface missing name.'),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39553 ]
[email protected]99171a92014-06-03 08:44:47554
555 input_api.files = [MockFile(filename, contents)
556 for (filename, contents, _) in test_data]
557
558 for (filename, _, expected_error) in test_data:
559 actual_error = PRESUBMIT._GetIDLParseError(input_api, filename)
560 self.assertTrue(expected_error in str(actual_error),
561 "'%s' not found in '%s'" % (expected_error, actual_error))
562
563
[email protected]0bb112362014-07-26 04:38:32564class TryServerMasterTest(unittest.TestCase):
565 def testTryServerMasters(self):
566 bots = {
tandriie5587792016-07-14 00:34:50567 'master.tryserver.chromium.android': [
jbudorick3ae7a772016-05-20 02:36:04568 'android_archive_rel_ng',
569 'android_arm64_dbg_recipe',
570 'android_blink_rel',
571 'android_chromium_variable',
572 'android_chromium_variable_archive',
573 'android_chromium_variable_arm64',
574 'android_chromium_variable_cast_shell',
575 'android_chromium_variable_clang',
576 'android_chromium_variable_gn',
577 'android_chromium_variable_nexus4',
578 'android_clang_dbg_recipe',
579 'android_compile_dbg',
jbudorick3ae7a772016-05-20 02:36:04580 'android_compile_x64_dbg',
581 'android_compile_x86_dbg',
582 'android_coverage',
583 'android_cronet_tester'
584 'android_swarming_rel',
585 'cast_shell_android',
586 'linux_android_dbg_ng',
587 'linux_android_rel_ng',
588 ],
tandriie5587792016-07-14 00:34:50589 'master.tryserver.chromium.mac': [
[email protected]0bb112362014-07-26 04:38:32590 'ios_dbg_simulator',
591 'ios_rel_device',
592 'ios_rel_device_ninja',
593 'mac_asan',
594 'mac_asan_64',
595 'mac_chromium_compile_dbg',
596 'mac_chromium_compile_rel',
597 'mac_chromium_dbg',
598 'mac_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32599 'mac_nacl_sdk',
600 'mac_nacl_sdk_build',
601 'mac_rel_naclmore',
[email protected]0bb112362014-07-26 04:38:32602 'mac_x64_rel',
603 'mac_xcodebuild',
604 ],
tandriie5587792016-07-14 00:34:50605 'master.tryserver.chromium.linux': [
[email protected]0bb112362014-07-26 04:38:32606 'chromium_presubmit',
607 'linux_arm_cross_compile',
608 'linux_arm_tester',
[email protected]0bb112362014-07-26 04:38:32609 'linux_chromeos_asan',
610 'linux_chromeos_browser_asan',
611 'linux_chromeos_valgrind',
[email protected]0bb112362014-07-26 04:38:32612 'linux_chromium_chromeos_dbg',
613 'linux_chromium_chromeos_rel',
[email protected]0bb112362014-07-26 04:38:32614 'linux_chromium_compile_dbg',
615 'linux_chromium_compile_rel',
616 'linux_chromium_dbg',
617 'linux_chromium_gn_dbg',
618 'linux_chromium_gn_rel',
619 'linux_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32620 'linux_chromium_trusty32_dbg',
621 'linux_chromium_trusty32_rel',
622 'linux_chromium_trusty_dbg',
623 'linux_chromium_trusty_rel',
624 'linux_clang_tsan',
625 'linux_ecs_ozone',
626 'linux_layout',
627 'linux_layout_asan',
628 'linux_layout_rel',
629 'linux_layout_rel_32',
630 'linux_nacl_sdk',
631 'linux_nacl_sdk_bionic',
632 'linux_nacl_sdk_bionic_build',
633 'linux_nacl_sdk_build',
634 'linux_redux',
635 'linux_rel_naclmore',
636 'linux_rel_precise32',
637 'linux_valgrind',
638 'tools_build_presubmit',
639 ],
tandriie5587792016-07-14 00:34:50640 'master.tryserver.chromium.win': [
[email protected]0bb112362014-07-26 04:38:32641 'win8_aura',
642 'win8_chromium_dbg',
643 'win8_chromium_rel',
644 'win_chromium_compile_dbg',
645 'win_chromium_compile_rel',
646 'win_chromium_dbg',
647 'win_chromium_rel',
648 'win_chromium_rel',
[email protected]0bb112362014-07-26 04:38:32649 'win_chromium_x64_dbg',
650 'win_chromium_x64_rel',
[email protected]0bb112362014-07-26 04:38:32651 'win_nacl_sdk',
652 'win_nacl_sdk_build',
653 'win_rel_naclmore',
654 ],
655 }
656 for master, bots in bots.iteritems():
657 for bot in bots:
658 self.assertEqual(master, PRESUBMIT.GetTryServerMasterForBot(bot),
659 'bot=%s: expected %s, computed %s' % (
660 bot, master, PRESUBMIT.GetTryServerMasterForBot(bot)))
661
662
davileene0426252015-03-02 21:10:41663class UserMetricsActionTest(unittest.TestCase):
664 def testUserMetricsActionInActions(self):
665 input_api = MockInputApi()
666 file_with_user_action = 'file_with_user_action.cc'
667 contents_with_user_action = [
668 'base::UserMetricsAction("AboutChrome")'
669 ]
670
671 input_api.files = [MockFile(file_with_user_action,
672 contents_with_user_action)]
673
674 self.assertEqual(
675 [], PRESUBMIT._CheckUserActionUpdate(input_api, MockOutputApi()))
676
davileene0426252015-03-02 21:10:41677 def testUserMetricsActionNotAddedToActions(self):
678 input_api = MockInputApi()
679 file_with_user_action = 'file_with_user_action.cc'
680 contents_with_user_action = [
681 'base::UserMetricsAction("NotInActionsXml")'
682 ]
683
684 input_api.files = [MockFile(file_with_user_action,
685 contents_with_user_action)]
686
687 output = PRESUBMIT._CheckUserActionUpdate(input_api, MockOutputApi())
688 self.assertEqual(
689 ('File %s line %d: %s is missing in '
690 'tools/metrics/actions/actions.xml. Please run '
691 'tools/metrics/actions/extract_actions.py to update.'
692 % (file_with_user_action, 1, 'NotInActionsXml')),
693 output[0].message)
694
695
agrievef32bcc72016-04-04 14:57:40696class PydepsNeedsUpdatingTest(unittest.TestCase):
697
698 class MockSubprocess(object):
699 CalledProcessError = subprocess.CalledProcessError
700
701 def setUp(self):
702 mock_all_pydeps = ['A.pydeps', 'B.pydeps']
703 self.old_ALL_PYDEPS_FILES = PRESUBMIT._ALL_PYDEPS_FILES
704 PRESUBMIT._ALL_PYDEPS_FILES = mock_all_pydeps
705 self.mock_input_api = MockInputApi()
706 self.mock_output_api = MockOutputApi()
707 self.mock_input_api.subprocess = PydepsNeedsUpdatingTest.MockSubprocess()
708 self.checker = PRESUBMIT.PydepsChecker(self.mock_input_api, mock_all_pydeps)
709 self.checker._file_cache = {
710 'A.pydeps': '# Generated by:\n# CMD A\nA.py\nC.py\n',
711 'B.pydeps': '# Generated by:\n# CMD B\nB.py\nC.py\n',
712 }
713
714 def tearDown(self):
715 PRESUBMIT._ALL_PYDEPS_FILES = self.old_ALL_PYDEPS_FILES
716
717 def _RunCheck(self):
718 return PRESUBMIT._CheckPydepsNeedsUpdating(self.mock_input_api,
719 self.mock_output_api,
720 checker_for_tests=self.checker)
721
722 def testAddedPydep(self):
pastarmovj89f7ee12016-09-20 14:58:13723 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
724 if self.mock_input_api.platform != 'linux2':
725 return []
726
agrievef32bcc72016-04-04 14:57:40727 self.mock_input_api.files = [
728 MockAffectedFile('new.pydeps', [], action='A'),
729 ]
730
Zhiling Huang45cabf32018-03-10 00:50:03731 self.mock_input_api.CreateMockFileInPath(
732 [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
733 include_deletes=True)])
agrievef32bcc72016-04-04 14:57:40734 results = self._RunCheck()
735 self.assertEqual(1, len(results))
736 self.assertTrue('PYDEPS_FILES' in str(results[0]))
737
Zhiling Huang45cabf32018-03-10 00:50:03738 def testPydepNotInSrc(self):
739 self.mock_input_api.files = [
740 MockAffectedFile('new.pydeps', [], action='A'),
741 ]
742 self.mock_input_api.CreateMockFileInPath([])
743 results = self._RunCheck()
744 self.assertEqual(0, len(results))
745
agrievef32bcc72016-04-04 14:57:40746 def testRemovedPydep(self):
pastarmovj89f7ee12016-09-20 14:58:13747 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
748 if self.mock_input_api.platform != 'linux2':
749 return []
750
agrievef32bcc72016-04-04 14:57:40751 self.mock_input_api.files = [
752 MockAffectedFile(PRESUBMIT._ALL_PYDEPS_FILES[0], [], action='D'),
753 ]
Zhiling Huang45cabf32018-03-10 00:50:03754 self.mock_input_api.CreateMockFileInPath(
755 [x.LocalPath() for x in self.mock_input_api.AffectedFiles(
756 include_deletes=True)])
agrievef32bcc72016-04-04 14:57:40757 results = self._RunCheck()
758 self.assertEqual(1, len(results))
759 self.assertTrue('PYDEPS_FILES' in str(results[0]))
760
761 def testRandomPyIgnored(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('random.py', []),
768 ]
769
770 results = self._RunCheck()
771 self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
772
773 def testRelevantPyNoChange(self):
pastarmovj89f7ee12016-09-20 14:58:13774 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
775 if self.mock_input_api.platform != 'linux2':
776 return []
777
agrievef32bcc72016-04-04 14:57:40778 self.mock_input_api.files = [
779 MockAffectedFile('A.py', []),
780 ]
781
John Budorickab2fa102017-10-06 16:59:49782 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40783 self.assertEqual('CMD A --output ""', cmd)
784 return self.checker._file_cache['A.pydeps']
785
786 self.mock_input_api.subprocess.check_output = mock_check_output
787
788 results = self._RunCheck()
789 self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
790
791 def testRelevantPyOneChange(self):
pastarmovj89f7ee12016-09-20 14:58:13792 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
793 if self.mock_input_api.platform != 'linux2':
794 return []
795
agrievef32bcc72016-04-04 14:57:40796 self.mock_input_api.files = [
797 MockAffectedFile('A.py', []),
798 ]
799
John Budorickab2fa102017-10-06 16:59:49800 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40801 self.assertEqual('CMD A --output ""', cmd)
802 return 'changed data'
803
804 self.mock_input_api.subprocess.check_output = mock_check_output
805
806 results = self._RunCheck()
807 self.assertEqual(1, len(results))
808 self.assertTrue('File is stale' in str(results[0]))
809
810 def testRelevantPyTwoChanges(self):
pastarmovj89f7ee12016-09-20 14:58:13811 # PRESUBMIT._CheckPydepsNeedsUpdating is only implemented for Android.
812 if self.mock_input_api.platform != 'linux2':
813 return []
814
agrievef32bcc72016-04-04 14:57:40815 self.mock_input_api.files = [
816 MockAffectedFile('C.py', []),
817 ]
818
John Budorickab2fa102017-10-06 16:59:49819 def mock_check_output(cmd, shell=False, env=None):
agrievef32bcc72016-04-04 14:57:40820 return 'changed data'
821
822 self.mock_input_api.subprocess.check_output = mock_check_output
823
824 results = self._RunCheck()
825 self.assertEqual(2, len(results))
826 self.assertTrue('File is stale' in str(results[0]))
827 self.assertTrue('File is stale' in str(results[1]))
828
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39829
Daniel Bratell8ba52722018-03-02 16:06:14830class IncludeGuardTest(unittest.TestCase):
831 def testIncludeGuardChecks(self):
832 mock_input_api = MockInputApi()
833 mock_output_api = MockOutputApi()
834 mock_input_api.files = [
835 MockAffectedFile('content/browser/thing/foo.h', [
836 '// Comment',
837 '#ifndef CONTENT_BROWSER_THING_FOO_H_',
838 '#define CONTENT_BROWSER_THING_FOO_H_',
839 'struct McBoatFace;',
840 '#endif // CONTENT_BROWSER_THING_FOO_H_',
841 ]),
842 MockAffectedFile('content/browser/thing/bar.h', [
843 '#ifndef CONTENT_BROWSER_THING_BAR_H_',
844 '#define CONTENT_BROWSER_THING_BAR_H_',
845 'namespace content {',
846 '#endif // CONTENT_BROWSER_THING_BAR_H_',
847 '} // namespace content',
848 ]),
849 MockAffectedFile('content/browser/test1.h', [
850 'namespace content {',
851 '} // namespace content',
852 ]),
853 MockAffectedFile('content\\browser\\win.h', [
854 '#ifndef CONTENT_BROWSER_WIN_H_',
855 '#define CONTENT_BROWSER_WIN_H_',
856 'struct McBoatFace;',
857 '#endif // CONTENT_BROWSER_WIN_H_',
858 ]),
859 MockAffectedFile('content/browser/test2.h', [
860 '// Comment',
861 '#ifndef CONTENT_BROWSER_TEST2_H_',
862 'struct McBoatFace;',
863 '#endif // CONTENT_BROWSER_TEST2_H_',
864 ]),
865 MockAffectedFile('content/browser/internal.h', [
866 '// Comment',
867 '#ifndef CONTENT_BROWSER_INTERNAL_H_',
868 '#define CONTENT_BROWSER_INTERNAL_H_',
869 '// Comment',
870 '#ifndef INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
871 '#define INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
872 'namespace internal {',
873 '} // namespace internal',
874 '#endif // INTERNAL_CONTENT_BROWSER_THING_BAR_H_',
875 'namespace content {',
876 '} // namespace content',
877 '#endif // CONTENT_BROWSER_THING_BAR_H_',
878 ]),
879 MockAffectedFile('content/browser/thing/foo.cc', [
880 '// This is a non-header.',
881 ]),
882 MockAffectedFile('content/browser/disabled.h', [
883 '// no-include-guard-because-multiply-included',
884 'struct McBoatFace;',
885 ]),
886 # New files don't allow misspelled include guards.
887 MockAffectedFile('content/browser/spleling.h', [
888 '#ifndef CONTENT_BROWSER_SPLLEING_H_',
889 '#define CONTENT_BROWSER_SPLLEING_H_',
890 'struct McBoatFace;',
891 '#endif // CONTENT_BROWSER_SPLLEING_H_',
892 ]),
Olivier Robinbba137492018-07-30 11:31:34893 # New files don't allow + in include guards.
894 MockAffectedFile('content/browser/foo+bar.h', [
895 '#ifndef CONTENT_BROWSER_FOO+BAR_H_',
896 '#define CONTENT_BROWSER_FOO+BAR_H_',
897 'struct McBoatFace;',
898 '#endif // CONTENT_BROWSER_FOO+BAR_H_',
899 ]),
Daniel Bratell8ba52722018-03-02 16:06:14900 # Old files allow misspelled include guards (for now).
901 MockAffectedFile('chrome/old.h', [
902 '// New contents',
903 '#ifndef CHROME_ODL_H_',
904 '#define CHROME_ODL_H_',
905 '#endif // CHROME_ODL_H_',
906 ], [
907 '// Old contents',
908 '#ifndef CHROME_ODL_H_',
909 '#define CHROME_ODL_H_',
910 '#endif // CHROME_ODL_H_',
911 ]),
912 # Using a Blink style include guard outside Blink is wrong.
913 MockAffectedFile('content/NotInBlink.h', [
914 '#ifndef NotInBlink_h',
915 '#define NotInBlink_h',
916 'struct McBoatFace;',
917 '#endif // NotInBlink_h',
918 ]),
Daniel Bratell39b5b062018-05-16 18:09:57919 # Using a Blink style include guard in Blink is no longer ok.
920 MockAffectedFile('third_party/blink/InBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14921 '#ifndef InBlink_h',
922 '#define InBlink_h',
923 'struct McBoatFace;',
924 '#endif // InBlink_h',
925 ]),
926 # Using a bad include guard in Blink is not ok.
Daniel Bratell39b5b062018-05-16 18:09:57927 MockAffectedFile('third_party/blink/AlsoInBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14928 '#ifndef WrongInBlink_h',
929 '#define WrongInBlink_h',
930 'struct McBoatFace;',
931 '#endif // WrongInBlink_h',
932 ]),
Daniel Bratell39b5b062018-05-16 18:09:57933 # Using a bad include guard in Blink is not accepted even if
934 # it's an old file.
935 MockAffectedFile('third_party/blink/StillInBlink.h', [
Daniel Bratell8ba52722018-03-02 16:06:14936 '// New contents',
937 '#ifndef AcceptedInBlink_h',
938 '#define AcceptedInBlink_h',
939 'struct McBoatFace;',
940 '#endif // AcceptedInBlink_h',
941 ], [
942 '// Old contents',
943 '#ifndef AcceptedInBlink_h',
944 '#define AcceptedInBlink_h',
945 'struct McBoatFace;',
946 '#endif // AcceptedInBlink_h',
947 ]),
Daniel Bratell39b5b062018-05-16 18:09:57948 # Using a non-Chromium include guard in third_party
949 # (outside blink) is accepted.
950 MockAffectedFile('third_party/foo/some_file.h', [
951 '#ifndef REQUIRED_RPCNDR_H_',
952 '#define REQUIRED_RPCNDR_H_',
953 'struct SomeFileFoo;',
954 '#endif // REQUIRED_RPCNDR_H_',
955 ]),
Daniel Bratell8ba52722018-03-02 16:06:14956 ]
957 msgs = PRESUBMIT._CheckForIncludeGuards(
958 mock_input_api, mock_output_api)
Olivier Robinbba137492018-07-30 11:31:34959 expected_fail_count = 8
Daniel Bratell8ba52722018-03-02 16:06:14960 self.assertEqual(expected_fail_count, len(msgs),
961 'Expected %d items, found %d: %s'
962 % (expected_fail_count, len(msgs), msgs))
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39963 self.assertEqual(msgs[0].items, ['content/browser/thing/bar.h'])
Daniel Bratell8ba52722018-03-02 16:06:14964 self.assertEqual(msgs[0].message,
965 'Include guard CONTENT_BROWSER_THING_BAR_H_ '
966 'not covering the whole file')
967
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39968 self.assertEqual(msgs[1].items, ['content/browser/test1.h'])
Daniel Bratell8ba52722018-03-02 16:06:14969 self.assertEqual(msgs[1].message,
970 'Missing include guard CONTENT_BROWSER_TEST1_H_')
971
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39972 self.assertEqual(msgs[2].items, ['content/browser/test2.h:3'])
Daniel Bratell8ba52722018-03-02 16:06:14973 self.assertEqual(msgs[2].message,
974 'Missing "#define CONTENT_BROWSER_TEST2_H_" for '
975 'include guard')
976
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:39977 self.assertEqual(msgs[3].items, ['content/browser/spleling.h:1'])
Daniel Bratell8ba52722018-03-02 16:06:14978 self.assertEqual(msgs[3].message,
979 'Header using the wrong include guard name '
980 'CONTENT_BROWSER_SPLLEING_H_')
981
Olivier Robinbba137492018-07-30 11:31:34982 self.assertEqual(msgs[4].items, ['content/browser/foo+bar.h'])
Daniel Bratell8ba52722018-03-02 16:06:14983 self.assertEqual(msgs[4].message,
Olivier Robinbba137492018-07-30 11:31:34984 'Missing include guard CONTENT_BROWSER_FOO_BAR_H_')
985
986 self.assertEqual(msgs[5].items, ['content/NotInBlink.h:1'])
987 self.assertEqual(msgs[5].message,
Daniel Bratell8ba52722018-03-02 16:06:14988 'Header using the wrong include guard name '
989 'NotInBlink_h')
990
Olivier Robinbba137492018-07-30 11:31:34991 self.assertEqual(msgs[6].items, ['third_party/blink/InBlink.h:1'])
992 self.assertEqual(msgs[6].message,
Daniel Bratell8ba52722018-03-02 16:06:14993 'Header using the wrong include guard name '
Daniel Bratell39b5b062018-05-16 18:09:57994 'InBlink_h')
995
Olivier Robinbba137492018-07-30 11:31:34996 self.assertEqual(msgs[7].items, ['third_party/blink/AlsoInBlink.h:1'])
997 self.assertEqual(msgs[7].message,
Daniel Bratell39b5b062018-05-16 18:09:57998 'Header using the wrong include guard name '
Daniel Bratell8ba52722018-03-02 16:06:14999 'WrongInBlink_h')
1000
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391001
yolandyan45001472016-12-21 21:12:421002class AndroidDeprecatedTestAnnotationTest(unittest.TestCase):
1003 def testCheckAndroidTestAnnotationUsage(self):
1004 mock_input_api = MockInputApi()
1005 mock_output_api = MockOutputApi()
1006
1007 mock_input_api.files = [
1008 MockAffectedFile('LalaLand.java', [
1009 'random stuff'
1010 ]),
1011 MockAffectedFile('CorrectUsage.java', [
1012 'import android.support.test.filters.LargeTest;',
1013 'import android.support.test.filters.MediumTest;',
1014 'import android.support.test.filters.SmallTest;',
1015 ]),
1016 MockAffectedFile('UsedDeprecatedLargeTestAnnotation.java', [
1017 'import android.test.suitebuilder.annotation.LargeTest;',
1018 ]),
1019 MockAffectedFile('UsedDeprecatedMediumTestAnnotation.java', [
1020 'import android.test.suitebuilder.annotation.MediumTest;',
1021 ]),
1022 MockAffectedFile('UsedDeprecatedSmallTestAnnotation.java', [
1023 'import android.test.suitebuilder.annotation.SmallTest;',
1024 ]),
1025 MockAffectedFile('UsedDeprecatedSmokeAnnotation.java', [
1026 'import android.test.suitebuilder.annotation.Smoke;',
1027 ])
1028 ]
1029 msgs = PRESUBMIT._CheckAndroidTestAnnotationUsage(
1030 mock_input_api, mock_output_api)
1031 self.assertEqual(1, len(msgs),
1032 'Expected %d items, found %d: %s'
1033 % (1, len(msgs), msgs))
1034 self.assertEqual(4, len(msgs[0].items),
1035 'Expected %d items, found %d: %s'
1036 % (4, len(msgs[0].items), msgs[0].items))
1037 self.assertTrue('UsedDeprecatedLargeTestAnnotation.java:1' in msgs[0].items,
1038 'UsedDeprecatedLargeTestAnnotation not found in errors')
1039 self.assertTrue('UsedDeprecatedMediumTestAnnotation.java:1'
1040 in msgs[0].items,
1041 'UsedDeprecatedMediumTestAnnotation not found in errors')
1042 self.assertTrue('UsedDeprecatedSmallTestAnnotation.java:1' in msgs[0].items,
1043 'UsedDeprecatedSmallTestAnnotation not found in errors')
1044 self.assertTrue('UsedDeprecatedSmokeAnnotation.java:1' in msgs[0].items,
1045 'UsedDeprecatedSmokeAnnotation not found in errors')
1046
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391047
Yoland Yanb92fa522017-08-28 17:37:061048class AndroidDeprecatedJUnitFrameworkTest(unittest.TestCase):
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271049 def testCheckAndroidTestJUnitFramework(self):
Yoland Yanb92fa522017-08-28 17:37:061050 mock_input_api = MockInputApi()
1051 mock_output_api = MockOutputApi()
yolandyan45001472016-12-21 21:12:421052
Yoland Yanb92fa522017-08-28 17:37:061053 mock_input_api.files = [
1054 MockAffectedFile('LalaLand.java', [
1055 'random stuff'
1056 ]),
1057 MockAffectedFile('CorrectUsage.java', [
1058 'import org.junit.ABC',
1059 'import org.junit.XYZ;',
1060 ]),
1061 MockAffectedFile('UsedDeprecatedJUnit.java', [
1062 'import junit.framework.*;',
1063 ]),
1064 MockAffectedFile('UsedDeprecatedJUnitAssert.java', [
1065 'import junit.framework.Assert;',
1066 ]),
1067 ]
1068 msgs = PRESUBMIT._CheckAndroidTestJUnitFrameworkImport(
1069 mock_input_api, mock_output_api)
1070 self.assertEqual(1, len(msgs),
1071 'Expected %d items, found %d: %s'
1072 % (1, len(msgs), msgs))
1073 self.assertEqual(2, len(msgs[0].items),
1074 'Expected %d items, found %d: %s'
1075 % (2, len(msgs[0].items), msgs[0].items))
1076 self.assertTrue('UsedDeprecatedJUnit.java:1' in msgs[0].items,
1077 'UsedDeprecatedJUnit.java not found in errors')
1078 self.assertTrue('UsedDeprecatedJUnitAssert.java:1'
1079 in msgs[0].items,
1080 'UsedDeprecatedJUnitAssert not found in errors')
1081
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391082
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271083class AndroidJUnitBaseClassTest(unittest.TestCase):
1084 def testCheckAndroidTestJUnitBaseClass(self):
Yoland Yanb92fa522017-08-28 17:37:061085 mock_input_api = MockInputApi()
1086 mock_output_api = MockOutputApi()
1087
1088 mock_input_api.files = [
1089 MockAffectedFile('LalaLand.java', [
1090 'random stuff'
1091 ]),
1092 MockAffectedFile('CorrectTest.java', [
1093 '@RunWith(ABC.class);'
1094 'public class CorrectTest {',
1095 '}',
1096 ]),
1097 MockAffectedFile('HistoricallyIncorrectTest.java', [
1098 'public class Test extends BaseCaseA {',
1099 '}',
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391100 ], old_contents=[
Yoland Yanb92fa522017-08-28 17:37:061101 'public class Test extends BaseCaseB {',
1102 '}',
1103 ]),
1104 MockAffectedFile('CorrectTestWithInterface.java', [
1105 '@RunWith(ABC.class);'
1106 'public class CorrectTest implement Interface {',
1107 '}',
1108 ]),
1109 MockAffectedFile('IncorrectTest.java', [
1110 'public class IncorrectTest extends TestCase {',
1111 '}',
1112 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241113 MockAffectedFile('IncorrectWithInterfaceTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061114 'public class Test implements X extends BaseClass {',
1115 '}',
1116 ]),
Vaclav Brozekf01ed502018-03-16 19:38:241117 MockAffectedFile('IncorrectMultiLineTest.java', [
Yoland Yanb92fa522017-08-28 17:37:061118 'public class Test implements X, Y, Z',
1119 ' extends TestBase {',
1120 '}',
1121 ]),
1122 ]
1123 msgs = PRESUBMIT._CheckAndroidTestJUnitInheritance(
1124 mock_input_api, mock_output_api)
1125 self.assertEqual(1, len(msgs),
1126 'Expected %d items, found %d: %s'
1127 % (1, len(msgs), msgs))
1128 self.assertEqual(3, len(msgs[0].items),
1129 'Expected %d items, found %d: %s'
1130 % (3, len(msgs[0].items), msgs[0].items))
1131 self.assertTrue('IncorrectTest.java:1' in msgs[0].items,
1132 'IncorrectTest not found in errors')
Vaclav Brozekf01ed502018-03-16 19:38:241133 self.assertTrue('IncorrectWithInterfaceTest.java:1'
Yoland Yanb92fa522017-08-28 17:37:061134 in msgs[0].items,
Vaclav Brozekf01ed502018-03-16 19:38:241135 'IncorrectWithInterfaceTest not found in errors')
1136 self.assertTrue('IncorrectMultiLineTest.java:2' in msgs[0].items,
1137 'IncorrectMultiLineTest not found in errors')
yolandyan45001472016-12-21 21:12:421138
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391139
dgn4401aa52015-04-29 16:26:171140class LogUsageTest(unittest.TestCase):
1141
dgnaa68d5e2015-06-10 10:08:221142 def testCheckAndroidCrLogUsage(self):
1143 mock_input_api = MockInputApi()
1144 mock_output_api = MockOutputApi()
1145
1146 mock_input_api.files = [
1147 MockAffectedFile('RandomStuff.java', [
1148 'random stuff'
1149 ]),
dgn87d9fb62015-06-12 09:15:121150 MockAffectedFile('HasAndroidLog.java', [
1151 'import android.util.Log;',
1152 'some random stuff',
1153 'Log.d("TAG", "foo");',
1154 ]),
1155 MockAffectedFile('HasExplicitUtilLog.java', [
1156 'some random stuff',
1157 'android.util.Log.d("TAG", "foo");',
1158 ]),
1159 MockAffectedFile('IsInBasePackage.java', [
1160 'package org.chromium.base;',
dgn38736db2015-09-18 19:20:511161 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121162 'Log.d(TAG, "foo");',
1163 ]),
1164 MockAffectedFile('IsInBasePackageButImportsLog.java', [
1165 'package org.chromium.base;',
1166 'import android.util.Log;',
dgn38736db2015-09-18 19:20:511167 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121168 'Log.d(TAG, "foo");',
1169 ]),
1170 MockAffectedFile('HasBothLog.java', [
1171 'import org.chromium.base.Log;',
1172 'some random stuff',
dgn38736db2015-09-18 19:20:511173 'private static final String TAG = "cr_Foo";',
dgn87d9fb62015-06-12 09:15:121174 'Log.d(TAG, "foo");',
1175 'android.util.Log.d("TAG", "foo");',
1176 ]),
dgnaa68d5e2015-06-10 10:08:221177 MockAffectedFile('HasCorrectTag.java', [
1178 'import org.chromium.base.Log;',
1179 'some random stuff',
dgn38736db2015-09-18 19:20:511180 'private static final String TAG = "cr_Foo";',
1181 'Log.d(TAG, "foo");',
1182 ]),
1183 MockAffectedFile('HasOldTag.java', [
1184 'import org.chromium.base.Log;',
1185 'some random stuff',
dgnaa68d5e2015-06-10 10:08:221186 'private static final String TAG = "cr.Foo";',
1187 'Log.d(TAG, "foo");',
1188 ]),
dgn38736db2015-09-18 19:20:511189 MockAffectedFile('HasDottedTag.java', [
dgnaa68d5e2015-06-10 10:08:221190 'import org.chromium.base.Log;',
1191 'some random stuff',
dgn38736db2015-09-18 19:20:511192 'private static final String TAG = "cr_foo.bar";',
dgnaa68d5e2015-06-10 10:08:221193 'Log.d(TAG, "foo");',
1194 ]),
1195 MockAffectedFile('HasNoTagDecl.java', [
1196 'import org.chromium.base.Log;',
1197 'some random stuff',
1198 'Log.d(TAG, "foo");',
1199 ]),
1200 MockAffectedFile('HasIncorrectTagDecl.java', [
1201 'import org.chromium.base.Log;',
dgn38736db2015-09-18 19:20:511202 'private static final String TAHG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221203 'some random stuff',
1204 'Log.d(TAG, "foo");',
1205 ]),
1206 MockAffectedFile('HasInlineTag.java', [
1207 'import org.chromium.base.Log;',
1208 'some random stuff',
dgn38736db2015-09-18 19:20:511209 'private static final String TAG = "cr_Foo";',
dgnaa68d5e2015-06-10 10:08:221210 'Log.d("TAG", "foo");',
1211 ]),
dgn38736db2015-09-18 19:20:511212 MockAffectedFile('HasUnprefixedTag.java', [
dgnaa68d5e2015-06-10 10:08:221213 'import org.chromium.base.Log;',
1214 'some random stuff',
1215 'private static final String TAG = "rubbish";',
1216 'Log.d(TAG, "foo");',
1217 ]),
1218 MockAffectedFile('HasTooLongTag.java', [
1219 'import org.chromium.base.Log;',
1220 'some random stuff',
dgn38736db2015-09-18 19:20:511221 'private static final String TAG = "21_charachers_long___";',
dgnaa68d5e2015-06-10 10:08:221222 'Log.d(TAG, "foo");',
1223 ]),
1224 ]
1225
1226 msgs = PRESUBMIT._CheckAndroidCrLogUsage(
1227 mock_input_api, mock_output_api)
1228
dgn38736db2015-09-18 19:20:511229 self.assertEqual(5, len(msgs),
1230 'Expected %d items, found %d: %s' % (5, len(msgs), msgs))
dgnaa68d5e2015-06-10 10:08:221231
1232 # Declaration format
dgn38736db2015-09-18 19:20:511233 nb = len(msgs[0].items)
1234 self.assertEqual(2, nb,
1235 'Expected %d items, found %d: %s' % (2, nb, msgs[0].items))
dgnaa68d5e2015-06-10 10:08:221236 self.assertTrue('HasNoTagDecl.java' in msgs[0].items)
1237 self.assertTrue('HasIncorrectTagDecl.java' in msgs[0].items)
dgnaa68d5e2015-06-10 10:08:221238
1239 # Tag length
dgn38736db2015-09-18 19:20:511240 nb = len(msgs[1].items)
1241 self.assertEqual(1, nb,
1242 'Expected %d items, found %d: %s' % (1, nb, msgs[1].items))
dgnaa68d5e2015-06-10 10:08:221243 self.assertTrue('HasTooLongTag.java' in msgs[1].items)
1244
1245 # Tag must be a variable named TAG
dgn38736db2015-09-18 19:20:511246 nb = len(msgs[2].items)
1247 self.assertEqual(1, nb,
1248 'Expected %d items, found %d: %s' % (1, nb, msgs[2].items))
dgnaa68d5e2015-06-10 10:08:221249 self.assertTrue('HasInlineTag.java:4' in msgs[2].items)
1250
dgn87d9fb62015-06-12 09:15:121251 # Util Log usage
dgn38736db2015-09-18 19:20:511252 nb = len(msgs[3].items)
1253 self.assertEqual(2, nb,
1254 'Expected %d items, found %d: %s' % (2, nb, msgs[3].items))
dgn87d9fb62015-06-12 09:15:121255 self.assertTrue('HasAndroidLog.java:3' in msgs[3].items)
1256 self.assertTrue('IsInBasePackageButImportsLog.java:4' in msgs[3].items)
dgnaa68d5e2015-06-10 10:08:221257
dgn38736db2015-09-18 19:20:511258 # Tag must not contain
1259 nb = len(msgs[4].items)
1260 self.assertEqual(2, nb,
1261 'Expected %d items, found %d: %s' % (2, nb, msgs[4].items))
1262 self.assertTrue('HasDottedTag.java' in msgs[4].items)
1263 self.assertTrue('HasOldTag.java' in msgs[4].items)
1264
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391265
estadee17314a02017-01-12 16:22:161266class GoogleAnswerUrlFormatTest(unittest.TestCase):
1267
1268 def testCatchAnswerUrlId(self):
1269 input_api = MockInputApi()
1270 input_api.files = [
1271 MockFile('somewhere/file.cc',
1272 ['char* host = '
1273 ' "https://support.google.com/chrome/answer/123456";']),
1274 MockFile('somewhere_else/file.cc',
1275 ['char* host = '
1276 ' "https://support.google.com/chrome/a/answer/123456";']),
1277 ]
1278
1279 warnings = PRESUBMIT._CheckGoogleSupportAnswerUrl(
1280 input_api, MockOutputApi())
1281 self.assertEqual(1, len(warnings))
1282 self.assertEqual(2, len(warnings[0].items))
1283
1284 def testAllowAnswerUrlParam(self):
1285 input_api = MockInputApi()
1286 input_api.files = [
1287 MockFile('somewhere/file.cc',
1288 ['char* host = '
1289 ' "https://support.google.com/chrome/?p=cpn_crash_reports";']),
1290 ]
1291
1292 warnings = PRESUBMIT._CheckGoogleSupportAnswerUrl(
1293 input_api, MockOutputApi())
1294 self.assertEqual(0, len(warnings))
1295
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391296
reillyi38965732015-11-16 18:27:331297class HardcodedGoogleHostsTest(unittest.TestCase):
1298
1299 def testWarnOnAssignedLiterals(self):
1300 input_api = MockInputApi()
1301 input_api.files = [
1302 MockFile('content/file.cc',
1303 ['char* host = "https://www.google.com";']),
1304 MockFile('content/file.cc',
1305 ['char* host = "https://www.googleapis.com";']),
1306 MockFile('content/file.cc',
1307 ['char* host = "https://clients1.google.com";']),
1308 ]
1309
1310 warnings = PRESUBMIT._CheckHardcodedGoogleHostsInLowerLayers(
1311 input_api, MockOutputApi())
1312 self.assertEqual(1, len(warnings))
1313 self.assertEqual(3, len(warnings[0].items))
1314
1315 def testAllowInComment(self):
1316 input_api = MockInputApi()
1317 input_api.files = [
1318 MockFile('content/file.cc',
1319 ['char* host = "https://www.aol.com"; // google.com'])
1320 ]
1321
1322 warnings = PRESUBMIT._CheckHardcodedGoogleHostsInLowerLayers(
1323 input_api, MockOutputApi())
1324 self.assertEqual(0, len(warnings))
1325
dgn4401aa52015-04-29 16:26:171326
jbriance9e12f162016-11-25 07:57:501327class ForwardDeclarationTest(unittest.TestCase):
jbriance2c51e821a2016-12-12 08:24:311328 def testCheckHeadersOnlyOutsideThirdParty(self):
jbriance9e12f162016-11-25 07:57:501329 mock_input_api = MockInputApi()
1330 mock_input_api.files = [
1331 MockAffectedFile('somewhere/file.cc', [
1332 'class DummyClass;'
jbriance2c51e821a2016-12-12 08:24:311333 ]),
1334 MockAffectedFile('third_party/header.h', [
1335 'class DummyClass;'
jbriance9e12f162016-11-25 07:57:501336 ])
1337 ]
1338 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391339 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501340 self.assertEqual(0, len(warnings))
1341
1342 def testNoNestedDeclaration(self):
1343 mock_input_api = MockInputApi()
1344 mock_input_api.files = [
1345 MockAffectedFile('somewhere/header.h', [
jbriance2c51e821a2016-12-12 08:24:311346 'class SomeClass {',
1347 ' protected:',
1348 ' class NotAMatch;',
jbriance9e12f162016-11-25 07:57:501349 '};'
1350 ])
1351 ]
1352 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391353 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501354 self.assertEqual(0, len(warnings))
1355
1356 def testSubStrings(self):
1357 mock_input_api = MockInputApi()
1358 mock_input_api.files = [
1359 MockAffectedFile('somewhere/header.h', [
1360 'class NotUsefulClass;',
1361 'struct SomeStruct;',
1362 'UsefulClass *p1;',
1363 'SomeStructPtr *p2;'
1364 ])
1365 ]
1366 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391367 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501368 self.assertEqual(2, len(warnings))
1369
1370 def testUselessForwardDeclaration(self):
1371 mock_input_api = MockInputApi()
1372 mock_input_api.files = [
1373 MockAffectedFile('somewhere/header.h', [
1374 'class DummyClass;',
1375 'struct DummyStruct;',
1376 'class UsefulClass;',
1377 'std::unique_ptr<UsefulClass> p;'
jbriance2c51e821a2016-12-12 08:24:311378 ])
jbriance9e12f162016-11-25 07:57:501379 ]
1380 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391381 MockOutputApi())
jbriance9e12f162016-11-25 07:57:501382 self.assertEqual(2, len(warnings))
1383
jbriance2c51e821a2016-12-12 08:24:311384 def testBlinkHeaders(self):
1385 mock_input_api = MockInputApi()
1386 mock_input_api.files = [
1387 MockAffectedFile('third_party/WebKit/header.h', [
1388 'class DummyClass;',
1389 'struct DummyStruct;',
1390 ]),
1391 MockAffectedFile('third_party\\WebKit\\header.h', [
1392 'class DummyClass;',
1393 'struct DummyStruct;',
1394 ])
1395 ]
1396 warnings = PRESUBMIT._CheckUselessForwardDeclarations(mock_input_api,
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391397 MockOutputApi())
jbriance2c51e821a2016-12-12 08:24:311398 self.assertEqual(4, len(warnings))
1399
jbriance9e12f162016-11-25 07:57:501400
dbeam1ec68ac2016-12-15 05:22:241401class RiskyJsTest(unittest.TestCase):
1402 def testArrowWarnInIos9Code(self):
1403 mock_input_api = MockInputApi()
1404 mock_output_api = MockOutputApi()
1405
1406 mock_input_api.files = [
1407 MockAffectedFile('components/blah.js', ["shouldn't use => here"]),
1408 ]
1409 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1410 mock_input_api, mock_output_api)
1411 self.assertEqual(1, len(warnings))
1412
1413 mock_input_api.files = [
1414 MockAffectedFile('ios/blee.js', ['might => break folks']),
1415 ]
1416 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1417 mock_input_api, mock_output_api)
1418 self.assertEqual(1, len(warnings))
1419
1420 mock_input_api.files = [
1421 MockAffectedFile('ui/webui/resources/blarg.js', ['on => iOS9']),
1422 ]
1423 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1424 mock_input_api, mock_output_api)
1425 self.assertEqual(1, len(warnings))
1426
1427 def testArrowsAllowedInChromeCode(self):
1428 mock_input_api = MockInputApi()
1429 mock_input_api.files = [
1430 MockAffectedFile('chrome/browser/resources/blah.js', 'arrow => OK here'),
1431 ]
1432 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1433 mock_input_api, MockOutputApi())
1434 self.assertEqual(0, len(warnings))
1435
dpapadd651231d82017-07-21 02:44:471436 def testConstLetWarningIos9Code(self):
1437 mock_input_api = MockInputApi()
1438 mock_output_api = MockOutputApi()
1439
1440 mock_input_api.files = [
1441 MockAffectedFile('components/blah.js', [" const foo = 'bar';"]),
1442 MockAffectedFile('ui/webui/resources/blah.js', [" let foo = 3;"]),
1443 ]
1444 warnings = PRESUBMIT._CheckForRiskyJsFeatures(
1445 mock_input_api, mock_output_api)
1446 self.assertEqual(2, len(warnings))
1447
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391448
rlanday6802cf632017-05-30 17:48:361449class RelativeIncludesTest(unittest.TestCase):
1450 def testThirdPartyNotWebKitIgnored(self):
1451 mock_input_api = MockInputApi()
1452 mock_input_api.files = [
1453 MockAffectedFile('third_party/test.cpp', '#include "../header.h"'),
1454 MockAffectedFile('third_party/test/test.cpp', '#include "../header.h"'),
1455 ]
1456
1457 mock_output_api = MockOutputApi()
1458
1459 errors = PRESUBMIT._CheckForRelativeIncludes(
1460 mock_input_api, mock_output_api)
1461 self.assertEqual(0, len(errors))
1462
1463 def testNonCppFileIgnored(self):
1464 mock_input_api = MockInputApi()
1465 mock_input_api.files = [
1466 MockAffectedFile('test.py', '#include "../header.h"'),
1467 ]
1468
1469 mock_output_api = MockOutputApi()
1470
1471 errors = PRESUBMIT._CheckForRelativeIncludes(
1472 mock_input_api, mock_output_api)
1473 self.assertEqual(0, len(errors))
1474
1475 def testInnocuousChangesAllowed(self):
1476 mock_input_api = MockInputApi()
1477 mock_input_api.files = [
1478 MockAffectedFile('test.cpp', '#include "header.h"'),
1479 MockAffectedFile('test2.cpp', '../'),
1480 ]
1481
1482 mock_output_api = MockOutputApi()
1483
1484 errors = PRESUBMIT._CheckForRelativeIncludes(
1485 mock_input_api, mock_output_api)
1486 self.assertEqual(0, len(errors))
1487
1488 def testRelativeIncludeNonWebKitProducesError(self):
1489 mock_input_api = MockInputApi()
1490 mock_input_api.files = [
1491 MockAffectedFile('test.cpp', ['#include "../header.h"']),
1492 ]
1493
1494 mock_output_api = MockOutputApi()
1495
1496 errors = PRESUBMIT._CheckForRelativeIncludes(
1497 mock_input_api, mock_output_api)
1498 self.assertEqual(1, len(errors))
1499
1500 def testRelativeIncludeWebKitProducesError(self):
1501 mock_input_api = MockInputApi()
1502 mock_input_api.files = [
1503 MockAffectedFile('third_party/WebKit/test.cpp',
1504 ['#include "../header.h']),
1505 ]
1506
1507 mock_output_api = MockOutputApi()
1508
1509 errors = PRESUBMIT._CheckForRelativeIncludes(
1510 mock_input_api, mock_output_api)
1511 self.assertEqual(1, len(errors))
dbeam1ec68ac2016-12-15 05:22:241512
Daniel Cheng13ca61a882017-08-25 15:11:251513
Wei-Yin Chen (陳威尹)c0624d002018-07-30 18:22:191514class NewHeaderWithoutGnChangeTest(unittest.TestCase):
1515 def testAddHeaderWithoutGn(self):
1516 mock_input_api = MockInputApi()
1517 mock_input_api.files = [
1518 MockAffectedFile('base/stuff.h', ''),
1519 ]
1520 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1521 mock_input_api, MockOutputApi())
1522 self.assertEqual(1, len(warnings))
1523 self.assertTrue('base/stuff.h' in warnings[0].items)
1524
1525 def testModifyHeader(self):
1526 mock_input_api = MockInputApi()
1527 mock_input_api.files = [
1528 MockAffectedFile('base/stuff.h', '', action='M'),
1529 ]
1530 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1531 mock_input_api, MockOutputApi())
1532 self.assertEqual(0, len(warnings))
1533
1534 def testDeleteHeader(self):
1535 mock_input_api = MockInputApi()
1536 mock_input_api.files = [
1537 MockAffectedFile('base/stuff.h', '', action='D'),
1538 ]
1539 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1540 mock_input_api, MockOutputApi())
1541 self.assertEqual(0, len(warnings))
1542
1543 def testAddHeaderWithGn(self):
1544 mock_input_api = MockInputApi()
1545 mock_input_api.files = [
1546 MockAffectedFile('base/stuff.h', ''),
1547 MockAffectedFile('base/BUILD.gn', 'stuff.h'),
1548 ]
1549 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1550 mock_input_api, MockOutputApi())
1551 self.assertEqual(0, len(warnings))
1552
1553 def testAddHeaderWithGni(self):
1554 mock_input_api = MockInputApi()
1555 mock_input_api.files = [
1556 MockAffectedFile('base/stuff.h', ''),
1557 MockAffectedFile('base/files.gni', 'stuff.h'),
1558 ]
1559 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1560 mock_input_api, MockOutputApi())
1561 self.assertEqual(0, len(warnings))
1562
1563 def testAddHeaderWithOther(self):
1564 mock_input_api = MockInputApi()
1565 mock_input_api.files = [
1566 MockAffectedFile('base/stuff.h', ''),
1567 MockAffectedFile('base/stuff.cc', 'stuff.h'),
1568 ]
1569 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1570 mock_input_api, MockOutputApi())
1571 self.assertEqual(1, len(warnings))
1572
1573 def testAddHeaderWithWrongGn(self):
1574 mock_input_api = MockInputApi()
1575 mock_input_api.files = [
1576 MockAffectedFile('base/stuff.h', ''),
1577 MockAffectedFile('base/BUILD.gn', 'stuff_h'),
1578 ]
1579 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1580 mock_input_api, MockOutputApi())
1581 self.assertEqual(1, len(warnings))
1582
1583 def testAddHeadersWithGn(self):
1584 mock_input_api = MockInputApi()
1585 mock_input_api.files = [
1586 MockAffectedFile('base/stuff.h', ''),
1587 MockAffectedFile('base/another.h', ''),
1588 MockAffectedFile('base/BUILD.gn', 'another.h\nstuff.h'),
1589 ]
1590 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1591 mock_input_api, MockOutputApi())
1592 self.assertEqual(0, len(warnings))
1593
1594 def testAddHeadersWithWrongGn(self):
1595 mock_input_api = MockInputApi()
1596 mock_input_api.files = [
1597 MockAffectedFile('base/stuff.h', ''),
1598 MockAffectedFile('base/another.h', ''),
1599 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff.h'),
1600 ]
1601 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1602 mock_input_api, MockOutputApi())
1603 self.assertEqual(1, len(warnings))
1604 self.assertFalse('base/stuff.h' in warnings[0].items)
1605 self.assertTrue('base/another.h' in warnings[0].items)
1606
1607 def testAddHeadersWithWrongGn2(self):
1608 mock_input_api = MockInputApi()
1609 mock_input_api.files = [
1610 MockAffectedFile('base/stuff.h', ''),
1611 MockAffectedFile('base/another.h', ''),
1612 MockAffectedFile('base/BUILD.gn', 'another_h\nstuff_h'),
1613 ]
1614 warnings = PRESUBMIT._CheckNewHeaderWithoutGnChange(
1615 mock_input_api, MockOutputApi())
1616 self.assertEqual(1, len(warnings))
1617 self.assertTrue('base/stuff.h' in warnings[0].items)
1618 self.assertTrue('base/another.h' in warnings[0].items)
1619
1620
Daniel Cheng13ca61a882017-08-25 15:11:251621class MojoManifestOwnerTest(unittest.TestCase):
1622 def testMojoManifestChangeNeedsSecurityOwner(self):
1623 mock_input_api = MockInputApi()
1624 mock_input_api.files = [
1625 MockAffectedFile('services/goat/manifest.json',
1626 [
1627 '{',
1628 ' "name": "teleporter",',
1629 ' "display_name": "Goat Teleporter",'
1630 ' "interface_provider_specs": {',
1631 ' }',
1632 '}',
1633 ])
1634 ]
1635 mock_output_api = MockOutputApi()
1636 errors = PRESUBMIT._CheckIpcOwners(
1637 mock_input_api, mock_output_api)
1638 self.assertEqual(1, len(errors))
1639 self.assertEqual(
1640 'Found OWNERS files that need to be updated for IPC security review ' +
1641 'coverage.\nPlease update the OWNERS files below:', errors[0].message)
1642
1643 # No warning if already covered by an OWNERS rule.
1644
1645 def testNonManifestChangesDoNotRequireSecurityOwner(self):
1646 mock_input_api = MockInputApi()
1647 mock_input_api.files = [
1648 MockAffectedFile('services/goat/species.json',
1649 [
1650 '[',
1651 ' "anglo-nubian",',
1652 ' "angora"',
1653 ']',
1654 ])
1655 ]
1656 mock_output_api = MockOutputApi()
1657 errors = PRESUBMIT._CheckIpcOwners(
1658 mock_input_api, mock_output_api)
1659 self.assertEqual([], errors)
1660
1661
Miguel Casas-Sancheze0d46d42017-12-14 15:52:191662class CrbugUrlFormatTest(unittest.TestCase):
1663
1664 def testCheckCrbugLinksHaveHttps(self):
1665 input_api = MockInputApi()
1666 input_api.files = [
1667 MockFile('somewhere/file.cc',
1668 ['// TODO(developer): crbug.com should be linkified',
1669 '// TODO(developer): (crbug.com) should be linkified',
1670 '// TODO(developer): crbug/123 should be well formed',
1671 '// TODO(developer): http://crbug.com it\'s OK',
Miguel Casas68bdb652017-12-19 16:29:091672 '// TODO(developer): https://crbug.com is just great',
1673 '// TODO(crbug.com/123456): this pattern it\'s also OK']),
Miguel Casas-Sancheze0d46d42017-12-14 15:52:191674 ]
1675
1676 warnings = PRESUBMIT._CheckCrbugLinksHaveHttps(input_api, MockOutputApi())
1677 self.assertEqual(1, len(warnings))
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391678 self.assertEqual(3, warnings[0].message.count('\n'))
Miguel Casas-Sancheze0d46d42017-12-14 15:52:191679
1680
Sylvain Defresnea8b73d252018-02-28 15:45:541681class BannedFunctionCheckTest(unittest.TestCase):
1682
1683 def testBannedIosObcjFunctions(self):
1684 input_api = MockInputApi()
1685 input_api.files = [
1686 MockFile('some/ios/file.mm',
1687 ['TEST(SomeClassTest, SomeInteraction) {',
1688 '}']),
1689 MockFile('some/mac/file.mm',
1690 ['TEST(SomeClassTest, SomeInteraction) {',
1691 '}']),
1692 MockFile('another/ios_file.mm',
1693 ['class SomeTest : public testing::Test {};']),
1694 ]
1695
1696 errors = PRESUBMIT._CheckNoBannedFunctions(input_api, MockOutputApi())
1697 self.assertEqual(1, len(errors))
1698 self.assertTrue('some/ios/file.mm' in errors[0].message)
1699 self.assertTrue('another/ios_file.mm' in errors[0].message)
1700 self.assertTrue('some/mac/file.mm' not in errors[0].message)
1701
1702
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271703class NoProductionCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozekf01ed502018-03-16 19:38:241704 def testTruePositives(self):
1705 mock_input_api = MockInputApi()
1706 mock_input_api.files = [
1707 MockFile('some/path/foo.cc', ['foo_for_testing();']),
1708 MockFile('some/path/foo.mm', ['FooForTesting();']),
1709 MockFile('some/path/foo.cxx', ['FooForTests();']),
1710 MockFile('some/path/foo.cpp', ['foo_for_test();']),
1711 ]
1712
1713 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctions(
1714 mock_input_api, MockOutputApi())
1715 self.assertEqual(1, len(results))
1716 self.assertEqual(4, len(results[0].items))
1717 self.assertTrue('foo.cc' in results[0].items[0])
1718 self.assertTrue('foo.mm' in results[0].items[1])
1719 self.assertTrue('foo.cxx' in results[0].items[2])
1720 self.assertTrue('foo.cpp' in results[0].items[3])
1721
1722 def testFalsePositives(self):
1723 mock_input_api = MockInputApi()
1724 mock_input_api.files = [
1725 MockFile('some/path/foo.h', ['foo_for_testing();']),
1726 MockFile('some/path/foo.mm', ['FooForTesting() {']),
1727 MockFile('some/path/foo.cc', ['::FooForTests();']),
1728 MockFile('some/path/foo.cpp', ['// foo_for_test();']),
1729 ]
1730
1731 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctions(
1732 mock_input_api, MockOutputApi())
1733 self.assertEqual(0, len(results))
1734
1735
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271736class NoProductionJavaCodeUsingTestOnlyFunctionsTest(unittest.TestCase):
Vaclav Brozek7dbc28c2018-03-27 08:35:231737 def testTruePositives(self):
1738 mock_input_api = MockInputApi()
1739 mock_input_api.files = [
1740 MockFile('dir/java/src/foo.java', ['FooForTesting();']),
1741 MockFile('dir/java/src/bar.java', ['FooForTests(x);']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391742 MockFile('dir/java/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:231743 MockFile('dir/java/src/mult.java', [
1744 'int x = SomethingLongHere()',
1745 ' * SomethingLongHereForTesting();'
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391746 ])
Vaclav Brozek7dbc28c2018-03-27 08:35:231747 ]
1748
1749 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctionsJava(
1750 mock_input_api, MockOutputApi())
1751 self.assertEqual(1, len(results))
1752 self.assertEqual(4, len(results[0].items))
1753 self.assertTrue('foo.java' in results[0].items[0])
1754 self.assertTrue('bar.java' in results[0].items[1])
1755 self.assertTrue('baz.java' in results[0].items[2])
1756 self.assertTrue('mult.java' in results[0].items[3])
1757
1758 def testFalsePositives(self):
1759 mock_input_api = MockInputApi()
1760 mock_input_api.files = [
1761 MockFile('dir/java/src/foo.xml', ['FooForTesting();']),
1762 MockFile('dir/java/src/foo.java', ['FooForTests() {']),
1763 MockFile('dir/java/src/bar.java', ['// FooForTest();']),
1764 MockFile('dir/java/src/bar2.java', ['x = 1; // FooForTest();']),
Wei-Yin Chen (陳威尹)54086c212018-07-27 21:41:391765 MockFile('dir/javatests/src/baz.java', ['FooForTest(', 'y', ');']),
1766 MockFile('dir/junit/src/baz.java', ['FooForTest(', 'y', ');']),
Vaclav Brozek7dbc28c2018-03-27 08:35:231767 MockFile('dir/junit/src/javadoc.java', [
1768 '/** Use FooForTest(); to obtain foo in tests.'
1769 ' */'
1770 ]),
1771 MockFile('dir/junit/src/javadoc2.java', [
1772 '/** ',
1773 ' * Use FooForTest(); to obtain foo in tests.'
1774 ' */'
1775 ]),
1776 ]
1777
1778 results = PRESUBMIT._CheckNoProductionCodeUsingTestOnlyFunctionsJava(
1779 mock_input_api, MockOutputApi())
1780 self.assertEqual(0, len(results))
1781
1782
Wei-Yin Chen (陳威尹)032f1ac2018-07-27 21:21:271783class CheckUniquePtrTest(unittest.TestCase):
Vaclav Brozek851d9602018-04-04 16:13:051784 def testTruePositivesNullptr(self):
1785 mock_input_api = MockInputApi()
1786 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:161787 MockFile('dir/baz.cc', ['std::unique_ptr<T>()']),
1788 MockFile('dir/baz-p.cc', ['std::unique_ptr<T<P>>()']),
Vaclav Brozek851d9602018-04-04 16:13:051789 ]
1790
1791 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
1792 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:161793 self.assertTrue('nullptr' in results[0].message)
Vaclav Brozek851d9602018-04-04 16:13:051794 self.assertEqual(2, len(results[0].items))
1795 self.assertTrue('baz.cc' in results[0].items[0])
1796 self.assertTrue('baz-p.cc' in results[0].items[1])
1797
1798 def testTruePositivesConstructor(self):
Vaclav Brozek52e18bf2018-04-03 07:05:241799 mock_input_api = MockInputApi()
1800 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:161801 MockFile('dir/foo.cc', ['return std::unique_ptr<T>(foo);']),
1802 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T>(foo)']),
1803 MockFile('dir/mult.cc', [
Vaclav Brozek95face62018-04-04 14:15:111804 'return',
1805 ' std::unique_ptr<T>(barVeryVeryLongFooSoThatItWouldNotFitAbove);'
1806 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:161807 MockFile('dir/mult2.cc', [
Vaclav Brozek95face62018-04-04 14:15:111808 'barVeryVeryLongLongBaaaaaarSoThatTheLineLimitIsAlmostReached =',
1809 ' std::unique_ptr<T>(foo);'
1810 ]),
Vaclav Brozekc2fecf42018-04-06 16:40:161811 MockFile('dir/mult3.cc', [
Vaclav Brozek95face62018-04-04 14:15:111812 'bar = std::unique_ptr<T>(',
1813 ' fooVeryVeryVeryLongStillGoingWellThisWillTakeAWhileFinallyThere);'
1814 ]),
Vaclav Brozek52e18bf2018-04-03 07:05:241815 ]
1816
1817 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
Vaclav Brozek851d9602018-04-04 16:13:051818 self.assertEqual(1, len(results))
Vaclav Brozekc2fecf42018-04-06 16:40:161819 self.assertTrue('std::make_unique' in results[0].message)
Vaclav Brozek851d9602018-04-04 16:13:051820 self.assertEqual(5, len(results[0].items))
1821 self.assertTrue('foo.cc' in results[0].items[0])
1822 self.assertTrue('bar.mm' in results[0].items[1])
1823 self.assertTrue('mult.cc' in results[0].items[2])
1824 self.assertTrue('mult2.cc' in results[0].items[3])
1825 self.assertTrue('mult3.cc' in results[0].items[4])
Vaclav Brozek52e18bf2018-04-03 07:05:241826
1827 def testFalsePositives(self):
1828 mock_input_api = MockInputApi()
1829 mock_input_api.files = [
Vaclav Brozekc2fecf42018-04-06 16:40:161830 MockFile('dir/foo.cc', ['return std::unique_ptr<T[]>(foo);']),
1831 MockFile('dir/bar.mm', ['bar = std::unique_ptr<T[]>(foo)']),
1832 MockFile('dir/file.cc', ['std::unique_ptr<T> p = Foo();']),
1833 MockFile('dir/baz.cc', [
Vaclav Brozek52e18bf2018-04-03 07:05:241834 'std::unique_ptr<T> result = std::make_unique<T>();'
1835 ]),
Vaclav Brozeka54c528b2018-04-06 19:23:551836 MockFile('dir/baz2.cc', [
1837 'std::unique_ptr<T> result = std::make_unique<T>('
1838 ]),
1839 MockFile('dir/nested.cc', ['set<std::unique_ptr<T>>();']),
1840 MockFile('dir/nested2.cc', ['map<U, std::unique_ptr<T>>();']),
Vaclav Brozek52e18bf2018-04-03 07:05:241841 ]
1842
1843 results = PRESUBMIT._CheckUniquePtr(mock_input_api, MockOutputApi())
1844 self.assertEqual(0, len(results))
1845
1846
Mustafa Emre Acer29bf6ac92018-07-30 21:42:141847class TranslationScreenshotsTest(unittest.TestCase):
1848 # An empty grd file.
1849 OLD_GRD_CONTENTS = """<?xml version="1.0" encoding="UTF-8"?>
1850 <grit latest_public_release="1" current_release="1">
1851 <release seq="1">
1852 <messages></messages>
1853 </release>
1854 </grit>
1855 """.splitlines()
1856 # A grd file with a single message.
1857 NEW_GRD_CONTENTS1 = """<?xml version="1.0" encoding="UTF-8"?>
1858 <grit latest_public_release="1" current_release="1">
1859 <release seq="1">
1860 <messages>
1861 <message name="IDS_TEST1">
1862 Test string 1
1863 </message>
1864 </messages>
1865 </release>
1866 </grit>
1867 """.splitlines()
1868 # A grd file with two messages.
1869 NEW_GRD_CONTENTS2 = """<?xml version="1.0" encoding="UTF-8"?>
1870 <grit latest_public_release="1" current_release="1">
1871 <release seq="1">
1872 <messages>
1873 <message name="IDS_TEST1">
1874 Test string 1
1875 </message>
1876 <message name="IDS_TEST2">
1877 Test string 2
1878 </message>
1879 </messages>
1880 </release>
1881 </grit>
1882 """.splitlines()
1883
Mustafa Emre Acerc8a012d2018-07-31 00:00:391884 DO_NOT_UPLOAD_PNG_MESSAGE = ('Do not include actual screenshots in the '
1885 'changelist. Run '
1886 'tools/translate/upload_screenshots.py to '
1887 'upload them instead:')
1888 GENERATE_SIGNATURES_MESSAGE = ('You are adding or modifying UI strings.\n'
1889 'To ensure the best translations, take '
1890 'screenshots of the relevant UI '
1891 '(https://g.co/chrome/translation) and add '
1892 'these files to your changelist:')
1893 REMOVE_SIGNATURES_MESSAGE = ('You removed strings associated with these '
1894 'files. Remove:')
Mustafa Emre Acer29bf6ac92018-07-30 21:42:141895
1896 def makeInputApi(self, files):
1897 input_api = MockInputApi()
1898 input_api.files = files
1899 return input_api
1900
1901 def testNoScreenshots(self):
1902 # CL modified and added messages, but didn't add any screenshots.
1903 input_api = self.makeInputApi([
1904 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
1905 self.OLD_GRD_CONTENTS, action='M')])
1906 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1907 MockOutputApi())
1908 self.assertEqual(1, len(warnings))
1909 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
1910 self.assertEqual(
1911 ['test_grd/IDS_TEST1.png.sha1', 'test_grd/IDS_TEST2.png.sha1'],
1912 warnings[0].items)
1913
1914 input_api = self.makeInputApi([
1915 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
1916 self.NEW_GRD_CONTENTS1, action='M')])
1917 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1918 MockOutputApi())
1919 self.assertEqual(1, len(warnings))
1920 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[0].message)
1921 self.assertEqual(['test_grd/IDS_TEST2.png.sha1'], warnings[0].items)
1922
1923
1924 def testUnnecessaryScreenshots(self):
1925 # CL added a single message and added the png file, but not the sha1 file.
1926 input_api = self.makeInputApi([
1927 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS1,
1928 self.OLD_GRD_CONTENTS, action='M'),
1929 MockAffectedFile('test_grd/IDS_TEST1.png', 'binary', action='A')])
1930 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1931 MockOutputApi())
1932 self.assertEqual(2, len(warnings))
1933 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
1934 self.assertEqual(['test_grd/IDS_TEST1.png'], warnings[0].items)
1935 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
1936 self.assertEqual(['test_grd/IDS_TEST1.png.sha1'], warnings[1].items)
1937
1938 # CL added two messages, one has a png. Expect two messages:
1939 # - One for the unnecessary png.
1940 # - Another one for missing .sha1 files.
1941 input_api = self.makeInputApi([
1942 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
1943 self.OLD_GRD_CONTENTS, action='M'),
1944 MockAffectedFile('test_grd/IDS_TEST1.png', 'binary', action='A')])
1945 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1946 MockOutputApi())
1947 self.assertEqual(2, len(warnings))
1948 self.assertEqual(self.DO_NOT_UPLOAD_PNG_MESSAGE, warnings[0].message)
1949 self.assertEqual(['test_grd/IDS_TEST1.png'], warnings[0].items)
1950 self.assertEqual(self.GENERATE_SIGNATURES_MESSAGE, warnings[1].message)
1951 self.assertEqual(['test_grd/IDS_TEST1.png.sha1',
1952 'test_grd/IDS_TEST2.png.sha1'], warnings[1].items)
1953
1954 def testScreenshotsWithSha1(self):
1955 # CL added two messages and their corresponding .sha1 files. No warnings.
1956 input_api = self.makeInputApi([
1957 MockAffectedFile('test.grd', self.NEW_GRD_CONTENTS2,
1958 self.OLD_GRD_CONTENTS, action='M'),
1959 MockFile('test_grd/IDS_TEST1.png.sha1', 'binary', action='A'),
1960 MockFile('test_grd/IDS_TEST2.png.sha1', 'binary', action='A')])
1961 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1962 MockOutputApi())
1963 self.assertEqual([], warnings)
1964
1965 def testScreenshotsRemovedWithSha1(self):
1966 # Swap old contents with new contents, remove IDS_TEST1 and IDS_TEST2. The
1967 # sha1 files associated with the messages should also be removed by the CL.
1968 input_api = self.makeInputApi([
1969 MockAffectedFile('test.grd', self.OLD_GRD_CONTENTS,
1970 self.NEW_GRD_CONTENTS2, action='M'),
1971 MockFile('test_grd/IDS_TEST1.png.sha1', 'binary', ""),
1972 MockFile('test_grd/IDS_TEST2.png.sha1', 'binary', "")])
1973 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1974 MockOutputApi())
1975 self.assertEqual(1, len(warnings))
1976 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
1977 self.assertEqual(['test_grd/IDS_TEST1.png.sha1',
1978 'test_grd/IDS_TEST2.png.sha1'], warnings[0].items)
1979
1980 # Same as above, but this time one of the .sha1 files is removed.
1981 input_api = self.makeInputApi([
1982 MockAffectedFile('test.grd', self.OLD_GRD_CONTENTS,
1983 self.NEW_GRD_CONTENTS2, action='M'),
1984 MockFile('test_grd/IDS_TEST1.png.sha1', 'binary', ''),
1985 MockAffectedFile('test_grd/IDS_TEST2.png.sha1',
1986 '', 'old_contents', action='D')])
1987 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
1988 MockOutputApi())
1989 self.assertEqual(1, len(warnings))
1990 self.assertEqual(self.REMOVE_SIGNATURES_MESSAGE, warnings[0].message)
1991 self.assertEqual(['test_grd/IDS_TEST1.png.sha1'], warnings[0].items)
1992
1993 # Remove both sha1 files. No presubmit warnings.
1994 input_api = self.makeInputApi([
1995 MockAffectedFile('test.grd', self.OLD_GRD_CONTENTS,
1996 self.NEW_GRD_CONTENTS2, action='M'),
1997 MockFile('test_grd/IDS_TEST1.png.sha1', 'binary', action='D'),
1998 MockFile('test_grd/IDS_TEST2.png.sha1', 'binary', action='D')])
1999 warnings = PRESUBMIT._CheckTranslationScreenshots(input_api,
2000 MockOutputApi())
2001 self.assertEqual([], warnings)
2002
2003
[email protected]2299dcf2012-11-15 19:56:242004if __name__ == '__main__':
2005 unittest.main()