uv 0.11.12

A Python package and project manager
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
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
use assert_cmd::assert::OutputAssertExt;
use assert_fs::fixture::{FileTouch, FileWriteStr, PathChild};
use fs_err::OpenOptions;
use indoc::{formatdoc, indoc};
use serde_json::json;
use sha2::{Digest, Sha256};
use std::env::current_dir;
use std::io::Write;
use std::path::{Path, PathBuf};
use uv_static::EnvVars;
use uv_test::{uv_snapshot, venv_bin_path};
use wiremock::matchers::{basic_auth, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn dummy_wheel() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .join("test/links/ok-1.0.0-py3-none-any.whl")
}

#[test]
fn username_password_no_longer_supported() {
    let context = uv_test::test_context!("3.12");

    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg(dummy_wheel()), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to https://test.pypi.org/legacy/
      Caused by: Server returned status code 403 Forbidden. Server says: 403 Username/Password authentication is no longer supported. Migrate to API Tokens or Trusted Publishers instead. See https://test.pypi.org/help/#apitoken and https://test.pypi.org/help/#trusted-publishers
    "
    );
}

#[test]
fn invalid_token() {
    let context = uv_test::test_context!("3.12");

    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("__token__")
        .arg("-p")
        .arg("dummy")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg(dummy_wheel()), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to https://test.pypi.org/legacy/
      Caused by: Server returned status code 403 Forbidden. Server says: 403 Invalid or non-existent authentication information. See https://test.pypi.org/help/#invalid-auth for more information.
    "
    );
}

/// Emulate a missing `permission` `id-token: write` situation.
#[test]
fn mixed_credentials() {
    let context = uv_test::test_context!("3.12");

    uv_snapshot!(context.filters(), context.publish()
        .arg("--username")
        .arg("ferris")
        .arg("--password")
        .arg("ZmVycmlz")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg("--trusted-publishing")
        .arg("always")
        .arg(dummy_wheel())
        // Emulate CI
        .env(EnvVars::GITHUB_ACTIONS, "true"), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/
    error: a username and a password are not allowed when using trusted publishing
    "
    );
}

/// Emulate a missing `permission` `id-token: write` situation.
#[test]
fn missing_trusted_publishing_permission() {
    let context = uv_test::test_context!("3.12");

    uv_snapshot!(context.filters(), context.publish()
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg("--trusted-publishing")
        .arg("always")
        .arg(dummy_wheel())
        // Emulate CI
        .env(EnvVars::GITHUB_ACTIONS, "true"), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/
    error: Failed to obtain token for trusted publishing
      Caused by: Failed to obtain OIDC token: is the `id-token: write` permission missing?
      Caused by: GitHub Actions detection error
      Caused by: insufficient permissions: missing ACTIONS_ID_TOKEN_REQUEST_URL
    "
    );
}

/// Check the error when there are no credentials provided on GitHub Actions. Is it an incorrect
/// trusted publishing configuration?
#[test]
fn no_credentials() {
    let context = uv_test::test_context!("3.12");

    uv_snapshot!(context.filters(), context.publish()
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg(dummy_wheel())
        // Emulate CI
        .env(EnvVars::GITHUB_ACTIONS, "true"), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/
    Note: Neither credentials nor keyring are configured, and there was an error fetching the trusted publishing token. If you don't want to use trusted publishing, you can ignore this error, but you need to provide credentials.
    error: Trusted publishing failed
      Caused by: Failed to obtain OIDC token: is the `id-token: write` permission missing?
      Caused by: GitHub Actions detection error
      Caused by: insufficient permissions: missing ACTIONS_ID_TOKEN_REQUEST_URL
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to https://test.pypi.org/legacy/
      Caused by: Failed to send POST request
      Caused by: Missing credentials for https://test.pypi.org/legacy/
    "
    );
}

