File: test_websocket_handler.c

package info (click to toggle)
aws-crt-python 0.20.4%2Bdfsg-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 72,656 kB
  • sloc: ansic: 381,805; python: 23,008; makefile: 6,251; sh: 4,536; cpp: 699; ruby: 208; java: 77; perl: 73; javascript: 46; xml: 11
file content (1959 lines) | stat: -rw-r--r-- 72,605 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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
/**
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

#include <aws/http/private/websocket_impl.h>

#include <aws/http/private/websocket_decoder.h>
#include <aws/http/private/websocket_encoder.h>
#include <aws/io/logging.h>
#include <aws/testing/io_testing_channel.h>

#ifdef _MSC_VER
#    pragma warning(disable : 4204) /* non-constant aggregate initializer */
#endif

/* Use small window so that we can observe it opening in tests.
 * Channel may wait until the window is small before issuing the increment command. */
static const size_t s_default_initial_window_size = 256;

#define TEST_CASE(NAME)                                                                                                \
    AWS_TEST_CASE(NAME, s_test_##NAME);                                                                                \
    static int s_test_##NAME(struct aws_allocator *allocator, void *ctx)

struct written_frame {
    struct aws_websocket_frame def;
    struct aws_byte_buf payload;
    bool is_complete;
};

struct incoming_frame {
    struct aws_websocket_incoming_frame def;
    struct aws_byte_buf payload;
    size_t on_payload_count;
    int on_complete_error_code;
    bool has_begun;
    bool is_complete;
};

static struct tester_options { bool manual_window_update; } s_tester_options;

struct tester {
    struct aws_allocator *alloc;
    struct aws_logger logger;
    void *specific_test_data;

    struct testing_channel testing_channel;
    struct aws_websocket *websocket;
    bool is_midchannel_handler;

    size_t on_send_complete_count;

    /* To make the written output of the websocket-handler easier to check,
     * we translate the written bytes back into `written_frames` using a websocket-decoder.
     * We're not testing the decoder here, just using it as a tool (decoder tests go in test_websocket_decoder.c). */
    struct written_frame written_frames[100];
    size_t num_written_frames;
    size_t num_written_io_messages;
    struct aws_websocket_decoder written_frame_decoder;

    /* Frames reported via the websocket's on_incoming_frame callbacks are recorded here */
    struct incoming_frame incoming_frames[100];
    size_t num_incoming_frames;
    size_t fail_on_incoming_frame_begin_n;    /* If set, return false on Nth incoming_frame_begin callback */
    size_t fail_on_incoming_frame_payload_n;  /* If set, return false on Nth incoming_frame_payload callback */
    size_t fail_on_incoming_frame_complete_n; /* If set, return false on Nth incoming_frame_complete callback */

    /* For pushing messages downstream, to be read by websocket handler.
     * readpush_frame is for tests to define websocket frames to be pushed downstream.
     * An encoder is used to turn these into proper bits */
    struct readpush_frame *readpush_frames;
    size_t num_readpush_frames;
    size_t readpush_frame_index;
    struct aws_websocket_encoder readpush_encoder;

    /* For pushing messages upstream, to test a websocket that's been converted to midchannel handler. */
    size_t num_writepush_messages;
    struct aws_byte_buf all_writepush_data; /* All data that's been writepushed, concatenated together */
};

/* Helps track the progress of a frame being sent. */
struct send_tester {
    struct aws_websocket_send_frame_options def; /* some properties are autoconfigured */
    struct aws_byte_cursor payload;

    size_t delay_ticks;    /* Don't send anything the first N ticks */
    size_t bytes_per_tick; /* Don't send more than N bytes per tick */
    size_t send_wrong_payload_amount;

    /* Everything below this line is auto-configured */
    struct tester *owner;

    struct aws_byte_cursor cursor; /* iterates as payload is written */
    size_t on_payload_count;
    size_t fail_on_nth_payload; /* If set, returns false on Nth callback (1 is first callback)*/

    size_t on_complete_count;
    size_t on_complete_order; /* Order that frame sent, amongst all frames sent this test */
    int on_complete_error_code;
    bool fail_on_complete; /* If true, return false from on_complete callback */
};

struct readpush_frame {
    struct aws_websocket_frame def;
    struct aws_byte_cursor payload;

    /* Everything below this is auto-configured */
    struct aws_byte_cursor cursor; /* advances as payload is written */
};

/* Run loop that keeps the websocket-handler chugging. We need this because:
 * 1) The websocket-handler won't write the next aws_io_message until the preceding one is processed.
 * 2) The websocket-handler won't finish shutdown until it can write a CLOSE frame.
 *
 * Repeat until no more work is being done:
 * - Drain task queue.
 * - Decode written aws_io_messages from raw bytes into tester->written_frames[].
 * - Mark aws_io_messages completed.
 */
static int s_drain_written_messages(struct tester *tester) {
    struct aws_linked_list *io_msgs = testing_channel_get_written_message_queue(&tester->testing_channel);
    bool still_draining;
    do {
        still_draining = false;
        testing_channel_drain_queued_tasks(&tester->testing_channel);

        while (!aws_linked_list_empty(io_msgs)) {
            struct aws_linked_list_node *node = aws_linked_list_pop_front(io_msgs);
            struct aws_io_message *msg = AWS_CONTAINER_OF(node, struct aws_io_message, queueing_handle);

            tester->num_written_io_messages++;

            struct aws_byte_cursor msg_cursor = aws_byte_cursor_from_buf(&msg->message_data);
            while (msg_cursor.len) {
                /* Make sure our arbitrarily sized buffer hasn't overflowed. */
                ASSERT_TRUE(tester->num_written_frames < AWS_ARRAY_SIZE(tester->written_frames));

                bool frame_complete;
                ASSERT_SUCCESS(
                    aws_websocket_decoder_process(&tester->written_frame_decoder, &msg_cursor, &frame_complete));

                if (frame_complete) {
                    tester->written_frames[tester->num_written_frames].is_complete = true;
                    tester->num_written_frames++;
                }
            }

            if (msg->on_completion) {
                msg->on_completion(tester->testing_channel.channel, msg, 0, msg->user_data);
                still_draining = true;
            }

            aws_mem_release(msg->allocator, msg);
        }
    } while (still_draining);

    return AWS_OP_SUCCESS;
}

static int s_on_written_frame(const struct aws_websocket_frame *frame, void *user_data) {
    struct tester *tester = user_data;
    struct written_frame *written = &tester->written_frames[tester->num_written_frames];
    written->def = *frame;
    if (frame->payload_length) {
        AWS_FATAL_ASSERT(frame->payload_length <= SIZE_MAX);
        ASSERT_SUCCESS(aws_byte_buf_init(&written->payload, tester->alloc, (size_t)frame->payload_length));
    }
    return AWS_OP_SUCCESS;
}

static int s_on_written_frame_payload(struct aws_byte_cursor data, void *user_data) {
    struct tester *tester = user_data;
    struct written_frame *written = &tester->written_frames[tester->num_written_frames];
    ASSERT_TRUE(aws_byte_buf_write_from_whole_cursor(&written->payload, data));
    return AWS_OP_SUCCESS;
}

static bool s_on_incoming_frame_begin(
    struct aws_websocket *websocket,
    const struct aws_websocket_incoming_frame *frame,
    void *user_data) {

    (void)websocket;
    struct tester *tester = user_data;

    /* Make sure our arbitrarily-sized testing buffer hasn't overflowed */
    AWS_FATAL_ASSERT(tester->num_incoming_frames < AWS_ARRAY_SIZE(tester->incoming_frames));

    if (tester->num_incoming_frames > 0) {
        /* Make sure previous frame was marked complete */
        AWS_FATAL_ASSERT(tester->incoming_frames[tester->num_incoming_frames - 1].is_complete);
    }

    struct incoming_frame *incoming_frame = &tester->incoming_frames[tester->num_incoming_frames];

    AWS_FATAL_ASSERT(!incoming_frame->has_begun);
    incoming_frame->has_begun = true;
    incoming_frame->def = *frame;

    AWS_FATAL_ASSERT(frame->payload_length <= SIZE_MAX);
    int err = aws_byte_buf_init(&incoming_frame->payload, tester->alloc, (size_t)frame->payload_length);
    AWS_FATAL_ASSERT(!err);

    if (tester->fail_on_incoming_frame_begin_n) {
        AWS_FATAL_ASSERT(tester->num_incoming_frames < tester->fail_on_incoming_frame_begin_n);

        if ((tester->num_incoming_frames + 1) == tester->fail_on_incoming_frame_begin_n) {
            return false;
        }
    }
    return true;
}

static bool s_on_incoming_frame_payload(
    struct aws_websocket *websocket,
    const struct aws_websocket_incoming_frame *frame,
    struct aws_byte_cursor data,
    void *user_data) {

    (void)websocket;
    (void)frame;
    struct tester *tester = user_data;
    struct incoming_frame *incoming_frame = &tester->incoming_frames[tester->num_incoming_frames];
    AWS_FATAL_ASSERT(incoming_frame->has_begun);
    AWS_FATAL_ASSERT(!incoming_frame->is_complete);

    /* buffer was allocated to exact payload length, so write should succeed */
    AWS_FATAL_ASSERT(aws_byte_buf_write_from_whole_cursor(&incoming_frame->payload, data));

    incoming_frame->on_payload_count++;

    if (tester->fail_on_incoming_frame_payload_n) {
        AWS_FATAL_ASSERT(incoming_frame->on_payload_count <= tester->fail_on_incoming_frame_payload_n);

        if (incoming_frame->on_payload_count == tester->fail_on_incoming_frame_payload_n) {
            return false;
        }
    }
    return true;
}

static bool s_on_incoming_frame_complete(
    struct aws_websocket *websocket,
    const struct aws_websocket_incoming_frame *frame,
    int error_code,
    void *user_data) {

    (void)websocket;
    (void)frame;
    struct tester *tester = user_data;
    struct incoming_frame *incoming_frame = &tester->incoming_frames[tester->num_incoming_frames++];
    AWS_FATAL_ASSERT(incoming_frame->has_begun);
    AWS_FATAL_ASSERT(!incoming_frame->is_complete);

    incoming_frame->is_complete = true;
    incoming_frame->on_complete_error_code = error_code;
    if (error_code == AWS_ERROR_SUCCESS) {
        AWS_FATAL_ASSERT(incoming_frame->payload.len == incoming_frame->def.payload_length);
    }

    if (tester->fail_on_incoming_frame_complete_n) {
        AWS_FATAL_ASSERT(tester->num_incoming_frames <= tester->fail_on_incoming_frame_complete_n);

        if (tester->num_incoming_frames == tester->fail_on_incoming_frame_complete_n) {
            return false;
        }
    }
    return true;
}

static void s_set_readpush_frames(struct tester *tester, struct readpush_frame *frames, size_t num_frames) {
    tester->readpush_frames = frames;
    tester->num_readpush_frames = num_frames;
    tester->readpush_frame_index = 0;
    for (size_t i = 0; i < num_frames; ++i) {
        struct readpush_frame *frame = &frames[i];
        frame->cursor = frame->payload;
        frame->def.payload_length = frame->payload.len;
    }
}

static int s_stream_readpush_payload(struct aws_byte_buf *out_buf, void *user_data) {
    struct tester *tester = user_data;

    struct readpush_frame *frame = &tester->readpush_frames[tester->readpush_frame_index];
    size_t available_bytes = out_buf->capacity - out_buf->len;
    size_t sending_bytes = available_bytes < frame->cursor.len ? available_bytes : frame->cursor.len;
    struct aws_byte_cursor sending_cursor = aws_byte_cursor_advance(&frame->cursor, sending_bytes);
    AWS_FATAL_ASSERT(sending_cursor.len > 0);

    ASSERT_TRUE(aws_byte_buf_write_from_whole_cursor(out_buf, sending_cursor));
    return AWS_OP_SUCCESS;
}

/* Options for pushing readpush_frames. Anything set to 0 is treated as "unlimited" */
struct readpush_options {
    size_t num_frames;   /* Stop after pushing this many frames. */
    size_t num_bytes;    /* Stop after pushing this many total bytes of aws_io_messages */
    size_t num_messages; /* Stop after pushing this many aws_io_messages */
    size_t message_size; /* Force fragmentation by limiting amount packed into each aws_io_message */
};

/* Encode readpush_frames into aws_io_messages and push those to websocket-handler. */
static int s_do_readpush(struct tester *tester, struct readpush_options options) {
    const size_t max_frames = options.num_frames ? options.num_frames : SIZE_MAX;
    const size_t max_bytes = options.num_bytes ? options.num_bytes : SIZE_MAX;
    const size_t max_messages = options.num_messages ? options.num_messages : SIZE_MAX;
    const size_t message_size = options.message_size ? options.message_size : (16 * 1024);

    size_t sum_frames = 0;
    size_t sum_bytes = 0;
    size_t sum_messages = 0;

    bool done = tester->readpush_frame_index >= tester->num_readpush_frames;
    while (!done) {
        size_t remaining_bytes = max_bytes - sum_bytes;
        size_t request_bytes = remaining_bytes < message_size ? remaining_bytes : message_size;
        struct aws_io_message *msg = aws_channel_acquire_message_from_pool(
            tester->testing_channel.channel, AWS_IO_MESSAGE_APPLICATION_DATA, request_bytes);
        ASSERT_NOT_NULL(msg);

        while (!done && (msg->message_data.len < msg->message_data.capacity)) {

            if (!aws_websocket_encoder_is_frame_in_progress(&tester->readpush_encoder)) {
                ASSERT_SUCCESS(aws_websocket_encoder_start_frame(
                    &tester->readpush_encoder, &tester->readpush_frames[tester->readpush_frame_index].def));
            }

            ASSERT_SUCCESS(aws_websocket_encoder_process(&tester->readpush_encoder, &msg->message_data));

            if (aws_websocket_encoder_is_frame_in_progress(&tester->readpush_encoder)) {
                /* This function doesn't expect encoder to stop until frame is done or buffer is full */
                ASSERT_UINT_EQUALS(msg->message_data.len, msg->message_data.capacity);
            } else {
                /* Frame done */
                if (++tester->readpush_frame_index >= tester->num_readpush_frames) {
                    done = true;
                }

                if (++sum_frames >= max_frames) {
                    done = true;
                }
            }
        }

        sum_bytes += msg->message_data.len;
        if (sum_bytes >= max_bytes) {
            done = true;
        }

        if (++sum_messages >= max_messages) {
            done = true;
        }

        ASSERT_SUCCESS(testing_channel_push_read_message(&tester->testing_channel, msg));
    }

    return AWS_OP_SUCCESS;
}

static int s_do_readpush_all(struct tester *tester) {
    struct readpush_options options;
    AWS_ZERO_STRUCT(options);
    return s_do_readpush(tester, options);
}

/* Check that a readpush_frame was received by websocket */
static int s_readpush_check(struct tester *tester, size_t frame_i, int expected_error_code) {
    ASSERT_TRUE(frame_i < tester->num_readpush_frames);
    struct readpush_frame *pushed = &tester->readpush_frames[frame_i];
    struct incoming_frame *received = &tester->incoming_frames[frame_i];

    ASSERT_TRUE(received->has_begun);
    ASSERT_TRUE(received->is_complete);
    ASSERT_INT_EQUALS(expected_error_code, received->on_complete_error_code);

    ASSERT_UINT_EQUALS(pushed->def.payload_length, received->def.payload_length);
    ASSERT_UINT_EQUALS(pushed->def.opcode, received->def.opcode);
    ASSERT_INT_EQUALS(pushed->def.fin, received->def.fin);

    if (received->on_complete_error_code == AWS_ERROR_SUCCESS) {
        ASSERT_UINT_EQUALS(received->def.payload_length, received->payload.len);
        ASSERT_TRUE(aws_byte_cursor_eq_byte_buf(&pushed->payload, &received->payload));
    }

    return AWS_OP_SUCCESS;
}

/* Check that a readpush_frame's payload was passed to the next handler downstream */
static int s_readpush_midchannel_check(struct tester *tester, size_t frame_i) {
    ASSERT_TRUE(frame_i < tester->num_readpush_frames);
    struct readpush_frame *pushed = &tester->readpush_frames[frame_i];
    struct aws_byte_cursor payload = pushed->payload;

    struct aws_linked_list *downstream_messages = testing_channel_get_read_message_queue(&tester->testing_channel);

    while (payload.len > 0) {
        ASSERT_FALSE(aws_linked_list_empty(downstream_messages));
        struct aws_linked_list_node *message_node = aws_linked_list_front(downstream_messages);
        struct aws_io_message *message = AWS_CONTAINER_OF(message_node, struct aws_io_message, queueing_handle);

        /* This function might be called multiple times, the copy_mark is used to track where the last check ended */
        size_t message_remainder = message->message_data.len - message->copy_mark;
        size_t compare_bytes = message_remainder < payload.len ? message_remainder : payload.len;
        struct aws_byte_cursor message_chunk =
            aws_byte_cursor_from_array(message->message_data.buffer + message->copy_mark, compare_bytes);

        struct aws_byte_cursor payload_chunk = aws_byte_cursor_advance(&payload, compare_bytes);
        ASSERT_TRUE(aws_byte_cursor_eq(&message_chunk, &payload_chunk));
        message->copy_mark += compare_bytes;
        if (message->copy_mark == message->message_data.len) {
            aws_linked_list_pop_front(downstream_messages);
            aws_mem_release(message->allocator, message);
        }
    }

    return AWS_OP_SUCCESS;
}

static int s_writepush(struct tester *tester, struct aws_byte_cursor data) {
    if (!tester->all_writepush_data.allocator) {
        ASSERT_SUCCESS(aws_byte_buf_init(&tester->all_writepush_data, tester->alloc, data.len));
    }

    while (data.len) {
        /* Ask for slightly more data than we need so that capacity != length.
         * This is to repro a bug where capacity and length were confused */
        size_t size_hint = data.len + 1;

        struct aws_io_message *msg = aws_channel_acquire_message_from_pool(
            tester->testing_channel.channel, AWS_IO_MESSAGE_APPLICATION_DATA, size_hint);
        ASSERT_NOT_NULL(msg);
        size_t chunk_size = msg->message_data.capacity < data.len ? msg->message_data.capacity : data.len;
        struct aws_byte_cursor chunk = aws_byte_cursor_advance(&data, chunk_size);
        ASSERT_NOT_NULL(chunk.ptr);
        ASSERT_TRUE(aws_byte_buf_write_from_whole_cursor(&msg->message_data, chunk));
        ASSERT_SUCCESS(testing_channel_push_write_message(&tester->testing_channel, msg));

        /* Update tracking data in tester */
        tester->num_writepush_messages++;
        ASSERT_SUCCESS(aws_byte_buf_append_dynamic(&tester->all_writepush_data, &chunk));
    }
    return AWS_OP_SUCCESS;
}

/* Scan all written_frames, and ensure that payloads of the binary frames match data */
static int s_writepush_check(struct tester *tester, size_t ignore_n_written_frames) {
    struct aws_byte_cursor expected_cursor = aws_byte_cursor_from_buf(&tester->all_writepush_data);
    for (size_t i = ignore_n_written_frames; i < tester->num_written_frames; ++i) {
        struct written_frame *frame_i = &tester->written_frames[i];
        if (aws_websocket_is_data_frame(frame_i->def.opcode)) {
            ASSERT_UINT_EQUALS(AWS_WEBSOCKET_OPCODE_BINARY, frame_i->def.opcode);
            struct aws_byte_cursor expected_i =
                aws_byte_cursor_advance(&expected_cursor, (size_t)frame_i->def.payload_length);
            ASSERT_TRUE(expected_i.len > 0);
            ASSERT_TRUE(aws_byte_cursor_eq_byte_buf(&expected_i, &frame_i->payload));
        }
    }
    ASSERT_UINT_EQUALS(0, expected_cursor.len);
    return AWS_OP_SUCCESS;
}

static int s_tester_init(struct tester *tester, struct aws_allocator *alloc) {
    aws_http_library_init(alloc);

    AWS_ZERO_STRUCT(*tester);
    tester->alloc = alloc;

    struct aws_logger_standard_options logger_options = {
        .level = AWS_LOG_LEVEL_TRACE,
        .file = stderr,
    };
    ASSERT_SUCCESS(aws_logger_init_standard(&tester->logger, tester->alloc, &logger_options));
    aws_logger_set(&tester->logger);

    struct aws_testing_channel_options test_channel_options = {.clock_fn = aws_high_res_clock_get_ticks};
    ASSERT_SUCCESS(testing_channel_init(&tester->testing_channel, alloc, &test_channel_options));

    struct aws_websocket_handler_options ws_options = {
        .allocator = alloc,
        .channel = tester->testing_channel.channel,
        .initial_window_size = s_default_initial_window_size,
        .user_data = tester,
        .on_incoming_frame_begin = s_on_incoming_frame_begin,
        .on_incoming_frame_payload = s_on_incoming_frame_payload,
        .on_incoming_frame_complete = s_on_incoming_frame_complete,
        .manual_window_update = s_tester_options.manual_window_update,
    };
    tester->websocket = aws_websocket_handler_new(&ws_options);
    ASSERT_NOT_NULL(tester->websocket);
    testing_channel_drain_queued_tasks(&tester->testing_channel);

    aws_websocket_decoder_init(
        &tester->written_frame_decoder, alloc, s_on_written_frame, s_on_written_frame_payload, tester);
    aws_websocket_encoder_init(&tester->readpush_encoder, s_stream_readpush_payload, tester);

    return AWS_OP_SUCCESS;
}

static int s_tester_clean_up(struct tester *tester) {
    aws_websocket_release(tester->websocket);
    ASSERT_SUCCESS(s_drain_written_messages(tester));

    ASSERT_SUCCESS(testing_channel_clean_up(&tester->testing_channel));

    for (size_t i = 0; i < AWS_ARRAY_SIZE(tester->written_frames); ++i) {
        aws_byte_buf_clean_up(&tester->written_frames[i].payload);
    }

    for (size_t i = 0; i < AWS_ARRAY_SIZE(tester->incoming_frames); ++i) {
        aws_byte_buf_clean_up(&tester->incoming_frames[i].payload);
    }

    aws_byte_buf_clean_up(&tester->all_writepush_data);

    aws_websocket_decoder_clean_up(&tester->written_frame_decoder);
    aws_http_library_clean_up();
    aws_logger_clean_up(&tester->logger);
    return AWS_OP_SUCCESS;
}

static int s_install_downstream_handler(struct tester *tester, size_t initial_window) {

    ASSERT_SUCCESS(aws_websocket_convert_to_midchannel_handler(tester->websocket));
    tester->is_midchannel_handler = true;

    ASSERT_SUCCESS(testing_channel_install_downstream_handler(&tester->testing_channel, initial_window));
    testing_channel_drain_queued_tasks(&tester->testing_channel);

    return AWS_OP_SUCCESS;
}

static bool s_on_stream_outgoing_payload(
    struct aws_websocket *websocket,
    struct aws_byte_buf *out_buf,
    void *user_data) {

    struct send_tester *send_tester = user_data;
    AWS_FATAL_ASSERT(websocket == send_tester->owner->websocket);

    /* If user wants frame to break websocket, write an extra byte */
    if (send_tester->send_wrong_payload_amount && (send_tester->on_payload_count == 0)) {
        aws_byte_buf_write_u8(out_buf, 'X');
    }

    send_tester->on_payload_count++;

    size_t space_available = out_buf->capacity - out_buf->len;

    size_t bytes_max = send_tester->cursor.len;
    if (send_tester->delay_ticks > 0) {
        bytes_max = 0;
        send_tester->delay_ticks--;
    } else if (send_tester->bytes_per_tick > 0) {
        bytes_max = bytes_max < send_tester->bytes_per_tick ? bytes_max : send_tester->bytes_per_tick;
    }

    size_t amount_to_send = bytes_max < space_available ? bytes_max : space_available;
    struct aws_byte_cursor send_cursor = aws_byte_cursor_advance(&send_tester->cursor, amount_to_send);
    if (send_cursor.len) {
        aws_byte_buf_write_from_whole_cursor(out_buf, send_cursor);
    }

    if (send_tester->fail_on_nth_payload) {
        AWS_FATAL_ASSERT(send_tester->on_payload_count <= send_tester->fail_on_nth_payload);
        if (send_tester->on_payload_count == send_tester->fail_on_nth_payload) {
            return false;
        }
    }

    return true;
}

static void s_on_outgoing_frame_complete(struct aws_websocket *websocket, int error_code, void *user_data) {
    struct send_tester *send_tester = user_data;
    AWS_FATAL_ASSERT(websocket == send_tester->owner->websocket);

    send_tester->on_complete_error_code = error_code;
    AWS_FATAL_ASSERT(send_tester->on_complete_count == 0);
    send_tester->on_complete_count++;
    send_tester->on_complete_order = send_tester->owner->on_send_complete_count;
    send_tester->owner->on_send_complete_count++;
}

static int s_send_frame_ex(struct tester *tester, struct send_tester *send_tester, bool assert_on_error) {
    send_tester->owner = tester;
    send_tester->cursor = send_tester->payload;

    send_tester->def.payload_length = send_tester->payload.len;
    send_tester->def.stream_outgoing_payload = s_on_stream_outgoing_payload;
    send_tester->def.on_complete = s_on_outgoing_frame_complete;
    send_tester->def.user_data = send_tester;

    if (assert_on_error) {
        ASSERT_SUCCESS(aws_websocket_send_frame(tester->websocket, &send_tester->def));
        return AWS_OP_SUCCESS;
    } else {
        return aws_websocket_send_frame(tester->websocket, &send_tester->def);
    }
}

static int s_send_frame(struct tester *tester, struct send_tester *send_tester) {
    return s_send_frame_ex(tester, send_tester, true);
}

static int s_send_frame_no_assert(struct tester *tester, struct send_tester *send_tester) {
    return s_send_frame_ex(tester, send_tester, false);
}

static int s_check_written_message(struct send_tester *send, size_t expected_order) {
    struct tester *tester = send->owner;

    ASSERT_UINT_EQUALS(1, send->on_complete_count);
    ASSERT_UINT_EQUALS(expected_order, send->on_complete_order);

    ASSERT_TRUE(expected_order < tester->num_written_frames);
    struct written_frame *written = &tester->written_frames[expected_order];

    ASSERT_TRUE(written->is_complete);
    ASSERT_UINT_EQUALS(send->def.opcode, written->def.opcode);
    ASSERT_UINT_EQUALS(send->def.payload_length, written->def.payload_length);
    ASSERT_INT_EQUALS(send->def.fin, written->def.fin);

    /* All payloads sent from client should have been masked (assuming client is being tested here) */
    ASSERT_TRUE(written->def.masked);
    if (written->def.masked) {
        bool valid_masking_key = false;
        for (int i = 0; i < 4; i++) {
            if (written->def.masking_key[i]) {
                valid_masking_key = true;
            }
        }
        ASSERT_TRUE(valid_masking_key);
    }

    /* If payload was masked, decoder already unmasked it for us, so we can directly compare contents here */
    ASSERT_TRUE(aws_byte_cursor_eq_byte_buf(&send->payload, &written->payload));

    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_sanity_check) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));
    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_refcounting) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* acquire() and then release() a refcount. The websocket should not shut down yet */
    ASSERT_PTR_EQUALS(tester.websocket, aws_websocket_acquire(tester.websocket));
    aws_websocket_release(tester.websocket);

    testing_channel_drain_queued_tasks(&tester.testing_channel);
    ASSERT_FALSE(tester.testing_channel.channel_shutdown_completed);

    /* should be safe to call release() on NULL */
    aws_websocket_release(NULL);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

