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."""
13 test_dir
= os
.path
.dirname(os
.path
.abspath(__file__
))
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
):
33 SuperMoxTestBase
.setUp(self
)
35 input_api
= self
.mox
.CreateMockAnything()
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
):
59 self
.ShouldFailIncludeCheck(line
)
61 def testIncludePasses(self
):
63 '<include src="assert.js">',
64 "<include src='../../assert.js'>",
65 "<i>include src='blah'</i>",
70 self
.ShouldPassIncludeCheck(line
)
73 class JsStyleGuideTest(SuperMoxTestBase
):
75 SuperMoxTestBase
.setUp(self
)
77 input_api
= self
.mox
.CreateMockAnything()
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
):
97 " const bar = 'foo';",
99 # Trying to use |const| as a variable name
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) {",
108 self
.ShouldFailConstCheck(line
)
110 def testConstPasses(self
):
116 "/** @const */ var SEVEN = 7;",
118 # @const tag in multi-line comment
122 # @constructor tag in multi-line comment
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';",
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
152 self
.assertEqual('', self
.checker
.ChromeSendCheck(1, line
),
153 'Should not be flagged as style error: ' + line
)
155 def testChromeSendFails(self
):
157 "chrome.send('message', []);",
158 " chrome.send('message', []);",
161 self
.ShouldFailChromeSendCheck(line
)
163 def testChromeSendPasses(self
):
165 "chrome.send('message', constructArgs('foo', []));",
166 " chrome.send('message', constructArgs('foo', []));",
167 "chrome.send('message', constructArgs([]));",
168 " chrome.send('message', constructArgs([]));",
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
):
188 "/** @type {number} @const **/",
193 self
.ShouldFailEndJsDocCommentCheck(line
)
195 def testEndJsDocCommentPasses(self
):
197 "/***************/", # visual separators
198 " */", # valid JSDoc comment ends
200 "/**/", # funky multi-line comment enders
201 "/** @override */", # legit JSDoc one-liners
204 self
.ShouldPassEndJsDocCommentCheck(line
)
206 def ShouldFailGetElementByIdCheck(self
, line
):
207 """Checks that the 'getElementById' checker flags |line| as a style
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
219 self
.assertEqual('', self
.checker
.GetElementByIdCheck(1, line
),
220 'Should not be flagged as style error: ' + line
)
222 def testGetElementByIdFails(self
):
224 "document.getElementById('foo');",
225 " document.getElementById('foo');",
226 "var x = document.getElementById('foo');",
227 "if (document.getElementById('foo').hidden) {",
230 self
.ShouldFailGetElementByIdCheck(line
)
232 def testGetElementByIdPasses(self
):
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) {",
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
259 self
.assertEqual('', self
.checker
.InheritDocCheck(1, line
),
260 msg
='Should not be flagged as style error: ' + line
)
262 def testInheritDocFails(self
):
264 " /** @inheritDoc */",
268 self
.ShouldFailInheritDocCheck(line
)
270 def testInheritDocPasses(self
):
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)",
278 self
.ShouldPassInheritDocCheck(line
)
280 def ShouldFailWrapperTypeCheck(self
, line
):
281 """Checks that the use of wrapper types (i.e. new Number(), @type {Number})
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
294 self
.assertEqual('', self
.checker
.WrapperTypeCheck(1, line
),
295 msg
='Should not be flagged as style error: ' + line
)
297 def testWrapperTypePasses(self
):
299 "/** @param {!ComplexType} */",
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)",
312 self
.ShouldPassWrapperTypeCheck(line
)
314 def testWrapperTypeFails(self
):
316 " /**@type {String}*/(string)",
317 " * @param{Number=} opt_blah A number",
318 "/** @private @return {!Boolean} */",
319 " * @param {number|String}",
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
):
340 " var _super_private",
341 " var unix_hacker = someFunc();",
344 self
.ShouldFailVarNameCheck(line
)
346 def testVarNamePasses(self
):
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 (<--).
362 self
.ShouldPassVarNameCheck(line
)
365 class ClosureLintTest(SuperMoxTestBase
):
367 SuperMoxTestBase
.setUp(self
)
369 input_api
= self
.mox
.CreateMockAnything()
370 input_api
.os_path
= os
.path
373 input_api
.change
= self
.mox
.CreateMockAnything()
374 self
.mox
.StubOutWithMock(input_api
.change
, 'RepositoryRoot')
375 src_root
= os
.path
.join(os
.path
.dirname(__file__
), '..', '..')
376 input_api
.change
.RepositoryRoot().MultipleTimes().AndReturn(src_root
)
378 output_api
= self
.mox
.CreateMockAnything()
382 self
.checker
= js_checker
.JSChecker(input_api
, output_api
)
384 def ShouldPassClosureLint(self
, source
):
385 errors
= self
.checker
.ClosureLint('', source
=source
)
388 print 'Error: ' + error
.message
390 self
.assertListEqual([], errors
)
392 def testBindFalsePositives(self
):
395 'var addOne = function(prop) {\n',
396 ' this[prop] += 1;\n',
397 '}.bind(counter, timer);\n',
399 'setInterval(addOne, 1000);\n',
403 '/** Da clickz. */\n',
404 'button.onclick = function() { this.add_(this.total_); }.bind(this);\n',
407 for source
in sources
:
408 self
.ShouldPassClosureLint(source
)
410 def testPromiseFalsePositives(self
):
413 'Promise.reject(1).catch(function(error) {\n',
418 'var loaded = new Promise();\n',
419 'loaded.then(runAwesomeApp);\n',
420 'loaded.catch(showSadFace);\n',
422 '/** Da loadz. */\n',
423 'document.onload = function() { loaded.resolve(); };\n',
425 '/** Da errorz. */\n',
426 'document.onerror = function() { loaded.reject(); };\n',
428 "if (document.readystate == 'complete') loaded.resolve();\n",
431 for source
in sources
:
432 self
.ShouldPassClosureLint(source
)
435 class CssStyleGuideTest(SuperMoxTestBase
):
437 SuperMoxTestBase
.setUp(self
)
439 self
.fake_file_name
= 'fake.css'
441 self
.fake_file
= self
.mox
.CreateMockAnything()
442 self
.mox
.StubOutWithMock(self
.fake_file
, 'LocalPath')
443 self
.fake_file
.LocalPath().AndReturn(self
.fake_file_name
)
444 # Actual calls to NewContents() are defined in each test.
445 self
.mox
.StubOutWithMock(self
.fake_file
, 'NewContents')
447 self
.input_api
= self
.mox
.CreateMockAnything()
448 self
.input_api
.re
= re
449 self
.mox
.StubOutWithMock(self
.input_api
, 'AffectedSourceFiles')
450 self
.input_api
.AffectedFiles(
451 include_deletes
=False, file_filter
=None).AndReturn([self
.fake_file
])
453 # Actual creations of PresubmitPromptWarning are defined in each test.
454 self
.output_api
= self
.mox
.CreateMockAnything()
455 self
.mox
.StubOutWithMock(self
.output_api
, 'PresubmitPromptWarning',
456 use_mock_anything
=True)
458 self
.output_api
= self
.mox
.CreateMockAnything()
459 self
.mox
.StubOutWithMock(self
.output_api
, 'PresubmitNotifyResult',
460 use_mock_anything
=True)
462 def VerifyContentsIsValid(self
, contents
):
463 self
.fake_file
.NewContents().AndReturn(contents
.splitlines())
465 css_checker
.CSSChecker(self
.input_api
, self
.output_api
).RunChecks()
467 def VerifyContentsProducesOutput(self
, contents
, output
):
468 self
.fake_file
.NewContents().AndReturn(contents
.splitlines())
469 author_msg
= ('Was the CSS checker useful? '
470 'Send feedback or hate mail to dbeam@chromium.org.')
471 self
.output_api
.PresubmitNotifyResult(author_msg
).AndReturn(None)
472 self
.output_api
.PresubmitPromptWarning(
473 self
.fake_file_name
+ ':\n' + output
.strip()).AndReturn(None)
475 css_checker
.CSSChecker(self
.input_api
, self
.output_api
).RunChecks()
477 def testCssAlphaWithAtBlock(self
):
478 self
.VerifyContentsProducesOutput("""
479 <include src="../shared/css/cr/ui/overlay.css">
480 <include src="chrome://resources/totally-cool.css" />
482 /* A hopefully safely ignored comment and @media statement. /**/
492 <if expr="not is macosx">
493 background-image: url(chrome://resources/BLAH); /* TODO(dbeam): Fix this. */
494 background-color: rgb(235, 239, 249);
496 <if expr="is_macosx">
497 background-color: white;
498 background-image: url(chrome://resources/BLAH2);
503 <if expr="is_macosx">
504 .language-options-right {
506 opacity: 1; /* TODO(dbeam): Fix this. */
509 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
516 def testCssStringWithAt(self
):
517 self
.VerifyContentsIsValid("""
519 background-image: url('images/google_logo.png@2x');
522 body.alternate-logo #logo {
523 -webkit-mask-image: url('images/google_logo.png@2x');
534 def testCssAlphaWithNonStandard(self
):
535 self
.VerifyContentsProducesOutput("""
537 /* A hopefully safely ignored comment and @media statement. /**/
539 -webkit-margin-start: 5px;
541 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
543 -webkit-margin-start: 5px;""")
545 def testCssAlphaWithLongerDashedProps(self
):
546 self
.VerifyContentsProducesOutput("""
548 border-left: 5px; /* A hopefully removed comment. */
549 border: 5px solid red;
551 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
553 border: 5px solid red;""")
555 def testCssBracesHaveSpaceBeforeAndNothingAfter(self
):
556 self
.VerifyContentsProducesOutput("""
557 /* Hello! */div/* Comment here*/{
566 .this.is { /* allowed */
569 - Start braces ({) end a selector, have a space before them and no rules after.
573 def testCssClassesUseDashes(self
):
574 self
.VerifyContentsProducesOutput("""
577 .class-name /* We should not catch this. */,
581 - Classes use .dash-form.
586 def testCssCloseBraceOnNewLine(self
):
587 self
.VerifyContentsProducesOutput("""
588 @media { /* TODO(dbeam) Fix this case. */
593 @-webkit-keyframe blah {
594 100% { height: -500px 0; }
598 rule: value; }""", """
599 - Always put a rule closing brace (}) on a new line.
602 def testCssColonsHaveSpaceAfter(self
):
603 self
.VerifyContentsProducesOutput("""
604 div:not(.class):not([attr=5]), /* We should not catch this. */
605 div:not(.class):not([attr]) /* Nor this. */ {
606 background: url(data:image/jpeg,asdfasdfsadf); /* Ignore this. */
607 background: -webkit-linear-gradient(left, red,
612 - Colons (:) should have a space after them.
615 - Don't use data URIs in source files. Use grit instead.
616 background: url(data:image/jpeg,asdfasdfsadf);""")
618 def testCssFavorSingleQuotes(self
):
619 self
.VerifyContentsProducesOutput("""
620 html[dir="rtl"] body,
621 html[dir=ltr] body /* TODO(dbeam): Require '' around rtl in future? */ {
622 background: url("chrome://resources/BLAH");
623 font-family: "Open Sans";
624 <if expr="is_macosx">
628 - Use single quotes (') instead of double quotes (") in strings.
629 html[dir="rtl"] body,
630 background: url("chrome://resources/BLAH");
631 font-family: "Open Sans";""")
633 def testCssHexCouldBeShorter(self
):
634 self
.VerifyContentsProducesOutput("""
642 background-color: #336699; /* Ignore short hex rule if not gray. */
646 - Use abbreviated hex (#rgb) when in form #rrggbb.
647 color: #999999; (replace with #999)
649 - Use rgb() over #hex when not a shade of gray (like #333).
650 background-color: #336699; (replace with rgb(51, 102, 153))""")
652 def testCssUseMillisecondsForSmallTimes(self
):
653 self
.VerifyContentsProducesOutput("""
654 .transition-0s /* This is gross but may happen. */ {
658 transform: four 300ms;
660 - Use milliseconds for time measurements under 1 second.
661 transform: one 0.2s; (replace with 200ms)
662 transform: two .1s; (replace with 100ms)""")
664 def testCssNoDataUrisInSourceFiles(self
):
665 self
.VerifyContentsProducesOutput("""
667 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
668 background: url('data:image/jpeg,4\/\/350|\/|3|2');
670 - Don't use data URIs in source files. Use grit instead.
671 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
672 background: url('data:image/jpeg,4\/\/350|\/|3|2');""")
674 def testCssOneRulePerLine(self
):
675 self
.VerifyContentsProducesOutput("""
676 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type,
677 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type ~
678 input[type='checkbox']:not([hidden]),
680 background: url(chrome://resources/BLAH);
681 rule: value; /* rule: value; */
682 rule: value; rule: value;
684 - One rule per line (what not to do: color: red; margin: 0;).
685 rule: value; rule: value;""")
687 def testCssOneSelectorPerLine(self
):
688 self
.VerifyContentsProducesOutput("""
691 div,/* Hello! */ span,
692 #id.class([dir=rtl):not(.class):any(a, b, d) {
698 some-other: rule here;
700 - One selector per line (what not to do: a, b {}).
705 def testCssPseudoElementDoubleColon(self
):
706 self
.VerifyContentsProducesOutput("""
709 ::-webkit-scrollbar-thumb,
710 a:not([empty]):hover:focus:active, /* shouldn't catch here and above */
712 .tree-label:empty:after,
717 - Pseudo-elements should use double colon (i.e. ::after).
718 :after (should be ::after)
719 :after (should be ::after)
720 :before (should be ::before)
721 :-WebKit-ScrollBar (should be ::-WebKit-ScrollBar)
724 def testCssRgbIfNotGray(self
):
725 self
.VerifyContentsProducesOutput("""
729 background: -webkit-linear-gradient(left, from(#abc), to(#def));
733 - Use rgb() over #hex when not a shade of gray (like #333).
734 background: -webkit-linear-gradient(left, from(#abc), to(#def)); """
735 """(replace with rgb(170, 187, 204), rgb(221, 238, 255))
736 color: #bad; (replace with rgb(187, 170, 221))
737 color: #bada55; (replace with rgb(186, 218, 85))""")
739 def testCssZeroLengthTerms(self
):
740 self
.VerifyContentsProducesOutput("""
741 @-webkit-keyframe anim {
742 0% { /* Ignore key frames */
753 /* http://crbug.com/359682 */
754 #spinner-container #spinner {
755 -webkit-animation-duration: 1.0s;
758 .media-button.play > .state0.active,
759 .media-button[state='0'] > .state0.normal /* blah */, /* blee */
760 .media-button[state='0']:not(.disabled):hover > .state0.hover {
761 -webkit-animation: anim 0s;
762 -webkit-animation-duration: anim 0ms;
763 -webkit-transform: scale(0%),
767 background-position-x: 0em;
768 background-position-y: 0ex;
770 color: hsl(0, 0%, 85%); /* Shouldn't trigger error. */
781 - Make all zero length terms (i.e. 0px) 0 unless inside of hsl() or part of"""
784 -webkit-animation: anim 0s;
785 -webkit-animation-duration: anim 0ms;
786 -webkit-transform: scale(0%),
790 background-position-x: 0em;
791 background-position-y: 0ex;
801 if __name__
== '__main__':