redis 1.2.0

Redis driver for Rust.
Documentation
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
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
mod support;

#[cfg(test)]
mod basic_async {
    use std::{collections::HashMap, time::Duration};

    use super::*;
    use crate::support::*;
    use assert_matches::assert_matches;
    use futures::{StreamExt, prelude::*};
    use futures_time::{future::FutureExt, task::sleep};
    #[cfg(feature = "json")]
    use redis::JsonAsyncCommands;
    use redis::{
        AsyncCommands, ErrorKind, IntoConnectionInfo, ParsingError, ProtocolVersion, PushKind,
        RedisConnectionInfo, RedisError, RedisResult, ScanOptions, ServerErrorKind, Value,
        aio::ConnectionLike, cmd, pipe,
    };
    use redis_test::redis_value;
    #[cfg(feature = "json")]
    use redis_test::server::Module;
    use redis_test::server::{redis_settings, use_protocol};
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };
    use test_macros::async_test;
    use tokio::sync::mpsc::error::TryRecvError;

    #[rstest::rstest]
    #[cfg_attr(feature = "tokio-comp", case::tokio(RuntimeType::Tokio))]
    #[cfg_attr(feature = "smol-comp", case::smol(RuntimeType::Smol))]
    #[should_panic(expected = "Internal thread panicked")]
    fn test_block_on_all_panics_from_spawns(#[case] runtime: RuntimeType) {
        use std::sync::{Arc, atomic::AtomicBool};

        let slept = Arc::new(AtomicBool::new(false));
        let slept_clone = slept.clone();
        block_on_all(
            async {
                spawn(async move {
                    futures_time::task::sleep(futures_time::time::Duration::from_millis(1)).await;
                    slept_clone.store(true, std::sync::atomic::Ordering::Relaxed);
                    panic!("As it should");
                });

                loop {
                    futures_time::task::sleep(futures_time::time::Duration::from_millis(2)).await;
                    if slept.load(std::sync::atomic::Ordering::Relaxed) {
                        break;
                    }
                }
            },
            runtime,
        );
    }

    #[async_test]
    async fn args(mut con: impl ConnectionLike) {
        redis::cmd("SET")
            .arg("key1")
            .arg(b"foo")
            .exec_async(&mut con)
            .await
            .unwrap();
        redis::cmd("SET")
            .arg(&["key2", "bar"])
            .exec_async(&mut con)
            .await
            .unwrap();
        let result = redis::cmd("MGET")
            .arg(&["key1", "key2"])
            .query_async(&mut con)
            .await;
        assert_eq!(result, Ok(("foo".to_string(), b"bar".to_vec())));
    }

    #[async_test]
    async fn no_response_skips_response_even_on_error(mut con: impl ConnectionLike) {
        redis::cmd("SET")
            .arg("key")
            .arg(b"foo")
            .set_no_response(true)
            .exec_async(&mut con)
            .await
            .unwrap();

        // this should error, since we hset a string value, but we shouldn't receive the error, because we ignore the response
        redis::cmd("HSET")
            .arg("key")
            .arg(b"foo")
            .arg("bar")
            .set_no_response(true)
            .exec_async(&mut con)
            .await
            .unwrap();

        let result = redis::cmd("GET").arg("key").query_async(&mut con).await;
        assert_eq!(result, Ok("foo".to_string()));
    }

    #[cfg(feature = "tokio-comp")]
    #[tokio::test]
    async fn works_with_paused_time_when_no_timeouts_are_set() {
        use redis::AsyncConnectionConfig;
        tokio::time::pause();
        async fn test(mut conn: impl ConnectionLike) {
            // Force the Redis command to take enough time that we have to park the task.  If
            // any timeouts have been created, Tokio will then auto-advance the paused clock to
            // the timeout's expiry time, resulting in a "timed out" error.
            redis::cmd("EVAL")
                .arg(
                    r#"
                          local function now()
                             local t = redis.call("TIME")
                             return t[1] + 0.000001 * t[2]
                          end
                          local t = now() + 0.5
                          while now() < t do end
                        "#,
                )
                .arg(0)
                .exec_async(&mut conn)
                .await
                .unwrap();
        }
        let ctx = TestContext::new();

        let conn = ctx
            .client
            .get_multiplexed_async_connection_with_config(
                &AsyncConnectionConfig::new()
                    .set_connection_timeout(None)
                    .set_response_timeout(None),
            )
            .await
            .unwrap();
        test(conn).await;

        #[cfg(feature = "connection-manager")]
        {
            use redis::aio::ConnectionManagerConfig;

            let conn = ctx
                .client
                .get_connection_manager_with_config(
                    ConnectionManagerConfig::new()
                        .set_connection_timeout(None)
                        .set_response_timeout(None),
                )
                .await
                .unwrap();
            test(conn).await
        };
    }

    #[async_test]
    async fn can_authenticate_with_username_and_password() {
        let ctx = TestContext::new();
        let mut con = ctx.async_connection().await.unwrap();

        let username = "foo";
        let password = "bar";

        // adds a "foo" user with "GET permissions"
        let mut set_user_cmd = redis::Cmd::new();
        set_user_cmd
            .arg("ACL")
            .arg("SETUSER")
            .arg(username)
            .arg("on")
            .arg("+acl")
            .arg(format!(">{password}"));
        assert_eq!(con.req_packed_command(&set_user_cmd).await, Ok(Value::Okay));

        let redis = redis_settings()
            .set_username(username)
            .set_password(password);
        let connection_info = ctx.server.connection_info().set_redis_settings(redis);
        let mut conn = redis::Client::open(connection_info)
            .unwrap()
            .get_multiplexed_async_connection()
            .await
            .unwrap();

        let result: String = cmd("ACL")
            .arg("whoami")
            .query_async(&mut conn)
            .await
            .unwrap();
        assert_eq!(result, username);
    }

    #[async_test]
    async fn nice_hash_api(mut connection: impl AsyncCommands) {
        assert_eq!(
            connection
                .hset_multiple("my_hash", &[("f1", 1), ("f2", 2), ("f3", 4), ("f4", 8)])
                .await,
            Ok(())
        );

        let hm: HashMap<String, isize> = connection.hgetall("my_hash").await.unwrap();
        assert_eq!(hm.len(), 4);
        assert_eq!(hm.get("f1"), Some(&1));
        assert_eq!(hm.get("f2"), Some(&2));
        assert_eq!(hm.get("f3"), Some(&4));
        assert_eq!(hm.get("f4"), Some(&8));
    }

    #[async_test]
    async fn nice_hash_api_in_pipe(mut connection: impl AsyncCommands) {
        assert_eq!(
            connection
                .hset_multiple("my_hash", &[("f1", 1), ("f2", 2), ("f3", 4), ("f4", 8)])
                .await,
            Ok(())
        );

        let mut pipe = redis::pipe();
        pipe.cmd("HGETALL").arg("my_hash");
        let mut vec: Vec<HashMap<String, isize>> = pipe.query_async(&mut connection).await.unwrap();
        assert_eq!(vec.len(), 1);
        let hash = vec.pop().unwrap();
        assert_eq!(hash.len(), 4);
        assert_eq!(hash.get("f1"), Some(&1));
        assert_eq!(hash.get("f2"), Some(&2));
        assert_eq!(hash.get("f3"), Some(&4));
        assert_eq!(hash.get("f4"), Some(&8));
    }

    #[async_test]
    async fn dont_panic_on_closed_multiplexed_connection() {
        let ctx = TestContext::new();
        let client = ctx.client.clone();
        let connect = client.get_multiplexed_async_connection();
        drop(ctx);

        connect
            .and_then(|con| async move {
                let cmd = move || {
                    let mut con = con.clone();
                    async move {
                        redis::cmd("SET")
                            .arg("key1")
                            .arg(b"foo")
                            .query_async(&mut con)
                            .await
                    }
                };
                let result: RedisResult<()> = cmd().await;
                assert_eq!(result.as_ref().unwrap_err().kind(), redis::ErrorKind::Io);
                cmd().await
            })
            .map(|result| {
                assert_eq!(result.as_ref().unwrap_err().kind(), redis::ErrorKind::Io);
            })
            .await;
    }

    #[async_test]
    async fn pipeline_transaction(mut con: impl ConnectionLike) {
        let mut pipe = redis::pipe();
        pipe.atomic()
            .cmd("SET")
            .arg("key_1")
            .arg(42)
            .ignore()
            .cmd("SET")
            .arg("key_2")
            .arg(43)
            .ignore()
            .cmd("MGET")
            .arg(&["key_1", "key_2"]);
        pipe.query_async(&mut con)
            .map_ok(|((k1, k2),): ((i32, i32),)| {
                assert_eq!(k1, 42);
                assert_eq!(k2, 43);
            })
            .await
            .unwrap();
    }

    #[async_test]
    async fn client_tracking_doesnt_block_execution(mut con: impl AsyncCommands) {
        //It checks if the library distinguish a push-type message from the others and continues its normal operation.

        let mut pipe = redis::pipe();
        pipe.cmd("CLIENT")
            .arg("TRACKING")
            .arg("ON")
            .ignore()
            .cmd("GET")
            .arg("key_1")
            .ignore()
            .cmd("SET")
            .arg("key_1")
            .arg(42)
            .ignore();
        let _: RedisResult<()> = pipe.query_async(&mut con).await;
        let num: i32 = con.get("key_1").await.unwrap();
        assert_eq!(num, 42);
    }

    #[async_test]
    async fn pipeline_transaction_with_errors(mut con: impl AsyncCommands) {
        con.set::<_, _, ()>("x", 42).await.unwrap();

        // Make Redis a replica of a nonexistent master, thereby making it read-only.
        redis::cmd("slaveof")
            .arg("1.1.1.1")
            .arg("1")
            .exec_async(&mut con)
            .await
            .unwrap();

        // Ensure that a write command fails with a READONLY error
        let err = redis::pipe()
            .atomic()
            .ping()
            .set("x", 142)
            .ignore()
            .get("x")
            .set("x", 142)
            .query_async::<()>(&mut con)
            .await
            .unwrap_err();

        assert_eq!(err.kind(), ServerErrorKind::ExecAbort.into());
        let errors = err.into_server_errors().unwrap();
        assert_eq!(errors.len(), 2);
        assert_eq!(errors[0].0, 1);
        assert_eq!(errors[0].1.kind(), ServerErrorKind::ReadOnly.into());
        assert_eq!(errors[1].0, 3);
        assert_eq!(errors[1].1.kind(), ServerErrorKind::ReadOnly.into());

        let x: i32 = con.get("x").await.unwrap();
        assert_eq!(x, 42);
    }

    #[async_test]
    #[cfg(feature = "json")]
    async fn module_json_and_pipeline_transaction_with_ignore_errors() {
        let ctx = TestContext::with_modules(&[Module::Json]);
        let mut con = ctx.async_connection().await.unwrap();
        con.set::<_, _, ()>("x", 42).await.unwrap();
        con.json_set::<_, _, _, ()>("y", "$", &serde_json::json!({"path": "value"}))
            .await
            .unwrap();

        let mut pipeline = redis::pipe();
        pipeline
            .atomic()
            .ping()
            .set("x", 142)
            .ignore()
            .json_get("x", ".path")
            .unwrap()
            .ignore()
            .json_get("x", ".path")
            .unwrap()
            .json_get("y", ".path")
            .unwrap()
            .json_get("y", ".other")
            .unwrap()
            .get("x");

        type IgnoreErrorsResult = (
            RedisResult<Value>,
            RedisResult<Value>,
            RedisResult<Value>,
            RedisResult<Value>,
            RedisResult<Value>,
        );

        let result: IgnoreErrorsResult = pipeline
            .ignore_errors()
            .query_async(&mut con)
            .await
            .unwrap();

        assert_eq!(result.0.unwrap(), redis_value!(simple:"PONG"));
        assert_eq!(result.2.unwrap(), redis_value!("\"value\""));
        assert_eq!(result.4.unwrap(), redis_value!("142"));

        assert_eq!(result.1.unwrap_err().code(), Some("Existing"));
        assert_eq!(
            result.3.unwrap_err().kind(),
            ServerErrorKind::ResponseError.into()
        );
    }

    #[async_test]
    async fn pipeline_with_ignore_errors(mut con: impl AsyncCommands) {
        con.set::<_, _, ()>("x", 42).await.unwrap();

        let mut pipeline = redis::pipe();
        pipeline
            .ping()
            .set("x", 142)
            .ignore()
            .cmd("JSON.GET")
            .arg("x")
            .arg(".path")
            .get("x");

        let result: Vec<RedisResult<Value>> = pipeline
            .ignore_errors()
            .query_async(&mut con)
            .await
            .unwrap();

        assert_eq!(result[0].clone().unwrap(), redis_value!(simple:"PONG"));
        assert_eq!(result[2].clone().unwrap(), redis_value!("142"));

        assert_eq!(
            result[1].clone().unwrap_err().kind(),
            ServerErrorKind::ResponseError.into()
        );
    }

    #[async_test]
    async fn pipeline_returns_server_errors(mut con: impl AsyncCommands) {
        let mut pipe = redis::pipe();
        pipe.set("x", "x-value")
            .ignore()
            .hset("x", "field", "field_value")
            .ignore()
            .get("x");

        let res = pipe.exec_async(&mut con).await;
        let error_message = res.unwrap_err().to_string();
        assert_eq!(
            &error_message,
            "Pipeline failure: [(Index 1, error: \"WRONGTYPE\": Operation against a key holding the wrong kind of value)]"
        );
    }

    fn test_cmd(con: impl AsyncCommands + Clone, i: i32) -> impl Future<Output = ()> + Send {
        let mut con = con.clone();
        async move {
            let key = format!("key{i}");
            let key_2 = key.clone();
            let key2 = format!("key{i}_2");
            let key2_2 = key2.clone();

            let foo_val = format!("foo{i}");

            redis::cmd("SET")
                .arg(&key[..])
                .arg(foo_val.as_bytes())
                .exec_async(&mut con)
                .await
                .unwrap();
            redis::cmd("SET")
                .arg(&[&key2, "bar"])
                .exec_async(&mut con)
                .await
                .unwrap();
            redis::cmd("MGET")
                .arg(&[&key_2, &key2_2])
                .query_async(&mut con)
                .map(|result| {
                    assert_eq!(Ok((foo_val, b"bar".to_vec())), result);
                })
                .await;
        }
    }

    #[async_test]
    async fn pipe_over_multiplexed_connection(mut con: impl ConnectionLike) {
        let mut pipe = pipe();
        pipe.zrange("zset", 0, 0);
        pipe.zrange("zset", 0, 0);
        let frames = con.req_packed_commands(&pipe, 0, 2).await.unwrap();
        assert_eq!(frames.len(), 2);
        assert_matches!(frames[0], redis::Value::Array(_));
        assert_matches!(frames[1], redis::Value::Array(_));
    }

    #[async_test]
    async fn running_multiple_commands(con: impl AsyncCommands + Clone) {
        let cmds = (0..100).map(move |i| test_cmd(con.clone(), i));
        future::join_all(cmds).await;
    }

    #[async_test]
    async fn transaction_multiplexed_connection(con: impl ConnectionLike + Clone) {
        let cmds = (0..100).map(move |i| {
            let mut con = con.clone();
            async move {
                let foo_val = i;
                let bar_val = format!("bar{i}");

                let mut pipe = redis::pipe();
                pipe.atomic()
                    .cmd("SET")
                    .arg("key")
                    .arg(foo_val)
                    .ignore()
                    .cmd("SET")
                    .arg(&["key2", &bar_val[..]])
                    .ignore()
                    .cmd("MGET")
                    .arg(&["key", "key2"]);

                pipe.query_async(&mut con)
                    .map(move |result| {
                        assert_eq!(Ok(((foo_val, bar_val.into_bytes()),)), result);
                        result
                    })
                    .await
            }
        });
        future::try_join_all(cmds)
            .map_ok(|results| {
                assert_eq!(results.len(), 100);
            })
            .map_err(|err| panic!("{err}"))
            .await
            .unwrap();
    }

    #[async_test]
    async fn async_scanning(mut con: impl ConnectionLike + Send) {
        let mut unseen = std::collections::HashSet::new();

        for x in 0..1000 {
            redis::cmd("SADD")
                .arg("foo")
                .arg(x)
                .exec_async(&mut con)
                .await
                .unwrap();
            unseen.insert(x);
        }

        let mut iter = redis::cmd("SSCAN")
            .arg("foo")
            .cursor_arg(0)
            .clone()
            .iter_async(&mut con)
            .await
            .unwrap();

        while let Some(x) = iter.next_item().await {
            let x = x.unwrap();

            // if this assertion fails, too many items were returned by the iterator.
            assert!(unseen.remove(&x));
        }

        assert!(unseen.is_empty());
    }

    #[async_test]
    async fn async_scanning_iterative(mut con: impl ConnectionLike + Send) {
        let mut unseen = std::collections::HashSet::new();

        for x in 0..1000 {
            let key_name = format!("key.{x}");
            redis::cmd("SET")
                .arg(key_name.clone())
                .arg("foo")
                .exec_async(&mut con)
                .await
                .unwrap();
            unseen.insert(key_name.clone());
        }

        let mut iter = redis::cmd("SCAN")
            .cursor_arg(0)
            .arg("MATCH")
            .arg("key*")
            .arg("COUNT")
            .arg(1)
            .clone()
            .iter_async::<String>(&mut con)
            .await
            .unwrap();

        while let Some(item) = iter.next_item().await {
            let item = item.unwrap();

            // if this assertion fails, too many items were returned by the iterator.
            assert!(unseen.remove(&item));
        }

        assert!(unseen.is_empty());
    }

    #[async_test]
    async fn async_scanning_stream(mut con: impl ConnectionLike + Sync + Send) {
        let mut unseen = std::collections::HashSet::new();

        for x in 0..1000 {
            let key_name = format!("key.{x}");
            redis::cmd("SET")
                .arg(key_name.clone())
                .arg("foo")
                .exec_async(&mut con)
                .await
                .unwrap();
            unseen.insert(key_name.clone());
        }

        let mut iter = redis::cmd("SCAN")
            .cursor_arg(0)
            .arg("MATCH")
            .arg("key*")
            .arg("COUNT")
            .arg(1)
            .clone()
            .iter_async::<String>(&mut con)
            .await
            .unwrap();

        while let Some(item) = iter.next_item().await {
            let item = item.unwrap();

            // if this assertion fails, too many items were returned by the iterator.
            assert!(unseen.remove(&item));
        }

        assert!(unseen.is_empty());
    }

    #[async_test]
    async fn response_timeout_multiplexed_connection() {
        let ctx = TestContext::new();

        let mut connection = ctx.async_connection().await.unwrap();
        connection.set_response_timeout(Duration::from_millis(1));
        let mut cmd = redis::Cmd::new();
        cmd.arg("BLPOP").arg("foo").arg(0); // 0 timeout blocks indefinitely
        let result = connection.req_packed_command(&cmd).await;
        assert_matches!(result, Err(_));
        assert!(result.unwrap_err().is_timeout());
    }

    #[async_test]
    #[cfg(feature = "script")]
    async fn script(mut con: impl ConnectionLike) {
        // Note this test runs both scripts twice to test when they have already been loaded
        // into Redis and when they need to be loaded in
        let script1 = redis::Script::new("return redis.call('SET', KEYS[1], ARGV[1])");
        let script2 = redis::Script::new("return redis.call('GET', KEYS[1])");
        let script3 = redis::Script::new("return redis.call('KEYS', '*')");
        script1
            .key("key1")
            .arg("foo")
            .invoke_async::<()>(&mut con)
            .await
            .unwrap();
        let val: String = script2.key("key1").invoke_async(&mut con).await.unwrap();
        assert_eq!(val, "foo");
        let keys: Vec<String> = script3.invoke_async(&mut con).await.unwrap();
        assert_eq!(keys, ["key1"]);
        script1
            .key("key1")
            .arg("bar")
            .invoke_async::<()>(&mut con)
            .await
            .unwrap();
        let val: String = script2.key("key1").invoke_async(&mut con).await.unwrap();
        assert_eq!(val, "bar");
        let keys: Vec<String> = script3.invoke_async(&mut con).await.unwrap();
        assert_eq!(keys, ["key1"]);
    }

    #[async_test]
    #[cfg(feature = "script")]
    async fn script_load(mut con: impl ConnectionLike) {
        let script = redis::Script::new("return 'Hello World'");

        let hash = script.prepare_invoke().load_async(&mut con).await.unwrap();
        assert_eq!(hash, script.get_hash().to_string());
    }

    #[async_test]
    #[cfg(feature = "script")]
    async fn script_returning_complex_type(mut con: impl ConnectionLike) {
        redis::Script::new("return {1, ARGV[1], true}")
            .arg("hello")
            .invoke_async(&mut con)
            .map_ok(|(i, s, b): (i32, String, bool)| {
                assert_eq!(i, 1);
                assert_eq!(s, "hello");
                assert!(b);
            })
            .await
            .unwrap()
    }

    // Allowing `nth(0)` for similarity with the following `nth(1)`.
    // Allowing `let ()` as `query_async` requires the type it converts the result to.
    #[allow(clippy::let_unit_value, clippy::iter_nth_zero)]
    #[async_test]
    async fn io_error_on_kill_issue_320() {
        let ctx = TestContext::new();

        let mut conn_to_kill = ctx.async_connection().await.unwrap();
        kill_client_async(&mut conn_to_kill, &ctx.client)
            .await
            .unwrap();
        let mut killed_client = conn_to_kill;

        let err = loop {
            let _ = match killed_client.get::<_, Option<String>>("a").await {
                // We are racing against the server being shutdown so try until we a get an io error
                Ok(_) => sleep(Duration::from_millis(50).into()).await,
                Err(err) => break err,
            };
        };
        assert_eq!(err.kind(), ErrorKind::Io);
    }

    #[async_test]
    async fn invalid_password_issue_343() {
        let ctx = TestContext::new();

        let redis = RedisConnectionInfo::default().set_password("asdcasc");
        let connection_info = ctx
            .server
            .client_addr()
            .clone()
            .into_connection_info()
            .unwrap()
            .set_redis_settings(redis);

        let client = redis::Client::open(connection_info).unwrap();

        let err = client
            .get_multiplexed_async_connection()
            .await
            .err()
            .unwrap();
        assert_eq!(
            err.kind(),
            ErrorKind::AuthenticationFailed,
            "Unexpected error: {err}",
        );
    }

    #[async_test]
    async fn scan_with_options_works(mut con: impl AsyncCommands) {
        for i in 0..20usize {
            let _: () = con.append(format!("test/{i}"), i).await.unwrap();
            let _: () = con.append(format!("other/{i}"), i).await.unwrap();
        }
        // scan with pattern
        let opts = ScanOptions::default().with_count(20).with_pattern("test/*");
        let values = con.scan_options::<String>(opts).await.unwrap();
        let values: Vec<_> = values
            .collect()
            .timeout(futures_time::time::Duration::from_millis(100))
            .await
            .unwrap();
        assert_eq!(values.len(), 20);

        // scan without pattern
        let opts = ScanOptions::default();
        let values = con.scan_options::<String>(opts).await.unwrap();
        let values: Vec<_> = values
            .collect()
            .timeout(futures_time::time::Duration::from_millis(100))
            .await
            .unwrap();
        assert_eq!(values.len(), 40);
    }

    // Test issue of Stream trait blocking if we try to iterate more than 10 items
    // https://github.com/mitsuhiko/redis-rs/issues/537 and https://github.com/mitsuhiko/redis-rs/issues/583
    #[async_test]
    async fn issue_stream_blocks(mut con: impl AsyncCommands) {
        for i in 0..20usize {
            let _: () = con.append(format!("test/{i}"), i).await.unwrap();
        }
        let values = con.scan_match::<&str, String>("test/*").await.unwrap();
        async move {
            let values: Vec<_> = values.collect().await;
            assert_eq!(values.len(), 20);
        }
        .timeout(futures_time::time::Duration::from_millis(100))
        .await
        .unwrap();
    }

    // Test issue of AsyncCommands::scan returning the wrong number of keys
    // https://github.com/redis-rs/redis-rs/issues/759
    #[async_test]
    async fn issue_async_commands_scan_broken(mut con: impl AsyncCommands) {
        let mut keys: Vec<String> = (0..100).map(|k| format!("async-key{k}")).collect();
        keys.sort();
        for key in &keys {
            let _: () = con.set(key, b"foo").await.unwrap();
        }

        let iter: redis::AsyncIter<String> = con.scan().await.unwrap();
        let mut keys_from_redis: Vec<_> = iter.map(std::result::Result::unwrap).collect().await;
        keys_from_redis.sort();
        assert_eq!(keys, keys_from_redis);
        assert_eq!(keys.len(), 100);
    }

    mod pub_sub {
        use std::time::Duration;

        use super::*;

        #[async_test]
        async fn pub_sub_subscription() {
            let ctx = TestContext::new();

            let mut pubsub_conn = ctx.async_pubsub().await.unwrap();
            let _: () = pubsub_conn.subscribe("phonewave").await.unwrap();
            let mut pubsub_stream = pubsub_conn.on_message();
            let mut publish_conn = ctx.async_connection().await.unwrap();
            let _: () = publish_conn.publish("phonewave", "banana").await.unwrap();

            let repeats = 6;
            for _ in 0..repeats {
                let _: () = publish_conn.publish("phonewave", "banana").await.unwrap();
            }

            for _ in 0..repeats {
                let message: String = pubsub_stream.next().await.unwrap().get_payload().unwrap();

                assert_eq!("banana".to_string(), message);
            }
        }

        #[async_test]
        async fn pub_sub_subscription_to_multiple_channels() {
            let ctx = TestContext::new();

            let mut pubsub_conn = ctx.async_pubsub().await.unwrap();
            let _: () = pubsub_conn
                .subscribe(&["phonewave", "foo", "bar"])
                .await
                .unwrap();
            let mut pubsub_stream = pubsub_conn.on_message();
            let mut publish_conn = ctx.async_connection().await.unwrap();
            let _: () = publish_conn.publish("phonewave", "banana").await.unwrap();

            let msg_payload: String = pubsub_stream.next().await.unwrap().get_payload().unwrap();
            assert_eq!("banana".to_string(), msg_payload);

            let _: () = publish_conn.publish("foo", "foobar").await.unwrap();
            let msg_payload: String = pubsub_stream.next().await.unwrap().get_payload().unwrap();
            assert_eq!("foobar".to_string(), msg_payload);
        }

        // Test issue of AsyncCommands::scan not returning keys because wrong assumptions about the key type were made
        // https://github.com/redis-rs/redis-rs/issues/1309
        #[async_test]
        async fn issue_async_commands_scan_finishing_prematurely(mut con: impl AsyncCommands) {
            const PREFIX: &str = "async-key";
            const NUM_KEYS: usize = 100;

            /// Container that is constructed from a string that has [`PREFIX`] as prefix
            struct Container(String);

            impl redis::FromRedisValue for Container {
                fn from_redis_value(v: Value) -> Result<Self, ParsingError> {
                    let text = String::from_redis_value(v.clone()).unwrap();

                    // If container does not start with [`PREFIX`], return error
                    if !text.starts_with(PREFIX) {
                        // hack to create a parsing error
                        return Err(u64::from_redis_value(v).unwrap_err());
                    }

                    Ok(Container(text))
                }
            }

            // Insert 100 keys but one with an incorrect prefix
            let keys: Vec<String> = (0..NUM_KEYS)
                .map(|i| format!("{}{i}", if i == 50 { "NOPE" } else { PREFIX }))
                .collect();

            for key in &keys {
                let _: () = con.set(key, "bar".as_bytes()).await.unwrap();
            }

            // Query all keys
            let mut iter: redis::AsyncIter<Container> = con.scan().await.unwrap();

            let mut error = None;
            let mut count = 0;

            while let Some(key) = iter.next_item().await {
                match key {
                    Ok(key) => {
                        assert!(key.0.starts_with(PREFIX));
                        count += 1;
                    }
                    Err(_) if error.is_some() => {
                        panic!("Encountered multiple errors");
                    }
                    Err(e) => error = Some(e.kind()),
                };
            }

            // Assert that the number of visited keys is all keys minus
            // the one invalid key
            assert_eq!(count, NUM_KEYS - 1);

            // Assert that the encountered error is a type error
            assert_eq!(error, Some(ErrorKind::Parse));
        }

        #[async_test]
        async fn pub_sub_unsubscription() {
            const SUBSCRIPTION_KEY: &str = "phonewave-pub-sub-unsubscription";

            let ctx = TestContext::new();

            let mut pubsub_conn = ctx.async_pubsub().await.unwrap();
            pubsub_conn.subscribe(SUBSCRIPTION_KEY).await.unwrap();
            pubsub_conn.unsubscribe(SUBSCRIPTION_KEY).await.unwrap();

            let mut conn = ctx.async_connection().await.unwrap();
            let subscriptions_counts: HashMap<String, u32> = redis::cmd("PUBSUB")
                .arg("NUMSUB")
                .arg(SUBSCRIPTION_KEY)
                .query_async(&mut conn)
                .await
                .unwrap();
            let subscription_count = *subscriptions_counts.get(SUBSCRIPTION_KEY).unwrap();
            assert_eq!(subscription_count, 0);
        }

        #[async_test]
        async fn can_receive_messages_while_sending_requests_from_split_pub_sub() {
            let ctx = TestContext::new();

            let (mut sink, mut stream) = ctx.async_pubsub().await.unwrap().split();
            let mut publish_conn = ctx.async_connection().await.unwrap();

            let _: () = sink.subscribe("phonewave").await.unwrap();
            let repeats = 6;
            for _ in 0..repeats {
                let _: () = publish_conn.publish("phonewave", "banana").await.unwrap();
            }

            for _ in 0..repeats {
                let message: String = stream.next().await.unwrap().get_payload().unwrap();

                assert_eq!("banana".to_string(), message);
            }
        }

        #[async_test]
        async fn can_send_ping_on_split_pubsub() {
            let ctx = TestContext::new();

            let (mut sink, mut stream) = ctx.async_pubsub().await.unwrap().split();
            let mut publish_conn = ctx.async_connection().await.unwrap();

            let _: () = sink.subscribe("phonewave").await.unwrap();

            // we publish before the ping, to verify that published messages don't distort the ping's resuilt.
            let repeats = 6;
            for _ in 0..repeats {
                let _: () = publish_conn.publish("phonewave", "banana").await.unwrap();
            }

            if ctx.protocol.supports_resp3() {
                let message: String = sink.ping().await.unwrap();
                assert_eq!(message, "PONG");
            } else {
                let message: Vec<String> = sink.ping().await.unwrap();
                assert_eq!(message, vec!["pong", ""]);
            }

            if ctx.protocol.supports_resp3() {
                let message: String = sink.ping_message("foobar").await.unwrap();
                assert_eq!(message, "foobar");
            } else {
                let message: Vec<String> = sink.ping_message("foobar").await.unwrap();
                assert_eq!(message, vec!["pong", "foobar"]);
            }

            for _ in 0..repeats {
                let message: String = stream.next().await.unwrap().get_payload().unwrap();

                assert_eq!("banana".to_string(), message);
            }

            // after the stream is closed, pinging should fail.
            drop(stream);
            let err = sink.ping_message::<()>("foobar").await.unwrap_err();
            assert!(err.is_unrecoverable_error());
        }

        #[async_test]
        async fn can_receive_messages_from_split_pub_sub_after_sink_was_dropped() {
            let ctx = TestContext::new();

            let (mut sink, mut stream) = ctx.async_pubsub().await.unwrap().split();
            let mut publish_conn = ctx.async_connection().await.unwrap();

            let _: () = sink.subscribe("phonewave").await.unwrap();
            drop(sink);
            let repeats = 6;
            for _ in 0..repeats {
                let _: () = publish_conn.publish("phonewave", "banana").await.unwrap();
            }

            for _ in 0..repeats {
                let message: String = stream.next().await.unwrap().get_payload().unwrap();

                assert_eq!("banana".to_string(), message);
            }
        }

        #[async_test]
        async fn can_receive_messages_from_split_pub_sub_after_into_on_message() {
            let ctx = TestContext::new();

            let mut pubsub = ctx.async_pubsub().await.unwrap();
            let mut publish_conn = ctx.async_connection().await.unwrap();

            let _: () = pubsub.subscribe("phonewave").await.unwrap();
            let mut stream = pubsub.into_on_message();
            // wait a bit
            sleep(Duration::from_secs(2).into()).await;
            let repeats = 6;
            for _ in 0..repeats {
                let _: () = publish_conn.publish("phonewave", "banana").await.unwrap();
            }

            for _ in 0..repeats {
                let message: String = stream.next().await.unwrap().get_payload().unwrap();

                assert_eq!("banana".to_string(), message);
            }
        }

        #[async_test]
        async fn cannot_subscribe_on_split_pub_sub_after_stream_was_dropped() {
            let ctx = TestContext::new();

            let (mut sink, stream) = ctx.async_pubsub().await.unwrap().split();
            drop(stream);

            assert_matches!(sink.subscribe("phonewave").await, Err(_));
        }

        #[async_test]
        async fn automatic_unsubscription() {
            const SUBSCRIPTION_KEY: &str = "phonewave-automatic-unsubscription";

            let ctx = TestContext::new();

            let mut pubsub_conn = ctx.async_pubsub().await.unwrap();
            pubsub_conn.subscribe(SUBSCRIPTION_KEY).await.unwrap();
            drop(pubsub_conn);

            let mut conn = ctx.async_connection().await.unwrap();
            let mut subscription_count = 1;
            // Allow for the unsubscription to occur within 5 seconds
            for _ in 0..100 {
                let subscriptions_counts: HashMap<String, u32> = redis::cmd("PUBSUB")
                    .arg("NUMSUB")
                    .arg(SUBSCRIPTION_KEY)
                    .query_async(&mut conn)
                    .await
                    .unwrap();
                subscription_count = *subscriptions_counts.get(SUBSCRIPTION_KEY).unwrap();
                if subscription_count == 0 {
                    break;
                }

                sleep(Duration::from_millis(50).into()).await;
            }
            assert_eq!(subscription_count, 0);
        }

        #[async_test]
        async fn automatic_unsubscription_on_split() {
            const SUBSCRIPTION_KEY: &str = "phonewave-automatic-unsubscription-on-split";

            let ctx = TestContext::new();

            let (mut sink, stream) = ctx.async_pubsub().await.unwrap().split();
            sink.subscribe(SUBSCRIPTION_KEY).await.unwrap();
            let mut conn = ctx.async_connection().await.unwrap();
            sleep(Duration::from_millis(100).into()).await;

            let subscriptions_counts: HashMap<String, u32> = redis::cmd("PUBSUB")
                .arg("NUMSUB")
                .arg(SUBSCRIPTION_KEY)
                .query_async(&mut conn)
                .await
                .unwrap();
            let mut subscription_count = *subscriptions_counts.get(SUBSCRIPTION_KEY).unwrap();
            assert_eq!(subscription_count, 1);

            drop(stream);

            // Allow for the unsubscription to occur within 5 seconds
            for _ in 0..100 {
                let subscriptions_counts: HashMap<String, u32> = redis::cmd("PUBSUB")
                    .arg("NUMSUB")
                    .arg(SUBSCRIPTION_KEY)
                    .query_async(&mut conn)
                    .await
                    .unwrap();
                subscription_count = *subscriptions_counts.get(SUBSCRIPTION_KEY).unwrap();
                if subscription_count == 0 {
                    break;
                }

                sleep(Duration::from_millis(50).into()).await;
            }
            assert_eq!(subscription_count, 0);

            // verify that the sink is unusable after the stream is dropped.
            let err = sink.subscribe(SUBSCRIPTION_KEY).await.unwrap_err();
            assert!(err.is_unrecoverable_error(), "{err}");
        }

        #[async_test]
        async fn pipe_errors_do_not_affect_subsequent_commands(mut conn: impl AsyncCommands) {
            conn.lpush::<&str, &str, ()>("key", "value").await.unwrap();

            redis::pipe()
                        .get("key") // WRONGTYPE
                        .llen("key")
                        .exec_async(&mut conn)
                        .await.unwrap_err();

            let list: Vec<String> = conn.lrange("key", 0, -1).await.unwrap();

            assert_eq!(list, vec!["value".to_owned()]);
        }

        #[async_test]
        async fn multiplexed_pub_sub_subscribe_on_multiple_channels() {
            let ctx = TestContext::new();
            if !ctx.protocol.supports_resp3() {
                return;
            }

            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
            let config = redis::AsyncConnectionConfig::new().set_push_sender(tx);
            let mut conn = ctx
                .client
                .get_multiplexed_async_connection_with_config(&config)
                .await
                .unwrap();
            let _: () = conn.subscribe(&["phonewave", "foo", "bar"]).await.unwrap();
            let mut publish_conn = ctx.async_connection().await.unwrap();

            let msg_payload = rx.recv().await.unwrap();
            assert_eq!(msg_payload.kind, PushKind::Subscribe);

            let _: () = publish_conn.publish("foo", "foobar").await.unwrap();

            let msg_payload = rx.recv().await.unwrap();
            assert_eq!(msg_payload.kind, PushKind::Subscribe);
            let msg_payload = rx.recv().await.unwrap();
            assert_eq!(msg_payload.kind, PushKind::Subscribe);
            let msg_payload = rx.recv().await.unwrap();
            assert_eq!(msg_payload.kind, PushKind::Message);
        }

        #[async_test]
        async fn non_transaction_errors_do_not_affect_other_results_in_pipeline(
            mut conn: impl AsyncCommands,
        ) {
            conn.lpush::<&str, &str, ()>("key", "value").await.unwrap();

            let mut results: Vec<Value> = conn
                .req_packed_commands(
                    redis::pipe()
                        .get("key") // WRONGTYPE
                                .llen("key"),
                    0,
                    2,
                )
                .await
                .unwrap();

            assert_eq!(results.pop().unwrap(), redis_value!(1));
            assert_matches!(results.pop().unwrap().extract_error(), Err(_));
        }

        #[async_test]
        async fn pub_sub_multiple() {
            let ctx = TestContext::new();
            let redis = RedisConnectionInfo::default().set_protocol(ProtocolVersion::RESP3);
            let connection_info = ctx.server.connection_info().set_redis_settings(redis);
            let client = redis::Client::open(connection_info).unwrap();

            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
            let config = redis::AsyncConnectionConfig::new().set_push_sender(tx);
            let mut conn = client
                .get_multiplexed_async_connection_with_config(&config)
                .await
                .unwrap();
            let pub_count = 10;
            let channel_name = "phonewave".to_string();
            conn.subscribe(channel_name.clone()).await.unwrap();
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Subscribe);

            let mut publish_conn = ctx.async_connection().await.unwrap();
            for i in 0..pub_count {
                let _: () = publish_conn
                    .publish(channel_name.clone(), format!("banana {i}"))
                    .await
                    .unwrap();
            }
            for i in 0..pub_count {
                let push = rx.recv().await.unwrap();
                assert_eq!(push.kind, PushKind::Message);
                assert_eq!(
                    push.data,
                    vec![
                        redis_value!("phonewave"),
                        redis_value!(format!("banana {i}")),
                    ]
                );
            }
            assert_matches!(rx.try_recv(), Err(_));

            //Lets test if unsubscribing from individual channel subscription works
            let _: () = publish_conn
                .publish(channel_name.clone(), "banana!")
                .await
                .unwrap();
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Message);
            assert_eq!(
                push.data,
                vec![redis_value!("phonewave"), redis_value!("banana!")]
            );

            //Giving none for channel id should unsubscribe all subscriptions from that channel and send unsubcribe command to server.
            conn.unsubscribe(channel_name.clone()).await.unwrap();
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Unsubscribe);
            let _: () = publish_conn
                .publish(channel_name.clone(), "banana!")
                .await
                .unwrap();
            //Let's wait for 100ms to make sure there is nothing in channel.
            sleep(Duration::from_millis(100).into()).await;
            assert_matches!(rx.try_recv(), Err(_));
        }

        #[async_test]
        async fn pub_sub_requires_resp3() {
            if use_protocol().supports_resp3() {
                return;
            }
            let ctx = TestContext::new();
            let mut conn = ctx.async_connection().await.unwrap();

            let res = conn.subscribe("foo").await;

            assert_eq!(
                res.unwrap_err().kind(),
                redis::ErrorKind::InvalidClientConfig
            );
        }

        #[async_test]
        async fn push_sender_send_on_disconnect() {
            let ctx = TestContext::new();
            let redis = RedisConnectionInfo::default().set_protocol(ProtocolVersion::RESP3);
            let connection_info = ctx.server.connection_info().set_redis_settings(redis);
            let client = redis::Client::open(connection_info).unwrap();

            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
            let config = redis::AsyncConnectionConfig::new().set_push_sender(tx);
            let mut conn = client
                .get_multiplexed_async_connection_with_config(&config)
                .await
                .unwrap();

            let _: () = conn.set("A", "1").await.unwrap();
            assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty);
            kill_client_async(&mut conn, &ctx.client).await.unwrap();

            assert_eq!(rx.recv().await.unwrap().kind, PushKind::Disconnection);
        }

        #[cfg(feature = "connection-manager")]
        #[async_test]
        async fn manager_should_resubscribe_to_pubsub_channels_after_disconnect() {
            let ctx = TestContext::new();
            if !ctx.protocol.supports_resp3() {
                return;
            }
            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

            let max_delay_between_attempts = Duration::from_millis(2);
            let config = redis::aio::ConnectionManagerConfig::new()
                .set_push_sender(tx)
                .set_automatic_resubscription()
                .set_max_delay(max_delay_between_attempts);

            let mut pubsub_conn = ctx
                .client
                .get_connection_manager_with_config(config)
                .await
                .unwrap();
            let _: () = pubsub_conn
                .subscribe(&["phonewave", "foo", "bar"])
                .await
                .unwrap();
            let _: () = pubsub_conn.psubscribe(&["zoom*"]).await.unwrap();
            let _: () = pubsub_conn.unsubscribe("foo").await.unwrap();

            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Subscribe);
            assert_eq!(push.data, vec![redis_value!("phonewave"), redis_value!(1)]);
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Subscribe);
            assert_eq!(push.data, vec![redis_value!("foo"), redis_value!(2)]);
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Subscribe);
            assert_eq!(push.data, vec![redis_value!("bar"), redis_value!(3)]);
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::PSubscribe);
            assert_eq!(push.data, vec![redis_value!("zoom*"), redis_value!(4)]);
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Unsubscribe);
            assert_eq!(push.data, vec![redis_value!("foo"), redis_value!(3)]);

            let addr = ctx.server.client_addr().clone();
            drop(ctx);
            // a yield, to let the connection manager to notice the broken connection.
            // this is required to reduce differences in test runs between smol & tokio runtime.
            sleep(Duration::from_millis(1).into()).await;
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Disconnection);
            let ctx = TestContext::new_with_addr(addr);

            let push1 = rx.recv().await.unwrap();
            assert_eq!(push1.kind, PushKind::Subscribe);
            // we don't know the order that the resubscription requests will be sent in, so we check if both were received, in either order.
            let push2 = rx.recv().await.unwrap();
            assert_eq!(push2.kind, PushKind::Subscribe);
            assert!(
                (push1.data == vec![redis_value!("phonewave"), redis_value!(1)]
                    && push2.data == vec![redis_value!("bar"), redis_value!(2)])
                    || (push1.data == vec![redis_value!("bar"), redis_value!(1)]
                        && push2.data == vec![redis_value!("phonewave"), redis_value!(2)])
            );
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::PSubscribe);
            assert_eq!(push.data, vec![redis_value!("zoom*"), redis_value!(3)]);

            let mut publish_conn = ctx.async_connection().await.unwrap();
            let _: () = publish_conn.publish("phonewave", "banana").await.unwrap();

            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Message);
            assert_eq!(
                push.data,
                vec![redis_value!("phonewave"), redis_value!("banana")]
            );

            // this should be skipped, because we unsubscribed from foo
            let _: () = publish_conn.publish("foo", "goo").await.unwrap();
            let _: () = publish_conn.publish("zoomer", "foobar").await.unwrap();
            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::PMessage);
            assert_eq!(
                push.data,
                vec![
                    redis_value!("zoom*"),
                    redis_value!("zoomer"),
                    redis_value!("foobar"),
                ]
            );

            // no more messages should be sent.
            assert_matches!(rx.try_recv(), Err(_));
        }
    }

    #[async_test]
    async fn async_basic_pipe_with_parsing_error(mut conn: impl ConnectionLike) {
        // Tests a specific case involving repeated errors in transactions.

        // create a transaction where 2 errors are returned.
        // we call EVALSHA twice with no loaded script, thus triggering 2 errors.
        redis::pipe()
            .atomic()
            .cmd("EVALSHA")
            .arg("foobar")
            .arg(0)
            .cmd("EVALSHA")
            .arg("foobar")
            .arg(0)
            .query_async::<((), ())>(&mut conn)
            .await
            .expect_err("should return an error");

        assert!(
            // Arbitrary Redis command that should not return an error.
            redis::cmd("SMEMBERS")
                .arg("nonexistent_key")
                .query_async::<Vec<String>>(&mut conn)
                .await
                .is_ok(),
            "Failed transaction should not interfere with future calls."
        );
    }

    #[async_test]
    #[cfg(feature = "connection-manager")]
    async fn connection_manager_reconnect_after_delay() {
        let max_delay_between_attempts = Duration::from_millis(2);
        let mut config = redis::aio::ConnectionManagerConfig::new()
            .set_exponent_base(10000.0)
            .set_max_delay(max_delay_between_attempts);

        let tempdir = tempfile::Builder::new()
            .prefix("redis")
            .tempdir()
            .expect("failed to create tempdir");
        let tls_files = redis_test::utils::build_keys_and_certs_for_tls(&tempdir);

        let ctx = TestContext::with_tls(tls_files.clone(), false);
        let protocol = ctx.protocol;

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        if ctx.protocol.supports_resp3() {
            config = config.set_push_sender(tx);
        }
        let mut manager =
            redis::aio::ConnectionManager::new_with_config(ctx.client.clone(), config)
                .await
                .unwrap();
        let addr = ctx.server.client_addr().clone();
        drop(ctx);
        let result: RedisResult<redis::Value> = manager.set("foo", "bar").await;
        // we expect a connection failure error.
        assert!(result.unwrap_err().is_unrecoverable_error());
        if protocol.supports_resp3() {
            assert_eq!(rx.recv().await.unwrap().kind, PushKind::Disconnection);
        }

        let _server = redis_test::server::RedisServer::new_with_addr_and_modules(addr, &[], false);

        for _ in 0..5 {
            let Ok(result) = manager.set::<_, _, Value>("foo", "bar").await else {
                sleep(Duration::from_millis(3).into()).await;
                continue;
            };
            assert_eq!(result, redis::Value::Okay);
            if protocol.supports_resp3() {
                assert_matches!(rx.try_recv(), Err(_));
            }
            return;
        }
        panic!("failed to reconnect");
    }

    #[cfg(feature = "connection-manager")]
    #[async_test]
    async fn manager_should_reconnect_without_actions_if_resp3_is_set() {
        let ctx = TestContext::new();
        if !ctx.protocol.supports_resp3() {
            return;
        }

        let max_delay_between_attempts = Duration::from_millis(2);
        let config = redis::aio::ConnectionManagerConfig::new()
            .set_exponent_base(10000.0)
            .set_max_delay(max_delay_between_attempts);

        let mut conn = ctx
            .client
            .get_connection_manager_with_config(config)
            .await
            .unwrap();

        let addr = ctx.server.client_addr().clone();
        drop(ctx);
        let _ctx = TestContext::new_with_addr(addr);

        sleep(Duration::from_secs_f32(0.01).into()).await;

        assert_matches!(cmd("PING").exec_async(&mut conn).await, Ok(_));
    }

    #[cfg(feature = "connection-manager")]
    #[async_test]
    async fn manager_should_completely_disconnect_when_drop() {
        let ctx = TestContext::new();
        let redis = RedisConnectionInfo::default().set_protocol(ProtocolVersion::RESP3);
        let connection_info = ctx.server.connection_info().set_redis_settings(redis);
        let client = redis::Client::open(connection_info).unwrap();

        let number_of_connections;

        {
            let mut conn = client
                .get_connection_manager_with_config(redis::aio::ConnectionManagerConfig::new())
                .await
                .unwrap();
            let connections: String = cmd("CLIENT")
                .arg("LIST")
                .query_async(&mut conn)
                .await
                .unwrap();

            number_of_connections = connections.lines().collect::<Vec<_>>().len();
        }
        {
            let mut conn = client
                .get_connection_manager_with_config(redis::aio::ConnectionManagerConfig::new())
                .await
                .unwrap();
            let connections: String = cmd("CLIENT")
                .arg("LIST")
                .query_async(&mut conn)
                .await
                .unwrap();

            assert_eq!(
                number_of_connections,
                connections.lines().collect::<Vec<_>>().len()
            );
        }
    }

    #[cfg(feature = "connection-manager")]
    #[async_test]
    async fn manager_should_reconnect_without_actions_if_push_sender_is_set_even_after_sender_returns_error()
     {
        let ctx = TestContext::new();
        if !ctx.protocol.supports_resp3() {
            return;
        }
        println!("running");
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

        let max_delay_between_attempts = Duration::from_millis(2);
        let config = redis::aio::ConnectionManagerConfig::new()
            .set_exponent_base(10000.0)
            .set_push_sender(tx)
            .set_max_delay(max_delay_between_attempts);

        let mut conn = ctx
            .client
            .get_connection_manager_with_config(config)
            .await
            .unwrap();

        let addr = ctx.server.client_addr().clone();
        // drop once, to trigger reconnect and sending the push message
        drop(ctx);
        let push = rx.recv().await.unwrap();
        assert_eq!(push.kind, PushKind::Disconnection);
        let _ctx = TestContext::new_with_addr(addr.clone());

        assert_matches!(cmd("PING").exec_async(&mut conn).await, Ok(_));
        assert_matches!(rx.try_recv(), Err(_));

        // drop again, to verify that the mechanism works even after the sender returned an error.
        drop(_ctx);
        let push = rx.recv().await.unwrap();
        assert_eq!(push.kind, PushKind::Disconnection);
        let _ctx = TestContext::new_with_addr(addr);

        sleep(Duration::from_secs_f32(0.01).into()).await;
        assert_matches!(cmd("PING").exec_async(&mut conn).await, Ok(_));
        assert_matches!(rx.try_recv(), Err(_));
    }

    #[async_test]
    async fn multiplexed_connection_kills_connection_on_drop_even_when_blocking() {
        let ctx = TestContext::new();

        let mut conn = ctx.async_connection().await.unwrap();
        let mut connection_to_dispose_of = ctx.async_connection().await.unwrap();
        connection_to_dispose_of.set_response_timeout(Duration::from_millis(1));

        async fn count_ids(conn: &mut impl redis::aio::ConnectionLike) -> RedisResult<usize> {
            let initial_connections: String =
                cmd("CLIENT").arg("LIST").query_async(conn).await.unwrap();

            Ok(initial_connections
                .as_bytes()
                .windows(3)
                .filter(|substr| substr == b"id=")
                .count())
        }

        assert_eq!(count_ids(&mut conn).await.unwrap(), 2);

        let command_that_blocks = cmd("BLPOP")
            .arg("foo")
            .arg(0)
            .exec_async(&mut connection_to_dispose_of)
            .await;

        let err = command_that_blocks.unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Io);

        drop(connection_to_dispose_of);

        sleep(Duration::from_millis(10).into()).await;

        assert_eq!(count_ids(&mut conn).await.unwrap(), 1);
    }

    #[async_test]
    async fn monitor() {
        let ctx = TestContext::new();

        let mut conn = ctx.async_connection().await.unwrap();
        let monitor_conn = ctx.client.get_async_monitor().await.unwrap();
        let mut stream = monitor_conn.into_on_message();

        let _: () = conn.set("foo", "bar").await.unwrap();

        let msg: String = stream.next().await.unwrap();
        assert!(msg.ends_with("\"SET\" \"foo\" \"bar\""));

        drop(ctx);

        assert!(stream.next().await.is_none());
    }

    #[cfg(feature = "tls-rustls")]
    mod mtls_test {
        use super::*;

        #[rstest::rstest]
        #[cfg_attr(feature = "tokio-comp", case::tokio(RuntimeType::Tokio))]
        #[cfg_attr(feature = "smol-comp", case::smol(RuntimeType::Smol))]
        fn test_should_connect_mtls(#[case] runtime: RuntimeType) {
            let ctx = TestContext::new_with_mtls();

            let client =
                build_single_client(ctx.server.connection_info(), &ctx.server.tls_paths, true)
                    .unwrap();
            let connect = client.get_multiplexed_async_connection();
            block_on_all(
                async move {
                    let mut con = connect.await.unwrap();

                    redis::cmd("SET")
                        .arg("key1")
                        .arg(b"foo")
                        .exec_async(&mut con)
                        .await
                        .unwrap();
                    let result = redis::cmd("GET").arg(&["key1"]).query_async(&mut con).await;
                    assert_eq!(result, Ok("foo".to_string()));
                },
                runtime,
            );
        }

        #[rstest::rstest]
        #[cfg_attr(feature = "tokio-comp", case::tokio(RuntimeType::Tokio))]
        #[cfg_attr(feature = "smol-comp", case::smol(RuntimeType::Smol))]
        fn test_should_not_connect_if_tls_active(#[case] runtime: RuntimeType) {
            let ctx = TestContext::new_with_mtls();

            let client =
                build_single_client(ctx.server.connection_info(), &ctx.server.tls_paths, false)
                    .unwrap();
            let connect = client.get_multiplexed_async_connection();
            let result = block_on_all(
                async move {
                    let mut con = connect.await?;
                    redis::cmd("SET")
                        .arg("key1")
                        .arg(b"foo")
                        .exec_async(&mut con)
                        .await
                        .unwrap();
                    let result = redis::cmd("GET").arg(&["key1"]).query_async(&mut con).await;
                    assert_eq!(result, Ok("foo".to_string()));
                    result
                },
                runtime,
            );

            // depends on server type set (REDISRS_SERVER_TYPE)
            match ctx.server.connection_info().addr() {
                redis::ConnectionAddr::TcpTls { .. } => {
                    if result.is_ok() {
                        panic!(
                            "Must NOT be able to connect without client credentials if server accepts TLS"
                        );
                    }
                }
                _ => {
                    if result.is_err() {
                        panic!(
                            "Must be able to connect without client credentials if server does NOT accept TLS"
                        );
                    }
                }
            }
        }
    }

    #[async_test]
    #[cfg(feature = "connection-manager")]
    async fn resp3_pushes_connection_manager() {
        let ctx = TestContext::new();
        let redis = RedisConnectionInfo::default().set_protocol(ProtocolVersion::RESP3);
        let connection_info = ctx.server.connection_info().set_redis_settings(redis);
        let client = redis::Client::open(connection_info).unwrap();

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let config = redis::aio::ConnectionManagerConfig::new().set_push_sender(tx);
        let mut manager = redis::aio::ConnectionManager::new_with_config(client, config)
            .await
            .unwrap();
        manager
            .send_packed_command(cmd("CLIENT").arg("TRACKING").arg("ON"))
            .await
            .unwrap();
        let pipe = build_simple_pipeline_for_invalidation();
        let _: RedisResult<()> = pipe.query_async(&mut manager).await;
        let _: i32 = manager.get("key_1").await.unwrap();
        let redis::PushInfo { kind, data } = rx.try_recv().unwrap();
        assert_eq!(
            (PushKind::Invalidate, vec![redis_value!(["key_1"])]),
            (kind, data)
        );
    }

    #[async_test]
    async fn select_db() {
        let ctx = TestContext::new();
        let redis = redis_settings().set_db(5);
        let connection_info = ctx.server.connection_info().set_redis_settings(redis);
        let client = redis::Client::open(connection_info).unwrap();

        let mut connection = client.get_multiplexed_async_connection().await.unwrap();

        let info: String = redis::cmd("CLIENT")
            .arg("info")
            .query_async(&mut connection)
            .await
            .unwrap();
        assert!(info.contains("db=5"));
    }

    #[async_test]
    async fn multiplexed_connection_send_single_disconnect_on_connection_failure() {
        let mut ctx = TestContext::new();
        if !ctx.protocol.supports_resp3() {
            return;
        }

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let config = redis::AsyncConnectionConfig::new().set_push_sender(tx);
        let _res = ctx
            .client
            .get_multiplexed_async_connection_with_config(&config)
            .await
            .unwrap();
        drop(config);
        ctx.stop_server();

        assert_eq!(rx.recv().await.unwrap().kind, PushKind::Disconnection);
        sleep(Duration::from_millis(1).into()).await;
        assert_matches!(rx.try_recv(), Err(_));
        assert!(rx.is_closed());
    }

    #[async_test]
    async fn fail_on_empty_command() {
        let ctx = TestContext::new();
        let mut connection = ctx.async_connection().await.unwrap();

        let error: RedisError = redis::Pipeline::new()
            .query_async::<String>(&mut connection)
            .await
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Client);
        assert_eq!(error.to_string(), "empty command - Client");

        let error: RedisError = redis::Cmd::new()
            .query_async::<String>(&mut connection)
            .await
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Client);
        assert_eq!(error.to_string(), "empty command - Client");
    }

    mod transaction {
        use futures::future::join;

        use super::*;

        async fn check_unwatched(con: &mut impl AsyncCommands) {
            let info: String = cmd("CLIENT").arg("INFO").query_async(con).await.unwrap();
            assert!(
                info.contains("watch=0") || !info.contains("watch"),
                "{info}"
            );
        }

        #[async_test]
        async fn simple_case_success(mut con: impl AsyncCommands + Clone) {
            let res: Vec<usize> = redis::aio::transaction_async(
                con.clone(),
                &["x", "y"],
                |mut con, mut pipe| async move {
                    pipe.set("x", 42)
                        .ignore()
                        .set("y", 21)
                        .ignore()
                        .get("x")
                        .get("y")
                        .query_async(&mut con)
                        .await
                },
            )
            .await
            .unwrap();

            assert_eq!(&res, &[42, 21]);
            check_unwatched(&mut con).await;
        }

        #[async_test]
        async fn transaction_should_retry_on_watch() {
            let ctx = TestContext::new();
            let con1 = ctx.async_connection().await.unwrap();
            let mut con2 = ctx.async_connection().await.unwrap();

            let attempts = Arc::new(AtomicUsize::new(0));
            let transaction_started = Arc::new(tokio::sync::Notify::new());
            let transaction_started_clone = transaction_started.clone();
            let interfering_value_sent = Arc::new(tokio::sync::Notify::new());
            let interfering_value_sent_clone = interfering_value_sent.clone();

            let res: Vec<usize> = join(
                redis::aio::transaction_async(con1.clone(), &["x", "y"], |mut con, mut pipe| {
                    let attempts = attempts.clone();
                    let transaction_started = transaction_started_clone.clone();
                    let interfering_value_sent = interfering_value_sent_clone.clone();
                    async move {
                        transaction_started.notify_one();
                        interfering_value_sent.notified().await;
                        let res = attempts.fetch_add(1, Ordering::Relaxed);

                        pipe.set("x", res)
                            .ignore()
                            .get("x")
                            .query_async(&mut con)
                            .await
                    }
                }),
                async move {
                    transaction_started.notified().await;
                    () = con2.set("x", "interfering_value").await.unwrap();
                    interfering_value_sent.notify_one();
                    // we do this again, in order to let the next transaction pass
                    transaction_started.notified().await;
                    interfering_value_sent.notify_one();
                },
            )
            .await
            .0
            .unwrap();

            assert_eq!(&res, &[1]);
            check_unwatched(&mut con1.clone()).await;
        }

        #[async_test]
        async fn transaction_should_retry_on_none_from_closure() {
            let ctx = TestContext::new();
            let con = ctx.async_connection().await.unwrap();

            let attempts = Arc::new(AtomicUsize::new(0));

            let res: Vec<usize> =
                redis::aio::transaction_async(con.clone(), &["x", "y"], |_con, _pipe| {
                    let attempts = attempts.clone();
                    async move {
                        let res = attempts.fetch_add(1, Ordering::Relaxed);

                        if res > 1 {
                            return Ok(Some(vec![res]));
                        }

                        Ok(None)
                    }
                })
                .await
                .unwrap();

            assert_eq!(&res, &[2]);
            check_unwatched(&mut con.clone()).await;
        }

        #[async_test]
        async fn transaction_abort_if_internal_function_returns_error() {
            let ctx = TestContext::new();
            let con = ctx.async_connection().await.unwrap();
            let attempts = Arc::new(AtomicUsize::new(0));

            let res = redis::aio::transaction_async::<_, _, (), _, _>(
                con.clone(),
                &["z"],
                |_con, _pipe| {
                    let attempts = attempts.clone();
                    async move {
                        let curr_attempts = attempts.fetch_add(1, Ordering::SeqCst);

                        if curr_attempts > 1 {
                            return Err(redis::RedisError::from((
                                redis::ErrorKind::Io,
                                "Internal error",
                            )));
                        }

                        // this triggers a retry of the transaction
                        Ok(None)
                    }
                },
            )
            .await
            .unwrap_err();

            assert_eq!(
                res,
                redis::RedisError::from((redis::ErrorKind::Io, "Internal error",))
            );
            assert_eq!(attempts.load(Ordering::SeqCst), 3);
            check_unwatched(&mut con.clone()).await;
        }
    }

    #[cfg(feature = "connection-manager")]
    mod lazy_connection_manager {
        use super::*;

        #[async_test]
        async fn lazy_connection_manager_can_be_created_synchronously() {
            let ctx = TestContext::new();

            let config = redis::aio::ConnectionManagerConfig::new()
                .set_pipeline_buffer_size(100)
                .set_number_of_retries(3);

            let manager = ctx.client.get_connection_manager_lazy(config).unwrap();

            let mut manager = manager;
            let _: () = manager.set("key", "value").await.unwrap();
            let result: String = manager.get("key").await.unwrap();
            assert_eq!(result, "value");
        }

        #[async_test]
        async fn lazy_connection_manager_reconnects_after_disconnect() {
            let ctx = TestContext::new();

            let max_delay_between_attempts = Duration::from_millis(2);
            let config = redis::aio::ConnectionManagerConfig::new()
                .set_max_delay(max_delay_between_attempts);

            let mut manager = ctx.client.get_connection_manager_lazy(config).unwrap();

            let _: () = manager.set("key", "value").await.unwrap();

            let addr = ctx.server.client_addr().clone();
            drop(ctx);

            let result: RedisResult<String> = manager.get("key").await;
            assert!(result.is_err());

            let _ctx = TestContext::new_with_addr(addr);

            for _ in 0..10 {
                sleep(Duration::from_millis(10).into()).await;
                if manager.set::<_, _, ()>("key2", "value2").await.is_ok() {
                    let result: String = manager.get("key2").await.unwrap();
                    assert_eq!(result, "value2");
                    return;
                }
            }
            panic!("Failed to reconnect after multiple attempts");
        }

        #[async_test]
        async fn lazy_connection_manager_can_be_cloned_before_sending() {
            let ctx = TestContext::new();

            let config = redis::aio::ConnectionManagerConfig::new();
            let manager = ctx.client.get_connection_manager_lazy(config).unwrap();
            let mut manager1 = manager.clone();
            let mut manager2 = manager;

            let _: () = manager1.set("key1", "value1").await.unwrap();
            let _: () = manager2.set("key2", "value2").await.unwrap();

            let result1: String = manager1.get("key2").await.unwrap();
            let result2: String = manager2.get("key1").await.unwrap();

            assert_eq!(result1, "value2");
            assert_eq!(result2, "value1");
        }

        #[async_test]
        async fn lazy_connection_manager_with_resp3_push() {
            let ctx = TestContext::new();
            if !ctx.protocol.supports_resp3() {
                return;
            }

            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
            let config = redis::aio::ConnectionManagerConfig::new().set_push_sender(tx);

            let mut manager = ctx.client.get_connection_manager_lazy(config).unwrap();

            let _: () = manager.set("key", "value").await.unwrap();

            manager
                .send_packed_command(cmd("CLIENT").arg("TRACKING").arg("ON"))
                .await
                .unwrap();

            let _: String = manager.get("key").await.unwrap();
            let _: () = manager.set("key", "new_value").await.unwrap();

            let push = rx.recv().await.unwrap();
            assert_eq!(push.kind, PushKind::Invalidate);
        }
    }
}