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 CssStyleGuideTest(SuperMoxTestBase
):
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)
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. /**/
417 <if expr="not is macosx">
418 background-image: url(chrome://resources/BLAH); /* TODO(dbeam): Fix this. */
419 background-color: rgb(235, 239, 249);
421 <if expr="is_macosx">
422 background-color: white;
423 background-image: url(chrome://resources/BLAH2);
428 <if expr="is_macosx">
429 .language-options-right {
431 opacity: 1; /* TODO(dbeam): Fix this. */
434 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
441 def testCssAlphaWithNonStandard(self
):
442 self
.VerifyContentsProducesOutput("""
444 /* A hopefully safely ignored comment and @media statement. /**/
446 -webkit-margin-start: 5px;
448 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
450 -webkit-margin-start: 5px;""")
452 def testCssAlphaWithLongerDashedProps(self
):
453 self
.VerifyContentsProducesOutput("""
455 border-left: 5px; /* A hopefully removed comment. */
456 border: 5px solid red;
458 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
460 border: 5px solid red;""")
462 def testCssBracesHaveSpaceBeforeAndNothingAfter(self
):
463 self
.VerifyContentsProducesOutput("""
464 /* Hello! */div/* Comment here*/{
473 .this.is { /* allowed */
476 - Start braces ({) end a selector, have a space before them and no rules after.
480 def testCssClassesUseDashes(self
):
481 self
.VerifyContentsProducesOutput("""
484 .class-name /* We should not catch this. */,
488 - Classes use .dash-form.
493 def testCssCloseBraceOnNewLine(self
):
494 self
.VerifyContentsProducesOutput("""
495 @media { /* TODO(dbeam) Fix this case. */
500 @-webkit-keyframe blah {
501 100% { height: -500px 0; }
505 rule: value; }""", """
506 - Always put a rule closing brace (}) on a new line.
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,
519 - Colons (:) should have a space after them.
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">
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("""
549 background-color: #336699; /* Ignore short hex rule if not gray. */
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. */ {
565 transform: four 300ms;
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("""
574 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
575 background: url('data:image/jpeg,4\/\/350|\/|3|2');
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]),
587 background: url(chrome://resources/BLAH);
588 rule: value; /* rule: value; */
589 rule: value; rule: value;
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("""
598 div,/* Hello! */ span,
599 #id.class([dir=rtl):not(.class):any(a, b, d) {
605 some-other: rule here;
607 - One selector per line (what not to do: a, b {}).
612 def testCssPseudoElementDoubleColon(self
):
613 self
.VerifyContentsProducesOutput("""
616 ::-webkit-scrollbar-thumb,
617 a:not([empty]):hover:focus:active, /* shouldn't catch here and above */
619 .tree-label:empty:after,
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)
631 def testCssRgbIfNotGray(self
):
632 self
.VerifyContentsProducesOutput("""
636 background: -webkit-linear-gradient(left, from(#abc), to(#def));
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 */
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%),
674 background-position-x: 0em;
675 background-position-y: 0ex;
677 color: hsl(0, 0%, 85%); /* Shouldn't trigger error. */
688 - Make all zero length terms (i.e. 0px) 0 unless inside of hsl() or part of"""
691 -webkit-animation: anim 0s;
692 -webkit-animation-duration: anim 0ms;
693 -webkit-transform: scale(0%),
697 background-position-x: 0em;
698 background-position-y: 0ex;
708 if __name__
== '__main__':