// Cotton Cinemas' intake on the phone: the folder walk names each film by its// path, the files go to the core two hundred at a time with what Cotton asks// (`onlyFilms`), and what came in says where to land. Every file here is// invented: empty bytes under a film's name, never a real film.importCottonMailboximportFoundationimport XCTest@testable importCottonKitfinalclassFilmIntakeTests: XCTestCase {privatevar folder: URL!overridefunc setUpWithError() throws { folder = FileManager.default.temporaryDirectory.appendingPathComponent("film-intake-\(UUID().uuidString)", isDirectory: true)tryFileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) }overridefunc tearDownWithError() throws {try? FileManager.default.removeItem(at: folder) }/// The facts a test reads: the path alone, as an MKV's are.privatestaticlet pathOnly: FilmIntake.Reading = { file, _ inFilmFacts(path: file.url.path(percentEncoded: false), sourcePath: file.sourcePath) }// RULE (Cinemas definition, 5 Nov 2026): a folder is walked whole, deepest too, each film named by its path under the folder picked — the series, its season and the episode's own name — and nothing that is no film's container, nor a hidden file, comes in.func testAFolderIsWalkedWholeAndEachFilmNamedByItsPath() throws {let season = folder.appendingPathComponent("Synthetic Serial/Season 02", isDirectory: true)tryFileManager.default.createDirectory(at: season, withIntermediateDirectories: true)for name in ["S02E05 - The Long Night.mkv", "S02E06.mp4", "S02E05 - The Long Night.srt", ".hidden.mkv", "poster.jpg"] {tryData("x".utf8).write(to: season.appendingPathComponent(name)) }tryData("x".utf8).write(to: folder.appendingPathComponent("Synthetic Test Pattern (2019).avi"))let found = FilmIntake.films(in: folder, named: "Films") XCTAssertEqual(found.map(\.sourcePath), ["Films/Synthetic Serial/Season 02/S02E05 - The Long Night.mkv","Films/Synthetic Serial/Season 02/S02E06.mp4","Films/Synthetic Test Pattern (2019).avi", ]) }// RULE: the containers the drain takes for films are the core's own (`cotton_core::films::VIDEO_EXTENSIONS`), said once in each language and held equal here.func testTheFilmContainersAreTheCoresOwn() throws {let rust = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("../../../../crates/cotton-core/src/films/mod.rs")let source = tryString(contentsOf: rust.standardizedFileURL, encoding: .utf8)let line = try XCTUnwrap(source.split(separator: "\n").first { $0.contains("pub const VIDEO_EXTENSIONS") })let named = line.split(separator: "=").last.map { $0.split(separator: "\"").enumerated().filter { $0.offset % 2 == 1 }.map { String($0.element) } } ?? [] XCTAssertFalse(named.isEmpty) XCTAssertEqual(Set(named), filmFileExtensions) }// RULE (Cinemas definition, 5 Nov 2026): the core takes at most two hundred files a capture, so a big folder goes in turns, in its order, each turn asking what the drain asked (`onlyFilms`), the deck told how far it has got; past one turn the words count every film that came in.func testABigFolderGoesInTurnsOfTwoHundred() asyncthrows {let files = (1 ... 450).map { FilmFile(url: folder.appendingPathComponent("\($0).mkv"), sourcePath: "Films/\($0).mkv") }let core = ScriptedCore([CottonMethod.filmsCapture: .ok(#"{"films":[{"sourcePath":"x","outcome":"added","id":"f","table":"film","title":"x","line":"x"}],"said":"one turn"}"#)])let told = Told()let intake = FilmIntake(core: core, read: Self.pathOnly) { done, total, reading in told.add(done, total, reading) }let result = tryawait intake.bring(files, onlyFilms: true)let calls = await core.calls XCTAssertEqual(calls.map(\.method), Array(repeating: CottonMethod.filmsCapture, count: 3))structAsked: Decodable { structFilm: Decodable { let sourcePath: String }; let films: [Film]; let onlyFilms: Bool }let asked = try calls.map { try JSONDecoder().decode(Asked.self, from: Data($0.requestJSON.utf8)) } XCTAssertEqual(asked.map(\.films.count), [200, 200, 50]) XCTAssertEqual(asked.flatMap(\.films).map(\.sourcePath), files.map(\.sourcePath)) XCTAssertTrue(asked.allSatisfy(\.onlyFilms)) XCTAssertEqual(told.said.map(\.done), [0, 200, 400, 450]) XCTAssertEqual(told.said.map(\.reading), [true, false, false, false]) XCTAssertEqual(result.said, ShellLines.line("cinemas", "intake.added_many", ["count": "3"])) XCTAssertEqual(FilmIntake.batches(Array(files.prefix(200))).count, 1) }// RULE (open standards, 7 Nov 2026): a film from a folder hands the core every name beside it, each NFO's text and each subtitle's and picture's path, so a sidecar the core names is never missing; an episode in a season's folder hands its series' folder too, and a file the core reads as no episode never does.func testAFolderHandsTheCoreWhatLiesBesideEachFilm() asyncthrows {let film = folder.appendingPathComponent("Night Ferry (2019)", isDirectory: true)let season = folder.appendingPathComponent("Lowmarsh/Season 01", isDirectory: true)for directory in [film, season] { tryFileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) }let invented: [(URL, String)] = [ (film, "Night Ferry (2019).mkv"), (film, "Night Ferry (2019).nfo"), (film, "poster.jpg"), (film, "Night Ferry (2019).en.srt"), (film, "notes.txt"), (film, ".hidden.srt"), (season.deletingLastPathComponent(), "tvshow.nfo"), (season.deletingLastPathComponent(), "poster.png"), (season, "S01E01 - Pilot.mkv"), (season, "S01E01 - Pilot.nfo"), (season, "S01E02.mp4"), (season, "S01E02.nfo"), (season, "Making of.mkv"), ]for (directory, name) in invented {tryData("<movie><title>Invented ‘\(name)’</title></movie>".utf8).write(to: directory.appendingPathComponent(name)) }let found = FilmIntake.films(in: folder, named: "Films") XCTAssertEqual(found.map(\.sourcePath), ["Films/Lowmarsh/Season 01/Making of.mkv","Films/Lowmarsh/Season 01/S01E01 - Pilot.mkv","Films/Lowmarsh/Season 01/S01E02.mp4","Films/Night Ferry (2019)/Night Ferry (2019).mkv", ])let ferry = try XCTUnwrap(found.last?.beside) XCTAssertEqual(ferry.siblings, ["Night Ferry (2019).en.srt", "Night Ferry (2019).mkv", "Night Ferry (2019).nfo", "notes.txt", "poster.jpg"]) XCTAssertEqual(ferry.nfos, ["Night Ferry (2019).nfo": "<movie><title>Invented ‘Night Ferry (2019).nfo’</title></movie>"]) XCTAssertEqual(Set(ferry.files.keys), ["Night Ferry (2019).en.srt", "poster.jpg"]) XCTAssertEqual(ferry.files["poster.jpg"].map { URL(fileURLWithPath: $0).standardizedFileURL }, film.appendingPathComponent("poster.jpg").standardizedFileURL) XCTAssertNil(found.last?.seriesBeside, "a film has no series") XCTAssertNil(found.first?.seriesBeside, "the core reads Making of as no episode, and would refuse a series folder with it")for episode in found[1 ... 2] { XCTAssertEqual(Set(try XCTUnwrap(episode.beside).nfos.keys), ["S01E01 - Pilot.nfo", "S01E02.nfo"])let series = try XCTUnwrap(episode.seriesBeside, episode.sourcePath) XCTAssertEqual(series.siblings, ["Season 01", "poster.png", "tvshow.nfo"]) XCTAssertEqual(Array(series.nfos.keys), ["tvshow.nfo"]) XCTAssertEqual(Array(series.files.keys), ["poster.png"]) }// The hand-in: `films.capture` takes each file's folders as the core names them.let core = ScriptedCore([CottonMethod.filmsCapture: .ok(#"{"films":[],"said":null}"#)]) _ = tryawaitFilmIntake(core: core, read: Self.pathOnly).bring(found, onlyFilms: false)let calls = await core.callslet asked = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(try XCTUnwrap(calls.first).requestJSON.utf8)) as? [String: Any])let films = try XCTUnwrap(asked["films"] as? [[String: Any]])let pilot = films[1] XCTAssertEqual(Set((pilot["beside"] as? [String: Any] ?? [:]).keys), ["siblings", "nfos", "files"]) XCTAssertEqual(((pilot["seriesBeside"] as? [String: Any])?["nfos"] as? [String: String])?.keys.first, "tvshow.nfo") XCTAssertNil(films[0]["seriesBeside"]) XCTAssertNil(films[3]["seriesBeside"]) }// RULE: an NFO is read whole only while it is an NFO's size (a few kilobytes of XML): a file past `nfoMostBytes` under that name is left unread, never read into memory whole.func testAnNFOPastItsSizeIsLeftUnread() throws {tryData("<movie><title>Invented</title></movie>".utf8).write(to: folder.appendingPathComponent("small.nfo"))tryData(repeating: 0x20, count: FilmSidecars.nfoMostBytes + 1).write(to: folder.appendingPathComponent("huge.nfo"))tryData(repeating: 0x20, count: FilmSidecars.nfoMostBytes).write(to: folder.appendingPathComponent("edge.nfo"))let beside = FilmSidecars.folder(at: folder) XCTAssertEqual(beside.nfos["small.nfo"], "<movie><title>Invented</title></movie>") XCTAssertNil(beside.nfos["huge.nfo"], "past the size, no NFO") XCTAssertEqual(beside.nfos["edge.nfo"]?.utf8.count, FilmSidecars.nfoMostBytes, "at the size, read whole") XCTAssertTrue(beside.siblings.contains("huge.nfo"), "still named beside the film") }// RULE: the phone reads a path as an episode exactly as the core does (`from_path`, held to the shared `film_names.json`), and its sidecars' containers, skipped folders and release words are the core's own.func testThePhoneReadsAnEpisodeAsTheCoreDoes() throws {let fixtures = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("../../../../crates/cotton-core/tests/fixtures").standardizedFileURLstructName: Decodable { structExpect: Decodable { let kind: String }; let path: String; let expect: Expect? }let names = try JSONDecoder().decode([Name].self, from: Data(contentsOf: fixtures.appendingPathComponent("film_names.json"))) XCTAssertFalse(names.isEmpty)for name in names { XCTAssertEqual(FilmPathRule.isEpisode(name.path), name.expect?.kind == "episode", name.path) } XCTAssertFalse(FilmPathRule.isEpisode("Season 02/S02E05.mkv"), "a season's folder alone names no series") XCTAssertFalse(FilmPathRule.isEpisode("Lowmarsh/Season 02/Behind the curtain.mkv")) XCTAssertTrue(FilmPathRule.isEpisode("Lowmarsh/Season 02/05.mkv"))structLists: Decodable { let subtitle_extensions: [String]; let art_extensions: [String] }structSidecars: Decodable { let lists: Lists }let lists = try JSONDecoder().decode(Sidecars.self, from: Data(contentsOf: fixtures.appendingPathComponent("film_sidecars.json"))).lists XCTAssertEqual(FilmSidecars.subtitleExtensions, Set(lists.subtitle_extensions)) XCTAssertEqual(FilmSidecars.artExtensions, Set(lists.art_extensions))let rust = tryString(contentsOf: fixtures.appendingPathComponent("../../src/films/mod.rs").standardizedFileURL, encoding: .utf8)func named(_ constant: String) throws -> Set<String> {let start = try XCTUnwrap(rust.range(of: "const \(constant)"))letopen = try XCTUnwrap(rust.range(of: "= [", range: start.upperBound ..< rust.endIndex))let list = rust[open.upperBound...].prefix { $0 != "]" }returnSet(list.split(separator: "\"", omittingEmptySubsequences: false).enumerated().filter { $0.offset % 2 == 1 }.map { String($0.element) }) } XCTAssertEqual(FilmPathRule.skippedFolders, try named("SKIPPED_FOLDERS")) XCTAssertEqual(FilmPathRule.releaseWords, try named("RELEASE_WORDS")) }// RULE: what came in says where to land — the last film or episode added, else the last already here — and only where the core named its table; an episode lands on its series, a film row Cinemas' views draw; Cotton's clips the core said are no films are named for Photos.func testWhatCameInSaysWhereToLand() {let result = FilmIntakeResult(outcomes: [FilmOutcome(outcome: "here", sourcePath: "a.mkv", id: "f-old", table: "film"),FilmOutcome(outcome: "added", sourcePath: "S01E01.mkv", id: "e-1", table: "film_episode", series: "s-1"),FilmOutcome(outcome: "added", sourcePath: "S01E02.mkv", id: "e-2"),FilmOutcome(outcome: "not_film", sourcePath: "IMG_0042.mp4"),FilmOutcome(outcome: "refused", sourcePath: "locked.m4v"), ], said: nil) XCTAssertEqual(result.landing?.table, "film") XCTAssertEqual(result.landing?.id, "s-1")let unnamed = FilmIntakeResult(outcomes: [FilmOutcome(outcome: "added", id: "e-1", table: "film_episode")], said: nil) XCTAssertEqual(unnamed.landing?.table, "film_episode", "an episode whose series the core did not name opens itself") XCTAssertEqual(result.notFilms, ["IMG_0042.mp4"]) XCTAssertEqual(FilmIntakeResult(outcomes: [FilmOutcome(outcome: "worse", id: "f-1", table: "film")], said: nil).landing?.id, "f-1") XCTAssertNil(FilmIntakeResult(outcomes: [FilmOutcome(outcome: "refused")], said: nil).landing) }// RULE: the deck says "Reading 12 files" until the first are in, then "41 of 212".func testTheDecksLineWhileFilmsComeIn() { XCTAssertEqual(FilmIntakeProgress.line(0, of: 12, reading: true), ShellLines.line("cinemas", "intake.reading", ["count": "12"])) XCTAssertEqual(FilmIntakeProgress.line(41, of: 212, reading: false), "41 of 212") }// RULE: a codec is named by its four characters as AVFoundation says them, and a tag's year is the four digits its date begins with.func testCodecsAndYearsAreReadAsTheCoreTakesThem() { XCTAssertEqual(FilmFactsReader.fourCC(0x6176_6331), "avc1") XCTAssertEqual(FilmFactsReader.fourCC(0x6D70_3461), "mp4a") XCTAssertEqual(FilmFactsReader.year("2019-05-01T00:00:00Z"), "2019") XCTAssertNil(FilmFactsReader.year("May 2019")) }// RULE: an MKV or an AVI, which AVFoundation cannot open, is sent by its path alone: nothing guessed.func testAnMKVIsSentByItsPathAlone() asyncthrows {let mkv = folder.appendingPathComponent("The Long Night (2019).mkv")tryData("not a film".utf8).write(to: mkv)let facts = awaitFilmFactsReader.read(FilmFile(url: mkv, sourcePath: "The Long Night (2019).mkv"), folder) XCTAssertEqual(facts, FilmFacts(path: mkv.path(percentEncoded: false), sourcePath: "The Long Night (2019).mkv")) }}/// How far an intake said it had got, in order.privatefinalclassTold: @unchecked Sendable {privatelet lock = NSLock()privatevar all: [(done: Int, total: Int, reading: Bool)] = []var said: [(done: Int, total: Int, reading: Bool)] { lock.withLock { all } }func add(_ done: Int, _ total: Int, _ reading: Bool) { lock.withLock { all.append((done, total, reading)) } }}