-
Notifications
You must be signed in to change notification settings - Fork 306
/
Copy pathcompose_box_test.dart
1242 lines (1063 loc) · 49.3 KB
/
compose_box_test.dart
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 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:checks/checks.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter_checks/flutter_checks.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
import 'package:zulip/api/model/events.dart';
import 'package:zulip/api/model/model.dart';
import 'package:zulip/api/route/channels.dart';
import 'package:zulip/api/route/messages.dart';
import 'package:zulip/model/localizations.dart';
import 'package:zulip/model/narrow.dart';
import 'package:zulip/model/store.dart';
import 'package:zulip/model/typing_status.dart';
import 'package:zulip/widgets/app.dart';
import 'package:zulip/widgets/color.dart';
import 'package:zulip/widgets/compose_box.dart';
import 'package:zulip/widgets/page.dart';
import 'package:zulip/widgets/icons.dart';
import 'package:zulip/widgets/theme.dart';
import '../api/fake_api.dart';
import '../example_data.dart' as eg;
import '../flutter_checks.dart';
import '../model/binding.dart';
import '../model/test_store.dart';
import '../model/typing_status_test.dart';
import '../stdlib_checks.dart';
import 'dialog_checks.dart';
import 'test_app.dart';
void main() {
TestZulipBinding.ensureInitialized();
late PerAccountStore store;
late FakeApiConnection connection;
late ComposeBoxController? controller;
Future<void> prepareComposeBox(WidgetTester tester, {
required Narrow narrow,
User? selfUser,
List<User> otherUsers = const [],
List<ZulipStream> streams = const [],
bool? mandatoryTopics,
int? zulipFeatureLevel,
}) async {
if (narrow case ChannelNarrow(:var streamId) || TopicNarrow(: var streamId)) {
assert(streams.any((stream) => stream.streamId == streamId),
'Add a channel with "streamId" the same as of $narrow.streamId to the store.');
}
addTearDown(testBinding.reset);
selfUser ??= eg.selfUser;
zulipFeatureLevel ??= eg.futureZulipFeatureLevel;
final selfAccount = eg.account(user: selfUser, zulipFeatureLevel: zulipFeatureLevel);
await testBinding.globalStore.add(selfAccount, eg.initialSnapshot(
zulipFeatureLevel: zulipFeatureLevel,
realmMandatoryTopics: mandatoryTopics,
));
store = await testBinding.globalStore.perAccount(selfAccount.id);
await store.addUsers([selfUser, ...otherUsers]);
await store.addStreams(streams);
connection = store.connection as FakeApiConnection;
await tester.pumpWidget(TestZulipApp(accountId: selfAccount.id,
child: Column(
// This positions the compose box at the bottom of the screen,
// simulating the layout of the message list page.
children: [
const Expanded(child: SizedBox.expand()),
ComposeBox(narrow: narrow),
])));
await tester.pumpAndSettle();
controller = tester.state<ComposeBoxState>(find.byType(ComposeBox)).controller;
}
/// A [Finder] for the topic input.
///
/// To enter some text, use [enterTopic].
final topicInputFinder = find.byWidgetPredicate(
(widget) => widget is TextField && widget.controller is ComposeTopicController);
/// Set the topic input's text to [topic], using [WidgetTester.enterText].
Future<void> enterTopic(WidgetTester tester, {
required ChannelNarrow narrow,
required String topic,
}) async {
connection.prepare(body:
jsonEncode(GetStreamTopicsResult(topics: [eg.getStreamTopicsEntry()]).toJson()));
await tester.enterText(topicInputFinder, topic);
check(connection.takeRequests()).single
..method.equals('GET')
..url.path.equals('/api/v1/users/me/${narrow.streamId}/topics');
}
/// A [Finder] for the content input.
///
/// To enter some text, use [enterContent].
final contentInputFinder = find.byWidgetPredicate(
(widget) => widget is TextField && widget.controller is ComposeContentController);
/// Set the content input's text to [content], using [WidgetTester.enterText].
Future<void> enterContent(WidgetTester tester, String content) async {
await tester.enterText(contentInputFinder, content);
}
Future<void> tapSendButton(WidgetTester tester) async {
connection.prepare(json: SendMessageResult(id: 123).toJson());
await tester.tap(find.byIcon(ZulipIcons.send));
await tester.pump(Duration.zero);
}
group('ComposeBoxTheme', () {
test('lerp light to dark, no crash', () {
final a = ComposeBoxTheme.light;
final b = ComposeBoxTheme.dark;
check(() => a.lerp(b, 0.5)).returnsNormally();
});
});
group('ComposeContentController', () {
group('insertPadded', () {
// Like `parseMarkedText` in test/model/autocomplete_test.dart,
// but a bit different -- could maybe deduplicate some.
TextEditingValue parseMarkedText(String markedText) {
final textBuffer = StringBuffer();
int? insertionPoint;
int i = 0;
for (final char in markedText.codeUnits) {
if (char == 94 /* ^ */) {
if (insertionPoint != null) {
throw Exception('Test error: too many ^ in input');
}
insertionPoint = i;
continue;
}
textBuffer.writeCharCode(char);
i++;
}
if (insertionPoint == null) {
throw Exception('Test error: expected ^ in input');
}
return TextEditingValue(text: textBuffer.toString(), selection: TextSelection.collapsed(offset: insertionPoint));
}
/// Test the given `insertPadded` call, in a convenient format.
///
/// In valueBefore, represent the insertion point as "^".
/// In expectedValue, represent the collapsed selection as "^".
void testInsertPadded(String description, String valueBefore, String textToInsert, String expectedValue) {
test(description, () {
final controller = ComposeContentController();
controller.value = parseMarkedText(valueBefore);
controller.insertPadded(textToInsert);
check(controller.value).equals(parseMarkedText(expectedValue));
});
}
// TODO(?) exercise the part of insertPadded that chooses the insertion
// point based on [TextEditingValue.selection], which may be collapsed,
// expanded, or null (what they call !TextSelection.isValid).
testInsertPadded('empty; insert one line',
'^', 'a\n', 'a\n\n^');
testInsertPadded('empty; insert two lines',
'^', 'a\nb\n', 'a\nb\n\n^');
group('insert at end', () {
testInsertPadded('one empty line; insert one line',
'\n^', 'a\n', '\na\n\n^');
testInsertPadded('two empty lines; insert one line',
'\n\n^', 'a\n', '\n\na\n\n^');
testInsertPadded('one line, incomplete; insert one line',
'a^', 'b\n', 'a\n\nb\n\n^');
testInsertPadded('one line, complete; insert one line',
'a\n^', 'b\n', 'a\n\nb\n\n^');
testInsertPadded('multiple lines, last is incomplete; insert one line',
'a\nb^', 'c\n', 'a\nb\n\nc\n\n^');
testInsertPadded('multiple lines, last is complete; insert one line',
'a\nb\n^', 'c\n', 'a\nb\n\nc\n\n^');
testInsertPadded('multiple lines, last is complete; insert two lines',
'a\nb\n^', 'c\nd\n', 'a\nb\n\nc\nd\n\n^');
});
group('insert at start', () {
testInsertPadded('one empty line; insert one line',
'^\n', 'a\n', 'a\n\n^');
testInsertPadded('two empty lines; insert one line',
'^\n\n', 'a\n', 'a\n\n^\n');
testInsertPadded('one line, incomplete; insert one line',
'^a', 'b\n', 'b\n\n^a');
testInsertPadded('one line, complete; insert one line',
'^a\n', 'b\n', 'b\n\n^a\n');
testInsertPadded('multiple lines, last is incomplete; insert one line',
'^a\nb', 'c\n', 'c\n\n^a\nb');
testInsertPadded('multiple lines, last is complete; insert one line',
'^a\nb\n', 'c\n', 'c\n\n^a\nb\n');
testInsertPadded('multiple lines, last is complete; insert two lines',
'^a\nb\n', 'c\nd\n', 'c\nd\n\n^a\nb\n');
});
group('insert in middle', () {
testInsertPadded('middle of line',
'a^a\n', 'b\n', 'a\n\nb\n\n^a\n');
testInsertPadded('start of non-empty line, after empty line',
'b\n\n^a\n', 'c\n', 'b\n\nc\n\n^a\n');
testInsertPadded('end of non-empty line, before non-empty line',
'a^\nb\n', 'c\n', 'a\n\nc\n\n^b\n');
testInsertPadded('start of non-empty line, after non-empty line',
'a\n^b\n', 'c\n', 'a\n\nc\n\n^b\n');
testInsertPadded('text start; one empty line; insertion point; one empty line',
'\n^\n', 'a\n', '\na\n\n^');
testInsertPadded('text start; one empty line; insertion point; two empty lines',
'\n^\n\n', 'a\n', '\na\n\n^\n');
testInsertPadded('text start; two empty lines; insertion point; one empty line',
'\n\n^\n', 'a\n', '\n\na\n\n^');
testInsertPadded('text start; two empty lines; insertion point; two empty lines',
'\n\n^\n\n', 'a\n', '\n\na\n\n^\n');
});
});
});
group('length validation', () {
final channel = eg.stream();
/// String where there are [n] Unicode code points,
/// >[n] UTF-16 code units, and <[n] "characters" a.k.a. grapheme clusters.
String makeStringWithCodePoints(int n) {
assert(n >= 5);
const graphemeCluster = '👨👩👦';
assert(graphemeCluster.runes.length == 5);
assert(graphemeCluster.length == 8);
assert(graphemeCluster.characters.length == 1);
final result =
graphemeCluster * (n ~/ 5)
+ 'a' * (n % 5);
assert(result.runes.length == n);
return result;
}
group('content', () {
Future<void> prepareWithContent(WidgetTester tester, String content) async {
TypingNotifier.debugEnable = false;
addTearDown(TypingNotifier.debugReset);
final narrow = ChannelNarrow(channel.streamId);
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await enterTopic(tester, narrow: narrow, topic: 'some topic');
await enterContent(tester, content);
}
Future<void> checkErrorResponse(WidgetTester tester) async {
await tester.tap(find.byWidget(checkErrorDialog(tester,
expectedTitle: 'Message not sent',
expectedMessage: 'Message length shouldn\'t be greater than 10000 characters.')));
}
testWidgets('too-long content is rejected', (tester) async {
await prepareWithContent(tester,
makeStringWithCodePoints(kMaxMessageLengthCodePoints + 1));
await tapSendButton(tester);
await checkErrorResponse(tester);
});
testWidgets('max-length content not rejected', (tester) async {
await prepareWithContent(tester,
makeStringWithCodePoints(kMaxMessageLengthCodePoints));
await tapSendButton(tester);
checkNoDialog(tester);
});
testWidgets('code points not counted unnecessarily', (tester) async {
await prepareWithContent(tester, 'a' * kMaxMessageLengthCodePoints);
check(controller!.content.debugLengthUnicodeCodePointsIfLong).isNull();
});
});
group('topic', () {
Future<void> prepareWithTopic(WidgetTester tester, String topic) async {
TypingNotifier.debugEnable = false;
addTearDown(TypingNotifier.debugReset);
final narrow = ChannelNarrow(channel.streamId);
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await enterTopic(tester, narrow: narrow, topic: topic);
await enterContent(tester, 'some content');
}
Future<void> checkErrorResponse(WidgetTester tester) async {
await tester.tap(find.byWidget(checkErrorDialog(tester,
expectedTitle: 'Message not sent',
expectedMessage: 'Topic length shouldn\'t be greater than 60 characters.')));
}
testWidgets('too-long topic is rejected', (tester) async {
await prepareWithTopic(tester,
makeStringWithCodePoints(kMaxTopicLengthCodePoints + 1));
await tapSendButton(tester);
await checkErrorResponse(tester);
});
testWidgets('max-length topic not rejected', (tester) async {
await prepareWithTopic(tester,
makeStringWithCodePoints(kMaxTopicLengthCodePoints));
await tapSendButton(tester);
checkNoDialog(tester);
});
testWidgets('code points not counted unnecessarily', (tester) async {
await prepareWithTopic(tester, 'a' * kMaxTopicLengthCodePoints);
check((controller as StreamComposeBoxController)
.topic.debugLengthUnicodeCodePointsIfLong).isNull();
});
});
});
group('ComposeBox hintText', () {
final channel = eg.stream();
Future<void> prepare(WidgetTester tester, {
required Narrow narrow,
bool? mandatoryTopics,
int? zulipFeatureLevel,
}) async {
await prepareComposeBox(tester,
narrow: narrow,
otherUsers: [eg.otherUser, eg.thirdUser],
streams: [channel],
mandatoryTopics: mandatoryTopics,
zulipFeatureLevel: zulipFeatureLevel);
}
/// This checks the input's configured hint text without regard to whether
/// it's currently visible, as it won't be if the user has entered some text.
///
/// If `topicHintText` is `null`, check that the topic input is not present.
void checkComposeBoxHintTexts(WidgetTester tester, {
String? topicHintText,
required String contentHintText,
}) {
if (topicHintText != null) {
check(tester.widget<TextField>(topicInputFinder))
.decoration.isNotNull().hintText.equals(topicHintText);
} else {
check(topicInputFinder).findsNothing();
}
check(tester.widget<TextField>(contentInputFinder))
.decoration.isNotNull().hintText.equals(contentHintText);
}
group('to ChannelNarrow, topics not mandatory', () {
final narrow = ChannelNarrow(channel.streamId);
testWidgets('with empty topic, topic input has focus', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: false);
await enterTopic(tester, narrow: narrow, topic: '');
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name}');
});
testWidgets('legacy: with empty topic, topic input has focus', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: false,
zulipFeatureLevel: 333); // TODO(server-10)
await enterTopic(tester, narrow: narrow, topic: '');
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name}');
});
testWidgets('with non-empty but vacuous topic, topic input has focus', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: false);
await enterTopic(tester, narrow: narrow,
topic: eg.defaultRealmEmptyTopicDisplayName);
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name}');
});
testWidgets('with empty topic, content input has focus', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: false);
await enterContent(tester, '');
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name} > '
'${eg.defaultRealmEmptyTopicDisplayName}');
}, skip: true); // null topic names soon to be enabled
testWidgets('legacy: with empty topic, content input has focus', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: false,
zulipFeatureLevel: 333);
await enterContent(tester, '');
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name} > (no topic)');
});
testWidgets('with non-empty topic', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: false);
await enterTopic(tester, narrow: narrow, topic: 'new topic');
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name} > new topic');
});
});
group('to ChannelNarrow, mandatory topics', () {
final narrow = ChannelNarrow(channel.streamId);
testWidgets('with empty topic', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: true);
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name}');
});
testWidgets('legacy: with empty topic', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: true,
zulipFeatureLevel: 333); // TODO(server-10)
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name}');
});
group('with non-empty but vacuous topics', () {
testWidgets('realm_empty_topic_display_name', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: true);
await enterTopic(tester, narrow: narrow,
topic: eg.defaultRealmEmptyTopicDisplayName);
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name}');
});
testWidgets('"(no topic)"', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: true);
await enterTopic(tester, narrow: narrow,
topic: '(no topic)');
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name}');
});
});
testWidgets('with non-empty topic', (tester) async {
await prepare(tester, narrow: narrow, mandatoryTopics: true);
await enterTopic(tester, narrow: narrow, topic: 'new topic');
await tester.pump();
checkComposeBoxHintTexts(tester,
topicHintText: 'Topic',
contentHintText: 'Message #${channel.name} > new topic');
});
});
group('to TopicNarrow', () {
testWidgets('with non-empty topic', (tester) async {
await prepare(tester,
narrow: TopicNarrow(channel.streamId, TopicName('topic')));
checkComposeBoxHintTexts(tester,
contentHintText: 'Message #${channel.name} > topic');
});
testWidgets('with empty topic', (tester) async {
await prepare(tester,
narrow: TopicNarrow(channel.streamId, TopicName('')));
checkComposeBoxHintTexts(tester, contentHintText:
'Message #${channel.name} > ${eg.defaultRealmEmptyTopicDisplayName}');
}, skip: true); // null topic names soon to be enabled
});
testWidgets('to DmNarrow with self', (tester) async {
await prepare(tester, narrow: DmNarrow.withUser(
eg.selfUser.userId, selfUserId: eg.selfUser.userId));
checkComposeBoxHintTexts(tester,
contentHintText: 'Jot down something');
});
testWidgets('to 1:1 DmNarrow', (tester) async {
await prepare(tester, narrow: DmNarrow.withUser(
eg.otherUser.userId, selfUserId: eg.selfUser.userId));
checkComposeBoxHintTexts(tester,
contentHintText: 'Message @${eg.otherUser.fullName}');
});
testWidgets('to group DmNarrow', (tester) async {
await prepare(tester, narrow: DmNarrow.withOtherUsers(
[eg.otherUser.userId, eg.thirdUser.userId],
selfUserId: eg.selfUser.userId));
checkComposeBoxHintTexts(tester,
contentHintText: 'Message group');
});
});
group('ComposeBox textCapitalization', () {
void checkComposeBoxTextFields(WidgetTester tester, {
required bool expectTopicTextField,
}) {
if (expectTopicTextField) {
final topicController = (controller as StreamComposeBoxController).topic;
final topicTextField = tester.widgetList<TextField>(find.byWidgetPredicate(
(widget) => widget is TextField && widget.controller == topicController
)).singleOrNull;
check(topicTextField).isNotNull()
.textCapitalization.equals(TextCapitalization.none);
} else {
check(controller).isA<FixedDestinationComposeBoxController>();
check(find.byType(TextField)).findsOne(); // just content input, no topic
}
final contentTextField = tester.widget<TextField>(find.byWidgetPredicate(
(widget) => widget is TextField
&& widget.controller == controller!.content));
check(contentTextField)
.textCapitalization.equals(TextCapitalization.sentences);
}
testWidgets('_StreamComposeBox', (tester) async {
final channel = eg.stream();
await prepareComposeBox(tester,
narrow: ChannelNarrow(channel.streamId), streams: [channel]);
checkComposeBoxTextFields(tester, expectTopicTextField: true);
});
testWidgets('_FixedDestinationComposeBox', (tester) async {
final channel = eg.stream();
await prepareComposeBox(tester,
narrow: eg.topicNarrow(channel.streamId, 'topic'), streams: [channel]);
checkComposeBoxTextFields(tester, expectTopicTextField: false);
});
});
group('ComposeBox typing notices', () {
final channel = eg.stream();
final narrow = eg.topicNarrow(channel.streamId, 'some topic');
void checkTypingRequest(TypingOp op, SendableNarrow narrow) =>
checkSetTypingStatusRequests(connection.takeRequests(), [(op, narrow)]);
Future<void> checkStartTyping(WidgetTester tester, SendableNarrow narrow) async {
connection.prepare(json: {});
await enterContent(tester, 'hello world');
checkTypingRequest(TypingOp.start, narrow);
}
testWidgets('smoke TopicNarrow', (tester) async {
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await checkStartTyping(tester, narrow);
connection.prepare(json: {});
await tester.pump(store.typingNotifier.typingStoppedWaitPeriod);
checkTypingRequest(TypingOp.stop, narrow);
});
testWidgets('smoke DmNarrow', (tester) async {
final narrow = DmNarrow.withUsers(
[eg.otherUser.userId], selfUserId: eg.selfUser.userId);
await prepareComposeBox(tester, narrow: narrow);
await checkStartTyping(tester, narrow);
connection.prepare(json: {});
await tester.pump(store.typingNotifier.typingStoppedWaitPeriod);
checkTypingRequest(TypingOp.stop, narrow);
});
testWidgets('smoke ChannelNarrow', (tester) async {
final narrow = ChannelNarrow(channel.streamId);
final destinationNarrow = eg.topicNarrow(narrow.streamId, 'test topic');
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await enterTopic(tester, narrow: narrow, topic: 'test topic');
await checkStartTyping(tester, destinationNarrow);
connection.prepare(json: {});
await tester.pump(store.typingNotifier.typingStoppedWaitPeriod);
checkTypingRequest(TypingOp.stop, destinationNarrow);
});
testWidgets('clearing text sends a "typing stopped" notice', (tester) async {
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await checkStartTyping(tester, narrow);
connection.prepare(json: {});
await enterContent(tester, '');
checkTypingRequest(TypingOp.stop, narrow);
});
testWidgets('hitting send button sends a "typing stopped" notice', (tester) async {
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await checkStartTyping(tester, narrow);
connection.prepare(json: {});
connection.prepare(json: SendMessageResult(id: 123).toJson());
await tester.tap(find.byIcon(ZulipIcons.send));
await tester.pump(Duration.zero);
final requests = connection.takeRequests();
checkSetTypingStatusRequests([requests.first], [(TypingOp.stop, narrow)]);
check(requests).length.equals(2);
});
Future<void> prepareComposeBoxWithNavigation(WidgetTester tester) async {
addTearDown(testBinding.reset);
final selfUser = eg.selfUser;
final selfAccount = eg.account(user: selfUser);
await testBinding.globalStore.add(selfAccount, eg.initialSnapshot());
store = await testBinding.globalStore.perAccount(selfAccount.id);
await store.addUser(selfUser);
await store.addStream(channel);
connection = store.connection as FakeApiConnection;
await tester.pumpWidget(const ZulipApp());
await tester.pump();
final navigator = await ZulipApp.navigator;
unawaited(navigator.push(MaterialAccountWidgetRoute(
accountId: selfAccount.id, page: ComposeBox(narrow: narrow))));
await tester.pumpAndSettle();
}
testWidgets('navigating away sends a "typing stopped" notice', (tester) async {
await prepareComposeBoxWithNavigation(tester);
await checkStartTyping(tester, narrow);
connection.prepare(json: {});
(await ZulipApp.navigator).pop();
await tester.pump(Duration.zero);
checkTypingRequest(TypingOp.stop, narrow);
});
testWidgets('for content input, unfocusing sends a "typing stopped" notice', (tester) async {
final narrow = ChannelNarrow(channel.streamId);
final destinationNarrow = eg.topicNarrow(narrow.streamId, 'test topic');
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await enterTopic(tester, narrow: narrow, topic: 'test topic');
await checkStartTyping(tester, destinationNarrow);
connection.prepare(json: {});
FocusManager.instance.primaryFocus!.unfocus();
await tester.pump(Duration.zero);
checkTypingRequest(TypingOp.stop, destinationNarrow);
});
testWidgets('selection change sends a "typing started" notice', (tester) async {
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await checkStartTyping(tester, narrow);
connection.prepare(json: {});
await tester.pump(store.typingNotifier.typingStoppedWaitPeriod);
checkTypingRequest(TypingOp.stop, narrow);
connection.prepare(json: {});
controller!.content.selection =
const TextSelection(baseOffset: 0, extentOffset: 2);
checkTypingRequest(TypingOp.start, narrow);
// Ensures that a "typing stopped" notice is sent when the test ends.
connection.prepare(json: {});
await tester.pump(store.typingNotifier.typingStoppedWaitPeriod);
checkTypingRequest(TypingOp.stop, narrow);
});
testWidgets('unfocusing app sends a "typing stopped" notice', (tester) async {
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
await checkStartTyping(tester, narrow);
connection.prepare(json: {});
// While this state lives on [ServicesBinding], testWidgets resets it
// for us when the test ends so we don't have to:
// https://github.com/flutter/flutter/blob/c78c166e3ecf963ca29ed503e710fd3c71eda5c9/packages/flutter_test/lib/src/binding.dart#L1189
// On iOS and Android, a transition to [hidden] is synthesized before
// transitioning into [paused].
WidgetsBinding.instance.handleAppLifecycleStateChanged(
AppLifecycleState.hidden);
await tester.pump(Duration.zero);
checkTypingRequest(TypingOp.stop, narrow);
WidgetsBinding.instance.handleAppLifecycleStateChanged(
AppLifecycleState.paused);
await tester.pump(Duration.zero);
check(connection.lastRequest).isNull();
});
});
group('message-send request response', () {
Future<void> setupAndTapSend(WidgetTester tester, {
required void Function(int messageId) prepareResponse,
}) async {
TypingNotifier.debugEnable = false;
addTearDown(TypingNotifier.debugReset);
final zulipLocalizations = GlobalLocalizations.zulipLocalizations;
await prepareComposeBox(tester, narrow: eg.topicNarrow(123, 'some topic'),
streams: [eg.stream(streamId: 123)]);
await enterContent(tester, 'hello world');
prepareResponse(456);
await tester.tap(find.byTooltip(zulipLocalizations.composeBoxSendTooltip));
await tester.pump(Duration.zero);
check(connection.lastRequest).isA<http.Request>()
..method.equals('POST')
..url.path.equals('/api/v1/messages')
..bodyFields.deepEquals({
'type': 'stream',
'to': '123',
'topic': 'some topic',
'content': 'hello world',
'read_by_sender': 'true',
});
}
testWidgets('success', (tester) async {
await setupAndTapSend(tester, prepareResponse: (int messageId) {
connection.prepare(json: SendMessageResult(id: messageId).toJson());
});
checkNoDialog(tester);
});
testWidgets('ZulipApiException', (tester) async {
await setupAndTapSend(tester, prepareResponse: (message) {
connection.prepare(apiException: eg.apiBadRequest(
message: 'You do not have permission to initiate direct message conversations.'));
});
final zulipLocalizations = GlobalLocalizations.zulipLocalizations;
await tester.tap(find.byWidget(checkErrorDialog(tester,
expectedTitle: zulipLocalizations.errorMessageNotSent,
expectedMessage: zulipLocalizations.errorServerMessage(
'You do not have permission to initiate direct message conversations.'),
)));
});
});
group('sending to empty topic', () {
late ZulipStream channel;
Future<void> setupAndTapSend(WidgetTester tester, {
required String topicInputText,
required bool mandatoryTopics,
int? zulipFeatureLevel,
}) async {
TypingNotifier.debugEnable = false;
addTearDown(TypingNotifier.debugReset);
channel = eg.stream();
final narrow = ChannelNarrow(channel.streamId);
await prepareComposeBox(tester,
narrow: narrow, streams: [channel],
mandatoryTopics: mandatoryTopics,
zulipFeatureLevel: zulipFeatureLevel);
await enterTopic(tester, narrow: narrow, topic: topicInputText);
await tester.enterText(contentInputFinder, 'test content');
await tester.tap(find.byIcon(ZulipIcons.send));
await tester.pump();
}
void checkMessageNotSent(WidgetTester tester) {
check(connection.takeRequests()).isEmpty();
checkErrorDialog(tester,
expectedTitle: 'Message not sent',
expectedMessage: 'Topics are required in this organization.');
}
testWidgets('empty topic -> ""', (tester) async {
await setupAndTapSend(tester,
topicInputText: '',
mandatoryTopics: false);
check(connection.lastRequest).isA<http.Request>()
..method.equals('POST')
..url.path.equals('/api/v1/messages')
..bodyFields['topic'].equals('');
});
testWidgets('legacy: empty topic -> "(no topic)"', (tester) async {
await setupAndTapSend(tester,
topicInputText: '',
mandatoryTopics: false,
zulipFeatureLevel: 333);
check(connection.lastRequest).isA<http.Request>()
..method.equals('POST')
..url.path.equals('/api/v1/messages')
..bodyFields['topic'].equals('(no topic)');
});
testWidgets('if topics are mandatory, reject empty topic', (tester) async {
await setupAndTapSend(tester,
topicInputText: '',
mandatoryTopics: true);
checkMessageNotSent(tester);
});
testWidgets('if topics are mandatory, reject `realmEmptyTopicDisplayName`', (tester) async {
await setupAndTapSend(tester,
topicInputText: eg.defaultRealmEmptyTopicDisplayName,
mandatoryTopics: true);
checkMessageNotSent(tester);
});
testWidgets('if topics are mandatory, reject "(no topic)"', (tester) async {
await setupAndTapSend(tester,
topicInputText: '(no topic)',
mandatoryTopics: true);
checkMessageNotSent(tester);
});
});
group('uploads', () {
void checkAppearsLoading(WidgetTester tester, bool expected) {
final sendButtonElement = tester.element(find.ancestor(
of: find.byIcon(ZulipIcons.send),
matching: find.byType(IconButton)));
final sendButtonWidget = sendButtonElement.widget as IconButton;
final designVariables = DesignVariables.of(sendButtonElement);
final expectedIconColor = expected
? designVariables.icon.withFadedAlpha(0.5)
: designVariables.icon;
check(sendButtonWidget.icon)
.isA<Icon>().color.isNotNull().isSameColorAs(expectedIconColor);
}
group('attach from media library', () {
testWidgets('success', (tester) async {
TypingNotifier.debugEnable = false;
addTearDown(TypingNotifier.debugReset);
final channel = eg.stream();
final narrow = ChannelNarrow(channel.streamId);
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
// (When we check that the send button looks disabled, it should be because
// the file is uploading, not a pre-existing reason.)
await enterTopic(tester, narrow: narrow, topic: 'some topic');
controller!.content.value = const TextEditingValue(text: 'see image: ');
await tester.pump();
checkAppearsLoading(tester, false);
testBinding.pickFilesResult = FilePickerResult([PlatformFile(
readStream: Stream.fromIterable(['asdf'.codeUnits]),
// TODO test inference of MIME type from initial bytes, when
// it can't be inferred from path
path: '/private/var/mobile/Containers/Data/Application/foo/tmp/image.jpg',
name: 'image.jpg',
size: 12345,
)]);
connection.prepare(delay: const Duration(seconds: 1), json:
UploadFileResult(uri: '/user_uploads/1/4e/m2A3MSqFnWRLUf9SaPzQ0Up_/image.jpg').toJson());
await tester.tap(find.byIcon(ZulipIcons.image));
await tester.pump();
final call = testBinding.takePickFilesCalls().single;
check(call.allowMultiple).equals(true);
check(call.type).equals(FileType.media);
checkNoDialog(tester);
check(controller!.content.text)
.equals('see image: [Uploading image.jpg…]()\n\n');
// (the request is checked more thoroughly in API tests)
check(connection.lastRequest!).isA<http.MultipartRequest>()
..method.equals('POST')
..files.single.which((it) => it
..field.equals('file')
..length.equals(12345)
..filename.equals('image.jpg')
..contentType.asString.equals('image/jpeg')
..has<Future<List<int>>>((f) => f.finalize().toBytes(), 'contents')
.completes((it) => it.deepEquals(['asdf'.codeUnits].expand((l) => l)))
);
checkAppearsLoading(tester, true);
await tester.pump(const Duration(seconds: 1));
check(controller!.content.text)
.equals('see image: [image.jpg](/user_uploads/1/4e/m2A3MSqFnWRLUf9SaPzQ0Up_/image.jpg)\n\n');
checkAppearsLoading(tester, false);
});
// TODO test what happens when selecting/uploading fails
});
group('attach from camera', () {
testWidgets('success', (tester) async {
TypingNotifier.debugEnable = false;
addTearDown(TypingNotifier.debugReset);
final channel = eg.stream();
final narrow = ChannelNarrow(channel.streamId);
await prepareComposeBox(tester, narrow: narrow, streams: [channel]);
// (When we check that the send button looks disabled, it should be because
// the file is uploading, not a pre-existing reason.)
await enterTopic(tester, narrow: narrow, topic: 'some topic');
controller!.content.value = const TextEditingValue(text: 'see image: ');
await tester.pump();
checkAppearsLoading(tester, false);
testBinding.pickImageResult = XFile.fromData(
// TODO test inference of MIME type when it's missing here
mimeType: 'image/jpeg',
utf8.encode('asdf'),
name: 'image.jpg',
length: 12345,
path: '/private/var/mobile/Containers/Data/Application/foo/tmp/image.jpg',
);
connection.prepare(delay: const Duration(seconds: 1), json:
UploadFileResult(uri: '/user_uploads/1/4e/m2A3MSqFnWRLUf9SaPzQ0Up_/image.jpg').toJson());
await tester.tap(find.byIcon(ZulipIcons.camera));
await tester.pump();
final call = testBinding.takePickImageCalls().single;
check(call.source).equals(ImageSource.camera);
check(call.requestFullMetadata).equals(false);
checkNoDialog(tester);
check(controller!.content.text)
.equals('see image: [Uploading image.jpg…]()\n\n');
// (the request is checked more thoroughly in API tests)
check(connection.lastRequest!).isA<http.MultipartRequest>()
..method.equals('POST')
..files.single.which((it) => it
..field.equals('file')
..length.equals(12345)
..filename.equals('image.jpg')
..contentType.asString.equals('image/jpeg')
..has<Future<List<int>>>((f) => f.finalize().toBytes(), 'contents')
.completes((it) => it.deepEquals(['asdf'.codeUnits].expand((l) => l)))
);
checkAppearsLoading(tester, true);
await tester.pump(const Duration(seconds: 1));
check(controller!.content.text)
.equals('see image: [image.jpg](/user_uploads/1/4e/m2A3MSqFnWRLUf9SaPzQ0Up_/image.jpg)\n\n');
checkAppearsLoading(tester, false);
});
// TODO test what happens when capturing/uploading fails
},
// This test fails on Windows because [XFile.name] splits on
// [Platform.pathSeparator], corresponding to the actual host platform
// the test is running on, instead of the path separator for the
// target platform the test is simulating.
// TODO(upstream): unskip after fix to https://github.com/flutter/flutter/issues/161073
skip: Platform.isWindows);
});
group('error banner', () {
final zulipLocalizations = GlobalLocalizations.zulipLocalizations;
Finder inputFieldFinder() => find.descendant(
of: find.byType(ComposeBox),
matching: find.byType(TextField));
Finder attachButtonFinder(IconData icon) => find.descendant(
of: find.byType(ComposeBox),
matching: find.widgetWithIcon(IconButton, icon));
void checkComposeBoxParts({required bool areShown}) {
final inputFieldCount = inputFieldFinder().evaluate().length;
areShown ? check(inputFieldCount).isGreaterThan(0) : check(inputFieldCount).equals(0);
check(attachButtonFinder(ZulipIcons.attach_file).evaluate().length).equals(areShown ? 1 : 0);
check(attachButtonFinder(ZulipIcons.image).evaluate().length).equals(areShown ? 1 : 0);
check(attachButtonFinder(ZulipIcons.camera).evaluate().length).equals(areShown ? 1 : 0);
}
void checkBannerWithLabel(String label, {required bool isShown}) {
check(find.text(label).evaluate().length).equals(isShown ? 1 : 0);
}
void checkComposeBoxIsShown(bool isShown, {required String bannerLabel}) {
checkComposeBoxParts(areShown: isShown);
checkBannerWithLabel(bannerLabel, isShown: !isShown);
}
group('in DMs with deactivated users', () {