static int s_websocket_handler_send_frame_common(struct aws_allocator *allocator, bool on_thread) {
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    const char *payload = "Shall I come in to cut off your threads?";

    struct send_tester send = {
        .payload = aws_byte_cursor_from_c_str(payload),
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_PING,
                .fin = true,
            },
    };

    testing_channel_set_is_on_users_thread(&tester.testing_channel, on_thread);
    ASSERT_SUCCESS(s_send_frame(&tester, &send));

    testing_channel_set_is_on_users_thread(&tester.testing_channel, true);
    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    ASSERT_SUCCESS(s_check_written_message(&send, 0));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_send_frame) {
    (void)ctx;
    return s_websocket_handler_send_frame_common(allocator, true);
}

TEST_CASE(websocket_handler_send_frame_off_thread) {
    (void)ctx;
    return s_websocket_handler_send_frame_common(allocator, false);
}

TEST_CASE(websocket_handler_send_multiple_frames) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct send_tester sending[] = {
        {
            .payload = aws_byte_cursor_from_c_str("Wee Willie Winkie runs through the town."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("Upstairs and downstairs in his nightgown."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("Rapping at the window, crying through the lock."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = false,
                },
        },
        {
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_PING,
                    .fin = true,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("Are the children all in bed, for now it's eight o'clock?"),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = true,
                },
        },

    };

    for (size_t i = 0; i < AWS_ARRAY_SIZE(sending); ++i) {
        ASSERT_SUCCESS(s_send_frame(&tester, &sending[i]));
    }

    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    for (size_t i = 0; i < AWS_ARRAY_SIZE(sending); ++i) {
        ASSERT_SUCCESS(s_check_written_message(&sending[i], i));
    }
    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_send_huge_frame) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* transmit giant buffer with random contents */
    struct aws_byte_buf giant_buf;
    ASSERT_SUCCESS(aws_byte_buf_init(&giant_buf, allocator, 100000));
    while (aws_byte_buf_write_be32(&giant_buf, (uint32_t)rand())) {
    }
    while (aws_byte_buf_write_u8(&giant_buf, (uint8_t)rand())) {
    }

    struct send_tester sending[] = {
        {
            .payload = aws_byte_cursor_from_c_str("Little frame before big one."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_BINARY,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_buf(&giant_buf),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("Little frame after big one."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = true,
                },
        },
    };

    for (size_t i = 0; i < AWS_ARRAY_SIZE(sending); ++i) {
        ASSERT_SUCCESS(s_send_frame(&tester, &sending[i]));
    }

    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    for (size_t i = 0; i < AWS_ARRAY_SIZE(sending); ++i) {
        ASSERT_SUCCESS(s_check_written_message(&sending[i], i));
    }

    /* Ensure this was actually big enough to be split across aws_io_messages */
    ASSERT_TRUE(sending[1].on_payload_count > 1);

    aws_byte_buf_clean_up(&giant_buf);
    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_send_payload_slowly) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct send_tester sending[] = {
        {
            .payload = aws_byte_cursor_from_c_str("quick A."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("s l o o w w w l l y  B."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = false,
                },
            .bytes_per_tick = 1,
        },
        {
            .payload = aws_byte_cursor_from_c_str("quick C."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = true,
                },
        },
    };

    for (size_t i = 0; i < AWS_ARRAY_SIZE(sending); ++i) {
        ASSERT_SUCCESS(s_send_frame(&tester, &sending[i]));
    }

    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    for (size_t i = 0; i < AWS_ARRAY_SIZE(sending); ++i) {
        ASSERT_SUCCESS(s_check_written_message(&sending[i], i));
    }

    /* Ensure this test really did send data over multiple callbacks */
    ASSERT_TRUE(sending[1].on_payload_count > 1);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_send_payload_with_pauses) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct send_tester sending = {
        .payload = aws_byte_cursor_from_c_str("delayed B."),
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                .fin = true,
            },
        .delay_ticks = 5,
    };

    ASSERT_SUCCESS(s_send_frame(&tester, &sending));

    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    ASSERT_SUCCESS(s_check_written_message(&sending, 0));

    /* Ensure this test really did send data over multiple callbacks */
    ASSERT_TRUE(sending.on_payload_count > 1);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_sends_nothing_after_close_frame) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct send_tester sending[] = {
        {
            .payload = aws_byte_cursor_from_c_str("Last text frame"),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
        {
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CLOSE,
                    .fin = true,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("Should not be sent."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
    };

    /* Ensure these frames are queued and processed later */
    testing_channel_set_is_on_users_thread(&tester.testing_channel, false);

    for (size_t i = 0; i < AWS_ARRAY_SIZE(sending); ++i) {
        ASSERT_SUCCESS(s_send_frame(&tester, &sending[i]));
    }

    testing_channel_set_is_on_users_thread(&tester.testing_channel, true);
    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    /* Ensure that only 1st frame and CLOSE frame were written*/
    ASSERT_UINT_EQUALS(2, tester.num_written_frames);
    ASSERT_SUCCESS(s_check_written_message(&sending[0], 0));
    ASSERT_SUCCESS(s_check_written_message(&sending[1], 1));

    /* Ensure no more frames written during shutdown */
    aws_channel_shutdown(tester.testing_channel.channel, AWS_ERROR_SUCCESS);
    ASSERT_SUCCESS(s_drain_written_messages(&tester));
    ASSERT_UINT_EQUALS(2, tester.num_written_frames);

    /* Ensure 3rd frame completed with error code */
    ASSERT_UINT_EQUALS(1, sending[2].on_complete_count);
    ASSERT_TRUE(sending[2].on_complete_error_code != AWS_ERROR_SUCCESS);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

/* Send a frame while the handler is in every conceivable state.
 * Ensure that the completion callback always fires. */
TEST_CASE(websocket_handler_send_frames_always_complete) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    enum {
        ON_THREAD_BEFORE_CLOSE,
        OFF_THREAD_BEFORE_CLOSE,
        CLOSE,
        ON_THREAD_AFTER_CLOSE,
        OFF_THREAD_AFTER_CLOSE,
        ON_THREAD_DURING_SHUTDOWN,
        OFF_THREAD_DURING_SHUTDOWN,
        ON_THREAD_AFTER_SHUTDOWN,
        OFF_THREAD_AFTER_SHUTDOWN,
        COUNT,
    };

    struct send_tester sending[COUNT];
    memset(sending, 0, sizeof(sending));
    for (int i = 0; i < COUNT; ++i) {
        struct send_tester *send = &sending[i];
        send->def.opcode = (i == CLOSE) ? AWS_WEBSOCKET_OPCODE_CLOSE : AWS_WEBSOCKET_OPCODE_PING;
        send->def.fin = true;
    }

    int sending_err[AWS_ARRAY_SIZE(sending)];

    /* Start sending frames */
    sending_err[ON_THREAD_BEFORE_CLOSE] = s_send_frame_no_assert(&tester, &sending[ON_THREAD_BEFORE_CLOSE]);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, false);
    sending_err[OFF_THREAD_BEFORE_CLOSE] = s_send_frame_no_assert(&tester, &sending[OFF_THREAD_BEFORE_CLOSE]);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, true);

    /* Send close frame */
    sending_err[CLOSE] = s_send_frame_no_assert(&tester, &sending[CLOSE]);

    sending_err[ON_THREAD_AFTER_CLOSE] = s_send_frame_no_assert(&tester, &sending[ON_THREAD_AFTER_CLOSE]);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, false);
    sending_err[OFF_THREAD_AFTER_CLOSE] = s_send_frame_no_assert(&tester, &sending[OFF_THREAD_AFTER_CLOSE]);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, true);

    /* Issue channel shutdown */
    aws_channel_shutdown(tester.testing_channel.channel, AWS_ERROR_SUCCESS);

    sending_err[ON_THREAD_DURING_SHUTDOWN] = s_send_frame_no_assert(&tester, &sending[ON_THREAD_DURING_SHUTDOWN]);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, false);
    sending_err[OFF_THREAD_DURING_SHUTDOWN] = s_send_frame_no_assert(&tester, &sending[OFF_THREAD_DURING_SHUTDOWN]);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, true);

    /* Wait for shutdown to complete */
    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    /* Try to send even more frames */
    sending_err[ON_THREAD_AFTER_SHUTDOWN] = s_send_frame_no_assert(&tester, &sending[ON_THREAD_AFTER_SHUTDOWN]);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, false);
    sending_err[OFF_THREAD_AFTER_SHUTDOWN] = s_send_frame_no_assert(&tester, &sending[OFF_THREAD_AFTER_SHUTDOWN]);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, true);

    /* Check that each send() failed immediately, or had its completion callback invoked. */
    ASSERT_SUCCESS(s_drain_written_messages(&tester));
    for (int i = 0; i < COUNT; ++i) {
        if (sending_err[i] == AWS_OP_SUCCESS) {
            ASSERT_UINT_EQUALS(1, sending[i].on_complete_count);
        }
    }

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_send_one_io_msg_at_a_time) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct aws_byte_cursor payload = aws_byte_cursor_from_c_str("bitter butter.");

    const size_t count = 10000;
    struct send_tester *sending = aws_mem_acquire(allocator, sizeof(struct send_tester) * count);
    ASSERT_NOT_NULL(sending);
    memset(sending, 0, sizeof(struct send_tester) * count);

    for (size_t i = 0; i < count; ++i) {
        struct send_tester *send = &sending[i];
        send->payload = payload;
        send->def.opcode = AWS_WEBSOCKET_OPCODE_TEXT;
        send->def.fin = true;

        ASSERT_SUCCESS(s_send_frame(&tester, send));
    }

    /* Turn off instant write completion */
    testing_channel_complete_written_messages_immediately(&tester.testing_channel, false, AWS_OP_SUCCESS);

    /* Repeatedly drain event loop and ensure that only 1 aws_io_message is written */
    struct aws_linked_list *io_msgs = testing_channel_get_written_message_queue(&tester.testing_channel);
    size_t total_io_msg_count = 0;
    while (true) {
        testing_channel_drain_queued_tasks(&tester.testing_channel);
        if (aws_linked_list_empty(io_msgs)) {
            break;
        }

        total_io_msg_count++;
        struct aws_linked_list_node *node = aws_linked_list_pop_front(io_msgs);
        struct aws_io_message *msg = AWS_CONTAINER_OF(node, struct aws_io_message, queueing_handle);

        ASSERT_TRUE(aws_linked_list_empty(io_msgs)); /* Only 1 aws_io_message should be in the channel at a time */

        if (msg->on_completion) {
            msg->on_completion(tester.testing_channel.channel, msg, AWS_ERROR_SUCCESS, msg->user_data);
        }
        aws_mem_release(msg->allocator, msg);
    }

    /* Assert that every frame sent */
    ASSERT_UINT_EQUALS(1, sending[count - 1].on_complete_count);

    /* Assert this test actually actually involved several aws_io_messages */
    ASSERT_TRUE(total_io_msg_count >= 3);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    aws_mem_release(allocator, sending);
    return AWS_OP_SUCCESS;
}

