forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PRESUBMIT_test.py
executable file
·3809 lines (3430 loc) · 143 KB
/
PRESUBMIT_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os.path
import subprocess
import unittest
import PRESUBMIT
from PRESUBMIT_test_mocks import MockFile, MockAffectedFile
from PRESUBMIT_test_mocks import MockInputApi, MockOutputApi
_TEST_DATA_DIR = 'base/test/data/presubmit'
class VersionControlConflictsTest(unittest.TestCase):
def testTypicalConflict(self):
lines = ['<<<<<<< HEAD',
' base::ScopedTempDir temp_dir_;',
'=======',
' ScopedTempDir temp_dir_;',
'>>>>>>> master']
errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
self.assertEqual(3, len(errors))
self.assertTrue('1' in errors[0])
self.assertTrue('3' in errors[1])
self.assertTrue('5' in errors[2])
def testIgnoresReadmes(self):
lines = ['A First Level Header',
'====================',
'',
'A Second Level Header',
'---------------------']
errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
MockInputApi(), MockFile('some/polymer/README.md', lines))
self.assertEqual(0, len(errors))
class BadExtensionsTest(unittest.TestCase):
def testBadRejFile(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockFile('some/path/foo.cc', ''),
MockFile('some/path/foo.cc.rej', ''),
MockFile('some/path2/bar.h.rej', ''),
]
results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
self.assertEqual(1, len(results))
self.assertEqual(2, len(results[0].items))
self.assertTrue('foo.cc.rej' in results[0].items[0])
self.assertTrue('bar.h.rej' in results[0].items[1])
def testBadOrigFile(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockFile('other/path/qux.h.orig', ''),
MockFile('other/path/qux.h', ''),
MockFile('other/path/qux.cc', ''),
]
results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
self.assertEqual(1, len(results))
self.assertEqual(1, len(results[0].items))
self.assertTrue('qux.h.orig' in results[0].items[0])
def testGoodFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockFile('other/path/qux.h', ''),
MockFile('other/path/qux.cc', ''),
]
results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
self.assertEqual(0, len(results))
class CheckForSuperfluousStlIncludesInHeadersTest(unittest.TestCase):
def testGoodFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
# The check is not smart enough to figure out which definitions correspond
# to which header.
MockFile('other/path/foo.h',
['#include <string>',
'std::vector']),
# The check is not smart enough to do IWYU.
MockFile('other/path/bar.h',
['#include "base/check.h"',
'std::vector']),
MockFile('other/path/qux.h',
['#include "base/stl_util.h"',
'foobar']),
MockFile('other/path/baz.h',
['#include "set/vector.h"',
'bazzab']),
# The check is only for header files.
MockFile('other/path/not_checked.cc',
['#include <vector>',
'bazbaz']),
]
results = PRESUBMIT.CheckForSuperfluousStlIncludesInHeaders(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(results))
def testBadFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockFile('other/path/foo.h',
['#include <vector>',
'vector']),
MockFile('other/path/bar.h',
['#include <limits>',
'#include <set>',
'no_std_namespace']),
]
results = PRESUBMIT.CheckForSuperfluousStlIncludesInHeaders(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(results))
self.assertTrue('foo.h: Includes STL' in results[0].message)
self.assertTrue('bar.h: Includes STL' in results[0].message)
class CheckSingletonInHeadersTest(unittest.TestCase):
def testSingletonInArbitraryHeader(self):
diff_singleton_h = ['base::subtle::AtomicWord '
'base::Singleton<Type, Traits, DifferentiatingType>::']
diff_foo_h = ['// base::Singleton<Foo> in comment.',
'friend class base::Singleton<Foo>']
diff_foo2_h = [' //Foo* bar = base::Singleton<Foo>::get();']
diff_bad_h = ['Foo* foo = base::Singleton<Foo>::get();']
mock_input_api = MockInputApi()
mock_input_api.files = [MockAffectedFile('base/memory/singleton.h',
diff_singleton_h),
MockAffectedFile('foo.h', diff_foo_h),
MockAffectedFile('foo2.h', diff_foo2_h),
MockAffectedFile('bad.h', diff_bad_h)]
warnings = PRESUBMIT.CheckSingletonInHeaders(mock_input_api,
MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertEqual(1, len(warnings[0].items))
self.assertEqual('error', warnings[0].type)
self.assertTrue('Found base::Singleton<T>' in warnings[0].message)
def testSingletonInCC(self):
diff_cc = ['Foo* foo = base::Singleton<Foo>::get();']
mock_input_api = MockInputApi()
mock_input_api.files = [MockAffectedFile('some/path/foo.cc', diff_cc)]
warnings = PRESUBMIT.CheckSingletonInHeaders(mock_input_api,
MockOutputApi())
self.assertEqual(0, len(warnings))
class InvalidOSMacroNamesTest(unittest.TestCase):
def testInvalidOSMacroNames(self):
lines = ['#if defined(OS_WINDOWS)',
' #elif defined(OS_WINDOW)',
' # if defined(OS_MAC) || defined(OS_CHROME)',
'# else // defined(OS_MACOSX)',
'#endif // defined(OS_MACOS)']
errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
self.assertEqual(len(lines), len(errors))
self.assertTrue(':1 OS_WINDOWS' in errors[0])
self.assertTrue('(did you mean OS_WIN?)' in errors[0])
def testValidOSMacroNames(self):
lines = ['#if defined(%s)' % m for m in PRESUBMIT._VALID_OS_MACROS]
errors = PRESUBMIT._CheckForInvalidOSMacrosInFile(
MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
self.assertEqual(0, len(errors))
class InvalidIfDefinedMacroNamesTest(unittest.TestCase):
def testInvalidIfDefinedMacroNames(self):
lines = ['#if defined(TARGET_IPHONE_SIMULATOR)',
'#if !defined(TARGET_IPHONE_SIMULATOR)',
'#elif defined(TARGET_IPHONE_SIMULATOR)',
'#ifdef TARGET_IPHONE_SIMULATOR',
' # ifdef TARGET_IPHONE_SIMULATOR',
'# if defined(VALID) || defined(TARGET_IPHONE_SIMULATOR)',
'# else // defined(TARGET_IPHONE_SIMULATOR)',
'#endif // defined(TARGET_IPHONE_SIMULATOR)']
errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
MockInputApi(), MockFile('some/path/source.mm', lines))
self.assertEqual(len(lines), len(errors))
def testValidIfDefinedMacroNames(self):
lines = ['#if defined(FOO)',
'#ifdef BAR']
errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
MockInputApi(), MockFile('some/path/source.cc', lines))
self.assertEqual(0, len(errors))
class CheckAddedDepsHaveTestApprovalsTest(unittest.TestCase):
def calculate(self, old_include_rules, old_specific_include_rules,
new_include_rules, new_specific_include_rules):
return PRESUBMIT._CalculateAddedDeps(
os.path, 'include_rules = %r\nspecific_include_rules = %r' % (
old_include_rules, old_specific_include_rules),
'include_rules = %r\nspecific_include_rules = %r' % (
new_include_rules, new_specific_include_rules))
def testCalculateAddedDeps(self):
old_include_rules = [
'+base',
'-chrome',
'+content',
'-grit',
'-grit/",',
'+jni/fooblat.h',
'!sandbox',
]
old_specific_include_rules = {
'compositor\.*': {
'+cc',
},
}
new_include_rules = [
'-ash',
'+base',
'+chrome',
'+components',
'+content',
'+grit',
'+grit/generated_resources.h",',
'+grit/",',
'+jni/fooblat.h',
'+policy',
'+' + os.path.join('third_party', 'WebKit'),
]
new_specific_include_rules = {
'compositor\.*': {
'+cc',
},
'widget\.*': {
'+gpu',
},
}
expected = set([
os.path.join('chrome', 'DEPS'),
os.path.join('gpu', 'DEPS'),
os.path.join('components', 'DEPS'),
os.path.join('policy', 'DEPS'),
os.path.join('third_party', 'WebKit', 'DEPS'),
])
self.assertEqual(
expected,
self.calculate(old_include_rules, old_specific_include_rules,
new_include_rules, new_specific_include_rules))
def testCalculateAddedDepsIgnoresPermutations(self):
old_include_rules = [
'+base',
'+chrome',
]
new_include_rules = [
'+chrome',
'+base',
]
self.assertEqual(set(),
self.calculate(old_include_rules, {}, new_include_rules,
{}))
class JSONParsingTest(unittest.TestCase):
def testSuccess(self):
input_api = MockInputApi()
filename = 'valid_json.json'
contents = ['// This is a comment.',
'{',
' "key1": ["value1", "value2"],',
' "key2": 3 // This is an inline comment.',
'}'
]
input_api.files = [MockFile(filename, contents)]
self.assertEqual(None,
PRESUBMIT._GetJSONParseError(input_api, filename))
def testFailure(self):
input_api = MockInputApi()
test_data = [
('invalid_json_1.json',
['{ x }'],
'Expecting property name'),
('invalid_json_2.json',
['// Hello world!',
'{ "hello": "world }'],
'Unterminated string starting at:'),
('invalid_json_3.json',
['{ "a": "b", "c": "d", }'],
'Expecting property name'),
('invalid_json_4.json',
['{ "a": "b" "c": "d" }'],
"Expecting ',' delimiter:"),
]
input_api.files = [MockFile(filename, contents)
for (filename, contents, _) in test_data]
for (filename, _, expected_error) in test_data:
actual_error = PRESUBMIT._GetJSONParseError(input_api, filename)
self.assertTrue(expected_error in str(actual_error),
"'%s' not found in '%s'" % (expected_error, actual_error))
def testNoEatComments(self):
input_api = MockInputApi()
file_with_comments = 'file_with_comments.json'
contents_with_comments = ['// This is a comment.',
'{',
' "key1": ["value1", "value2"],',
' "key2": 3 // This is an inline comment.',
'}'
]
file_without_comments = 'file_without_comments.json'
contents_without_comments = ['{',
' "key1": ["value1", "value2"],',
' "key2": 3',
'}'
]
input_api.files = [MockFile(file_with_comments, contents_with_comments),
MockFile(file_without_comments,
contents_without_comments)]
self.assertNotEqual(None,
str(PRESUBMIT._GetJSONParseError(input_api,
file_with_comments,
eat_comments=False)))
self.assertEqual(None,
PRESUBMIT._GetJSONParseError(input_api,
file_without_comments,
eat_comments=False))
class IDLParsingTest(unittest.TestCase):
def testSuccess(self):
input_api = MockInputApi()
filename = 'valid_idl_basics.idl'
contents = ['// Tests a valid IDL file.',
'namespace idl_basics {',
' enum EnumType {',
' name1,',
' name2',
' };',
'',
' dictionary MyType1 {',
' DOMString a;',
' };',
'',
' callback Callback1 = void();',
' callback Callback2 = void(long x);',
' callback Callback3 = void(MyType1 arg);',
' callback Callback4 = void(EnumType type);',
'',
' interface Functions {',
' static void function1();',
' static void function2(long x);',
' static void function3(MyType1 arg);',
' static void function4(Callback1 cb);',
' static void function5(Callback2 cb);',
' static void function6(Callback3 cb);',
' static void function7(Callback4 cb);',
' };',
'',
' interface Events {',
' static void onFoo1();',
' static void onFoo2(long x);',
' static void onFoo2(MyType1 arg);',
' static void onFoo3(EnumType type);',
' };',
'};'
]
input_api.files = [MockFile(filename, contents)]
self.assertEqual(None,
PRESUBMIT._GetIDLParseError(input_api, filename))
def testFailure(self):
input_api = MockInputApi()
test_data = [
('invalid_idl_1.idl',
['//',
'namespace test {',
' dictionary {',
' DOMString s;',
' };',
'};'],
'Unexpected "{" after keyword "dictionary".\n'),
# TODO(yoz): Disabled because it causes the IDL parser to hang.
# See crbug.com/363830.
# ('invalid_idl_2.idl',
# (['namespace test {',
# ' dictionary MissingSemicolon {',
# ' DOMString a',
# ' DOMString b;',
# ' };',
# '};'],
# 'Unexpected symbol DOMString after symbol a.'),
('invalid_idl_3.idl',
['//',
'namespace test {',
' enum MissingComma {',
' name1',
' name2',
' };',
'};'],
'Unexpected symbol name2 after symbol name1.'),
('invalid_idl_4.idl',
['//',
'namespace test {',
' enum TrailingComma {',
' name1,',
' name2,',
' };',
'};'],
'Trailing comma in block.'),
('invalid_idl_5.idl',
['//',
'namespace test {',
' callback Callback1 = void(;',
'};'],
'Unexpected ";" after "(".'),
('invalid_idl_6.idl',
['//',
'namespace test {',
' callback Callback1 = void(long );',
'};'],
'Unexpected ")" after symbol long.'),
('invalid_idl_7.idl',
['//',
'namespace test {',
' interace Events {',
' static void onFoo1();',
' };',
'};'],
'Unexpected symbol Events after symbol interace.'),
('invalid_idl_8.idl',
['//',
'namespace test {',
' interface NotEvent {',
' static void onFoo1();',
' };',
'};'],
'Did not process Interface Interface(NotEvent)'),
('invalid_idl_9.idl',
['//',
'namespace test {',
' interface {',
' static void function1();',
' };',
'};'],
'Interface missing name.'),
]
input_api.files = [MockFile(filename, contents)
for (filename, contents, _) in test_data]
for (filename, _, expected_error) in test_data:
actual_error = PRESUBMIT._GetIDLParseError(input_api, filename)
self.assertTrue(expected_error in str(actual_error),
"'%s' not found in '%s'" % (expected_error, actual_error))
class UserMetricsActionTest(unittest.TestCase):
def testUserMetricsActionInActions(self):
input_api = MockInputApi()
file_with_user_action = 'file_with_user_action.cc'
contents_with_user_action = [
'base::UserMetricsAction("AboutChrome")'
]
input_api.files = [MockFile(file_with_user_action,
contents_with_user_action)]
self.assertEqual(
[], PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi()))
def testUserMetricsActionNotAddedToActions(self):
input_api = MockInputApi()
file_with_user_action = 'file_with_user_action.cc'
contents_with_user_action = [
'base::UserMetricsAction("NotInActionsXml")'
]
input_api.files = [MockFile(file_with_user_action,
contents_with_user_action)]
output = PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi())
self.assertEqual(
('File %s line %d: %s is missing in '
'tools/metrics/actions/actions.xml. Please run '
'tools/metrics/actions/extract_actions.py to update.'
% (file_with_user_action, 1, 'NotInActionsXml')),
output[0].message)
def testUserMetricsActionInTestFile(self):
input_api = MockInputApi()
file_with_user_action = 'file_with_user_action_unittest.cc'
contents_with_user_action = [
'base::UserMetricsAction("NotInActionsXml")'
]
input_api.files = [MockFile(file_with_user_action,
contents_with_user_action)]
self.assertEqual(
[], PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi()))
class PydepsNeedsUpdatingTest(unittest.TestCase):
class MockSubprocess(object):
CalledProcessError = subprocess.CalledProcessError
def _MockParseGclientArgs(self, is_android=True):
return lambda: {'checkout_android': 'true' if is_android else 'false' }
def setUp(self):
mock_all_pydeps = ['A.pydeps', 'B.pydeps', 'D.pydeps']
self.old_ALL_PYDEPS_FILES = PRESUBMIT._ALL_PYDEPS_FILES
PRESUBMIT._ALL_PYDEPS_FILES = mock_all_pydeps
mock_android_pydeps = ['D.pydeps']
self.old_ANDROID_SPECIFIC_PYDEPS_FILES = (
PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES)
PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES = mock_android_pydeps
self.old_ParseGclientArgs = PRESUBMIT._ParseGclientArgs
PRESUBMIT._ParseGclientArgs = self._MockParseGclientArgs()
self.mock_input_api = MockInputApi()
self.mock_output_api = MockOutputApi()
self.mock_input_api.subprocess = PydepsNeedsUpdatingTest.MockSubprocess()
self.checker = PRESUBMIT.PydepsChecker(self.mock_input_api, mock_all_pydeps)
self.checker._file_cache = {
'A.pydeps': '# Generated by:\n# CMD --output A.pydeps A\nA.py\nC.py\n',
'B.pydeps': '# Generated by:\n# CMD --output B.pydeps B\nB.py\nC.py\n',
'D.pydeps': '# Generated by:\n# CMD --output D.pydeps D\nD.py\n',
}
def tearDown(self):
PRESUBMIT._ALL_PYDEPS_FILES = self.old_ALL_PYDEPS_FILES
PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES = (
self.old_ANDROID_SPECIFIC_PYDEPS_FILES)
PRESUBMIT._ParseGclientArgs = self.old_ParseGclientArgs
def _RunCheck(self):
return PRESUBMIT.CheckPydepsNeedsUpdating(self.mock_input_api,
self.mock_output_api,
checker_for_tests=self.checker)
def testAddedPydep(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if self.mock_input_api.platform != 'linux2':
return []
self.mock_input_api.files = [
MockAffectedFile('new.pydeps', [], action='A'),
]
self.mock_input_api.CreateMockFileInPath(
[x.LocalPath() for x in self.mock_input_api.AffectedFiles(
include_deletes=True)])
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('PYDEPS_FILES', str(results[0]))
def testPydepNotInSrc(self):
self.mock_input_api.files = [
MockAffectedFile('new.pydeps', [], action='A'),
]
self.mock_input_api.CreateMockFileInPath([])
results = self._RunCheck()
self.assertEqual(0, len(results))
def testRemovedPydep(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if self.mock_input_api.platform != 'linux2':
return []
self.mock_input_api.files = [
MockAffectedFile(PRESUBMIT._ALL_PYDEPS_FILES[0], [], action='D'),
]
self.mock_input_api.CreateMockFileInPath(
[x.LocalPath() for x in self.mock_input_api.AffectedFiles(
include_deletes=True)])
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('PYDEPS_FILES', str(results[0]))
def testRandomPyIgnored(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if self.mock_input_api.platform != 'linux2':
return []
self.mock_input_api.files = [
MockAffectedFile('random.py', []),
]
results = self._RunCheck()
self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
def testRelevantPyNoChange(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if self.mock_input_api.platform != 'linux2':
return []
self.mock_input_api.files = [
MockAffectedFile('A.py', []),
]
def mock_check_output(cmd, shell=False, env=None):
self.assertEqual('CMD --output A.pydeps A --output ""', cmd)
return self.checker._file_cache['A.pydeps']
self.mock_input_api.subprocess.check_output = mock_check_output
results = self._RunCheck()
self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
def testRelevantPyOneChange(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if self.mock_input_api.platform != 'linux2':
return []
self.mock_input_api.files = [
MockAffectedFile('A.py', []),
]
def mock_check_output(cmd, shell=False, env=None):
self.assertEqual('CMD --output A.pydeps A --output ""', cmd)
return 'changed data'
self.mock_input_api.subprocess.check_output = mock_check_output
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('File is stale', str(results[0]))
def testRelevantPyTwoChanges(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if self.mock_input_api.platform != 'linux2':
return []
self.mock_input_api.files = [
MockAffectedFile('C.py', []),
]
def mock_check_output(cmd, shell=False, env=None):
return 'changed data'
self.mock_input_api.subprocess.check_output = mock_check_output
results = self._RunCheck()
self.assertEqual(2, len(results))
self.assertIn('File is stale', str(results[0]))
self.assertIn('File is stale', str(results[1]))
def testRelevantAndroidPyInNonAndroidCheckout(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if self.mock_input_api.platform != 'linux2':
return []
self.mock_input_api.files = [
MockAffectedFile('D.py', []),
]
def mock_check_output(cmd, shell=False, env=None):
self.assertEqual('CMD --output D.pydeps D --output ""', cmd)
return 'changed data'
self.mock_input_api.subprocess.check_output = mock_check_output
PRESUBMIT._ParseGclientArgs = self._MockParseGclientArgs(is_android=False)
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('Android', str(results[0]))
self.assertIn('D.pydeps', str(results[0]))
def testGnPathsAndMissingOutputFlag(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if self.mock_input_api.platform != 'linux2':
return []
self.checker._file_cache = {
'A.pydeps': '# Generated by:\n# CMD --gn-paths A\n//A.py\n//C.py\n',
'B.pydeps': '# Generated by:\n# CMD --gn-paths B\n//B.py\n//C.py\n',
'D.pydeps': '# Generated by:\n# CMD --gn-paths D\n//D.py\n',
}
self.mock_input_api.files = [
MockAffectedFile('A.py', []),
]
def mock_check_output(cmd, shell=False, env=None):
self.assertEqual('CMD --gn-paths A --output A.pydeps --output ""', cmd)
return 'changed data'
self.mock_input_api.subprocess.check_output = mock_check_output
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('File is stale', str(results[0]))
class IncludeGuardTest(unittest.TestCase):
def testIncludeGuardChecks(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('content/browser/thing/foo.h', [
'// Comment',
'#ifndef CONTENT_BROWSER_THING_FOO_H_',
'#define CONTENT_BROWSER_THING_FOO_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_THING_FOO_H_',
]),
MockAffectedFile('content/browser/thing/bar.h', [
'#ifndef CONTENT_BROWSER_THING_BAR_H_',
'#define CONTENT_BROWSER_THING_BAR_H_',
'namespace content {',
'#endif // CONTENT_BROWSER_THING_BAR_H_',
'} // namespace content',
]),
MockAffectedFile('content/browser/test1.h', [
'namespace content {',
'} // namespace content',
]),
MockAffectedFile('content\\browser\\win.h', [
'#ifndef CONTENT_BROWSER_WIN_H_',
'#define CONTENT_BROWSER_WIN_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_WIN_H_',
]),
MockAffectedFile('content/browser/test2.h', [
'// Comment',
'#ifndef CONTENT_BROWSER_TEST2_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_TEST2_H_',
]),
MockAffectedFile('content/browser/internal.h', [
'// Comment',
'#ifndef CONTENT_BROWSER_INTERNAL_H_',
'#define CONTENT_BROWSER_INTERNAL_H_',
'// Comment',
'#ifndef INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
'#define INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
'namespace internal {',
'} // namespace internal',
'#endif // INTERNAL_CONTENT_BROWSER_THING_BAR_H_',
'namespace content {',
'} // namespace content',
'#endif // CONTENT_BROWSER_THING_BAR_H_',
]),
MockAffectedFile('content/browser/thing/foo.cc', [
'// This is a non-header.',
]),
MockAffectedFile('content/browser/disabled.h', [
'// no-include-guard-because-multiply-included',
'struct McBoatFace;',
]),
# New files don't allow misspelled include guards.
MockAffectedFile('content/browser/spleling.h', [
'#ifndef CONTENT_BROWSER_SPLLEING_H_',
'#define CONTENT_BROWSER_SPLLEING_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_SPLLEING_H_',
]),
# New files don't allow + in include guards.
MockAffectedFile('content/browser/foo+bar.h', [
'#ifndef CONTENT_BROWSER_FOO+BAR_H_',
'#define CONTENT_BROWSER_FOO+BAR_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_FOO+BAR_H_',
]),
# Old files allow misspelled include guards (for now).
MockAffectedFile('chrome/old.h', [
'// New contents',
'#ifndef CHROME_ODL_H_',
'#define CHROME_ODL_H_',
'#endif // CHROME_ODL_H_',
], [
'// Old contents',
'#ifndef CHROME_ODL_H_',
'#define CHROME_ODL_H_',
'#endif // CHROME_ODL_H_',
]),
# Using a Blink style include guard outside Blink is wrong.
MockAffectedFile('content/NotInBlink.h', [
'#ifndef NotInBlink_h',
'#define NotInBlink_h',
'struct McBoatFace;',
'#endif // NotInBlink_h',
]),
# Using a Blink style include guard in Blink is no longer ok.
MockAffectedFile('third_party/blink/InBlink.h', [
'#ifndef InBlink_h',
'#define InBlink_h',
'struct McBoatFace;',
'#endif // InBlink_h',
]),
# Using a bad include guard in Blink is not ok.
MockAffectedFile('third_party/blink/AlsoInBlink.h', [
'#ifndef WrongInBlink_h',
'#define WrongInBlink_h',
'struct McBoatFace;',
'#endif // WrongInBlink_h',
]),
# Using a bad include guard in Blink is not accepted even if
# it's an old file.
MockAffectedFile('third_party/blink/StillInBlink.h', [
'// New contents',
'#ifndef AcceptedInBlink_h',
'#define AcceptedInBlink_h',
'struct McBoatFace;',
'#endif // AcceptedInBlink_h',
], [
'// Old contents',
'#ifndef AcceptedInBlink_h',
'#define AcceptedInBlink_h',
'struct McBoatFace;',
'#endif // AcceptedInBlink_h',
]),
# Using a non-Chromium include guard in third_party
# (outside blink) is accepted.
MockAffectedFile('third_party/foo/some_file.h', [
'#ifndef REQUIRED_RPCNDR_H_',
'#define REQUIRED_RPCNDR_H_',
'struct SomeFileFoo;',
'#endif // REQUIRED_RPCNDR_H_',
]),
# Not having proper include guard in *_message_generator.h
# for old IPC messages is allowed.
MockAffectedFile('content/common/content_message_generator.h', [
'#undef CONTENT_COMMON_FOO_MESSAGES_H_',
'#include "content/common/foo_messages.h"',
'#ifndef CONTENT_COMMON_FOO_MESSAGES_H_',
'#error "Failed to include content/common/foo_messages.h"',
'#endif',
]),
]
msgs = PRESUBMIT.CheckForIncludeGuards(
mock_input_api, mock_output_api)
expected_fail_count = 8
self.assertEqual(expected_fail_count, len(msgs),
'Expected %d items, found %d: %s'
% (expected_fail_count, len(msgs), msgs))
self.assertEqual(msgs[0].items, ['content/browser/thing/bar.h'])
self.assertEqual(msgs[0].message,
'Include guard CONTENT_BROWSER_THING_BAR_H_ '
'not covering the whole file')
self.assertEqual(msgs[1].items, ['content/browser/test1.h'])
self.assertEqual(msgs[1].message,
'Missing include guard CONTENT_BROWSER_TEST1_H_')
self.assertEqual(msgs[2].items, ['content/browser/test2.h:3'])
self.assertEqual(msgs[2].message,
'Missing "#define CONTENT_BROWSER_TEST2_H_" for '
'include guard')
self.assertEqual(msgs[3].items, ['content/browser/spleling.h:1'])
self.assertEqual(msgs[3].message,
'Header using the wrong include guard name '
'CONTENT_BROWSER_SPLLEING_H_')
self.assertEqual(msgs[4].items, ['content/browser/foo+bar.h'])
self.assertEqual(msgs[4].message,
'Missing include guard CONTENT_BROWSER_FOO_BAR_H_')
self.assertEqual(msgs[5].items, ['content/NotInBlink.h:1'])
self.assertEqual(msgs[5].message,
'Header using the wrong include guard name '
'NotInBlink_h')
self.assertEqual(msgs[6].items, ['third_party/blink/InBlink.h:1'])
self.assertEqual(msgs[6].message,
'Header using the wrong include guard name '
'InBlink_h')
self.assertEqual(msgs[7].items, ['third_party/blink/AlsoInBlink.h:1'])
self.assertEqual(msgs[7].message,
'Header using the wrong include guard name '
'WrongInBlink_h')
class AccessibilityRelnotesFieldTest(unittest.TestCase):
def testRelnotesPresent(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [MockAffectedFile('ui/accessibility/foo.bar', [''])]
mock_input_api.change.DescriptionText = lambda : 'Commit description'
mock_input_api.change.footers['AX-Relnotes'] = [
'Important user facing change']
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(0, len(msgs),
'Expected %d messages, found %d: %s'
% (0, len(msgs), msgs))
def testRelnotesMissingFromAccessibilityChange(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('some/file', ['']),
MockAffectedFile('ui/accessibility/foo.bar', ['']),
MockAffectedFile('some/other/file', [''])
]
mock_input_api.change.DescriptionText = lambda : 'Commit description'
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(1, len(msgs),
'Expected %d messages, found %d: %s'
% (1, len(msgs), msgs))
self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
'Missing AX-Relnotes field message not found in errors')
# The relnotes footer is not required for changes which do not touch any
# accessibility directories.
def testIgnoresNonAccesssibilityCode(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('some/file', ['']),
MockAffectedFile('some/other/file', [''])
]
mock_input_api.change.DescriptionText = lambda : 'Commit description'
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(0, len(msgs),
'Expected %d messages, found %d: %s'
% (0, len(msgs), msgs))
# Test that our presubmit correctly raises an error for a set of known paths.
def testExpectedPaths(self):
filesToTest = [
"chrome/browser/accessibility/foo.py",
"chrome/browser/ash/arc/accessibility/foo.cc",
"chrome/browser/ui/views/accessibility/foo.h",
"chrome/browser/extensions/api/automation/foo.h",
"chrome/browser/extensions/api/automation_internal/foo.cc",
"chrome/renderer/extensions/accessibility_foo.h",
"chrome/tests/data/accessibility/foo.html",
"content/browser/accessibility/foo.cc",
"content/renderer/accessibility/foo.h",
"content/tests/data/accessibility/foo.cc",
"extensions/renderer/api/automation/foo.h",
"ui/accessibility/foo/bar/baz.cc",
"ui/views/accessibility/foo/bar/baz.h",
]
for testFile in filesToTest:
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile(testFile, [''])
]
mock_input_api.change.DescriptionText = lambda : 'Commit description'
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(1, len(msgs),
'Expected %d messages, found %d: %s, for file %s'
% (1, len(msgs), msgs, testFile))
self.assertTrue("Missing 'AX-Relnotes:' field" in msgs[0].message,
('Missing AX-Relnotes field message not found in errors '
' for file %s' % (testFile)))
# Test that AX-Relnotes field can appear in the commit description (as long
# as it appears at the beginning of a line).
def testRelnotesInCommitDescription(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('ui/accessibility/foo.bar', ['']),
]
mock_input_api.change.DescriptionText = lambda : ('Description:\n' +
'AX-Relnotes: solves all accessibility issues forever')
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(0, len(msgs),
'Expected %d messages, found %d: %s'
% (0, len(msgs), msgs))
# Test that we don't match AX-Relnotes if it appears in the middle of a line.
def testRelnotesMustAppearAtBeginningOfLine(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()