File: HtmlInputTransformHelperTest.php

package info (click to toggle)
mediawiki 1%3A1.43.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 417,464 kB
  • sloc: php: 1,062,949; javascript: 664,290; sql: 9,714; python: 5,458; xml: 3,489; sh: 1,131; makefile: 64
file content (1228 lines) | stat: -rw-r--r-- 37,827 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
<?php

namespace MediaWiki\Tests\Rest\Handler\Helper;

use Exception;
use LogicException;
use MediaWiki\Content\TextContent;
use MediaWiki\Content\WikitextContent;
use MediaWiki\Edit\ParsoidRenderID;
use MediaWiki\Edit\SelserContext;
use MediaWiki\MainConfigNames;
use MediaWiki\MainConfigSchema;
use MediaWiki\Message\TextFormatter;
use MediaWiki\Page\PageIdentity;
use MediaWiki\Page\PageIdentityValue;
use MediaWiki\Parser\ParserOptions;
use MediaWiki\Parser\ParserOutput;
use MediaWiki\Parser\Parsoid\HtmlToContentTransform;
use MediaWiki\Parser\Parsoid\HtmlTransformFactory;
use MediaWiki\Parser\Parsoid\PageBundleParserOutputConverter;
use MediaWiki\Rest\Handler\Helper\HtmlInputTransformHelper;
use MediaWiki\Rest\Handler\Helper\ParsoidFormatHelper;
use MediaWiki\Rest\HttpException;
use MediaWiki\Rest\LocalizedHttpException;
use MediaWiki\Rest\ResponseFactory;
use MediaWiki\Revision\MutableRevisionRecord;
use MediaWiki\Revision\RevisionRecord;
use MediaWiki\Revision\SlotRecord;
use MediaWikiIntegrationTestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\NullLogger;
use Wikimedia\Bcp47Code\Bcp47Code;
use Wikimedia\Message\MessageValue;
use Wikimedia\Parsoid\Core\ClientError;
use Wikimedia\Parsoid\Core\PageBundle;
use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
use Wikimedia\Parsoid\Parsoid;
use Wikimedia\Parsoid\Utils\ContentUtils;
use Wikimedia\Stats\BufferingStatsdDataFactory;
use Wikimedia\Stats\Emitters\NullEmitter;
use Wikimedia\Stats\StatsCache;
use Wikimedia\Stats\StatsFactory;

/**
 * @covers \MediaWiki\Rest\Handler\Helper\HtmlInputTransformHelper
 * @group Database
 */
class HtmlInputTransformHelperTest extends MediaWikiIntegrationTestCase {
	private const CACHE_EPOCH = '20001111010101';

	protected function setUp(): void {
		parent::setUp();

		$this->overrideConfigValue( MainConfigNames::CacheEpoch, self::CACHE_EPOCH );
	}

	/**
	 * @param array $methodOverrides
	 *
	 * @return MockObject|HtmlTransformFactory
	 */
	public function newMockHtmlTransformFactory( $methodOverrides = [] ): HtmlTransformFactory {
		$factory = $this->createNoOpMock( HtmlTransformFactory::class, [ 'getHtmlToContentTransform' ] );

		$factory->method( 'getHtmlToContentTransform' )->willReturnCallback(
			function ( $html ) use ( $methodOverrides ) {
				return $this->newHtmlToContentTransform( $html, $methodOverrides );
			}
		);

		return $factory;
	}

	/**
	 * @param array $transformMethodOverrides
	 * @param StatsFactory|null $stats
	 * @param ?PageIdentity $page
	 * @param array|string $body Body structure, or an HTML string
	 * @param array $parameters
	 * @param RevisionRecord|null $originalRevision
	 * @param Bcp47Code|null $pageLanguage
	 *
	 * @return HtmlInputTransformHelper
	 * @throws Exception
	 */
	private function newHelper(
		array $transformMethodOverrides = [],
		?StatsFactory $stats = null,
		?PageIdentity $page = null,
		$body = '',
		array $parameters = [],
		?RevisionRecord $originalRevision = null,
		?Bcp47Code $pageLanguage = null
	): HtmlInputTransformHelper {
		// TODO: $cache = $cache ?: new EmptyBagOStuff();
		// TODO: $stash = new SimpleParsoidOutputStash( $cache, 1 );

		$stats = $stats ?? StatsFactory::newNull();
		return new HtmlInputTransformHelper(
			$stats,
			$this->newMockHtmlTransformFactory( $transformMethodOverrides ),
			$this->getServiceContainer()->getParsoidOutputStash(),
			$this->getServiceContainer()->getParserOutputAccess(),
			$this->getServiceContainer()->getPageStore(),
			$this->getServiceContainer()->getRevisionLookup(),
			[], /* envOptions */
			$page,
			$body,
			$parameters,
			$originalRevision,
			$pageLanguage
		);
	}

	private function getTextFromFile( string $name ): string {
		return trim( file_get_contents( __DIR__ . "/../data/Transform/$name" ) );
	}

	private function getJsonFromFile( string $name ): array {
		$text = $this->getTextFromFile( $name );
		return json_decode( $text, JSON_OBJECT_AS_ARRAY );
	}

