ruchy 4.2.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! HTTP Client Module (STD-002)
//!
//! Thin wrappers around `reqwest::blocking` for Ruchy-friendly API.
//!
//! # Examples
//!
#![cfg(feature = "http-client")]
//! ```no_run
//! use ruchy::stdlib::http;
//!
//! // GET request
//! let response = http::get("https://api.example.com/data")?;
//! println!("{}", response);
//!
//! // POST request with body
//! let body = r#"{"name": "Alice"}"#;
//! let response = http::post("https://api.example.com/users", body)?;
//!
//! // PUT request
//! let body = r#"{"name": "Bob"}"#;
//! let response = http::put("https://api.example.com/users/123", body)?;
//!
//! // DELETE request
//! http::delete("https://api.example.com/users/123")?;
//! # Ok::<(), anyhow::Error>(())
//! ```

use anyhow::{Context, Result};

/// Send a GET request to the specified URL
///
/// # Examples
///
/// ```no_run
/// use ruchy::stdlib::http;
///
/// let response = http::get("https://api.example.com/data")?;
/// println!("Response: {}", response);
/// # Ok::<(), anyhow::Error>(())
/// ```
///
/// # Errors
///
/// Returns error if the request fails or the server returns an error status
///
/// # Complexity
///
/// Complexity: 2 (within Toyota Way limits ≤10)
pub fn get(url: &str) -> Result<String> {
    let response = reqwest::blocking::get(url)
        .with_context(|| format!("Failed to send GET request to {url}"))?;

    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("GET request failed with status {status}: {url}");
    }

    response
        .text()
        .with_context(|| format!("Failed to read response body from {url}"))
}

/// Send a POST request with a body to the specified URL
///
/// # Examples
///
/// ```no_run
/// use ruchy::stdlib::http;
///
/// let body = r#"{"name": "Alice", "age": 30}"#;
/// let response = http::post("https://api.example.com/users", body)?;
/// println!("Created: {}", response);
/// # Ok::<(), anyhow::Error>(())
/// ```
///
/// # Errors
///
/// Returns error if the request fails or the server returns an error status
///
/// # Complexity
///
/// Complexity: 2 (within Toyota Way limits ≤10)
pub fn post(url: &str, body: &str) -> Result<String> {
    let client = reqwest::blocking::Client::new();
    let response = client
        .post(url)
        .header("content-type", "application/json")
        .body(body.to_string())
        .send()
        .with_context(|| format!("Failed to send POST request to {url}"))?;

    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("POST request failed with status {status}: {url}");
    }

    response
        .text()
        .with_context(|| format!("Failed to read response body from {url}"))
}

/// Send a PUT request with a body to the specified URL
///
/// # Examples
///
/// ```no_run
/// use ruchy::stdlib::http;
///
/// let body = r#"{"name": "Bob", "age": 31}"#;
/// let response = http::put("https://api.example.com/users/123", body)?;
/// println!("Updated: {}", response);
/// # Ok::<(), anyhow::Error>(())
/// ```
///
/// # Errors
///
/// Returns error if the request fails or the server returns an error status
///
/// # Complexity
///
/// Complexity: 2 (within Toyota Way limits ≤10)
pub fn put(url: &str, body: &str) -> Result<String> {
    let client = reqwest::blocking::Client::new();
    let response = client
        .put(url)
        .header("content-type", "application/json")
        .body(body.to_string())
        .send()
        .with_context(|| format!("Failed to send PUT request to {url}"))?;

    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("PUT request failed with status {status}: {url}");
    }

    response
        .text()
        .with_context(|| format!("Failed to read response body from {url}"))
}

