tidal-player-api 1.3.4

Tidal HTTP API client for tidal-player
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
//! Spec 0004, metadata over HTTP: AC17, AC27. No real network: a `wiremock`
//! server answers with the fixtures under `fixtures/metadata/`.

use std::sync::Arc;
use std::time::{Duration, SystemTime};

use serde_json::{Value, json};
use tidal_player_api::auth::{
    AuthConfig, AuthError, Authenticator, ManualClock, MemoryStore, Session, SessionStore,
};
use tidal_player_api::metadata::{MetadataClient, MetadataError};
use tidal_player_core::{AlbumRef, ArtistRef, Item, Track, TrackId};
use wiremock::matchers::{header, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

const TRACK: &str = include_str!("fixtures/metadata/track.json");
const TRACK_NO_ALLOW: &str = include_str!("fixtures/metadata/track_unstreamable_allow.json");
const TRACK_NO_READY: &str = include_str!("fixtures/metadata/track_unstreamable_ready.json");
const TRACK_NO_DURATION: &str = include_str!("fixtures/metadata/track_no_duration.json");
const TRACK_NO_ALBUM: &str = include_str!("fixtures/metadata/track_no_album.json");
const TRACK_VERSION: &str = include_str!("fixtures/metadata/track_version.json");
const ALBUM_PAGE: &str = include_str!("fixtures/metadata/album_page.json");
const PLAYLIST_PAGE: &str = include_str!("fixtures/metadata/playlist_page_with_video.json");
const RADIO_PAGE: &str = include_str!("fixtures/metadata/radio_page.json");
const TRACK_404: &str = include_str!("fixtures/metadata/error_track_not_found_2001.json");
const ALBUM_404: &str = include_str!("fixtures/metadata/error_album_not_found_2001.json");
const PLAYLIST_404: &str = include_str!("fixtures/metadata/error_playlist_not_found_2001.json");
const RADIO_404: &str = include_str!("fixtures/metadata/error_radio_not_found_2001.json");
const SERVER_500: &str = include_str!("fixtures/metadata/error_server_500.json");
const TOKEN_401: &str = include_str!("fixtures/auth/api_unauthorized.json");
const INVALID_GRANT: &str = include_str!("fixtures/auth/refresh_invalid_grant.json");

const UUID: &str = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d";

fn t0() -> SystemTime {
    SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000)
}

/// Valid for an hour, in Finland.
fn session() -> Session {
    Session {
        access_token: "FAKE-ACCESS".into(),
        refresh_token: "FAKE-REFRESH".into(),
        expires_at: t0() + Duration::from_secs(3600),
        user_id: 1,
        country_code: "FI".into(),
    }
}

fn json_body(status: u16, body: &str) -> ResponseTemplate {
    ResponseTemplate::new(status).set_body_raw(body.to_owned(), "application/json")
}

struct Setup {
    server: MockServer,
    client: MetadataClient,
}

impl Setup {
    async fn new() -> Self {
        let server = MockServer::start().await;
        let store = Arc::new(MemoryStore::default());
        store.save(&session()).unwrap();
        let config = AuthConfig::with_bases(
            format!("{}/oauth2", server.uri()),
            format!("{}/v1", server.uri()),
        );
        let clock = Arc::new(ManualClock::new(t0()));
        let auth = Authenticator::new(config, store, session(), clock).unwrap();
        let client = MetadataClient::new(Arc::new(auth));
        Self { server, client }
    }

    /// The `(path, sorted query)` of every request received, in order.
    async fn requests(&self) -> Vec<(String, Vec<(String, String)>)> {
        self.server
            .received_requests()
            .await
            .unwrap()
            .iter()
            .map(|r| {
                let mut query: Vec<(String, String)> = r
                    .url
                    .query_pairs()
                    .map(|(k, v)| (k.into_owned(), v.into_owned()))
                    .collect();
                query.sort();
                (r.url.path().to_owned(), query)
            })
            .collect()
    }
}

fn query(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
    let mut v: Vec<(String, String)> = pairs
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    v.sort();
    v
}

fn fixture(text: &str) -> Value {
    serde_json::from_str(text).unwrap()
}

/// `n` bare tracks with IDs `first..first + n`, cloned from `track.json`.
fn tracks(first: u64, n: u64) -> Vec<Value> {
    (first..first + n)
        .map(|id| {
            let mut t = fixture(TRACK);
            t["id"] = json!(id);
            t["title"] = json!(format!("Track {id}"));
            t
        })
        .collect()
}

