~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
150 lines · 5.8 KB Raw History
import Foundation
import Testing

@testable import HydraulophoneCore

struct SearchScopeTests {
  // Synthetic, structural-only equivalents of the pinned AuraMusic search
  // renderer contract. All names, IDs, and params here are invented test data.
  @Test func searchDecodesArtistAndAlbumVariantsWithoutCollectingSubtitleLinks() throws {
    let artist = responsive("artist", type: "MUSIC_PAGE_TYPE_ARTIST", title: "Artist")
    let album = responsive("album", type: "MUSIC_PAGE_TYPE_ALBUM", title: "Album")
    let twoRow: [String: Any] = [
      "musicTwoRowItemRenderer": [
        "title": ["runs": [["text": "Second Album"]]],
        "navigationEndpoint": endpoint("second-album", type: "MUSIC_PAGE_TYPE_ALBUM"),
      ]
    ]
    let contents = [
      artist, album, twoRow, album, responsive("ignored", type: "UNKNOWN", title: "Unknown"),
    ]
    let initial = try JSONSerialization.data(withJSONObject: [
      "contents": [
        "tabbedSearchResultsRenderer": [
          "tabs": [
            [
              "tabRenderer": [
                "content": [
                  "sectionListRenderer": [
                    "contents": [
                      [
                        "musicShelfRenderer": [
                          "contents": contents,
                          "continuations": [
                            ["nextContinuationData": ["continuation": "opaque/next?="]]
                          ],
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ])
    let page = try CatalogResponseParser.searchPage(from: initial)
    #expect(page.items.map(\.id) == ["artist-artist", "album-album", "album-second-album"])
    #expect(page.next?.rawValue == "opaque/next?=")
    guard case .album(let value) = page.items[1] else {
      Issue.record("Missing album")
      return
    }
    #expect(value.params == "opaque=browse")
    #expect(value.artistReferences?.map(\.id) == ["linked-artist"])
    let continuation = try JSONSerialization.data(withJSONObject: [
      "continuationContents": [
        "musicShelfContinuation": ["contents": contents]
      ]
    ])
    #expect(
      try CatalogResponseParser.searchPage(from: continuation, continuation: true).items
        == page.items)
  }

  @Test func scopesPreserveOpaqueParametersAndKeepBothPlaylistKinds() {
    #expect(SearchParameters.value(for: .artists) == "EgWKAQIgAWoKEAkQChAFEAMQBA%3D%3D")
    #expect(SearchParameters.value(for: .albums) == "EgWKAQIYAWoKEAkQChAFEAMQBA%3D%3D")
    #expect(SearchParameters.value(for: .songs) == "EgWKAQIIAWoKEAkQBRAKEAMQBA%3D%3D")
    #expect(SearchParameters.value(for: .all) == nil)
    #expect(SearchParameters.value(for: .playlists) == nil)
    #expect(SearchScope.artists.includes(.artist(Artist(browseID: "a", title: "A"))))
    #expect(!SearchScope.albums.includes(.song(Song(id: "s", title: "S", artist: "A"))))
  }

  @Test func cachedSearchDoesNotReuseAnotherScopesPageOrCursor() async throws {
    let upstream = ScopedSearchFake()
    let cache = CachedMusicService(base: upstream)
    let artist = try await cache.searchPage(
      query: "query", scope: .artists, continuation: nil, policy: .cacheFirst)
    let album = try await cache.searchPage(
      query: "query", scope: .albums, continuation: nil, policy: .cacheFirst)
    _ = try await cache.searchPage(
      query: "query", scope: .artists, continuation: nil, policy: .cacheFirst)
    #expect(artist.items.map(\.id) == ["artist-a"])
    #expect(album.items.map(\.id) == ["album-b"])
    #expect(artist.next?.rawValue == "artists-next")
    #expect(album.next?.rawValue == "albums-next")
    #expect(await upstream.calls == [.artists, .albums])
    let offline = OfflineMusicService(upstream: cache, offlineOnly: true)
    await #expect(throws: OfflineModeError.self) {
      try await offline.searchPage(
        query: "query", scope: .artists, continuation: nil, policy: .cacheFirst)
    }
    #expect(await upstream.calls.count == 2)
  }

  private func endpoint(_ id: String, type: String) -> [String: Any] {
    [
      "browseEndpoint": [
        "browseId": id, "params": "opaque=browse",
        "browseEndpointContextSupportedConfigs": [
          "browseEndpointContextMusicConfig": ["pageType": type]
        ],
      ]
    ]
  }

  private func responsive(_ id: String, type: String, title: String) -> [String: Any] {
    [
      "musicResponsiveListItemRenderer": [
        "navigationEndpoint": endpoint(id, type: type),
        "flexColumns": [
          ["musicResponsiveListItemFlexColumnRenderer": ["text": ["runs": [["text": title]]]]],
          [
            "musicResponsiveListItemFlexColumnRenderer": [
              "text": [
                "runs": [
                  [
                    "text": "Artist",
                    "navigationEndpoint": endpoint("linked-artist", type: "MUSIC_PAGE_TYPE_ARTIST"),
                  ]
                ]
              ]
            ]
          ],
        ],
      ]
    ]
  }
}

private actor ScopedSearchFake: ScopedSearchMusicService {
  private(set) var calls: [SearchScope] = []
  func search(query: String) async throws -> [SearchResult] { [] }
  func playlists() async throws -> [Playlist] { [] }
  func tracks(in playlist: Playlist) async throws -> [Song] { [] }
  func stream(for song: Song) async throws -> URL {
    throw InnerTubeError.playbackUnavailable("Fixture")
  }
  func searchPage(
    query: String, scope: SearchScope, continuation: PaginationToken?, policy: CatalogLoadPolicy
  ) async throws -> Page<SearchResult> {
    calls.append(scope)
    let item: SearchResult =
      scope == .artists
      ? .artist(Artist(browseID: "a", title: "A")) : .album(Album(browseID: "b", title: "B"))
    return Page(items: [item], next: PaginationToken(rawValue: "\(scope.rawValue)-next"))
  }
}