/*
 * Verifies that the write completion callbacks for websocket frames are not invoked immediately after relaying
 * towards the left end (socket) of the channel
 */
TEST_CASE(websocket_handler_delayed_write_completion) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct aws_byte_cursor payload = aws_byte_cursor_from_c_str("bitter butter.");

    const size_t count = 2;
    struct send_tester *sending = aws_mem_acquire(allocator, sizeof(struct send_tester) * count);
    ASSERT_NOT_NULL(sending);
    memset(sending, 0, sizeof(struct send_tester) * count);

    for (size_t i = 0; i < count; ++i) {
        struct send_tester *send = &sending[i];
        send->payload = payload;
        send->def.opcode = AWS_WEBSOCKET_OPCODE_TEXT;
        send->def.fin = true;

        ASSERT_SUCCESS(s_send_frame(&tester, send));
    }

    /* Turn off instant write completion and run the channel */
    testing_channel_complete_written_messages_immediately(&tester.testing_channel, false, AWS_OP_SUCCESS);
    testing_channel_drain_queued_tasks(&tester.testing_channel);

    struct aws_linked_list *io_msgs = testing_channel_get_written_message_queue(&tester.testing_channel);
    ASSERT_FALSE(aws_linked_list_empty(io_msgs));

    struct aws_linked_list_node *node = aws_linked_list_pop_front(io_msgs);
    struct aws_io_message *msg = AWS_CONTAINER_OF(node, struct aws_io_message, queueing_handle);

    /* we've relayed the frames, but no frame write completions should have been invoked */
    for (size_t i = 0; i < count; ++i) {
        struct send_tester *send = &sending[i];
        ASSERT_UINT_EQUALS(0, send->on_complete_count);
    }

    /* manually invoke the write completion on the downstream io message */
    msg->on_completion(tester.testing_channel.channel, msg, AWS_ERROR_SUCCESS, msg->user_data);
    aws_mem_release(msg->allocator, msg);

    /* now all frame write completions should have been invoked exactly once */
    for (size_t i = 0; i < count; ++i) {
        struct send_tester *send = &sending[i];
        ASSERT_UINT_EQUALS(1, send->on_complete_count);
    }

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    aws_mem_release(allocator, sending);
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_send_halts_if_payload_fn_returns_false) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct send_tester sending[] = {
        {
            /* Sending should halt after 1st frame sends 1byte of payload */
            .payload = aws_byte_cursor_from_c_str("Stop"),
            .fail_on_nth_payload = 1,
            .bytes_per_tick = 1,
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("Should never send"),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
    };

    for (size_t i = 0; i < AWS_ARRAY_SIZE(sending); ++i) {
        ASSERT_SUCCESS(s_send_frame(&tester, &sending[i]));
    }

    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    /* Check that frame stopped processing */
    ASSERT_UINT_EQUALS(1, sending[0].on_payload_count);
    ASSERT_UINT_EQUALS(1, sending[0].on_complete_count);
    ASSERT_INT_EQUALS(AWS_ERROR_HTTP_CALLBACK_FAILURE, sending[0].on_complete_error_code);

    /* The websocket should close when a callback returns false */
    ASSERT_TRUE(testing_channel_is_shutdown_completed(&tester.testing_channel));

    /* Other send should have been cancelled without it payload callback ever being invoked */
    ASSERT_UINT_EQUALS(0, sending[1].on_payload_count);
    ASSERT_UINT_EQUALS(1, sending[1].on_complete_count);
    ASSERT_INT_EQUALS(AWS_ERROR_HTTP_CONNECTION_CLOSED, sending[1].on_complete_error_code);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_shutdown_automatically_sends_close_frame) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* Shutdown channel normally */
    aws_channel_shutdown(tester.testing_channel.channel, AWS_ERROR_SUCCESS);
    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    /* Check that CLOSE frame written */
    ASSERT_UINT_EQUALS(AWS_WEBSOCKET_OPCODE_CLOSE, tester.written_frames[0].def.opcode);
    ASSERT_TRUE(tester.written_frames[0].is_complete);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