fn page(total: u64, offset: u64, items: Vec<Value>) -> String {
    json!({"limit": 100, "offset": offset, "totalNumberOfItems": total, "items": items}).to_string()
}

fn ids(tracks: &[Track]) -> Vec<u64> {
    tracks.iter().map(|t| t.id.0).collect()
}

fn artist(id: u64, name: &str) -> ArtistRef {
    ArtistRef {
        id,
        name: name.into(),
    }
}

fn artist_a() -> ArtistRef {
    artist(3001, "Artist A")
}

fn track_one() -> Track {
    Track {
        id: TrackId(1001),
        title: "Track One".into(),
        version: None,
        artists: vec![artist_a(), artist(3002, "Artist B")],
        album: Some(AlbumRef {
            id: 2001,
            title: "Album One".into(),
            cover: Some("00000000-0000-4000-8000-000000000002".into()),
        }),
        duration: Some(Duration::from_secs(291)),
        streamable: true,
    }
}

/// Spec 0006 AC2: artist and album IDs come from `artists[].id` (or the
/// lone `artist`) and `album.id`; `album: null` is `None`; `version` is
/// kept.
#[tokio::test]
async fn ac2_track_refs() {
    let rows: [(&str, &str, Track); 4] = [
        ("two artists, an album", TRACK, track_one()),
        (
            "album null",
            TRACK_NO_ALBUM,
            Track {
                id: TrackId(1005),
                title: "Track Five".into(),
                album: None,
                ..track_one()
            },
        ),
        (
            "a version",
            TRACK_VERSION,
            Track {
                id: TrackId(1006),
                title: "Track Six".into(),
                version: Some("Instrumental".into()),
                ..track_one()
            },
        ),
        (
            "only the lone artist",
            &{
                let mut t = fixture(TRACK);
                t["artists"] = json!([]);
                t.to_string()
            },
            Track {
                artists: vec![artist_a()],
                ..track_one()
            },
        ),
    ];
    for (name, body, want) in rows {
        let s = Setup::new().await;
        Mock::given(method("GET"))
            .and(path(format!("/v1/tracks/{}", want.id.0)))
            .respond_with(json_body(200, body))
            .mount(&s.server)
            .await;
        let got = s.client.get_track(want.id).await.unwrap();
        let refs = |t: &Track| {
            (
                t.artists.iter().map(|a| a.id).collect::<Vec<_>>(),
                t.album.as_ref().map(|a| a.id),
            )
        };
        assert_eq!(refs(&got), refs(&want), "{name}: IDs");
        assert_eq!(got, want, "{name}");
    }

    // Pages map their tracks the same way.
    let s = Setup::new().await;
    Mock::given(method("GET"))
        .and(path("/v1/albums/9/tracks"))
        .respond_with(json_body(200, ALBUM_PAGE))
        .mount(&s.server)
        .await;
    let got = s.client.get_album_tracks(9).await.unwrap();
    for t in &got {
        assert_eq!(t.artists, [artist_a()], "album track {}", t.id);
        assert_eq!(
            t.album.as_ref().map(|a| a.id),
            Some(2001),
            "album track {}",
            t.id
        );
    }
}

const COVER: &str = "00000000-0000-4000-8000-000000000002";

/// Spec 0010 AC18: the album's `cover` ID is kept on tracks from a single
/// track, an album page and a playlist page (favorites and search are
/// covered by the full-equality tables in `library.rs` and `search.rs`); a
/// `null` or absent `cover` is `None`.
#[tokio::test]
async fn ac18_cover() {
    let mut null = fixture(TRACK);
    null["album"]["cover"] = Value::Null;
    let mut absent = fixture(TRACK);
    absent["album"].as_object_mut().unwrap().remove("cover");
    let rows = [
        ("a cover", TRACK.to_owned(), Some(COVER)),
        ("cover null", null.to_string(), None),
        ("no cover key", absent.to_string(), None),
    ];
    for (name, body, want) in rows {
        let s = Setup::new().await;
        Mock::given(method("GET"))
            .and(path("/v1/tracks/1001"))
            .respond_with(json_body(200, &body))
            .mount(&s.server)
            .await;
        let got = s.client.get_track(TrackId(1001)).await.unwrap();
        let cover = got.album.and_then(|a| a.cover);
        assert_eq!(cover.as_deref(), want, "{name}");
    }

    for (name, route, body) in [
        ("album page", "/v1/albums/9/tracks", ALBUM_PAGE),
        ("playlist page", "/v1/playlists/p/items", PLAYLIST_PAGE),
    ] {
        let s = Setup::new().await;
        Mock::given(method("GET"))
            .and(path(route))
            .respond_with(json_body(200, body))
            .mount(&s.server)
            .await;
        let got = if route.contains("albums") {
            s.client.get_album_tracks(9).await.unwrap()
        } else {
            s.client.get_playlist_tracks("p").await.unwrap()
        };
        assert!(!got.is_empty(), "{name}");
        for t in &got {
            let cover = t.album.as_ref().and_then(|a| a.cover.as_deref());
            assert_eq!(cover, Some(COVER), "{name}: track {}", t.id);
        }
    }
}

