frakt 0.1.0

Ergonomic platform HTTP client bindings for Rust
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
//! Integration tests for frakt

use std::time::Duration;

use frakt::{BackendType, Client, Result, backend};

fn backend() -> BackendType {
    match std::env::var("BACKEND").as_deref() {
        #[cfg(target_vendor = "apple")]
        Ok("foundation") => BackendType::Foundation,
        Ok("reqwest") => BackendType::Reqwest,
        #[cfg(windows)]
        Ok("windows") => BackendType::Windows,
        Ok(x) => panic!("Unknown BACKEND env var value: {:?}", x),
        Err(_) => panic!("Please set BACKEND env var to either 'foundation' or 'reqwest'"),
    }
}

#[tokio::test]
async fn test_basic_get_request() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let response = client.get("https://httpbin.org/get")?.send().await?;

    assert_eq!(response.status(), 200);

    let text = response.text().await?;
    println!("Response text: {}", text);
    assert!(text.contains("httpbin.org"));

    Ok(())
}

#[tokio::test]
async fn test_post_with_json() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let json_data = r#"{"test": "data", "number": 42}"#;

    let response = client
        .post("https://httpbin.org/post")?
        .header("Content-Type", "application/json")?
        .body(json_data)
        .send()
        .await?;

    assert_eq!(response.status(), 200);

    let text = response.text().await?;
    // Verify the JSON was properly echoed back
    assert!(text.contains("\"test\": \"data\""));
    assert!(text.contains("\"number\": 42"));
    assert!(text.contains("\"json\": {"));

    // Verify it was sent as POST
    assert!(text.contains("\"url\": \"https://httpbin.org/post\""));

    Ok(())
}

#[tokio::test]
async fn test_headers() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .header("X-Custom-Header", "test-value")?
        .build()?;

    let response = client
        .get("https://httpbin.org/headers")?
        .header("X-Request-Header", "request-value")?
        .send()
        .await?;

    assert_eq!(response.status(), 200);

    let text = response.text().await?;
    assert!(text.contains("X-Custom-Header"));
    assert!(text.contains("test-value"));
    assert!(text.contains("X-Request-Header"));
    assert!(text.contains("request-value"));

    Ok(())
}

#[tokio::test]
async fn test_basic_auth() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let response = client
        .get("https://httpbin.org/basic-auth/testuser/testpass")?
        .auth(frakt::Auth::Basic {
            username: "testuser".to_string(),
            password: "testpass".to_string(),
        })
        .send()
        .await?;

    assert_eq!(response.status(), 200);

    let text = response.text().await?;
    assert!(text.contains("authenticated"));

    Ok(())
}

#[tokio::test]
async fn test_bearer_auth() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let response = client
        .get("https://httpbin.org/bearer")?
        .auth(frakt::Auth::Bearer {
            token: "test-token".to_string(),
        })
        .send()
        .await?;

    assert_eq!(response.status(), 200);

    let text = response.text().await?;
    assert!(text.contains("authenticated"));
    assert!(text.contains("test-token"));

    Ok(())
}

#[tokio::test]
async fn test_cookie_jar() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .use_cookies(true)
        .build()?;

    // Set a cookie
    eprintln!("== Setting cookie via httpbin... ==");
    let _response = client
        .get("https://httpbin.org/cookies/set/test_cookie/test_value")?
        .send()
        .await?;

    eprintln!("== Verifying cookie was set ==");
    // Verify the cookie is sent back
    let response = client.get("https://httpbin.org/cookies")?.send().await?;

    assert_eq!(response.status(), 200);

    let text = response.text().await?;
    eprintln!("Response: {:?}", text);

    assert!(text.contains("test_cookie"));
    assert!(text.contains("test_value"));

    Ok(())
}