/// Hint people that it's not `--skip-existing` but `--check-url`.
#[test]
fn skip_existing_redirect() {
    let context = uv_test::test_context!("3.12");

    uv_snapshot!(context.filters(), context.publish()
        .arg("--skip-existing")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/"), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: `uv publish` does not support `--skip-existing` because there is not a reliable way to identify when an upload fails due to an existing distribution. Instead, use `--check-url` to provide the URL to the simple API for your index. uv will check the index for existing distributions before attempting uploads.
    "
    );
}

#[test]
fn dubious_filenames() {
    let context = uv_test::test_context!("3.12");

    context.temp_dir.child("not-a-wheel.whl").touch().unwrap();
    context.temp_dir.child("data.tar.gz").touch().unwrap();
    context
        .temp_dir
        .child("not-sdist-1-2-3-asdf.zip")
        .touch()
        .unwrap();

    uv_snapshot!(context.filters(), context.publish()
        .current_dir(current_dir().unwrap())
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg(context.temp_dir.join("*")), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    warning: Skipping file that looks like a distribution, but is not a valid distribution filename: `[TEMP_DIR]/data.tar.gz`
    warning: Skipping file that looks like a distribution, but is not a valid distribution filename: `[TEMP_DIR]/not-a-wheel.whl`
    warning: Skipping file that looks like a distribution, but is not a valid distribution filename: `[TEMP_DIR]/not-sdist-1-2-3-asdf.zip`
    error: No files found to publish
    "
    );
}

/// Check that we (don't) use the keyring and warn for missing keyring behaviors correctly.
#[test]
fn check_keyring_behaviours() {
    let context = uv_test::test_context!("3.12");

    // Install our keyring plugin
    context
        .pip_install()
        .arg(
            context
                .workspace_root
                .join("test")
                .join("packages")
                .join("keyring_test_plugin"),
        )
        .assert()
        .success();

    // Ok: The keyring may be used for the index page.
    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--keyring-provider")
        .arg("subprocess")
        .arg("--check-url")
        .arg("https://test.pypi.org/simple/")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/?ok")
        .arg(dummy_wheel())
        .env(EnvVars::PATH, venv_bin_path(&context.venv)), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/?ok
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to https://test.pypi.org/legacy/?ok
      Caused by: Server returned status code 403 Forbidden. Server says: 403 Username/Password authentication is no longer supported. Migrate to API Tokens or Trusted Publishers instead. See https://test.pypi.org/help/#apitoken and https://test.pypi.org/help/#trusted-publishers
    "
    );

    // Warn: The keyring is unused.
    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--keyring-provider")
        .arg("subprocess")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/?ok")
        .arg(dummy_wheel())
        .env(EnvVars::PATH, venv_bin_path(&context.venv)),  @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/?ok
    warning: Using `--keyring-provider` with a password or token and no check URL has no effect
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to https://test.pypi.org/legacy/?ok
      Caused by: Server returned status code 403 Forbidden. Server says: 403 Username/Password authentication is no longer supported. Migrate to API Tokens or Trusted Publishers instead. See https://test.pypi.org/help/#apitoken and https://test.pypi.org/help/#trusted-publishers
    "
    );

    // Warn: There is no keyring entry for the user dummy.
    // https://github.com/astral-sh/uv/issues/7963#issuecomment-2453558043
    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("dummy")
        .arg("--keyring-provider")
        .arg("subprocess")
        .arg("--check-url")
        .arg("https://test.pypi.org/simple/")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/?ok")
        .arg(dummy_wheel())
        .env(EnvVars::PATH, venv_bin_path(&context.venv)), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/?ok
    Keyring request for dummy@https://test.pypi.org/legacy/?ok
    Keyring request for dummy@test.pypi.org
    warning: Keyring has no password for URL `https://test.pypi.org/legacy/?ok` and username `dummy`
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    Keyring request for dummy@https://test.pypi.org/legacy/?ok
    Keyring request for dummy@test.pypi.org
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to https://test.pypi.org/legacy/?ok
      Caused by: Server returned status code 403 Forbidden. Server says: 403 Username/Password authentication is no longer supported. Migrate to API Tokens or Trusted Publishers instead. See https://test.pypi.org/help/#apitoken and https://test.pypi.org/help/#trusted-publishers
    "
    );

    // Ok: There is a keyring entry for the user dummy.
    // https://github.com/astral-sh/uv/issues/7963#issuecomment-2453558043
    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("dummy")
        .arg("--keyring-provider")
        .arg("subprocess")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/?ok")
        .arg(dummy_wheel())
        .env(EnvVars::KEYRING_TEST_CREDENTIALS, r#"{"https://test.pypi.org/legacy/?ok": {"dummy": "dummy"}}"#)
        .env(EnvVars::PATH, venv_bin_path(&context.venv)), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/?ok
    Keyring request for dummy@https://test.pypi.org/legacy/?ok
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to https://test.pypi.org/legacy/?ok
      Caused by: Server returned status code 403 Forbidden. Server says: 403 Username/Password authentication is no longer supported. Migrate to API Tokens or Trusted Publishers instead. See https://test.pypi.org/help/#apitoken and https://test.pypi.org/help/#trusted-publishers
    "
    );
}