#[tokio::test]
async fn ac17_get_track() {
    let rows: [(&str, &str, Track); 4] = [
        ("full", TRACK, track_one()),
        (
            "allowStreaming false",
            TRACK_NO_ALLOW,
            Track {
                id: TrackId(1002),
                title: "Track Two".into(),
                artists: vec![artist_a()],
                streamable: false,
                ..track_one()
            },
        ),
        (
            "streamReady false",
            TRACK_NO_READY,
            Track {
                id: TrackId(1003),
                title: "Track Three".into(),
                artists: vec![artist_a()],
                streamable: false,
                ..track_one()
            },
        ),
        (
            "no duration",
            TRACK_NO_DURATION,
            Track {
                id: TrackId(1004),
                title: "Track Four".into(),
                artists: vec![artist_a()],
                duration: None,
                ..track_one()
            },
        ),
    ];
    for (name, body, want) in rows {
        let s = Setup::new().await;
        let p = format!("/v1/tracks/{}", want.id.0);
        Mock::given(method("GET"))
            .and(path(p))
            .and(query_param("countryCode", "FI"))
            .and(header("authorization", "Bearer FAKE-ACCESS"))
            .respond_with(json_body(200, body))
            .expect(1)
            .mount(&s.server)
            .await;

        let got = s.client.get_track(want.id).await;

        assert_eq!(got, Ok(want.clone()), "{name}");
        assert_eq!(
            s.requests().await,
            [(
                format!("/v1/tracks/{}", want.id.0),
                query(&[("countryCode", "FI")])
            )],
            "{name}: one request, only countryCode"
        );
        s.server.verify().await;
    }
}

#[tokio::test]
async fn ac17_album_pages() {
    // (name, total, page sizes served in order, expected request offsets)
    let rows: [(&str, u64, &[u64], &[u64]); 4] = [
        ("one page", 3, &[3], &[0]),
        ("250 items", 250, &[100, 100, 50], &[0, 100, 200]),
        ("100 items is one page", 100, &[100], &[0]),
        ("empty page ends the walk", 250, &[100, 0], &[0, 100]),
    ];
    for (name, total, sizes, offsets) in rows {
        let s = Setup::new().await;
        let mut served = 0;
        for (i, size) in sizes.iter().enumerate() {
            let offset = offsets[i];
            let body = if name == "one page" {
                ALBUM_PAGE.to_owned()
            } else {
                page(total, offset, tracks(2000 + offset, *size))
            };
            served += size;
            Mock::given(method("GET"))
                .and(path("/v1/albums/77/tracks"))
                .and(query_param("offset", offset.to_string()))
                .respond_with(json_body(200, &body))
                .expect(1)
                .mount(&s.server)
                .await;
        }

        let got = s.client.get_album_tracks(77).await.unwrap();

        assert_eq!(got.len() as u64, served, "{name}: every item returned");
        let expected: Vec<u64> = if name == "one page" {
            vec![1001, 1002, 1003]
        } else {
            sizes
                .iter()
                .zip(offsets)
                .flat_map(|(n, o)| 2000 + o..2000 + o + n)
                .collect()
        };
        assert_eq!(ids(&got), expected, "{name}: in order");
        let want: Vec<_> = offsets
            .iter()
            .map(|o| {
                (
                    "/v1/albums/77/tracks".to_owned(),
                    query(&[
                        ("countryCode", "FI"),
                        ("limit", "100"),
                        ("offset", &o.to_string()),
                    ]),
                )
            })
            .collect();
        assert_eq!(s.requests().await, want, "{name}: requests");
        s.server.verify().await;
    }
}

fn playlist_item(track: Value) -> Value {
    json!({"item": track, "type": "track", "cut": null})
}