#[tokio::test]
async fn test_download_file() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let temp_dir = std::env::temp_dir();
    let file_path = temp_dir.join("test_download.txt");

    // Clean up any existing file
    let _ = std::fs::remove_file(&file_path);

    let _response = client
        .download("https://httpbin.org/base64/SHR0cCBkb3dubG9hZCB0ZXN0")?
        .to_file(&file_path)
        .send()
        .await?;

    // Verify the file was downloaded
    assert!(file_path.exists());

    let content = std::fs::read_to_string(&file_path)?;
    assert!(content.contains("Http download test"));

    // Clean up
    let _ = std::fs::remove_file(&file_path);

    Ok(())
}

// Note: Multipart form test removed - feature may not be fully implemented yet

#[tokio::test]
async fn test_timeout() -> Result<()> {
    use std::time::Duration;

    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .timeout(Duration::from_millis(100)) // Short but more reasonable timeout
        .build()?;

    // This should timeout
    let result = client
        .get("https://httpbin.org/delay/5")? // 5 second delay
        .send()
        .await;

    eprintln!("{:?}", result);

    // Should get a timeout error
    assert!(result.is_err());
    if let Err(error) = result {
        assert!(
            matches!(error, frakt::Error::Timeout),
            "Expected Timeout error, got: {:?}",
            error
        );
    }

    Ok(())
}

#[tokio::test]
async fn test_error_status_codes() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let response = client.get("https://httpbin.org/status/404")?.send().await?;

    assert_eq!(response.status(), 404);

    Ok(())
}

#[tokio::test]
async fn test_response_headers() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let response = client.get("https://httpbin.org/json")?.send().await?;

    assert_eq!(response.status(), 200);

    // Verify we can actually extract headers from the response
    let headers = response.headers();

    // These headers should always be present in httpbin.org responses
    assert!(headers.contains_key("content-type") || headers.contains_key("Content-Type"));

    // Get the content-type header and verify it's JSON
    let content_type = headers
        .get("content-type")
        .or_else(|| headers.get("Content-Type"))
        .expect("Should have content-type header");

    let content_type_str = content_type.to_str().unwrap();
    assert!(
        content_type_str.contains("application/json"),
        "Expected JSON content type, got: {}",
        content_type_str
    );

    Ok(())
}

#[tokio::test]
async fn test_websocket_connection() -> Result<()> {
    println!("test_websocket_connection - Starting test");

    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    println!("test_websocket_connection - Created client, connecting to WebSocket...");

    // Test WebSocket connection to echo server
    let mut websocket = client
        .websocket()
        .connect("wss://ws.postman-echo.com/raw")
        .await?;

    println!("test_websocket_connection - WebSocket connected successfully!");

    // Send a text message
    println!("test_websocket_connection - Sending text message...");
    websocket
        .send(frakt::Message::text("Hello WebSocket!"))
        .await?;
    println!("test_websocket_connection - Text message sent successfully");

    // Receive the echo
    println!("test_websocket_connection - Receiving echo...");
    let message = websocket.receive().await?;
    println!("test_websocket_connection - Received message");
    match message {
        frakt::Message::Text(text) => {
            println!("test_websocket_connection - Received text: {}", text);
            assert_eq!(text, "Hello WebSocket!");
        }
        _ => panic!("Expected text message, got binary"),
    }

    // Send another text message to test multi-message flow
    println!("test_websocket_connection - Sending second text message...");
    websocket
        .send(frakt::Message::text("Second message!"))
        .await?;
    println!("test_websocket_connection - Second text message sent successfully");

    // Receive the second echo
    println!("test_websocket_connection - Receiving second echo...");
    let message = websocket.receive().await?;
    println!("test_websocket_connection - Received second message");
    match message {
        frakt::Message::Text(text) => {
            println!("test_websocket_connection - Received second text: {}", text);
            assert_eq!(text, "Second message!");
        }
        _ => panic!("Expected text message, got binary"),
    }

    // Close the connection
    println!("test_websocket_connection - Closing connection...");
    websocket
        .close(frakt::CloseCode::Normal, Some("Test completed"))
        .await?;
    println!("test_websocket_connection - Connection closed successfully");

    println!("test_websocket_connection - Test completed successfully!");
    Ok(())
}

