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
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
use std::fmt::Write;
use std::panic::Location;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::SystemTime;
use ::url::Url;
use bytes::Bytes;
use cookie::time::OffsetDateTime;
use http::{HeaderMap, StatusCode, header};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use super::find_error;
use super::json::{
AssertableJson, Match, descend, difference, entries, fail, find_fragment, pretty, rejection, sorted,
structure_difference, subject, to_json,
};
use crate::error::Error;
use crate::errors::Handled;
use crate::foundation::Application;
use crate::head::AssertableHeadInternals as _;
#[cfg(feature = "inertia")]
use crate::head::HeadConfigInternals as _;
use crate::html::escape;
use crate::http::IntoStatusCode;
use crate::routing::{HandlerId, RouteHandler};
use crate::url::{InvalidSignature, RouteParams};
use crate::view::RenderedView;
const SUMMARY_LENGTH: usize = 2000;
/// The session key that holds the input flashed for the next page.
const OLD_INPUT: &str = "_old_input";
/// Define methods that each assert one status code, with the given doc comment as each method's
/// summary.
macro_rules! status_assertions {
($($(#[$doc:meta])* $name:ident => $status:literal;)*) => {
$(
$(#[$doc])*
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn $name(&self) -> &Self {
self.assert_status($status)
}
)*
};
}
/// The application's response to a [`TestRequest`](super::TestRequest), with assertions.
///
/// Each assertion returns the response, so assertions chain. Because assertions borrow the
/// response, you may bind it to a variable and still read its body or send its cookies
/// afterward:
///
/// ```no_run
/// use laravel::testing::MakesHttpRequests;
///
/// # async fn test(app: laravel::Application) {
/// let response = app.post("/cart").form([("item", "1")]).await;
///
/// response.assert_redirect_to("/cart").assert_session_has("cart.0", 1);
///
/// app.get("/cart").with_cookies_from(&response).await.assert_see("1 item");
/// # }
/// ```
///
/// # Panics
///
/// Dropping a response whose body failed part way through, as a stream that returns an error
/// does, panics unless the test asserted the failure with
/// [`assert_body_failed`](Self::assert_body_failed).
#[derive(Debug)]
pub struct TestResponse {
pub(super) application: Application,
pub(super) root: String,
pub(super) path: String,
/// The request's `Referer`, which is the page that
/// [`assert_redirect_back`](Self::assert_redirect_back) expects.
pub(super) referer: Option<String>,
pub(super) status: StatusCode,
pub(super) headers: HeaderMap,
pub(super) body: Bytes,
pub(super) failed_body: Option<String>,
pub(super) asserted_failed_body: AtomicBool,
pub(super) handled: Option<Handled>,
pub(super) reports: Vec<Arc<Error>>,
pub(super) view: Option<RenderedView>,
pub(super) session: Option<Map<String, Value>>,
pub(super) earlier_cookies: Vec<cookie::Cookie<'static>>,
pub(super) received_at: SystemTime,
pub(super) requested_at: &'static Location<'static>,
/// The request as it was sent, so an Inertia page can
/// [reload](crate::inertia::AssertablePage::reload) itself.
#[cfg(feature = "inertia")]
pub(super) request: super::TestRequest,
}
impl TestResponse {
/// The response's status code.
pub const fn status(&self) -> StatusCode {
self.status
}
/// The response's headers.
pub const fn headers(&self) -> &HeaderMap {
&self.headers
}
/// A header's value, or `None` when the header is missing or its value isn't visible ASCII
/// text.
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.get(name).and_then(|value| value.to_str().ok())
}
/// The value of a cookie that the response sets, as the application gave it.
///
/// An encrypted cookie's value is decrypted, so you can send it back with
/// [`TestRequest::cookie`](super::TestRequest::cookie). Returns `None` when the response
/// doesn't set the cookie.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// let theme = app.post("/theme").await.cookie("theme").unwrap();
///
/// app.get("/").cookie("theme", &theme).await.assert_see(&theme);
/// # }
/// ```
pub fn cookie(&self, name: &str) -> Option<String> {
self.set_cookie(name).map(|cookie| self.plaintext(&cookie))
}
fn set_cookie(&self, name: &str) -> Option<cookie::Cookie<'static>> {
self.set_cookies().find(|cookie| cookie.name() == name)
}
pub(super) fn set_cookies(&self) -> impl Iterator<Item = cookie::Cookie<'static>> {
self.headers
.get_all(header::SET_COOKIE)
.iter()
.filter_map(crate::cookie::parse_set_cookie)
}
pub(super) fn cookies_on_the_way(&self) -> impl Iterator<Item = cookie::Cookie<'static>> {
self.earlier_cookies.iter().cloned().chain(self.set_cookies())
}
pub(super) fn removes(&self, cookie: &cookie::Cookie<'_>) -> bool {
self.expired_by(cookie, self.received_at)
}
pub(super) fn has_expired(&self, cookie: &cookie::Cookie<'_>) -> bool {
self.expired_by(cookie, self.application.clock().now())
}
fn expired_by(&self, cookie: &cookie::Cookie<'_>, time: SystemTime) -> bool {
let expires = match cookie.max_age() {
Some(age) if !age.is_positive() => return true,
Some(age) => Some(OffsetDateTime::from(self.received_at).saturating_add(age)),
None => cookie.expires_datetime(),
};
expires.is_some_and(|expires| expires < OffsetDateTime::from(time))
}
/// Assert the value of a cookie that the response sets, as the application gave it.
///
/// The assertion decrypts an encrypted cookie before it compares the value.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.post("/theme").await.assert_cookie("theme", "dark");
/// # }
/// ```
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_cookie(&self, name: &str, expected: &str) -> &Self {
let cookie = self.set_cookie(name);
let actual = cookie
.as_ref()
.filter(|cookie| !self.removes(cookie))
.map(|cookie| self.plaintext(cookie));
if actual.as_deref() != Some(expected) {
let problem = match (&cookie, actual) {
(None, _) => "the response doesn't set it".to_owned(),
(Some(_), None) => "the response removes it".to_owned(),
(Some(_), Some(actual)) => format!("it's `{actual}`"),
};
panic!(
"expected the `{name}` cookie to be `{expected}`, but {problem}\n\n{}",
self.summary()
);
}
self
}
/// Assert that the response removes a cookie, as
/// [`Response::without_cookie`](crate::http::Response::without_cookie) does.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_cookie_expired(&self, name: &str) -> &Self {
let cookie = self.set_cookie(name);
assert!(
cookie.as_ref().is_some_and(|cookie| self.removes(cookie)),
"expected the response to remove the `{name}` cookie, but {}\n\n{}",
if cookie.is_some() {
"it sets it"
} else {
"it doesn't set it"
},
self.summary()
);
self
}
/// Assert that the response sets a cookie to any value, and doesn't remove it.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_cookie_present(&self, name: &str) -> &Self {
let cookie = self.set_cookie(name);
assert!(
cookie.as_ref().is_some_and(|cookie| !self.removes(cookie)),
"expected the response to set the `{name}` cookie, but {}\n\n{}",
if cookie.is_some() {
"it removes it"
} else {
"it doesn't set it"
},
self.summary()
);
self
}
/// Assert that the response doesn't set a cookie.
///
/// Removing a cookie also sets it, with an expired date, so this assertion fails for a
/// response that removes the cookie. To check a removal, use
/// [`assert_cookie_expired`](Self::assert_cookie_expired).
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_cookie_missing(&self, name: &str) -> &Self {
if let Some(cookie) = self.set_cookie(name) {
panic!(
"expected the response not to set the `{name}` cookie, but it {}\n\n{}",
if self.removes(&cookie) { "removes it" } else { "sets it" },
self.summary()
);
}
self
}
fn plaintext(&self, cookie: &cookie::Cookie<'_>) -> String {
let decrypted = self
.application
.encrypter()
.ok()
.and_then(|encrypter| crate::cookie::decrypt_value(cookie.name(), cookie.value(), encrypter));
decrypted.unwrap_or_else(|| cookie.value().to_owned())
}
/// The response's body as text, with invalid UTF-8 replaced by `�`.
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
/// The response's body as JSON.
///
/// # Panics
///
/// Panics when the body isn't JSON.
#[track_caller]
pub fn json(&self) -> Value {
match serde_json::from_slice(&self.body) {
Ok(json) => json,
Err(error) => panic!("expected a JSON response ({error})\n\n{}", self.summary()),
}
}
/// Assert the status code, as a number or a [`StatusCode`].
///
/// # Panics
///
/// Panics when the assertion fails, or the number isn't a status code.
#[track_caller]
pub fn assert_status(&self, expected: impl IntoStatusCode) -> &Self {
let expected = expected.into_status_code();
assert!(
self.status == expected,
"expected status {expected}, got {}\n\n{}",
self.status,
self.summary()
);
self
}
status_assertions! {
/// Assert a `200 OK`.
assert_ok => 200;
/// Assert a `201 Created`.
assert_created => 201;
/// Assert a `202 Accepted`.
assert_accepted => 202;
/// Assert a `301 Moved Permanently`.
assert_moved_permanently => 301;
/// Assert a `302 Found`, the status of [`Redirect::to`](crate::http::Redirect::to).
assert_found => 302;
/// Assert a `304 Not Modified`.
assert_not_modified => 304;
/// Assert a `307 Temporary Redirect`.
assert_temporary_redirect => 307;
/// Assert a `308 Permanent Redirect`.
assert_permanent_redirect => 308;
/// Assert a `400 Bad Request`.
assert_bad_request => 400;
/// Assert a `401 Unauthorized`.
assert_unauthorized => 401;
/// Assert a `402 Payment Required`.
assert_payment_required => 402;
/// Assert a `403 Forbidden`.
assert_forbidden => 403;
/// Assert a `404 Not Found`.
assert_not_found => 404;
/// Assert a `405 Method Not Allowed`.
assert_method_not_allowed => 405;
/// Assert a `406 Not Acceptable`.
assert_not_acceptable => 406;
/// Assert a `408 Request Timeout`.
assert_request_timeout => 408;
/// Assert a `409 Conflict`.
assert_conflict => 409;
/// Assert a `410 Gone`.
assert_gone => 410;
/// Assert a `415 Unsupported Media Type`.
assert_unsupported_media_type => 415;
/// Assert a `422 Unprocessable Content`.
assert_unprocessable => 422;
/// Assert a `424 Failed Dependency`.
assert_failed_dependency => 424;
/// Assert a `429 Too Many Requests`.
assert_too_many_requests => 429;
/// Assert a `500 Internal Server Error`.
assert_internal_server_error => 500;
/// Assert a `503 Service Unavailable`.
assert_service_unavailable => 503;
}
/// Assert a `204 No Content` with an empty body.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_no_content(&self) -> &Self {
self.assert_status(204);
assert!(
self.body.is_empty(),
"expected no content, but the body isn't empty\n\n{}",
self.summary()
);
self
}
/// Assert a successful status, which is any `2xx` status.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_successful(&self) -> &Self {
self.assert_status_class(self.status.is_success(), "a successful")
}
/// Assert a client error, which is any `4xx` status.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_client_error(&self) -> &Self {
self.assert_status_class(self.status.is_client_error(), "a client error")
}
/// Assert a server error, which is any `5xx` status.
///
/// To assert only a `500`, use
/// [`assert_internal_server_error`](Self::assert_internal_server_error).
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_server_error(&self) -> &Self {
self.assert_status_class(self.status.is_server_error(), "a server error")
}
#[track_caller]
fn assert_status_class(&self, matches: bool, class: &str) -> &Self {
assert!(
matches,
"expected {class} status, got {}\n\n{}",
self.status,
self.summary()
);
self
}
/// Assert a redirect, which is a `3xx` status with a `location` header.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_redirect(&self) -> &Self {
assert!(
self.status.is_redirection() && self.header("location").is_some(),
"expected a redirect, got {}\n\n{}",
self.status,
self.summary()
);
self
}
/// Assert a redirect to the given path or URL.
///
/// A path resolves against the request's scheme and host, as the application saw them, so a
/// redirect to another host doesn't match it. URLs match however they're written, so a
/// redirect to `http://localhost` matches `/` when the request went to `localhost`.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_redirect_to(&self, expected: impl AsRef<str>) -> &Self {
let expected = expected.as_ref();
self.assert_redirect();
let expected_url = self.resolve(expected);
let location = self.location();
assert!(
expected_url.is_some() && location == expected_url,
"expected a redirect to {}, but it redirects to {}\n\n{}",
expected_url.as_ref().map_or(expected, Url::as_str),
location
.as_ref()
.map_or_else(|| self.header("location").unwrap_or_default(), Url::as_str),
self.summary()
);
self
}
/// Assert a redirect to the URL of the route that `handler` handles, filled in with
/// `parameters`.
///
/// The URLs compare as they do in [`assert_redirect_to`](Self::assert_redirect_to).
///
/// # Panics
///
/// Panics when the assertion fails, or the route's URL can't be built, such as when the
/// handler doesn't handle exactly one route.
#[track_caller]
pub fn assert_redirect_to_route<H, T>(&self, handler: H, parameters: impl RouteParams) -> &Self
where
H: RouteHandler<T>,
{
self.assert_redirect_to(self.route_url(handler, parameters))
}
#[track_caller]
fn route_url<H, T>(&self, handler: H, parameters: impl RouteParams) -> String
where
H: RouteHandler<T>,
{
let routes = self.application.routes();
match routes.destination(HandlerId::of(handler), parameters.into_params(), &self.root) {
Ok(destination) => destination.url(),
Err(error) => panic!("{error}"),
}
}
/// Assert a redirect whose `location` contains the text, such as a query parameter.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_redirect_contains(&self, text: &str) -> &Self {
self.assert_redirect();
let location = self.header("location").unwrap_or_default();
assert!(
location.contains(text),
"expected a redirect to a URL containing `{text}`, but it redirects to {location}\n\n{}",
self.summary()
);
self
}
/// Assert a redirect back to the page the request came from, as
/// [`Redirect::back`](crate::http::Redirect::back) returns.
///
/// Send the request [`from`](super::TestRequest::from) that page, so the assertion knows
/// which page to expect.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.post("/profile")
/// .from("/profile/edit")
/// .form([("email", "not-an-email")])
/// .await
/// .assert_redirect_back()
/// .assert_invalid(&["email"]);
/// # }
/// ```
///
/// # Panics
///
/// Panics when the assertion fails, or the request has no `Referer` header.
#[track_caller]
pub fn assert_redirect_back(&self) -> &Self {
let Some(previous) = &self.referer else {
panic!(
"the request didn't say which page it came from: send it `from` the page, as in `app.post(\"/profile\").from(\"/profile/edit\")`\n\n{}",
self.summary()
);
};
self.assert_redirect_to(previous)
}
/// Assert a redirect back, as [`assert_redirect_back`](Self::assert_redirect_back) does, and
/// a validation error in the session for each field, as
/// [`assert_invalid`](Self::assert_invalid) does.
///
/// # Panics
///
/// Panics when the assertion fails, or the request has no `Referer` header.
#[track_caller]
pub fn assert_redirect_back_with_errors(&self, fields: &[&str]) -> &Self {
self.assert_redirect_back().assert_invalid(fields)
}
/// Assert a redirect back, as [`assert_redirect_back`](Self::assert_redirect_back) does, with
/// no validation errors in the session.
///
/// # Panics
///
/// Panics when the assertion fails, or the request has no `Referer` header.
#[track_caller]
pub fn assert_redirect_back_without_errors(&self) -> &Self {
self.assert_redirect_back().assert_valid(&[])
}
/// Assert a redirect to a [signed URL](crate::url::signed_route) of the route that `handler`
/// handles, filled in with `parameters`.
///
/// The signature must be valid. A [temporary](crate::url::temporary_signed_route) URL must
/// also be unexpired. The URLs compare as they do in
/// [`assert_redirect_to`](Self::assert_redirect_to), ignoring the `expires` and `signature`
/// parameters.
///
/// # Panics
///
/// Panics when the assertion fails, or the route's URL can't be built, such as when the
/// handler doesn't handle exactly one route.
#[track_caller]
pub fn assert_redirect_to_signed_route<H, T>(&self, handler: H, parameters: impl RouteParams) -> &Self
where
H: RouteHandler<T>,
{
self.assert_redirect();
let location = self.location().expect("a redirect has a location");
let signature = crate::routing::signed::verify(
&self.application.config().app,
&location.origin().ascii_serialization(),
location.path(),
location.query(),
&[],
self.application.clock().now(),
);
if let Err(invalid) = signature {
let problem = match invalid {
InvalidSignature::Expired => "expired",
_ => "invalid",
};
panic!(
"expected a redirect to a signed URL, but its signature is {problem}: {location}\n\n{}",
self.summary()
);
}
let expected = self.route_url(handler, parameters);
let expected_url = self.resolve(&expected);
let unsigned_query: Vec<&str> = location
.query()
.unwrap_or_default()
.split('&')
.filter(|part| !part.is_empty() && !matches!(part.split('=').next(), Some("expires" | "signature")))
.collect();
let mut unsigned = location.clone();
unsigned.set_query(
Some(unsigned_query.join("&"))
.filter(|query| !query.is_empty())
.as_deref(),
);
assert!(
expected_url.as_ref() == Some(&unsigned),
"expected a redirect to a signed URL of {}, but it redirects to {location}\n\n{}",
expected_url.as_ref().map_or(expected.as_str(), Url::as_str),
self.summary()
);
self
}
pub(super) fn root_url(&self) -> Option<Url> {
Url::parse(&self.root).ok()
}
pub(super) fn location(&self) -> Option<Url> {
self.resolve(&self.path)?.join(self.header("location")?).ok()
}
/// A path or URL resolved against the request's scheme and host.
fn resolve(&self, url: &str) -> Option<Url> {
self.root_url()?.join(url).ok()
}
/// Assert a header's value.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_header(&self, name: &str, expected: &str) -> &Self {
let actual = self.header(name);
assert!(
actual == Some(expected),
"expected the `{name}` header to be `{expected}`, but it's {}\n\n{}",
actual.map_or_else(|| "missing".to_owned(), |actual| format!("`{actual}`")),
self.summary()
);
self
}
/// Assert that a header is missing.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_header_missing(&self, name: &str) -> &Self {
if let Some(actual) = self.header(name) {
panic!("expected no `{name}` header, but it's `{actual}`\n\n{}", self.summary());
}
self
}
/// Assert that the response has a header with any value.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_header_present(&self, name: &str) -> &Self {
assert!(
self.headers.contains_key(name),
"expected a `{name}` header\n\n{}",
self.summary()
);
self
}
/// Assert that a header's value contains the text, such as `charset=utf-8` in a
/// `content-type`.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_header_contains(&self, name: &str, text: &str) -> &Self {
let actual = self.header(name);
assert!(
actual.is_some_and(|actual| actual.contains(text)),
"expected the `{name}` header to contain `{text}`, but it's {}\n\n{}",
actual.map_or_else(|| "missing".to_owned(), |actual| format!("`{actual}`")),
self.summary()
);
self
}
/// Assert that the response is a download of a file with this name, as
/// [`File::download`](crate::http::File::download) and [`Download`](crate::http::Download)
/// send.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/invoices/1/download").await.assert_ok().assert_download("invoice-1.pdf");
/// # }
/// ```
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_download(&self, name: &str) -> &Self {
let disposition = self.header("content-disposition");
let file_name = disposition.and_then(download_name);
assert!(
file_name.as_deref() == Some(name),
"expected a download of `{name}`, but {}\n\n{}",
match (disposition, file_name) {
(None, _) => "the response has no `content-disposition` header".to_owned(),
(Some(disposition), None) => format!("its `content-disposition` is `{disposition}`"),
(Some(_), Some(other)) => format!("it downloads `{other}`"),
},
self.summary()
);
self
}
/// Assert that the body contains the text.
///
/// The text matches either escaped for HTML, as a view prints a value, or as written, as in a
/// template's own text. For example, `assert_see("O'Reilly")` matches both `O'Reilly` and
/// `O'Reilly`. To match markup exactly, use [`assert_see_html`](Self::assert_see_html).
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_see(&self, text: &str) -> &Self {
assert!(
find(&self.text(), text).is_some(),
"expected the response to contain `{text}`\n\n{}",
self.summary()
);
self
}
/// Assert that the body contains the markup, exactly as written.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_see_html(&self, markup: &str) -> &Self {
assert!(
self.text().contains(markup),
"expected the response to contain `{markup}`\n\n{}",
self.summary()
);
self
}
/// Assert that the body contains the texts in the given order, such as the items of a list
/// sorted by date.
///
/// Each text matches escaped or as written, as it does with [`assert_see`](Self::assert_see).
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_see_in_order(&self, texts: &[&str]) -> &Self {
let body = self.text();
let mut rest = body.as_str();
for text in texts {
let Some((position, length)) = find(rest, text) else {
panic!(
"expected the response to contain {texts:?} in order, but not `{text}` after those before it\n\n{}",
self.summary()
);
};
rest = &rest[position + length..];
}
self
}
/// Assert that the body doesn't contain the text, either escaped for HTML or as written.
///
/// The text matches as it does with [`assert_see`](Self::assert_see).
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_dont_see(&self, text: &str) -> &Self {
assert!(
find(&self.text(), text).is_none(),
"expected the response not to contain `{text}`\n\n{}",
self.summary()
);
self
}
/// Assert that the body doesn't contain the markup, exactly as written.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_dont_see_html(&self, markup: &str) -> &Self {
assert!(
!self.text().contains(markup),
"expected the response not to contain `{markup}`\n\n{}",
self.summary()
);
self
}
/// Assert that the JSON body contains the given JSON.
///
/// Objects in the body may have keys that the expected JSON doesn't mention. Lists match item
/// by item from the first, so a list in the body may have more items after the expected
/// ones.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// // The first users are Taylor and Abigail, in that order, with any other fields...
/// app.get("/api/users")
/// .await
/// .assert_json(serde_json::json!({ "data": [{ "name": "Taylor" }, { "name": "Abigail" }] }));
/// # }
/// ```
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_json(&self, expected: impl Serialize) -> &Self {
self.assert_json_against(expected, Match::Contains)
}
/// Assert that the JSON body is exactly the given JSON.
///
/// The body may have no other keys or items, and its lists must have their items in the same
/// order. Object keys may be in any order.
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_exact_json(&self, expected: impl Serialize) -> &Self {
self.assert_json_against(expected, Match::Exact)
}
/// Assert that the JSON body is the given JSON, with list items in any order.
///
/// The body may have no other keys or items.
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_similar_json(&self, expected: impl Serialize) -> &Self {
self.assert_json_against(expected, Match::Similar)
}
#[track_caller]
fn assert_json_against(&self, expected: impl Serialize, matching: Match) -> &Self {
let expected = to_json(expected);
let (actual, expected) = match matching {
Match::Similar => (sorted(&self.json()), sorted(&expected)),
Match::Contains | Match::Exact => (self.json(), expected),
};
if let Some(difference) = difference(&actual, &expected, "", matching) {
self.fail_json(
&actual,
format_args!(
"expected the JSON response to {}:\n{}\n\nbut {difference}, in",
matching.wanted(),
pretty(&expected)
),
);
}
self
}
/// Assert how many items the JSON body's top-level array or object has.
///
/// To count the items of an array or object at a path, use
/// [`assert_json_count_at`](Self::assert_json_count_at).
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/api/users").await.assert_json_count(3);
/// # }
/// ```
///
/// # Panics
///
/// Panics when the body isn't JSON, isn't an array or object, or has another number of items.
#[track_caller]
pub fn assert_json_count(&self, count: usize) -> &Self {
self.assert_json_count_at("", count)
}
/// Assert how many items the array or object at a dot-notation path of the JSON body has.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/api/users").await.assert_json_count_at("data", 3);
/// # }
/// ```
///
/// # Panics
///
/// Panics when the body isn't JSON, or the value at the path is missing, isn't an array or
/// object, or has another number of items.
#[track_caller]
pub fn assert_json_count_at(&self, path: &str, count: usize) -> &Self {
let actual = self.json();
let value = descend(&actual, path);
let length = value.and_then(entries).map(|entries| entries.len());
if length == Some(count) {
return self;
}
let target = if path.is_empty() {
"the JSON response".to_owned()
} else {
format!("`{path}` of the JSON response")
};
let problem = match (value, length) {
(None, _) => "it's missing".to_owned(),
(Some(value), None) => format!("it's {value}"),
(Some(_), Some(length)) => format!("it has {length}"),
};
self.fail_json(
&actual,
format_args!("expected {target} to have {count} items, but {problem}"),
)
}
/// Assert the value at a dot-notation path of the JSON body.
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_json_path(&self, path: &str, expected: impl Serialize) -> &Self {
let expected = to_json(expected);
let actual = self.json();
let value = descend(&actual, path);
if value != Some(&expected) {
self.fail_json(
&actual,
format_args!(
"expected `{path}` of the JSON response to be {expected}, but it's {}",
shown(value)
),
);
}
self
}
/// Assert that the value at a dot-notation path of the JSON body reads as a `T` that passes
/// the check.
///
/// Name the type in the closure, as in `|total: u64| total > 10`.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/api/users")
/// .await
/// .assert_json_path_where("meta.total", |total: u64| total > 10)
/// .assert_json_path_where("data.0.email", |email: String| email.ends_with("@laravel.com"));
/// # }
/// ```
///
/// # Panics
///
/// Panics when the body isn't JSON, or the value is missing, doesn't read as a `T`, or fails
/// the check.
#[track_caller]
pub fn assert_json_path_where<T: DeserializeOwned>(&self, path: &str, check: impl FnOnce(T) -> bool) -> &Self {
let actual = self.json();
self.assert_satisfies(&format!("`{path}` of the JSON response"), descend(&actual, path), check);
self
}
/// Assert that the JSON body has no value at a dot-notation path.
///
/// A `null` counts as a value, so this assertion fails for a path that holds `null`.
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_json_missing_path(&self, path: &str) -> &Self {
let actual = self.json();
if let Some(value) = descend(&actual, path) {
self.fail_json(
&actual,
format_args!("expected the JSON response to have no `{path}`, but it's {value}"),
);
}
self
}
/// Assert that the given JSON appears anywhere in the JSON body.
///
/// The assertion passes when some object or list in the body contains the given JSON, as
/// [`assert_json`](Self::assert_json) matches it.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/api/users")
/// .await
/// .assert_json_fragment(serde_json::json!({ "name": "Taylor", "role": "admin" }));
/// # }
/// ```
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_json_fragment(&self, fragment: impl Serialize) -> &Self {
let fragment = to_json(fragment);
let actual = self.json();
if find_fragment(&actual, &fragment, "").is_none() {
self.fail_json(
&actual,
format_args!(
"expected the JSON response to contain the fragment:\n{}\n\nin",
pretty(&fragment)
),
);
}
self
}
/// Assert that the given JSON appears nowhere in the JSON body.
///
/// This assertion is the opposite of [`assert_json_fragment`](Self::assert_json_fragment).
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_json_missing(&self, fragment: impl Serialize) -> &Self {
let fragment = to_json(fragment);
let actual = self.json();
if let Some(path) = find_fragment(&actual, &fragment, "") {
self.fail_json(
&actual,
format_args!(
"expected the JSON response not to contain the fragment:\n{}\n\nbut {} contains it, in",
pretty(&fragment),
subject(&path)
),
);
}
self
}
/// Assert that the JSON body has the keys that a structure names, whatever their values.
///
/// In the structure, a list names keys, and an object names keys along with the structure of
/// their values. The key `*` gives the structure of every item of a list or object:
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/api/users")
/// .await
/// .assert_json_structure(serde_json::json!({
/// "data": { "*": ["id", "name", { "team": ["id", "name"] }] },
/// "meta": ["total"],
/// }));
/// # }
/// ```
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_json_structure(&self, structure: impl Serialize) -> &Self {
self.assert_structure(structure, false)
}
/// Assert that the JSON body has exactly the keys that a structure names, and no others.
///
/// The structure works as it does in [`assert_json_structure`](Self::assert_json_structure).
///
/// # Panics
///
/// Panics when the assertion fails, or the body isn't JSON.
#[track_caller]
pub fn assert_exact_json_structure(&self, structure: impl Serialize) -> &Self {
self.assert_structure(structure, true)
}
#[track_caller]
fn assert_structure(&self, structure: impl Serialize, exact: bool) -> &Self {
let structure = to_json(structure);
let actual = self.json();
if let Some(difference) = structure_difference(&actual, &structure, "", exact) {
self.fail_json(
&actual,
format_args!(
"expected the JSON response to have the structure:\n{}\n\nbut {difference}, in",
pretty(&structure)
),
);
}
self
}
/// Assert on the JSON body with [`AssertableJson`]'s methods, in a closure.
///
/// The closure must assert on every key or item at the top level, or call
/// [`etc`](AssertableJson::etc) to allow the keys it doesn't check. Without `etc`, the test
/// fails when the response gains a key that the test doesn't expect, such as a password
/// hash.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/api/users/1").await.assert_json_matches(|json| {
/// json.equals("id", 1)
/// .equals("name", "Taylor")
/// .missing("password")
/// .scope("team", |team| team.has("id").etc())
/// });
/// # }
/// ```
///
/// # Panics
///
/// Panics when the body isn't JSON, or an assertion fails.
#[track_caller]
pub fn assert_json_matches(
&self,
assertions: impl for<'a> FnOnce(&'a AssertableJson) -> &'a AssertableJson,
) -> &Self {
AssertableJson::assert_root(self.json(), self.outline(), assertions);
self
}
#[track_caller]
fn assert_satisfies<T: DeserializeOwned>(
&self,
subject: &str,
value: Option<&Value>,
check: impl FnOnce(T) -> bool,
) {
let rejection = match value {
Some(value) => rejection(value, check),
None => Some("pass the check, but it's missing".to_owned()),
};
if let Some(rejection) = rejection {
panic!("expected {subject} to {rejection}\n\n{}", self.summary());
}
}
#[track_caller]
fn assert_equals(&self, subject: &str, actual: Option<&Value>, expected: impl Serialize) -> &Self {
let expected = to_json(expected);
assert!(
actual == Some(&expected),
"expected {subject} to be {expected}, but it's {}\n\n{}",
shown(actual),
self.summary()
);
self
}
/// Assert that the response is an Inertia page, and return the page for assertions on its
/// component and props.
///
/// When the application has a `resources/js/pages` directory, asserting the page's
/// [`component`](crate::inertia::AssertablePage::component) also asserts that the component
/// has a page file there.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/").await.assert_inertia().component("Welcome").has("name");
/// # }
/// ```
///
/// The page can [reload](crate::inertia::AssertablePage::reload) itself with an Inertia
/// visit. The visit sends this request's headers, cookies,
/// [user](super::TestRequest::acting_as), and IP address, plus the cookies that this response
/// set:
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/posts/1")
/// .await
/// .assert_inertia()
/// .missing("reviews")
/// .reload_only(&["reviews"])
/// .await
/// .has_count("reviews", 3);
/// # }
/// ```
///
/// # Panics
///
/// Panics when the response doesn't contain an Inertia page.
#[cfg(feature = "inertia")]
#[track_caller]
pub fn assert_inertia(&self) -> crate::inertia::AssertablePage {
assert!(
self.has_inertia_page(),
"expected an Inertia page\n\n{}",
self.summary()
);
self.inertia_page()
}
#[cfg(feature = "inertia")]
fn has_inertia_page(&self) -> bool {
self.header("x-inertia").is_some() || self.text().contains(r#"type="application/json">"#)
}
#[cfg(feature = "inertia")]
#[track_caller]
fn inertia_page(&self) -> crate::inertia::AssertablePage {
let client = self.request.after(self);
let mut page = crate::inertia::AssertablePage::from_body(&self.text());
let pages = self.application.config().app.base_path.join("resources/js/pages");
if pages.is_dir() {
page = page.pages_in(pages);
}
page.reloads_with(move |reload| {
let request = client.clone().reload(&reload);
async move {
let response = request.await;
assert!(
response.has_inertia_page(),
"expected the reload to respond with an Inertia page\n\n{}\n\nat {}",
response.summary(),
reload.location()
);
response.inertia_page()
}
})
}
/// Read the response's head for assertions on its tags.
///
/// The head is the `<head>` of an HTML document, or the head prop of an Inertia visit's page,
/// so the same assertions work for both kinds of response.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/posts/1")
/// .await
/// .assert_head()
/// .title("Hello World · Laravel")
/// .meta("og:title", "Hello World · Laravel")
/// .link("canonical", "http://localhost/posts/1")
/// .missing("robots");
/// # }
/// ```
///
/// # Panics
///
/// Panics when the response is neither an HTML document nor an Inertia page, or when an Inertia
/// visit's page has no head prop.
#[track_caller]
pub fn assert_head(&self) -> crate::head::AssertableHead {
#[cfg(feature = "inertia")]
if self.header("x-inertia").is_some() {
let name = self.application.head().inertia_prop_name();
let json = self.json();
let elements: Option<Vec<&str>> = json["props"][name]
.as_array()
.and_then(|elements| elements.iter().map(Value::as_str).collect());
let Some(elements) = elements else {
panic!("expected the head in the Inertia prop `{name}`\n\n{}", self.summary());
};
return crate::head::AssertableHead::from_markup(&elements.join("\n"));
}
match self.header("content-type") {
Some(content_type) if content_type.starts_with("text/html") => {}
Some(content_type) => panic!(
"expected an HTML document or an Inertia page, but the content type is `{content_type}`\n\n{}",
self.summary()
),
None => panic!(
"expected an HTML document or an Inertia page, but the response has no content type\n\n{}",
self.summary()
),
}
crate::head::AssertableHead::from_markup(&self.text())
}
/// Assert that the response is the view with this name.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_view_is(&self, name: &str) -> &Self {
let rendered = self.view.as_ref().map(|view| view.name.as_str());
assert!(
rendered == Some(name),
"expected the view `{name}`, but {}\n\n{}",
rendered.map_or_else(
|| "the response isn't a view".to_owned(),
|other| format!("got `{other}`")
),
self.summary()
);
self
}
/// Assert a value of the view's own data, by dot-notation key, such as `ticket.subject`.
///
/// The assertion checks the data given to this view, not the data shared with every view.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_view_has(&self, name: &str, expected: impl Serialize) -> &Self {
self.assert_equals(&format!("the view data `{name}`"), self.view_data(name), expected)
}
/// Assert that the view's own data has a value of any kind at this dot-notation key.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_view_present(&self, name: &str) -> &Self {
assert!(
self.view_data(name).is_some(),
"expected the view to have the data `{name}`\n\n{}",
self.summary()
);
self
}
/// Assert that a value of the view's own data reads as a `T` that passes the check.
///
/// Name the type in the closure, as in `|posts: Vec<Post>| posts.len() == 3`.
///
/// # Panics
///
/// Panics when the value is missing, doesn't read as a `T`, or fails the check.
#[track_caller]
pub fn assert_view_where<T: DeserializeOwned>(&self, name: &str, check: impl FnOnce(T) -> bool) -> &Self {
self.assert_satisfies(&format!("the view data `{name}`"), self.view_data(name), check);
self
}
/// Assert that the view's own data has no value at this dot-notation key.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_view_missing(&self, name: &str) -> &Self {
assert!(
self.view_data(name).is_none(),
"expected the view not to have the data `{name}`\n\n{}",
self.summary()
);
self
}
/// Assert that the view rendered only this block, as with
/// [`View::fragment`](crate::view::View::fragment).
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_fragment_is(&self, block: &str) -> &Self {
let fragment = self.view.as_ref().and_then(|view| view.fragment.as_deref());
assert!(
fragment == Some(block),
"expected the fragment `{block}`, but {}\n\n{}",
fragment.map_or_else(
|| "the whole view rendered".to_owned(),
|other| format!("got `{other}`")
),
self.summary()
);
self
}
/// Assert that each field has a validation error, in the JSON body's `errors` or the
/// session's `default` form.
///
/// An empty list asserts that at least one field has an error. Field names are error keys as
/// written, such as `items.0.name`, not patterns. For a
/// [named form](crate::validation::InvalidInput::for_form), use
/// [`assert_invalid_in`](Self::assert_invalid_in).
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.post("/users")
/// .form([("email", "not-an-email")])
/// .await
/// .assert_invalid(&["email", "name"])
/// .assert_valid(&["password_confirmation"]);
/// # }
/// ```
///
/// # Panics
///
/// Panics when the response has no validation errors, or a named field has none.
#[track_caller]
pub fn assert_invalid(&self, fields: &[&str]) -> &Self {
let errors = self.validation_errors();
if errors.is_empty() {
let hint = self
.named_form_with_errors()
.map(|form| format!(", but the `{form}` form has some: use `assert_invalid_in(\"{form}\", ..)`"))
.unwrap_or_default();
panic!("expected validation errors{hint}\n\n{}", self.summary());
}
self.assert_fields_invalid(&errors, fields, "")
}
/// Assert validation errors in the session for the named
/// [form](crate::validation::InvalidInput::for_form).
///
/// The fields work as they do with [`assert_invalid`](Self::assert_invalid).
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.post("/login").await.assert_invalid_in("login", &["email"]);
/// # }
/// ```
///
/// # Panics
///
/// Panics when the route has no session, the form has no errors, or a named field has none.
#[track_caller]
pub fn assert_invalid_in(&self, form: &str, fields: &[&str]) -> &Self {
self.expect_session();
let errors = self.form_errors(form);
let in_form = format!(" in the `{form}` form");
assert!(
!errors.is_empty(),
"expected validation errors{in_form}\n\n{}",
self.summary()
);
self.assert_fields_invalid(&errors, fields, &in_form)
}
#[track_caller]
fn assert_fields_invalid(&self, errors: &Map<String, Value>, fields: &[&str], in_form: &str) -> &Self {
for field in fields {
assert!(
errors.contains_key(*field),
"expected validation errors for `{field}`{in_form}\n\n{}",
self.summary()
);
}
self
}
/// Assert that each field has a validation error that contains the given text, in the JSON
/// body or the session's `default` form.
///
/// The text may be part of the error message.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.post("/users")
/// .await
/// .assert_invalid_messages(&[("email", "required"), ("password", "at least 8")]);
/// # }
/// ```
///
/// # Panics
///
/// Panics when a field has no errors, or has no error that contains its text.
#[track_caller]
pub fn assert_invalid_messages(&self, expected: &[(&str, &str)]) -> &Self {
let errors = self.validation_errors();
for (field, text) in expected {
let messages = errors.get(*field).map(Value::as_array);
let found = messages.flatten().is_some_and(|messages| {
messages
.iter()
.filter_map(Value::as_str)
.any(|message| message.contains(text))
});
assert!(
found,
"expected a validation error for `{field}` containing `{text}`\n\n{}",
self.summary()
);
}
self
}
/// Assert that none of the fields has a validation error, in the JSON body or the session's
/// `default` form.
///
/// An empty list asserts that no field has an error.
///
/// # Panics
///
/// Panics when a checked field has a validation error.
#[track_caller]
pub fn assert_valid(&self, fields: &[&str]) -> &Self {
let errors = self.validation_errors();
let failed = if fields.is_empty() {
errors.keys().next().map(String::as_str)
} else {
fields.iter().find(|field| errors.contains_key(**field)).copied()
};
if let Some(field) = failed {
panic!("unexpected validation errors for `{field}`\n\n{}", self.summary());
}
self
}
fn form_errors(&self, form: &str) -> Map<String, Value> {
self.session("errors")
.and_then(|forms| forms.get(form))
.and_then(Value::as_object)
.cloned()
.unwrap_or_default()
}
fn named_form_with_errors(&self) -> Option<&str> {
let forms = self.session("errors")?.as_object()?;
forms
.iter()
.find(|(form, errors)| *form != "default" && errors.as_object().is_some_and(|errors| !errors.is_empty()))
.map(|(form, _)| form.as_str())
}
fn validation_errors(&self) -> Map<String, Value> {
let mut errors = self.form_errors("default");
if let Ok(Value::Object(json)) = serde_json::from_slice::<Value>(&self.body)
&& let Some(json) = json.get("errors").and_then(Value::as_object)
{
errors.extend(json.clone());
}
errors
}
/// A session value by dot-notation key, as the request left the session.
///
/// The values include those the request flashed for the next request. Returns `None` when
/// the key is missing or the route has no session.
pub fn session(&self, key: &str) -> Option<&Value> {
let (first, rest) = key.split_once('.').unwrap_or((key, ""));
descend(self.session.as_ref()?.get(first)?, rest)
}
/// Assert a session value by dot-notation key, as the request left the session.
///
/// Values flashed for the next request, such as a redirect's status message, also match.
///
/// # Panics
///
/// Panics when the assertion fails, or the route has no session.
#[track_caller]
pub fn assert_session_has(&self, key: &str, expected: impl Serialize) -> &Self {
self.expect_session();
self.assert_equals(&format!("the session's `{key}`"), self.session(key), expected)
}
/// Assert that the session has no value for a key, or has `null` for it.
///
/// # Panics
///
/// Panics when the assertion fails, or the route has no session.
#[track_caller]
pub fn assert_session_missing(&self, key: &str) -> &Self {
self.expect_session();
let actual = self.session(key).filter(|value| !value.is_null());
assert!(
actual.is_none(),
"expected the session to have no `{key}`, but it's {}\n\n{}",
actual.map_or_else(String::new, ToString::to_string),
self.summary()
);
self
}
/// Assert that the session has a value of any kind for a key, as the request left the
/// session.
///
/// Values flashed for the next request also match.
///
/// # Panics
///
/// Panics when the assertion fails, or the route has no session.
#[track_caller]
pub fn assert_session_present(&self, key: &str) -> &Self {
self.expect_session();
assert!(
self.session(key).is_some_and(|value| !value.is_null()),
"expected the session to have `{key}`\n\n{}",
self.summary()
);
self
}
/// Assert that a session value reads as a `T` that passes the check.
///
/// Name the type in the closure, as in `|cart: Vec<u64>| cart.contains(&7)`.
///
/// # Panics
///
/// Panics when the route has no session, or the value is missing, doesn't read as a `T`, or
/// fails the check.
#[track_caller]
pub fn assert_session_where<T: DeserializeOwned>(&self, key: &str, check: impl FnOnce(T) -> bool) -> &Self {
self.expect_session();
self.assert_satisfies(&format!("the session's `{key}`"), self.session(key), check);
self
}
/// Assert the old input that the response flashed for the next page, by dot-notation path.
///
/// The next page reads this input with [`old`](crate::http::Request::old).
/// [`Redirect::with_input`](crate::http::Redirect::with_input) and failed validation both
/// flash it.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.post("/sign-up")
/// .form([("email", "taylor@laravel.com"), ("password", "short")])
/// .await
/// .assert_session_has_input("email", "taylor@laravel.com")
/// .assert_session_missing_input("password");
/// # }
/// ```
///
/// # Panics
///
/// Panics when the assertion fails, or the route has no session.
#[track_caller]
pub fn assert_session_has_input(&self, path: &str, expected: impl Serialize) -> &Self {
self.expect_session();
self.assert_equals(
&format!("the old input `{path}`"),
self.session(&format!("{OLD_INPUT}.{path}")),
expected,
)
}
/// Assert that the response flashed no old input at this dot-notation path, such as for a
/// password field.
///
/// # Panics
///
/// Panics when the assertion fails, or the route has no session.
#[track_caller]
pub fn assert_session_missing_input(&self, path: &str) -> &Self {
self.expect_session();
if let Some(actual) = self.session(&format!("{OLD_INPUT}.{path}")) {
panic!(
"expected no old input `{path}`, but it's {actual}\n\n{}",
self.summary()
);
}
self
}
/// Assert that a user is logged in to the session after the request, such as after a login
/// form.
///
/// The assertion reads the session that the request left. A request sent
/// [`acting_as`](super::TestRequest::acting_as) a user doesn't log the user in to the
/// session, so the assertion fails for that request unless the handler logged the user in.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.post("/login")
/// .form([("email", "taylor@laravel.com"), ("password", "password")])
/// .await
/// .assert_redirect_to("/dashboard")
/// .assert_authenticated();
/// # }
/// ```
///
/// # Panics
///
/// Panics when the assertion fails, or the route has no session.
#[track_caller]
pub fn assert_authenticated(&self) -> &Self {
self.expect_session();
assert!(
self.logged_in_id().is_some(),
"expected a user to be logged in, but the session has none\n\n{}",
self.summary()
);
self
}
/// Assert that no user is logged in to the session after the request, such as after logging
/// out or a failed login.
///
/// # Panics
///
/// Panics when the assertion fails, or the route has no session.
#[track_caller]
pub fn assert_guest(&self) -> &Self {
self.expect_session();
if let Some(id) = self.logged_in_id() {
panic!(
"expected no user to be logged in, but the user with ID {id} is\n\n{}",
self.summary()
);
}
self
}
/// Assert that this user is logged in to the session after the request, by their
/// [`auth_id`](crate::auth::Authenticatable::auth_id).
///
/// # Panics
///
/// Panics when the assertion fails, or the route has no session.
#[track_caller]
pub fn assert_authenticated_as<U: crate::auth::Authenticatable>(&self, user: &U) -> &Self {
self.expect_session();
let expected = serde_json::to_value(user.auth_id()).expect("the user's ID should serialize");
let actual = self.logged_in_id();
assert!(
actual == Some(&expected),
"expected the user with ID {expected} to be logged in, but {}\n\n{}",
actual.map_or_else(|| "no user is".to_owned(), |id| format!("the user with ID {id} is")),
self.summary()
);
self
}
fn logged_in_id(&self) -> Option<&Value> {
self.session(crate::auth::USER_ID_KEY).filter(|id| !id.is_null())
}
#[track_caller]
fn expect_session(&self) {
assert!(
self.session.is_some(),
"the route has no session: only routes in the `web` group start one\n\n{}",
self.summary()
);
}
/// A value of the view's own data by dot-notation key, such as `ticket.subject` or
/// `tickets.0.id`.
///
/// Returns `None` when the response isn't a view, or the view didn't receive the value.
pub fn view_data(&self, name: &str) -> Option<&Value> {
let (first, rest) = name.split_once('.').unwrap_or((name, ""));
descend(self.view.as_ref()?.data.get(first)?, rest)
}
/// The error the application handled while responding, if any.
///
/// This is the error itself, not the page that the application rendered for it.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// let response = app.post("/checkout").await;
///
/// let message = response.error().map(ToString::to_string);
/// # }
/// ```
pub fn error(&self) -> Option<&Error> {
self.handled.as_ref().map(|handled| &*handled.error)
}
/// Assert that the application rendered the response for an error of the given type.
///
/// The error may also be wrapped in context or kept as another error's `#[source]`.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # #[derive(Debug)] struct PaymentFailed;
/// # impl std::fmt::Display for PaymentFailed {
/// # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("The payment failed") }
/// # }
/// # impl std::error::Error for PaymentFailed {}
/// # async fn test(app: laravel::Application) {
/// app.post("/checkout").await.assert_status(402).assert_error::<PaymentFailed>();
/// # }
/// ```
///
/// # Panics
///
/// Panics when the response has no error, or an error of another type.
#[track_caller]
pub fn assert_error<E>(&self) -> &Self
where
E: std::error::Error + Send + Sync + 'static,
{
self.assert_error_where(|_: &E| true)
}
/// Assert that the application rendered the response for an error of the given type that
/// passes a check, such as a check on its fields.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # #[derive(Debug)] struct PaymentFailed { reason: String }
/// # impl std::fmt::Display for PaymentFailed {
/// # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("The payment failed") }
/// # }
/// # impl std::error::Error for PaymentFailed {}
/// # async fn test(app: laravel::Application) {
/// app.post("/checkout")
/// .await
/// .assert_error_where(|error: &PaymentFailed| error.reason == "insufficient funds");
/// # }
/// ```
///
/// # Panics
///
/// Panics when the response has no error, has an error of another type, or has an error that
/// fails the check.
#[track_caller]
pub fn assert_error_where<E>(&self, check: impl FnOnce(&E) -> bool) -> &Self
where
E: std::error::Error + Send + Sync + 'static,
{
let expected = std::any::type_name::<E>();
let found = self.error().map(find_error::<E>);
match found {
None => panic!(
"expected the response's error to be a `{expected}`, but it has no error\n\n{}",
self.summary()
),
Some(None) => panic!(
"expected the response's error to be a `{expected}`\n\n{}",
self.summary()
),
Some(Some(error)) => assert!(
check(error),
"expected the response's `{expected}` to pass the check, but it was {error:?}\n\n{}",
self.summary()
),
}
self
}
fn reported(&self) -> impl Iterator<Item = &Error> {
let handled = self.handled.iter().filter(|handled| handled.reported);
handled
.map(|handled| &*handled.error)
.chain(self.reports.iter().map(|error| &**error))
}
/// Assert that the application reported an error of the given type, which means it logged
/// the error and passed it to the application's reporters.
///
/// The error may have failed the request, or the application may have passed it to
/// [`report`](crate::report). As with [`assert_error`](Self::assert_error), the error may be
/// kept as another error's `#[source]`.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_reported<E: std::error::Error + Send + Sync + 'static>(&self) -> &Self {
let reported = self.reported().any(|error| find_error::<E>(error).is_some());
assert!(
reported,
"expected a `{}` to be reported, but it wasn't\n\n{}",
std::any::type_name::<E>(),
self.summary()
);
self
}
/// Assert that the application reported no error of the given type, such as an error it
/// handles as an expected outcome.
///
/// The application may have reported errors of other types.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_not_reported<E: std::error::Error + Send + Sync + 'static>(&self) -> &Self {
if let Some(error) = self.reported().find(|error| find_error::<E>(error).is_some()) {
panic!(
"expected no `{}` to be reported, but `{error}` was\n\n{}",
std::any::type_name::<E>(),
self.summary()
);
}
self
}
/// Assert that the application reported no errors.
///
/// # Panics
///
/// Panics when the assertion fails.
#[track_caller]
pub fn assert_nothing_reported(&self) -> &Self {
assert!(
self.reported().next().is_none(),
"expected nothing to be reported\n\n{}",
self.summary()
);
self
}
/// Assert that the body failed part way through, as a stream that returns an error does.
///
/// The client received the status, the headers, and the start of the body, which
/// [`text`](Self::text) returns, and then the response broke off.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// let response = app.get("/export").await;
///
/// response.assert_ok().assert_body_failed();
/// assert_eq!(response.text(), "id,name\n");
/// # }
/// ```
///
/// Without this assertion, a body that fails part way through fails the test.
///
/// # Panics
///
/// Panics when the body didn't fail.
#[track_caller]
pub fn assert_body_failed(&self) -> &Self {
assert!(
self.failed_body.is_some(),
"expected the body to fail part way\n\n{}",
self.summary()
);
self.asserted_failed_body.store(true, Ordering::Relaxed);
self
}
pub(super) fn summary(&self) -> String {
let mut summary = self.status_line();
let body = self.excerpt();
if !body.is_empty() {
summary.push('\n');
summary.push_str(&body);
}
self.diagnose(&mut summary);
summary
}
#[track_caller]
fn fail_json(&self, actual: &Value, message: std::fmt::Arguments<'_>) -> ! {
fail(actual, &self.outline(), message)
}
fn outline(&self) -> String {
let mut outline = self.status_line();
self.diagnose(&mut outline);
outline
}
fn status_line(&self) -> String {
match self.header("location").filter(|_| self.status.is_redirection()) {
Some(location) => format!("{}, redirecting to {location}", self.status),
None => self.status.to_string(),
}
}
fn excerpt(&self) -> String {
let is_html = self
.header("content-type")
.is_some_and(|content_type| content_type.starts_with("text/html"));
// A server error's page, such as the debug page, only renders the error the diagnosis names...
if is_html && self.status.is_server_error() && self.handled.is_some() {
return String::new();
}
let body = String::from_utf8_lossy(&self.body);
let body = match body.find("<body") {
Some(start) if is_html => &body[start..],
_ => &body,
};
if body.len() <= SUMMARY_LENGTH {
return body.to_owned();
}
format!("{}…", &body[..body.floor_char_boundary(SUMMARY_LENGTH)])
}
fn diagnose(&self, summary: &mut String) {
if let Some(error) = &self.failed_body {
let _ = write!(summary, "\n\nThe body failed part way: {error}");
}
if let Some(Handled { error, .. }) = &self.handled {
let _ = write!(summary, "\n\nThe error: {error} ({})", error.type_name());
for cause in error.chain().skip(1) {
let _ = write!(summary, "\n caused by: {cause}");
}
}
for error in &self.reports {
let _ = write!(summary, "\n\nReported: {error} ({})", error.type_name());
}
if let Some(errors) = self.session("errors").filter(|forms| has_errors(forms)) {
let _ = write!(summary, "\n\nThe session's validation errors:\n{}", pretty(errors));
}
}
}
impl Drop for TestResponse {
fn drop(&mut self) {
if let Some(error) = &self.failed_body
&& !*self.asserted_failed_body.get_mut()
&& !std::thread::panicking()
{
panic!(
"the response's body failed: {error}; use `assert_body_failed()` to test a body that fails part way\n\n{}\n\nat {}",
self.summary(),
self.requested_at
);
}
}
}
/// A value for a failure message, which names a missing value.
fn shown(value: Option<&Value>) -> String {
value.map_or_else(|| "missing".to_owned(), ToString::to_string)
}
fn has_errors(forms: &Value) -> bool {
forms.as_object().is_some_and(|forms| {
forms
.values()
.any(|errors| errors.as_object().is_some_and(|errors| !errors.is_empty()))
})
}
fn find(body: &str, text: &str) -> Option<(usize, usize)> {
let escaped = escape(text);
let found = [
body.find(&escaped).map(|at| (at, escaped.len())),
body.find(text).map(|at| (at, text.len())),
];
found.into_iter().flatten().min_by_key(|(at, _)| *at)
}
/// The file name in an `attachment` disposition. This is the exact `filename*` when the
/// disposition has one, or else its ASCII `filename`.
fn download_name(disposition: &str) -> Option<String> {
let mut quoted = false;
let mut escaped = false;
let mut parts = disposition
.split(|c| {
if escaped {
escaped = false;
} else if c == '"' {
quoted = !quoted;
} else if quoted && c == '\\' {
escaped = true;
}
c == ';' && !quoted
})
.map(str::trim);
if !parts.next()?.eq_ignore_ascii_case("attachment") {
return None;
}
let parameters: Vec<(&str, &str)> = parts.filter_map(|part| part.split_once('=')).collect();
let exact = parameters
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("filename*"))
.and_then(|(_, value)| value.strip_prefix("UTF-8''"))
.and_then(|name| percent_encoding::percent_decode_str(name).decode_utf8().ok());
if let Some(name) = exact {
return Some(name.into_owned());
}
parameters
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("filename"))
.map(|(_, value)| value.trim_matches('"').to_owned())
}