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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use std::borrow::Cow;
use std::future::ready;
use std::time::Duration;
use bytesbuf::BytesView;
use futures::Stream;
use futures::future::Either;
use http::header::CONTENT_TYPE;
use http::{HeaderMap, HeaderName, HeaderValue, Method, Response, Version};
use templated_uri::Uri;
use crate::http_utils::{CONTENT_TYPE_TEXT, try_content_length_header, try_header};
use crate::timeout::{BodyTimeout, ResponseTimeout};
use crate::{HttpBody, HttpBodyBuilder, HttpBodyOptions, HttpError, HttpRequest, HttpResponse, RequestHandler, Result};
/// A fluent builder for creating HTTP requests.
///
/// `HttpRequestBuilder` simplifies the process of building HTTP requests by providing a chainable API.
/// It handles setting headers and different body types, and offers convenient methods for common
/// request building patterns.
///
/// # Creating a Request Builder
///
/// There are two main ways to create an `HttpRequestBuilder`:
///
/// 1. **Without a request handler** - Use [`new`](Self::new) to create a builder that can only
/// build requests via [`build`](Self::build):
///
/// ```
/// # use http::Method;
/// # use http_extensions::{HttpBodyBuilder, HttpError, HttpRequest, HttpRequestBuilder};
/// # let builder = HttpBodyBuilder::new_fake();
/// let request_builder = HttpRequestBuilder::new(&builder);
/// let request: HttpRequest = request_builder
/// .method(Method::POST)
/// .uri("https://example.com/api")
/// .text("Hello world")
/// .build()?;
/// # Ok::<(), HttpError>(())
/// ```
///
/// 2. **With a request handler** - Use [`with_request_handler`](Self::with_request_handler) to create
/// a builder that can send requests directly using fetch methods like [`fetch`](Self::fetch) or
/// [`fetch_text`](Self::fetch_text):
///
/// ```
/// # use http_extensions::{HttpBodyBuilder, HttpError, HttpResponse, HttpResponseBuilder,
/// # HttpRequestBuilderExt, FakeHandler, HttpRequestBuilder};
/// # #[tokio::main]
/// # async fn main() -> Result<(), HttpError> {
/// # let bb = HttpBodyBuilder::new_fake();
/// # let handler = FakeHandler::from(HttpResponseBuilder::new(&bb).status(200).build()?);
/// # let request_handler = &handler;
/// # let builder = &bb;
/// let response: HttpResponse = HttpRequestBuilder::with_request_handler(request_handler, builder)
/// .get("https://example.com/api")
/// .fetch()
/// .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
#[must_use]
pub struct HttpRequestBuilder<'a, R = ()> {
body_builder: Cow<'a, HttpBodyBuilder>,
builder: http::request::Builder,
uri: Option<Result<Uri>>,
body: Option<Result<HttpBody>>,
content_type: Option<HeaderValue>,
request_handler: &'a R,
}
impl HttpRequestBuilder<'static> {
/// Creates a new request builder instance for testing.
///
/// This method provides a convenient way to create a `HttpRequestBuilder` for tests
/// without needing an existing body builder. The request builder is ready to be
/// configured with headers, method, URI, and body.
///
/// The `test-util` feature must be enabled to use this method.
///
/// # Examples
///
/// ```
/// # use http::Method;
/// # use http_extensions::{HttpBodyBuilder, HttpError, HttpRequest, HttpRequestBuilder};
/// let request = HttpRequestBuilder::new_fake()
/// .method(Method::GET)
/// .uri("https://example.com")
/// .build()?;
/// # Ok::<(), HttpError>(())
/// ```
#[cfg(any(feature = "test-util", test))]
pub fn new_fake() -> Self {
Self {
body_builder: Cow::Owned(HttpBodyBuilder::new_fake()),
builder: http::request::Builder::new(),
uri: None,
body: None,
content_type: None,
request_handler: &(),
}
}
}
impl<'a> HttpRequestBuilder<'a> {
/// Creates a new request builder instance with the given body builder.
pub fn new(builder: &'a HttpBodyBuilder) -> Self {
Self {
body_builder: Cow::Borrowed(builder),
builder: http::request::Builder::new(),
uri: None,
body: None,
content_type: None,
request_handler: &(),
}
}
}
impl<'a, R> HttpRequestBuilder<'a, R> {
/// Creates a new request builder instance with the given body builder and request handler.
pub fn with_request_handler(request_handler: &'a R, body_builder: &'a HttpBodyBuilder) -> Self {
Self {
builder: http::request::Builder::new(),
body_builder: Cow::Borrowed(body_builder),
uri: None,
body: None,
content_type: None,
request_handler,
}
}
}
impl<R> HttpRequestBuilder<'_, R> {
/// Sets the HTTP method for the request.
pub fn method(mut self, method: impl TryInto<http::Method, Error: Into<http::Error>>) -> Self {
self.builder = self.builder.method(method);
self
}
/// Sets the URI for the request.
pub fn uri(mut self, uri: impl TryInto<Uri, Error: Into<HttpError>>) -> Self {
self.uri = Some(uri.try_into().map_err(Into::into));
self
}
/// Creates a GET request to the specified URI.
pub fn get(self, uri: impl TryInto<Uri, Error: Into<HttpError>>) -> Self {
self.uri(uri).method(Method::GET)
}
/// Creates a POST request to the specified URI.
pub fn post(self, uri: impl TryInto<Uri, Error: Into<HttpError>>) -> Self {
self.uri(uri).method(Method::POST)
}
/// Creates a DELETE request to the specified URI.
pub fn delete(self, uri: impl TryInto<Uri, Error: Into<HttpError>>) -> Self {
self.uri(uri).method(Method::DELETE)
}
/// Creates a PUT request to the specified URI.
pub fn put(self, uri: impl TryInto<Uri, Error: Into<HttpError>>) -> Self {
self.uri(uri).method(Method::PUT)
}
/// Creates a PATCH request to the specified URI.
pub fn patch(self, uri: impl TryInto<Uri, Error: Into<HttpError>>) -> Self {
self.uri(uri).method(Method::PATCH)
}
/// Creates a HEAD request to the specified URI.
pub fn head(self, uri: impl TryInto<Uri, Error: Into<HttpError>>) -> Self {
self.uri(uri).method(Method::HEAD)
}
/// Provides mutable access to the request headers.
///
/// Use this when you need to manipulate headers directly.
/// For simple header addition, prefer using the [`header`](Self::header) method.
///
/// When the builder has errors, this method will return `None`.
pub fn headers_mut(&mut self) -> Option<&mut HeaderMap<HeaderValue>> {
self.builder.headers_mut()
}
/// Adds a header to the request.
///
/// This method accepts any type that can be converted to a [`HeaderName`] and [`HeaderValue`].
/// It returns `self` to enable method chaining.
///
/// # Performance
///
/// It's better to use pre-created `HeaderName` and `HeaderValue` instances to avoid
/// parsing overhead. This applies for values that are fixed and used multiple times.
pub fn header(
mut self,
key: impl TryInto<HeaderName, Error: Into<http::Error>>,
value: impl TryInto<HeaderValue, Error: Into<http::Error>>,
) -> Self {
self.builder = self.builder.header(key, value);
self
}
/// Sets the HTTP protocol version for the request.
pub fn version(mut self, version: Version) -> Self {
self.builder = self.builder.version(version);
self
}
/// Adds an extension to the request.
///
/// Extensions are type-mapped data that can be attached to requests for use by
/// middleware, handlers, or other parts of your application.
///
/// # Examples
///
/// ```
/// # use http_extensions::HttpRequestBuilder;
/// #[derive(Clone)]
/// struct RequestId(String);
///
/// let request = HttpRequestBuilder::new_fake()
/// .get("https://example.com/api/users/123")
/// .extension(RequestId("req-456".to_string()))
/// .build()
/// .unwrap();
/// ```
pub fn extension<T>(mut self, extension: T) -> Self
where
T: Clone + Send + Sync + 'static,
{
self.builder = self.builder.extension(extension);
self
}
/// Sets a response-level timeout for receiving the response.
///
/// This attaches a [`ResponseTimeout`] extension to the request, which middleware
/// or HTTP clients can use to enforce a maximum duration for receiving the response.
/// The timeout covers connection, sending the request, and receiving the response
/// headers. It does not cover reading data from the response body; use
/// [`body_timeout`](Self::body_timeout) for that.
pub fn response_timeout(self, duration: Duration) -> Self {
self.extension(ResponseTimeout::new(duration))
}
/// Sets a body-level idle timeout for streaming the response body.
///
/// This attaches a [`BodyTimeout`] extension to the request, which middleware
/// or HTTP clients can use to limit how long the client will wait between
/// chunks of body data. The timer resets every time the body makes progress,
/// so only idle periods (no data received) count toward the timeout.
pub fn body_timeout(self, duration: Duration) -> Self {
self.extension(BodyTimeout::new(duration))
}
/// Sets both the response timeout and the body timeout to the same duration.
///
/// This is a convenience method equivalent to calling both
/// [`response_timeout`](Self::response_timeout) and
/// [`body_timeout`](Self::body_timeout) with the same value.
pub fn timeout(self, duration: Duration) -> Self {
self.response_timeout(duration).body_timeout(duration)
}
/// Sets a plain text body for the request.
///
/// Automatically sets the `Content-Type` header to `text/plain`.
/// If the `Content-Type` header is already set, it will not override it.
///
/// This method always encodes the provided string as UTF-8.
pub fn text(mut self, data: impl AsRef<str>) -> Self {
let body = self.body_builder.text(data);
self.content_type = Some(CONTENT_TYPE_TEXT);
self.body(body)
}
/// Sets a byte sequence as the request body.
///
/// Use this when you need to send raw binary data.
/// Unlike [`text`](Self::text), this doesn't set a `Content-Type` header.
pub fn bytes(self, b: impl Into<BytesView>) -> Self {
let body = self.body_builder.bytes(b);
self.body(body)
}
/// Sets a JSON-serialized body for the request.
///
/// Takes any type that implements `serde::Serialize` and converts it to JSON with the following rules:
///
/// - The `Content-Type` header is set to `application/json` if not already set.
/// - The data is always encoded as UTF-8.
///
/// This method requires the `json` feature to be enabled.
///
/// # Errors
///
/// Returns an error if JSON serialization fails.
#[cfg(any(feature = "json", test))]
pub fn json<T: serde_core::ser::Serialize>(mut self, data: &T) -> Self {
let body = self.body_builder.json(data).map_err(HttpError::from);
self.content_type = Some(crate::http_utils::CONTENT_TYPE_JSON);
self.body_result(body)
}
/// Sets the request body directly.
///
/// Use this when you already have an `HttpBody` instance.
/// For most cases, prefer the more specific methods like
/// [`text`](Self::text) or [`bytes`](Self::bytes).
pub fn body(self, body: HttpBody) -> Self {
self.body_result(Ok(body))
}
/// Sets the request body from a result that might contain an error.
///
/// This is used internally by methods that might fail when creating the body.
fn body_result(mut self, body: Result<HttpBody>) -> Self {
self.body = Some(body);
self
}
/// Creates a request with the configured settings.
///
/// This method consumes the `HttpRequestBuilder` instance. It automatically sets
/// appropriate headers based on the body, such as `Content-Length` and `Content-Type`,
/// if they haven't been set already.
///
/// # Errors
///
/// Returns an error if:
/// - The request couldn't be built because of errors
/// - The URI is missing, or invalid
/// - Body processing failed
pub fn build(mut self) -> Result<HttpRequest> {
let body = self.body.take().unwrap_or_else(|| Ok(self.body_builder.empty()))?;
if let Some(length) = body.content_length() {
try_content_length_header(&mut self.builder, length);
}
if let Some(content_type) = self.content_type.take() {
try_header(&mut self.builder, CONTENT_TYPE, content_type);
}
let uri = self
.uri
.ok_or_else(|| HttpError::validation("URI is required when building the request"))??;
let path_and_query = uri.target_path_and_query().cloned();
let mut request = self.builder.uri(uri.into_http_uri()?).body(body)?;
if let Some(path_and_query) = path_and_query {
request.extensions_mut().insert(path_and_query);
}
Ok(request)
}
/// Sets a custom body implementation as the request body.
///
/// This is useful when you have a custom body implementation that implements
/// the `http_body::Body` trait and want to use it with the `HttpRequestBuilder`.
pub fn custom_body<B>(self, body: B) -> Self
where
B: http_body::Body<Data = BytesView, Error: Into<HttpError>> + Send + 'static,
{
let body = self.body_builder.body(body, &HttpBodyOptions::default());
self.body(body)
}
/// Sets a streaming body for the request.
///
/// This is a convenience wrapper around [`custom_body`](Self::custom_body) that accepts
/// a [`Stream`] of [`BytesView`] chunks. It avoids the need to manually wrap
/// the stream in a [`StreamBody`][http_body_util::StreamBody].
///
/// Note that streaming bodies do not have a known content length, so the
/// `Content-Length` header will not be set automatically.
///
/// # Examples
///
/// ```
/// # use http_extensions::{HttpBodyBuilder, HttpError, HttpRequestBuilder};
/// # use bytesbuf::BytesView;
/// # let body_builder = HttpBodyBuilder::new_fake();
/// let chunks = vec![
/// Ok(BytesView::copied_from_slice(b"hello ", &body_builder)),
/// Ok(BytesView::copied_from_slice(b"world", &body_builder)),
/// ];
/// let request = HttpRequestBuilder::new(&body_builder)
/// .post("https://example.com/upload")
/// .stream(futures::stream::iter(chunks))
/// .build()?;
/// # Ok::<(), HttpError>(())
/// ```
pub fn stream<S>(self, stream: S) -> Self
where
S: Stream<Item = Result<BytesView>> + Send + 'static,
{
let body = self.body_builder.stream(stream, &HttpBodyOptions::default());
self.body(body)
}
}
/// Extension methods for sending requests built with `HttpRequestBuilder`.
impl<R: RequestHandler> HttpRequestBuilder<'_, R> {
/// Sends the request and fetches the response.
///
/// Calling this method consumes the `HttpRequestBuilder` instance. It automatically sets
/// appropriate headers based on the body, such as `Content-Length` and `Content-Type`,
/// if they haven't been set already.
///
/// # Examples
///
/// ```
/// # use http_extensions::{HttpError, HttpRequestBuilder, HttpResponse, HttpResponseBuilder,
/// # HttpBodyBuilder, FakeHandler, HttpRequestBuilderExt};
/// # #[tokio::main]
/// # async fn main() -> Result<(), HttpError> {
/// # let bb = HttpBodyBuilder::new_fake();
/// # let handler = FakeHandler::from(HttpResponseBuilder::new(&bb).status(200).build()?);
/// # let request_builder = handler.request_builder();
/// let response: HttpResponse = request_builder.get("https://example.com").fetch().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The request couldn't be built because of errors
/// - The network request failed
/// - Body processing failed
pub fn fetch(self) -> impl Future<Output = Result<HttpResponse>> + Send {
let handler = self.request_handler;
match self.build() {
Ok(request) => Either::Left(handler.execute(request)),
Err(err) => Either::Right(ready(Err(err))),
}
}
/// Sends the request and fetches the fully buffered response.
///
/// Unlike [`fetch`](Self::fetch), this method reads the entire response body into
/// memory before returning. This is useful when you need to process the entire
/// response at once.
///
/// Calling this method consumes the [`HttpRequestBuilder`] instance. It automatically sets
/// appropriate headers based on the request body, such as `Content-Length` and `Content-Type`,
/// if they haven't been set already.
///
/// # Examples
///
/// ```
/// # use http_extensions::{HttpError, HttpRequestBuilder, HttpResponse, HttpResponseBuilder,
/// # HttpBodyBuilder, FakeHandler, HttpRequestBuilderExt};
/// # #[tokio::main]
/// # async fn main() -> Result<(), HttpError> {
/// # let bb = HttpBodyBuilder::new_fake();
/// # let handler = FakeHandler::from(HttpResponseBuilder::new(&bb).status(200).build()?);
/// # let request_builder = handler.request_builder();
/// let response: HttpResponse = request_builder.get("https://example.com").fetch_buffered().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The request couldn't be built because of errors
/// - The network request failed
/// - Body processing failed
/// - The response content exceeds the size limit (default is 2 GB)
pub async fn fetch_buffered(self) -> Result<HttpResponse> {
let response = self.fetch().await?;
let (parts, body) = response.into_parts();
let body = body.into_buffered().await?;
Ok(HttpResponse::from_parts(parts, body))
}
/// Sends the request and fetches the response as text.
///
/// Calling this method consumes the [`HttpRequestBuilder`] instance. It automatically sets
/// appropriate headers based on the request body, such as `Content-Length` and `Content-Type`,
/// if they haven't been set already.
///
/// # Body Processing
///
/// The response body is processed as UTF-8 text. If the response body is not valid UTF-8,
/// this method will return an error. This method returns a [`Response<String>`], where the body
/// is the text content of the response. This preserves all the information about the response.
///
/// # Examples
///
/// ```
/// # use http::Response;
/// # use http_extensions::{HttpError, HttpRequestBuilder, HttpResponse, HttpResponseBuilder,
/// # HttpBodyBuilder, FakeHandler, HttpRequestBuilderExt};
/// # #[tokio::main]
/// # async fn main() -> Result<(), HttpError> {
/// # let bb = HttpBodyBuilder::new_fake();
/// # let handler = FakeHandler::from(HttpResponseBuilder::new(&bb).status(200).text("hello").build()?);
/// # let request_builder = handler.request_builder();
/// let response: Response<String> = request_builder.get("https://example.com").fetch_text().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The request couldn't be built because of errors
/// - The network request failed
/// - Body processing failed
pub async fn fetch_text(self) -> Result<Response<String>> {
let (parts, body) = self.fetch().await?.into_parts();
let body = body.into_text().await?;
Ok(Response::from_parts(parts, body))
}
/// Sends the request and fetches the response body as a byte sequence.
///
/// This is useful when working with binary data or when you need
/// low-level access to the response bytes.
///
/// Calling this method consumes the [`HttpRequestBuilder`] instance. It automatically sets
/// appropriate headers based on the request body, such as `Content-Length` and `Content-Type`,
/// if they haven't been set already.
///
/// # Body Processing
///
/// The response body is processed as a sequence of bytes. This method returns a [`Response<BytesView>`],
/// where the body is the raw byte content of the response. This preserves all the information about the response.
///
/// # Examples
///
/// ```
/// # use http::Response;
/// # use http_extensions::{HttpError, HttpRequestBuilder, HttpResponse, HttpResponseBuilder,
/// # HttpBodyBuilder, FakeHandler, HttpRequestBuilderExt};
/// #
/// # use bytesbuf::BytesView;
/// # #[tokio::main]
/// # async fn main() -> Result<(), HttpError> {
/// # let bb = HttpBodyBuilder::new_fake();
/// # let handler = FakeHandler::from(HttpResponseBuilder::new(&bb).status(200).build()?);
/// # let request_builder = handler.request_builder();
/// let response: Response<BytesView> = request_builder.get("https://example.com").fetch_bytes().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The request couldn't be built because of errors
/// - The network request failed
/// - Body processing failed
pub async fn fetch_bytes(self) -> Result<Response<BytesView>> {
let (parts, body) = self.fetch().await?.into_parts();
let body = body.into_bytes().await?;
Ok(Response::from_parts(parts, body))
}
/// Sends the request and deserializes the response body as JSON.
///
/// Handles the complete request-response cycle and JSON deserialization. Consumes the
/// [`HttpRequestBuilder`] and automatically sets headers like `Content-Length` and `Content-Type`.
/// Use this when you need owned data that can outlive the response.
///
/// This method requires the `json` feature to be enabled.
///
/// # Examples
///
/// ```
/// # use http::Response;
/// # use serde::Deserialize;
/// # use http_extensions::{HttpError, HttpRequestBuilder, HttpResponseBuilder,
/// # HttpBodyBuilder, FakeHandler, HttpRequestBuilderExt};
/// #
/// # #[derive(Deserialize)]
/// # struct User { id: u32, name: String }
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), HttpError> {
/// # let bb = HttpBodyBuilder::new_fake();
/// # let handler = FakeHandler::from(
/// # HttpResponseBuilder::new(&bb).status(200).text(r#"{"id":42,"name":"Alice"}"#).build()?
/// # );
/// # let request_builder = handler.request_builder();
/// let response: Response<User> = request_builder
/// .get("https://example.com/users/42")
/// .fetch_json_owned::<User>()
/// .await?;
///
/// println!("User: {}", response.body().name);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The request couldn't be built
/// - The network request failed
/// - The response body isn't valid UTF-8
/// - JSON deserialization failed
#[cfg(any(feature = "json", test))]
pub async fn fetch_json_owned<J: serde_core::de::DeserializeOwned>(self) -> Result<Response<J>> {
let (parts, body) = self.fetch().await?.into_parts();
let body = body.into_json_owned().await?;
Ok(Response::from_parts(parts, body))
}
/// Sends the request and deserializes the response body as JSON with optional borrowing.
///
/// Handles the complete request-response cycle and JSON deserialization. Consumes the
/// [`HttpRequestBuilder`] and automatically sets headers like `Content-Length` and `Content-Type`.
/// Returns a [`Json<T>`][crate::Json] wrapper that can borrow from the underlying response data.
///
/// This method requires the `json` feature to be enabled.
///
/// # Note
///
/// This method only prepares the data for deserialization by downloading all content
/// to memory. The actual JSON deserialization happens lazily when you access the data
/// through the [`Json<T>`][crate::Json] wrapper.
///
/// # Examples
///
/// ```
/// # use serde::Deserialize;
/// # use std::borrow::Cow;
/// # use http_extensions::{HttpError, HttpRequestBuilder, Json, HttpResponseBuilder,
/// # HttpBodyBuilder, FakeHandler, HttpRequestBuilderExt};
/// #
/// # #[derive(Deserialize)]
/// # struct User<'a> { id: u32, #[serde(borrow)] name: Cow<'a, str> }
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), HttpError> {
/// # let bb = HttpBodyBuilder::new_fake();
/// # let handler = FakeHandler::from(
/// # HttpResponseBuilder::new(&bb).status(200).text(r#"{"id":42,"name":"Alice"}"#).build()?
/// # );
/// # let request_builder = handler.request_builder();
/// let mut response: Json<User> = request_builder
/// .get("https://example.com/users/42")
/// .fetch_json::<User>()
/// .await?
/// .into_body();
///
/// let user: User = response.read()?;
/// println!("User: {}", user.name);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The request couldn't be built
/// - The network request failed
/// - The response body isn't valid UTF-8
#[cfg(any(feature = "json", test))]
pub async fn fetch_json<'de, J: serde_core::de::Deserialize<'de>>(self) -> Result<Response<crate::Json<J>>> {
let (parts, body) = self.fetch().await?.into_parts();
let body = body.into_json().await?;
Ok(Response::from_parts(parts, body))
}
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use futures::executor::block_on;
use http::StatusCode;
use http::header::CONTENT_LENGTH;
use ohno::ErrorExt;
use serde::{Deserialize, Serialize};
use super::*;
use crate::http_request_builder_ext::HttpRequestBuilderExt;
use crate::testing::{SingleChunkBody, create_stream_body_from_chunks};
use crate::{FakeHandler, HeaderMapExt, HttpResponseBuilder, RequestExt};
#[test]
fn new_with_borrowed_builder() {
let body_builder = HttpBodyBuilder::new_fake();
let request_builder = HttpRequestBuilder::new(&body_builder);
let request = request_builder
.method(Method::GET)
.uri("https://example.com")
.text("test")
.build()
.unwrap();
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "test");
}
#[test]
fn json_body_ok() {
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.json(&JsonData { id: 42 })
.build()
.unwrap();
assert_eq!(request.headers().get_value_or(CONTENT_LENGTH, 0), 9);
assert_eq!(request.headers().get_str_value_or(CONTENT_TYPE, ""), "application/json");
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "{\"id\":42}");
}
#[test]
fn json_does_not_override_existing_content_type() {
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.header(CONTENT_TYPE, "application/custom")
.json(&JsonData { id: 42 })
.build()
.unwrap();
assert_eq!(request.headers().get_str_value_or(CONTENT_TYPE, ""), "application/custom");
}
#[test]
fn text_body_ok() {
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.text("hello")
.build()
.unwrap();
assert_eq!(request.headers().get_value_or(CONTENT_LENGTH, 0), 5);
assert_eq!(request.headers().get_str_value_or(CONTENT_TYPE, ""), "text/plain");
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "hello");
}
#[test]
fn text_does_not_override_existing_content_type() {
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.header(CONTENT_TYPE, "text/custom")
.text("hello")
.build()
.unwrap();
assert_eq!(request.headers().get_str_value_or(CONTENT_TYPE, ""), "text/custom");
}
#[test]
fn method_setting() {
let request = HttpRequestBuilder::new_fake()
.method(Method::PUT)
.uri("https://example.com")
.text("hello")
.build()
.unwrap();
assert_eq!(request.method(), Method::PUT);
}
#[test]
fn version_setting() {
let request = HttpRequestBuilder::new_fake()
.method(Method::GET)
.uri("https://example.com")
.version(Version::HTTP_2)
.text("hello")
.build()
.unwrap();
assert_eq!(request.version(), Version::HTTP_2);
}
#[test]
fn header_with_string_key_value() {
let request = HttpRequestBuilder::new_fake()
.method(Method::GET)
.uri("https://example.com")
.header("X-Custom-Header", "custom-value")
.text("hello")
.build()
.unwrap();
assert_eq!(request.headers().get("X-Custom-Header").unwrap(), "custom-value");
}
#[test]
fn header_with_header_name_value() {
let header_name = HeaderName::from_static("x-test-header");
let header_value = HeaderValue::from_static("test-value");
let request = HttpRequestBuilder::new_fake()
.method(Method::GET)
.uri("https://example.com")
.header(header_name.clone(), header_value.clone())
.text("hello")
.build()
.unwrap();
assert_eq!(request.headers().get(&header_name).unwrap(), &header_value);
}
#[test]
fn headers_mut_access() {
let mut request_builder = HttpRequestBuilder::new_fake();
// Test successful access to headers_mut
if let Some(headers) = request_builder.headers_mut() {
headers.insert("X-Mut-Header", "mut-value".parse().unwrap());
}
let request = request_builder
.method(Method::GET)
.uri("https://example.com")
.text("hello")
.build()
.unwrap();
assert_eq!(request.headers().get("X-Mut-Header").unwrap(), "mut-value");
}
#[test]
fn multiple_headers() {
let request = HttpRequestBuilder::new_fake()
.method(Method::GET)
.uri("https://example.com")
.header("X-Header-1", "value1")
.header("X-Header-2", "value2")
.header("X-Header-3", "value3")
.text("hello")
.build()
.unwrap();
assert_eq!(request.headers().get("X-Header-1").unwrap(), "value1");
assert_eq!(request.headers().get("X-Header-2").unwrap(), "value2");
assert_eq!(request.headers().get("X-Header-3").unwrap(), "value3");
}
#[test]
fn direct_body_setting() {
let body = HttpBodyBuilder::new_fake().text("direct body");
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.body(body)
.build()
.unwrap();
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "direct body");
}
#[test]
fn chained_operations() {
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.version(Version::HTTP_11)
.header("X-Custom", "value")
.header(CONTENT_TYPE, "application/custom")
.text("chained")
.build()
.unwrap();
assert_eq!(request.method(), Method::POST);
assert_eq!(request.version(), Version::HTTP_11);
assert_eq!(request.headers().get("X-Custom").unwrap(), "value");
assert_eq!(request.headers().get(CONTENT_TYPE).unwrap(), "application/custom");
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "chained");
}
#[test]
fn custom_body_functionality() {
let builder = HttpBodyBuilder::new_fake();
let body = create_stream_body_from_chunks(&builder, &[b"custom", b" body", b" content"], &HttpBodyOptions::default());
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.body(body)
.build()
.unwrap();
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "custom body content");
}
#[test]
fn custom_body_sets_body_from_custom_body_impl() {
let builder = HttpBodyBuilder::new_fake();
let request = HttpRequestBuilder::new_fake()
.post("https://example.com/upload")
.custom_body(SingleChunkBody::new(BytesView::copied_from_slice(b"external payload", &builder)))
.build()
.unwrap();
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "external payload");
}
#[test]
fn stream_sets_body_from_chunks() {
let builder = HttpBodyBuilder::new_fake();
let chunks: Vec<crate::Result<BytesView>> = vec![
Ok(BytesView::copied_from_slice(b"hello ", &builder)),
Ok(BytesView::copied_from_slice(b"streaming ", &builder)),
Ok(BytesView::copied_from_slice(b"world", &builder)),
];
let request = HttpRequestBuilder::new_fake()
.post("https://example.com/upload")
.stream(futures::stream::iter(chunks))
.build()
.unwrap();
// Streams don't have a known content length
assert!(request.headers().get(CONTENT_LENGTH).is_none());
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "hello streaming world");
}
#[test]
fn bytes_body_ok() {
let builder = HttpBodyBuilder::new_fake();
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.bytes(BytesView::copied_from_slice(b"hello", &builder))
.build()
.unwrap();
assert_eq!(request.headers().get_value_or(CONTENT_LENGTH, 0), 5);
assert!(request.headers().get(CONTENT_TYPE).is_none());
assert_eq!(block_on(request.into_body().into_bytes()).unwrap(), b"hello");
}
#[test]
fn empty_body_ok() {
let request = HttpRequestBuilder::new_fake()
.method(Method::GET)
.uri("https://example.com")
.build()
.unwrap();
assert_eq!(request.headers().get_value_or(CONTENT_LENGTH, -1), 0);
assert!(request.headers().get(CONTENT_TYPE).is_none());
assert_eq!(block_on(request.into_body().into_bytes()).unwrap().len(), 0,);
}
#[test]
fn uri_required() {
HttpRequestBuilder::new_fake()
.method(Method::GET)
.text("hello")
.build()
.unwrap_err();
}
#[derive(Serialize, Deserialize, Debug)]
struct JsonData {
id: u32,
}
#[derive(Deserialize, Debug, PartialEq)]
struct BorrowedJsonData<'a> {
id: u32,
#[serde(borrow)]
name: Cow<'a, str>,
#[serde(borrow)]
description: Cow<'a, str>,
}
#[test]
fn headers_mut_returns_none_on_error() {
let mut request_builder = HttpRequestBuilder::new_fake();
// Force an error in the builder by adding an invalid header
request_builder = request_builder.header("invalid\0header", "value");
// headers_mut should return None when builder has errors
assert!(request_builder.headers_mut().is_none());
}
#[test]
fn header_multiple_calls() {
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.header(CONTENT_TYPE, "application/custom1")
.header(CONTENT_TYPE, "application/custom2")
.build()
.unwrap();
let headers: Vec<_> = request.headers().get_all(CONTENT_TYPE).iter().collect();
assert_eq!(headers.len(), 2);
assert_eq!(headers[0].to_str().unwrap(), "application/custom1");
assert_eq!(headers[1].to_str().unwrap(), "application/custom2");
}
#[test]
fn content_type_preservation() {
let request = HttpRequestBuilder::new_fake()
.method(Method::POST)
.uri("https://example.com")
.json(&JsonData { id: 42 })
.build()
.unwrap();
// Both Content-Length and Content-Type should be set
assert_eq!(request.headers().get_value_or(CONTENT_LENGTH, 0), 9);
assert_eq!(request.headers().get_str_value_or(CONTENT_TYPE, ""), "application/json");
}
#[test]
fn request_build_error() {
// Create an invalid header that will cause builder to fail
let result = HttpRequestBuilder::new_fake()
.method(Method::GET)
.uri("https://example.com")
.header("invalid\0header", "value")
.build();
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.message(), "invalid HTTP header name");
}
#[test]
fn fetch_json_borrowed_with_escaped_strings() {
// JSON with escaped characters that should be properly deserialized into Cow
let json_response = r#"{"id":123,"name":"John Doe","description":"A person with \"special\" characters: \n\t\\"}"#;
let client = FakeHandler::from_sync_handler(move |_request| {
let json_response = json_response.to_string();
HttpResponseBuilder::new_fake()
.status(StatusCode::OK)
.header(CONTENT_TYPE, "application/json")
.text(json_response)
.build()
});
let mut response = block_on(
client
.request_builder()
.uri("https://example.com/user")
.method(Method::GET)
.fetch_json::<BorrowedJsonData>(),
)
.unwrap()
.into_body();
let json_data = response.read().unwrap();
// Verify the basic fields
assert_eq!(json_data.id, 123);
assert_eq!(json_data.name, "John Doe");
// Verify that escaped characters are properly decoded
let expected_description = "A person with \"special\" characters: \n\t\\";
assert_eq!(json_data.description, expected_description);
assert!(matches!(json_data.name, Cow::Borrowed(_)));
assert!(matches!(json_data.description, Cow::Owned(_)));
}
#[test]
fn json_deserialization_error() {
let client = FakeHandler::from_sync_handler(|_request| {
HttpResponseBuilder::new_fake()
.status(StatusCode::OK)
.text("corrupted json")
.build()
});
let result = block_on(
client
.request_builder()
.uri("https://example.com")
.method(Method::GET)
.fetch_json_owned::<JsonData>(),
);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.message().contains("JSON deserialization error"));
}
#[test]
fn fetch_ok() {
let client =
FakeHandler::from_sync_handler(|_request| HttpResponseBuilder::new_fake().status(StatusCode::OK).text("response body").build());
let response = block_on(client.request_builder().uri("https://example.com").method(Method::GET).fetch()).unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(block_on(response.into_body().into_text()).unwrap(), "response body");
}
#[test]
fn fetch_buffered_ok() {
let client = FakeHandler::from_sync_handler(|_request| {
HttpResponseBuilder::new_fake()
.status(StatusCode::OK)
.text("buffered response")
.build()
});
let response = block_on(
client
.request_builder()
.uri("https://example.com")
.method(Method::GET)
.fetch_buffered(),
)
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(block_on(response.into_body().into_text()).unwrap(), "buffered response");
}
#[test]
fn fetch_text_ok() {
let client =
FakeHandler::from_sync_handler(|_request| HttpResponseBuilder::new_fake().status(StatusCode::OK).text("text response").build());
let response = block_on(client.request_builder().uri("https://example.com").method(Method::GET).fetch_text()).unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_body(), "text response");
}
#[test]
fn fetch_bytes_ok() {
let client = FakeHandler::from_sync_handler(|_request| {
HttpResponseBuilder::new_fake()
.status(StatusCode::OK)
.bytes(BytesView::copied_from_slice(b"BytesView response", &HttpBodyBuilder::new_fake()))
.build()
});
let response = block_on(
client
.request_builder()
.uri("https://example.com")
.method(Method::GET)
.fetch_bytes(),
)
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_body(), b"BytesView response");
}
#[test]
fn fetch_json_ok() {
let client = FakeHandler::from_sync_handler(|_request| {
HttpResponseBuilder::new_fake()
.status(StatusCode::OK)
.json(&JsonData { id: 42 })
.build()
});
let response = block_on(
client
.request_builder()
.uri("https://example.com")
.method(Method::GET)
.fetch_json::<JsonData>(),
)
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let json_data = response.into_body().read().unwrap();
assert_eq!(json_data.id, 42);
}
#[test]
fn fetch_json_owned_ok() {
let client = FakeHandler::from_sync_handler(|_request| {
HttpResponseBuilder::new_fake()
.status(StatusCode::OK)
.json(&JsonData { id: 123 })
.build()
});
let response = block_on(
client
.request_builder()
.uri("https://example.com")
.method(Method::GET)
.fetch_json_owned::<JsonData>(),
)
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_body().id, 123);
}
#[test]
fn fetch_with_request_validation() {
let client = FakeHandler::from_async_handler(|request| {
async move {
// Validate the request that was sent
assert_eq!(request.method(), Method::POST);
assert_eq!(request.headers().get_str_value_or("x-test", ""), "chained");
assert_eq!(request.version(), http::Version::HTTP_2);
assert_eq!(request.into_body().into_text().await.unwrap(), "chained body");
HttpResponseBuilder::new_fake().status(StatusCode::CREATED).build()
}
});
let response = block_on(
client
.request_builder()
.uri("https://example.com")
.method(Method::POST)
.header("x-test", "chained")
.version(http::Version::HTTP_2)
.text("chained body")
.fetch(),
)
.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
}
#[test]
fn fetch_with_empty_body() {
let client = FakeHandler::from_async_handler(|request| async move {
assert_eq!(request.headers().get_value_or(CONTENT_LENGTH, -1), 0);
assert!(request.headers().get(CONTENT_TYPE).is_none());
let body_len = request.into_body().into_bytes().await.unwrap().len();
assert_eq!(body_len, 0);
HttpResponseBuilder::new_fake().status(StatusCode::OK).build()
});
block_on(client.request_builder().uri("https://example.com").method(Method::GET).fetch()).unwrap();
}
#[test]
fn fetch_with_json_body_validation() {
let client = FakeHandler::from_sync_handler(|request| {
// Both Content-Length and Content-Type should be set
assert_eq!(request.headers().get_value_or(CONTENT_LENGTH, 0), 9);
assert_eq!(request.headers().get_str_value_or(CONTENT_TYPE, ""), "application/json");
HttpResponseBuilder::new_fake().status(StatusCode::OK).build()
});
block_on(
client
.request_builder()
.uri("https://example.com")
.method(Method::POST)
.json(&JsonData { id: 42 })
.fetch(),
)
.unwrap();
}
#[test]
fn fetch_with_multiple_headers() {
let client = FakeHandler::from_sync_handler(|request| {
assert_eq!(request.headers().get_str_value_or("x-first", ""), "first");
assert_eq!(request.headers().get_str_value_or("x-second", ""), "second");
assert_eq!(request.version(), http::Version::HTTP_11);
HttpResponseBuilder::new_fake().status(StatusCode::OK).build()
});
block_on(
client
.request_builder()
.uri("https://example.com")
.method(Method::GET)
.header("x-first", "first")
.header("x-second", "second")
.version(http::Version::HTTP_11)
.fetch(),
)
.unwrap();
}
#[test]
fn get_method_sets_uri_and_method() {
let request = HttpRequestBuilder::new_fake().get("https://example.com/api").build().unwrap();
assert_eq!(request.method(), Method::GET);
assert_eq!(request.uri(), "https://example.com/api");
}
#[test]
fn post_method_sets_uri_and_method() {
let request = HttpRequestBuilder::new_fake()
.post("https://example.com/api")
.text("data")
.build()
.unwrap();
assert_eq!(request.method(), Method::POST);
assert_eq!(request.uri(), "https://example.com/api");
}
#[test]
fn delete_method_sets_uri_and_method() {
let request = HttpRequestBuilder::new_fake()
.delete("https://example.com/api/123")
.build()
.unwrap();
assert_eq!(request.method(), Method::DELETE);
assert_eq!(request.uri(), "https://example.com/api/123");
}
#[test]
fn put_method_sets_uri_and_method() {
let request = HttpRequestBuilder::new_fake()
.put("https://example.com/api/123")
.text("updated data")
.build()
.unwrap();
assert_eq!(request.method(), Method::PUT);
assert_eq!(request.uri(), "https://example.com/api/123");
}
#[test]
fn patch_method_sets_uri_and_method() {
let request = HttpRequestBuilder::new_fake()
.patch("https://example.com/api/123")
.text("partial update")
.build()
.unwrap();
assert_eq!(request.method(), Method::PATCH);
assert_eq!(request.uri(), "https://example.com/api/123");
}
#[test]
fn head_method_sets_uri_and_method() {
let request = HttpRequestBuilder::new_fake().head("https://example.com/api").build().unwrap();
assert_eq!(request.method(), Method::HEAD);
assert_eq!(request.uri(), "https://example.com/api");
assert_eq!(request.path_and_query().unwrap().to_uri_string(), "/api");
}
#[test]
fn method_convenience_functions_can_be_chained() {
let request = HttpRequestBuilder::new_fake()
.post("https://example.com/api")
.header("Authorization", "Bearer token")
.json(&JsonData { id: 42 })
.build()
.unwrap();
assert_eq!(request.method(), Method::POST);
assert_eq!(request.uri(), "https://example.com/api");
assert_eq!(request.headers().get_str_value_or("Authorization", ""), "Bearer token");
assert_eq!(block_on(request.into_body().into_text()).unwrap(), "{\"id\":42}");
}
#[test]
fn method_convenience_with_fetch() {
let client = FakeHandler::from_sync_handler(|request| {
assert_eq!(request.method(), Method::POST);
assert_eq!(request.uri(), "https://example.com/api");
HttpResponseBuilder::new_fake().status(StatusCode::CREATED).build()
});
let response = block_on(client.request_builder().post("https://example.com/api").text("test data").fetch()).unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
}
#[test]
fn extension_attaches_to_request() {
use crate::UrlTemplateLabel;
let request = HttpRequestBuilder::new_fake()
.get("https://example.com/api/users/123")
.extension(UrlTemplateLabel::new("/api/users/{id}"))
.build()
.unwrap();
let label = request.extensions().get::<UrlTemplateLabel>().expect("extension should be present");
assert_eq!(label.as_str(), "/api/users/{id}");
}
#[test]
fn extension_with_custom_type() {
#[derive(Clone, Debug, PartialEq)]
struct RequestId(String);
let request = HttpRequestBuilder::new_fake()
.get("https://example.com/api")
.extension(RequestId("req-123".to_string()))
.build()
.unwrap();
let id = request.extensions().get::<RequestId>().expect("extension should be present");
assert_eq!(id.0, "req-123");
}
#[test]
fn timeout_sets_both_response_and_body_timeout() {
use std::time::Duration;
use crate::timeout::{BodyTimeout, ResponseTimeout};
let request = HttpRequestBuilder::new_fake()
.get("https://example.com/api")
.timeout(Duration::from_secs(30))
.build()
.unwrap();
let response_timeout = request
.extensions()
.get::<ResponseTimeout>()
.expect("response timeout extension should be present");
assert_eq!(response_timeout.duration(), Duration::from_secs(30));
let body_timeout = request
.extensions()
.get::<BodyTimeout>()
.expect("body timeout extension should be present");
assert_eq!(body_timeout.duration(), Duration::from_secs(30));
}
#[test]
fn response_timeout_attaches_to_request() {
use std::time::Duration;
use crate::timeout::ResponseTimeout;
let request = HttpRequestBuilder::new_fake()
.get("https://example.com/api")
.response_timeout(Duration::from_secs(15))
.build()
.unwrap();
let timeout = request
.extensions()
.get::<ResponseTimeout>()
.expect("response timeout extension should be present");
assert_eq!(timeout.duration(), Duration::from_secs(15));
}
#[test]
fn body_timeout_attaches_to_request() {
use std::time::Duration;
use crate::timeout::BodyTimeout;
let request = HttpRequestBuilder::new_fake()
.get("https://example.com/api")
.body_timeout(Duration::from_secs(60))
.build()
.unwrap();
let timeout = request
.extensions()
.get::<BodyTimeout>()
.expect("body timeout extension should be present");
assert_eq!(timeout.duration(), Duration::from_secs(60));
}
#[test]
fn fetch_returns_error_when_build_fails() {
let handler = FakeHandler::from_sync_handler(|_request| {
HttpResponseBuilder::new_fake()
.status(StatusCode::OK)
.text("should not reach")
.build()
});
let result = block_on(handler.request_builder().method(Method::GET).fetch());
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
err.message().contains("URI is required"),
"expected 'URI is required' but got: {}",
err.message()
);
}
}