#[tokio::test]
async fn test_websocket_max_message_size() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    // Test WebSocket with custom max message size
    let websocket = client
        .websocket()
        .maximum_message_size(1024) // 1KB limit
        .connect("wss://ws.postman-echo.com/raw")
        .await?;

    // Verify the max message size was set
    assert_eq!(websocket.maximum_message_size(), 1024);

    Ok(())
}

#[tokio::test]
async fn test_websocket_close_code_and_reason() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let mut websocket = client
        .websocket()
        .connect("wss://ws.postman-echo.com/raw")
        .await?;

    // Initially no close code or reason
    assert_eq!(websocket.close_code(), None);
    assert_eq!(websocket.close_reason(), None);

    // Close with specific code and reason
    websocket
        .close(frakt::CloseCode::Normal, Some("Manual close"))
        .await?;

    // Note: The close code and reason might not be immediately available
    // This is platform and implementation dependent

    Ok(())
}

#[tokio::test]
async fn test_platform_backend() -> Result<()> {
    // Test that the client uses the appropriate backend for the platform
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let response = client.get("https://httpbin.org/get")?.send().await?;
    assert_eq!(response.status(), 200);

    // Verify the response body contains expected data
    let text = response.text().await?;
    assert!(text.contains("\"url\": \"https://httpbin.org/get\""));

    Ok(())
}

#[tokio::test]
async fn test_invalid_url_handling() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    // Test invalid URL schemes
    let result = client.get("ftp://invalid.com")?.send().await;
    assert!(result.is_err());

    // Test malformed URLs
    let result = client.get("not-a-url");
    assert!(result.is_err());

    // Test URLs with invalid characters
    let result = client.get("https://[invalid-host]");
    assert!(result.is_err());

    Ok(())
}

#[tokio::test]
async fn test_connection_failures() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .timeout(Duration::from_secs(2))
        .build()?;

    // Test connection to non-existent host (this should still work as it's a valid URL)
    let result = client
        .get("http://this-domain-does-not-exist-12345.com")?
        .send()
        .await;
    assert!(result.is_err());

    // Test connection to invalid port
    let result = client.get("https://httpbin.org:199999");
    assert!(result.is_err());

    Ok(())
}

#[tokio::test]
async fn test_invalid_headers() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    // Test invalid header values (should return error)
    let result = client
        .get("https://httpbin.org/get")?
        .header("Invalid-Header", "value\nwith\nnewlines");

    assert!(result.is_err()); // Should fail due to invalid header value

    Ok(())
}

#[tokio::test]
async fn test_empty_request_body() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    // Test POST with empty body
    let response = client.post("https://httpbin.org/post")?.send().await?;

    assert_eq!(response.status(), 200);

    // Test POST with explicitly empty body
    let response = client
        .post("https://httpbin.org/post")?
        .body("")
        .send()
        .await?;

    assert_eq!(response.status(), 200);

    Ok(())
}

#[tokio::test]
async fn test_response_content_validation() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    // Test JSON response parsing
    let response = client.get("https://httpbin.org/json")?.send().await?;
    assert_eq!(response.status(), 200);

    // Verify content-type header is correct
    let content_type = response
        .header("content-type")
        .expect("Should have content-type header");
    assert!(content_type.contains("application/json"));

    let text = response.text().await?;
    // Verify JSON structure is correct
    assert!(text.contains("\"slideshow\""));
    assert!(text.contains("\"title\""));
    assert!(text.contains("\"slides\""));

    // Verify it's valid JSON by checking for proper structure (trim whitespace)
    let trimmed_text = text.trim();
    assert!(trimmed_text.starts_with("{"));
    assert!(trimmed_text.ends_with("}"));

    // Test XML-like response (base64 endpoint returns text)
    let response = client.get("https://httpbin.org/xml")?.send().await?;
    assert_eq!(response.status(), 200);

    let text = response.text().await?;
    assert!(text.contains("<?xml"));

    Ok(())
}