	public function provideRequests() {
		$profileVersion = '2.4.0';
		$wikitextProfileUri = 'https://www.mediawiki.org/wiki/Specs/wikitext/1.0.0';
		$htmlProfileUri = 'https://www.mediawiki.org/wiki/Specs/HTML/' . $profileVersion;
		$dataParsoidProfileUri = 'https://www.mediawiki.org/wiki/Specs/data-parsoid/' . $profileVersion;

		$wikiTextContentType = "text/plain; charset=utf-8; profile=\"$wikitextProfileUri\"";
		$htmlContentType = "text/html;profile=\"$htmlProfileUri\"";
		$dataParsoidContentType = "application/json;profile=\"$dataParsoidProfileUri\"";

		$htmlHeaders = [
			'content-type' => $htmlContentType,
		];

		// NOTE: profile version 999 is a placeholder for a future feature, see T78676
		$htmlContentType999 = 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/999.0.0"';
		$htmlHeaders999 = [
			'content-type' => $htmlContentType999,
		];

		// should convert html to wikitext ///////////////////////////////////
		$html = $this->getTextFromFile( 'MainPage-data-parsoid.html' );
		$expectedText = [
			'MediaWiki has been successfully installed',
			'== Getting started ==',
		];

		$params = [];
		$body = [ 'html' => $html ];
		yield 'should convert html to wikitext' => [
			$body,
			$params,
			$expectedText,
		];

		// should load original wikitext by revision id ////////////////////
		$params = [
			'oldid' => 1, // will be replaced by the actual revid
		];
		$body = [ 'html' => $html ];
		yield 'should load original wikitext by revision id' => [
			$body,
			$params,
			$expectedText,
		];

		// should accept original wikitext in body ////////////////////
		$originalWikitext = $this->getTextFromFile( 'OriginalMainPage.wikitext' );
		$params = [];
		$body = [
			'html' => $html,
			'original' => [
				'wikitext' => [
					'headers' => [
						'content-type' => $wikiTextContentType,
					],
					'body' => $originalWikitext,
				]
			]
		];
		yield 'should accept original wikitext in body' => [
			$body,
			$params,
			$expectedText, // TODO: ensure it's actually used!
		];

		// should use original html for selser (default) //////////////////////
		$originalDataParsoid = $this->getJsonFromFile( 'MainPage-original.data-parsoid' );
		$params = [
			'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
		];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => $htmlHeaders,
					'body' => $this->getTextFromFile( 'MainPage-original.html' ),
				],
				'data-parsoid' => [
					'headers' => [
						'content-type' => $dataParsoidContentType,
					],
					'body' => $originalDataParsoid
				]
			]
		];
		yield 'should use original html for selser (default)' => [
			$body,
			$params,
			$expectedText,
		];

		// should use original html for selser (1.1.1, meta) ///////////////////
		$params = [];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => [
						// XXX: If this is required anyway, how do we know we are using the
						//      version given in the HTML?
						'content-type' => 'text/html; profile="mediawiki.org/specs/html/1.1.1"',
					],
					'body' => $this->getTextFromFile( 'MainPage-data-parsoid-1.1.1.html' ),
				],
				'data-parsoid' => [
					'headers' => [
						'content-type' => $dataParsoidContentType,
					],
					'body' => $originalDataParsoid
				]
			]
		];
		yield 'should use original html for selser (1.1.1, meta)' => [
			$body,
			$params,
			$expectedText,
		];

		// should accept original html for selser (1.1.1, headers) ////////////
		$params = [
			'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
		];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => [
						// Set the schema version to 1.1.1!
						'content-type' => 'text/html; profile="mediawiki.org/specs/html/1.1.1"',
					],
					// No schema version in HTML
					'body' => $this->getTextFromFile( 'MainPage-original.html' ),
				],
				'data-parsoid' => [
					'headers' => [
						'content-type' => $dataParsoidContentType,
					],
					'body' => $originalDataParsoid
				]
			]
		];
		yield 'should use original html for selser (1.1.1, headers)' => [
			$body,
			$params,
			$expectedText,
		];

		// Return original wikitext when HTML doesn't change ////////////////////////////
		// New and old html are identical, which should produce no diffs
		// and reuse the original wikitext.
		$html = '<html><body id="mwAA"><div id="mwBB">Selser test</div></body></html>';
		$dataParsoid = [
			'ids' => [
				'mwAA' => [],
				'mwBB' => [ 'autoInsertedEnd' => true, 'stx' => 'html' ]
			]
		];

		$params = [
			'oldid' => 1, // Will be replaced by the revision ID of the default test page
		];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => $htmlHeaders,
					// original HTML is the same as the new HTML
					'body' => $html
				],
				'data-parsoid' => [
					'body' => $dataParsoid,
				]
			]
		];
		yield 'should use selser, return original wikitext because the HTML didn\'t change' => [
			$body,
			$params,
			null, // Returns original wikitext, because HTML didn't change.
		];

		// Should fall back to non-selective serialization. //////////////////
		// Without the original wikitext, use non-selective serialization.
		$params = [
			// No wikitext, no revid/oldid
			'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
		];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => $htmlHeaders,
					// original HTML is the same as the new HTML
					'body' => $html
				],
				'data-parsoid' => [
					'body' => $dataParsoid,
				]
			]
		];
		yield 'Should fallback to non-selective serialization' => [
			$body,
			$params,
			[ '<div>Selser test' ],
		];

		// should apply data-parsoid to duplicated ids /////////////////////////
		$html = '<html><body id="mwAA"><div id="mwBB">data-parsoid test</div>' .
			'<div id="mwBB">data-parsoid test</div></body></html>';
		$originalHtml = '<html><body id="mwAA"><div id="mwBB">data-parsoid test</div></body></html>';

		$params = [];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => $htmlHeaders,
					'body' => $originalHtml
				],
				'data-parsoid' => [
					'body' => $dataParsoid,
				]
			]
		];
		yield 'should apply data-parsoid to duplicated ids' => [
			$body,
			$params,
			[ '<div>data-parsoid test<div>data-parsoid test' ],
		];

		// should ignore data-parsoid if the input format is given but not pagebundle //////////////
		$html = '<html><body id="mwAA"><div id="mwBB">data-parsoid test</div>' .
			'<div id="mwBB">data-parsoid test</div></body></html>';
		$originalHtml = '<html><body id="mwAA"><div id="mwBB">data-parsoid test</div></body></html>';

		$params = [
			'from' => ParsoidFormatHelper::FORMAT_HTML,
		];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => $htmlHeaders,
					'body' => $originalHtml
				],
				'data-parsoid' => [
					// This has 'autoInsertedEnd' => true, which would cause
					// closing </div> tags to be omitted.
					'body' => $dataParsoid,
				]
			]
		];
		yield 'should ignore data-parsoid if the input format is not pagebundle' => [
			$body,
			$params,
			[ '<div>data-parsoid test</div><div>data-parsoid test</div>' ],
		];

		// should apply original data-mw ///////////////////////////////////////
		$html = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">hi</p>';
		$originalHtml = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">ho</p>';
		$dataParsoid = [ 'ids' => [ 'mwAQ' => [ 'pi' => [ [ [ 'k' => '1' ] ] ] ] ] ];
		$dataMediaWiki = [
			'ids' => [
				'mwAQ' => [
					'parts' => [ [
						'template' => [
							'target' => [ 'wt' => '1x', 'href' => './Template:1x' ],
							'params' => [ '1' => [ 'wt' => 'hi' ] ],
							'i' => 0
						]
					] ]
				]
			]
		];
		$params = [];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => $htmlHeaders,
					'body' => $originalHtml,
				],
				'data-parsoid' => [
					'body' => $dataParsoid,
				],
				'data-mw' => [
					'body' => $dataMediaWiki,
				],
			],
		];
		yield 'should apply original data-mw' => [
			$body,
			$params,
			[ '{{1x|hi}}' ],
		];

		// should give precedence to inline data-mw over original ////////
		$html = '<p about="#mwt1" typeof="mw:Transclusion" data-mw=\'{"parts":[{"template":{"target":{"wt":"1x","href":"./Template:1x"},"params":{"1":{"wt":"hi"}},"i":0}}]}\' id="mwAQ">hi</p>';
		$originalHtml = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">ho</p>';
		$dataParsoid = [ 'ids' => [ 'mwAQ' => [ 'pi' => [ [ [ 'k' => '1' ] ] ] ] ] ];
		$dataMediaWiki = [ 'ids' => [ 'mwAQ' => [] ] ]; // Missing data-mw.parts!
		$params = [];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => $htmlHeaders,
					'body' => $originalHtml
				],
				'data-parsoid' => [
					'body' => $dataParsoid,
				],
				'data-mw' => [
					'body' => $dataMediaWiki,
				],
			]
		];
		yield 'should give precedence to inline data-mw over original' => [
			$body,
			$params,
			[ '{{1x|hi}}' ],
		];

		// should not apply original data-mw if modified is supplied ///////////
		$html = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">hi</p>';
		$originalHtml = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">ho</p>';
		$dataParsoid = [ 'ids' => [ 'mwAQ' => [ 'pi' => [ [ [ 'k' => '1' ] ] ] ] ] ];
		$dataMediaWiki = [ 'ids' => [ 'mwAQ' => [] ] ]; // Missing data-mw.parts!
		$dataMediaWikiModified = [
			'ids' => [
				'mwAQ' => [
					'parts' => [ [
						'template' => [
							'target' => [ 'wt' => '1x', 'href' => './Template:1x' ],
							'params' => [ '1' => [ 'wt' => 'hi' ] ],
							'i' => 0
						]
					] ]
				]
			]
		];
		$params = [];
		$body = [
			'html' => $html,
			'data-mw' => [ // modified data
				'body' => $dataMediaWikiModified,
			],
			'original' => [
				'html' => [
					'headers' => $htmlHeaders999,
					'body' => $originalHtml
				],
				'data-parsoid' => [
					'body' => $dataParsoid,
				],
				'data-mw' => [ // original data
					'body' => $dataMediaWiki,
				],
			]
		];
		yield 'should not apply original data-mw if modified is supplied' => [
			$body,
			$params,
			[ '{{1x|hi}}' ],
		];

		// should apply original data-mw when modified is absent (captions 1) ///////////
		$html = $this->getTextFromFile( 'Image.html' );
		$dataParsoid = [ 'ids' => [
			'mwAg' => [ 'optList' => [ [ 'ck' => 'caption', 'ak' => 'Testing 123' ] ] ],
			'mwAw' => [ 'a' => [ 'href' => './File:Foobar.jpg' ], 'sa' => [] ],
			'mwBA' => [
				'a' => [ 'resource' => './File:Foobar.jpg', 'height' => '28', 'width' => '240' ],
				'sa' => [ 'resource' => 'File:Foobar.jpg' ]
			]
		] ];
		$dataMediaWiki = [ 'ids' => [ 'mwAg' => [ 'caption' => 'Testing 123' ] ] ];

		$params = [];
		$body = [
			'html' => $html,
			'original' => [
				'data-parsoid' => [
					'body' => $dataParsoid,
				],
				'data-mw' => [ // original data
					'body' => $dataMediaWiki,
				],
				'html' => [
					'headers' => $htmlHeaders999,
					'body' => $html
				],
			]
		];
		yield 'should apply original data-mw when modified is absent (captions 1)' => [
			$body,
			$params,
			[ '[[File:Foobar.jpg|Testing 123]]' ],
		];

		// should give precedence to inline data-mw over modified (captions 2) /////////////
		$htmlModified = $this->getTextFromFile( 'Image-data-mw.html' );
		$dataMediaWikiModified = [
			'ids' => [
				'mwAg' => [ 'caption' => 'Testing 123' ]
			]
		];

		$params = [];
		$body = [
			'html' => $htmlModified, // modified HTML
			'data-mw' => [
				'body' => $dataMediaWikiModified,
			],
			'original' => [
				'data-parsoid' => [
					'body' => $dataParsoid,
				],
				'data-mw' => [ // original data
					'body' => $dataMediaWiki,
				],
				'html' => [
					'headers' => $htmlHeaders999,
					'body' => $html
				],
			]
		];
		yield 'should give precedence to inline data-mw over modified (captions 2)' => [
			$body,
			$params,
			[ '[[File:Foobar.jpg]]' ],
		];

		// should give precedence to modified data-mw over original (captions 3) /////////////
		$dataMediaWikiModified = [
			'ids' => [
				'mwAg' => []
			]
		];

		$params = [];
		$body = [
			'html' => $html,
			'data-mw' => [
				'body' => $dataMediaWikiModified,
			],
			'original' => [
				'data-parsoid' => [
					'body' => $dataParsoid,
				],
				'data-mw' => [ // original data
					'body' => $dataMediaWiki,
				],
				'html' => [
					'headers' => $htmlHeaders999,
					'body' => $html
				],
			]
		];
		yield 'should give precedence to modified data-mw over original (captions 3)' => [
			$body,
			$params,
			[ '[[File:Foobar.jpg]]' ],
		];

		// should apply extra normalizations ///////////////////
		$htmlModified = 'Foo<h2></h2>Bar';
		$params = [
			'opts' => [
				'original' => []
			],
		];
		$body = [ 'html' => $htmlModified ]; // modified HTML
		yield 'should apply extra normalizations' => [
			$body,
			$params,
			[ 'FooBar' ], // empty tag was stripped
		];

		// should apply version downgrade ///////////
		$htmlOfMinimal = $this->getTextFromFile( 'Minimal.html' ); // Uses profile version 2.4.0
		$params = [
			'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
		];
		$body = [
			'html' => $htmlOfMinimal,
			'original' => [
				'html' => [
					'headers' => [
						// Specify newer profile version for original HTML
						'content-type' => 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/999.0.0"'
					],
					// The profile version given inline in the original HTML doesn't matter, it's ignored
					'body' => $htmlOfMinimal,
				],
				'data-parsoid' => [ 'body' => [ 'ids' => [] ] ],
				'data-mw' => [ 'body' => [ 'ids' => [] ] ], // required by version 999.0.0
			]
		];
		yield 'should apply version downgrade' => [
			$body,
			$params,
			[ '123' ]
		];

		// should not apply version downgrade if versions are the same ///////////
		$htmlOfMinimal = $this->getTextFromFile( 'Minimal.html' ); // Uses profile version 2.4.0
		$params = [];
		$body = [
			'html' => $htmlOfMinimal,
			'original' => [
				'html' => [
					'headers' => [
						// Specify the exact same version specified inline in Minimal.html 2.4.0
						'content-type' => 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/2.4.0"'
					],
					// The profile version given inline in the original HTML doesn't matter, it's ignored
					'body' => $htmlOfMinimal,
				],
				'data-parsoid' => [ 'body' => [ 'ids' => [] ] ],
			]
		];
		yield 'should not apply version downgrade if versions are the same' => [
			$body,
			$params,
			[ '123' ]
		];

		// should convert html to json ///////////////////////////////////
		$html = $this->getTextFromFile( 'JsonConfig.html' );
		$expectedText = [
			'{"a":4,"b":3}',
		];

		$params = [
			'contentmodel' => CONTENT_MODEL_JSON,
		];
		$body = [ 'html' => $html ];
		yield 'should convert html to json' => [
			$body,
			$params,
			$expectedText,
			[ 'content-type' => 'application/json' ],
		];

		// page bundle input should work with no original data present  ///////////
		$htmlOfMinimal = $this->getTextFromFile( 'Minimal.html' ); // Uses profile version 2.4.0
		$params = [];
		$body = [
			'html' => $htmlOfMinimal,
			'original' => [],
		];
		yield 'page bundle input should work with no original data present' => [
			$body,
			$params,
			[ '123' ]
		];
	}

	private function createResponse() {
		$responseFactory = new ResponseFactory( [ new TextFormatter( 'qqx' ) ] );
		$response = $responseFactory->create();
		return $response;
	}

	/**
	 * @param array $body
	 * @param array $params
	 * @param string|string[]|null $expectedText Null means use the original content.
	 * @param array $expectedHeaders
	 * @dataProvider provideRequests()
	 * @covers \MediaWiki\Rest\Handler\Helper\HtmlInputTransformHelper
	 * @covers \MediaWiki\Parser\Parsoid\HtmlToContentTransform
	 */
	public function testResponse( $body, $params, $expectedText, array $expectedHeaders = [] ) {
		if ( !empty( $params['oldid'] ) ) {
			// If an oldid is set, run the test with an actual existing revision ID
			$originalContent = __METHOD__ . ' original content';
			$page = $this->getNonexistingTestPage();
			$this->editPage( $page, new WikitextContent( $originalContent ) );
			$page = $page->getTitle();
			$params['oldid'] = $page->getLatestRevID();
		} else {
			$page = PageIdentityValue::localIdentity( 7, NS_MAIN, $body['pageName'] ?? 'HtmlInputTransformHelperTest' );
			$originalContent = '';
		}

		$statsCache = new StatsCache();
		$statsdFactory = new BufferingStatsdDataFactory( '' );
		$stats = new StatsFactory( $statsCache, new NullEmitter(), new NullLogger() );
		$stats = $stats->withStatsdDataFactory( $statsdFactory );

		// TODO: find a way to test $pageLanguage
		$helper = $this->newHelper( [], $stats, $page, $body, $params );

		$response = $this->createResponse();
		$helper->putContent( $response );

		foreach ( $expectedHeaders as $name => $value ) {
			$this->assertSame( $value, $response->getHeaderLine( $name ) );
		}

		$body = $response->getBody();
		$body->rewind();
		$text = $body->getContents();

		$expectedText ??= $originalContent;
		foreach ( (array)$expectedText as $exp ) {
			$this->assertStringContainsString( $exp, $text );
		}

		// Ensure that exactly one key with the given prefix is set.
		// This ensures that the number of keys set always adds up to 100%,
		// for any set of keys under this prefix.
		$this->assertMetricsCount( 1, $statsdFactory, 'html_input_transform.original_html.' );
	}

	private function assertMetricsCount( $expected, BufferingStatsdDataFactory $stats, $prefix = '' ) {
		$keys = [];
		foreach ( $stats->getData() as $datum ) {
			if ( str_starts_with( $datum->getKey(), $prefix ) ) {
				$keys[] = $datum->getKey();
			}
		}

		$this->addToAssertionCount( 1 );
		if ( count( $keys ) !== $expected ) {
			$this->fail(
				"Failed to assert that the number of metrics keys starting with '$prefix' is $expected. Keys: \n\t"
				. implode( "\n\t", $keys )
			);
		}
	}

	public function provideOriginal() {
		$unchangedPB = new PageBundle(
			$this->getTextFromFile( 'MainPage-original.html' ),
			$this->getJsonFromFile( 'MainPage-original.data-parsoid' ),
			null,
			Parsoid::defaultHTMLVersion()
		);

		$originalContent = new WikitextContent( 'Goats are great!' );
		$selserContext = new SelserContext( $unchangedPB, 0, $originalContent );

		$unchangedPO = PageBundleParserOutputConverter::parserOutputFromPageBundle( $unchangedPB );

		$renderID = new ParsoidRenderID( 0, 'testing' );

		yield 'no original data' => [
			$selserContext,
			null,
			null,
			[
				'MediaWiki has been successfully installed',
				'== Getting started ==',
			]
		];

		// should load original wikitext by revision id ////////////////////
		yield 'should load original wikitext by revision id' => [
			$selserContext,
			1, // will be replaced by the actual revid
			$unchangedPB, // Expect selser, since HTML didn't change.
			null, // Selser should preserve the original content.
		];

		// should use wikitext from fake revision ////////////////////
		$page = PageIdentityValue::localIdentity( 7, NS_MAIN, 'HtmlInputTransformHelperTest' );
		$rev = new MutableRevisionRecord( $page );
		$rev->setContent( SlotRecord::MAIN, new WikitextContent( 'Goats are great!' ) );

		yield 'should use wikitext from fake revision' => [
			$selserContext,
			$rev,
			$unchangedPO, // Expect selser, since HTML didn't change.
			'Goats are great!', // Text from the fake revision. Selser should preserve it.
		];

		// should get original HTML from stash ////////////////////
		yield 'should get original HTML from stash' => [
			$selserContext,
			$rev,
			$renderID, // Expect selser, since HTML didn't change.
			'Goats are great!', // Text from the fake revision. Selser should preserve it.
		];
	}

	/**
	 * @dataProvider provideOriginal()
	 *
	 * @param SelserContext|null $stashed
	 * @param RevisionRecord|int|null $rev
	 * @param ParsoidRenderID|PageBundle|ParserOutput|null $originalRendering
	 * @param string|string[]|null $expectedText Null means use the original content
	 *
	 * @covers \MediaWiki\Rest\Handler\Helper\HtmlInputTransformHelper::setOriginal
	 */
	public function testSetOriginal( ?SelserContext $stashed, $rev, $originalRendering, $expectedText ) {
		if ( is_int( $rev ) && $rev > 0 ) {
			// If a revision ID is given, run the test with an actual existing revision ID
			$originalContent = __METHOD__ . ' original content';
			$page = $this->getNonexistingTestPage();
			$this->editPage( $page, new WikitextContent( $originalContent ) );
			$page = $page->getTitle();
			$revId = $page->getLatestRevID() ?: 0;
			$rev = $revId;
		} elseif ( $rev instanceof RevisionRecord ) {
			$originalContentObj = $rev->getContent( SlotRecord::MAIN );
			if ( !$originalContentObj instanceof TextContent ) {
				throw new LogicException( 'Not implemented' );
			}
			$originalContent = $originalContentObj->getText();
			$page = $rev->getPage();
			$revId = $rev->getId() ?: 0;
		} else {
			$originalContent = '';
			$page = PageIdentityValue::localIdentity( 7, NS_MAIN, 'HtmlInputTransformHelperTest' );
			$revId = 0;
		}

		if ( $stashed ) {
			$renderID = new ParsoidRenderID( $revId, 'testing' );
			$stash = $this->getServiceContainer()->getParsoidOutputStash();
			$stash->set( $renderID, $stashed );
		}

		$html = $this->getTextFromFile( 'MainPage-original.html' );

		$params = [];
		$body = [
			'html' => $html
		];

		$statsCache = new StatsCache();
		$statsdFactory = new BufferingStatsdDataFactory( '' );
		$stats = new StatsFactory( $statsCache, new NullEmitter(), new NullLogger() );
		$stats = $stats->withStatsdDataFactory( $statsdFactory );

		$helper = $this->newHelper( [], $stats, $page, $body, $params );
		$helper->setOriginal( $rev, $originalRendering );

		$response = $this->createResponse();
		$helper->putContent( $response );

		$body = $response->getBody();
		$body->rewind();
		$text = $body->getContents();

		$expectedText ??= $originalContent;
		foreach ( (array)$expectedText as $exp ) {
			$this->assertStringContainsString( $exp, $text );
		}

		// Ensure that exactly one key with the given prefix is set.
		// This ensures that the number of keys set always adds up to 100%,
		// for any set of keys under this prefix.
		if ( $rev || $originalRendering ) {
			$this->assertMetricsCount( 1, $statsdFactory, 'html_input_transform.original_html.given' );
		} else {
			$this->assertMetricsCount( 1, $statsdFactory, 'html_input_transform.original_html.not_given' );
		}
	}

	/**
	 * @covers \MediaWiki\Rest\Handler\Helper\HtmlInputTransformHelper::getTransform
	 */
	public function testGetTransform() {
		$page = PageIdentityValue::localIdentity( 7, NS_MAIN, 'HtmlInputTransformHelperTest' );
		$html = '<p>kittens are cute</p>';

		$params = [];
		$body = [
			'html' => $html
		];

		$helper = $this->newHelper( [], StatsFactory::newNull(), $page, $body, $params );

		$transform = $helper->getTransform();

		$this->assertStringContainsString( 'kittens', ContentUtils::toXML( $transform->getModifiedDocument() ) );
	}

	/**
	 * @covers \MediaWiki\Rest\Handler\Helper\HtmlInputTransformHelper
	 * @covers \MediaWiki\Parser\Parsoid\HtmlToContentTransform
	 */
	public function testResponseForFakeRevision() {
		$wikitext = 'Unsaved Revision Content';

		$html = $this->getTextFromFile( 'Minimal.html' );
		$page = PageIdentityValue::localIdentity( 7, NS_MAIN, $body['pageName'] ?? 'HtmlInputTransformHelperTest' );

		// Create a fake revision. Since the HTML didn't change, we expect to get back the content
		// we defined for this revision.
		$revision = new MutableRevisionRecord( $page );
		$revision->setContent( SlotRecord::MAIN, new WikitextContent( $wikitext ) );

		$params = [];
		$body = [
			'html' => $html,
			'original' => [
				'html' => [
					'headers' => [ 'content-type' => 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/2.4.0"' ],
					// original HTML is the same as the new HTML
					'body' => $html
				],
			]
		];

		$page = PageIdentityValue::localIdentity( 7, NS_MAIN, $body['pageName'] ?? 'HtmlInputTransformHelperTest' );

		$helper = $this->newHelper( [], StatsFactory::newNull(), $page, $body, $params, $revision );

		$response = $this->createResponse();
		$helper->putContent( $response );

		$body = $response->getBody();
		$body->rewind();

		// Since the HTML didn't change, we expect to get back the content of the fake revision.
		$this->assertSame( $wikitext, $body->getContents() );
	}

	public function testResponseWithRenderIdForExistingRevision() {
		$profileVersion = '2.4.0';
		$htmlProfileUri = 'https://www.mediawiki.org/wiki/Specs/HTML/' . $profileVersion;
		$htmlContentType = "text/html;profile=\"$htmlProfileUri\"";

		$htmlHeaders = [
			'content-type' => $htmlContentType,
		];

		$page = $this->getExistingTestPage();
		$oldWikitext = $page->getContent()->serialize();

		$html = $this->getTextFromFile( 'MainPage-original.html' );
		$dataParsoid = $this->getJsonFromFile( 'MainPage-original.data-parsoid' );

		$pb = new PageBundle(
			$html,
			$dataParsoid,
			[],
			$profileVersion,
			$htmlHeaders,
			CONTENT_MODEL_WIKITEXT
		);

		$eTag = '"' . $page->getLatest() . '/just-a-test/edit"';

		// Load the original data based on the ETag
		$body = [ 'html' => $html, 'original' => [ 'renderid' => $eTag ] ];
		$params = [];

		$stash = $this->getServiceContainer()->getParsoidOutputStash();
		$stash->set(
			ParsoidRenderID::newFromETag( $eTag ),
			new SelserContext( $pb, $page->getLatest() ),
		);

		$helper = $this->newHelper( [], StatsFactory::newNull(), $page, $body, $params );

		$content = $helper->getContent();

		// Assert that we get back the old wikitext, not wikitext derived from the HTML.
		// Since the supplied HTML is the same as the HTML in the stash, selser should
		// decide that there is nothing to do and return the wikitext unchanged.
		$this->assertSame( $oldWikitext, $content->serialize() );
	}

	public function testResponseWithRenderIdForUnsavedWikitext() {
		$profileVersion = '2.4.0';
		$htmlProfileUri = 'https://www.mediawiki.org/wiki/Specs/HTML/' . $profileVersion;
		$htmlContentType = "text/html;profile=\"$htmlProfileUri\"";

		$htmlHeaders = [
			'content-type' => $htmlContentType,
		];

		$page = $this->getNonexistingTestPage();

		$html = $this->getTextFromFile( 'MainPage-original.html' );
		$dataParsoid = $this->getJsonFromFile( 'MainPage-original.data-parsoid' );
		$oldWikitext = 'Fake old wikitext';

		$content = new WikitextContent( $oldWikitext );
		$pb = new PageBundle(
			$html,
			$dataParsoid,
			[],
			$profileVersion,
			$htmlHeaders,
			CONTENT_MODEL_WIKITEXT
		);

		// NOTE: Using 0 as the prefix in the ETag indicates that the content does
		// not correspond to a saved revision. Since we don't have a revision
		// ID that we could use to load the wikitext from the database,
		// the wikitext should be taken from the stash.
		// That is the behavior asserted by this test case.
		$eTag = '"0/just-a-test/edit"';

		// Load the original data based on the ETag
		$body = [ 'html' => $html, 'original' => [ 'renderid' => $eTag ] ];
		$params = [];

		$stash = $this->getServiceContainer()->getParsoidOutputStash();
		$stash->set(
			ParsoidRenderID::newFromETag( $eTag ),
			new SelserContext( $pb, 0, $content )
		);

		$helper = $this->newHelper( [], StatsFactory::newNull(), $page, $body, $params );

		$content = $helper->getContent();

		// Assert that we get back the old wikitext, not wikitext derived from the HTML.
		// Since the supplied HTML is the same as the HTML in the stash, selser should
		// decide that there is nothing to do and return the wikitext unchanged.
		$this->assertSame( $oldWikitext, $content->serialize() );
	}

	public function testETagWithBadUUIDFails() {
		$page = $this->getExistingTestPage();
		$html = 'whatever';

		// Call getParserOutput() to make sure a rendering is in the ParserCache.
		// Even though we find a rendering, it should be discarded because it doesn't match
		// the ETag.
		$access = $this->getServiceContainer()->getParserOutputAccess();
		$pageLookup = $this->getServiceContainer()->getPageStore();
		$popt = ParserOptions::newFromAnon();
		$popt->setUseParsoid();
		$access->getParserOutput( $pageLookup->getPageByReference( $page ), $popt )->getValue();

		$revid = $page->getLatest();
		$eTag = "\"$revid/nope-nope-nope\"";

		$body = [ 'html' => $html, 'original' => [ 'renderid' => $eTag ] ];
		$params = [];

		$this->expectException( HttpException::class );
		$this->expectExceptionCode( 412 );
		$helper = $this->newHelper( [], StatsFactory::newNull(), $page, $body, $params );
		$helper->getContent();
	}

	public function testETagWithBadRevIDFails() {
		$page = $this->getExistingTestPage();
		$html = 'whatever';

		// Non-Existing revision
		$eTag = "\"1111111/nope-nope-nope\"";

		$body = [ 'html' => $html, 'original' => [ 'renderid' => $eTag ] ];
		$params = [];

		$this->expectException( HttpException::class );
		$this->expectExceptionCode( 412 );
		$helper = $this->newHelper( [], StatsFactory::newNull(), $page, $body, $params );
		$helper->getContent();
	}

	public function testResponseWithRenderIDFallbackToParserCache() {
		// use wikitext that would be normalized without selser.
		$oldWikitext = '<p >testing</P>';
		$rev = $this->editPage( __METHOD__, $oldWikitext )->value['revision-record'];
		$page = $rev->getPage();

		$access = $this->getServiceContainer()->getParserOutputAccess();
		$pageLookup = $this->getServiceContainer()->getPageStore();

		$popt = ParserOptions::newFromAnon();
		$popt->setUseParsoid();
		$pout = $access->getParserOutput( $pageLookup->getPageByReference( $page ), $popt )->getValue();

		$key = ParsoidRenderID::newFromParserOutput( $pout )->getKey();
		$html = $pout->getRawText();

		// Load the original data based on the ETag
		$body = [ 'html' => $html, 'original' => [ 'renderid' => $key ] ];
		$params = [];

		// We are asking for a stash key that is not in the stash.
		// However, a rendering with the corresponding key is in the ParserCache.
		// Because of this, the code below will not throw to trigger a 412 response.
		$helper = $this->newHelper( [], StatsFactory::newNull(), $page, $body, $params );
		$content = $helper->getContent();

		// The wikitext should not have been normalized by re-serialization
		$this->assertSame( $oldWikitext, $content->serialize() );
	}

	public function testResponseWithRevisionIDFallbackToRendering() {
		// use wikitext that would be normalized without selser.
		$oldWikitext = '<p >testing</P>';
		$rev = $this->editPage( __METHOD__, $oldWikitext )->value['revision-record'];
		$page = $rev->getPage();

		$access = $this->getServiceContainer()->getParserOutputAccess();
		$pageLookup = $this->getServiceContainer()->getPageStore();

		$popt = ParserOptions::newFromAnon();
		$popt->setUseParsoid();
		$pout = $access->getParserOutput( $pageLookup->getPageByReference( $page ), $popt )->getValue();
		$html = $pout->getRawText();

		// Load the original data based on the ETag
		$body = [ 'html' => $html, 'original' => [ 'revid' => $rev->getId() ] ];
		$params = [];

		// We are asking for a stash key that is not in the stash.
		// However, a rendering with the corresponding key is in the ParserCache.
		// Because of this, the code below will not trigger a 412 response.
		$helper = $this->newHelper( [], StatsFactory::newNull(), $page, $body, $params );
		$content = $helper->getContent();

		// The wikitext should not have been normalized by re-serialization
		$this->assertSame( $oldWikitext, $content->serialize() );
	}

	public static function provideHandlesParsoidError() {
		yield 'ClientError' => [
			new ClientError( 'TEST_TEST' ),
			new LocalizedHttpException(
				new MessageValue( 'rest-html-backend-error' ),
				400,
				[
					'reason' => 'TEST_TEST'
				]
			)
		];
		yield 'ResourceLimitExceededException' => [
			new ResourceLimitExceededException( 'TEST_TEST' ),
			new LocalizedHttpException(
				new MessageValue( 'rest-resource-limit-exceeded' ),
				413,
				[
					'reason' => 'TEST_TEST'
				]
			)
		];
	}

	/**
	 * @dataProvider provideHandlesParsoidError
	 */
	public function testHandlesParsoidError(
		Exception $parsoidException,
		Exception $expectedException
	) {
		$page = $this->getExistingTestPage( __METHOD__ );

		$body = [ 'html' => 'hi', ];
		$params = [];

		$helper = $this->newHelper( [
			'htmlToContent' => static function () use ( $parsoidException ) {
				throw $parsoidException;
			}
		], StatsFactory::newNull(), $page, $body, $params );

		$this->expectExceptionObject( $expectedException );
		$helper->getContent();
	}

	public function testHandlesInvalidRenderID(): void {
		$page = $this->getExistingTestPage( __METHOD__ );

		$body = [ 'html' => 'hi', 'original' => [ 'renderid' => 'foo' ] ];
		$params = [];

		$this->expectExceptionObject( new LocalizedHttpException(
			new MessageValue( 'rest-parsoid-bad-render-id', [ 'foo' ] ),
			400
		) );

		$this->newHelper( [], StatsFactory::newNull(), $page, $body, $params );
	}

	private function newHtmlToContentTransform( $html, $methodOverrides = [] ): HtmlToContentTransform {
		$transform = $this->getMockBuilder( HtmlToContentTransform::class )
			->onlyMethods( array_keys( $methodOverrides ) )
			->setConstructorArgs( [
				$html,
				$this->getExistingTestPage(),
				new Parsoid(
					$this->getServiceContainer()->getParsoidSiteConfig(),
					$this->getServiceContainer()->getParsoidDataAccess()
				),
				MainConfigSchema::getDefaultValue( MainConfigNames::ParsoidSettings ),
				$this->getServiceContainer()->getParsoidPageConfigFactory(),
				$this->getServiceContainer()->getContentHandlerFactory()
			] )
			->getMock();

		foreach ( $methodOverrides as $method => $callback ) {
			$transform->method( $method )->willReturnCallback( $callback );
		}

		return $transform;
	}

}