/* Ensure that, if user had queued their own CLOSE frame before shutdown,
 * The user frame is the only one that gets written. */
TEST_CASE(websocket_handler_shutdown_handles_queued_close_frame) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* Try to make it so we issue channel-shutdown while user CLOSE frame is mid-send.
     * We use the "payload delay" feature in the `send_tester` struct */
    uint8_t payload_bytes[] = {0x01, 0x02};
    struct send_tester send = {
        .payload = aws_byte_cursor_from_array(payload_bytes, sizeof(payload_bytes)),
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_CLOSE,
                .fin = true,
            },
        .delay_ticks = 5,
    };

    ASSERT_SUCCESS(s_send_frame(&tester, &send));

    /* Assert that test has one aws_io_message written, containing a partially sent frame */
    testing_channel_run_currently_queued_tasks(&tester.testing_channel);
    ASSERT_TRUE(send.on_payload_count > 0);
    ASSERT_UINT_EQUALS(0, send.on_complete_count);

    /* Shutdown channel normally */
    aws_channel_shutdown(tester.testing_channel.channel, AWS_ERROR_SUCCESS);
    ASSERT_SUCCESS(s_drain_written_messages(&tester));
    ASSERT_TRUE(testing_channel_is_shutdown_completed(&tester.testing_channel));

    /* Check that user's CLOSE frame was written, and nothing further */
    ASSERT_SUCCESS(s_check_written_message(&send, 0));
    ASSERT_UINT_EQUALS(1, tester.num_written_frames);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_shutdown_immediately_in_emergency) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* Try to make it so we issue channel-shutdown while a frame is mid-send.
     * We use the "payload delay" feature in the `send_tester` struct */
    struct send_tester send = {
        .payload = aws_byte_cursor_from_c_str("delayed payload"),
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                .fin = true,
            },
        .delay_ticks = 15,
    };

    ASSERT_SUCCESS(s_send_frame(&tester, &send));

    /* Assert that test is issuing shutdown while frame is partially written */
    testing_channel_run_currently_queued_tasks(&tester.testing_channel);
    ASSERT_TRUE(send.on_payload_count > 0);
    ASSERT_UINT_EQUALS(0, send.on_complete_count);

    /* Shutdown channel with error code, which should result in IMMEDIATE style shutdown */
    aws_channel_shutdown(tester.testing_channel.channel, AWS_IO_SOCKET_CLOSED);
    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    /* Ensure shutdown is complete at this point*/
    ASSERT_TRUE(testing_channel_is_shutdown_completed(&tester.testing_channel));

    /* Frame should not have sent completely, no CLOSE frame should have been sent either */
    ASSERT_UINT_EQUALS(1, send.on_complete_count);
    ASSERT_TRUE(send.on_complete_error_code != AWS_ERROR_SUCCESS);

    ASSERT_UINT_EQUALS(0, tester.num_written_frames);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