#[tokio::test]
async fn test_download_with_progress() -> Result<()> {
    use std::sync::{Arc, Mutex};

    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    let temp_dir = std::env::temp_dir();
    let file_path = temp_dir.join("test_progress_download.txt");

    // Clean up any existing file
    let _ = std::fs::remove_file(&file_path);

    // Track progress calls
    let progress_calls = Arc::new(Mutex::new(Vec::new()));
    let progress_calls_clone = progress_calls.clone();

    let _response = client
        .download("https://httpbin.org/base64/SGVsbG8gV29ybGQhIFRoaXMgaXMgYSB0ZXN0IGZvciB0aGUgZG93bmxvYWQgcHJvZ3Jlc3MgY2FsbGJhY2suIFdlIG5lZWQgYSBiaXQgbW9yZSB0ZXh0IHRvIG1ha2UgaXQgaW50ZXJlc3RpbmcgYW5kIHRyaWdnZXIgbXVsdGlwbGUgcHJvZ3Jlc3MgdXBkYXRlcy4=")?
        .to_file(&file_path)
        .progress(move |bytes_downloaded, total_bytes| {
            let mut calls = progress_calls_clone.lock().unwrap();
            calls.push((bytes_downloaded, total_bytes));
        })
        .send()
        .await?;

    // Verify the file was downloaded
    assert!(file_path.exists());

    // Verify progress callbacks were called
    let calls = progress_calls.lock().unwrap();
    assert!(
        !calls.is_empty(),
        "Progress callback should have been called"
    );

    // Verify the last call shows completion
    if let Some(last_call) = calls.last() {
        assert!(last_call.0 > 0, "Should have downloaded some bytes");
    }

    // Clean up
    let _ = std::fs::remove_file(&file_path);

    Ok(())
}

#[tokio::test]
async fn test_upload_with_progress() -> Result<()> {
    use std::sync::{Arc, Mutex};

    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    // Create test data
    let test_data = "This is test data for upload with progress tracking. ".repeat(100);

    // Track progress calls
    let progress_calls = Arc::new(Mutex::new(Vec::new()));
    let progress_calls_clone = progress_calls.clone();

    let response = client
        .upload("https://httpbin.org/post")?
        .from_data(test_data.as_bytes().to_vec())
        .progress(move |bytes_uploaded, total_bytes| {
            let mut calls = progress_calls_clone.lock().unwrap();
            calls.push((bytes_uploaded, total_bytes));
        })
        .send()
        .await?;

    assert_eq!(response.status(), 200);

    // Verify progress callbacks were called
    let calls = progress_calls.lock().unwrap();
    assert!(
        !calls.is_empty(),
        "Progress callback should have been called"
    );

    // Verify the last call shows completion
    if let Some(last_call) = calls.last() {
        assert!(last_call.0 > 0, "Should have uploaded some bytes");
    }

    Ok(())
}

#[tokio::test]
async fn test_form_urlencoded_upload() -> Result<()> {
    let client = Client::builder()
        .backend(backend())
        .user_agent("frakt-integration-test/1.0")
        .build()?;

    // Test form-urlencoded data
    let form_fields = vec![
        ("username", "john_doe"),
        ("email", "john@example.com"),
        ("age", "30"),
        ("message", "Hello world with spaces and symbols!@#$%"),
    ];

    let response = client
        .post("https://httpbin.org/post")?
        .form(form_fields)
        .send()
        .await?;

    assert_eq!(response.status(), 200);

    let text = response.json::<serde_json::Value>().await?;
    let form = text
        .get("form")
        .expect("Should have form field")
        .as_object()
        .unwrap();

    // Verify form data was sent correctly
    assert!(form.get("username").and_then(|x| x.as_str()) == Some("john_doe"));
    Ok(())
}