#[tokio::test]
async fn ac17_playlist_pages_and_videos() {
    // One page with a video among the tracks: the video is dropped.
    let s = Setup::new().await;
    let p = format!("/v1/playlists/{UUID}/items");
    Mock::given(method("GET"))
        .and(path(p.clone()))
        .and(query_param("countryCode", "FI"))
        .and(query_param("limit", "100"))
        .and(query_param("offset", "0"))
        .respond_with(json_body(200, PLAYLIST_PAGE))
        .expect(1)
        .mount(&s.server)
        .await;
    let got = s.client.get_playlist_tracks(UUID).await.unwrap();
    assert_eq!(ids(&got), [1001, 1002, 1003], "video left out, order kept");
    let mut first = track_one();
    first.artists = vec![artist_a()];
    first.title = "Track One".into();
    first.duration = Some(Duration::from_secs(200));
    assert_eq!(got[0], first, "mapped as a bare track");
    s.server.verify().await;

    // 250 entries over three pages, the video entries counting towards the
    // total and the offset but not the result.
    let s = Setup::new().await;
    let mut entries: Vec<Value> = tracks(3000, 250).into_iter().map(playlist_item).collect();
    for i in [5, 150, 249] {
        entries[i] = json!({"item": {"id": 9000 + i, "album": null}, "type": "video", "cut": null});
    }
    for (offset, chunk) in entries.chunks(100).enumerate() {
        Mock::given(method("GET"))
            .and(path(p.clone()))
            .and(query_param("offset", (offset * 100).to_string()))
            .respond_with(json_body(
                200,
                &page(250, offset as u64 * 100, chunk.to_vec()),
            ))
            .expect(1)
            .mount(&s.server)
            .await;
    }
    let got = s.client.get_playlist_tracks(UUID).await.unwrap();
    let expected: Vec<u64> = (3000..3250)
        .filter(|id| ![3005, 3150, 3249].contains(id))
        .collect();
    assert_eq!(ids(&got), expected, "tracks of all pages, videos dropped");
    let offsets: Vec<String> = s
        .requests()
        .await
        .into_iter()
        .map(|(p, q)| {
            assert!(q.contains(&("limit".into(), "100".into())), "{p} {q:?}");
            q.into_iter().find(|(k, _)| k == "offset").unwrap().1
        })
        .collect();
    assert_eq!(offsets, ["0", "100", "200"]);
    s.server.verify().await;

    // An empty page ends the walk before totalNumberOfItems.
    let s = Setup::new().await;
    Mock::given(method("GET"))
        .and(path(p.clone()))
        .and(query_param("offset", "0"))
        .respond_with(json_body(
            200,
            &page(
                500,
                0,
                tracks(4000, 2).into_iter().map(playlist_item).collect(),
            ),
        ))
        .expect(1)
        .mount(&s.server)
        .await;
    Mock::given(method("GET"))
        .and(path(p))
        .and(query_param("offset", "2"))
        .respond_with(json_body(200, &page(500, 2, vec![])))
        .expect(1)
        .mount(&s.server)
        .await;
    let got = s.client.get_playlist_tracks(UUID).await.unwrap();
    assert_eq!(ids(&got), [4000, 4001]);
    assert_eq!(s.requests().await.len(), 2);
    s.server.verify().await;
}

#[tokio::test]
async fn ac17_errors() {
    #[derive(Clone, Copy)]
    enum Call {
        Track,
        Album,
        Playlist,
    }
    let playlist_path = format!("/v1/playlists/{UUID}/items");
    let rows: Vec<(&str, Call, String, u16, &str, MetadataError)> = vec![
        (
            "track 404",
            Call::Track,
            "/v1/tracks/1".into(),
            404,
            TRACK_404,
            MetadataError::NotFound(Item::Track(TrackId(1))),
        ),
        (
            "album 404",
            Call::Album,
            "/v1/albums/1/tracks".into(),
            404,
            ALBUM_404,
            MetadataError::NotFound(Item::Album(1)),
        ),
        (
            "playlist 404",
            Call::Playlist,
            playlist_path.clone(),
            404,
            PLAYLIST_404,
            MetadataError::NotFound(Item::Playlist(UUID.into())),
        ),
        (
            "track 500",
            Call::Track,
            "/v1/tracks/1".into(),
            500,
            SERVER_500,
            MetadataError::Auth(AuthError::Http {
                status: 500,
                code: None,
            }),
        ),
        (
            "album 429",
            Call::Album,
            "/v1/albums/1/tracks".into(),
            429,
            "{}",
            MetadataError::Auth(AuthError::Http {
                status: 429,
                code: None,
            }),
        ),
        (
            "playlist 404 without a subStatus",
            Call::Playlist,
            playlist_path,
            404,
            "{}",
            MetadataError::Auth(AuthError::Http {
                status: 404,
                code: None,
            }),
        ),
        (
            "track 200 with a bad body",
            Call::Track,
            "/v1/tracks/1".into(),
            200,
            "{\"nope\":1}",
            MetadataError::Malformed("track"),
        ),
    ];
    for (name, call, p, status, body, want) in rows {
        let s = Setup::new().await;
        Mock::given(method("GET"))
            .and(path(p))
            .respond_with(json_body(status, body))
            .expect(1)
            .mount(&s.server)
            .await;
        let got = match call {
            Call::Track => s.client.get_track(TrackId(1)).await.map(|_| ()),
            Call::Album => s.client.get_album_tracks(1).await.map(|_| ()),
            Call::Playlist => s.client.get_playlist_tracks(UUID).await.map(|_| ()),
        };
        assert_eq!(got, Err(want), "{name}");
        s.server.verify().await;
    }

    // The not-found message names the item.
    assert_eq!(
        MetadataError::NotFound(Item::Album(1)).to_string(),
        "Album 1 was not found"
    );
}

