Updated drag and drop thumbnails.
[chromium-blink-merge.git] / chrome / browser / resources / test_presubmit.py
blob10e4292d57b93aaff393a8c7900c4a9ad90faea9
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, js_checker # pylint: disable=F0401
24 class JsStyleGuideTest(SuperMoxTestBase):
25 def setUp(self):
26 SuperMoxTestBase.setUp(self)
28 input_api = self.mox.CreateMockAnything()
29 input_api.re = re
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):
52 lines = [
53 "const foo = 'bar';",
54 " const bar = 'foo';",
56 # Trying to use |const| as a variable name
57 "var const = 0;",
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) {",
64 for line in lines:
65 self.ShouldFailConstCheck(line)
67 def testConstPasses(self):
68 lines = [
69 # sanity check
70 "var foo = 'bar'",
72 # @const JsDoc tag
73 "/** @const */ var SEVEN = 7;",
75 # @const tag in multi-line comment
76 " * @const",
77 " * @const",
79 # @constructor tag in multi-line comment
80 " * @constructor",
81 " * @constructor",
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';",
95 for line in lines:
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
107 error.
109 self.assertEqual('', self.checker.ChromeSendCheck(1, line),
110 'Should not be flagged as style error: ' + line)
112 def testChromeSendFails(self):
113 lines = [
114 "chrome.send('message', []);",
115 " chrome.send('message', []);",
117 for line in lines:
118 self.ShouldFailChromeSendCheck(line)
120 def testChromeSendPasses(self):
121 lines = [
122 "chrome.send('message', constructArgs('foo', []));",
123 " chrome.send('message', constructArgs('foo', []));",
124 "chrome.send('message', constructArgs([]));",
125 " chrome.send('message', constructArgs([]));",
127 for line in lines:
128 self.ShouldPassChromeSendCheck(line)
130 def ShouldFailGetElementByIdCheck(self, line):
131 """Checks that the 'getElementById' checker flags |line| as a style
132 error.
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
141 error.
143 self.assertEqual('', self.checker.GetElementByIdCheck(1, line),
144 'Should not be flagged as style error: ' + line)
146 def testGetElementByIdFails(self):
147 lines = [
148 "document.getElementById('foo');",
149 " document.getElementById('foo');",
150 "var x = document.getElementById('foo');",
151 "if (document.getElementById('foo').hidden) {",
153 for line in lines:
154 self.ShouldFailGetElementByIdCheck(line)
156 def testGetElementByIdPasses(self):
157 lines = [
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) {",
169 for line in lines:
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
181 error.
183 self.assertEqual('', self.checker.InheritDocCheck(1, line),
184 msg='Should not be flagged as style error: ' + line)
186 def testInheritDocFails(self):
187 lines = [
188 " /** @inheritDoc */",
189 " * @inheritDoc",
191 for line in lines:
192 self.ShouldFailInheritDocCheck(line)
194 def testInheritDocPasses(self):
195 lines = [
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)",
201 for line in lines:
202 self.ShouldPassInheritDocCheck(line)
204 def ShouldFailWrapperTypeCheck(self, line):
205 """Checks that the use of wrapper types (i.e. new Number(), @type {Number})
206 is a style error.
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
216 error.
218 self.assertEqual('', self.checker.WrapperTypeCheck(1, line),
219 msg='Should not be flagged as style error: ' + line)
221 def testWrapperTypePasses(self):
222 lines = [
223 "/** @param {!ComplexType} */",
224 " * @type {Object}",
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)",
235 for line in lines:
236 self.ShouldPassWrapperTypeCheck(line)
238 def testWrapperTypeFails(self):
239 lines = [
240 " /**@type {String}*/(string)",
241 " * @param{Number=} opt_blah A number",
242 "/** @private @return {!Boolean} */",
243 " * @param {number|String}",
245 for line in lines:
246 self.ShouldFailWrapperTypeCheck(line)
249 class CssStyleGuideTest(SuperMoxTestBase):
250 def setUp(self):
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)
283 self.mox.ReplayAll()
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. /**/
292 @media print {
293 div {
294 display: block;
295 color: red;
299 .rule {
300 z-index: 5;
301 <if expr="not is macosx">
302 background-image: url(chrome://resources/BLAH); /* TODO(dbeam): Fix this. */
303 background-color: rgb(235, 239, 249);
304 </if>
305 <if expr="is_macosx">
306 background-color: white;
307 background-image: url(chrome://resources/BLAH2);
308 </if>
309 color: black;
312 <if expr="is_macosx">
313 .language-options-right {
314 visibility: hidden;
315 opacity: 1; /* TODO(dbeam): Fix this. */
317 </if>""", """
318 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
319 display: block;
320 color: red;
322 z-index: 5;
323 color: black;""")
325 def testCssAlphaWithNonStandard(self):
326 self.VerifyContentsProducesOutput("""
327 div {
328 /* A hopefully safely ignored comment and @media statement. /**/
329 color: red;
330 -webkit-margin-start: 5px;
331 }""", """
332 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
333 color: red;
334 -webkit-margin-start: 5px;""")
336 def testCssAlphaWithLongerDashedProps(self):
337 self.VerifyContentsProducesOutput("""
338 div {
339 border-left: 5px; /* A hopefully removed comment. */
340 border: 5px solid red;
341 }""", """
342 - Alphabetize properties and list vendor specific (i.e. -webkit) above standard.
343 border-left: 5px;
344 border: 5px solid red;""")
346 def testCssBracesHaveSpaceBeforeAndNothingAfter(self):
347 self.VerifyContentsProducesOutput("""
348 /* Hello! */div/* Comment here*/{
349 display: block;
352 blah /* hey! */
354 rule: value;
357 .this.is { /* allowed */
358 rule: value;
359 }""", """
360 - Start braces ({) end a selector, have a space before them and no rules after.
361 div{
362 {""")
364 def testCssClassesUseDashes(self):
365 self.VerifyContentsProducesOutput("""
366 .className,
367 .ClassName,
368 .class-name /* We should not catch this. */,
369 .class_name {
370 display: block;
371 }""", """
372 - Classes use .dash-form.
373 .className,
374 .ClassName,
375 .class_name {""")
377 def testCssCloseBraceOnNewLine(self):
378 self.VerifyContentsProducesOutput("""
379 @media { /* TODO(dbeam) Fix this case. */
380 .rule {
381 display: block;
384 @-webkit-keyframe blah {
385 100% { height: -500px 0; }
388 #rule {
389 rule: value; }""", """
390 - Always put a rule closing brace (}) on a new line.
391 rule: value; }""")
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,
399 80% blah blee blar);
400 color: red;
401 display:block;
402 }""", """
403 - Colons (:) should have a space after them.
404 display:block;
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">
416 blah: blee;
417 </if>
418 }""", """
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("""
426 #abc,
427 #abc-,
428 #abc-ghij,
429 #abcdef-,
430 #abcdef-ghij,
431 #aaaaaa,
432 #bbaacc {
433 background-color: #336699; /* Ignore short hex rule if not gray. */
434 color: #999999;
435 color: #666;
436 }""", """
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. */ {
446 transform: one 0.2s;
447 transform: two .1s;
448 transform: tree 1s;
449 transform: four 300ms;
450 }""", """
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("""
457 img {
458 background: url( data:image/jpeg,4\/\/350|\/|3|2 );
459 background: url('data:image/jpeg,4\/\/350|\/|3|2');
460 }""", """
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]),
470 div {
471 background: url(chrome://resources/BLAH);
472 rule: value; /* rule: value; */
473 rule: value; rule: value;
474 }""", """
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("""
481 div,a,
482 div,/* Hello! */ span,
483 #id.class([dir=rtl):not(.class):any(a, b, d) {
484 rule: value;
488 div,a {
489 some-other: rule here;
490 }""", """
491 - One selector per line (what not to do: a, b {}).
492 div,a,
493 div, span,
494 div,a {""")
496 def testCssPseudoElementDoubleColon(self):
497 self.VerifyContentsProducesOutput("""
498 a:href,
499 br::after,
500 ::-webkit-scrollbar-thumb,
501 a:not([empty]):hover:focus:active, /* shouldn't catch here and above */
502 abbr:after,
503 .tree-label:empty:after,
504 b:before,
505 :-WebKit-ScrollBar {
506 rule: value;
507 }""", """
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)
513 """)
515 def testCssRgbIfNotGray(self):
516 self.VerifyContentsProducesOutput("""
517 #abc,
518 #aaa,
519 #aabbcc {
520 background: -webkit-linear-gradient(left, from(#abc), to(#def));
521 color: #bad;
522 color: #bada55;
523 }""", """
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 */
534 width: 0px;
536 10% {
537 width: 10px;
539 100% {
540 width: 100px;
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%),
550 translateX(0deg),
551 translateY(0rad),
552 translateZ(0grad);
553 background-position-x: 0em;
554 background-position-y: 0ex;
555 border-width: 0em;
556 color: hsl(0, 0%, 85%); /* Shouldn't trigger error. */
557 opacity: .0;
558 opacity: 0.0;
559 opacity: 0.;
562 @page {
563 border-width: 0mm;
564 height: 0cm;
565 width: 0in;
566 }""", """
567 - Make all zero length terms (i.e. 0px) 0 unless inside of hsl() or part of"""
568 """ @keyframe.
569 width: 0px;
570 -webkit-animation: anim 0s;
571 -webkit-animation-duration: anim 0ms;
572 -webkit-transform: scale(0%),
573 translateX(0deg),
574 translateY(0rad),
575 translateZ(0grad);
576 background-position-x: 0em;
577 background-position-y: 0ex;
578 border-width: 0em;
579 opacity: .0;
580 opacity: 0.0;
581 opacity: 0.;
582 border-width: 0mm;
583 height: 0cm;
584 width: 0in;
585 """)
587 if __name__ == '__main__':
588 unittest.main()