/* During normal shutdown, the websocket delays until a CLOSE frame can be sent.
 * This test checks that, if unexpected errors occur during that waiting period, shutdown doesn't hang forever */
TEST_CASE(websocket_handler_shutdown_handles_unexpected_write_error) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* Queue a frame that delays a while, and then breaks the websocket entirely. */
    struct send_tester send = {
        .payload = aws_byte_cursor_from_c_str("bad frame"),
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                .fin = true,
            },
        .delay_ticks = 15,
        .send_wrong_payload_amount = 1,
    };

    ASSERT_SUCCESS(s_send_frame(&tester, &send));

    /* Assert that test is issuing shutdown while frame is partially written */
    testing_channel_run_currently_queued_tasks(&tester.testing_channel);
    ASSERT_TRUE(send.on_payload_count > 0);
    ASSERT_UINT_EQUALS(0, send.on_complete_count);

    /* Shutdown channel normally, which should cause the websocket to queue a CLOSE frame and wait until it's sent. */
    aws_channel_shutdown(tester.testing_channel.channel, AWS_IO_SOCKET_CLOSED);

    /* Wait for shutdown to complete */
    ASSERT_SUCCESS(s_drain_written_messages(&tester));

    /* Assert that test did actually experience a write error */
    ASSERT_UINT_EQUALS(1, send.on_complete_count);
    ASSERT_TRUE(send.on_complete_error_code != AWS_ERROR_SUCCESS);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_close_on_thread) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    aws_websocket_close(tester.websocket, false);

    ASSERT_SUCCESS(s_drain_written_messages(&tester));
    ASSERT_TRUE(testing_channel_is_shutdown_completed(&tester.testing_channel));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_close_off_thread) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    testing_channel_set_is_on_users_thread(&tester.testing_channel, false);
    aws_websocket_close(tester.websocket, false);
    testing_channel_set_is_on_users_thread(&tester.testing_channel, true);

    ASSERT_SUCCESS(s_drain_written_messages(&tester));
    ASSERT_TRUE(testing_channel_is_shutdown_completed(&tester.testing_channel));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_read_frame) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct readpush_frame pushing[] = {
        {
            .payload = aws_byte_cursor_from_c_str("guten morgen"),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
    };

    s_set_readpush_frames(&tester, pushing, AWS_ARRAY_SIZE(pushing));
    s_do_readpush_all(&tester);

    testing_channel_drain_queued_tasks(&tester.testing_channel);

    for (size_t i = 0; i < AWS_ARRAY_SIZE(pushing); ++i) {
        ASSERT_SUCCESS(s_readpush_check(&tester, i, AWS_ERROR_SUCCESS));
    }

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_read_multiple_frames) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct readpush_frame pushing[] = {
        {
            .payload = aws_byte_cursor_from_c_str("Uno."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("Dos."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("Tres."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = true,
                },
        },
    };

    s_set_readpush_frames(&tester, pushing, AWS_ARRAY_SIZE(pushing));
    ASSERT_SUCCESS(s_do_readpush_all(&tester));

    testing_channel_drain_queued_tasks(&tester.testing_channel);

    for (size_t i = 0; i < AWS_ARRAY_SIZE(pushing); ++i) {
        ASSERT_SUCCESS(s_readpush_check(&tester, i, AWS_ERROR_SUCCESS));
    }

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_read_frames_split_across_io_messages) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct readpush_frame pushing[] = {
        {
            .payload = aws_byte_cursor_from_c_str("As dry leaves that before the wild hurricane fly,"),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("when they meet with an obstacle,"),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = false,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("mount to the sky"),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION,
                    .fin = true,
                },
        },
    };

    s_set_readpush_frames(&tester, pushing, AWS_ARRAY_SIZE(pushing));

    /* Send 1 byte at a time to ensure we can tolerate frames split across multiple aws_io_messages */
    struct readpush_options options = {.message_size = 1};
    ASSERT_SUCCESS(s_do_readpush(&tester, options));

    testing_channel_drain_queued_tasks(&tester.testing_channel);

    for (size_t i = 0; i < AWS_ARRAY_SIZE(pushing); ++i) {
        ASSERT_SUCCESS(s_readpush_check(&tester, i, AWS_ERROR_SUCCESS));
    }

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_read_frames_complete_on_shutdown) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct readpush_frame pushing[] = {
        {
            .payload = aws_byte_cursor_from_c_str("This frame will not be completely sent."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
    };

    s_set_readpush_frames(&tester, pushing, AWS_ARRAY_SIZE(pushing));

    /* Push most, but not all, of a frame */
    struct readpush_options options = {
        .num_bytes = (size_t)(aws_websocket_frame_encoded_size(&pushing[0].def) - 1),
    };
    s_do_readpush(&tester, options);

    /* Shut down channel */
    aws_channel_shutdown(tester.testing_channel.channel, AWS_ERROR_SUCCESS);
    s_drain_written_messages(&tester);

    /* Check that completion callbacks fired */
    ASSERT_SUCCESS(s_readpush_check(&tester, 0, AWS_ERROR_HTTP_CONNECTION_CLOSED));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_read_halts_if_begin_fn_returns_false) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct readpush_frame pushing[] = {
        {
            .payload = aws_byte_cursor_from_c_str("Fail on frame begin."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("This frame should never get read."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
    };

    tester.fail_on_incoming_frame_begin_n = 1;

    s_set_readpush_frames(&tester, pushing, AWS_ARRAY_SIZE(pushing));
    ASSERT_SUCCESS(s_do_readpush_all(&tester));

    s_drain_written_messages(&tester);

    /* First frame should have completed immediately with an error */
    ASSERT_SUCCESS(s_readpush_check(&tester, 0, AWS_ERROR_HTTP_CALLBACK_FAILURE));
    ASSERT_UINT_EQUALS(0, tester.incoming_frames[0].on_payload_count);

    /* No further frames should have been read */
    ASSERT_UINT_EQUALS(1, tester.num_incoming_frames);

    /* Callback failure should have caused connection to close */
    ASSERT_TRUE(testing_channel_is_shutdown_completed(&tester.testing_channel));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_read_halts_if_payload_fn_returns_false) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct readpush_frame pushing[] = {
        {
            .payload = aws_byte_cursor_from_c_str("Fail on payload."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("This frame should never get read."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
    };

    /* Return false from 1st on_payload callback. */
    tester.fail_on_incoming_frame_payload_n = 1;

    s_set_readpush_frames(&tester, pushing, AWS_ARRAY_SIZE(pushing));
    ASSERT_SUCCESS(s_do_readpush_all(&tester));

    s_drain_written_messages(&tester);

    /* First frame should complete with error */
    ASSERT_SUCCESS(s_readpush_check(&tester, 0, AWS_ERROR_HTTP_CALLBACK_FAILURE));
    ASSERT_UINT_EQUALS(1, tester.incoming_frames[0].on_payload_count);

    /* No further frames should have been read */
    ASSERT_UINT_EQUALS(1, tester.num_incoming_frames);

    /* Callback failure should have caused connection to close */
    ASSERT_TRUE(testing_channel_is_shutdown_completed(&tester.testing_channel));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_read_halts_if_complete_fn_returns_false) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    struct readpush_frame pushing[] = {
        {
            .payload = aws_byte_cursor_from_c_str("Fail on completion."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
        {
            .payload = aws_byte_cursor_from_c_str("This frame should never get read."),
            .def =
                {
                    .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                    .fin = true,
                },
        },
    };

    /* Return false when 1st frame's on_complete callback */
    tester.fail_on_incoming_frame_complete_n = 1;

    s_set_readpush_frames(&tester, pushing, AWS_ARRAY_SIZE(pushing));
    ASSERT_SUCCESS(s_do_readpush_all(&tester));

    s_drain_written_messages(&tester);

    /* First frame should have succeeded */
    ASSERT_SUCCESS(s_readpush_check(&tester, 0, AWS_ERROR_SUCCESS));

    /* No further frames should have been read */
    ASSERT_UINT_EQUALS(1, tester.num_incoming_frames);

    /* Callback failure should have caused connection to close */
    ASSERT_TRUE(testing_channel_is_shutdown_completed(&tester.testing_channel));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

static int s_window_manual_increment_common(struct aws_allocator *allocator, bool on_thread) {
    struct tester tester;
    s_tester_options.manual_window_update = true;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* Push "data" frame to websocket */
    struct readpush_frame pushing = {
        .payload = aws_byte_cursor_from_c_str("Shrink, then open"),
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_TEXT,
                .fin = true,
            },
    };

    s_set_readpush_frames(&tester, &pushing, 1);
    ASSERT_SUCCESS(s_do_readpush_all(&tester));
    testing_channel_drain_queued_tasks(&tester.testing_channel);

    /* Assert that window did not fully re-open*/
    uint64_t frame_minus_payload_size = aws_websocket_frame_encoded_size(&pushing.def) - pushing.def.payload_length;

    ASSERT_UINT_EQUALS(frame_minus_payload_size, testing_channel_last_window_update(&tester.testing_channel));

    /* Manually increment window */
    testing_channel_set_is_on_users_thread(&tester.testing_channel, on_thread);
    aws_websocket_increment_read_window(tester.websocket, (size_t)pushing.def.payload_length);

    /* Assert it re-opened that much */
    testing_channel_set_is_on_users_thread(&tester.testing_channel, true);
    testing_channel_drain_queued_tasks(&tester.testing_channel);
    ASSERT_UINT_EQUALS(pushing.def.payload_length, testing_channel_last_window_update(&tester.testing_channel));

    /* Now push a control frame, and ensure the window automatically re-opens by the whole amount */
    struct readpush_frame pushing_control_frame = {
        .payload = aws_byte_cursor_from_c_str("free data"),
        .def = {.opcode = AWS_WEBSOCKET_OPCODE_PONG, .fin = true},
    };

    s_set_readpush_frames(&tester, &pushing_control_frame, 1);
    ASSERT_SUCCESS(s_do_readpush_all(&tester));
    testing_channel_drain_queued_tasks(&tester.testing_channel);

    ASSERT_UINT_EQUALS(
        aws_websocket_frame_encoded_size(&pushing_control_frame.def),
        testing_channel_last_window_update(&tester.testing_channel));

    /* Done */
    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_window_manual_increment) {
    (void)ctx;
    return s_window_manual_increment_common(allocator, true);
}

TEST_CASE(websocket_handler_window_manual_increment_off_thread) {
    (void)ctx;
    return s_window_manual_increment_common(allocator, false);
}

TEST_CASE(websocket_midchannel_sanity_check) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));
    ASSERT_SUCCESS(s_install_downstream_handler(&tester, s_default_initial_window_size));
    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_midchannel_write_message) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));
    ASSERT_SUCCESS(s_install_downstream_handler(&tester, s_default_initial_window_size));

    /* Write data */
    struct aws_byte_cursor writing = aws_byte_cursor_from_c_str("My hat it has three corners");
    ASSERT_SUCCESS(s_writepush(&tester, writing));

    /* Compare results */
    ASSERT_SUCCESS(s_drain_written_messages(&tester));
    ASSERT_SUCCESS(s_writepush_check(&tester, 0));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_midchannel_write_multiple_messages) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));
    ASSERT_SUCCESS(s_install_downstream_handler(&tester, s_default_initial_window_size));

    struct aws_byte_cursor writing[] = {
        aws_byte_cursor_from_c_str("My hat it has three corners."),
        aws_byte_cursor_from_c_str("Three corners has my hat."),
        aws_byte_cursor_from_c_str("And had it not three corners, it would not be my hat."),
    };

    /* Write data */
    for (size_t i = 0; i < AWS_ARRAY_SIZE(writing); ++i) {
        ASSERT_SUCCESS(s_writepush(&tester, writing[i]));
    }

    /* Compare results */
    ASSERT_SUCCESS(s_drain_written_messages(&tester));
    ASSERT_SUCCESS(s_writepush_check(&tester, 0));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_midchannel_write_huge_message) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));
    ASSERT_SUCCESS(s_install_downstream_handler(&tester, s_default_initial_window_size));

    /* Fill big buffer with random data */
    struct aws_byte_buf writing;
    ASSERT_SUCCESS(aws_byte_buf_init(&writing, allocator, 1000000));
    while (aws_byte_buf_write_be32(&writing, (uint32_t)rand())) {
    }
    while (aws_byte_buf_write_u8(&writing, (uint8_t)rand())) {
    }

    /* Send as multiple aws_io_messages that are as full as they can be */
    ASSERT_SUCCESS(s_writepush(&tester, aws_byte_cursor_from_buf(&writing)));

    /* Compare results */
    ASSERT_SUCCESS(s_drain_written_messages(&tester));
    ASSERT_TRUE(tester.num_written_io_messages > 1); /* Assert that message was huge enough to stress limits */
    ASSERT_SUCCESS(s_writepush_check(&tester, 0));

    aws_byte_buf_clean_up(&writing);
    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_sends_pong_automatically) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* Read PING with a payload */
    struct readpush_frame read_ping_with_payload = {
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_PING,
                .fin = true,
            },
        .payload = aws_byte_cursor_from_c_str("echo me pls"),
    };
    s_set_readpush_frames(&tester, &read_ping_with_payload, 1);
    ASSERT_SUCCESS(s_do_readpush_all(&tester));

    /* Check that PONG is automatically written, with payload echoing the PING */
    s_drain_written_messages(&tester);
    const struct written_frame *written_frame = &tester.written_frames[0];
    ASSERT_UINT_EQUALS(AWS_WEBSOCKET_OPCODE_PONG, written_frame->def.opcode);
    ASSERT_TRUE(written_frame->is_complete);
    ASSERT_BIN_ARRAYS_EQUALS(
        read_ping_with_payload.payload.ptr,
        read_ping_with_payload.payload.len,
        written_frame->payload.buffer,
        written_frame->payload.len);

    /* Read PING without empty payload */
    struct readpush_frame read_ping_with_empty_payload = {
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_PING,
                .fin = true,
            },
    };
    s_set_readpush_frames(&tester, &read_ping_with_empty_payload, 1);
    ASSERT_SUCCESS(s_do_readpush_all(&tester));

    /* Check that PONG with empty payload is automatically written */
    s_drain_written_messages(&tester);
    written_frame = &tester.written_frames[1];
    ASSERT_UINT_EQUALS(AWS_WEBSOCKET_OPCODE_PONG, written_frame->def.opcode);
    ASSERT_TRUE(written_frame->is_complete);
    ASSERT_UINT_EQUALS(0, written_frame->payload.len);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_handler_wont_send_pong_after_close_frame) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));

    /* Send a CLOSE frame */
    struct send_tester send_close = {
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_CLOSE,
                .fin = true,
            },
    };
    ASSERT_SUCCESS(s_send_frame(&tester, &send_close));

    /* Now have the websocket read a PING */
    struct readpush_frame read_ping = {
        .def =
            {
                .opcode = AWS_WEBSOCKET_OPCODE_PING,
                .fin = true,
            },
    };
    s_set_readpush_frames(&tester, &read_ping, 1);
    ASSERT_SUCCESS(s_do_readpush_all(&tester));

    /* Check that PONG is NOT sent automatically, because a CLOSE was sent before it */
    s_drain_written_messages(&tester);
    ASSERT_TRUE(tester.num_written_frames == 1);
    ASSERT_INT_EQUALS(AWS_WEBSOCKET_OPCODE_CLOSE, tester.written_frames[0].def.opcode);

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_midchannel_read_message) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));
    ASSERT_SUCCESS(s_install_downstream_handler(&tester, s_default_initial_window_size));

    struct readpush_frame pushing = {
        .payload = aws_byte_cursor_from_c_str("Hello hello can you hear me Joe?"),
        .def = {.opcode = AWS_WEBSOCKET_OPCODE_BINARY, .fin = true},
    };

    s_set_readpush_frames(&tester, &pushing, 1);
    ASSERT_SUCCESS(s_do_readpush_all(&tester));
    testing_channel_drain_queued_tasks(&tester.testing_channel);

    ASSERT_SUCCESS(s_readpush_midchannel_check(&tester, 0));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}