#[test]
fn invalid_index() {
    let context = uv_test::test_context!("3.12");

    let pyproject_toml = indoc! {r#"
        [project]
        name = "foo"
        version = "0.1.0"

        [[tool.uv.index]]
        explicit = true
        name = "foo"
        url = "https://example.com"

        [[tool.uv.index]]
        name = "internal"
        url = "https://internal.example.org"
    "#};
    context
        .temp_dir
        .child("pyproject.toml")
        .write_str(pyproject_toml)
        .unwrap();

    let ok_wheel = current_dir()
        .unwrap()
        .join("../../test/links/ok-1.0.0-py3-none-any.whl");

    // No such index
    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("__token__")
        .arg("-p")
        .arg("dummy")
        .arg("--index")
        .arg("bar")
        .arg(&ok_wheel)
        .current_dir(context.temp_dir.path()), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Index not found: `bar`. Found indexes: `foo`, `internal`
    "
    );

    // Index does not have a publish URL
    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("__token__")
        .arg("-p")
        .arg("dummy")
        .arg("--index")
        .arg("foo")
        .arg(&ok_wheel)
        .current_dir(context.temp_dir.path()), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Index is missing a publish URL: `foo`
    "
    );
}

/// Ensure that we read index credentials from the environment when publishing.
///
/// <https://github.com/astral-sh/uv/issues/11836#issuecomment-3022735011>
#[tokio::test]
async fn read_index_credential_env_vars_for_check_url() {
    let context = uv_test::test_context!("3.12");

    let server = MockServer::start().await;

    context
        .init()
        .arg("--name")
        .arg("astral-test-private")
        .arg(".")
        .assert()
        .success();

    context.build().arg("--wheel").assert().success();

    let mut file = OpenOptions::new()
        .write(true)
        .append(true)
        .create(false)
        .open(context.temp_dir.join("pyproject.toml"))
        .unwrap();
    file.write_all(
        formatdoc! {
            r#"
            [[tool.uv.index]]
            name = "private-index"
            url = "{index_uri}/simple/"
            publish-url = "{index_uri}/upload"
            "#,
            index_uri = server.uri()
        }
        .as_bytes(),
    )
    .unwrap();

    let filename = "astral_test_private-0.1.0-py3-none-any.whl";
    let wheel = context.temp_dir.join("dist").join(filename);
    let sha256 = format!("{:x}", Sha256::digest(fs_err::read(&wheel).unwrap()));

    let simple_index = json! ({
          "files": [
            {
              "filename": filename,
              "hashes": {
                "sha256": sha256
              },
              "url": format!("{}/{}", server.uri(), filename),
            }
        ]
    });
    Mock::given(method("GET"))
        .and(path("/simple/astral-test-private/"))
        .and(basic_auth("username", "secret"))
        .respond_with(ResponseTemplate::new(200).set_body_raw(
            simple_index.to_string().into_bytes(),
            "application/vnd.pypi.simple.v1+json",
        ))
        .mount(&server)
        .await;

    // Test that we fail without credentials
    uv_snapshot!(context.filters(), context.publish()
        .arg(&wheel)
        .arg("--index")
        .arg("private-index")
        .arg("--trusted-publishing")
        .arg("never"),
        @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to http://[LOCALHOST]/upload
    Hashing astral_test_private-0.1.0-py3-none-any.whl ([SIZE])
    Uploading astral_test_private-0.1.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `dist/astral_test_private-0.1.0-py3-none-any.whl` to http://[LOCALHOST]/upload
      Caused by: Failed to send POST request
      Caused by: Missing credentials for http://[LOCALHOST]/upload
    "
    );
    // Test that it works with credentials
    uv_snapshot!(context.filters(), context.publish()
        .arg(&wheel)
        .arg("--index")
        .arg("private-index")
        .env(EnvVars::index_username("PRIVATE_INDEX"), "username")
        .env(EnvVars::index_password("PRIVATE_INDEX"), "secret")
        .arg("--trusted-publishing")
        .arg("never"),
        @"
    success: true
    exit_code: 0
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to http://[LOCALHOST]/upload
    File astral_test_private-0.1.0-py3-none-any.whl already exists, skipping
    "
    );
}

