// 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.
import CottonMailbox
import Foundation
import XCTest
@testable import CottonKit
final class FilmIntakeTests: XCTestCase {
private var folder: URL!
override func setUpWithError() throws {
folder = FileManager.default.temporaryDirectory.appendingPathComponent("film-intake-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
}
override func tearDownWithError() throws {
try? FileManager.default.removeItem(at: folder)
}
/// The facts a test reads: the path alone, as an MKV's are.
private static let pathOnly: FilmIntake.Reading = { file, _ in
FilmFacts(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)
try FileManager.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"] {
try Data("x".utf8).write(to: season.appendingPathComponent(name))
}
try Data("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 = try String(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() async throws {
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 = try await intake.bring(files, onlyFilms: true)
let calls = await core.calls
XCTAssertEqual(calls.map(\.method), Array(repeating: CottonMethod.filmsCapture, count: 3))
struct Asked: Decodable { struct Film: 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() async throws {
let film = folder.appendingPathComponent("Night Ferry (2019)", isDirectory: true)
let season = folder.appendingPathComponent("Lowmarsh/Season 01", isDirectory: true)
for directory in [film, season] { try FileManager.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 {
try Data("Invented ‘\(name)’".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": "Invented ‘Night Ferry (2019).nfo’"])
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}"#)])
_ = try await FilmIntake(core: core, read: Self.pathOnly).bring(found, onlyFilms: false)
let calls = await core.calls
let 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 {
try Data("Invented".utf8).write(to: folder.appendingPathComponent("small.nfo"))
try Data(repeating: 0x20, count: FilmSidecars.nfoMostBytes + 1).write(to: folder.appendingPathComponent("huge.nfo"))
try Data(repeating: 0x20, count: FilmSidecars.nfoMostBytes).write(to: folder.appendingPathComponent("edge.nfo"))
let beside = FilmSidecars.folder(at: folder)
XCTAssertEqual(beside.nfos["small.nfo"], "Invented")
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").standardizedFileURL
struct Name: Decodable { struct Expect: 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"))
struct Lists: Decodable { let subtitle_extensions: [String]; let art_extensions: [String] }
struct Sidecars: 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 = try String(contentsOf: fixtures.appendingPathComponent("../../src/films/mod.rs").standardizedFileURL, encoding: .utf8)
func named(_ constant: String) throws -> Set {
let start = try XCTUnwrap(rust.range(of: "const \(constant)"))
let open = try XCTUnwrap(rust.range(of: "= [", range: start.upperBound ..< rust.endIndex))
let list = rust[open.upperBound...].prefix { $0 != "]" }
return Set(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() async throws {
let mkv = folder.appendingPathComponent("The Long Night (2019).mkv")
try Data("not a film".utf8).write(to: mkv)
let facts = await FilmFactsReader.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.
private final class Told: @unchecked Sendable {
private let lock = NSLock()
private var 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)) } }
}