1
#[allow(unused_imports)]
2
pub use super::*;
3

            
4
#[cfg(test)]
5
mod tests {
6
    use super::*;
7

            
8
    #[test]
9
    #[cfg(feature = "url")]
10
    fn test_url_parse() {
11
        let url = Url::parse("https://example.com:8080/path?query=1#frag").unwrap();
12
        assert_eq!(url.scheme.as_str(), "https");
13
        assert_eq!(url.host.as_str(), "example.com");
14
        assert_eq!(url.port, 8080);
15
        assert_eq!(url.path.as_str(), "/path");
16
        assert_eq!(url.query.as_str(), "query=1");
17
        assert_eq!(url.fragment.as_str(), "frag");
18
    }
19

            
20
    #[test]
21
1
    fn test_url_from_parts() {
22
1
        let url = Url::from_parts("https", "example.com", 443, "/api");
23
1
        assert!(url.is_https());
24
1
        assert_eq!(url.effective_port(), 443);
25
1
    }
26
}
27

            
28
#[cfg(test)]
29
mod autotest_generated {
30
    use alloc::format;
31

            
32
    use super::*;
33

            
34
    /// Structural invariants that must hold for ANY `Url`, however it was built.
35
    ///
36
    /// Only checks properties derivable from the type's own contract, so it is
37
    /// safe to apply to the output of the external `url` crate parser too.
38
    fn assert_url_invariants(u: &Url) {
39
        // as_str() is exactly the href field, and Display agrees with it.
40
        assert_eq!(u.as_str(), u.href.as_str());
41
        assert_eq!(format!("{u}"), u.href.as_str());
42

            
43
        // is_http / is_https are mutually exclusive and match the scheme exactly.
44
        assert_eq!(u.is_https(), u.scheme.as_str() == "https");
45
        assert_eq!(u.is_http(), u.scheme.as_str() == "http");
46
        assert!(!(u.is_http() && u.is_https()));
47

            
48
        // effective_port() is a pure function of (port, scheme).
49
        let expected_port = if u.port != 0 {
50
            u.port
51
        } else if u.is_https() {
52
            443
53
        } else if u.is_http() {
54
            80
55
        } else {
56
            0
57
        };
58
        assert_eq!(u.effective_port(), expected_port);
59

            
60
        // Equality/clone consistency (the type derives Clone + PartialEq).
61
        assert_eq!(u.clone(), *u);
62
    }
63

            
64
    // ---------------------------------------------------------------------
65
    // Url::default() / getters / predicates on degenerate instances
66
    // ---------------------------------------------------------------------
67

            
68
    #[test]
69
    fn default_url_is_inert_and_does_not_panic() {
70
        let u = Url::default();
71
        assert_eq!(u.as_str(), "");
72
        assert_eq!(u.href.as_str(), "");
73
        assert_eq!(u.scheme.as_str(), "");
74
        assert_eq!(u.host.as_str(), "");
75
        assert_eq!(u.port, 0);
76
        assert!(!u.is_https());
77
        assert!(!u.is_http());
78
        // Unknown scheme + sentinel port => no default port to infer.
79
        assert_eq!(u.effective_port(), 0);
80
        assert_eq!(format!("{u}"), "");
81
        assert_url_invariants(&u);
82
    }
83

            
84
    #[test]
85
    fn effective_port_covers_every_scheme_port_combination() {
86
        // Explicit port always wins, even when it contradicts the scheme default.
87
        assert_eq!(
88
            Url::from_parts("https", "h", 80, "/").effective_port(),
89
            80,
90
            "explicit port must win over the https default"
91
        );
92
        assert_eq!(Url::from_parts("http", "h", 443, "/").effective_port(), 443);
93
        assert_eq!(
94
            Url::from_parts("http", "h", u16::MAX, "/").effective_port(),
95
            u16::MAX
96
        );
97
        assert_eq!(Url::from_parts("https", "h", 1, "/").effective_port(), 1);
98

            
99
        // Sentinel port 0 => infer from scheme.
100
        assert_eq!(Url::from_parts("https", "h", 0, "/").effective_port(), 443);
101
        assert_eq!(Url::from_parts("http", "h", 0, "/").effective_port(), 80);
102
        assert_eq!(Url::from_parts("ftp", "h", 0, "/").effective_port(), 0);
103
        assert_eq!(Url::from_parts("", "", 0, "").effective_port(), 0);
104
    }
105

            
106
    #[test]
107
    fn predicates_are_case_sensitive_and_reject_near_misses() {
108
        // Near-miss schemes must NOT be reported as http/https.
109
        for scheme in [
110
            "HTTPS", "Https", "httpss", "https ", " https", "http\0", "ws", "httpx", "",
111
        ] {
112
            let u = Url::from_parts(scheme, "example.com", 0, "/");
113
            assert!(
114
                !u.is_https(),
115
                "scheme {scheme:?} must not be treated as https"
116
            );
117
            assert_url_invariants(&u);
118
        }
119
        for scheme in ["HTTP", "Http", "httpx", "https", "htt", ""] {
120
            let u = Url::from_parts(scheme, "example.com", 0, "/");
121
            assert!(
122
                !u.is_http(),
123
                "scheme {scheme:?} must not be treated as http"
124
            );
125
        }
126
        assert!(Url::from_parts("https", "h", 0, "/").is_https());
127
        assert!(Url::from_parts("http", "h", 0, "/").is_http());
128
    }
129

            
130
    // ---------------------------------------------------------------------
131
    // Url::from_parts — constructor, no panics, invariants
132
    // ---------------------------------------------------------------------
133

            
134
    #[test]
135
    fn from_parts_omits_default_and_sentinel_ports_only() {
136
        // Sentinel 0 => no port in href.
137
        assert_eq!(
138
            Url::from_parts("https", "example.com", 0, "/a").as_str(),
139
            "https://example.com/a"
140
        );
141
        // Scheme-matching default ports => elided.
142
        assert_eq!(
143
            Url::from_parts("http", "example.com", 80, "/").as_str(),
144
            "http://example.com/"
145
        );
146
        assert_eq!(
147
            Url::from_parts("https", "example.com", 443, "/").as_str(),
148
            "https://example.com/"
149
        );
150
        // Cross-scheme "defaults" are NOT elided.
151
        assert_eq!(
152
            Url::from_parts("https", "example.com", 80, "/").as_str(),
153
            "https://example.com:80/"
154
        );
155
        assert_eq!(
156
            Url::from_parts("http", "example.com", 443, "/").as_str(),
157
            "http://example.com:443/"
158
        );
159
        // A non-default port is always rendered, including the u16 boundary.
160
        assert_eq!(
161
            Url::from_parts("http", "example.com", u16::MAX, "/").as_str(),
162
            "http://example.com:65535/"
163
        );
164
        assert_eq!(
165
            Url::from_parts("ftp", "example.com", 443, "/").as_str(),
166
            "ftp://example.com:443/"
167
        );
168
    }
169

            
170
    #[test]
171
    fn from_parts_keeps_the_port_field_even_when_elided_from_href() {
172
        // The elision is purely cosmetic: the struct field must still carry the
173
        // caller's port, and effective_port() must agree with it.
174
        let u = Url::from_parts("https", "example.com", 443, "/api");
175
        assert_eq!(u.port, 443);
176
        assert!(!u.as_str().contains(":443"));
177
        assert_eq!(u.effective_port(), 443);
178
        assert_url_invariants(&u);
179
    }
180

            
181
    #[test]
182
    fn from_parts_fields_mirror_the_arguments_verbatim() {
183
        let u = Url::from_parts("https", "example.com", 8080, "/a/b");
184
        assert_eq!(u.scheme.as_str(), "https");
185
        assert_eq!(u.host.as_str(), "example.com");
186
        assert_eq!(u.port, 8080);
187
        assert_eq!(u.path.as_str(), "/a/b");
188
        // from_parts has no query/fragment inputs; they must be empty, not garbage.
189
        assert_eq!(u.query.as_str(), "");
190
        assert_eq!(u.fragment.as_str(), "");
191
        assert_eq!(u.as_str(), "https://example.com:8080/a/b");
192
        assert_url_invariants(&u);
193
    }
194

            
195
    #[test]
196
    fn from_parts_does_not_panic_on_extreme_or_empty_arguments() {
197
        // Every argument empty: degenerate but must not panic.
198
        let u = Url::from_parts("", "", 0, "");
199
        assert_eq!(u.as_str(), "://");
200
        assert_url_invariants(&u);
201

            
202
        // from_parts is a raw formatter, not a validator: it must not panic on
203
        // inputs that could never parse, and must reproduce them byte-for-byte.
204
        for (scheme, host, port, path) in [
205
            ("://", "://", 1, "://"),
206
            ("http", "user:pw@host", 0, "/x"),
207
            ("http", "[::1]", 8080, "/x"),
208
            ("http", "a b c", 0, "/p a t h"),
209
            ("http", "example.com", 0, "no-leading-slash"),
210
            ("http", "example.com", 0, "?query#frag"),
211
            ("\n\t", "\r", 65535, "\0"),
212
        ] {
213
            let u = Url::from_parts(scheme, host, port, path);
214
            assert_eq!(u.scheme.as_str(), scheme);
215
            assert_eq!(u.host.as_str(), host);
216
            assert_eq!(u.port, port);
217
            assert_eq!(u.path.as_str(), path);
218
            assert!(u.as_str().starts_with(scheme));
219
            assert_url_invariants(&u);
220
        }
221
    }
222

            
223
    #[test]
224
    fn from_parts_handles_unicode_without_panicking_or_mangling() {
225
        let u = Url::from_parts("https", "例え.テスト", 0, "/パス/😀");
226
        assert_eq!(u.host.as_str(), "例え.テスト");
227
        assert_eq!(u.path.as_str(), "/パス/😀");
228
        // No IDNA/percent-encoding happens here — from_parts is a plain formatter.
229
        assert_eq!(u.as_str(), "https://例え.テスト/パス/😀");
230
        assert!(u.is_https());
231
        assert_url_invariants(&u);
232

            
233
        // Combining marks + a lone emoji as the whole host.
234
        let u = Url::from_parts("http", "e\u{0301}xample", 1, "/\u{1F600}");
235
        assert!(u.as_str().contains('\u{0301}'));
236
        assert_url_invariants(&u);
237
    }
238

            
239
    #[test]
240
    fn from_parts_handles_huge_inputs_without_hanging() {
241
        let host = "a".repeat(100_000);
242
        let path = "/".to_string() + &"b".repeat(100_000);
243
        let u = Url::from_parts("https", &host, 8080, &path);
244
        // "https" + "://" + host + ":8080" + path
245
        assert_eq!(u.as_str().len(), 5 + 3 + 100_000 + 5 + 100_001);
246
        assert_eq!(u.host.as_str().len(), 100_000);
247
        assert!(u.is_https());
248
        assert_eq!(u.effective_port(), 8080);
249
        assert_url_invariants(&u);
250
    }
251

            
252
    // ---------------------------------------------------------------------
253
    // Display / serializer
254
    // ---------------------------------------------------------------------
255

            
256
    #[test]
257
    fn url_display_never_reinterprets_the_href() {
258
        // Display must be a verbatim echo of href, not a re-serialization.
259
        for href in ["", "://", "not a url", "{}{{}", "%s%n", "\u{1F600}"] {
260
            let u = Url {
261
                href: AzString::from(href),
262
                ..Url::default()
263
            };
264
            assert_eq!(format!("{u}"), href);
265
            assert_eq!(u.as_str(), href);
266
        }
267
    }
268

            
269
    #[test]
270
    fn url_parse_error_display_is_verbatim_and_panic_free() {
271
        // Default / empty message.
272
        let e = UrlParseError {
273
            message: AzString::from(""),
274
        };
275
        assert_eq!(format!("{e}"), "");
276

            
277
        // Format-specifier-looking payloads must NOT be interpreted.
278
        for msg in [
279
            "relative URL without a base",
280
            "{}",
281
            "{0} {1} {}",
282
            "%s %n %p",
283
            "\u{1F600} invalid",
284
            "e\u{0301}",
285
            "\0\t\n",
286
        ] {
287
            let e = UrlParseError {
288
                message: AzString::from(msg),
289
            };
290
            assert_eq!(format!("{e}"), msg);
291
        }
292

            
293
        // Non-empty for a representative value, and huge messages don't panic.
294
        let big = "x".repeat(100_000);
295
        let e = UrlParseError {
296
            message: AzString::from(big.as_str()),
297
        };
298
        assert_eq!(format!("{e}").len(), 100_000);
299

            
300
        // from_const_str path (used by the no-`url`-feature stubs).
301
        let e = UrlParseError {
302
            message: AzString::from_const_str("url feature not enabled"),
303
        };
304
        assert_eq!(format!("{e}"), "url feature not enabled");
305
    }
306

            
307
    // ---------------------------------------------------------------------
308
    // FFI result type
309
    // ---------------------------------------------------------------------
310

            
311
    #[test]
312
    fn ffi_result_round_trips_both_variants() {
313
        let ok: Result<Url, UrlParseError> = Ok(Url::from_parts("https", "a.b", 0, "/"));
314
        let ffi: ResultUrlUrlParseError = ok.clone().into();
315
        assert!(ffi.is_ok());
316
        assert!(!ffi.is_err());
317
        let back: Result<Url, UrlParseError> = ffi.into();
318
        assert_eq!(back, ok);
319

            
320
        let err: Result<Url, UrlParseError> = Err(UrlParseError {
321
            message: AzString::from("boom"),
322
        });
323
        let ffi: ResultUrlUrlParseError = err.clone().into();
324
        assert!(ffi.is_err());
325
        assert!(!ffi.is_ok());
326
        assert_eq!(
327
            ffi.as_result().unwrap_err().message.as_str(),
328
            "boom",
329
            "as_result() must borrow the same error payload"
330
        );
331
        let back: Result<Url, UrlParseError> = ffi.into();
332
        assert_eq!(back, err);
333
    }
334

            
335
    #[cfg(feature = "std")]
336
    #[test]
337
    fn eq_implies_equal_hash() {
338
        use std::{
339
            collections::hash_map::DefaultHasher,
340
            hash::{Hash, Hasher},
341
        };
342

            
343
        fn hash_of(u: &Url) -> u64 {
344
            let mut h = DefaultHasher::new();
345
            u.hash(&mut h);
346
            h.finish()
347
        }
348

            
349
        let a = Url::from_parts("https", "example.com", 8080, "/a");
350
        let b = Url::from_parts("https", "example.com", 8080, "/a");
351
        assert_eq!(a, b);
352
        assert_eq!(hash_of(&a), hash_of(&b));
353

            
354
        // Port is part of identity even when it is elided from the href.
355
        let c = Url::from_parts("https", "example.com", 443, "/a");
356
        let d = Url::from_parts("https", "example.com", 0, "/a");
357
        assert_eq!(c.as_str(), d.as_str(), "hrefs are identical…");
358
        assert_ne!(c, d, "…but the port field still distinguishes them");
359
    }
360

            
361
    // =====================================================================
362
    // Parser tests — only meaningful with the `url` feature.
363
    // =====================================================================
364

            
365
    /// Parse `s`; if it succeeds, assert the general invariants AND that
366
    /// re-parsing the serialization is a fixed point (`parse(as_str(x)) == x`).
367
    ///
368
    /// Used for inputs whose accept/reject verdict is the `url` crate's business:
369
    /// the point is that we never panic and never produce an inconsistent `Url`.
370
    #[cfg(feature = "url")]
371
    fn assert_no_panic_and_idempotent(s: &str) {
372
        match Url::parse(s) {
373
            Ok(u) => {
374
                assert_url_invariants(&u);
375
                let again = Url::parse(u.as_str())
376
                    .expect("a serialized URL must always re-parse (idempotent normalization)");
377
                assert_eq!(again, u, "parse(serialize(x)) must equal x for input {s:?}");
378
                assert_eq!(again.as_str(), u.as_str());
379
            }
380
            Err(e) => {
381
                // An error must carry a diagnosable, non-empty message.
382
                assert!(
383
                    !e.message.as_str().is_empty(),
384
                    "error for {s:?} must have a message"
385
                );
386
                assert_eq!(format!("{e}"), e.message.as_str());
387
            }
388
        }
389
    }
390

            
391
    #[cfg(feature = "url")]
392
    #[test]
393
    fn parse_valid_minimal_positive_control() {
394
        let u = Url::parse("http://example.com").expect("minimal absolute URL must parse");
395
        assert_eq!(u.scheme.as_str(), "http");
396
        assert_eq!(u.host.as_str(), "example.com");
397
        // No explicit port => the 0 sentinel, resolved by effective_port().
398
        assert_eq!(u.port, 0);
399
        assert_eq!(u.effective_port(), 80);
400
        assert!(u.is_http());
401
        assert!(!u.is_https());
402
        // The parser normalizes the empty path to "/".
403
        assert_eq!(u.path.as_str(), "/");
404
        assert_eq!(u.query.as_str(), "");
405
        assert_eq!(u.fragment.as_str(), "");
406
        assert_url_invariants(&u);
407
    }
408

            
409
    #[cfg(feature = "url")]
410
    #[test]
411
    fn parse_rejects_empty_and_whitespace_only_input() {
412
        for s in ["", " ", "   ", "\t", "\n", "\t\n", "\r\n  \t "] {
413
            let r = Url::parse(s);
414
            assert!(r.is_err(), "{s:?} must not parse as an absolute URL");
415
            let e = r.unwrap_err();
416
            assert!(!e.message.as_str().is_empty());
417
        }
418
    }
419

            
420
    #[cfg(feature = "url")]
421
    #[test]
422
    fn parse_rejects_garbage_without_panicking() {
423
        for s in [
424
            "not a url",
425
            "///",
426
            "::::",
427
            "http://",
428
            "\u{0}\u{1}\u{2}",
429
            "\u{FFFD}\u{FFFD}",
430
            "?query-only",
431
            "#fragment-only",
432
            "/absolute/path/only",
433
            "../relative",
434
        ] {
435
            let r = Url::parse(s);
436
            if let Ok(ref u) = r {
437
                // If the parser DOES accept it, the result must still be coherent.
438
                assert_url_invariants(u);
439
            } else {
440
                assert!(!r.unwrap_err().message.as_str().is_empty());
441
            }
442
        }
443
        // These are unambiguously relative and must be rejected.
444
        assert!(Url::parse("not a url").is_err());
445
        assert!(Url::parse("/absolute/path/only").is_err());
446
        assert!(
447
            Url::parse("http://").is_err(),
448
            "empty host must be an error"
449
        );
450
    }
451

            
452
    #[cfg(feature = "url")]
453
    #[test]
454
    fn parse_rejects_out_of_range_and_non_numeric_ports() {
455
        // u16 overflow at the boundary and far beyond it.
456
        assert!(Url::parse("http://example.com:65536/").is_err());
457
        assert!(Url::parse("http://example.com:99999/").is_err());
458
        assert!(Url::parse("http://example.com:4294967296/").is_err());
459
        assert!(Url::parse("http://example.com:18446744073709551616/").is_err());
460
        assert!(Url::parse("http://example.com:-1/").is_err());
461
        assert!(Url::parse("http://example.com:NaN/").is_err());
462
        assert!(Url::parse("http://example.com:inf/").is_err());
463
        assert!(Url::parse("http://example.com:+80/").is_err());
464
        assert!(Url::parse(&format!("http://example.com:{}/", "9".repeat(10_000))).is_err());
465

            
466
        // The largest in-range port must survive intact (no truncation to 0).
467
        let u = Url::parse("http://example.com:65535/").expect("65535 is a valid port");
468
        assert_eq!(u.port, u16::MAX);
469
        assert_eq!(u.effective_port(), u16::MAX);
470
        assert_url_invariants(&u);
471
    }
472

            
473
    #[cfg(feature = "url")]
474
    #[test]
475
    fn parse_port_zero_collides_with_the_no_port_sentinel() {
476
        // `port: 0` doubles as "unspecified", so an explicit :0 is indistinguishable
477
        // from no port at all — effective_port() then reports the scheme default.
478
        // This documents the sentinel's cost; it must at least stay self-consistent.
479
        if let Ok(u) = Url::parse("http://example.com:0/") {
480
            assert_eq!(u.port, 0);
481
            assert_eq!(
482
                u.effective_port(),
483
                80,
484
                "explicit :0 is swallowed by the 0 sentinel"
485
            );
486
            assert_url_invariants(&u);
487
        }
488
    }
489

            
490
    #[cfg(feature = "url")]
491
    #[test]
492
    fn parse_default_ports_are_reported_via_effective_port() {
493
        // Whether the parser stores or elides a scheme-default port, effective_port()
494
        // must resolve to the same answer.
495
        let u = Url::parse("https://example.com:443/").unwrap();
496
        assert!(u.port == 0 || u.port == 443);
497
        assert_eq!(u.effective_port(), 443);
498
        assert_url_invariants(&u);
499

            
500
        let u = Url::parse("http://example.com:80/").unwrap();
501
        assert!(u.port == 0 || u.port == 80);
502
        assert_eq!(u.effective_port(), 80);
503
        assert_url_invariants(&u);
504

            
505
        // A non-http(s) scheme with no port has no default to fall back on.
506
        let u = Url::parse("ftp://example.com/").unwrap();
507
        assert_eq!(u.effective_port(), 0);
508
        assert_url_invariants(&u);
509
    }
510

            
511
    #[cfg(feature = "url")]
512
    #[test]
513
    fn parse_is_idempotent_across_hostile_inputs() {
514
        for s in [
515
            // boundary numbers
516
            "http://example.com/0",
517
            "http://example.com/-0",
518
            "http://example.com/9223372036854775807",
519
            "http://example.com/-9223372036854775808",
520
            "http://example.com/18446744073709551615",
521
            "http://example.com/?n=NaN&i=inf&e=1e400&t=1e-400",
522
            "http://example.com/#-0.0",
523
            // leading/trailing junk
524
            "  https://example.com/  ",
525
            "\thttps://example.com/\n",
526
            "https://example.com/valid;garbage",
527
            "https://example.com/a?b=c;d#e;f",
528
            // odd but legal shapes
529
            "https://user:pw@example.com:8080/p?q#f",
530
            "https://example.com/%2e%2e/%2E%2E/",
531
            "https://example.com/a//b///c",
532
            "https://example.com/?",
533
            "https://example.com/#",
534
            "https://example.com/?#",
535
            "http://[::1]:8080/",
536
            "http://[2001:db8::1]/",
537
            "http://127.0.0.1:8080/",
538
            "file:///etc/passwd",
539
            "data:text/plain,hello",
540
            "mailto:user@example.com",
541
            "urn:isbn:0451450523",
542
            "blob:https://example.com/uuid",
543
            // percent-encoding edge cases
544
            "https://example.com/%",
545
            "https://example.com/%zz",
546
            "https://example.com/%00",
547
            "https://example.com/%%%%",
548
            // unicode
549
            "https://example.com/\u{1F600}",
550
            "https://example.com/e\u{0301}\u{0301}\u{0301}",
551
            "https://example.com/?q=\u{4F8B}\u{3048}",
552
            "https://example.com/#\u{200B}\u{FEFF}",
553
            "https://\u{4F8B}\u{3048}.\u{30C6}\u{30B9}\u{30C8}/",
554
        ] {
555
            assert_no_panic_and_idempotent(s);
556
        }
557
    }
558

            
559
    #[cfg(feature = "url")]
560
    #[test]
561
    fn parse_normalizes_leading_and_trailing_whitespace_deterministically() {
562
        // Either the junk is stripped (spec behaviour) or the input is rejected —
563
        // never a Url carrying stray whitespace in its href.
564
        match Url::parse("  https://example.com/  ") {
565
            Ok(u) => {
566
                assert_eq!(u.host.as_str(), "example.com");
567
                assert_eq!(u.as_str(), "https://example.com/");
568
                assert!(!u.as_str().contains(' '));
569
                assert_url_invariants(&u);
570
            }
571
            Err(e) => assert!(!e.message.as_str().is_empty()),
572
        }
573
    }
574

            
575
    #[cfg(feature = "url")]
576
    #[test]
577
    fn parse_unicode_host_is_idna_encoded_to_ascii() {
578
        let u = Url::parse("https://\u{4F8B}\u{3048}.\u{30C6}\u{30B9}\u{30C8}/")
579
            .expect("an IDN host must parse");
580
        assert!(
581
            u.host.as_str().is_ascii(),
582
            "host must be punycode/ASCII after IDNA, got {:?}",
583
            u.host.as_str()
584
        );
585
        assert!(!u.host.as_str().is_empty());
586
        assert!(u.as_str().is_ascii(), "serialized href must be ASCII");
587
        assert_url_invariants(&u);
588
    }
589

            
590
    #[cfg(feature = "url")]
591
    #[test]
592
    fn parse_unicode_path_is_percent_encoded() {
593
        let u = Url::parse("https://example.com/\u{1F600}").expect("emoji path must parse");
594
        assert!(
595
            u.path.as_str().is_ascii(),
596
            "path must be percent-encoded, got {:?}",
597
            u.path.as_str()
598
        );
599
        assert!(u.as_str().is_ascii());
600
        assert_url_invariants(&u);
601
    }
602

            
603
    #[cfg(feature = "url")]
604
    #[test]
605
    fn parse_survives_extremely_long_input() {
606
        // 1M-char path segment: must be linear-time and allocation-safe, not a hang.
607
        let long = format!("http://example.com/{}", "a".repeat(1_000_000));
608
        let u = Url::parse(&long).expect("a long-but-valid URL must parse");
609
        assert_eq!(u.host.as_str(), "example.com");
610
        assert_eq!(u.path.as_str().len(), 1 + 1_000_000);
611
        assert_url_invariants(&u);
612

            
613
        // A 1M-char query and a 1M-char host label must also not panic.
614
        let long_q = format!("http://example.com/?{}", "k=v&".repeat(250_000));
615
        assert_no_panic_and_idempotent(&long_q);
616
        let long_host = format!("http://{}/", "h".repeat(100_000));
617
        assert_no_panic_and_idempotent(&long_host);
618
    }
619

            
620
    #[cfg(feature = "url")]
621
    #[test]
622
    fn parse_survives_deeply_nested_and_repetitive_input() {
623
        // 10k nested path segments — must not blow the stack.
624
        let nested = format!("http://example.com/{}", "a/".repeat(10_000));
625
        let u = Url::parse(&nested).expect("deeply nested path must parse");
626
        assert_eq!(u.path.as_str().matches('/').count(), 10_001);
627
        assert_url_invariants(&u);
628

            
629
        // 10k dot-dot segments that all try to escape the root.
630
        let dotdot = format!("http://example.com/{}", "../".repeat(10_000));
631
        let u = Url::parse(&dotdot).expect("dot-dot flood must parse");
632
        assert_eq!(u.host.as_str(), "example.com", "must not escape the origin");
633
        assert!(u.path.as_str().starts_with('/'));
634
        assert!(
635
            !u.path.as_str().contains(".."),
636
            "dot-dot segments must be resolved away, got {:?}",
637
            u.path.as_str()
638
        );
639
        assert_url_invariants(&u);
640

            
641
        // 10k nested brackets/parens as raw path junk.
642
        let brackets = format!(
643
            "http://example.com/{}{}",
644
            "(".repeat(10_000),
645
            ")".repeat(10_000)
646
        );
647
        assert_no_panic_and_idempotent(&brackets);
648
    }
649

            
650
    #[cfg(feature = "url")]
651
    #[test]
652
    fn parse_round_trips_a_fully_populated_url() {
653
        let src = "https://example.com:8080/path?query=1#frag";
654
        let u = Url::parse(src).unwrap();
655
        // Serialization is byte-identical to the (already-normalized) input…
656
        assert_eq!(u.as_str(), src);
657
        // …and re-parsing it is a fixed point across every field.
658
        let u2 = Url::parse(u.as_str()).unwrap();
659
        assert_eq!(u2, u);
660
        assert_eq!(format!("{u2}"), format!("{u}"));
661
        assert_url_invariants(&u);
662
    }
663

            
664
    #[cfg(feature = "url")]
665
    #[test]
666
    fn from_parts_output_reparses_into_the_same_url() {
667
        // Non-default port: from_parts and parse must agree on every field.
668
        let built = Url::from_parts("https", "example.com", 8080, "/a/b");
669
        let parsed = Url::parse(built.as_str()).expect("from_parts output must be parseable");
670
        assert_eq!(parsed, built, "from_parts must be a faithful serializer");
671

            
672
        // Elided default port: the href round-trips, but the port FIELD does not —
673
        // the parser reports the 0 sentinel where from_parts kept 443. The two
674
        // disagree on `port` yet must still agree on `effective_port()`.
675
        let built = Url::from_parts("https", "example.com", 443, "/a");
676
        let parsed = Url::parse(built.as_str()).unwrap();
677
        assert_eq!(parsed.as_str(), built.as_str());
678
        assert_eq!(built.port, 443);
679
        assert_eq!(parsed.port, 0);
680
        assert_ne!(parsed, built, "port-field asymmetry across the round trip");
681
        assert_eq!(parsed.effective_port(), built.effective_port());
682
        assert_eq!(parsed.effective_port(), 443);
683
    }
684

            
685
    // ---------------------------------------------------------------------
686
    // Url::join
687
    // ---------------------------------------------------------------------
688

            
689
    #[cfg(feature = "url")]
690
    #[test]
691
    fn join_valid_minimal_positive_control() {
692
        let base = Url::parse("https://example.com/a/b").unwrap();
693
        let j = base.join("c").expect("relative join must work");
694
        assert_eq!(j.as_str(), "https://example.com/a/c");
695
        assert_eq!(j.host.as_str(), "example.com");
696
        assert!(j.is_https());
697
        assert_eq!(j.effective_port(), 443);
698
        assert_url_invariants(&j);
699

            
700
        // Absolute path, absolute URL, and fragment-only joins.
701
        assert_eq!(
702
            base.join("/root").unwrap().as_str(),
703
            "https://example.com/root"
704
        );
705
        assert_eq!(
706
            base.join("http://other.com/x").unwrap().host.as_str(),
707
            "other.com"
708
        );
709
        assert_eq!(base.join("#f").unwrap().fragment.as_str(), "f");
710
        assert_eq!(base.join("?q=1").unwrap().query.as_str(), "q=1");
711
    }
712

            
713
    #[cfg(feature = "url")]
714
    #[test]
715
    fn join_on_an_unparseable_base_errors_instead_of_panicking() {
716
        // Default Url: href is "" — the base itself cannot be parsed.
717
        let e = Url::default()
718
            .join("/x")
719
            .expect_err("joining onto an empty base must fail");
720
        assert!(!e.message.as_str().is_empty());
721

            
722
        // from_parts can produce hrefs that are not valid URLs at all.
723
        for bad in [
724
            Url::from_parts("", "", 0, ""),
725
            Url::from_parts("://", "://", 1, "://"),
726
            Url::from_parts("http", "", 0, "/x"),
727
        ] {
728
            let r = bad.join("/y");
729
            if let Ok(ref u) = r {
730
                assert_url_invariants(u);
731
            } else {
732
                assert!(!r.unwrap_err().message.as_str().is_empty());
733
            }
734
        }
735
    }
736

            
737
    #[cfg(feature = "url")]
738
    #[test]
739
    fn join_never_panics_on_hostile_relative_inputs() {
740
        let base = Url::parse("https://example.com/a/b?q=1#f").unwrap();
741
        for path in [
742
            "",
743
            " ",
744
            "   ",
745
            "\t\n",
746
            "..",
747
            "../..",
748
            "/",
749
            "//",
750
            "///",
751
            "//other.com/x",
752
            "?",
753
            "#",
754
            "?#",
755
            ":",
756
            "::::",
757
            "not a path",
758
            "valid;garbage",
759
            "  padded  ",
760
            "%",
761
            "%zz",
762
            "%00",
763
            "\u{1F600}",
764
            "e\u{0301}",
765
            "\u{4F8B}\u{3048}",
766
            "\u{0}",
767
            "0",
768
            "-0",
769
            "9223372036854775807",
770
            "NaN",
771
            "inf",
772
            "javascript:alert(1)",
773
            "data:text/plain,x",
774
            "mailto:a@b.c",
775
        ] {
776
            match base.join(path) {
777
                Ok(u) => {
778
                    assert_url_invariants(&u);
779
                    // join() funnels through parse(), so the result must be a
780
                    // fixed point of the parser too.
781
                    let again = Url::parse(u.as_str()).expect("join() output must always re-parse");
782
                    assert_eq!(again, u, "join({path:?}) is not idempotent");
783
                }
784
                Err(e) => assert!(
785
                    !e.message.as_str().is_empty(),
786
                    "join({path:?}) error needs a message"
787
                ),
788
            }
789
        }
790
    }
791

            
792
    #[cfg(feature = "url")]
793
    #[test]
794
    fn join_cannot_escape_the_origin_with_a_dot_dot_flood() {
795
        let base = Url::parse("https://example.com/a/b/c").unwrap();
796
        let escape = "../".repeat(10_000);
797
        let u = base
798
            .join(&escape)
799
            .expect("a dot-dot flood must resolve, not fail");
800
        assert_eq!(u.host.as_str(), "example.com");
801
        assert_eq!(u.scheme.as_str(), "https");
802
        assert_eq!(u.path.as_str(), "/", "must clamp at the root");
803
        assert!(!u.path.as_str().contains(".."));
804
        assert_url_invariants(&u);
805
    }
806

            
807
    #[cfg(feature = "url")]
808
    #[test]
809
    fn join_survives_extremely_long_relative_paths() {
810
        let base = Url::parse("https://example.com/").unwrap();
811
        let long = "a".repeat(1_000_000);
812
        let u = base.join(&long).expect("a long relative path must join");
813
        assert_eq!(u.host.as_str(), "example.com");
814
        assert_eq!(u.path.as_str().len(), 1 + 1_000_000);
815
        assert_url_invariants(&u);
816

            
817
        // 10k nested segments.
818
        let nested = "x/".repeat(10_000);
819
        let u = base.join(&nested).expect("deep nesting must join");
820
        assert_eq!(u.path.as_str().matches('/').count(), 10_001);
821
        assert_url_invariants(&u);
822
    }
823

            
824
    #[cfg(feature = "url")]
825
    #[test]
826
    fn join_result_is_a_fully_populated_url_not_a_partial_one() {
827
        // join() re-parses, so query/fragment/port must all be repopulated
828
        // from the joined string rather than inherited or dropped.
829
        let base = Url::parse("http://example.com:8080/a?old=1#oldfrag").unwrap();
830
        let u = base.join("b?new=2#newfrag").unwrap();
831
        assert_eq!(u.as_str(), "http://example.com:8080/b?new=2#newfrag");
832
        assert_eq!(u.scheme.as_str(), "http");
833
        assert_eq!(u.host.as_str(), "example.com");
834
        assert_eq!(u.port, 8080);
835
        assert_eq!(u.path.as_str(), "/b");
836
        assert_eq!(u.query.as_str(), "new=2");
837
        assert_eq!(u.fragment.as_str(), "newfrag");
838
        assert_eq!(u.effective_port(), 8080);
839
        assert_url_invariants(&u);
840
    }
841

            
842
    // =====================================================================
843
    // Stub tests — the `url` feature is OFF, parse/join are const Err stubs.
844
    // =====================================================================
845

            
846
    #[cfg(not(feature = "url"))]
847
    #[test]
848
    fn stub_parse_always_errors_and_never_panics() {
849
        let huge = "a".repeat(1_000_000);
850
        let nested = "(".repeat(10_000);
851
        for s in [
852
            "",
853
            " ",
854
            "\t\n",
855
            "https://example.com/",
856
            "not a url",
857
            "0",
858
            "-0",
859
            "NaN",
860
            "inf",
861
            "9223372036854775807",
862
            "\u{1F600}",
863
            "e\u{0301}",
864
            "\u{0}",
865
            huge.as_str(),
866
            nested.as_str(),
867
        ] {
868
            let e = Url::parse(s).expect_err("the stub must always fail");
869
            assert_eq!(e.message.as_str(), "url feature not enabled");
870
            assert_eq!(format!("{e}"), "url feature not enabled");
871
        }
872
    }
873

            
874
    #[cfg(not(feature = "url"))]
875
    #[test]
876
    fn stub_join_always_errors_for_every_base_and_path() {
877
        let huge = "b".repeat(1_000_000);
878
        let bases = [
879
            Url::default(),
880
            Url::from_parts("https", "example.com", 8080, "/a"),
881
            Url::from_parts("", "", 0, ""),
882
        ];
883
        for base in &bases {
884
            for path in ["", " ", "../..", "\u{1F600}", "x", huge.as_str()] {
885
                let e = base.join(path).expect_err("the stub must always fail");
886
                assert_eq!(e.message.as_str(), "url feature not enabled");
887
            }
888
            // The base must be left untouched by the failed join.
889
            assert_url_invariants(base);
890
        }
891
    }
892

            
893
    #[cfg(not(feature = "url"))]
894
    #[test]
895
    fn stub_parse_and_join_are_usable_in_const_context() {
896
        // Both stubs are `const fn`; evaluating them at compile time must not
897
        // trip a const-eval panic.
898
        const PARSED: Result<Url, UrlParseError> = Url::parse("https://example.com/");
899
        assert!(PARSED.is_err());
900
    }
901
}