/// Send a DELETE request to the specified URL
///
/// # Examples
///
/// ```no_run
/// use ruchy::stdlib::http;
///
/// let response = http::delete("https://api.example.com/users/123")?;
/// println!("Deleted: {}", response);
/// # Ok::<(), anyhow::Error>(())
/// ```
///
/// # Errors
///
/// Returns error if the request fails or the server returns an error status
///
/// # Complexity
///
/// Complexity: 2 (within Toyota Way limits ≤10)
pub fn delete(url: &str) -> Result<String> {
    let client = reqwest::blocking::Client::new();
    let response = client
        .delete(url)
        .send()
        .with_context(|| format!("Failed to send DELETE request to {url}"))?;

    let status = response.status();
    if !status.is_success() {
        anyhow::bail!("DELETE request failed with status {status}: {url}");
    }

    response
        .text()
        .with_context(|| format!("Failed to read response body from {url}"))
}

#[cfg(test)]
mod tests {
    use super::*;

    // ============================================================================
    // EXTREME TDD: Comprehensive HTTP Client Testing
    // Coverage Target: 19.67% → 80%+
    // Mutation Target: ≥75% caught
    // ============================================================================

    // --------------------------------------------------------------------------
    // Error Path Tests (Critical for Mutation Testing)
    // --------------------------------------------------------------------------

    #[test]
    fn test_invalid_url_error() {
        let result = get("not-a-url");
        assert!(result.is_err(), "Invalid URL should return error");

        // Verify error message contains context
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Failed to send GET request"),
            "Error should contain context"
        );
    }

    #[test]
    fn test_connection_refused_error() {
        // Port 1 is almost always not listening
        let result = get("http://localhost:1");
        assert!(result.is_err(), "Connection refused should return error");

        // Verify error message contains URL
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("localhost:1"),
            "Error should contain failed URL"
        );
    }

    #[test]
    fn test_post_invalid_url() {
        let result = post("not-a-url", "{}");
        assert!(result.is_err(), "POST with invalid URL should fail");

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Failed to send POST request"),
            "Error should contain POST context"
        );
    }

    #[test]
    fn test_put_invalid_url() {
        let result = put("not-a-url", "{}");
        assert!(result.is_err(), "PUT with invalid URL should fail");

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Failed to send PUT request"),
            "Error should contain PUT context"
        );
    }

    #[test]
    fn test_delete_invalid_url() {
        let result = delete("not-a-url");
        assert!(result.is_err(), "DELETE with invalid URL should fail");

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Failed to send DELETE request"),
            "Error should contain DELETE context"
        );
    }

    #[test]
    fn test_post_connection_refused() {
        let result = post("http://localhost:1", "{}");
        assert!(result.is_err(), "POST to closed port should fail");
    }

    #[test]
    fn test_put_connection_refused() {
        let result = put("http://localhost:1", "{}");
        assert!(result.is_err(), "PUT to closed port should fail");
    }

    #[test]
    fn test_delete_connection_refused() {
        let result = delete("http://localhost:1");
        assert!(result.is_err(), "DELETE to closed port should fail");
    }

    // --------------------------------------------------------------------------
    // HTTP Status Code Tests (Critical for Branch Coverage)
    // --------------------------------------------------------------------------

    // Note: These tests require a mock HTTP server running on localhost
    // We test error paths with httpbin.org when available

    #[test]
    fn test_get_success_with_httpbin() {
        let result = get("https://httpbin.org/get");
        if let Ok(response) = result {
            assert!(!response.is_empty(), "Response should not be empty");
            assert!(
                response.contains("httpbin"),
                "Response should be from httpbin"
            );
        }
        // If network fails, test is inconclusive (not a test failure)
    }

    #[test]
    fn test_get_404_error() {
        let result = get("https://httpbin.org/status/404");
        assert!(result.is_err(), "404 status should return error");

        if let Err(e) = result {
            let err_msg = e.to_string();
            assert!(
                err_msg.contains("404") || err_msg.contains("failed"),
                "Error should indicate HTTP failure"
            );
        }
    }

    #[test]
    fn test_post_success_with_httpbin() {
        let body = r#"{"test": "data"}"#;
        let result = post("https://httpbin.org/post", body);
        if let Ok(response) = result {
            assert!(!response.is_empty(), "Response should not be empty");
            assert!(response.contains("test"), "Response should echo data");
        }
    }

    #[test]
    fn test_put_success_with_httpbin() {
        let body = r#"{"test": "update"}"#;
        let result = put("https://httpbin.org/put", body);
        if let Ok(response) = result {
            assert!(!response.is_empty(), "Response should not be empty");
            assert!(response.contains("test"), "Response should echo data");
        }
    }

    #[test]
    fn test_delete_success_with_httpbin() {
        let result = delete("https://httpbin.org/delete");
        if let Ok(response) = result {
            assert!(!response.is_empty(), "Response should not be empty");
        }
    }

    // --------------------------------------------------------------------------
    // Property Tests (Mathematical Invariants)
    // --------------------------------------------------------------------------

    #[test]
    fn test_empty_url_fails() {
        assert!(get("").is_err(), "Empty URL should fail");
        assert!(post("", "{}").is_err(), "Empty URL should fail");
        assert!(put("", "{}").is_err(), "Empty URL should fail");
        assert!(delete("").is_err(), "Empty URL should fail");
    }

    #[test]
    fn test_url_without_scheme_fails() {
        // URLs without http:// or https:// should fail
        assert!(
            get("example.com").is_err(),
            "URL without scheme should fail"
        );
        assert!(
            post("example.com", "{}").is_err(),
            "URL without scheme should fail"
        );
    }

    // --------------------------------------------------------------------------
    // Boundary Condition Tests
    // --------------------------------------------------------------------------

    #[test]
    fn test_empty_body_post() {
        // Empty body should not panic, just fail on connection
        let result = post("http://localhost:1", "");
        assert!(
            result.is_err(),
            "POST with empty body should fail on connection"
        );
    }

    #[test]
    fn test_large_body_post() {
        // Large body should not panic
        let large_body = "x".repeat(10_000);
        let result = post("http://localhost:1", &large_body);
        assert!(
            result.is_err(),
            "POST with large body should fail on connection"
        );
    }

    #[test]
    fn test_special_characters_in_url() {
        // Special characters should be handled (will fail on connection, not panic)
        let result = get("http://localhost:1/test?query=value&foo=bar");
        assert!(
            result.is_err(),
            "URL with query params should fail on connection"
        );
    }
}