/// Native GitLab CI trusted publishing using `PYPI_ID_TOKEN`
#[tokio::test]
async fn gitlab_trusted_publishing_pypi_id_token() {
    let context = uv_test::test_context!("3.12");

    let server = MockServer::start().await;

    // Audience endpoint (PyPI)
    Mock::given(method("GET"))
        .and(path("/_/oidc/audience"))
        .respond_with(
            ResponseTemplate::new(200).set_body_raw("{\"audience\":\"pypi\"}", "application/json"),
        )
        .mount(&server)
        .await;

    // Mint token endpoint returns a short-lived API token
    Mock::given(method("POST"))
        .and(path("/_/oidc/mint-token"))
        .respond_with(
            ResponseTemplate::new(200).set_body_raw("{\"token\":\"apitoken\"}", "application/json"),
        )
        .mount(&server)
        .await;

    // Upload endpoint requires the minted token as Basic auth
    Mock::given(method("POST"))
        .and(path("/upload"))
        .and(basic_auth("__token__", "apitoken"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&server)
        .await;

    uv_snapshot!(context.filters(), context.publish()
        .arg("--trusted-publishing")
        .arg("always")
        .arg("--publish-url")
        .arg(format!("{}/upload", server.uri()))
        .arg(dummy_wheel())
        .env(EnvVars::GITLAB_CI, "true")
        .env(EnvVars::PYPI_ID_TOKEN, "gitlab-oidc-jwt"), @"
    success: true
    exit_code: 0
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to http://[LOCALHOST]/upload
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    "
    );
}

/// Native GitLab CI trusted publishing using `TESTPYPI_ID_TOKEN`
#[tokio::test]
async fn gitlab_trusted_publishing_testpypi_id_token() {
    let context = uv_test::test_context!("3.12");

    let server = MockServer::start().await;

    // Audience endpoint (TestPyPI)
    Mock::given(method("GET"))
        .and(path("/_/oidc/audience"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_raw("{\"audience\":\"testpypi\"}", "application/json"),
        )
        .mount(&server)
        .await;

    // Mint token endpoint returns a short-lived API token
    Mock::given(method("POST"))
        .and(path("/_/oidc/mint-token"))
        .respond_with(
            ResponseTemplate::new(200).set_body_raw("{\"token\":\"apitoken\"}", "application/json"),
        )
        .mount(&server)
        .await;

    // Upload endpoint requires the minted token as Basic auth
    Mock::given(method("POST"))
        .and(path("/upload"))
        .and(basic_auth("__token__", "apitoken"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&server)
        .await;

    uv_snapshot!(context.filters(), context.publish()
        .arg("--trusted-publishing")
        .arg("always")
        .arg("--publish-url")
        .arg(format!("{}/upload", server.uri()))
        .arg(dummy_wheel())
        // Emulate GitLab CI with TESTPYPI_ID_TOKEN present
        .env(EnvVars::GITLAB_CI, "true")
        .env(EnvVars::TESTPYPI_ID_TOKEN, "gitlab-oidc-jwt"), @"
    success: true
    exit_code: 0
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to http://[LOCALHOST]/upload
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    "
    );
}

#[tokio::test]
async fn direct_publish_redacts_presigned_upload_url() {
    let context = uv_test::test_context!("3.12");
    let server = MockServer::start().await;

    let upload_url = format!(
        "{}/s3/ok-1.0.0-py3-none-any.whl?X-Amz-Credential=credential&X-Amz-Signature=signature&X-Amz-Security-Token=token",
        server.uri()
    );

    Mock::given(method("POST"))
        .and(path("/upload/reserve"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "upload_url": upload_url,
        })))
        .mount(&server)
        .await;
    Mock::given(method("PUT"))
        .and(path("/s3/ok-1.0.0-py3-none-any.whl"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/upload/finalize"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&server)
        .await;

    uv_snapshot!(context.filters(), context.publish()
        .arg("--preview-features")
        .arg("direct-publish")
        .arg("--direct")
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--publish-url")
        .arg(format!("{}/upload", server.uri()))
        .arg(dummy_wheel())
        .env(EnvVars::RUST_LOG, "uv_publish=debug"), @"
    success: true
    exit_code: 0
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to http://[LOCALHOST]/upload
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    DEBUG Hashing [WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    DEBUG Reserving upload slot at http://[LOCALHOST]/upload/reserve
    DEBUG Using HTTP Basic authentication
    DEBUG Got pre-signed URL for upload: http://[LOCALHOST]/s3/ok-1.0.0-py3-none-any.whl?X-Amz-Credential=****&X-Amz-Signature=****&X-Amz-Security-Token=****
    DEBUG S3 upload complete for ok-1.0.0-py3-none-any.whl
    DEBUG Finalizing upload at http://[LOCALHOST]/upload/finalize
    DEBUG Using HTTP Basic authentication
    DEBUG Response code for http://[LOCALHOST]/upload/finalize: 200 OK
    DEBUG Upload finalized for ok-1.0.0-py3-none-any.whl
    "
    );
}

/// PyPI returns `application/json` errors with a `code` field.
#[tokio::test]
async fn upload_error_pypi_json() {
    let context = uv_test::test_context!("3.12");
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(400).set_body_raw(
            r#"{"message": "Error", "code": "400 Use 'source' as Python version for an sdist.", "title": "Bad Request"}"#,
            "application/json",
        ))
        .mount(&server)
        .await;

    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--publish-url")
        .arg(format!("{}/upload", server.uri()))
        .arg(dummy_wheel()), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to http://[LOCALHOST]/upload
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to http://[LOCALHOST]/upload
      Caused by: Server returned status code 400 Bad Request. Server says: 400 Use 'source' as Python version for an sdist.
    "
    );
}

/// pyx returns `application/problem+json` errors with RFC 9457 Problem Details.
#[tokio::test]
async fn upload_error_problem_details() {
    let context = uv_test::test_context!("3.12");
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(400).set_body_raw(
            r#"{"type": "about:blank", "status": 400, "title": "Bad Request", "detail": "Missing required field `name`"}"#,
            "application/problem+json",
        ))
        .mount(&server)
        .await;

    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--publish-url")
        .arg(format!("{}/upload", server.uri()))
        .arg(dummy_wheel()), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to http://[LOCALHOST]/upload
    Hashing ok-1.0.0-py3-none-any.whl ([SIZE])
    Uploading ok-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish `[WORKSPACE]/test/links/ok-1.0.0-py3-none-any.whl` to http://[LOCALHOST]/upload
      Caused by: Server returned status code 400 Bad Request. Server message: Bad Request, Missing required field `name`
    "
    );
}