#[tokio::test]
async fn ac17_login_required() {
    // The access token is rejected and the refresh is refused: LoginRequired,
    // after which no metadata request is made.
    let s = Setup::new().await;
    Mock::given(method("GET"))
        .and(path("/v1/tracks/1"))
        .respond_with(json_body(401, TOKEN_401))
        .mount(&s.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/oauth2/token"))
        .respond_with(json_body(400, INVALID_GRANT))
        .mount(&s.server)
        .await;
    let got = s.client.get_track(TrackId(1)).await;
    assert_eq!(got, Err(MetadataError::Auth(AuthError::LoginRequired)));
    let again = s.client.get_album_tracks(1).await;
    assert_eq!(again, Err(MetadataError::Auth(AuthError::LoginRequired)));
}

#[tokio::test]
async fn ac27_suggestions() {
    // The seed comes back first and stays.
    let s = Setup::new().await;
    Mock::given(method("GET"))
        .and(path("/v1/tracks/1001/radio"))
        .and(query_param("countryCode", "FI"))
        .and(query_param("limit", "100"))
        .and(header("authorization", "Bearer FAKE-ACCESS"))
        .respond_with(json_body(200, RADIO_PAGE))
        .expect(1)
        .mount(&s.server)
        .await;
    let got = s.client.get_suggestions(TrackId(1001)).await.unwrap();
    assert_eq!(ids(&got), [1001, 1011, 1012], "in order, seed included");
    assert_eq!(got[0], track_one());
    assert_eq!(got[1].album_title(), Some("Album Two"));
    assert_eq!(
        s.requests().await,
        [(
            "/v1/tracks/1001/radio".to_owned(),
            query(&[("countryCode", "FI"), ("limit", "100")])
        )],
        "exactly one request"
    );
    s.server.verify().await;

    // Errors.
    let rows: [(&str, u16, &str, Result<usize, MetadataError>); 3] = [
        ("404 2001 is an empty list", 404, RADIO_404, Ok(0)),
        (
            "500 is unchanged",
            500,
            SERVER_500,
            Err(MetadataError::Auth(AuthError::Http {
                status: 500,
                code: None,
            })),
        ),
        (
            "429 is unchanged",
            429,
            "{}",
            Err(MetadataError::Auth(AuthError::Http {
                status: 429,
                code: None,
            })),
        ),
    ];
    for (name, status, body, want) in rows {
        let s = Setup::new().await;
        Mock::given(method("GET"))
            .and(path("/v1/tracks/1/radio"))
            .respond_with(json_body(status, body))
            .expect(1)
            .mount(&s.server)
            .await;
        let got = s.client.get_suggestions(TrackId(1)).await.map(|t| t.len());
        assert_eq!(got, want, "{name}");
        s.server.verify().await;
    }

    // LoginRequired is returned unchanged.
    let s = Setup::new().await;
    Mock::given(method("GET"))
        .and(path("/v1/tracks/1/radio"))
        .respond_with(json_body(401, TOKEN_401))
        .mount(&s.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/oauth2/token"))
        .respond_with(json_body(400, INVALID_GRANT))
        .mount(&s.server)
        .await;
    let got = s.client.get_suggestions(TrackId(1)).await;
    assert_eq!(got, Err(MetadataError::Auth(AuthError::LoginRequired)));
}