-
Notifications
You must be signed in to change notification settings - Fork 5
/
HtmlTokenizerTests.pas
1414 lines (1212 loc) · 34.6 KB
/
HtmlTokenizerTests.pas
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
unit HtmlTokenizerTests;
interface
{$R 'TokenizerTests.res'}
uses
Classes, Contnrs,
TestFramework,
DomCore, HtmlTokenizer, System.JSON;
type
THtmlTokenizerTests = class(TTestCase)
private
FTokens: TObjectList;
procedure GotToken(Sender: TObject; Token: THtmlToken);
function GetToken(i: Integer): THtmlToken;
procedure CheckSyntaxError(s: string);
property Tokens[i: Integer]: THtmlToken read GetToken;
procedure Tokenize(szHtml: UnicodeString; InitialTokenizerState: TTokenizerState=tsDataState; LastStartTag: string='');
procedure CheckTokensEqual(const ExpectedTokens: array of string; const MessageText: string='');
{
These 5 methods are using to construct an token, set its values, and then
return it as a string representation of an "expected" tag.
If the test case expects a comment "Hello, world!", we call:
comment('Hello, world!')
This will return the token's Description:
#comment: Hello, world!
We can then compare that to the .Description of the actual parsed tokens.
}
function doctype(): string;
function startTag(TagName: string): string; overload;
function startTag(TagName: string; Attributes: array of UnicodeString; SelfClosing: Boolean): string; overload;
function endtag(TagName: string): string;
function charToken(ch: UnicodeString): string;
// function chars(text: UnicodeString): string;
function comment(data: string): string;
// function locInfo(Expected: string; StartLine, StartColumn, EndLine, EndColumn: Integer): string;
procedure RunJsonTestFromResource(ResName: string);
procedure TestWithJson(Json: string);
procedure RunTestCase(test: TJsonObject);
protected
procedure SetUp; override;
procedure TearDown; override;
//Tests line/column metadata associated with each token; which we don't do.
// procedure Test_LinesAreCountedCorrectly;
// procedure Test_TokensChars;
// procedure Test_TokensCharsStartTagChars;
// procedure TestTokensStartTagStartTag;
// procedure Test_TokensHtmlCharRefStartTag;
// procedure Test_tokensCharsStartTagCharsStartTag;
// procedure Test_TokensCommentStartTagCharsEndTag;
public
procedure Status(const Msg: string); reintroduce;
procedure WhatWG_XmlViolation; //not yet supported; moved to Public
{ https://github.com/tildeio/simple-html-tokenizer/blob/master/tests/tokenizer-tests.ts }
//These are the ones were result results from simple-html-tokenizer differ from mine.
//I assume that the simple tokenizer is wrong.
//But i really need to do my due dilligence, and walk through the state machine documentation manaully to make sure.
procedure TestASimpleTagWithTrailingSpaces;
procedure Test_ATagWithMultipleAttributes;
procedure Test_ATagWithCapitalizationInAttributes;
procedure Test_ASelfClosingTagWithAnAttributeWithUnquotedValueWithoutSpaceBeforeClosingRegression;
procedure Test_CharacterReferencesAreExpanded;
procedure Test_TheTitleElementContentIsAlwaysText;
procedure Test_TheStyleElementContentIsAlwaysText;
procedure Test_TheScriptElementContentRestrictions;
procedure Test_TwoFollowingScriptTags;
published
procedure TestEmptyDocument;
procedure TestMalformedDocType; //because i messed it up
// These are specific cases from the official tests that the tokenizer fails to handle.
// So i create a more focused test so i can debug this one test case.
// See? Test vectors work!
procedure TestUnfinishedCommentAfterStartOfNestedComment;
procedure TestLessThanInScriptData;
procedure TestEndTagInScriptHTMLComment;
procedure TestAmpersandEOF;
procedure TestUnfinishedEntity;
procedure TestASCIIDecimalEntity;
procedure TestEntityInAttributeWithoutSemicolonEndingInI;
procedure TestUnescapedLessThanSign;
procedure TestUnquotedAttributeEndingInAmpersand;
procedure TestEndtagClosingRCDATAorRAWTEST;
{
Official whatwg tokenizer test cases.
https://wiki.whatwg.org/wiki/Parser_tests
https://github.com/html5lib/html5lib-tests
https://github.com/html5lib/html5lib-tests/tree/master/tokenizer
They are 15 files, containing thousands of test cases,
hitting probably every code path and edge case there is.
}
procedure WhatWG_Test1;
procedure WhatWG_Test2;
procedure WhatWG_Test3;
procedure WhatWG_Test4;
procedure WhatWG_Entities;
procedure WhatWG_NamedEntities;
procedure WhatWG_NumericEntities;
procedure WhatWG_UnicodeChars;
procedure WhatWG_UnicodeCharsProblematic;
procedure WhatWG_ContentModelFlags;
procedure WhatWG_DomJS;
procedure WhatWG_EscapeFlag;
procedure WhatWG_PendingSpecChanges;
//procedure WhatWG_XmlViolation; not yet supported; temporarily living in Public
{ https://github.com/tildeio/simple-html-tokenizer/blob/master/tests/tokenizer-tests.ts }
procedure TestDocType;
procedure TestSimpleContent;
procedure TestASimpleTag;
procedure TestAPairOfHyphenatedTags;
procedure Test_ATagWithASingleQuotedAttribute;
procedure Test_ATagWithADoubleQuotedAttribute;
procedure Test_ATagWithADoubleQuotedEmptyAttribute;
procedure Test_ATagWithUnquotedAttribute;
procedure Test_ATagWithValuelessAttributes;
procedure Test_MissingAttributeName;
procedure Test_InvalidCharacterInAttributeName;
procedure Test_ATagWithCapitalizationInTheTag;
procedure Test_ASelfClosingTag;
procedure TestASelfClosingTagWithValuelessAttributesRegression;
procedure Teset_ASelfClosingTagWithValuelessAttributesWithoutSpaceBeforeClosingRegression;
procedure Test_ATagWithASlashInTheMiddle;
procedure Test_AnOpeningAndClosingTagWithSomeContent;
procedure Test_AComment;
procedure Test_ABuggyCommentWithNoEndingDoubleDash;
procedure Test_ACommentThatImmediatelyCloses;
procedure Test_ACommentThatContainsADash;
procedure Test_ABuggyCommentThatContainsTwoDashes;
procedure Test_ANewlineImmediatelyFollowingAPreTagIsStripped;
procedure Test_ANewlineImmediatelyFollowingAClosingPreTagIsNotStripped;
procedure Test_ANewlineImmediatelyFollowingAnUppercasePreTagIsStripped;
procedure Test_ANewlineImmediatelyFollowingATextareaTagIsStripped;
procedure Test_TitleElementContentIsNotText;
procedure Test_AnEmberishNamedArgInvocation;
procedure Test_ParsingScriptsOutOfAcomplexHTMLDocument;
procedure Test_CarriageReturnsAreReplacedWithLineFeeds;
end;
implementation
uses
SysUtils, System.Generics.Collections;
const
CR = #$0D; // "\r"
LF = #$0A; // "\n"
TAB = #$09; // "\t"
CRLF = #$0D#$0A; // "\r\n"
type
TObjectHolder = class(TInterfacedObject)
private
FValue: TObject;
public
constructor Create(AObject: TObject);
destructor Destroy; override;
end;
function AutoFree(AObject: TObject): IUnknown;
begin
if AObject <> nil then
Result := TObjectHolder.Create(AObject)
else
Result := nil;
end;
{ TObjectHolder }
constructor TObjectHolder.Create(AObject: TObject);
begin
inherited Create;
FValue := AObject;
end;
destructor TObjectHolder.Destroy;
begin
FValue.Free;
FValue := nil;
inherited;
end;
{ THtmlTokenizerTests }
//function THtmlTokenizerTests.chars(text: UnicodeString): string;
//begin
//
//end;
function THtmlTokenizerTests.charToken(ch: UnicodeString): string;
var
t: TCharacterToken;
begin
{
#character: S
}
t := TCharacterToken.Create;
try
t.Data := ch;
Result := t.Description;
finally
t.Free;
end;
end;
procedure THtmlTokenizerTests.CheckSyntaxError(s: string);
begin
end;
procedure THtmlTokenizerTests.CheckTokensEqual(const ExpectedTokens: array of string;
const MessageText: string);
var
token: THtmlToken;
i: Integer;
expected, actual: string;
begin
//Our "ExpectedTokens" does not include the final EndOfFile token.
//Whereas the actual FTokens does.
//So we do ExpectedTokens+1
CheckEquals(Length(ExpectedTokens)+1, FTokens.Count);
for i := 0 to High(ExpectedTokens) do
begin
expected := ExpectedTokens[i];
actual := Tokens[i].Description;
CheckEquals(expected, actual, 'Tokens['+IntToStr(i)+']');
end;
token := FTokens[FTokens.Count-1] as THtmlToken;
CheckEquals('[End-of-File]', token.Description);
end;
function THtmlTokenizerTests.comment(data: string): string;
var
t: TCommentToken;
begin
t := TCommentToken.Create;
try
t.DataString := data;
Result := t.Description;
finally
t.Free;
end;
end;
function THtmlTokenizerTests.doctype(): string;
var
t: TDocTypeToken;
begin
// if Name = '' then
// Name := 'html';
t := TDocTypeToken.Create;
try
t.Name := 'html'; //Name;
Result := t.Description;
finally
t.Free;
end;
end;
function THtmlTokenizerTests.endtag(TagName: string): string;
var
t: TEndTagToken;
begin
t := TEndTagToken.Create;
try
t.TagName := TagName;
Result := t.Description;
finally
t.Free;
end;
end;
function THtmlTokenizerTests.GetToken(i: Integer): THtmlToken;
begin
if i < 0 then
raise Exception.Create('i < 0');
if i >= FTokens.Count then
raise Exception.Create('i >= FTokens.Count');
Result := TObject(FTokens[i]) as THtmlToken;
end;
procedure THtmlTokenizerTests.GotToken(Sender: TObject; Token: THtmlToken);
begin
if FTokens = nil then
raise Exception.Create('FTokens list is nil');
FTokens.Add(Token);
end;
procedure THtmlTokenizerTests.TestWithJson(Json: string);
var
i: Integer;
tests: TJsonArray;
value: TJSonValue;
test: TJsonObject;
testName: string;
begin
{
Json is a string that contains one of the whatwg test case json files.
E.g. https://github.com/html5lib/html5lib-tests/blob/master/tokenizer/test1.test
Run a json query to find all the test cases, and run each one in turn
}
value := TJsonObject.ParseJsonValue(Json);
tests := value.FindValue('tests') as TJsonArray;
CheckTrue(tests <> nil, 'Could not locate tests element in json');
Status('Description Input');
for i := 0 to tests.Count-1 do
begin
test := tests.Items[i] as TJsonObject;
testName := '['+IntToStr(i+1)+' of '+IntToStr(tests.Count)+'] '+test.GetValue<String>('description')+' "'+test.GetValue<string>('input')+'"';
try
Status(testName);
except
on E:Exception do
begin
//Sometimes DUnit GUI test runner fails with an exception itself
Status('Error testName status text "'+testName+'": '+e.Message);
end;
end;
RunTestCase(test);
// Status((testCase.GetValue('description') as TJSONString).Value);
// Status((testCase.GetValue('input') as TJsonString).Value);
end;
end;
procedure THtmlTokenizerTests.RunJsonTestFromResource(ResName: string);
var
rs: TResourceStream;
json: RawByteString;
begin
{
ResName is the name of a JSON file that contains whatwg test case file.
Load the JSON test cases into a string, and then run them.
}
rs := TResourceStream.Create(HInstance, ResName, PChar('JSON'));
try
SetLength(json, rs.Size);
rs.Read(json[1], rs.Size);
Self.TestWithJson(json);
finally
rs.Free;
end;
end;
procedure THtmlTokenizerTests.RunTestCase(test: TJsonObject);
var
testDescription: string;
html: UnicodeString;
output: TJsonArray;
lastStartTag: string;
i: Integer;
expectedToken: TJsonArray;
tokenType: THtmlTokenType;
initialStates: TJsonArray;
initialState: string;
ts: TTokenizerState;
function TokenNameToType(s: string): THtmlTokenType;
begin
if s = 'DOCTYPE' then //(TDocTypeToken)
Result := ttDocType
else if s = 'StartTag' then // (TStartTagToken)
Result := ttStartTag
else if s = 'EndTag' then // (TEndTagToken)
Result := ttEndTag
else if s = 'Comment' then //(TCommentToken)
Result := ttComment
else if s = 'Character' then //(TCharacterToken)
Result := ttCharacter
else
raise Exception.CreateFmt('Unknown test case token type "%s"', [s]);
end;
function StrToTokenizerState(TokenizerStateStr: string): TTokenizerState;
begin
if TokenizerStateStr = 'Data state' then
Result := tsDataState
else if TokenizerStateStr = 'PLAINTEXT state' then
Result := tsPlaintextState
else if TokenizerStateStr = 'RCDATA state' then
Result := tsRCDataState
else if TokenizerStateStr = 'RAWTEXT state' then
Result := tsRawTextState
else if TokenizerStateStr = 'Script data state' then
Result := tsScriptDataState
else if TokenizerStateStr = 'CDATA section state' then
Result := tsCDATASectionState
else
raise Exception.CreateFmt('Unknown initial state "%s"', [TokenizerStateStr]);
end;
procedure RunSingleTest(TokenizerInitialState: TTokenizerState);
var
i: Integer;
begin
Tokenize(html, TokenizerInitialState, lastStartTag);
//Add one, because we also include the EOF token
CheckEquals(output.Count+1, FTokens.Count, 'Test case "'+testDescription+'" number of tokens mismatch');
for i := 0 to output.Count-1 do
begin
expectedToken := output[i] as TJsonArray;
tokenType := TokenNameToType(expectedToken[0].GetValue<string>);
case tokenType of
ttDocType: CheckTrue(Tokens[i] is TDocTypeToken);
ttStartTag: CheckTrue(Tokens[i] is TStartTagToken);
ttEndTag: CheckTrue(Tokens[i] is TEndTagToken);
ttComment: CheckTrue(Tokens[i] is TCommentToken);
ttCharacter: CheckTrue(Tokens[i] is TCharacterToken);
else
CheckTrue(False, 'Unknown token type');
end;
end;
end;
begin
(*
The passed in JSON object is of the form:
{
"description": "Test description", (mandatory)
"input": "input_string", (mandatory)
"output": [expected_output_tokens], (mandaotry)
"initialStates": [initial_states], (optional)
"lastStartTag": last_start_tag, (optional)
"errors": [parse_errors] (optional)
}
For example
description: 'Two unclosed start tags'
input: '<p>One<p>Two'
lastStartTag: 'xmp',
output: [
["StartTag", "p", {}],
["Character", "One"],
["StartTag", "p", {}],
["Character", "Two"]
]
initialStates: ["Script data state"]
Note that output is an array of token information
*)
testDescription := test.GetValue<string>('description');
Status('Test Description: '+testDescription);
html := test.GetValue<string>('input');
Status('Input: "'+html+'"');
lastStartTag := '';
if test.TryGetValue<string>('lastStartTag', {out}lastStartTag) then
Status('Last Start Tag: "'+lastStartTag+'"');
output := test.GetValue('output') as TJsonArray;
Status('Expected: '+output.ToString);
initialStates := test.GetValue('initialStates') as TJsonArray;
if (initialStates = nil) or (initialStates.Count = 0) then
begin
RunSingleTest(tsDataState);
Exit;
end;
for i := 0 to initialStates.Count-1 do
begin
initialState := (initialStates[i] as TJsonString).Value;
ts := StrToTokenizerState(initialState);
RunSingleTest(ts);
end;
end;
procedure THtmlTokenizerTests.SetUp;
var
o: TObject;
begin
inherited;
o := FTokens;
FTokens := TObjectList.Create(True); //owns objects
o.Free;
end;
function THtmlTokenizerTests.startTag(TagName: string): string;
var
t: TStartTagToken;
begin
t := TStartTagToken.Create;
try
t.TagName := TagName;
Result := t.Description;
finally
t.Free;
end;
end;
function THtmlTokenizerTests.startTag(TagName: string; Attributes: array of UnicodeString; SelfClosing: Boolean): string;
var
t: TStartTagToken;
i: Integer;
begin
if (Length(Attributes) mod 2) <> 0 then
raise Exception.Create('Attributes must come in pairs');
t := TStartTagToken.Create;
try
t.TagName := TagName;
i := 0;
while i < Length(Attributes) do
begin
t.AddAttribute(Attributes[i], Attributes[i+1]);
Inc(i, 2);
end;
Result := t.Description;
finally
t.Free;
end;
end;
procedure THtmlTokenizerTests.Status(const Msg: string);
var
s: string;
begin
s := StringReplace(Msg, #$0, '#0', [rfReplaceAll]);
inherited Status(s);
end;
procedure THtmlTokenizerTests.TearDown;
var
o: TObjectList;
begin
o := FTokens;
FTokens := nil;
if o <> nil then
begin
try
o.Free;
except
raise Exception.Create('Error freeing tokens list');
end;
end;
inherited;
end;
procedure THtmlTokenizerTests.Tokenize(szHtml: UnicodeString; InitialTokenizerState: TTokenizerState=tsDataState; LastStartTag: string='');
var
tokenizer: THtmlTokenizer;
begin
FTokens.Clear;
tokenizer := THtmlTokenizer.Create(szHtml);
try
tokenizer.SetState(InitialTokenizerState);
tokenizer.SetLastStartTag(LastStartTag);
tokenizer.OnToken := GotToken;
tokenizer.Parse;
finally
tokenizer.Free;
end;
end;
procedure THtmlTokenizerTests.WhatWG_ContentModelFlags;
begin
RunJsonTestFromResource('html_tests_Tokenizer_contentModelFlags');
end;
procedure THtmlTokenizerTests.WhatWG_DomJS;
begin
RunJsonTestFromResource('html_tests_Tokenizer_domjs');
end;
procedure THtmlTokenizerTests.WhatWG_Entities;
begin
RunJsonTestFromResource('html_tests_Tokenizer_entities');
end;
procedure THtmlTokenizerTests.WhatWG_EscapeFlag;
begin
RunJsonTestFromResource('html_tests_Tokenizer_escapeFlag');
end;
procedure THtmlTokenizerTests.WhatWG_NamedEntities;
begin
RunJsonTestFromResource('html_tests_Tokenizer_namedEntities');
end;
procedure THtmlTokenizerTests.WhatWG_NumericEntities;
begin
RunJsonTestFromResource('html_tests_Tokenizer_numericEntities');
end;
procedure THtmlTokenizerTests.WhatWG_PendingSpecChanges;
begin
RunJsonTestFromResource('html_tests_Tokenizer_pendingSpecChanges');
end;
procedure THtmlTokenizerTests.WhatWG_Test1;
begin
RunJsonTestFromResource('html_tests_Tokenizer_test1');
end;
procedure THtmlTokenizerTests.WhatWG_Test2;
begin
RunJsonTestFromResource('html_tests_Tokenizer_test2');
end;
procedure THtmlTokenizerTests.WhatWG_Test3;
begin
RunJsonTestFromResource('html_tests_Tokenizer_test3');
end;
procedure THtmlTokenizerTests.WhatWG_Test4;
begin
RunJsonTestFromResource('html_tests_Tokenizer_test4');
end;
procedure THtmlTokenizerTests.WhatWG_UnicodeChars;
begin
RunJsonTestFromResource('html_tests_Tokenizer_unicodeChars');
end;
procedure THtmlTokenizerTests.WhatWG_UnicodeCharsProblematic;
begin
RunJsonTestFromResource('html_tests_Tokenizer_unicodeCharsProblematic');
end;
procedure THtmlTokenizerTests.WhatWG_XmlViolation;
begin
{
https://github.com/html5lib/html5lib-tests/blob/master/tokenizer/xmlViolation.test
And from https://github.com/html5lib/html5lib-tests/tree/master/tokenizer:
xmlViolation tests
------------------
tokenizer/xmlViolation.test differs from the above in a couple of ways:
- The name of the single member of the top-level JSON object is "xmlViolationTests" instead of "tests".
- Each test's expected output assumes that implementation is applying the tweaks
given in the spec's "Coercing an HTML DOM into an infoset" section.
}
RunJsonTestFromResource('html_tests_Tokenizer_xmlViolation');
end;
procedure THtmlTokenizerTests.TestEmptyDocument;
var
expected: array of string;
begin
Tokenize(
'<!doctype html>'+CRLF+
'<html>'+CRLF+
'<head></head>'+CRLF+
'<body></body>'+CRLF+
'</html>');
expected := [
doctype(), charToken(LF),
startTag('html'), charToken(LF),
startTag('head'),
endTag('head'), charToken(LF),
startTag('body'),
endTag('body'), charToken(LF),
endTag('html')
];
CheckTokensEqual(expected);
end;
procedure THtmlTokenizerTests.TestEndTagInScriptHTMLComment;
var
html: string;
begin
(*
{
"description": "End tag in script HTML comment",
"initialStates": ["Script data state"]
"input": "<!-- </test> -->"
"output": [
["Character", "<!-- </test> -->"]
]
*)
html := '<!-- </test> -->';
Tokenize(html, tsScriptDataState);
CheckTokensEqual([
charToken('<!-- </test> -->')
]);
end;
procedure THtmlTokenizerTests.TestEntityInAttributeWithoutSemicolonEndingInI;
begin
(*
{
"description": "Entity in attribute without semicolon ending in i"
"input": "<h a=''¬i''>"
"output": [
["StartTag", "h", {"a":"¬i"}]
]
}
*)
Tokenize('<h a=''¬i''>');
CheckTokensEqual([
startTag('h', ['a', '¬i'], False)
]);
end;
procedure THtmlTokenizerTests.TestLessThanInScriptData;
var
html: string;
begin
(*
'{"description":"< in script data",'+CRLF+
'"initialStates":["Script data state"],'+CRLF+
'"input":"<test-->",'+CRLF+
'"output":[["Character", "<test-->"]]},'+CRLF+
*)
html := '<test-->';
Tokenize(html, tsScriptDataState);
CheckTokensEqual([
charToken('<test-->')
]);
end;
procedure THtmlTokenizerTests.TestAmpersandEOF;
begin
(*
{
"description": "Ampersand EOF"
"input": "&"
"output": [
["Character", "&"]
]
}
*)
Tokenize('&');
CheckTokensEqual([
charToken('&')
]);
end;
procedure THtmlTokenizerTests.TestAPairOfHyphenatedTags;
begin
Tokenize('<x-foo></x-foo>');
CheckTokensEqual([
startTag('x-foo'),
endTag('x-foo')
]);
end;
procedure THtmlTokenizerTests.TestASimpleTag;
begin
Tokenize('<div>');
CheckTokensEqual([
startTag('div')
]);
end;
procedure THtmlTokenizerTests.TestASimpleTagWithTrailingSpaces;
begin
Tokenize('</div '+TAB+LF+'>');
//tildeio/simple-html-tokenizer results:
CheckTokensEqual([
startTag('div')
]);
//My tokenizer says "end tag"
// CheckTokensEqual([
// endTag('div')
// ]);
end;
procedure THtmlTokenizerTests.TestDocType;
begin
//https://github.com/tildeio/simple-html-tokenizer/blob/master/tests/tokenizer-tests.ts
Tokenize('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">');
CheckTokensEqual([
doctype()
]);
Tokenize('<!-- comment --><!DOCTYPE html PUBLIC >');
CheckTokensEqual([
comment(' comment '),
doctype()
]);
end;
procedure THtmlTokenizerTests.TestMalformedDocType;
const
html =
'<doctype html>'+CRLF+ //oops, forgot the exclamation point (!)
'<html>'+CRLF+
'<head></head>'+CRLF+
'<body></body>'+CRLF+
'</html>';
begin
tokenize(html);
CheckTokensEqual([
startTag('doctype', ['html', ''], False),
charToken(LF),
startTag('html'),
charToken(LF),
startTag('head'),
endTag('head'),
charToken(LF),
startTag('body'),
endTag('body'),
charToken(LF),
endTag('html')
]);
end;
procedure THtmlTokenizerTests.TestSimpleContent;
begin
Tokenize('hello');
CheckTokensEqual([
charToken('hello')
]);
end;
procedure THtmlTokenizerTests.TestUnescapedLessThanSign;
begin
(*
{
"description": "Unescaped <"
"input": "foo < bar"
"output": [
["Character", "foo < bar"]
]
"errors": [
{
"code": "invalid-first-character-of-tag-name",
"line": 1,
"col": 6
}
]
}
*)
Tokenize('foo < bar');
CheckTokensEqual([
charToken('foo < bar')
]);
end;
procedure THtmlTokenizerTests.TestUnfinishedCommentAfterStartOfNestedComment;
var
html: string;
begin
html := '<!-- <!--';
//Error: "eof-in-comment"
Tokenize(html);
CheckTokensEqual([
comment(' <!')
]);
end;
procedure THtmlTokenizerTests.TestUnfinishedEntity;
begin
(*
{
"description": "Unfinished entity"
"input": "&f"
"output": [
["Character", "&f"]
]
}
*)
Tokenize('&f');
CheckTokensEqual([
charToken('&f')
]);
end;
procedure THtmlTokenizerTests.TestUnquotedAttributeEndingInAmpersand;
begin
Tokenize('<s o=& t>');
CheckTokensEqual([
startTag('s', ['o', '&', 't', ''], False)
]);
end;
procedure THtmlTokenizerTests.Test_ATagWithASingleQuotedAttribute;
begin
Tokenize('<div id=''foo''>');
CheckTokensEqual([
startTag('div', ['id', 'foo'], True)
]);
end;
procedure THtmlTokenizerTests.Test_ATagWithADoubleQuotedAttribute;
begin
Tokenize('<div id="foo">');
CheckTokensEqual([
startTag('div', ['id', 'foo'], True)
]);
end;
procedure THtmlTokenizerTests.Test_ATagWithADoubleQuotedEmptyAttribute;
begin
Tokenize('<div id="">');
CheckTokensEqual([
startTag('div', ['id', ''], False)
]);
end;
procedure THtmlTokenizerTests.Test_ATagWithUnquotedAttribute;
begin
Tokenize('<div id=foo>');
CheckTokensEqual([
startTag('div', ['id', 'foo'], False)
]);
end;
procedure THtmlTokenizerTests.Test_ATagWithValuelessAttributes;
begin
Tokenize('<div foo bar>');
CheckTokensEqual([
startTag('div', ['foo', '', 'bar', ''], False)
]);
end;
procedure THtmlTokenizerTests.Test_MissingAttributeName;
begin
Tokenize('<div =foo>');
CheckTokensEqual([
startTag('div', ['=foo', ''], False)
]);
CheckSyntaxError('attribute name cannot start with equals sign');
end;
procedure THtmlTokenizerTests.Test_InvalidCharacterInAttributeName;
begin
Tokenize('<div ">');
CheckTokensEqual([
startTag('div', ['"', ''], False)
]);
CheckSyntaxError('" is not a valid character within attribute names');
end;
procedure THtmlTokenizerTests.Test_ATagWithMultipleAttributes;
begin
Tokenize('<div id=foo class="bar baz" href=\''bat\''>');