/// Test that `--dry-run` checks all files and reports all errors instead of
/// stopping at the first failure.
#[test]
fn dry_run_reports_all_errors() {
    let context = uv_test::test_context!("3.12");

    // Create two fake wheel files that will fail metadata reading.
    let wheel_a = context.temp_dir.child("a-1.0.0-py3-none-any.whl");
    wheel_a.touch().unwrap();
    let wheel_b = context.temp_dir.child("b-1.0.0-py3-none-any.whl");
    wheel_b.touch().unwrap();

    uv_snapshot!(context.filters(), context.publish()
        .arg("--dry-run")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg("--token")
        .arg("dummy")
        .arg(wheel_a.path())
        .arg(wheel_b.path()), @"
    success: false
    exit_code: 1
    ----- stdout -----

    ----- stderr -----
    Checking 2 files against https://test.pypi.org/legacy/
    Checking a-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish: `a-1.0.0-py3-none-any.whl`
      Caused by: Failed to read metadata
      Caused by: Failed to read from zip file
      Caused by: unable to locate the end of central directory record
    Checking b-1.0.0-py3-none-any.whl ([SIZE])
    error: Failed to publish: `b-1.0.0-py3-none-any.whl`
      Caused by: Failed to read metadata
      Caused by: Failed to read from zip file
      Caused by: unable to locate the end of central directory record
    Found issues with 2 files
    "
    );
}

