Disable accessible touch exploration by default.
[chromium-blink-merge.git] / chrome / browser / test_presubmit.py
blob018991f0b7673cd7c69503f522d506b4189c5ef4
1 #!/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.
6 """Unit tests for Web Development Style Guide checker."""
8 import os
9 import re
10 import sys
11 import unittest
13 test_dir = os.path.dirname(os.path.abspath(__file__))
14 sys.path.extend([
15 os.path.normpath(os.path.join(test_dir, '..', '..', 'tools')),
16 os.path.join(test_dir),
19 import find_depot_tools # pylint: disable=W0611
20 from testing_support.super_mox import SuperMoxTestBase
21 from web_dev_style import resource_checker, css_checker, js_checker # pylint: disable=F0401
24 def GetHighlight(line, error):
25 """Returns the substring of |line| that is highlighted in |error|."""
26 error_lines = error.split('\n')
27 highlight = error_lines[error_lines.index(line) + 1]
28 return ''.join(ch1 for (ch1, ch2) in zip(line, highlight) if ch2 == '^')
31 class ResourceStyleGuideTest(SuperMoxTestBase):
32 def setUp(self):
33 SuperMoxTestBase.setUp(self)
35 input_api = self.mox.CreateMockAnything()
36 input_api.re = re
37 output_api = self.mox.CreateMockAnything()
38 self.checker = resource_checker.ResourceChecker(input_api, output_api)
40 def ShouldFailIncludeCheck(self, line):
41 """Checks that the '</include>' checker flags |line| as a style error."""
42 error = self.checker.IncludeCheck(1, line)
43 self.assertNotEqual('', error,
44 'Should be flagged as style error: ' + line)
45 self.assertEqual(GetHighlight(line, error), '</include>')
47 def ShouldPassIncludeCheck(self, line):
48 """Checks that the '</include>' checker doesn't flag |line| as an error."""
49 self.assertEqual('', self.checker.IncludeCheck(1, line),
50 'Should not be flagged as style error: ' + line)
52 def testIncludeFails(self):
53 lines = [
54 "</include> ",
55 " </include>",
56 " </include> ",
58 for line in lines:
59 self.ShouldFailIncludeCheck(line)
61 def testIncludePasses(self):
62 lines = [
63 '<include src="assert.js">',
64 "<include src='../../assert.js'>",
65 "<i>include src='blah'</i>",
66 "</i>nclude",
67 "</i>include",
69 for line in lines:
70 self.ShouldPassIncludeCheck(line)
73 class JsStyleGuideTest(SuperMoxTestBase):
74 def setUp(self):
75 SuperMoxTestBase.setUp(self)
77 input_api = self.mox.CreateMockAnything()
78 input_api.re = re
79 output_api = self.mox.CreateMockAnything()
80 self.checker = js_checker.JSChecker(input_api, output_api)
82 def ShouldFailConstCheck(self, line):
83 """Checks that the 'const' checker flags |line| as a style error."""
84 error = self.checker.ConstCheck(1, line)
85 self.assertNotEqual('', error,
86 'Should be flagged as style error: ' + line)
87 self.assertEqual(GetHighlight(line, error), 'const')
89 def ShouldPassConstCheck(self, line):
90 """Checks that the 'const' checker doesn't flag |line| as a style error."""
91 self.assertEqual('', self.checker.ConstCheck(1, line),
92 'Should not be flagged as style error: ' + line)
94 def testConstFails(self):
95 lines = [
96 "const foo = 'bar';",
97 " const bar = 'foo';",
99 # Trying to use |const| as a variable name
100 "var const = 0;",
102 "var x = 5; const y = 6;",
103 "for (var i=0, const e=10; i<e; i++) {",
104 "for (const x=0; x<foo; i++) {",
105 "while (const x = 7) {",
107 for line in lines:
108 self.ShouldFailConstCheck(line)
110 def testConstPasses(self):
111 lines = [
112 # sanity check
113 "var foo = 'bar'",
115 # @const JsDoc tag
116 "/** @const */ var SEVEN = 7;",
118 # @const tag in multi-line comment
119 " * @const",
120 " * @const",
122 # @constructor tag in multi-line comment
123 " * @constructor",
124 " * @constructor",
126 # words containing 'const'
127 "if (foo.constructor) {",
128 "var deconstruction = 'something';",
129 "var madeUpWordconst = 10;",
131 # Strings containing the word |const|
132 "var str = 'const at the beginning';",
133 "var str = 'At the end: const';",
135 # doing this one with regex is probably not practical
136 #"var str = 'a const in the middle';",
138 for line in lines:
139 self.ShouldPassConstCheck(line)
141 def ShouldFailChromeSendCheck(self, line):
142 """Checks that the 'chrome.send' checker flags |line| as a style error."""
143 error = self.checker.ChromeSendCheck(1, line)
144 self.assertNotEqual('', error,
145 'Should be flagged as style error: ' + line)
146 self.assertEqual(GetHighlight(line, error), ', []')
148 def ShouldPassChromeSendCheck(self, line):
149 """Checks that the 'chrome.send' checker doesn't flag |line| as a style
150 error.
152 self.assertEqual('', self.checker.ChromeSendCheck(1, line),
153 'Should not be flagged as style error: ' + line)
155 def testChromeSendFails(self):
156 lines = [
157 "chrome.send('message', []);",
158 " chrome.send('message', []);",
160 for line in lines:
161 self.ShouldFailChromeSendCheck(line)
163 def testChromeSendPasses(self):
164 lines = [
165 "chrome.send('message', constructArgs('foo', []));",
166 " chrome.send('message', constructArgs('foo', []));",
167 "chrome.send('message', constructArgs([]));",
168 " chrome.send('message', constructArgs([]));",
170 for line in lines:
171 self.ShouldPassChromeSendCheck(line)
173 def ShouldFailEndJsDocCommentCheck(self, line):
174 """Checks that the **/ checker flags |line| as a style error."""
175 error = self.checker.EndJsDocCommentCheck(1, line)
176 self.assertNotEqual('', error,
177 'Should be flagged as style error: ' + line)
178 self.assertEqual(GetHighlight(line, error), '**/')
180 def ShouldPassEndJsDocCommentCheck(self, line):
181 """Checks that the **/ checker doesn't flag |line| as a style error."""
182 self.assertEqual('', self.checker.EndJsDocCommentCheck(1, line),
183 'Should not be flagged as style error: ' + line)
185 def testEndJsDocCommentFails(self):
186 lines = [
187 "/** @override **/",
188 "/** @type {number} @const **/",
189 " **/",
190 "**/ ",
192 for line in lines:
193 self.ShouldFailEndJsDocCommentCheck(line)
195 def testEndJsDocCommentPasses(self):
196 lines = [
197 "/***************/", # visual separators
198 " */", # valid JSDoc comment ends
199 "*/ ",
200 "/**/", # funky multi-line comment enders
201 "/** @override */", # legit JSDoc one-liners
203 for line in lines:
204 self.ShouldPassEndJsDocCommentCheck(line)
206 def ShouldFailGetElementByIdCheck(self, line):
207 """Checks that the 'getElementById' checker flags |line| as a style
208 error.
210 error = self.checker.GetElementByIdCheck(1, line)
211 self.assertNotEqual('', error,
212 'Should be flagged as style error: ' + line)
213 self.assertEqual(GetHighlight(line, error), 'document.getElementById')
215 def ShouldPassGetElementByIdCheck(self, line):
216 """Checks that the 'getElementById' checker doesn't flag |line| as a style
217 error.
219 self.assertEqual('', self.checker.GetElementByIdCheck(1, line),
220 'Should not be flagged as style error: ' + line)
222 def testGetElementByIdFails(self):
223 lines = [
224 "document.getElementById('foo');",
225 " document.getElementById('foo');",
226 "var x = document.getElementById('foo');",
227 "if (document.getElementById('foo').hidden) {",
229 for line in lines:
230 self.ShouldFailGetElementByIdCheck(line)
232 def testGetElementByIdPasses(self):
233 lines = [
234 "elem.ownerDocument.getElementById('foo');",
235 " elem.ownerDocument.getElementById('foo');",
236 "var x = elem.ownerDocument.getElementById('foo');",
237 "if (elem.ownerDocument.getElementById('foo').hidden) {",
238 "doc.getElementById('foo');",
239 " doc.getElementById('foo');",
240 "cr.doc.getElementById('foo');",
241 " cr.doc.getElementById('foo');",
242 "var x = doc.getElementById('foo');",
243 "if (doc.getElementById('foo').hidden) {",
245 for line in lines:
246 self.ShouldPassGetElementByIdCheck(line)
248 def ShouldFailInheritDocCheck(self, line):
249 """Checks that the '@inheritDoc' checker flags |line| as a style error."""
250 error = self.checker.InheritDocCheck(1, line)
251 self.assertNotEqual('', error,
252 msg='Should be flagged as style error: ' + line)
253 self.assertEqual(GetHighlight(line, error), '@inheritDoc')
255 def ShouldPassInheritDocCheck(self, line):
256 """Checks that the '@inheritDoc' checker doesn't flag |line| as a style
257 error.
259 self.assertEqual('', self.checker.InheritDocCheck(1, line),
260 msg='Should not be flagged as style error: ' + line)
262 def testInheritDocFails(self):
263 lines = [
264 " /** @inheritDoc */",
265 " * @inheritDoc",
267 for line in lines:
268 self.ShouldFailInheritDocCheck(line)
270 def testInheritDocPasses(self):
271 lines = [
272 "And then I said, but I won't @inheritDoc! Hahaha!",
273 " If your dad's a doctor, do you inheritDoc?",
274 " What's up, inherit doc?",
275 " this.inheritDoc(someDoc)",
277 for line in lines:
278 self.ShouldPassInheritDocCheck(line)
280 def ShouldFailWrapperTypeCheck(self, line):
281 """Checks that the use of wrapper types (i.e. new Number(), @type {Number})
282 is a style error.
284 error = self.checker.WrapperTypeCheck(1, line)
285 self.assertNotEqual('', error,
286 msg='Should be flagged as style error: ' + line)
287 highlight = GetHighlight(line, error)
288 self.assertTrue(highlight in ('Boolean', 'Number', 'String'))
290 def ShouldPassWrapperTypeCheck(self, line):
291 """Checks that the wrapper type checker doesn't flag |line| as a style
292 error.
294 self.assertEqual('', self.checker.WrapperTypeCheck(1, line),
295 msg='Should not be flagged as style error: ' + line)
297 def testWrapperTypePasses(self):
298 lines = [
299 "/** @param {!ComplexType} */",
300 " * @type {Object}",
301 " * @param {Function=} opt_callback",
302 " * @param {} num Number of things to add to {blah}.",
303 " * @return {!print_preview.PageNumberSet}",
304 " /* @returns {Number} */", # Should be /** @return {Number} */
305 "* @param {!LocalStrings}"
306 " Your type of Boolean is false!",
307 " Then I parameterized her Number from her friend!",
308 " A String of Pearls",
309 " types.params.aBoolean.typeString(someNumber)",
311 for line in lines:
312 self.ShouldPassWrapperTypeCheck(line)
314 def testWrapperTypeFails(self):
315 lines = [
316 " /**@type {String}*/(string)",
317 " * @param{Number=} opt_blah A number",
318 "/** @private @return {!Boolean} */",
319 " * @param {number|String}",
321 for line in lines:
322 self.ShouldFailWrapperTypeCheck(line)
324 def ShouldFailVarNameCheck(self, line):
325 """Checks that var unix_hacker, $dollar are style errors."""
326 error = self.checker.VarNameCheck(1, line)
327 self.assertNotEqual('', error,
328 msg='Should be flagged as style error: ' + line)
329 highlight = GetHighlight(line, error)
330 self.assertFalse('var ' in highlight);
332 def ShouldPassVarNameCheck(self, line):
333 """Checks that variableNamesLikeThis aren't style errors."""
334 self.assertEqual('', self.checker.VarNameCheck(1, line),
335 msg='Should not be flagged as style error: ' + line)
337 def testVarNameFails(self):
338 lines = [
339 "var private_;",
340 " var _super_private",
341 " var unix_hacker = someFunc();",
343 for line in lines:
344 self.ShouldFailVarNameCheck(line)
346 def testVarNamePasses(self):
347 lines = [
348 " var namesLikeThis = [];",
349 " for (var i = 0; i < 10; ++i) { ",
350 "for (var i in obj) {",
351 " var one, two, three;",
352 " var magnumPI = {};",
353 " var g_browser = 'da browzer';",
354 "/** @const */ var Bla = options.Bla;", # goog.scope() replacement.
355 " var $ = function() {", # For legacy reasons.
356 " var StudlyCaps = cr.define('bla')", # Classes.
357 " var SCARE_SMALL_CHILDREN = [", # TODO(dbeam): add @const in
358 # front of all these vars like
359 "/** @const */ CONST_VAR = 1;", # this line has (<--).
361 for line in lines:
362 self.ShouldPassVarNameCheck(line)
365 class CssStyleGuideTest(SuperMoxTestBase):
366 def setUp(self):
367 SuperMoxTestBase.setUp(self)
369 self.fake_file_name = 'fake.css'
371 self.fake_file = self.mox.CreateMockAnything()
372 self.mox.StubOutWithMock(self.fake_file, 'LocalPath')
373 self.fake_file.LocalPath().AndReturn(self.fake_file_name)
374 # Actual calls to NewContents() are defined in each test.
375 self.mox.StubOutWithMock(self.fake_file, 'NewContents')
377 self.input_api = self.mox.CreateMockAnything()
378 self.input_api.re = re
379 self.mox.StubOutWithMock(self.input_api, 'AffectedSourceFiles')
380 self.input_api.AffectedFiles(
381 include_deletes=False, file_filter=None).AndReturn([self.fake_file])
383 # Actual creations of PresubmitPromptWarning are defined in each test.
384 self.output_api = self.mox.CreateMockAnything()
385 self.mox.StubOutWithMock(self.output_api, 'PresubmitPromptWarning',
386 use_mock_anything=True)
388 author_msg = ('Was the CSS checker useful? '
389 'Send feedback or hate mail to dbeam@chromium.org.')
390 self.output_api = self.mox.CreateMockAnything()
391 self.mox.StubOutWithMock(self.output_api, 'PresubmitNotifyResult',
392 use_mock_anything=True)
393 self.output_api.PresubmitNotifyResult(author_msg).AndReturn(None)
395 def VerifyContentsProducesOutput(self, contents, output):
396 self.fake_file.NewContents().AndReturn(contents.splitlines())
397 self.output_api.PresubmitPromptWarning(
398 self.fake_file_name + ':\n' + output.strip()).AndReturn(None)
399 self.mox.ReplayAll()
400 css_checker.CSSChecker(self.input_api, self.output_api).RunChecks()
402 def testCssAlphaWithAtBlock(self):
403 self.VerifyContentsProducesOutput("""
404 <include src="../shared/css/cr/ui/overlay.css">
405 <include src="chrome://resources/totally-cool.css" />
407 /* A hopefully safely ignored comment and @media statement. /**/
408 @media print {
409 div {
410 display: block;
411 color: red;
415 .rule {
416 z-index: 5;
417 <if expr="not is macosx">
418 background-image: url(chrome://resources/BLAH); /* TODO(dbeam): Fix this. */
419 background-color: rgb(235, 239, 249);
420 </if>
421 <if expr="is_macosx">
422 background-color: white;
423 background-image: url(chrome://resources/BLAH2);
424 </if>
425 color: black;
428 <if expr="is_macosx">
429 .language-options-right {
430 visibility: hidden;
431 opacity: 1; /* TODO(dbeam): Fix this. */
433 </if>""", """
434 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
435 display: block;
436 color: red;
438 z-index: 5;
439 color: black;""")
441 def testCssAlphaWithNonStandard(self):
442 self.VerifyContentsProducesOutput("""
443 div {
444 /* A hopefully safely ignored comment and @media statement. /**/
445 color: red;
446 -webkit-margin-start: 5px;
447 }""", """
448 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
449 color: red;
450 -webkit-margin-start: 5px;""")
452 def testCssAlphaWithLongerDashedProps(self):
453 self.VerifyContentsProducesOutput("""
454 div {
455 border-left: 5px; /* A hopefully removed comment. */
456 border: 5px solid red;
457 }""", """
458 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
459 border-left: 5px;
460 border: 5px solid red;""")
462 def testCssBracesHaveSpaceBeforeAndNothingAfter(self):
463 self.VerifyContentsProducesOutput("""
464 /* Hello! */div/* Comment here*/{
465 display: block;
468 blah /* hey! */
470 rule: value;
473 .this.is { /* allowed */
474 rule: value;
475 }""", """
476 - Start braces ({) end a selector, have a space before them and no rules after.
477 div{
478 {""")
480 def testCssClassesUseDashes(self):
481 self.VerifyContentsProducesOutput("""
482 .className,
483 .ClassName,
484 .class-name /* We should not catch this. */,
485 .class_name {
486 display: block;
487 }""", """
488 - Classes use .dash-form.
489 .className,
490 .ClassName,
491 .class_name {""")
493 def testCssCloseBraceOnNewLine(self):
494 self.VerifyContentsProducesOutput("""
495 @media { /* TODO(dbeam) Fix this case. */
496 .rule {
497 display: block;
500 @-webkit-keyframe blah {
501 100% { height: -500px 0; }
504 #rule {
505 rule: value; }""", """
506 - Always put a rule closing brace (}) on a new line.
507 rule: value; }""")
509 def testCssColonsHaveSpaceAfter(self):
510 self.VerifyContentsProducesOutput("""
511 div:not(.class):not([attr=5]), /* We should not catch this. */
512 div:not(.class):not([attr]) /* Nor this. */ {
513 background: url(data:image/jpeg,asdfasdfsadf); /* Ignore this. */
514 background: -webkit-linear-gradient(left, red,
515 80% blah blee blar);
516 color: red;
517 display:block;
518 }""", """
519 - Colons (:) should have a space after them.
520 display:block;
522 - Don't use data URIs in source files. Use grit instead.
523 background: url(data:image/jpeg,asdfasdfsadf);""")
525 def testCssFavorSingleQuotes(self):
526 self.VerifyContentsProducesOutput("""
527 html[dir="rtl"] body,
528 html[dir=ltr] body /* TODO(dbeam): Require '' around rtl in future? */ {
529 background: url("chrome://resources/BLAH");
530 font-family: "Open Sans";
531 <if expr="is_macosx">
532 blah: blee;
533 </if>
534 }""", """
535 - Use single quotes (') instead of double quotes (") in strings.
536 html[dir="rtl"] body,
537 background: url("chrome://resources/BLAH");
538 font-family: "Open Sans";""")
540 def testCssHexCouldBeShorter(self):
541 self.VerifyContentsProducesOutput("""
542 #abc,
543 #abc-,
544 #abc-ghij,
545 #abcdef-,
546 #abcdef-ghij,
547 #aaaaaa,
548 #bbaacc {
549 background-color: #336699; /* Ignore short hex rule if not gray. */
550 color: #999999;
551 color: #666;
552 }""", """
553 - Use abbreviated hex (#rgb) when in form #rrggbb.
554 color: #999999; (replace with #999)
556 - Use rgb() over #hex when not a shade of gray (like #333).
557 background-color: #336699; (replace with rgb(51, 102, 153))""")
559 def testCssUseMillisecondsForSmallTimes(self):
560 self.VerifyContentsProducesOutput("""
561 .transition-0s /* This is gross but may happen. */ {
562 transform: one 0.2s;
563 transform: two .1s;
564 transform: tree 1s;
565 transform: four 300ms;
566 }""", """
567 - Use milliseconds for time measurements under 1 second.
568 transform: one 0.2s; (replace with 200ms)
569 transform: two .1s; (replace with 100ms)""")
571 def testCssNoDataUrisInSourceFiles(self):
572 self.VerifyContentsProducesOutput("""
573 img {
574 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
575 background: url('data:image/jpeg,4\/\/350|\/|3|2');
576 }""", """
577 - Don't use data URIs in source files. Use grit instead.
578 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
579 background: url('data:image/jpeg,4\/\/350|\/|3|2');""")
581 def testCssOneRulePerLine(self):
582 self.VerifyContentsProducesOutput("""
583 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type,
584 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type ~
585 input[type='checkbox']:not([hidden]),
586 div {
587 background: url(chrome://resources/BLAH);
588 rule: value; /* rule: value; */
589 rule: value; rule: value;
590 }""", """
591 - One rule per line (what not to do: color: red; margin: 0;).
592 rule: value; rule: value;""")
594 def testCssOneSelectorPerLine(self):
595 self.VerifyContentsProducesOutput("""
597 div,a,
598 div,/* Hello! */ span,
599 #id.class([dir=rtl):not(.class):any(a, b, d) {
600 rule: value;
604 div,a {
605 some-other: rule here;
606 }""", """
607 - One selector per line (what not to do: a, b {}).
608 div,a,
609 div, span,
610 div,a {""")
612 def testCssPseudoElementDoubleColon(self):
613 self.VerifyContentsProducesOutput("""
614 a:href,
615 br::after,
616 ::-webkit-scrollbar-thumb,
617 a:not([empty]):hover:focus:active, /* shouldn't catch here and above */
618 abbr:after,
619 .tree-label:empty:after,
620 b:before,
621 :-WebKit-ScrollBar {
622 rule: value;
623 }""", """
624 - Pseudo-elements should use double colon (i.e. ::after).
625 :after (should be ::after)
626 :after (should be ::after)
627 :before (should be ::before)
628 :-WebKit-ScrollBar (should be ::-WebKit-ScrollBar)
629 """)
631 def testCssRgbIfNotGray(self):
632 self.VerifyContentsProducesOutput("""
633 #abc,
634 #aaa,
635 #aabbcc {
636 background: -webkit-linear-gradient(left, from(#abc), to(#def));
637 color: #bad;
638 color: #bada55;
639 }""", """
640 - Use rgb() over #hex when not a shade of gray (like #333).
641 background: -webkit-linear-gradient(left, from(#abc), to(#def)); """
642 """(replace with rgb(170, 187, 204), rgb(221, 238, 255))
643 color: #bad; (replace with rgb(187, 170, 221))
644 color: #bada55; (replace with rgb(186, 218, 85))""")
646 def testCssZeroLengthTerms(self):
647 self.VerifyContentsProducesOutput("""
648 @-webkit-keyframe anim {
649 0% { /* Ignore key frames */
650 width: 0px;
652 10% {
653 width: 10px;
655 100% {
656 width: 100px;
660 /* http://crbug.com/359682 */
661 #spinner-container #spinner {
662 -webkit-animation-duration: 1.0s;
665 .media-button.play > .state0.active,
666 .media-button[state='0'] > .state0.normal /* blah */, /* blee */
667 .media-button[state='0']:not(.disabled):hover > .state0.hover {
668 -webkit-animation: anim 0s;
669 -webkit-animation-duration: anim 0ms;
670 -webkit-transform: scale(0%),
671 translateX(0deg),
672 translateY(0rad),
673 translateZ(0grad);
674 background-position-x: 0em;
675 background-position-y: 0ex;
676 border-width: 0em;
677 color: hsl(0, 0%, 85%); /* Shouldn't trigger error. */
678 opacity: .0;
679 opacity: 0.0;
680 opacity: 0.;
683 @page {
684 border-width: 0mm;
685 height: 0cm;
686 width: 0in;
687 }""", """
688 - Make all zero length terms (i.e. 0px) 0 unless inside of hsl() or part of"""
689 """ @keyframe.
690 width: 0px;
691 -webkit-animation: anim 0s;
692 -webkit-animation-duration: anim 0ms;
693 -webkit-transform: scale(0%),
694 translateX(0deg),
695 translateY(0rad),
696 translateZ(0grad);
697 background-position-x: 0em;
698 background-position-y: 0ex;
699 border-width: 0em;
700 opacity: .0;
701 opacity: 0.0;
702 opacity: 0.;
703 border-width: 0mm;
704 height: 0cm;
705 width: 0in;
706 """)
708 if __name__ == '__main__':
709 unittest.main()