forked from zulip/zulip-flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_test.dart
More file actions
1827 lines (1593 loc) · 77.2 KB
/
content_test.dart
File metadata and controls
1827 lines (1593 loc) · 77.2 KB
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
import 'package:checks/checks.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_checks/flutter_checks.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:legacy_checks/legacy_checks.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zulip/api/model/initial_snapshot.dart';
import 'package:zulip/api/model/model.dart';
import 'package:zulip/api/route/messages.dart';
import 'package:zulip/model/content.dart';
import 'package:zulip/model/narrow.dart';
import 'package:zulip/model/settings.dart';
import 'package:zulip/model/store.dart';
import 'package:zulip/widgets/content.dart';
import 'package:zulip/widgets/icons.dart';
import 'package:zulip/widgets/image.dart';
import 'package:zulip/widgets/katex.dart';
import 'package:zulip/widgets/lightbox.dart';
import 'package:zulip/widgets/message_list.dart';
import 'package:zulip/widgets/page.dart';
import 'package:zulip/widgets/text.dart';
import '../api/fake_api.dart';
import '../example_data.dart' as eg;
import '../flutter_checks.dart';
import '../model/binding.dart';
import '../model/content_test.dart';
import '../model/test_store.dart';
import '../test_images.dart';
import '../test_navigation.dart';
import 'checks.dart';
import 'dialog_checks.dart';
import 'test_app.dart';
/// Simulate a nested "inner" span's style by merging all ancestor-span
/// styles, starting from the root.
///
/// [isInnerSpan] must return true for some descendant of [outerSpan].
///
/// This isn't how the style actually gets applied in the code under test
/// (because that happens inside the engine, in SkParagraph),
/// but it should hopefully simulate it closely enough.
TextStyle? mergeSpanStylesOuterToInner(
InlineSpan outerSpan,
bool Function(InlineSpan) isInnerSpan,
) {
final styles = <TextStyle?>[];
bool recurse(InlineSpan span) {
if (isInnerSpan(span)) {
styles.add(span.style);
return false;
}
final notInSubtree = span.visitDirectChildren(recurse);
if (!notInSubtree) {
styles.add(span.style);
}
return notInSubtree;
}
final recurseResult = recurse(outerSpan);
check(recurseResult).isFalse(); // check inner span was actually found
return styles.reversed.reduce((value, element) => switch ((value, element)) {
(TextStyle(), TextStyle()) => value!.merge(element!),
(TextStyle(), null) => value,
(null, TextStyle()) => element,
(null, null) => null,
});
}
/// The "merged style" ([mergeSpanStylesOuterToInner]) of a text span
/// whose whole text matches the given pattern, under the given root span.
///
/// See also [mergedStyleOf], which can be more convenient.
TextStyle? mergedStyleOfSubstring(InlineSpan rootSpan, Pattern spanPattern) {
return mergeSpanStylesOuterToInner(rootSpan,
(span) {
if (span is! TextSpan) return false;
final text = span.text;
if (text == null) return false;
return switch (spanPattern) {
String() => text == spanPattern,
_ => spanPattern.allMatches(text)
.any((match) => match.start == 0 && match.end == text.length),
};
});
}
/// The "merged style" ([mergeSpanStylesOuterToInner]) of a text span
/// whose whole text matches the given pattern, somewhere in the tree.
///
/// This finds the relevant [Text] widget by a search for [spanPattern].
/// If [findAncestor] is non-null, the search will only consider descendants
/// of widgets matching [findAncestor].
TextStyle? mergedStyleOf(WidgetTester tester, Pattern spanPattern, {
Finder? findAncestor,
}) {
var findTextWidget = find.textContaining(spanPattern);
if (findAncestor != null) {
findTextWidget = find.descendant(of: findAncestor, matching: findTextWidget);
}
final rootSpan = tester.renderObject<RenderParagraph>(findTextWidget).text;
return mergedStyleOfSubstring(rootSpan, spanPattern);
}
/// A callback that finds some target subspan within the given span,
/// and reports the target's font size.
typedef TargetFontSizeFinder = double Function(InlineSpan rootSpan);
Widget plainContent(String html) {
return Builder(builder: (context) =>
DefaultTextStyle(
style: ContentTheme.of(context).textStylePlainParagraph,
child: BlockContentList(nodes: parseContent(html).nodes)));
}
// TODO(#488) For content that we need to show outside a per-message context
// or a context without a full PerAccountStore, make sure to include tests
// that don't provide such context.
Future<void> prepareContent(WidgetTester tester, Widget child, {
List<NavigatorObserver> navObservers = const [],
bool wrapWithPerAccountStoreWidget = false,
InitialSnapshot? initialSnapshot,
}) async {
if (wrapWithPerAccountStoreWidget) {
initialSnapshot ??= eg.initialSnapshot();
await testBinding.globalStore.add(eg.selfAccount, initialSnapshot);
} else {
assert(initialSnapshot == null);
}
addTearDown(testBinding.reset);
prepareBoringImageHttpClient();
await tester.pumpWidget(TestZulipApp(
accountId: wrapWithPerAccountStoreWidget ? eg.selfAccount.id : null,
navigatorObservers: navObservers,
child: child));
await tester.pump(); // global store
if (wrapWithPerAccountStoreWidget) {
await tester.pump();
}
debugNetworkImageHttpClientProvider = null;
}
void main() {
// For testing a new content feature:
//
// * Start by writing parsing tests using [ContentExample].
// Then use [testContentSmoke] here to smoke-test the widgets.
//
// * If the widgets have any interactive behavior, test that here too.
// Those tests might not use [ContentExample], because they're often
// clearest if the HTML text is visible directly in the test source code
// to compare with the other details of the test.
// For examples, see the "LinkNode interactions" group below.
TestZulipBinding.ensureInitialized();
Widget messageContent(String html) {
return MessageContent(message: eg.streamMessage(content: html),
content: parseContent(html));
}
/// Test that the given content example renders without throwing an exception.
///
/// This requires [ContentExample.expectedText] to be non-null in order to
/// check that the content has actually rendered. For examples where there's
/// no suitable value for [ContentExample.expectedText], use [prepareContent]
/// and write an appropriate content-has-rendered check directly.
void testContentSmoke(ContentExample example, {bool wrapWithPerAccountStoreWidget = false}) {
testWidgets('smoke: ${example.description}', (tester) async {
await prepareContent(tester, plainContent(example.html),
wrapWithPerAccountStoreWidget: wrapWithPerAccountStoreWidget);
assert(example.expectedText != null,
'testContentExample requires expectedText');
tester.widget(find.text(example.expectedText!));
});
}
/// Test the font weight found by [styleFinder] in the rendering of [content].
///
/// The weight will be expected to be [expectedWght] when the system
/// bold-text setting is not set, and to vary appropriately when it is set.
///
/// [styleFinder] must return the [TextStyle] containing the "wght"
/// (in [TextStyle.fontVariations]) and the [TextStyle.fontWeight]
/// to be checked.
void testFontWeight(String description, {
required Widget content,
required double expectedWght,
required TextStyle Function(WidgetTester tester) styleFinder,
bool wrapWithPerAccountStoreWidget = false,
}) {
for (final platformRequestsBold in [false, true]) {
testWidgets(
description + (platformRequestsBold ? ' (platform requests bold)' : ''),
(tester) async {
tester.platformDispatcher.accessibilityFeaturesTestValue =
FakeAccessibilityFeatures(boldText: platformRequestsBold);
await prepareContent(tester, content,
wrapWithPerAccountStoreWidget: wrapWithPerAccountStoreWidget);
final style = styleFinder(tester);
double effectiveExpectedWght = expectedWght;
if (platformRequestsBold) {
// bolderWght because that's what [weightVariableTextStyle] uses
effectiveExpectedWght = bolderWght(expectedWght);
}
check(style)
..fontVariations.isNotNull()
.any((it) => it..axis.equals('wght')..value.equals(effectiveExpectedWght))
..fontWeight.equals(clampVariableFontWeight(effectiveExpectedWght));
tester.platformDispatcher.clearAccessibilityFeaturesTestValue();
});
}
}
group('ThematicBreak', () {
testWidgets('smoke ThematicBreak', (tester) async {
await prepareContent(tester, plainContent(ContentExample.thematicBreak.html));
tester.widget(find.byType(ThematicBreak));
});
});
group('Heading', () {
testWidgets('plain h6', (tester) async {
await prepareContent(tester,
// "###### six"
plainContent('<h6>six</h6>'));
tester.widget(find.text('six'));
});
testWidgets('smoke test for h1, h2, h3, h4, h5', (tester) async {
await prepareContent(tester,
// "# one\n## two\n### three\n#### four\n##### five"
plainContent('<h1>one</h1>\n<h2>two</h2>\n<h3>three</h3>\n<h4>four</h4>\n<h5>five</h5>'));
check(find.byType(Heading).evaluate()).length.equals(5);
});
});
group('ListNodeWidget', () {
testWidgets('ordered list with custom start', (tester) async {
await prepareContent(tester, plainContent('<ol start="3">\n<li>third</li>\n<li>fourth</li>\n</ol>'));
expect(find.text('3. '), findsOneWidget);
expect(find.text('4. '), findsOneWidget);
expect(find.text('third'), findsOneWidget);
expect(find.text('fourth'), findsOneWidget);
});
testWidgets('list uses correct text baseline alignment', (tester) async {
await prepareContent(tester, plainContent(ContentExample.orderedListLargeStart.html));
final table = tester.widget<Table>(find.byType(Table));
check(table.defaultVerticalAlignment).equals(TableCellVerticalAlignment.baseline);
check(table.textBaseline).equals(localizedTextBaseline(tester.element(find.byType(Table))));
});
testWidgets('ordered list markers have enough space to render completely', (tester) async {
await prepareContent(tester, plainContent(ContentExample.orderedListLargeStart.html));
final marker = tester.renderObject(find.textContaining('9999.')) as RenderParagraph;
// The marker has the height of just one line of text, not more.
final textHeight = marker.size.height;
final lineHeight = marker.text.style!.height! * marker.text.style!.fontSize!;
check(textHeight).equals(lineHeight);
// The marker's text didn't overflow to more lines
// (and get cut off by a `maxLines: 1`).
check(marker).didExceedMaxLines.isFalse();
});
testWidgets('ordered list markers are end-aligned', (tester) async {
await prepareContent(tester, plainContent(ContentExample.orderedListLargeStart.html));
final marker9999 = tester.getRect(find.textContaining('9999.'));
final marker10000 = tester.getRect(find.textContaining('10000.'));
// The markers are aligned at their right edge...
check(marker9999).right.equals(marker10000.right);
// ... and not because they somehow happen to have the same width.
check(marker9999).width.isLessThan(marker10000.width);
});
});
group('Spoiler', () {
testContentSmoke(ContentExample.spoilerDefaultHeader);
testContentSmoke(ContentExample.spoilerPlainCustomHeader);
testContentSmoke(ContentExample.spoilerRichHeaderAndContent);
group('interactions: spoiler with tappable content (an image) in the header', () {
Future<List<Route<dynamic>>> prepare(WidgetTester tester, String html) async {
final pushedRoutes = <Route<dynamic>>[];
final testNavObserver = TestNavigatorObserver()
..onPushed = (route, prevRoute) => pushedRoutes.add(route);
await prepareContent(tester,
// Message is needed for the image's lightbox.
messageContent(html),
navObservers: [testNavObserver],
// We try to resolve the image's URL on the self-account's realm.
wrapWithPerAccountStoreWidget: true);
// `tester.pumpWidget` in prepareContent introduces an initial route;
// remove it so consumers only have newly pushed routes.
assert(pushedRoutes.length == 1);
pushedRoutes.removeLast();
return pushedRoutes;
}
void checkIsExpanded(WidgetTester tester,
bool expected, {
Finder? contentFinder,
}) {
final sizeTransition = tester.widget<SizeTransition>(find.ancestor(
of: contentFinder ?? find.text('hello world'),
matching: find.byType(SizeTransition),
));
check(sizeTransition.sizeFactor)
..value.equals(expected ? 1 : 0)
..status.equals(expected ? AnimationStatus.completed : AnimationStatus.dismissed);
}
const example = ContentExample.spoilerHeaderHasImagePreview;
testWidgets('tap image', (tester) async {
final pushedRoutes = await prepare(tester, example.html);
await tester.tap(find.byType(RealmContentNetworkImage));
check(pushedRoutes).single.isA<AccountPageRouteBuilder>()
.fullscreenDialog.isTrue(); // recognize the lightbox
});
testWidgets('tap header on expand/collapse icon', (tester) async {
final pushedRoutes = await prepare(tester, example.html);
checkIsExpanded(tester, false);
await tester.tap(find.byIcon(Icons.expand_more));
await tester.pumpAndSettle();
check(pushedRoutes).isEmpty(); // no lightbox
checkIsExpanded(tester, true);
await tester.tap(find.byIcon(Icons.expand_more));
await tester.pumpAndSettle();
check(pushedRoutes).isEmpty(); // no lightbox
checkIsExpanded(tester, false);
});
testWidgets('tap header away from expand/collapse icon (and image)', (tester) async {
final pushedRoutes = await prepare(tester, example.html);
checkIsExpanded(tester, false);
await tester.tapAt(
tester.getTopRight(find.byType(RealmContentNetworkImage)) + const Offset(10, 0));
await tester.pumpAndSettle();
check(pushedRoutes).isEmpty(); // no lightbox
checkIsExpanded(tester, true);
await tester.tapAt(
tester.getTopRight(find.byType(RealmContentNetworkImage)) + const Offset(10, 0));
await tester.pumpAndSettle();
check(pushedRoutes).isEmpty(); // no lightbox
checkIsExpanded(tester, false);
});
});
});
testContentSmoke(ContentExample.quotation);
group('MessageImagePreview, MessageImagePreviewList', () {
Future<void> prepare(WidgetTester tester, String html, {
List<NavigatorObserver> navObservers = const [],
}) async {
await prepareContent(tester,
navObservers: navObservers,
// Message is needed for an image's lightbox.
messageContent(html),
// We try to resolve image URLs on the self-account's realm.
// For URLs on the self-account's realm, we include the auth credential.
wrapWithPerAccountStoreWidget: true);
}
group('single image; URLs handled correctly', () {
/// Test that the right URLs are used for the right things.
///
/// [rawHref] and [rawSrc] are redundant with [example],
/// but included so they're directly visible at the callsites.
/// (The test asserts that the example HTML contains 'href="$rawHref"'
/// and 'src="$rawSrc"'.)
///
/// Pass null for [expectUrlInPreview]
/// if [expectLoadingIndicator] is true
/// or if we don't expect a preview image because of an invalid src.
///
/// Pass null for [expectThumbnailUrlInLightbox] and [expectUrlInLightbox]
/// if we don't expect to be able to offer the lightbox.
Future<void> doTest(WidgetTester tester, {
required String rawHref,
required String rawSrc,
required bool expectLoadingIndicator,
required Uri? expectUrlInPreview,
required Uri? expectThumbnailUrlInLightbox,
required Uri? expectUrlInLightbox,
// TODO(#42) required Uri expectUrlForDownload,
required ContentExample example,
}) async {
assert(!(expectUrlInPreview != null && expectLoadingIndicator));
check(example.html)
..contains('href="$rawHref"')
..contains('src="$rawSrc"');
final findImagePreview = find.byType(MessageImagePreview);
final findLoadingIndicator = find.descendant(
of: findImagePreview, matching: find.byType(CupertinoActivityIndicator));
final findLightboxPage = find.byType(ImageLightboxPage);
final transitionDurationObserver = TransitionDurationObserver();
await prepare(tester, example.html,
navObservers: [transitionDurationObserver]);
final imageInPreview = tester.widgetList<RealmContentNetworkImage>(
find.descendant(
of: findImagePreview, matching: find.byType(RealmContentNetworkImage))
).singleOrNull;
check(imageInPreview?.src).equals(expectUrlInPreview);
check(findLoadingIndicator).findsExactly(expectLoadingIndicator ? 1 : 0);
prepareBoringImageHttpClient();
final lightboxHeroInPreview = tester.widgetList<LightboxHero>(
find.descendant(of: findImagePreview, matching: find.byType(LightboxHero))
).singleOrNull;
if (expectUrlInLightbox != null) {
check(lightboxHeroInPreview).isNotNull().src.equals(expectUrlInLightbox);
} else {
check(lightboxHeroInPreview).isNull();
}
await tester.tap(findImagePreview);
await transitionDurationObserver.pumpPastTransition(tester);
final lightboxPage = tester.widgetList<ImageLightboxPage>(findLightboxPage)
.singleOrNull;
check(lightboxPage?.thumbnailUrl).equals(expectThumbnailUrlInLightbox);
check(lightboxPage?.src).equals(expectUrlInLightbox);
debugNetworkImageHttpClientProvider = null;
}
Uri url(String reference) => eg.realmUrl.resolve(reference);
testWidgets('thumbnail', (tester) async {
final rawHref = '/user_uploads/2/ce/nvoNL2LaZOciwGZ-FYagddtK/image.jpg';
final rawSrc = '/user_uploads/thumbnail/2/ce/nvoNL2LaZOciwGZ-FYagddtK/image.jpg/840x560.webp';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: url(rawSrc),
expectThumbnailUrlInLightbox: url('/user_uploads/thumbnail/2/ce/nvoNL2LaZOciwGZ-FYagddtK/image.jpg/840x560.webp'),
expectUrlInLightbox: url(rawHref),
example: ContentExample.imagePreviewSingle);
});
testWidgets('thumbnail (pre-FL 276)', (tester) async {
final rawHref = '/user_uploads/2/c3/wb9FXk8Ej6qIc28aWKcqUogD/image.jpg';
final rawSrc = '/user_uploads/thumbnail/2/c3/wb9FXk8Ej6qIc28aWKcqUogD/image.jpg/840x560.webp';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: url(rawSrc),
expectThumbnailUrlInLightbox: url(rawSrc),
expectUrlInLightbox: url(rawHref),
example: ContentExample.imagePreviewSingleNoDimensions);
});
testWidgets('thumbnail, animated', (tester) async {
final rawHref = '/user_uploads/2/9f/tZ9c5ZmsI_cSDZ6ZdJmW8pt4/2c8d985d.gif';
final rawSrc = '/user_uploads/thumbnail/2/9f/tZ9c5ZmsI_cSDZ6ZdJmW8pt4/2c8d985d.gif/840x560-anim.webp';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: url(rawSrc),
expectThumbnailUrlInLightbox: url(rawSrc),
expectUrlInLightbox: url(rawHref),
example: ContentExample.imagePreviewSingleAnimated);
});
testWidgets('thumbnail, loading', (tester) async {
final rawHref = '/user_uploads/path/to/example.png';
final rawSrc = '/static/images/loading/loader-black.svg';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: true,
expectUrlInPreview: null,
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: url(rawHref),
example: ContentExample.imagePreviewSingleLoadingPlaceholder);
});
testWidgets('thumbnail, loading (pre-FL 278)', (tester) async {
final rawHref = '/user_uploads/2/c3/wb9FXk8Ej6qIc28aWKcqUogD/image.jpg';
final rawSrc = '/static/images/loading/loader-black.svg';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: true,
expectUrlInPreview: null,
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: url(rawHref),
example: ContentExample.imagePreviewSingleLoadingPlaceholderNoDimensions);
});
testWidgets('thumbnail, loading, spinner image itself is a thumbnail', (tester) async {
final rawHref = '/user_uploads/path/to/spinner.png';
final rawSrc = '/user_uploads/thumbnail/path/to/spinner.png/840x560.webp';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: true,
expectUrlInPreview: null,
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: url(rawHref),
example: ContentExample.imagePreviewSingleLoadingPlaceholderSpinnerIsThumbnail);
});
testWidgets('no thumbnail', (tester) async {
final rawHref = 'https://chat.zulip.org/user_avatars/2/realm/icon.png?version=3';
final rawSrc = 'https://chat.zulip.org/user_avatars/2/realm/icon.png?version=3';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: Uri.parse(rawSrc),
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: Uri.parse(rawHref),
example: ContentExample.imagePreviewSingleNoThumbnail);
});
testWidgets('external; src starts with /external_content', (tester) async {
final rawHref = 'https://upload.wikimedia.org/wikipedia/commons/7/78/Verregende_bloem_van_een_Helenium_%27El_Dorado%27._22-07-2023._%28d.j.b%29.jpg';
final rawSrc = '/external_content/de28eb3abf4b7786de4545023dc42d434a2ea0c2/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37382f566572726567656e64655f626c6f656d5f76616e5f65656e5f48656c656e69756d5f253237456c5f446f7261646f2532372e5f32322d30372d323032332e5f253238642e6a2e622532392e6a7067';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: url(rawSrc),
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: url(rawSrc),
example: ContentExample.imagePreviewSingleExternal1);
});
testWidgets('external; src starts with https://uploads.zulipusercontent.net/', (tester) async {
final rawHref = 'https://upload.wikimedia.org/wikipedia/commons/7/78/Verregende_bloem_van_een_Helenium_%27El_Dorado%27._22-07-2023._%28d.j.b%29.jpg';
final rawSrc = 'https://uploads.zulipusercontent.net/99742b0f992be15283c428dd42f3b9f5db138d69/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37382f566572726567656e64655f626c6f656d5f76616e5f65656e5f48656c656e69756d5f253237456c5f446f7261646f2532372e5f32322d30372d323032332e5f253238642e6a2e622532392e6a7067';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: Uri.parse(rawSrc),
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: Uri.parse(rawSrc),
example: ContentExample.imagePreviewSingleExternal2);
});
testWidgets('external; src starts with https://custom.camo-uri.example/', (tester) async {
final rawHref = 'https://upload.wikimedia.org/wikipedia/commons/7/78/Verregende_bloem_van_een_Helenium_%27El_Dorado%27._22-07-2023._%28d.j.b%29.jpg';
final rawSrc = 'https://custom.camo-uri.example/99742b0f992be15283c428dd42f3b9f5db138d69/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37382f566572726567656e64655f626c6f656d5f76616e5f65656e5f48656c656e69756d5f253237456c5f446f7261646f2532372e5f32322d30372d323032332e5f253238642e6a2e622532392e6a7067';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: Uri.parse(rawSrc),
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: Uri.parse(rawSrc),
example: ContentExample.imagePreviewSingleExternal3);
});
testWidgets('invalid src', (tester) async {
final rawHref = '/user_uploads/2/ce/nvoNL2LaZOciwGZ-FYagddtK/image.jpg';
final rawSrc = '::not a URL::';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: null,
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: null,
example: ContentExample.imagePreviewInvalidSrc);
});
testWidgets('invalid href; external src', (tester) async {
final rawHref = '::not a URL::';
final rawSrc = '/external_content/de28eb3abf4b7786de4545023dc42d434a2ea0c2/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37382f566572726567656e64655f626c6f656d5f76616e5f65656e5f48656c656e69756d5f253237456c5f446f7261646f2532372e5f32322d30372d323032332e5f253238642e6a2e622532392e6a7067';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: url(rawSrc),
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: url(rawSrc),
example: ContentExample.imagePreviewInvalidHref1);
});
testWidgets('invalid href; thumbnail src', (tester) async {
final rawHref = '::not a URL::';
final rawSrc = '/user_uploads/thumbnail/2/ce/nvoNL2LaZOciwGZ-FYagddtK/image.jpg/840x560.webp';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: url(rawSrc),
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: null,
example: ContentExample.imagePreviewInvalidHref2);
});
testWidgets('invalid src and href', (tester) async {
final rawHref = '::not a URL::';
final rawSrc = '::not a URL::';
await doTest(tester,
rawHref: rawHref,
rawSrc: rawSrc,
expectLoadingIndicator: false,
expectUrlInPreview: null,
expectThumbnailUrlInLightbox: null,
expectUrlInLightbox: null,
example: ContentExample.imagePreviewInvalidSrcAndHref);
});
});
Uri thumbnailSrc(ImageNodeSrc src) {
final value = (src as ImageNodeSrcThumbnail).value;
return eg.realmUrl.resolve(value.defaultFormatSrc.toString());
}
Uri otherSrc(ImageNodeSrc src) {
final value = (src as ImageNodeSrcOther).value;
return eg.realmUrl.resolve(value);
}
testWidgets('multiple images', (tester) async {
final example = ContentExample.imagePreviewCluster;
await prepare(tester, example.html);
final expectedImages = (example.expectedNodes[1] as ImagePreviewNodeList).imagePreviews;
final images = tester.widgetList<RealmContentNetworkImage>(
find.byType(RealmContentNetworkImage));
check(images.map((i) => i.src).toList())
.deepEquals(expectedImages.map((n) => thumbnailSrc(n.src)));
});
testWidgets('multiple images no thumbnails', (tester) async {
const example = ContentExample.imagePreviewClusterNoThumbnails;
await prepare(tester, example.html);
final expectedImages = (example.expectedNodes[1] as ImagePreviewNodeList).imagePreviews;
final images = tester.widgetList<RealmContentNetworkImage>(
find.byType(RealmContentNetworkImage));
check(images.map((i) => i.src).toList())
.deepEquals(expectedImages.map((n) => otherSrc(n.src)));
});
testWidgets('content after image cluster', (tester) async {
const example = ContentExample.imagePreviewClusterThenContent;
await prepare(tester, example.html);
final expectedImages = (example.expectedNodes[1] as ImagePreviewNodeList).imagePreviews;
final images = tester.widgetList<RealmContentNetworkImage>(
find.byType(RealmContentNetworkImage));
check(images.map((i) => i.src).toList())
.deepEquals(expectedImages.map((n) => otherSrc(n.src)));
});
testWidgets('multiple clusters of images', (tester) async {
const example = ContentExample.imagePreviewMultipleClusters;
await prepare(tester, example.html);
final expectedImages = (example.expectedNodes[1] as ImagePreviewNodeList).imagePreviews
+ (example.expectedNodes[4] as ImagePreviewNodeList).imagePreviews;
final images = tester.widgetList<RealmContentNetworkImage>(
find.byType(RealmContentNetworkImage));
check(images.map((i) => i.src).toList())
.deepEquals(expectedImages.map((n) => otherSrc(n.src)));
});
testWidgets('image as immediate child in implicit paragraph', (tester) async {
const example = ContentExample.imagePreviewInImplicitParagraph;
await prepare(tester, example.html);
final expectedImages = ((example.expectedNodes[0] as ListNode)
.items[0][0] as ImagePreviewNodeList).imagePreviews;
final images = tester.widgetList<RealmContentNetworkImage>(
find.byType(RealmContentNetworkImage));
check(images.map((i) => i.src).toList())
.deepEquals(expectedImages.map((n) => otherSrc(n.src)));
});
testWidgets('image cluster in implicit paragraph', (tester) async {
const example = ContentExample.imagePreviewClusterInImplicitParagraph;
await prepare(tester, example.html);
final expectedImages = ((example.expectedNodes[0] as ListNode)
.items[0][1] as ImagePreviewNodeList).imagePreviews;
final images = tester.widgetList<RealmContentNetworkImage>(
find.byType(RealmContentNetworkImage));
check(images.map((i) => i.src).toList())
.deepEquals(expectedImages.map((n) => otherSrc(n.src)));
});
});
group("MessageInlineVideo", () {
Future<List<Route<dynamic>>> prepare(WidgetTester tester, String html) async {
final pushedRoutes = <Route<dynamic>>[];
final testNavObserver = TestNavigatorObserver()
..onPushed = (route, prevRoute) => pushedRoutes.add(route);
await prepareContent(tester,
// Message is needed for a video's lightbox.
messageContent(html),
navObservers: [testNavObserver],
// We try to resolve video URLs on the self-account's realm.
// With #656, we'll show a preview image. We'll try to resolve this
// image's URL on the self-account's realm. If it's on the
// self-account's realm, we'll request it with the auth credential.
// TODO(#656) in above comment, change "we will" to "we do"
wrapWithPerAccountStoreWidget: true);
// `tester.pumpWidget` in prepareContent introduces an initial route;
// remove it so consumers only have newly pushed routes.
assert(pushedRoutes.length == 1);
pushedRoutes.removeLast();
return pushedRoutes;
}
testWidgets('tapping on preview opens lightbox', (tester) async {
const example = ContentExample.videoInline;
final pushedRoutes = await prepare(tester, example.html);
await tester.tap(find.byIcon(Icons.play_arrow_rounded));
check(pushedRoutes).single.isA<AccountPageRouteBuilder>()
.fullscreenDialog.isTrue(); // opened lightbox
});
});
group("MessageEmbedVideo", () {
Future<void> prepare(WidgetTester tester, String html) async {
await prepareContent(tester,
// Message is needed for a video's lightbox.
messageContent(html),
// We try to resolve a video preview URL on the self-account's realm.
wrapWithPerAccountStoreWidget: true);
}
Future<void> checkEmbedVideo(WidgetTester tester, ContentExample example) async {
await prepare(tester, example.html);
final expectedTitle = (((example.expectedNodes[0] as ParagraphNode)
.nodes.single as LinkNode).nodes.single as TextNode).text;
await tester.ensureVisible(find.text(expectedTitle));
final expectedVideo = example.expectedNodes[1] as EmbedVideoNode;
final expectedResolvedUrl = eg.store()
.tryResolveUrl(expectedVideo.previewImageSrcUrl)!;
final image = tester.widget<RealmContentNetworkImage>(
find.byType(RealmContentNetworkImage));
check(image.src).equals(expectedResolvedUrl);
final expectedLaunchUrl = expectedVideo.hrefUrl;
await tester.tap(find.byIcon(Icons.play_arrow_rounded));
check(testBinding.takeLaunchUrlCalls())
.single.equals((url: Uri.parse(expectedLaunchUrl), mode: LaunchMode.inAppBrowserView));
}
testWidgets('video preview for youtube embed', (tester) async {
const example = ContentExample.videoEmbedYoutube;
await checkEmbedVideo(tester, example);
});
testWidgets('video preview for vimeo embed', (tester) async {
const example = ContentExample.videoEmbedVimeo;
await checkEmbedVideo(tester, example);
});
});
group("CodeBlock", () {
testContentSmoke(ContentExample.codeBlockPlain);
testContentSmoke(ContentExample.codeBlockHighlightedShort);
testContentSmoke(ContentExample.codeBlockHighlightedMultiline);
testContentSmoke(ContentExample.codeBlockSpansWithMultipleClasses);
testFontWeight('syntax highlighting: non-bold span',
expectedWght: 400,
content: plainContent(ContentExample.codeBlockHighlightedShort.html),
styleFinder: (tester) => mergedStyleOf(tester, 'class')!);
testFontWeight('syntax highlighting: bold span',
expectedWght: 700,
content: plainContent(ContentExample.codeBlockHighlightedShort.html),
styleFinder: (tester) => mergedStyleOf(tester, 'A')!);
});
group('MathBlock', () {
// See also katex_test.dart for detailed tests of
// how we render the inside of a math block.
// These tests check how it relates to the enclosing Zulip message.
testContentSmoke(ContentExample.mathBlock);
testWidgets('displays KaTeX content', (tester) async {
await prepareContent(tester, plainContent(ContentExample.mathBlock.html));
tester.widget(find.text('λ', findRichText: true));
});
testWidgets('fallback to displaying KaTeX source if unsupported KaTeX HTML', (tester) async {
await prepareContent(tester, plainContent(ContentExample.mathBlockUnknown.html));
tester.widget(find.text(r'\lambda', findRichText: true));
});
});
/// Make a [TargetFontSizeFinder] to pass to [checkFontSizeRatio],
/// from a target [Pattern] (such as a string).
TargetFontSizeFinder mkTargetFontSizeFinderFromPattern(Pattern targetPattern)
=> (InlineSpan rootSpan)
=> mergedStyleOfSubstring(rootSpan, targetPattern)!.fontSize!;
/// Check certain inline spans' font size are in a constant ratio with
/// the text around them.
///
/// The given `targetHtml` should be a self-contained HTML fragment
/// that parses as an [InlineContentNode].
///
/// [targetFontSizeFinder] should find some text in the given [InlineSpan]
/// and return its size. (Or something text-like, anyway, like the clock icon
/// in [GlobalTime].)
Future<void> checkFontSizeRatio(WidgetTester tester, {
required String targetHtml,
required TargetFontSizeFinder targetFontSizeFinder,
bool wrapWithPerAccountStoreWidget = false,
}) async {
await prepareContent(tester, wrapWithPerAccountStoreWidget: wrapWithPerAccountStoreWidget,
plainContent(
'<h1>header-plain $targetHtml</h1>\n'
'<p>paragraph-plain $targetHtml</p>'));
final headerRootSpan = tester.renderObject<RenderParagraph>(find.textContaining('header')).text;
final headerPlainStyle = mergedStyleOfSubstring(headerRootSpan, 'header-plain ');
final headerTargetFontSize = targetFontSizeFinder(headerRootSpan);
final paragraphRootSpan = tester.renderObject<RenderParagraph>(find.textContaining('paragraph')).text;
final paragraphPlainStyle = mergedStyleOfSubstring(paragraphRootSpan, 'paragraph-plain ');
final paragraphTargetFontSize = targetFontSizeFinder(paragraphRootSpan);
// Check that the font sizes even differ -- that e.g. the test hasn't grown
// some bug where we merge the [TextStyle]s in the wrong order and so get
// the same answer for every span.
check(headerPlainStyle!.fontSize! / paragraphPlainStyle!.fontSize!)
.isGreaterOrEqual(1.1);
final ratioInHeader = headerTargetFontSize / headerPlainStyle.fontSize!;
final ratioInParagraph = paragraphTargetFontSize / paragraphPlainStyle.fontSize!;
// Empirically we might have e.g. 0.825 and 0.8250000000000001.
check((ratioInHeader - ratioInParagraph).abs()).isLessThan(0.001);
}
group('strong (bold)', () {
testContentSmoke(ContentExample.strong);
TextStyle findWordBold(WidgetTester tester) {
return mergedStyleOf(tester, 'bold')!;
}
testFontWeight('in plain paragraph',
expectedWght: 600,
// **bold**
content: plainContent('<p><strong>bold</strong></p>'),
styleFinder: findWordBold,
);
for (final level in HeadingLevel.values) {
final name = level.name;
assert(RegExp(r'^h[1-6]$').hasMatch(name));
testFontWeight('in $name',
expectedWght: 800,
// # **bold**, ## **bold**, ### **bold**, etc.
content: plainContent('<$name><strong>bold</strong></$name>'),
styleFinder: findWordBold,
);
}
testFontWeight('in different kind of span in h1',
expectedWght: 800,
// # ~~**bold**~~
content: plainContent('<h1><del><strong>bold</strong></del></h1>'),
styleFinder: findWordBold,
);
testFontWeight('in spoiler header',
expectedWght: 900,
// ```spoiler regular **bold**
// content
// ```
content: plainContent(
'<div class="spoiler-block"><div class="spoiler-header">\n'
'<p>regular <strong>bold</strong></p>\n'
'</div><div class="spoiler-content" aria-hidden="true">\n'
'<p>content</p>\n'
'</div></div>'
),
styleFinder: findWordBold,
);
testFontWeight('in different kind of span in spoiler header',
expectedWght: 900,
// ```spoiler *italic **bold***
// content
// ```
content: plainContent(
'<div class="spoiler-block"><div class="spoiler-header">\n'
'<p><em>italic <strong>bold</strong></em></p>\n'
'</div><div class="spoiler-content" aria-hidden="true">\n'
'<p>content</p>\n'
'</div></div>'
),
styleFinder: findWordBold,
);
testFontWeight('in table column header',
expectedWght: 900,
// | **bold** |
// | - |
// | text |
content: plainContent(
'<table>\n'
'<thead>\n<tr>\n<th><strong>bold</strong></th>\n</tr>\n</thead>\n'
'<tbody>\n<tr>\n<td>text</td>\n</tr>\n</tbody>\n'
'</table>'),
styleFinder: findWordBold);
testFontWeight('in different kind of span in table column header',
expectedWght: 900,
// | *italic **bold*** |
// | - |
// | text |
content: plainContent(
'<table>\n'
'<thead>\n<tr>\n<th><em>italic <strong>bold</strong></em></th>\n</tr>\n</thead>\n'
'<tbody>\n<tr>\n<td>text</td>\n</tr>\n</tbody>\n'
'</table>'),
styleFinder: findWordBold);
testWidgets('has strike-through line in strike-through', (tester) async {
// Regression test for: https://github.com/zulip/zulip-flutter/issues/1817
await prepareContent(tester,
plainContent('<p><del><strong>bold</strong></del></p>'));
final style = mergedStyleOf(tester, 'bold');
check(style!.decoration).equals(TextDecoration.lineThrough);
});
});
testContentSmoke(ContentExample.deleted);
testContentSmoke(ContentExample.emphasis);
group('inline code', () {
testContentSmoke(ContentExample.inlineCode);
testWidgets('maintains font-size ratio with surrounding text', (tester) async {
await checkFontSizeRatio(tester,
targetHtml: '<code>code</code>',
targetFontSizeFinder: mkTargetFontSizeFinderFromPattern('code'));
});
testFontWeight('is bold in bold span',
// Regression test for: https://github.com/zulip/zulip-flutter/issues/1812
expectedWght: 600,
// **`bold`**
content: plainContent('<p><strong><code>bold</code></strong></p>'),
styleFinder: (tester) => mergedStyleOf(tester, 'bold')!,
);
testWidgets('is link-colored in link span', (tester) async {
// Regression test for: https://github.com/zulip/zulip-flutter/issues/806
await prepareContent(tester,
plainContent('<p><a href="https://example/"><code>code</code></a></p>'));
final style = mergedStyleOf(tester, 'code');
check(style!.color).equals(const HSLColor.fromAHSL(1, 200, 1, 0.4).toColor());
});
});
group('Mention', () {
testContentSmoke(ContentExample.userMentionPlain,
wrapWithPerAccountStoreWidget: true);
testContentSmoke(ContentExample.userMentionSilent,
wrapWithPerAccountStoreWidget: true);
testContentSmoke(ContentExample.userMentionSilentClassOrderReversed,
wrapWithPerAccountStoreWidget: true);
testContentSmoke(ContentExample.legacyUserMention,
wrapWithPerAccountStoreWidget: true);
testContentSmoke(ContentExample.groupMentionPlain,
wrapWithPerAccountStoreWidget: true);
testContentSmoke(ContentExample.groupMentionSilent,
wrapWithPerAccountStoreWidget: true);
testContentSmoke(ContentExample.groupMentionSilentClassOrderReversed,
wrapWithPerAccountStoreWidget: true);
testContentSmoke(ContentExample.channelWildcardMentionPlain,
wrapWithPerAccountStoreWidget: true);