-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
validator_test.js
1527 lines (1424 loc) · 56.4 KB
/
validator_test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the license.
*/
goog.provide('amp.validator.ValidatorTest');
goog.require('amp.validator.CssLength');
goog.require('amp.validator.HtmlFormat');
goog.require('amp.validator.TagSpec');
goog.require('amp.validator.ValidationError');
goog.require('amp.validator.annotateWithErrorCategories');
goog.require('amp.validator.createRules');
goog.require('amp.validator.renderErrorMessage');
goog.require('amp.validator.renderValidationResult');
goog.require('amp.validator.sortAndUniquify');
goog.require('amp.validator.subtractDiff');
goog.require('amp.validator.validateString');
goog.require('goog.uri.utils');
/**
* Returns the absolute path for a given test file, that is, a file
* underneath a testdata directory. E.g., 'foo/bar/testdata/baz.html' =>
* 'baz.html'.
* @param {string} testFile
* @return {string}
*/
function absolutePathFor(testFile) {
for (const dir of process.env['TESTDATA_ROOTS'].split(':')) {
const candidate = path.join(dir, testFile);
if (fs.existsSync(candidate)) {
return candidate;
}
}
goog.asserts.fail('Could not find ' + testFile);
}
/**
* @param {string} dir
* @return {!Array<string>}
*/
function readdir(dir) {
const files = fs.readdirSync(dir);
goog.asserts.assert(files != null, 'problem reading ' + dir);
return files;
}
/**
* @param {string} dir
* @return {boolean}
*/
function isdir(dir) {
try {
return fs.lstatSync(dir).isDirectory();
} catch (e) {
return false; // If there's neither a file nor a directory.
}
}
/**
* @param {null|string} regex
* @return {boolean}
*/
function isValidRegex(regex) {
let testRegex = null;
try {
testRegex = new RegExp(regex);
} catch (e) {
}
return testRegex != null;
}
/**
* Returns true if the regex has a group but is missing the corresponding
* Unicode group. For now this tests only for word character group (\\w) which
* must be followed by the Unicode equivalent group (\\p{L}\\p{N}_).
* @param {null|string} regex
* @return {boolean}
*/
function isMissingUnicodeGroup(regex) {
const wordGroupRegex = new RegExp('\\\\w(?!\\\\p{L}\\\\p{N}_)');
return wordGroupRegex.test(regex);
}
/**
* Returns all html files underneath the testdata roots. This looks
* both for feature_tests/*.html and for tests in extension directories.
* E.g.: extensions/amp-accordion/0.1/test/*.html,
* extensions/amp-sidebar/1.0/test/*.html, and
* testdata/feature_tests/amp_accordion.html.
* @return {!Array<string>}
*/
function findHtmlFilesRelativeToTestdata() {
const testSubdirs = [];
for (const root of process.env['TESTDATA_ROOTS'].split(':')) {
if (path.basename(root) === 'extensions') {
for (const extension of readdir(root)) {
const extensionFolder = path.join(root, extension);
if (!isdir(extensionFolder) || extension[0] === '.') {
// Skip if not a folder or if hidden folder
continue;
}
// Get all versions
for (const possibleVersion of readdir(extensionFolder)) {
const testPath = path.join(extension, possibleVersion, 'test');
// Skip if not a folder or if hidden folder
if (isdir(path.join(root, testPath)) && testPath[0] !== '.') {
testSubdirs.push({root, subdir: testPath});
}
}
}
} else {
for (const subdir of readdir(root)) {
// Skip if not a folder or if hidden folder
if (isdir(path.join(root, subdir)) && subdir[0] !== '.') {
testSubdirs.push({root, subdir});
}
}
}
}
const testFiles = [];
for (const entry of testSubdirs) {
for (const candidate of readdir(path.join(entry.root, entry.subdir))) {
if (candidate.match(/^.*.html/g)) {
testFiles.push(path.join(entry.subdir, candidate));
}
}
}
return testFiles;
}
/**
* An AMP Validator test case. This constructor will load the AMP HTML file
* and also find the adjacent .out file.
* @constructor
* @param {string} ampHtmlFile
* @param {string=} opt_ampUrl
*/
const ValidatorTestCase = function(ampHtmlFile, opt_ampUrl) {
/** @type {string} */
this.name = ampHtmlFile;
/** @type {string} */
this.ampHtmlFile = ampHtmlFile;
/** @type {string} */
this.ampUrl = opt_ampUrl || ampHtmlFile;
/** @type {string} */
this.htmlFormat = 'AMP';
if (this.ampHtmlFile.indexOf('amp4ads_feature_tests/') != -1 ||
this.ampHtmlFile.indexOf('/validator-amp4ads-') != -1) {
this.htmlFormat = 'AMP4ADS';
}
if (this.ampHtmlFile.indexOf('amp4email_feature_tests/') != -1 ||
this.ampHtmlFile.indexOf('/validator-amp4email-') != -1) {
this.htmlFormat = 'AMP4EMAIL';
}
if (this.ampHtmlFile.indexOf('actions_feature_tests/') != -1 ||
this.ampHtmlFile.indexOf('/validator-actions-') != -1) {
this.htmlFormat = 'ACTIONS';
}
/**
* If set to false, output will be generated without inlining the input
* document.
* @type {boolean}
*/
this.inlineOutput = true;
/**
* This field can be null, indicating that the expectedOutput did not
* come from a file.
* @type {?string}
*/
this.expectedOutputFile = path.join(
path.dirname(ampHtmlFile), path.basename(ampHtmlFile, '.html') + '.out');
/** @type {string} */
this.ampHtmlFileContents =
fs.readFileSync(absolutePathFor(this.ampHtmlFile), 'utf8').trim();
// Reading in the file with BOM characters appears to strip them. Add them
// back.
if (this.ampHtmlFile === 'feature_tests/unprintable_chars.html') {
this.ampHtmlFileContents = '\ufeff\ufeff\ufeff' + this.ampHtmlFileContents;
}
// In the update_tests case, this file may not exist.
const fullOutputFile = path.join(
path.dirname(absolutePathFor(this.ampHtmlFile)),
path.basename(ampHtmlFile, '.html') + '.out');
/** @type {string} */
this.expectedOutput;
try {
this.expectedOutput = fs.readFileSync(fullOutputFile, 'utf8').trim();
} catch (err) {
// If the file doesn't exist and we're trying to update the file, create it.
if (process.env['UPDATE_VALIDATOR_TEST'] === '1') {
fs.writeFileSync(fullOutputFile, '');
} else {
throw err;
}
}
};
/**
* Renders one line of error output.
* @param {string} filenameOrUrl
* @param {!amp.validator.ValidationError} error
* @return {string}
*/
function renderErrorWithPosition(filenameOrUrl, error) {
const line = error.line || 1;
const col = error.col || 0;
let errorLine = goog.uri.utils.removeFragment(filenameOrUrl) + ':' + line +
':' + col + ' ';
errorLine += amp.validator.renderErrorMessage(error);
if (error.specUrl) {
errorLine += ' (see ' + error.specUrl + ')';
}
if (error.category !== null) {
errorLine += ' [' + error.category + ']';
}
return errorLine;
}
/**
* Like amp.validator.renderValidationResult, except inlines any error messages
* into the input document.
* @param {!Object} validationResult
* @param {string} filename to use in rendering error messages.
* @param {string} filecontents
* @return {string}
*/
function renderInlineResult(validationResult, filename, filecontents) {
let rendered = '';
rendered += validationResult.status;
const lines = filecontents.split('\n');
let linesEmitted = 0;
for (const error of validationResult.errors) {
// Emit all input lines up to and including the line containing the error,
// prefixed with '| ' (or just '|' if the line is empty).
while (linesEmitted < error.line && linesEmitted < lines.length) {
rendered += '\n|';
if (lines[linesEmitted] !== '') {
rendered += ' ' + lines[linesEmitted];
}
linesEmitted++;
}
// Emit a carat showing the column of the following error.
rendered += '\n>>';
for (let i = 0; i < error.col + 1; ++i)
{rendered += ' ';}
rendered += '^~~~~~~~~\n';
rendered += renderErrorWithPosition(filename, error);
}
while (linesEmitted < lines.length) {
rendered += '\n|';
if (lines[linesEmitted] !== '') {
rendered += ' ' + lines[linesEmitted];
}
linesEmitted++;
}
return rendered;
}
/**
* Runs the test, by executing the AMP Validator, then comparing its output
* against the golden file content.
*/
ValidatorTestCase.prototype.run = function() {
const results =
amp.validator.validateString(this.ampHtmlFileContents, this.htmlFormat);
amp.validator.annotateWithErrorCategories(results);
const observed = this.inlineOutput ?
renderInlineResult(results, this.ampUrl, this.ampHtmlFileContents) :
amp.validator.renderValidationResult(results, this.ampUrl).join('\n');
if (observed === this.expectedOutput) {
return;
}
if (process.env['UPDATE_VALIDATOR_TEST'] === '1') {
if (this.expectedOutputFile !== null) {
console/*OK*/.log('Updating ' + this.expectedOutputFile + ' ...');
fs.writeFileSync(absolutePathFor(this.expectedOutputFile), observed);
}
return;
}
let message = '';
if (this.expectedOutputFile !== null) {
message = '\n' + this.expectedOutputFile + ':1:0\n';
}
message += 'expected:\n' + this.expectedOutput + '\nsaw:\n' + observed;
if (this.expectedOutputFile !== null) {
message += '\n\nIf validator/' + absolutePathFor(this.expectedOutputFile) +
' is incorrect, please run `gulp validator --update_tests` to ' +
'regenerate it based on its corresponding .html file.';
}
assert.fail('', '', message, '');
};
/**
* A strict comparison between two values.
* Note: Unfortunately assert.strictEqual has some drawbacks, including that
* it truncates the provided arguments (and it's not configurable) and
* with the Closure compiler, it requires a message argument to which
* we'd always have to pass undefined. Too messy, so we roll our own.
* @param {*} expected
* @param {*} saw
*/
function assertStrictEqual(expected, saw) {
assert.ok(expected === saw, 'expected: ' + expected + ' saw: ' + saw);
}
describe('ValidatorFeatures', () => {
for (const htmlFile of findHtmlFilesRelativeToTestdata()) {
const test = new ValidatorTestCase(htmlFile);
it(test.name, () => { test.run(); });
}
});
describe('ValidatorOutput', () => {
if (process.env['UPDATE_VALIDATOR_TEST'] === '1') { return; }
// What's tested here is that if a URL with #development=1 is passed
// (or any other hash), the validator output won't include the hash.
it('produces expected output with hash in the URL', () => {
const test = new ValidatorTestCase(
'feature_tests/no_custom_js.html',
'http://google.com/foo.html#development=1');
const results =
amp.validator.validateString(test.ampHtmlFileContents, test.htmlFormat);
amp.validator.annotateWithErrorCategories(results);
const observed =
amp.validator.renderValidationResult(results, test.ampUrl).join('\n');
const expectedSubstr = 'http://google.com/foo.html:28:3';
if (observed.indexOf(expectedSubstr) === -1)
{assert.fail(
'', '', 'expectedSubstr:\n' + expectedSubstr +
'\nsaw:\n' + observed, '');}
});
});
describe('ValidationResultTransformerVersion', () => {
if (process.env['UPDATE_VALIDATOR_TEST'] === '1') {
return;
}
// Confirm that the transformer version in attribute "transformed" is
// set to ValidationResult.transformer_version.
it('produces expected output with hash in the URL', () => {
const test = new ValidatorTestCase(
'transformed_feature_tests/minimum_valid_amp.html');
const result =
amp.validator.validateString(test.ampHtmlFileContents, test.htmlFormat);
assertStrictEqual(1, result.transformerVersion);
});
});
describe('ValidatorCssLength', () => {
if (process.env['UPDATE_VALIDATOR_TEST'] === '1') {
return;
}
// Rather than encoding some really long author stylesheets in
// testcases, which would be difficult to read/verify that the
// testcase is valid, we modify a valid testcase
// (feature_tests/css_length.html) designed for this purpose in code.
// We use a blob of length 10 (both bytes and chars) to make it easy to
// construct stylesheets of any length that we want.
const validStyleBlob = 'h1 {a: b}\n';
assertStrictEqual(10, validStyleBlob.length);
const validInlineStyleBlob = 'width:1px;';
assertStrictEqual(10, validInlineStyleBlob.length);
it('accepts 50000 bytes in author stylesheet and 0 bytes in inline style',
() => {
const stylesheet = Array(5001).join(validStyleBlob);
assertStrictEqual(50000, stylesheet.length);
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents = test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutput = 'PASS';
test.run();
});
it('will not accept 50001 bytes in author stylesheet and 0 bytes in ' +
'inline style',
() => {
const stylesheet = Array(5001).join(validStyleBlob) + ' ';
assertStrictEqual(50001, stylesheet.length);
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutputFile = null;
test.expectedOutput = 'FAIL\n' +
'feature_tests/css_length.html:28:2 The author stylesheet ' +
'specified in tag \'style amp-custom\' is too long - document ' +
'contains 50001 bytes whereas the limit is 50000 bytes. ' +
'(see https://www.ampproject.org/docs/reference/spec' +
'#maximum-size) [AUTHOR_STYLESHEET_PROBLEM]';
test.run();
});
it('knows utf8 and rejects file with 50002 bytes but 49999 characters ' +
'and 0 bytes in inline style',
() => {
const stylesheet = Array(5000).join(validStyleBlob) + 'h {a: 😺}';
assertStrictEqual(49999, stylesheet.length); // character length
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutputFile = null;
test.expectedOutput = 'FAIL\n' +
'feature_tests/css_length.html:28:2 The author stylesheet ' +
'specified in tag \'style amp-custom\' is too long - document ' +
'contains 50002 bytes whereas the limit is 50000 bytes. ' +
'(see https://www.ampproject.org/docs/reference/spec' +
'#maximum-size) [AUTHOR_STYLESHEET_PROBLEM]';
test.run();
});
it('accepts 0 bytes in author stylesheet and 50000 bytes in inline style',
() => {
const inlineStyle = Array(5001).join(validInlineStyleBlob);
assertStrictEqual(50000, inlineStyle.length);
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents.replace('.replace_amp_custom {}', '')
.replace('replace_inline_style', inlineStyle);
test.expectedOutput = 'PASS';
test.run();
});
it('will not accept 0 bytes in author stylesheet and 50001 bytes in ' +
'inline style',
() => {
const inlineStyle = Array(5001).join(validInlineStyleBlob) + ' ';
assertStrictEqual(50001, inlineStyle.length);
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents.replace('.replace_amp_custom {}', '')
.replace('replace_inline_style', inlineStyle);
test.expectedOutputFile = null;
test.expectedOutput = 'FAIL\n' +
'feature_tests/css_length.html:36:6 The author stylesheet ' +
'specified in tag \'style amp-custom\' and the combined inline ' +
'styles is too large - document contains 50001 bytes whereas the ' +
'limit is 50000 bytes. (see https://www.ampproject.org/docs/guides' +
'/author-develop/responsive/style_pages) ' +
'[AUTHOR_STYLESHEET_PROBLEM]';
test.run();
});
it('will not accept 50000 bytes in author stylesheet and 14 bytes in ' +
'inline style',
() => {
const stylesheet = Array(5001).join(validStyleBlob);
assertStrictEqual(50000, stylesheet.length);
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', 'display:block;');
test.expectedOutput = 'FAIL\n' +
'feature_tests/css_length.html:5036:6 The author stylesheet ' +
'specified in tag \'style amp-custom\' and the combined inline ' +
'styles is too large - document contains 50014 bytes whereas the ' +
'limit is 50000 bytes. (see https://www.ampproject.org/docs/guides' +
'/author-develop/responsive/style_pages) ' +
'[AUTHOR_STYLESHEET_PROBLEM]';
test.run();
});
});
describe('ValidatorCssLengthWithUrls', () => {
if (process.env['UPDATE_VALIDATOR_TEST'] === '1') {
return;
}
// Rather than encoding some really long author stylesheets in
// testcases, which would be difficult to read/verify that the
// testcase is valid, we modify a valid testcase
// (feature_tests/css_length.html) designed for this purpose in code.
// We use a blob of length 10 (both bytes and chars) to make it easy to
// construct stylesheets of any length that we want.
const validStyleBlob = 'h1 {a: b}\n';
assertStrictEqual(10, validStyleBlob.length);
it('will accept 50010 bytes in author stylesheet that includes an URL ' +
'of 19 bytes',
() => {
const url = 'http://example.com/';
assertStrictEqual(19, url.length);
const cssWithUrl = 'a{b:url(\'' + url + '\')';
assertStrictEqual(30, cssWithUrl.length);
const stylesheet = Array(4999).join(validStyleBlob) + cssWithUrl;
// 10 bytes over limit, 19 of which are the URL.
assertStrictEqual(50010, stylesheet.length);
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutputFile = null;
test.expectedOutput = 'FAIL\n' +
'feature_tests/css_length.html:28:2 The author stylesheet ' +
'specified in tag \'style amp-custom\' is too long - document ' +
'contains 50010 bytes whereas the limit is 50000 bytes. (see ' +
'https://www.ampproject.org/docs/reference/spec#maximum-size) ' +
'[AUTHOR_STYLESHEET_PROBLEM]';
test.run();
});
it('will accept 50010 bytes in stylesheet that includes a relative URL ' +
'of 19 bytes',
() => {
const url = 'a-relative-url.html';
assertStrictEqual(19, url.length);
const cssWithUrl = 'a{b:url(\'' + url + '\')';
assertStrictEqual(30, cssWithUrl.length);
const stylesheet = Array(4999).join(validStyleBlob) + cssWithUrl;
// 10 bytes over limit, 19 of which are the URL.
assertStrictEqual(50010, stylesheet.length);
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutputFile = null;
test.expectedOutput = 'FAIL\n' +
'feature_tests/css_length.html:28:2 The author stylesheet ' +
'specified in tag \'style amp-custom\' is too long - document ' +
'contains 50010 bytes whereas the limit is 50000 bytes. (see ' +
'https://www.ampproject.org/docs/reference/spec#maximum-size) ' +
'[AUTHOR_STYLESHEET_PROBLEM]';
test.run();
});
it('will accept 50010 bytes in stylesheet that includes a data URL ' +
'of 19 bytes',
() => {
const url = 'data:nineteen-bytes';
assertStrictEqual(19, url.length);
const cssWithUrl = 'a{b:url(\'' + url + '\')';
assertStrictEqual(30, cssWithUrl.length);
const stylesheet = Array(4999).join(validStyleBlob) + cssWithUrl;
// 10 bytes over limit, 19 of which are the URL.
assertStrictEqual(50010, stylesheet.length);
const test = new ValidatorTestCase('feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutputFile = null;
test.expectedOutput = 'FAIL\n' +
'feature_tests/css_length.html:28:2 The author stylesheet ' +
'specified in tag \'style amp-custom\' is too long - document ' +
'contains 50010 bytes whereas the limit is 50000 bytes. (see ' +
'https://www.ampproject.org/docs/reference/spec#maximum-size) ' +
'[AUTHOR_STYLESHEET_PROBLEM]';
test.run();
});
});
describe('ValidatorTransformedAmpCssLengthWithUrls', () => {
if (process.env['UPDATE_VALIDATOR_TEST'] === '1') {
return;
}
// Rather than encoding some really long author stylesheets in
// testcases, which would be difficult to read/verify that the
// testcase is valid, we modify a valid testcase
// (transformed_feature_tests/css_length.html) designed for this
// purpose in code.
// We use a blob of length 10 (both bytes and chars) to make it easy to
// construct stylesheets of any length that we want.
const validStyleBlob = 'h1 {a: b}\n';
assertStrictEqual(10, validStyleBlob.length);
it('will accept 50010 bytes in author stylesheet that includes an URL ' +
'of 19 bytes',
() => {
const url = 'http://example.com/';
assertStrictEqual(19, url.length);
const cssWithUrl = 'a{b:url(\'' + url + '\')';
assertStrictEqual(30, cssWithUrl.length);
const stylesheet = Array(4999).join(validStyleBlob) + cssWithUrl;
// 10 bytes over limit, 19 of which are the URL.
assertStrictEqual(50010, stylesheet.length);
const test =
new ValidatorTestCase('transformed_feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutputFile = null;
test.expectedOutput = 'PASS';
test.run();
});
it('will accept 50010 bytes in stylesheet that includes a relative URL ' +
'of 19 bytes',
() => {
const url = 'a-relative-url.html';
assertStrictEqual(19, url.length);
const cssWithUrl = 'a{b:url(\'' + url + '\')';
assertStrictEqual(30, cssWithUrl.length);
const stylesheet = Array(4999).join(validStyleBlob) + cssWithUrl;
// 10 bytes over limit, 19 of which are the URL.
assertStrictEqual(50010, stylesheet.length);
const test =
new ValidatorTestCase('transformed_feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutputFile = null;
test.expectedOutput = 'PASS';
test.run();
});
it('will accept 50010 bytes in stylesheet that includes a data URL ' +
'of 19 bytes',
() => {
const url = 'data:nineteen-bytes';
assertStrictEqual(19, url.length);
const cssWithUrl = 'a{b:url(\'' + url + '\')';
assertStrictEqual(30, cssWithUrl.length);
const stylesheet = Array(4999).join(validStyleBlob) + cssWithUrl;
// 10 bytes over limit, 19 of which are the URL.
assertStrictEqual(50010, stylesheet.length);
const test =
new ValidatorTestCase('transformed_feature_tests/css_length.html');
test.inlineOutput = false;
test.ampHtmlFileContents =
test.ampHtmlFileContents
.replace('.replace_amp_custom {}', stylesheet)
.replace('replace_inline_style', '');
test.expectedOutputFile = null;
test.expectedOutput = 'FAIL\n' +
'transformed_feature_tests/css_length.html:29:2 The author ' +
'stylesheet specified in tag \'style amp-custom (transformed)\' ' +
'is too long - document contains 50010 bytes whereas the limit ' +
'is 50000 bytes. (see ' +
'https://www.ampproject.org/docs/reference/spec#maximum-size) ' +
'[AUTHOR_STYLESHEET_PROBLEM]';
test.run();
});
});
describe('CssLength', () => {
if (process.env['UPDATE_VALIDATOR_TEST'] === '1') { return; }
it('parses a basic example', () => {
const parsed = new amp.validator.CssLength(
'10.1em', /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isSet).toBe(true);
expect(parsed.isValid).toBe(true);
expect(parsed.numeral).toEqual(10.1);
expect(parsed.unit).toEqual('em');
expect(parsed.isAuto).toBe(false);
});
it('supports several units', () => {
for (const allowedUnit of ['px', 'em', 'rem', 'vh', 'vmin', 'vmax']) {
const example = '10' + allowedUnit;
const parsed = new amp.validator.CssLength(
example, /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isSet).toBe(true);
expect(parsed.isValid).toBe(true);
expect(parsed.numeral).toEqual(10);
expect(parsed.unit).toEqual(allowedUnit);
expect(parsed.isAuto).toBe(false);
}
});
it('understands empty unit as "px"', () => {
const parsed = new amp.validator.CssLength(
'10', /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isSet).toBe(true);
expect(parsed.isValid).toBe(true);
expect(parsed.numeral).toEqual(10);
expect(parsed.unit).toEqual('px');
expect(parsed.isAuto).toBe(false);
});
it('understands undefined input as valid (means attr is not set)', () => {
const parsed = new amp.validator.CssLength(
undefined, /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isSet).toBe(false);
expect(parsed.isValid).toBe(true);
expect(parsed.unit).toEqual('px');
expect(parsed.isAuto).toBe(false);
});
it('understands empty string as invalid (means attr value is empty)', () => {
const parsed = new amp.validator.CssLength(
'', /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isValid).toBe(false);
});
it('considers other garbage as invalid', () => {
expect(new amp.validator
.CssLength('100%', /* allowAuto */ false, /* allowFluid */ false)
.isValid)
.toBe(false);
expect(
new amp.validator
.CssLength(
'not a number', /* allowAuto */ false, /* allowFluid */ false)
.isValid)
.toBe(false);
expect(
new amp.validator
.CssLength('1.1.1', /* allowAuto */ false, /* allowFluid */ false)
.isValid)
.toBe(false);
expect(new amp.validator
.CssLength(
'5 inches', /* allowAuto */ false, /* allowFluid */ false)
.isValid)
.toBe(false);
expect(new amp.validator
.CssLength(
'fahrenheit', /* allowAuto */ false, /* allowFluid */ false)
.isValid)
.toBe(false);
expect(new amp.validator
.CssLength('px', /* allowAuto */ false, /* allowFluid */ false)
.isValid)
.toBe(false);
expect(new amp.validator
.CssLength( // screen size in ancient Rome.
'ix unciae', /* allowAuto */ false, /* allowFluid */ false)
.isValid)
.toBe(false);
});
it('recognizes auto if allowed', () => {
{ // allow_auto = false with input != auto
const parsed = new amp.validator.CssLength(
'1', /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isValid).toBe(true);
expect(parsed.isAuto).toBe(false);
} {// allow_auto = true with input != auto
const parsed = new amp.validator.CssLength(
'1', /* allowAuto */ true, /* allowFluid */ false);
expect(parsed.isValid).toBe(true);
expect(parsed.isAuto)
.toBe(false);} { // allow_auto = false with input = auto
const parsed = new amp.validator.CssLength(
'auto', /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isValid).toBe(false);
} {// allow_auto = true with input = auto
const parsed = new amp.validator.CssLength(
'auto', /* allowAuto */ true, /* allowFluid */ false);
expect(parsed.isValid).toBe(true); expect(parsed.isAuto).toBe(true);}
});
it('recognizes fluid if allowed', () => {
{ // allow_fluid = false with input != fluid
const parsed = new amp.validator.CssLength(
'1', /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isValid).toBe(true);
expect(parsed.isFluid).toBe(false);
} {// allow_fluid = true with input != fluid
const parsed = new amp.validator.CssLength(
'1', /* allowAuto */ false, /* allowFluid */ true);
expect(parsed.isValid).toBe(true);
expect(parsed.isFluid)
.toBe(false);} { // allow_fluid = false with input = fluid
const parsed = new amp.validator.CssLength(
'fluid', /* allowAuto */ false, /* allowFluid */ false);
expect(parsed.isValid).toBe(false);
} {// allow_fluid = true with input = fluid
const parsed = new amp.validator.CssLength(
'fluid', /* allowAuto */ false, /* allowFluid */ true);
expect(parsed.isValid).toBe(true); expect(parsed.isFluid).toBe(true);}
});
});
/**
* Helper for ValidatorRulesMakeSense.
* @param {!amp.validator.AttrSpec} attrSpec
* @param {!amp.validator.TagSpec} tagSpec
* @param {!amp.validator.ValidatorRules} rules
*/
function attrRuleShouldMakeSense(attrSpec, tagSpec, rules) {
// name
it('attr_spec name defined', () => {
expect(attrSpec.name).toBeDefined();
});
it('attr_spec name is lower case', () => {
// Attribute Spec names are matched against lowercased attributes,
// so the rules *must* also be lower case or non-cased.
const attrSpecNameRegex = new RegExp('^[^A-Z]+$');
expect(attrSpecNameRegex.test(attrSpec.name)).toBe(true);
});
it('attr_spec name can not be [style]', () => {
expect(attrSpec.name).not.toEqual('[style]');
});
if (attrSpec.valueUrl !== null) {
const protocolRegex = new RegExp('[a-z-]+');
// UrlSpec protocol is matched against lowercased protocol names
// so the rules *must* also be lower case.
it('protocol must be lower case', () => {
for (const protocol of attrSpec.valueUrl.protocol) {
expect(protocolRegex.test(protocol)).toBe(true);
}
});
// If protocol is http then allow_relative should not be false
// except for `data-` attributes and email spec.
if (!attrSpec.name.startsWith('data-') &&
!tagSpec.htmlFormat.includes(amp.validator.HtmlFormat.Code.AMP4EMAIL)) {
for (const protocol of attrSpec.valueUrl.protocol) {
if ((protocol === 'http') &&
(attrSpec.valueUrl.allowRelative !== null)) {
it('allow_relative can not be false if protocol is http: ' +
attrSpec.name,
() => {
expect(attrSpec.valueUrl.allowRelative).toEqual(true);
});
}
}
}
}
if (attrSpec.valueRegex !== null) {
it('value_regex valid', () => {
const regex = rules.internedStrings[-1 - attrSpec.valueRegex];
expect(isValidRegex(regex)).toBe(true);
});
it('value_regex must have unicode named groups', () => {
const regex = rules.internedStrings[-1 - attrSpec.valueRegex];
expect(isMissingUnicodeGroup(regex)).toBe(false);
});
}
if (attrSpec.valueRegexCasei !== null) {
it('value_regex_casei valid', () => {
const regex = rules.internedStrings[-1 - attrSpec.valueRegexCasei];
expect(isValidRegex(regex)).toBe(true);
});
it('value_regex_casei must have unicode named groups', () => {
const regex = rules.internedStrings[-1 - attrSpec.valueRegexCasei];
expect(isMissingUnicodeGroup(regex)).toBe(false);
});
}
if (attrSpec.blacklistedValueRegex !== null) {
it('blacklisted_value_regex valid', () => {
const regex = rules.internedStrings[-1 - attrSpec.blacklistedValueRegex];
expect(isValidRegex(regex)).toBe(true);
});
it('blacklisted_value_regex must have unicode named groups', () => {
const regex = rules.internedStrings[-1 - attrSpec.blacklistedValueRegex];
expect(isMissingUnicodeGroup(regex)).toBe(false);
});
}
// value_url must have at least one allowed protocol.
if (attrSpec.valueUrl !== null) {
it('value_url must have at least one protocol', () => {
expect(attrSpec.valueUrl.protocol.length).toBeGreaterThan(0);
});
}
// only has one of value set.
let numValues = 0;
if (attrSpec.value.length > 0) {
numValues += 1;
}
if (attrSpec.valueCasei.length > 0) {
numValues += 1;
}
if (attrSpec.valueRegex !== null) {numValues += 1;}
if (attrSpec.valueRegexCasei !== null) {numValues += 1;}
if (attrSpec.valueUrl !== null) {numValues += 1;}
if (attrSpec.valueProperties !== null) {numValues += 1;}
it('attr_spec only has one value set', () => {
expect(numValues).toBeLessThan(2);
});
// `id` attribute must have blacklisted_value_regex set if no explicit values.
if ((attrSpec.name === 'id') && (numValues === 0)) {
it('"id" attribute must have blacklisted_value_regex set', () => {
expect(attrSpec.blacklistedValueRegex !== null).toBe(true);
});
}
// `name` attribute must have blacklisted_value_regex set if no explicit
// values.
if ((attrSpec.name === 'name') && (numValues === 0)) {
it('"name" attribute must have blacklisted_value_regex set', () => {
expect(attrSpec.blacklistedValueRegex !== null).toBe(true);
});
}
// deprecation
if ((attrSpec.deprecation !== null) || (attrSpec.deprecationUrl !== null)) {
it('deprecation and deprecation_url must both be defined if one is defined',
() => {
expect(attrSpec.deprecation).toBeDefined();
expect(attrSpec.deprecationUrl).toBeDefined();
});
}
// dispatch_key
if (attrSpec.dispatchKey !== null && attrSpec.dispatchKey) {
it('mandatory must be true when dispatch_key is true', () => {
expect(attrSpec.mandatory).toBeDefined();
expect(attrSpec.mandatory).toBe(true);
});
}
// Value property names must be unique.
if (attrSpec.valueProperties !== null) {
const seenPropertySpecNames = {};
it('value_properties must be unique', () => {
for (const propertySpec of attrSpec.valueProperties.properties) {
expect(seenPropertySpecNames.hasOwnProperty(propertySpec.name))
.toBe(false);
seenPropertySpecNames[propertySpec.name] = 0;
}
});
}
// Transformed AMP does not allow `nonce` attributes, so it must have
// disabled_by: "transformed".
if ((attrSpec.name === 'nonce') &&
tagSpec.htmlFormat.includes(amp.validator.HtmlFormat.Code.AMP)) {
it('nonce attributes must have `disabled_by: "transformed"`', () => {
expect(attrSpec.disabledBy.includes('transformed')).toBe(true);
});
}
}
/**
* Helper for typeIdentifiersShouldMakeSense.
* @param {!Object<string, number>} typeIdentifiers
* @param {!Array<string>} specTypeIdentifiers
* @param {string} fieldName
* @param {string} specType
* @param {string} specName
*/
function typeIdentifiersAreValidAndUnique(
typeIdentifiers, specTypeIdentifiers, fieldName, specType, specName) {
const encounteredTypeIdentifiers = {};
for (const typeIdentifier of specTypeIdentifiers) {
it(specType + ' \'' + specName + '\' has ' + fieldName +
' set to an invalid type identifier: \'' + typeIdentifier + '\'',
() => {
expect(typeIdentifiers.hasOwnProperty(typeIdentifier)).toBe(true);
});
it(specType + ' \'' + specName + '\' has duplicate ' + fieldName + ': \'' +
typeIdentifier + '\'.',
() => {
expect(encounteredTypeIdentifiers.hasOwnProperty(typeIdentifier))
.toBe(false);
encounteredTypeIdentifiers[typeIdentifier] = 0;
});
}
}