TEST_CASE(websocket_midchannel_read_multiple_messages) {
    (void)ctx;
    struct tester tester;
    ASSERT_SUCCESS(s_tester_init(&tester, allocator));
    ASSERT_SUCCESS(s_install_downstream_handler(&tester, s_default_initial_window_size));

    /* Read a mix of different frame types, most of which shouldn't get passed along to next handler. */
    struct readpush_frame pushing[] = {
        {
            .payload = aws_byte_cursor_from_c_str("Message 1."),
            .def = {.opcode = AWS_WEBSOCKET_OPCODE_BINARY, .fin = true},
        },
        {
            .payload = aws_byte_cursor_from_c_str("Ignore ping frame"),
            .def = {.opcode = AWS_WEBSOCKET_OPCODE_PING, .fin = true},
        },
        {
            .payload = aws_byte_cursor_from_c_str("Ignore text frame"),
            .def = {.opcode = AWS_WEBSOCKET_OPCODE_TEXT, .fin = false},
        },
        {
            .payload = aws_byte_cursor_from_c_str("Ignore continuation of text frame"),
            .def = {.opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION, .fin = true},
        },
        {
            .payload = aws_byte_cursor_from_c_str("Message 2 fragment 1/3."),
            .def = {.opcode = AWS_WEBSOCKET_OPCODE_BINARY, .fin = false},
        },
        {
            .payload = aws_byte_cursor_from_c_str("Message 2 fragment 2/3"),
            .def = {.opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION, .fin = false},
        },
        {
            .payload = aws_byte_cursor_from_c_str("Ignore ping frame"),
            .def = {.opcode = AWS_WEBSOCKET_OPCODE_PING, .fin = true},
        },
        {
            .payload = aws_byte_cursor_from_c_str("Message 2 fragment 3/3."),
            .def = {.opcode = AWS_WEBSOCKET_OPCODE_CONTINUATION, .fin = true},
        },
    };

    s_set_readpush_frames(&tester, pushing, AWS_ARRAY_SIZE(pushing));
    ASSERT_SUCCESS(s_do_readpush_all(&tester));
    testing_channel_drain_queued_tasks(&tester.testing_channel);

    /* Check that only BINARY (and continuation of BINARY) frames passed through */
    ASSERT_SUCCESS(s_readpush_midchannel_check(&tester, 0));
    ASSERT_SUCCESS(s_readpush_midchannel_check(&tester, 4));
    ASSERT_SUCCESS(s_readpush_midchannel_check(&tester, 5));
    ASSERT_SUCCESS(s_readpush_midchannel_check(&tester, 7));

    ASSERT_SUCCESS(s_tester_clean_up(&tester));
    return AWS_OP_SUCCESS;
}