/// Warn when a wheel has a non-normalized filename (e.g., leading zeros in version).
#[test]
fn non_normalized_filename_warning() {
    let context = uv_test::test_context!("3.12");

    // Create a wheel file with a non-normalized version (leading zero: 1.01.0 -> 1.1.0).
    let wheel = context.temp_dir.child("ok-1.01.0-py3-none-any.whl");
    wheel.touch().unwrap();

    uv_snapshot!(context.filters(), context.publish()
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg(wheel.path()), @"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/
    warning: `ok-1.01.0-py3-none-any.whl` has a non-normalized filename (expected `ok-1.1.0-py3-none-any.whl`). Pass `--preview-features publish-require-normalized` to skip such files.
    Hashing ok-1.1.0-py3-none-any.whl ([SIZE])
    error: Failed to publish: `ok-1.01.0-py3-none-any.whl`
      Caused by: Failed to read metadata
      Caused by: Failed to read from zip file
      Caused by: unable to locate the end of central directory record
    "
    );
}

/// With the preview flag, skip wheels with non-normalized filenames.
#[test]
fn non_normalized_filename_skip() {
    let context = uv_test::test_context!("3.12");

    // Create a wheel file with a non-normalized version.
    let wheel = context.temp_dir.child("ok-1.01.0-py3-none-any.whl");
    wheel.touch().unwrap();

    uv_snapshot!(context.filters(), context.publish()
        .arg("--preview-features")
        .arg("publish-require-normalized")
        .arg("-u")
        .arg("dummy")
        .arg("-p")
        .arg("dummy")
        .arg("--publish-url")
        .arg("https://test.pypi.org/legacy/")
        .arg(wheel.path()), @"
    success: true
    exit_code: 0
    ----- stdout -----

    ----- stderr -----
    Publishing 1 file to https://test.pypi.org/legacy/
    warning: `ok-1.01.0-py3-none-any.whl` has a non-normalized filename (expected `ok-1.1.0-py3-none-any.whl`), skipping
    "
    );
}