Use app list item shadow for app list folders.
[chromium-blink-merge.git] / chrome / browser / test_presubmit.py
blob3d2b0a6bca3d913ae29d6579980a05e2c9307a5f
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 ShouldFailExtraDotInGenericCheck(self, line):
252 """Checks that Array.< or Object.< is flagged as a style nit."""
253 error = self.checker.ExtraDotInGenericCheck(1, line)
254 self.assertNotEqual('', error)
255 self.assertTrue(GetHighlight(line, error).endswith(".<"))
257 def testExtraDotInGenericFails(self):
258 lines = [
259 "/** @private {!Array.<!Frobber>} */",
260 "var a = /** @type {Object.<number>} */({});",
261 "* @return {!Promise.<Change>}"
263 for line in lines:
264 self.ShouldFailExtraDotInGenericCheck(line)
266 def ShouldFailGetElementByIdCheck(self, line):
267 """Checks that the 'getElementById' checker flags |line| as a style
268 error.
270 error = self.checker.GetElementByIdCheck(1, line)
271 self.assertNotEqual('', error,
272 'Should be flagged as style error: ' + line)
273 self.assertEqual(GetHighlight(line, error), 'document.getElementById')
275 def ShouldPassGetElementByIdCheck(self, line):
276 """Checks that the 'getElementById' checker doesn't flag |line| as a style
277 error.
279 self.assertEqual('', self.checker.GetElementByIdCheck(1, line),
280 'Should not be flagged as style error: ' + line)
282 def testGetElementByIdFails(self):
283 lines = [
284 "document.getElementById('foo');",
285 " document.getElementById('foo');",
286 "var x = document.getElementById('foo');",
287 "if (document.getElementById('foo').hidden) {",
289 for line in lines:
290 self.ShouldFailGetElementByIdCheck(line)
292 def testGetElementByIdPasses(self):
293 lines = [
294 "elem.ownerDocument.getElementById('foo');",
295 " elem.ownerDocument.getElementById('foo');",
296 "var x = elem.ownerDocument.getElementById('foo');",
297 "if (elem.ownerDocument.getElementById('foo').hidden) {",
298 "doc.getElementById('foo');",
299 " doc.getElementById('foo');",
300 "cr.doc.getElementById('foo');",
301 " cr.doc.getElementById('foo');",
302 "var x = doc.getElementById('foo');",
303 "if (doc.getElementById('foo').hidden) {",
305 for line in lines:
306 self.ShouldPassGetElementByIdCheck(line)
308 def ShouldFailInheritDocCheck(self, line):
309 """Checks that the '@inheritDoc' checker flags |line| as a style error."""
310 error = self.checker.InheritDocCheck(1, line)
311 self.assertNotEqual('', error,
312 msg='Should be flagged as style error: ' + line)
313 self.assertEqual(GetHighlight(line, error), '@inheritDoc')
315 def ShouldPassInheritDocCheck(self, line):
316 """Checks that the '@inheritDoc' checker doesn't flag |line| as a style
317 error.
319 self.assertEqual('', self.checker.InheritDocCheck(1, line),
320 msg='Should not be flagged as style error: ' + line)
322 def testInheritDocFails(self):
323 lines = [
324 " /** @inheritDoc */",
325 " * @inheritDoc",
327 for line in lines:
328 self.ShouldFailInheritDocCheck(line)
330 def testInheritDocPasses(self):
331 lines = [
332 "And then I said, but I won't @inheritDoc! Hahaha!",
333 " If your dad's a doctor, do you inheritDoc?",
334 " What's up, inherit doc?",
335 " this.inheritDoc(someDoc)",
337 for line in lines:
338 self.ShouldPassInheritDocCheck(line)
340 def ShouldFailWrapperTypeCheck(self, line):
341 """Checks that the use of wrapper types (i.e. new Number(), @type {Number})
342 is a style error.
344 error = self.checker.WrapperTypeCheck(1, line)
345 self.assertNotEqual('', error,
346 msg='Should be flagged as style error: ' + line)
347 highlight = GetHighlight(line, error)
348 self.assertTrue(highlight in ('Boolean', 'Number', 'String'))
350 def ShouldPassWrapperTypeCheck(self, line):
351 """Checks that the wrapper type checker doesn't flag |line| as a style
352 error.
354 self.assertEqual('', self.checker.WrapperTypeCheck(1, line),
355 msg='Should not be flagged as style error: ' + line)
357 def testWrapperTypePasses(self):
358 lines = [
359 "/** @param {!ComplexType} */",
360 " * @type {Object}",
361 " * @param {Function=} opt_callback",
362 " * @param {} num Number of things to add to {blah}.",
363 " * @return {!print_preview.PageNumberSet}",
364 " /* @returns {Number} */", # Should be /** @return {Number} */
365 "* @param {!LocalStrings}"
366 " Your type of Boolean is false!",
367 " Then I parameterized her Number from her friend!",
368 " A String of Pearls",
369 " types.params.aBoolean.typeString(someNumber)",
371 for line in lines:
372 self.ShouldPassWrapperTypeCheck(line)
374 def testWrapperTypeFails(self):
375 lines = [
376 " /**@type {String}*/(string)",
377 " * @param{Number=} opt_blah A number",
378 "/** @private @return {!Boolean} */",
379 " * @param {number|String}",
381 for line in lines:
382 self.ShouldFailWrapperTypeCheck(line)
384 def ShouldFailVarNameCheck(self, line):
385 """Checks that var unix_hacker, $dollar are style errors."""
386 error = self.checker.VarNameCheck(1, line)
387 self.assertNotEqual('', error,
388 msg='Should be flagged as style error: ' + line)
389 highlight = GetHighlight(line, error)
390 self.assertFalse('var ' in highlight);
392 def ShouldPassVarNameCheck(self, line):
393 """Checks that variableNamesLikeThis aren't style errors."""
394 self.assertEqual('', self.checker.VarNameCheck(1, line),
395 msg='Should not be flagged as style error: ' + line)
397 def testVarNameFails(self):
398 lines = [
399 "var private_;",
400 " var _super_private",
401 " var unix_hacker = someFunc();",
403 for line in lines:
404 self.ShouldFailVarNameCheck(line)
406 def testVarNamePasses(self):
407 lines = [
408 " var namesLikeThis = [];",
409 " for (var i = 0; i < 10; ++i) { ",
410 "for (var i in obj) {",
411 " var one, two, three;",
412 " var magnumPI = {};",
413 " var g_browser = 'da browzer';",
414 "/** @const */ var Bla = options.Bla;", # goog.scope() replacement.
415 " var $ = function() {", # For legacy reasons.
416 " var StudlyCaps = cr.define('bla')", # Classes.
417 " var SCARE_SMALL_CHILDREN = [", # TODO(dbeam): add @const in
418 # front of all these vars like
419 "/** @const */ CONST_VAR = 1;", # this line has (<--).
421 for line in lines:
422 self.ShouldPassVarNameCheck(line)
425 class ClosureLintTest(SuperMoxTestBase):
426 def setUp(self):
427 SuperMoxTestBase.setUp(self)
429 input_api = self.mox.CreateMockAnything()
430 input_api.os_path = os.path
431 input_api.re = re
433 input_api.change = self.mox.CreateMockAnything()
434 self.mox.StubOutWithMock(input_api.change, 'RepositoryRoot')
435 src_root = os.path.join(os.path.dirname(__file__), '..', '..')
436 input_api.change.RepositoryRoot().MultipleTimes().AndReturn(src_root)
438 output_api = self.mox.CreateMockAnything()
440 self.mox.ReplayAll()
442 self.checker = js_checker.JSChecker(input_api, output_api)
444 def ShouldPassClosureLint(self, source):
445 errors = self.checker.ClosureLint('', source=source)
447 for error in errors:
448 print 'Error: ' + error.message
450 self.assertListEqual([], errors)
452 def testBindFalsePositives(self):
453 sources = [
455 'var addOne = function(prop) {\n',
456 ' this[prop] += 1;\n',
457 '}.bind(counter, timer);\n',
458 '\n',
459 'setInterval(addOne, 1000);\n',
460 '\n',
463 '/** Da clickz. */\n',
464 'button.onclick = function() { this.add_(this.total_); }.bind(this);\n',
467 for source in sources:
468 self.ShouldPassClosureLint(source)
470 def testPromiseFalsePositives(self):
471 sources = [
473 'Promise.reject(1).catch(function(error) {\n',
474 ' alert(error);\n',
475 '});\n',
478 'var loaded = new Promise();\n',
479 'loaded.then(runAwesomeApp);\n',
480 'loaded.catch(showSadFace);\n',
481 '\n',
482 '/** Da loadz. */\n',
483 'document.onload = function() { loaded.resolve(); };\n',
484 '\n',
485 '/** Da errorz. */\n',
486 'document.onerror = function() { loaded.reject(); };\n',
487 '\n',
488 "if (document.readystate == 'complete') loaded.resolve();\n",
491 for source in sources:
492 self.ShouldPassClosureLint(source)
495 class CssStyleGuideTest(SuperMoxTestBase):
496 def setUp(self):
497 SuperMoxTestBase.setUp(self)
499 self.fake_file_name = 'fake.css'
501 self.fake_file = self.mox.CreateMockAnything()
502 self.mox.StubOutWithMock(self.fake_file, 'LocalPath')
503 self.fake_file.LocalPath().AndReturn(self.fake_file_name)
504 # Actual calls to NewContents() are defined in each test.
505 self.mox.StubOutWithMock(self.fake_file, 'NewContents')
507 self.input_api = self.mox.CreateMockAnything()
508 self.input_api.re = re
509 self.mox.StubOutWithMock(self.input_api, 'AffectedSourceFiles')
510 self.input_api.AffectedFiles(
511 include_deletes=False, file_filter=None).AndReturn([self.fake_file])
513 # Actual creations of PresubmitPromptWarning are defined in each test.
514 self.output_api = self.mox.CreateMockAnything()
515 self.mox.StubOutWithMock(self.output_api, 'PresubmitPromptWarning',
516 use_mock_anything=True)
518 self.output_api = self.mox.CreateMockAnything()
519 self.mox.StubOutWithMock(self.output_api, 'PresubmitNotifyResult',
520 use_mock_anything=True)
522 def VerifyContentsIsValid(self, contents):
523 self.fake_file.NewContents().AndReturn(contents.splitlines())
524 self.mox.ReplayAll()
525 css_checker.CSSChecker(self.input_api, self.output_api).RunChecks()
527 def VerifyContentsProducesOutput(self, contents, output):
528 self.fake_file.NewContents().AndReturn(contents.splitlines())
529 author_msg = ('Was the CSS checker useful? '
530 'Send feedback or hate mail to dbeam@chromium.org.')
531 self.output_api.PresubmitNotifyResult(author_msg).AndReturn(None)
532 self.output_api.PresubmitPromptWarning(
533 self.fake_file_name + ':\n' + output.strip()).AndReturn(None)
534 self.mox.ReplayAll()
535 css_checker.CSSChecker(self.input_api, self.output_api).RunChecks()
537 def testCssAlphaWithAtBlock(self):
538 self.VerifyContentsProducesOutput("""
539 <include src="../shared/css/cr/ui/overlay.css">
540 <include src="chrome://resources/totally-cool.css" />
542 /* A hopefully safely ignored comment and @media statement. /**/
543 @media print {
544 div {
545 display: block;
546 color: red;
550 .rule {
551 z-index: 5;
552 <if expr="not is macosx">
553 background-image: url(chrome://resources/BLAH); /* TODO(dbeam): Fix this. */
554 background-color: rgb(235, 239, 249);
555 </if>
556 <if expr="is_macosx">
557 background-color: white;
558 background-image: url(chrome://resources/BLAH2);
559 </if>
560 color: black;
563 <if expr="is_macosx">
564 .language-options-right {
565 visibility: hidden;
566 opacity: 1; /* TODO(dbeam): Fix this. */
568 </if>""", """
569 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
570 display: block;
571 color: red;
573 z-index: 5;
574 color: black;""")
576 def testCssStringWithAt(self):
577 self.VerifyContentsIsValid("""
578 #logo {
579 background-image: url(images/google_logo.png@2x);
582 body.alternate-logo #logo {
583 -webkit-mask-image: url(images/google_logo.png@2x);
584 background: none;
587 .stuff1 {
590 .stuff2 {
592 """)
594 def testCssAlphaWithNonStandard(self):
595 self.VerifyContentsProducesOutput("""
596 div {
597 /* A hopefully safely ignored comment and @media statement. /**/
598 color: red;
599 -webkit-margin-start: 5px;
600 }""", """
601 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
602 color: red;
603 -webkit-margin-start: 5px;""")
605 def testCssAlphaWithLongerDashedProps(self):
606 self.VerifyContentsProducesOutput("""
607 div {
608 border-left: 5px; /* A hopefully removed comment. */
609 border: 5px solid red;
610 }""", """
611 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
612 border-left: 5px;
613 border: 5px solid red;""")
615 def testCssBracesHaveSpaceBeforeAndNothingAfter(self):
616 self.VerifyContentsProducesOutput("""
617 /* Hello! */div/* Comment here*/{
618 display: block;
621 blah /* hey! */
623 rule: value;
626 .this.is { /* allowed */
627 rule: value;
628 }""", """
629 - Start braces ({) end a selector, have a space before them and no rules after.
630 div{
631 {""")
633 def testCssClassesUseDashes(self):
634 self.VerifyContentsProducesOutput("""
635 .className,
636 .ClassName,
637 .class-name /* We should not catch this. */,
638 .class_name {
639 display: block;
640 }""", """
641 - Classes use .dash-form.
642 .className,
643 .ClassName,
644 .class_name {""")
646 def testCssCloseBraceOnNewLine(self):
647 self.VerifyContentsProducesOutput("""
648 @media { /* TODO(dbeam) Fix this case. */
649 .rule {
650 display: block;
653 @-webkit-keyframe blah {
654 from { height: rotate(-10turn); }
655 100% { height: 500px; }
658 #rule {
659 rule: value; }""", """
660 - Always put a rule closing brace (}) on a new line.
661 rule: value; }""")
663 def testCssColonsHaveSpaceAfter(self):
664 self.VerifyContentsProducesOutput("""
665 div:not(.class):not([attr=5]), /* We should not catch this. */
666 div:not(.class):not([attr]) /* Nor this. */ {
667 background: url(data:image/jpeg,asdfasdfsadf); /* Ignore this. */
668 background: -webkit-linear-gradient(left, red,
669 80% blah blee blar);
670 color: red;
671 display:block;
672 }""", """
673 - Colons (:) should have a space after them.
674 display:block;
676 - Don't use data URIs in source files. Use grit instead.
677 background: url(data:image/jpeg,asdfasdfsadf);""")
679 def testCssFavorSingleQuotes(self):
680 self.VerifyContentsProducesOutput("""
681 html[dir="rtl"] body,
682 html[dir=ltr] body /* TODO(dbeam): Require '' around rtl in future? */ {
683 font-family: "Open Sans";
684 <if expr="is_macosx">
685 blah: blee;
686 </if>
687 }""", """
688 - Use single quotes (') instead of double quotes (") in strings.
689 html[dir="rtl"] body,
690 font-family: "Open Sans";""")
692 def testCssHexCouldBeShorter(self):
693 self.VerifyContentsProducesOutput("""
694 #abc,
695 #abc-,
696 #abc-ghij,
697 #abcdef-,
698 #abcdef-ghij,
699 #aaaaaa,
700 #bbaacc {
701 background-color: #336699; /* Ignore short hex rule if not gray. */
702 color: #999999;
703 color: #666;
704 }""", """
705 - Use abbreviated hex (#rgb) when in form #rrggbb.
706 color: #999999; (replace with #999)
708 - Use rgb() over #hex when not a shade of gray (like #333).
709 background-color: #336699; (replace with rgb(51, 102, 153))""")
711 def testCssUseMillisecondsForSmallTimes(self):
712 self.VerifyContentsProducesOutput("""
713 .transition-0s /* This is gross but may happen. */ {
714 transform: one 0.2s;
715 transform: two .1s;
716 transform: tree 1s;
717 transform: four 300ms;
718 }""", """
719 - Use milliseconds for time measurements under 1 second.
720 transform: one 0.2s; (replace with 200ms)
721 transform: two .1s; (replace with 100ms)""")
723 def testCssNoDataUrisInSourceFiles(self):
724 self.VerifyContentsProducesOutput("""
725 img {
726 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
727 }""", """
728 - Don't use data URIs in source files. Use grit instead.
729 background: url( data:image/jpeg,4\/\/350|\/|3|2 );""")
731 def testCssNoQuotesInUrl(self):
732 self.VerifyContentsProducesOutput("""
733 img {
734 background: url('chrome://resources/images/blah.jpg');
735 background: url("../../folder/hello.png");
736 }""", """
737 - Use single quotes (') instead of double quotes (") in strings.
738 background: url("../../folder/hello.png");
740 - Don't use quotes in url().
741 background: url('chrome://resources/images/blah.jpg');
742 background: url("../../folder/hello.png");""")
744 def testCssOneRulePerLine(self):
745 self.VerifyContentsProducesOutput("""
746 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type,
747 a:not([hidden]):not(.custom-appearance):not([version=1]):first-of-type ~
748 input[type='checkbox']:not([hidden]),
749 div {
750 background: url(chrome://resources/BLAH);
751 rule: value; /* rule: value; */
752 rule: value; rule: value;
753 }""", """
754 - One rule per line (what not to do: color: red; margin: 0;).
755 rule: value; rule: value;""")
757 def testCssOneSelectorPerLine(self):
758 self.VerifyContentsProducesOutput("""
760 div,a,
761 div,/* Hello! */ span,
762 #id.class([dir=rtl):not(.class):any(a, b, d) {
763 rule: value;
767 div,a {
768 some-other: rule here;
769 }""", """
770 - One selector per line (what not to do: a, b {}).
771 div,a,
772 div, span,
773 div,a {""")
775 def testCssPseudoElementDoubleColon(self):
776 self.VerifyContentsProducesOutput("""
777 a:href,
778 br::after,
779 ::-webkit-scrollbar-thumb,
780 a:not([empty]):hover:focus:active, /* shouldn't catch here and above */
781 abbr:after,
782 .tree-label:empty:after,
783 b:before,
784 :-WebKit-ScrollBar {
785 rule: value;
786 }""", """
787 - Pseudo-elements should use double colon (i.e. ::after).
788 :after (should be ::after)
789 :after (should be ::after)
790 :before (should be ::before)
791 :-WebKit-ScrollBar (should be ::-WebKit-ScrollBar)
792 """)
794 def testCssRgbIfNotGray(self):
795 self.VerifyContentsProducesOutput("""
796 #abc,
797 #aaa,
798 #aabbcc {
799 background: -webkit-linear-gradient(left, from(#abc), to(#def));
800 color: #bad;
801 color: #bada55;
802 }""", """
803 - Use rgb() over #hex when not a shade of gray (like #333).
804 background: -webkit-linear-gradient(left, from(#abc), to(#def)); """
805 """(replace with rgb(170, 187, 204), rgb(221, 238, 255))
806 color: #bad; (replace with rgb(187, 170, 221))
807 color: #bada55; (replace with rgb(186, 218, 85))""")
809 def testWebkitBeforeOrAfter(self):
810 self.VerifyContentsProducesOutput("""
811 .test {
812 -webkit-margin-before: 10px;
813 -webkit-margin-start: 20px;
814 -webkit-padding-after: 3px;
815 -webkit-padding-end: 5px;
817 """, """
818 - Use *-top/bottom instead of -webkit-*-before/after.
819 -webkit-margin-before: 10px; (replace with margin-top)
820 -webkit-padding-after: 3px; (replace with padding-bottom)""")
822 def testCssZeroWidthLengths(self):
823 self.VerifyContentsProducesOutput("""
824 @-webkit-keyframe anim {
825 0% { /* Ignore key frames */
826 width: 0px;
828 10% {
829 width: 10px;
831 100% {
832 width: 100px;
836 #logo {
837 background-image: url(images/google_logo.png@2x);
840 body.alternate-logo #logo {
841 -webkit-mask-image: url(images/google_logo.png@2x);
844 /* http://crbug.com/359682 */
845 #spinner-container #spinner {
846 -webkit-animation-duration: 1.0s;
849 .media-button.play > .state0.active,
850 .media-button[state='0'] > .state0.normal /* blah */, /* blee */
851 .media-button[state='0']:not(.disabled):hover > .state0.hover {
852 -webkit-animation: anim 0s;
853 -webkit-animation-duration: anim 0ms;
854 -webkit-transform: scale(0%);
855 background-position-x: 0em;
856 background-position-y: 0ex;
857 border-width: 0em;
858 color: hsl(0, 0%, 85%); /* Shouldn't trigger error. */
859 opacity: .0;
860 opacity: 0.0;
861 opacity: 0.;
864 @page {
865 border-width: 0mm;
866 height: 0cm;
867 width: 0in;
868 }""", """
869 - Use "0" for zero-width lengths (i.e. 0px -> 0)
870 width: 0px;
871 -webkit-transform: scale(0%);
872 background-position-x: 0em;
873 background-position-y: 0ex;
874 border-width: 0em;
875 opacity: .0;
876 opacity: 0.0;
877 opacity: 0.;
878 border-width: 0mm;
879 height: 0cm;
880 width: 0in;
881 """)
883 if __name__ == '__main__':
884 unittest.main()