// ============================================================================
// Property Tests Module (High-Confidence Verification)
// ============================================================================

#[cfg(test)]
mod property_tests {
    use super::*;

    // Property: All HTTP functions should fail gracefully on invalid input
    // (Never panic, always return Result::Err)

    #[test]
    fn prop_get_never_panics_on_invalid_urls() {
        let invalid_urls = vec![
            "",
            "not-a-url",
            "://missing-scheme",
            "http://",
            "ftp://wrong-scheme.com",
            "http:// spaces .com",
        ];

        for url in invalid_urls {
            let result = get(url);
            assert!(result.is_err(), "get('{url}') should return Err, not panic");
        }
    }

    #[test]
    fn prop_post_never_panics_on_invalid_input() {
        let test_cases = vec![
            ("", ""),
            ("not-a-url", "{}"),
            ("http://localhost:1", "invalid json {"),
        ];

        for (url, body) in test_cases {
            let result = post(url, body);
            assert!(result.is_err(), "post('{url}', '{body}') should return Err");
        }
    }

    #[test]
    fn prop_all_methods_fail_on_unreachable_host() {
        // Property: Unreachable hosts should fail consistently across all methods
        let unreachable = "http://localhost:1";

        assert!(get(unreachable).is_err(), "GET should fail");
        assert!(post(unreachable, "{}").is_err(), "POST should fail");
        assert!(put(unreachable, "{}").is_err(), "PUT should fail");
        assert!(delete(unreachable).is_err(), "DELETE should fail");
    }
}