Roll src/third_party/WebKit eb1578b:b559582 (svn 193425:193437)
[chromium-blink-merge.git] / chrome / browser / test_presubmit.py
blobac0e13b90a02258f14a6ed528451db866ef213e4
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 css_checker, html_checker, js_checker, \
22 resource_checker # pylint: disable=F0401
25 def GetHighlight(line, error):
26 """Returns the substring of |line| that is highlighted in |error|."""
27 error_lines = error.split('\n')
28 highlight = error_lines[error_lines.index(line) + 1]
29 return ''.join(ch1 for (ch1, ch2) in zip(line, highlight) if ch2 == '^')
32 class HtmlStyleTest(SuperMoxTestBase):
33 def setUp(self):
34 SuperMoxTestBase.setUp(self)
36 input_api = self.mox.CreateMockAnything()
37 input_api.re = re
38 output_api = self.mox.CreateMockAnything()
39 self.checker = html_checker.HtmlChecker(input_api, output_api)
41 def ShouldFailLabelCheck(self, line):
42 """Checks that the label checker flags |line| as a style error."""
43 error = self.checker.LabelCheck(1, line)
44 self.assertNotEqual('', error, 'Should be flagged as style error: ' + line)
45 highlight = GetHighlight(line, error).strip()
46 self.assertEqual('for=', highlight)
48 def ShouldPassLabelCheck(self, line):
49 """Checks that the label checker doesn't flag |line| as a style error."""
50 error = self.checker.LabelCheck(1, line)
51 self.assertEqual('', error, 'Should not be flagged as style error: ' + line)
53 def testForAttributeFails(self):
54 lines = [
55 " for=\"abc\"",
56 "for= ",
57 " \tfor= ",
58 " for="
60 for line in lines:
61 self.ShouldFailLabelCheck(line)
63 def testOtherAttributesPass(self):
64 lines = [
65 " my-for=\"abc\" ",
66 " myfor=\"abc\" ",
67 " <for",
69 for line in lines:
70 self.ShouldPassLabelCheck(line)
73 class ResourceStyleGuideTest(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 = resource_checker.ResourceChecker(input_api, output_api)
82 def ShouldFailIncludeCheck(self, line):
83 """Checks that the '</include>' checker flags |line| as a style error."""
84 error = self.checker.IncludeCheck(1, line)
85 self.assertNotEqual('', error,
86 'Should be flagged as style error: ' + line)
87 highlight = GetHighlight(line, error).strip()
88 self.assertTrue('include' in highlight and highlight[0] == '<')
90 def ShouldPassIncludeCheck(self, line):
91 """Checks that the '</include>' checker doesn't flag |line| as an error."""
92 self.assertEqual('', self.checker.IncludeCheck(1, line),
93 'Should not be flagged as style error: ' + line)
95 def testIncludeFails(self):
96 lines = [
97 "</include> ",
98 " </include>",
99 " </include> ",
100 ' <include src="blah.js" /> ',
101 '<include src="blee.js"/>',
103 for line in lines:
104 self.ShouldFailIncludeCheck(line)
106 def testIncludePasses(self):
107 lines = [
108 '<include src="assert.js">',
109 "<include src='../../assert.js'>",
110 "<i>include src='blah'</i>",
111 "</i>nclude",
112 "</i>include",
114 for line in lines:
115 self.ShouldPassIncludeCheck(line)
118 class JsStyleGuideTest(SuperMoxTestBase):
119 def setUp(self):
120 SuperMoxTestBase.setUp(self)
122 input_api = self.mox.CreateMockAnything()
123 input_api.re = re
124 output_api = self.mox.CreateMockAnything()
125 self.checker = js_checker.JSChecker(input_api, output_api)
127 def ShouldFailConstCheck(self, line):
128 """Checks that the 'const' checker flags |line| as a style error."""
129 error = self.checker.ConstCheck(1, line)
130 self.assertNotEqual('', error,
131 'Should be flagged as style error: ' + line)
132 self.assertEqual(GetHighlight(line, error), 'const')
134 def ShouldPassConstCheck(self, line):
135 """Checks that the 'const' checker doesn't flag |line| as a style error."""
136 self.assertEqual('', self.checker.ConstCheck(1, line),
137 'Should not be flagged as style error: ' + line)
139 def testConstFails(self):
140 lines = [
141 "const foo = 'bar';",
142 " const bar = 'foo';",
144 # Trying to use |const| as a variable name
145 "var const = 0;",
147 "var x = 5; const y = 6;",
148 "for (var i=0, const e=10; i<e; i++) {",
149 "for (const x=0; x<foo; i++) {",
150 "while (const x = 7) {",
152 for line in lines:
153 self.ShouldFailConstCheck(line)
155 def testConstPasses(self):
156 lines = [
157 # sanity check
158 "var foo = 'bar'",
160 # @const JsDoc tag
161 "/** @const */ var SEVEN = 7;",
163 # @const tag in multi-line comment
164 " * @const",
165 " * @const",
167 # @constructor tag in multi-line comment
168 " * @constructor",
169 " * @constructor",
171 # words containing 'const'
172 "if (foo.constructor) {",
173 "var deconstruction = 'something';",
174 "var madeUpWordconst = 10;",
176 # Strings containing the word |const|
177 "var str = 'const at the beginning';",
178 "var str = 'At the end: const';",
180 # doing this one with regex is probably not practical
181 #"var str = 'a const in the middle';",
183 for line in lines:
184 self.ShouldPassConstCheck(line)
186 def ShouldFailChromeSendCheck(self, line):
187 """Checks that the 'chrome.send' checker flags |line| as a style error."""
188 error = self.checker.ChromeSendCheck(1, line)
189 self.assertNotEqual('', error,
190 'Should be flagged as style error: ' + line)
191 self.assertEqual(GetHighlight(line, error), ', []')
193 def ShouldPassChromeSendCheck(self, line):
194 """Checks that the 'chrome.send' checker doesn't flag |line| as a style
195 error.
197 self.assertEqual('', self.checker.ChromeSendCheck(1, line),
198 'Should not be flagged as style error: ' + line)
200 def testChromeSendFails(self):
201 lines = [
202 "chrome.send('message', []);",
203 " chrome.send('message', []);",
205 for line in lines:
206 self.ShouldFailChromeSendCheck(line)
208 def testChromeSendPasses(self):
209 lines = [
210 "chrome.send('message', constructArgs('foo', []));",
211 " chrome.send('message', constructArgs('foo', []));",
212 "chrome.send('message', constructArgs([]));",
213 " chrome.send('message', constructArgs([]));",
215 for line in lines:
216 self.ShouldPassChromeSendCheck(line)
218 def ShouldFailEndJsDocCommentCheck(self, line):
219 """Checks that the **/ checker flags |line| as a style error."""
220 error = self.checker.EndJsDocCommentCheck(1, line)
221 self.assertNotEqual('', error,
222 'Should be flagged as style error: ' + line)
223 self.assertEqual(GetHighlight(line, error), '**/')
225 def ShouldPassEndJsDocCommentCheck(self, line):
226 """Checks that the **/ checker doesn't flag |line| as a style error."""
227 self.assertEqual('', self.checker.EndJsDocCommentCheck(1, line),
228 'Should not be flagged as style error: ' + line)
230 def testEndJsDocCommentFails(self):
231 lines = [
232 "/** @override **/",
233 "/** @type {number} @const **/",
234 " **/",
235 "**/ ",
237 for line in lines:
238 self.ShouldFailEndJsDocCommentCheck(line)
240 def testEndJsDocCommentPasses(self):
241 lines = [
242 "/***************/", # visual separators
243 " */", # valid JSDoc comment ends
244 "*/ ",
245 "/**/", # funky multi-line comment enders
246 "/** @override */", # legit JSDoc one-liners
248 for line in lines:
249 self.ShouldPassEndJsDocCommentCheck(line)
251 def ShouldFailGetElementByIdCheck(self, line):
252 """Checks that the 'getElementById' checker flags |line| as a style
253 error.
255 error = self.checker.GetElementByIdCheck(1, line)
256 self.assertNotEqual('', error,
257 'Should be flagged as style error: ' + line)
258 self.assertEqual(GetHighlight(line, error), 'document.getElementById')
260 def ShouldPassGetElementByIdCheck(self, line):
261 """Checks that the 'getElementById' checker doesn't flag |line| as a style
262 error.
264 self.assertEqual('', self.checker.GetElementByIdCheck(1, line),
265 'Should not be flagged as style error: ' + line)
267 def testGetElementByIdFails(self):
268 lines = [
269 "document.getElementById('foo');",
270 " document.getElementById('foo');",
271 "var x = document.getElementById('foo');",
272 "if (document.getElementById('foo').hidden) {",
274 for line in lines:
275 self.ShouldFailGetElementByIdCheck(line)
277 def testGetElementByIdPasses(self):
278 lines = [
279 "elem.ownerDocument.getElementById('foo');",
280 " elem.ownerDocument.getElementById('foo');",
281 "var x = elem.ownerDocument.getElementById('foo');",
282 "if (elem.ownerDocument.getElementById('foo').hidden) {",
283 "doc.getElementById('foo');",
284 " doc.getElementById('foo');",
285 "cr.doc.getElementById('foo');",
286 " cr.doc.getElementById('foo');",
287 "var x = doc.getElementById('foo');",
288 "if (doc.getElementById('foo').hidden) {",
290 for line in lines:
291 self.ShouldPassGetElementByIdCheck(line)
293 def ShouldFailInheritDocCheck(self, line):
294 """Checks that the '@inheritDoc' checker flags |line| as a style error."""
295 error = self.checker.InheritDocCheck(1, line)
296 self.assertNotEqual('', error,
297 msg='Should be flagged as style error: ' + line)
298 self.assertEqual(GetHighlight(line, error), '@inheritDoc')
300 def ShouldPassInheritDocCheck(self, line):
301 """Checks that the '@inheritDoc' checker doesn't flag |line| as a style
302 error.
304 self.assertEqual('', self.checker.InheritDocCheck(1, line),
305 msg='Should not be flagged as style error: ' + line)
307 def testInheritDocFails(self):
308 lines = [
309 " /** @inheritDoc */",
310 " * @inheritDoc",
312 for line in lines:
313 self.ShouldFailInheritDocCheck(line)
315 def testInheritDocPasses(self):
316 lines = [
317 "And then I said, but I won't @inheritDoc! Hahaha!",
318 " If your dad's a doctor, do you inheritDoc?",
319 " What's up, inherit doc?",
320 " this.inheritDoc(someDoc)",
322 for line in lines:
323 self.ShouldPassInheritDocCheck(line)
325 def ShouldFailWrapperTypeCheck(self, line):
326 """Checks that the use of wrapper types (i.e. new Number(), @type {Number})
327 is a style error.
329 error = self.checker.WrapperTypeCheck(1, line)
330 self.assertNotEqual('', error,
331 msg='Should be flagged as style error: ' + line)
332 highlight = GetHighlight(line, error)
333 self.assertTrue(highlight in ('Boolean', 'Number', 'String'))
335 def ShouldPassWrapperTypeCheck(self, line):
336 """Checks that the wrapper type checker doesn't flag |line| as a style
337 error.
339 self.assertEqual('', self.checker.WrapperTypeCheck(1, line),
340 msg='Should not be flagged as style error: ' + line)
342 def testWrapperTypePasses(self):
343 lines = [
344 "/** @param {!ComplexType} */",
345 " * @type {Object}",
346 " * @param {Function=} opt_callback",
347 " * @param {} num Number of things to add to {blah}.",
348 " * @return {!print_preview.PageNumberSet}",
349 " /* @returns {Number} */", # Should be /** @return {Number} */
350 "* @param {!LocalStrings}"
351 " Your type of Boolean is false!",
352 " Then I parameterized her Number from her friend!",
353 " A String of Pearls",
354 " types.params.aBoolean.typeString(someNumber)",
356 for line in lines:
357 self.ShouldPassWrapperTypeCheck(line)
359 def testWrapperTypeFails(self):
360 lines = [
361 " /**@type {String}*/(string)",
362 " * @param{Number=} opt_blah A number",
363 "/** @private @return {!Boolean} */",
364 " * @param {number|String}",
366 for line in lines:
367 self.ShouldFailWrapperTypeCheck(line)
369 def ShouldFailVarNameCheck(self, line):
370 """Checks that var unix_hacker, $dollar are style errors."""
371 error = self.checker.VarNameCheck(1, line)
372 self.assertNotEqual('', error,
373 msg='Should be flagged as style error: ' + line)
374 highlight = GetHighlight(line, error)
375 self.assertFalse('var ' in highlight);
377 def ShouldPassVarNameCheck(self, line):
378 """Checks that variableNamesLikeThis aren't style errors."""
379 self.assertEqual('', self.checker.VarNameCheck(1, line),
380 msg='Should not be flagged as style error: ' + line)
382 def testVarNameFails(self):
383 lines = [
384 "var private_;",
385 " var _super_private",
386 " var unix_hacker = someFunc();",
388 for line in lines:
389 self.ShouldFailVarNameCheck(line)
391 def testVarNamePasses(self):
392 lines = [
393 " var namesLikeThis = [];",
394 " for (var i = 0; i < 10; ++i) { ",
395 "for (var i in obj) {",
396 " var one, two, three;",
397 " var magnumPI = {};",
398 " var g_browser = 'da browzer';",
399 "/** @const */ var Bla = options.Bla;", # goog.scope() replacement.
400 " var $ = function() {", # For legacy reasons.
401 " var StudlyCaps = cr.define('bla')", # Classes.
402 " var SCARE_SMALL_CHILDREN = [", # TODO(dbeam): add @const in
403 # front of all these vars like
404 "/** @const */ CONST_VAR = 1;", # this line has (<--).
406 for line in lines:
407 self.ShouldPassVarNameCheck(line)
410 class ClosureLintTest(SuperMoxTestBase):
411 def setUp(self):
412 SuperMoxTestBase.setUp(self)
414 input_api = self.mox.CreateMockAnything()
415 input_api.os_path = os.path
416 input_api.re = re
418 input_api.change = self.mox.CreateMockAnything()
419 self.mox.StubOutWithMock(input_api.change, 'RepositoryRoot')
420 src_root = os.path.join(os.path.dirname(__file__), '..', '..')
421 input_api.change.RepositoryRoot().MultipleTimes().AndReturn(src_root)
423 output_api = self.mox.CreateMockAnything()
425 self.mox.ReplayAll()
427 self.checker = js_checker.JSChecker(input_api, output_api)
429 def ShouldPassClosureLint(self, source):
430 errors = self.checker.ClosureLint('', source=source)
432 for error in errors:
433 print 'Error: ' + error.message
435 self.assertListEqual([], errors)
437 def testBindFalsePositives(self):
438 sources = [
440 'var addOne = function(prop) {\n',
441 ' this[prop] += 1;\n',
442 '}.bind(counter, timer);\n',
443 '\n',
444 'setInterval(addOne, 1000);\n',
445 '\n',
448 '/** Da clickz. */\n',
449 'button.onclick = function() { this.add_(this.total_); }.bind(this);\n',
452 for source in sources:
453 self.ShouldPassClosureLint(source)
455 def testPromiseFalsePositives(self):
456 sources = [
458 'Promise.reject(1).catch(function(error) {\n',
459 ' alert(error);\n',
460 '});\n',
463 'var loaded = new Promise();\n',
464 'loaded.then(runAwesomeApp);\n',
465 'loaded.catch(showSadFace);\n',
466 '\n',
467 '/** Da loadz. */\n',
468 'document.onload = function() { loaded.resolve(); };\n',
469 '\n',
470 '/** Da errorz. */\n',
471 'document.onerror = function() { loaded.reject(); };\n',
472 '\n',
473 "if (document.readystate == 'complete') loaded.resolve();\n",
476 for source in sources:
477 self.ShouldPassClosureLint(source)
480 class CssStyleGuideTest(SuperMoxTestBase):
481 def setUp(self):
482 SuperMoxTestBase.setUp(self)
484 self.fake_file_name = 'fake.css'
486 self.fake_file = self.mox.CreateMockAnything()
487 self.mox.StubOutWithMock(self.fake_file, 'LocalPath')
488 self.fake_file.LocalPath().AndReturn(self.fake_file_name)
489 # Actual calls to NewContents() are defined in each test.
490 self.mox.StubOutWithMock(self.fake_file, 'NewContents')
492 self.input_api = self.mox.CreateMockAnything()
493 self.input_api.re = re
494 self.mox.StubOutWithMock(self.input_api, 'AffectedSourceFiles')
495 self.input_api.AffectedFiles(
496 include_deletes=False, file_filter=None).AndReturn([self.fake_file])
498 # Actual creations of PresubmitPromptWarning are defined in each test.
499 self.output_api = self.mox.CreateMockAnything()
500 self.mox.StubOutWithMock(self.output_api, 'PresubmitPromptWarning',
501 use_mock_anything=True)
503 self.output_api = self.mox.CreateMockAnything()
504 self.mox.StubOutWithMock(self.output_api, 'PresubmitNotifyResult',
505 use_mock_anything=True)
507 def VerifyContentsIsValid(self, contents):
508 self.fake_file.NewContents().AndReturn(contents.splitlines())
509 self.mox.ReplayAll()
510 css_checker.CSSChecker(self.input_api, self.output_api).RunChecks()
512 def VerifyContentsProducesOutput(self, contents, output):
513 self.fake_file.NewContents().AndReturn(contents.splitlines())
514 author_msg = ('Was the CSS checker useful? '
515 'Send feedback or hate mail to dbeam@chromium.org.')
516 self.output_api.PresubmitNotifyResult(author_msg).AndReturn(None)
517 self.output_api.PresubmitPromptWarning(
518 self.fake_file_name + ':\n' + output.strip()).AndReturn(None)
519 self.mox.ReplayAll()
520 css_checker.CSSChecker(self.input_api, self.output_api).RunChecks()
522 def testCssAlphaWithAtBlock(self):
523 self.VerifyContentsProducesOutput("""
524 <include src="../shared/css/cr/ui/overlay.css">
525 <include src="chrome://resources/totally-cool.css" />
527 /* A hopefully safely ignored comment and @media statement. /**/
528 @media print {
529 div {
530 display: block;
531 color: red;
535 .rule {
536 z-index: 5;
537 <if expr="not is macosx">
538 background-image: url(chrome://resources/BLAH); /* TODO(dbeam): Fix this. */
539 background-color: rgb(235, 239, 249);
540 </if>
541 <if expr="is_macosx">
542 background-color: white;
543 background-image: url(chrome://resources/BLAH2);
544 </if>
545 color: black;
548 <if expr="is_macosx">
549 .language-options-right {
550 visibility: hidden;
551 opacity: 1; /* TODO(dbeam): Fix this. */
553 </if>""", """
554 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
555 display: block;
556 color: red;
558 z-index: 5;
559 color: black;""")
561 def testCssStringWithAt(self):
562 self.VerifyContentsIsValid("""
563 #logo {
564 background-image: url(images/google_logo.png@2x);
567 body.alternate-logo #logo {
568 -webkit-mask-image: url(images/google_logo.png@2x);
569 background: none;
572 .stuff1 {
575 .stuff2 {
577 """)
579 def testCssAlphaWithNonStandard(self):
580 self.VerifyContentsProducesOutput("""
581 div {
582 /* A hopefully safely ignored comment and @media statement. /**/
583 color: red;
584 -webkit-margin-start: 5px;
585 }""", """
586 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
587 color: red;
588 -webkit-margin-start: 5px;""")
590 def testCssAlphaWithLongerDashedProps(self):
591 self.VerifyContentsProducesOutput("""
592 div {
593 border-left: 5px; /* A hopefully removed comment. */
594 border: 5px solid red;
595 }""", """
596 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
597 border-left: 5px;
598 border: 5px solid red;""")
600 def testCssBracesHaveSpaceBeforeAndNothingAfter(self):
601 self.VerifyContentsProducesOutput("""
602 /* Hello! */div/* Comment here*/{
603 display: block;
606 blah /* hey! */
608 rule: value;
611 .this.is { /* allowed */
612 rule: value;
613 }""", """
614 - Start braces ({) end a selector, have a space before them and no rules after.
615 div{
616 {""")
618 def testCssClassesUseDashes(self):
619 self.VerifyContentsProducesOutput("""
620 .className,
621 .ClassName,
622 .class-name /* We should not catch this. */,
623 .class_name {
624 display: block;
625 }""", """
626 - Classes use .dash-form.
627 .className,
628 .ClassName,
629 .class_name {""")
631 def testCssCloseBraceOnNewLine(self):
632 self.VerifyContentsProducesOutput("""
633 @media { /* TODO(dbeam) Fix this case. */
634 .rule {
635 display: block;
638 @-webkit-keyframe blah {
639 from { height: rotate(-10turn); }
640 100% { height: 500px; }
643 #rule {
644 rule: value; }""", """
645 - Always put a rule closing brace (}) on a new line.
646 rule: value; }""")
648 def testCssColonsHaveSpaceAfter(self):
649 self.VerifyContentsProducesOutput("""
650 div:not(.class):not([attr=5]), /* We should not catch this. */
651 div:not(.class):not([attr]) /* Nor this. */ {
652 background: url(data:image/jpeg,asdfasdfsadf); /* Ignore this. */
653 background: -webkit-linear-gradient(left, red,
654 80% blah blee blar);
655 color: red;
656 display:block;
657 }""", """
658 - Colons (:) should have a space after them.
659 display:block;
661 - Don't use data URIs in source files. Use grit instead.
662 background: url(data:image/jpeg,asdfasdfsadf);""")
664 def testCssFavorSingleQuotes(self):
665 self.VerifyContentsProducesOutput("""
666 html[dir="rtl"] body,
667 html[dir=ltr] body /* TODO(dbeam): Require '' around rtl in future? */ {
668 font-family: "Open Sans";
669 <if expr="is_macosx">
670 blah: blee;
671 </if>
672 }""", """
673 - Use single quotes (') instead of double quotes (") in strings.
674 html[dir="rtl"] body,
675 font-family: "Open Sans";""")
677 def testCssHexCouldBeShorter(self):
678 self.VerifyContentsProducesOutput("""
679 #abc,
680 #abc-,
681 #abc-ghij,
682 #abcdef-,
683 #abcdef-ghij,
684 #aaaaaa,
685 #bbaacc {
686 background-color: #336699; /* Ignore short hex rule if not gray. */
687 color: #999999;
688 color: #666;
689 }""", """
690 - Use abbreviated hex (#rgb) when in form #rrggbb.
691 color: #999999; (replace with #999)
693 - Use rgb() over #hex when not a shade of gray (like #333).
694 background-color: #336699; (replace with rgb(51, 102, 153))""")
696 def testCssUseMillisecondsForSmallTimes(self):
697 self.VerifyContentsProducesOutput("""
698 .transition-0s /* This is gross but may happen. */ {
699 transform: one 0.2s;
700 transform: two .1s;
701 transform: tree 1s;
702 transform: four 300ms;
703 }""", """
704 - Use milliseconds for time measurements under 1 second.
705 transform: one 0.2s; (replace with 200ms)
706 transform: two .1s; (replace with 100ms)""")
708 def testCssNoDataUrisInSourceFiles(self):
709 self.VerifyContentsProducesOutput("""
710 img {
711 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
712 }""", """
713 - Don't use data URIs in source files. Use grit instead.
714 background: url( data:image/jpeg,4\/\/350|\/|3|2 );""")
716 def testCssNoQuotesInUrl(self):
717 self.VerifyContentsProducesOutput("""
718 img {
719 background: url('chrome://resources/images/blah.jpg');
720 background: url("../../folder/hello.png");
721 }""", """
722 - Use single quotes (') instead of double quotes (") in strings.
723 background: url("../../folder/hello.png");
725 - Don't use quotes in url().
726 background: url('chrome://resources/images/blah.jpg');
727 background: url("../../folder/hello.png");""")
729 def testCssOneRulePerLine(self):
730 self.VerifyContentsProducesOutput("""
731 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type,
732 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type ~
733 input[type='checkbox']:not([hidden]),
734 div {
735 background: url(chrome://resources/BLAH);
736 rule: value; /* rule: value; */
737 rule: value; rule: value;
738 }""", """
739 - One rule per line (what not to do: color: red; margin: 0;).
740 rule: value; rule: value;""")
742 def testCssOneSelectorPerLine(self):
743 self.VerifyContentsProducesOutput("""
745 div,a,
746 div,/* Hello! */ span,
747 #id.class([dir=rtl):not(.class):any(a, b, d) {
748 rule: value;
752 div,a {
753 some-other: rule here;
754 }""", """
755 - One selector per line (what not to do: a, b {}).
756 div,a,
757 div, span,
758 div,a {""")
760 def testCssPseudoElementDoubleColon(self):
761 self.VerifyContentsProducesOutput("""
762 a:href,
763 br::after,
764 ::-webkit-scrollbar-thumb,
765 a:not([empty]):hover:focus:active, /* shouldn't catch here and above */
766 abbr:after,
767 .tree-label:empty:after,
768 b:before,
769 :-WebKit-ScrollBar {
770 rule: value;
771 }""", """
772 - Pseudo-elements should use double colon (i.e. ::after).
773 :after (should be ::after)
774 :after (should be ::after)
775 :before (should be ::before)
776 :-WebKit-ScrollBar (should be ::-WebKit-ScrollBar)
777 """)
779 def testCssRgbIfNotGray(self):
780 self.VerifyContentsProducesOutput("""
781 #abc,
782 #aaa,
783 #aabbcc {
784 background: -webkit-linear-gradient(left, from(#abc), to(#def));
785 color: #bad;
786 color: #bada55;
787 }""", """
788 - Use rgb() over #hex when not a shade of gray (like #333).
789 background: -webkit-linear-gradient(left, from(#abc), to(#def)); """
790 """(replace with rgb(170, 187, 204), rgb(221, 238, 255))
791 color: #bad; (replace with rgb(187, 170, 221))
792 color: #bada55; (replace with rgb(186, 218, 85))""")
794 def testWebkitBeforeOrAfter(self):
795 self.VerifyContentsProducesOutput("""
796 .test {
797 -webkit-margin-before: 10px;
798 -webkit-margin-start: 20px;
799 -webkit-padding-after: 3px;
800 -webkit-padding-end: 5px;
802 """, """
803 - Use *-top/bottom instead of -webkit-*-before/after.
804 -webkit-margin-before: 10px; (replace with margin-top)
805 -webkit-padding-after: 3px; (replace with padding-bottom)""")
807 def testCssZeroWidthLengths(self):
808 self.VerifyContentsProducesOutput("""
809 @-webkit-keyframe anim {
810 0% { /* Ignore key frames */
811 width: 0px;
813 10% {
814 width: 10px;
816 100% {
817 width: 100px;
821 #logo {
822 background-image: url(images/google_logo.png@2x);
825 body.alternate-logo #logo {
826 -webkit-mask-image: url(images/google_logo.png@2x);
829 /* http://crbug.com/359682 */
830 #spinner-container #spinner {
831 -webkit-animation-duration: 1.0s;
834 .media-button.play > .state0.active,
835 .media-button[state='0'] > .state0.normal /* blah */, /* blee */
836 .media-button[state='0']:not(.disabled):hover > .state0.hover {
837 -webkit-animation: anim 0s;
838 -webkit-animation-duration: anim 0ms;
839 -webkit-transform: scale(0%);
840 background-position-x: 0em;
841 background-position-y: 0ex;
842 border-width: 0em;
843 color: hsl(0, 0%, 85%); /* Shouldn't trigger error. */
844 opacity: .0;
845 opacity: 0.0;
846 opacity: 0.;
849 @page {
850 border-width: 0mm;
851 height: 0cm;
852 width: 0in;
853 }""", """
854 - Use "0" for zero-width lengths (i.e. 0px -> 0)
855 width: 0px;
856 -webkit-transform: scale(0%);
857 background-position-x: 0em;
858 background-position-y: 0ex;
859 border-width: 0em;
860 opacity: .0;
861 opacity: 0.0;
862 opacity: 0.;
863 border-width: 0mm;
864 height: 0cm;
865 width: 0in;
866 """)
868 if __name__ == '__main__':
869 unittest.main()