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 css_checker
, js_checker
# pylint: disable=F0401
24 class JsStyleGuideTest(SuperMoxTestBase
):
26 SuperMoxTestBase
.setUp(self
)
28 input_api
= self
.mox
.CreateMockAnything()
30 output_api
= self
.mox
.CreateMockAnything()
31 self
.checker
= js_checker
.JSChecker(input_api
, output_api
)
33 def GetHighlight(self
, line
, error
):
34 """Returns the substring of |line| that is highlighted in |error|."""
35 error_lines
= error
.split('\n')
36 highlight
= error_lines
[error_lines
.index(line
) + 1]
37 return ''.join(ch1
for (ch1
, ch2
) in zip(line
, highlight
) if ch2
== '^')
39 def ShouldFailConstCheck(self
, line
):
40 """Checks that the 'const' checker flags |line| as a style error."""
41 error
= self
.checker
.ConstCheck(1, line
)
42 self
.assertNotEqual('', error
,
43 'Should be flagged as style error: ' + line
)
44 self
.assertEqual(self
.GetHighlight(line
, error
), 'const')
46 def ShouldPassConstCheck(self
, line
):
47 """Checks that the 'const' checker doesn't flag |line| as a style error."""
48 self
.assertEqual('', self
.checker
.ConstCheck(1, line
),
49 'Should not be flagged as style error: ' + line
)
51 def testConstFails(self
):
54 " const bar = 'foo';",
56 # Trying to use |const| as a variable name
59 "var x = 5; const y = 6;",
60 "for (var i=0, const e=10; i<e; i++) {",
61 "for (const x=0; x<foo; i++) {",
62 "while (const x = 7) {",
65 self
.ShouldFailConstCheck(line
)
67 def testConstPasses(self
):
73 "/** @const */ var SEVEN = 7;",
75 # @const tag in multi-line comment
79 # @constructor tag in multi-line comment
83 # words containing 'const'
84 "if (foo.constructor) {",
85 "var deconstruction = 'something';",
86 "var madeUpWordconst = 10;",
88 # Strings containing the word |const|
89 "var str = 'const at the beginning';",
90 "var str = 'At the end: const';",
92 # doing this one with regex is probably not practical
93 #"var str = 'a const in the middle';",
96 self
.ShouldPassConstCheck(line
)
98 def ShouldFailChromeSendCheck(self
, line
):
99 """Checks that the 'chrome.send' checker flags |line| as a style error."""
100 error
= self
.checker
.ChromeSendCheck(1, line
)
101 self
.assertNotEqual('', error
,
102 'Should be flagged as style error: ' + line
)
103 self
.assertEqual(self
.GetHighlight(line
, error
), ', []')
105 def ShouldPassChromeSendCheck(self
, line
):
106 """Checks that the 'chrome.send' checker doesn't flag |line| as a style
109 self
.assertEqual('', self
.checker
.ChromeSendCheck(1, line
),
110 'Should not be flagged as style error: ' + line
)
112 def testChromeSendFails(self
):
114 "chrome.send('message', []);",
115 " chrome.send('message', []);",
118 self
.ShouldFailChromeSendCheck(line
)
120 def testChromeSendPasses(self
):
122 "chrome.send('message', constructArgs('foo', []));",
123 " chrome.send('message', constructArgs('foo', []));",
124 "chrome.send('message', constructArgs([]));",
125 " chrome.send('message', constructArgs([]));",
128 self
.ShouldPassChromeSendCheck(line
)
130 def ShouldFailGetElementByIdCheck(self
, line
):
131 """Checks that the 'getElementById' checker flags |line| as a style
134 error
= self
.checker
.GetElementByIdCheck(1, line
)
135 self
.assertNotEqual('', error
,
136 'Should be flagged as style error: ' + line
)
137 self
.assertEqual(self
.GetHighlight(line
, error
), 'document.getElementById')
139 def ShouldPassGetElementByIdCheck(self
, line
):
140 """Checks that the 'getElementById' checker doesn't flag |line| as a style
143 self
.assertEqual('', self
.checker
.GetElementByIdCheck(1, line
),
144 'Should not be flagged as style error: ' + line
)
146 def testGetElementByIdFails(self
):
148 "document.getElementById('foo');",
149 " document.getElementById('foo');",
150 "var x = document.getElementById('foo');",
151 "if (document.getElementById('foo').hidden) {",
154 self
.ShouldFailGetElementByIdCheck(line
)
156 def testGetElementByIdPasses(self
):
158 "elem.ownerDocument.getElementById('foo');",
159 " elem.ownerDocument.getElementById('foo');",
160 "var x = elem.ownerDocument.getElementById('foo');",
161 "if (elem.ownerDocument.getElementById('foo').hidden) {",
162 "doc.getElementById('foo');",
163 " doc.getElementById('foo');",
164 "cr.doc.getElementById('foo');",
165 " cr.doc.getElementById('foo');",
166 "var x = doc.getElementById('foo');",
167 "if (doc.getElementById('foo').hidden) {",
170 self
.ShouldPassGetElementByIdCheck(line
)
172 def ShouldFailInheritDocCheck(self
, line
):
173 """Checks that the '@inheritDoc' checker flags |line| as a style error."""
174 error
= self
.checker
.InheritDocCheck(1, line
)
175 self
.assertNotEqual('', error
,
176 msg
='Should be flagged as style error: ' + line
)
177 self
.assertEqual(self
.GetHighlight(line
, error
), '@inheritDoc')
179 def ShouldPassInheritDocCheck(self
, line
):
180 """Checks that the '@inheritDoc' checker doesn't flag |line| as a style
183 self
.assertEqual('', self
.checker
.InheritDocCheck(1, line
),
184 msg
='Should not be flagged as style error: ' + line
)
186 def testInheritDocFails(self
):
188 " /** @inheritDoc */",
192 self
.ShouldFailInheritDocCheck(line
)
194 def testInheritDocPasses(self
):
196 "And then I said, but I won't @inheritDoc! Hahaha!",
197 " If your dad's a doctor, do you inheritDoc?",
198 " What's up, inherit doc?",
199 " this.inheritDoc(someDoc)",
202 self
.ShouldPassInheritDocCheck(line
)
204 def ShouldFailWrapperTypeCheck(self
, line
):
205 """Checks that the use of wrapper types (i.e. new Number(), @type {Number})
208 error
= self
.checker
.WrapperTypeCheck(1, line
)
209 self
.assertNotEqual('', error
,
210 msg
='Should be flagged as style error: ' + line
)
211 highlight
= self
.GetHighlight(line
, error
)
212 self
.assertTrue(highlight
in ('Boolean', 'Number', 'String'))
214 def ShouldPassWrapperTypeCheck(self
, line
):
215 """Checks that the wrapper type checker doesn't flag |line| as a style
218 self
.assertEqual('', self
.checker
.WrapperTypeCheck(1, line
),
219 msg
='Should not be flagged as style error: ' + line
)
221 def testWrapperTypePasses(self
):
223 "/** @param {!ComplexType} */",
225 " * @param {Function=} opt_callback",
226 " * @param {} num Number of things to add to {blah}.",
227 " * @return {!print_preview.PageNumberSet}",
228 " /* @returns {Number} */", # Should be /** @return {Number} */
229 "* @param {!LocalStrings}"
230 " Your type of Boolean is false!",
231 " Then I parameterized her Number from her friend!",
232 " A String of Pearls",
233 " types.params.aBoolean.typeString(someNumber)",
236 self
.ShouldPassWrapperTypeCheck(line
)
238 def testWrapperTypeFails(self
):
240 " /**@type {String}*/(string)",
241 " * @param{Number=} opt_blah A number",
242 "/** @private @return {!Boolean} */",
243 " * @param {number|String}",
246 self
.ShouldFailWrapperTypeCheck(line
)
249 class CssStyleGuideTest(SuperMoxTestBase
):
251 SuperMoxTestBase
.setUp(self
)
253 self
.fake_file_name
= 'fake.css'
255 self
.fake_file
= self
.mox
.CreateMockAnything()
256 self
.mox
.StubOutWithMock(self
.fake_file
, 'LocalPath')
257 self
.fake_file
.LocalPath().AndReturn(self
.fake_file_name
)
258 # Actual calls to NewContents() are defined in each test.
259 self
.mox
.StubOutWithMock(self
.fake_file
, 'NewContents')
261 self
.input_api
= self
.mox
.CreateMockAnything()
262 self
.input_api
.re
= re
263 self
.mox
.StubOutWithMock(self
.input_api
, 'AffectedSourceFiles')
264 self
.input_api
.AffectedFiles(
265 include_deletes
=False, file_filter
=None).AndReturn([self
.fake_file
])
267 # Actual creations of PresubmitPromptWarning are defined in each test.
268 self
.output_api
= self
.mox
.CreateMockAnything()
269 self
.mox
.StubOutWithMock(self
.output_api
, 'PresubmitPromptWarning',
270 use_mock_anything
=True)
272 author_msg
= ('Was the CSS checker useful? '
273 'Send feedback or hate mail to dbeam@chromium.org.')
274 self
.output_api
= self
.mox
.CreateMockAnything()
275 self
.mox
.StubOutWithMock(self
.output_api
, 'PresubmitNotifyResult',
276 use_mock_anything
=True)
277 self
.output_api
.PresubmitNotifyResult(author_msg
).AndReturn(None)
279 def VerifyContentsProducesOutput(self
, contents
, output
):
280 self
.fake_file
.NewContents().AndReturn(contents
.splitlines())
281 self
.output_api
.PresubmitPromptWarning(
282 self
.fake_file_name
+ ':\n' + output
.strip()).AndReturn(None)
284 css_checker
.CSSChecker(self
.input_api
, self
.output_api
).RunChecks()
286 def testCssAlphaWithAtBlock(self
):
287 self
.VerifyContentsProducesOutput("""
288 <include src="../shared/css/cr/ui/overlay.css">
289 <include src="chrome://resources/totally-cool.css" />
291 /* A hopefully safely ignored comment and @media statement. /**/
301 <if expr="not is macosx">
302 background-image: url(chrome://resources/BLAH); /* TODO(dbeam): Fix this. */
303 background-color: rgb(235, 239, 249);
305 <if expr="is_macosx">
306 background-color: white;
307 background-image: url(chrome://resources/BLAH2);
312 <if expr="is_macosx">
313 .language-options-right {
315 opacity: 1; /* TODO(dbeam): Fix this. */
318 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
325 def testCssAlphaWithNonStandard(self
):
326 self
.VerifyContentsProducesOutput("""
328 /* A hopefully safely ignored comment and @media statement. /**/
330 -webkit-margin-start: 5px;
332 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
334 -webkit-margin-start: 5px;""")
336 def testCssAlphaWithLongerDashedProps(self
):
337 self
.VerifyContentsProducesOutput("""
339 border-left: 5px; /* A hopefully removed comment. */
340 border: 5px solid red;
342 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
344 border: 5px solid red;""")
346 def testCssBracesHaveSpaceBeforeAndNothingAfter(self
):
347 self
.VerifyContentsProducesOutput("""
348 /* Hello! */div/* Comment here*/{
357 .this.is { /* allowed */
360 - Start braces ({) end a selector, have a space before them and no rules after.
364 def testCssClassesUseDashes(self
):
365 self
.VerifyContentsProducesOutput("""
368 .class-name /* We should not catch this. */,
372 - Classes use .dash-form.
377 def testCssCloseBraceOnNewLine(self
):
378 self
.VerifyContentsProducesOutput("""
379 @media { /* TODO(dbeam) Fix this case. */
384 @-webkit-keyframe blah {
385 100% { height: -500px 0; }
389 rule: value; }""", """
390 - Always put a rule closing brace (}) on a new line.
393 def testCssColonsHaveSpaceAfter(self
):
394 self
.VerifyContentsProducesOutput("""
395 div:not(.class):not([attr=5]), /* We should not catch this. */
396 div:not(.class):not([attr]) /* Nor this. */ {
397 background: url(data:image/jpeg,asdfasdfsadf); /* Ignore this. */
398 background: -webkit-linear-gradient(left, red,
403 - Colons (:) should have a space after them.
406 - Don't use data URIs in source files. Use grit instead.
407 background: url(data:image/jpeg,asdfasdfsadf);""")
409 def testCssFavorSingleQuotes(self
):
410 self
.VerifyContentsProducesOutput("""
411 html[dir="rtl"] body,
412 html[dir=ltr] body /* TODO(dbeam): Require '' around rtl in future? */ {
413 background: url("chrome://resources/BLAH");
414 font-family: "Open Sans";
415 <if expr="is_macosx">
419 - Use single quotes (') instead of double quotes (") in strings.
420 html[dir="rtl"] body,
421 background: url("chrome://resources/BLAH");
422 font-family: "Open Sans";""")
424 def testCssHexCouldBeShorter(self
):
425 self
.VerifyContentsProducesOutput("""
433 background-color: #336699; /* Ignore short hex rule if not gray. */
437 - Use abbreviated hex (#rgb) when in form #rrggbb.
438 color: #999999; (replace with #999)
440 - Use rgb() over #hex when not a shade of gray (like #333).
441 background-color: #336699; (replace with rgb(51, 102, 153))""")
443 def testCssUseMillisecondsForSmallTimes(self
):
444 self
.VerifyContentsProducesOutput("""
445 .transition-0s /* This is gross but may happen. */ {
449 transform: four 300ms;
451 - Use milliseconds for time measurements under 1 second.
452 transform: one 0.2s; (replace with 200ms)
453 transform: two .1s; (replace with 100ms)""")
455 def testCssNoDataUrisInSourceFiles(self
):
456 self
.VerifyContentsProducesOutput("""
458 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
459 background: url('data:image/jpeg,4\/\/350|\/|3|2');
461 - Don't use data URIs in source files. Use grit instead.
462 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
463 background: url('data:image/jpeg,4\/\/350|\/|3|2');""")
465 def testCssOneRulePerLine(self
):
466 self
.VerifyContentsProducesOutput("""
467 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type,
468 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type ~
469 input[type='checkbox']:not([hidden]),
471 background: url(chrome://resources/BLAH);
472 rule: value; /* rule: value; */
473 rule: value; rule: value;
475 - One rule per line (what not to do: color: red; margin: 0;).
476 rule: value; rule: value;""")
478 def testCssOneSelectorPerLine(self
):
479 self
.VerifyContentsProducesOutput("""
482 div,/* Hello! */ span,
483 #id.class([dir=rtl):not(.class):any(a, b, d) {
489 some-other: rule here;
491 - One selector per line (what not to do: a, b {}).
496 def testCssPseudoElementDoubleColon(self
):
497 self
.VerifyContentsProducesOutput("""
500 ::-webkit-scrollbar-thumb,
501 a:not([empty]):hover:focus:active, /* shouldn't catch here and above */
503 .tree-label:empty:after,
508 - Pseudo-elements should use double colon (i.e. ::after).
509 :after (should be ::after)
510 :after (should be ::after)
511 :before (should be ::before)
512 :-WebKit-ScrollBar (should be ::-WebKit-ScrollBar)
515 def testCssRgbIfNotGray(self
):
516 self
.VerifyContentsProducesOutput("""
520 background: -webkit-linear-gradient(left, from(#abc), to(#def));
524 - Use rgb() over #hex when not a shade of gray (like #333).
525 background: -webkit-linear-gradient(left, from(#abc), to(#def)); """
526 """(replace with rgb(170, 187, 204), rgb(221, 238, 255))
527 color: #bad; (replace with rgb(187, 170, 221))
528 color: #bada55; (replace with rgb(186, 218, 85))""")
530 def testCssZeroLengthTerms(self
):
531 self
.VerifyContentsProducesOutput("""
532 @-webkit-keyframe anim {
533 0% { /* Ignore key frames */
544 .media-button.play > .state0.active,
545 .media-button[state='0'] > .state0.normal /* blah */, /* blee */
546 .media-button[state='0']:not(.disabled):hover > .state0.hover {
547 -webkit-animation: anim 0s;
548 -webkit-animation-duration: anim 0ms;
549 -webkit-transform: scale(0%),
553 background-position-x: 0em;
554 background-position-y: 0ex;
556 color: hsl(0, 0%, 85%); /* Shouldn't trigger error. */
567 - Make all zero length terms (i.e. 0px) 0 unless inside of hsl() or part of"""
570 -webkit-animation: anim 0s;
571 -webkit-animation-duration: anim 0ms;
572 -webkit-transform: scale(0%),
576 background-position-x: 0em;
577 background-position-y: 0ex;
587 if __name__
== '__main__':