884 lines · 46.9 KB · RustRaw
//! `music-import`, end to end on synthetic files the test writes itself: tiny//! WAV, FLAC and MP3 streams of silence, tagged by lofty. No real music, and//! no network but a server inside the test.//!//! The folder walk and how files are named; the tags read; the same rows the//! phone's `music.capture` makes (artist, album, song, the cover, fill-only-//! empty); the duplicates by bytes and by song with the better file kept;//! and the HTTP the run speaks to the object.mod support;use std::fs;use std::path::{Path, PathBuf};use cotton_mac::music::import::{import_folder, Memory, Outcome, Report, ALBUM_TABLE, ARTIST_TABLE, LIST_TABLE, MEMBER_TABLE, SONG_TABLE};use cotton_mac::music::read::read_song;use cotton_mac::music::walk::{read, songs_in, CoverFrom};use cotton_mac::object::ObjectClient;use lofty::config::WriteOptions;use lofty::picture::{MimeType, Picture, PictureType};use lofty::prelude::*;use lofty::tag::{ItemKey, Tag, TagType};use serde_json::{json, Value};use support::{Answer, TestServer};const DB: &str = "00000000-0000-4000-8000-0000000000aa";const TODAY: &str = "2026-11-04";/// The first bytes of a JPEG, which is all a cover's kind is told by.const JPEG: &[u8] = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, b'J', b'F', b'I', b'F', 0x00, 0x01, 0x02, 0x03];// ── synthetic audio ─────────────────────────────────────────────────────────/// A mono 16-bit PCM WAV of `seconds` of silence at 8 kHz.fn wav(path: &Path, seconds: u32) { let rate = 8000u32; let data = rate * 2 * seconds; let mut bytes = Vec::new(); bytes.extend_from_slice(b"RIFF"); bytes.extend_from_slice(&(36 + data).to_le_bytes()); bytes.extend_from_slice(b"WAVEfmt "); bytes.extend_from_slice(&16u32.to_le_bytes()); bytes.extend_from_slice(&1u16.to_le_bytes()); // PCM bytes.extend_from_slice(&1u16.to_le_bytes()); // mono bytes.extend_from_slice(&rate.to_le_bytes()); bytes.extend_from_slice(&(rate * 2).to_le_bytes()); bytes.extend_from_slice(&2u16.to_le_bytes()); bytes.extend_from_slice(&16u16.to_le_bytes()); bytes.extend_from_slice(b"data"); bytes.extend_from_slice(&data.to_le_bytes()); bytes.resize(bytes.len() + data as usize, 0); write(path, &bytes);}/// A FLAC stream: its STREAMINFO saying `seconds` at 44.1 kHz, then `padding`/// bytes standing in for its frames (which set the bitrate lofty measures).fn flac(path: &Path, seconds: u64, padding: usize, salt: u8) { let rate: u64 = 44_100; let samples = rate * seconds; let mut info = Vec::new(); info.extend_from_slice(&4096u16.to_be_bytes()); info.extend_from_slice(&4096u16.to_be_bytes()); info.extend_from_slice(&[0, 0, 0, 0, 0, 0]); // 20 bits rate, 3 bits channels - 1 (stereo), 5 bits depth - 1 (16), 36 bits samples. let packed: u64 = (rate << 44) | (1 << 41) | (15 << 36) | samples; info.extend_from_slice(&packed.to_be_bytes()); info.extend_from_slice(&[salt; 16]); let mut bytes = b"fLaC".to_vec(); bytes.push(0x80); bytes.extend_from_slice(&(info.len() as u32).to_be_bytes()[1..]); bytes.extend_from_slice(&info); bytes.extend_from_slice(&[0xFF, 0xF8]); bytes.resize(bytes.len() + padding, salt); write(path, &bytes);}/// An MPEG-1 Layer III stream at 128 kbps, 44.1 kHz: `seconds` of frames.fn mp3(path: &Path, seconds: u32) { let frames = seconds * 44_100 / 1152 + 1; let mut bytes = Vec::new(); for _ in 0..frames { bytes.extend_from_slice(&[0xFF, 0xFB, 0x90, 0x64]); bytes.resize(bytes.len() + 413, 0); } write(path, &bytes);}fn write(path: &Path, bytes: &[u8]) { fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path, bytes).unwrap();}/// Tags written into a file by lofty, as a tagger would.fn tag(path: &Path, kind: TagType, fields: &[(ItemKey, &str)], cover: Option<&[u8]>) { let mut tag = Tag::new(kind); for (key, value) in fields { assert!(tag.insert_text(*key, value.to_string()), "{key:?} goes in a {kind:?} tag"); } if let Some(bytes) = cover { tag.push_picture(Picture::unchecked(bytes.to_vec()).pic_type(PictureType::CoverFront).mime_type(MimeType::Jpeg).build()); } tag.save_to_path(path, WriteOptions::default()).unwrap();}fn song_tags(title: &str, artist: &str, album: &str) -> Vec<(ItemKey, &'static str)> { vec![ (ItemKey::TrackTitle, leak(title)), (ItemKey::TrackArtist, leak(artist)), (ItemKey::AlbumTitle, leak(album)), ]}fn leak(text: &str) -> &'static str { Box::leak(text.to_string().into_boxed_str())}fn run(object: &Memory, folder: &Path) -> Report { let mut said: Vec<Outcome> = Vec::new(); let report = import_folder(object, folder, TODAY, &mut |outcome| said.push(outcome.clone())).unwrap(); assert_eq!(said, report.songs, "every file is told as it is answered"); report}fn outcomes(report: &Report) -> Vec<(&str, &str)> { report.songs.iter().map(|song| (song.outcome, song.source_path.as_str())).collect()}fn text<'a>(row: &'a serde_json::Map<String, Value>, key: &str) -> &'a str { row.get(key).and_then(Value::as_str).unwrap_or_default()}// ── the walk ────────────────────────────────────────────────────────────────#[test]fn a_folder_s_songs_are_found_to_the_bottom_and_named_under_the_folder_above() { let root = tempfile::tempdir().unwrap(); let artist = root.path().join("Lib/Ana Vell"); wav(&artist.join("Blue Hours (2001)/10 Ten.wav"), 1); wav(&artist.join("Blue Hours (2001)/2 Two.WAV"), 1); wav(&artist.join("Blue Hours (2001)/CD1/01 Deep.wav"), 1); wav(&artist.join("Blue Hours (2001)/.01 Hidden.wav"), 1); wav(&artist.join(".hidden/01 Away.wav"), 1); write(&artist.join("Blue Hours (2001)/notes.txt"), b"not a song"); write(&artist.join("Blue Hours (2001)/01 Ten.lrc"), b"[00:01.00]x"); let found: Vec<String> = songs_in(&artist).unwrap().into_iter().map(|found| found.source_path).collect(); assert_eq!( found, vec![ "Lib/Ana Vell/Blue Hours (2001)/2 Two.WAV", "Lib/Ana Vell/Blue Hours (2001)/10 Ten.wav", "Lib/Ana Vell/Blue Hours (2001)/CD1/01 Deep.wav", ] );}#[test]fn a_lrc_beside_a_file_is_its_timed_lyrics_and_the_folder_s_cover_its_picture() { let root = tempfile::tempdir().unwrap(); let album = root.path().join("Ana Vell/Blue Hours"); wav(&album.join("01 Morning.wav"), 1); write(&album.join("01 Morning.lrc"), b"[00:00.50]Wake\n[00:01.00]Up\n"); write(&album.join("folder.jpg"), JPEG); let found = songs_in(&album).unwrap(); let song = read(&found[0]); assert_eq!(song.tags.synced_lyrics.as_deref(), Some("[00:00.50]Wake\n[00:01.00]Up\n")); assert_eq!(song.tags.lyrics_beside, Some(true)); assert_eq!(song.cover, Some(CoverFrom::Folder(album.join("folder.jpg"))));}// ── the tags ────────────────────────────────────────────────────────────────#[test]fn every_whitelisted_field_is_read_from_a_flac() { let root = tempfile::tempdir().unwrap(); let path = root.path().join("song.flac"); flac(&path, 3, 400_000, 1); let lrc = "[00:00.50]One\n[00:01.00]Two"; tag( &path, TagType::VorbisComments, &[ (ItemKey::TrackTitle, "Morning"), (ItemKey::TrackArtist, "Ana Vell feat. Oru"), (ItemKey::AlbumTitle, "Blue Hours"), (ItemKey::AlbumArtist, "Ana Vell"), (ItemKey::TrackNumber, "3"), (ItemKey::DiscNumber, "1"), (ItemKey::DiscTotal, "2"), (ItemKey::RecordingDate, "2001-05-01"), (ItemKey::Genre, "Ambient"), (ItemKey::Composer, "Oru"), (ItemKey::FlagCompilation, "1"), (ItemKey::Lyrics, lrc), (ItemKey::ReplayGainTrackGain, "-6.54 dB"), (ItemKey::ReplayGainTrackPeak, "0.988"), (ItemKey::ReplayGainAlbumGain, "-7.10 dB"), (ItemKey::ReplayGainAlbumPeak, "0.999"), (ItemKey::Isrc, "ZZ0000000001"), (ItemKey::MusicBrainzRecordingId, "rec-1"), (ItemKey::MusicBrainzReleaseId, "rel-1"), (ItemKey::MusicBrainzReleaseGroupId, "grp-1"), (ItemKey::MusicBrainzArtistId, "art-1"), (ItemKey::MusicBrainzReleaseArtistId, "aart-1"), ], Some(JPEG), ); let read = read_song(&path).expect("lofty reads its own FLAC"); let tags = read.tags; assert!(read.embedded_cover); assert_eq!(tags.title.as_deref(), Some("Morning")); assert_eq!(tags.artist.as_deref(), Some("Ana Vell feat. Oru")); assert_eq!(tags.album.as_deref(), Some("Blue Hours")); assert_eq!(tags.album_artist.as_deref(), Some("Ana Vell")); assert_eq!((tags.track, tags.disc, tags.discs), (Some(3), Some(1), Some(2))); assert_eq!(tags.year.as_deref(), Some("2001")); assert_eq!(tags.genre.as_deref(), Some("Ambient")); assert_eq!(tags.composer.as_deref(), Some("Oru")); assert_eq!(tags.compilation, Some(true)); // A lyrics tag written as LRC is timed lyrics. assert_eq!(tags.synced_lyrics.as_deref(), Some(lrc)); assert_eq!(tags.lyrics, None); assert_eq!((tags.track_gain, tags.track_peak, tags.album_gain, tags.album_peak), (Some(-6.54), Some(0.988), Some(-7.1), Some(0.999))); assert_eq!(tags.isrc.as_deref(), Some("ZZ0000000001")); assert_eq!(tags.mb_recording.as_deref(), Some("rec-1")); assert_eq!(tags.mb_release.as_deref(), Some("rel-1")); assert_eq!(tags.mb_release_group.as_deref(), Some("grp-1")); assert_eq!(tags.mb_artist.as_deref(), Some("art-1")); assert_eq!(tags.mb_album_artist.as_deref(), Some("aart-1")); assert_eq!(tags.duration, Some(3.0)); assert_eq!(tags.sample_rate, Some(44_100)); assert!(tags.bitrate.is_some_and(|kbps| kbps > 900), "{:?}", tags.bitrate); assert_eq!(tags.lossless, None, "only an .m4a's box says its codec"); assert_eq!(cotton_mac::music::read::embedded_cover(&path).as_deref(), Some(JPEG));}#[test]fn an_r128_gain_reads_as_replaygain_decibels_and_plain_lyrics_stay_plain() { let root = tempfile::tempdir().unwrap(); let path = root.path().join("song.flac"); flac(&path, 2, 1000, 2); tag(&path, TagType::VorbisComments, &[(ItemKey::TrackTitle, "Night"), (ItemKey::R128TrackGain, "-512"), (ItemKey::R128AlbumGain, "256"), (ItemKey::Lyrics, "Hush now\nsleep")], None); let tags = read_song(&path).unwrap().tags; assert_eq!(tags.track_gain, Some(3.0)); assert_eq!(tags.album_gain, Some(6.0)); assert_eq!(tags.lyrics.as_deref(), Some("Hush now\nsleep")); assert_eq!(tags.synced_lyrics, None);}#[test]fn an_mp3_s_id3_tag_and_its_frames_are_read() { let root = tempfile::tempdir().unwrap(); let path = root.path().join("song.mp3"); mp3(&path, 2); tag(&path, TagType::Id3v2, &[(ItemKey::TrackTitle, "Morning"), (ItemKey::TrackArtist, "Ana Vell"), (ItemKey::TrackNumber, "4"), (ItemKey::UnsyncLyrics, "Words")], None); let tags = read_song(&path).unwrap().tags; assert_eq!(tags.title.as_deref(), Some("Morning")); assert_eq!(tags.track, Some(4)); assert_eq!(tags.lyrics.as_deref(), Some("Words")); assert_eq!(tags.bitrate, Some(128)); assert_eq!(tags.sample_rate, Some(44_100)); assert!(tags.duration.is_some_and(|seconds| (seconds - 2.0).abs() < 0.2), "{:?}", tags.duration);}/// Vorbis comments by their own names, as Picard writes them into a FLAC.fn vorbis(path: &Path, fields: &[(&str, &str)]) { let mut tag = lofty::ogg::tag::VorbisComments::new(); for (key, value) in fields { tag.push(key.to_string(), value.to_string()); } tag.save_to_path(path, WriteOptions::default()).unwrap();}/// RULE (open standards, 7 Nov 2026): the tags every tagger writes are read from Vorbis comments: sort names, ORIGINALDATE, LABEL, CATALOGNUMBER, BARCODE, RELEASETYPE and the release-track id, the recording id staying the recording's.#[test]fn a_picard_flac_says_its_release_its_sort_names_and_both_musicbrainz_ids() { let root = tempfile::tempdir().unwrap(); let path = root.path().join("song.flac"); flac(&path, 2, 1000, 3); vorbis( &path, &[ ("TITLE", "Low Tide"), ("ARTIST", "The Paper Lanterns"), ("ARTISTSORT", "Paper Lanterns, The"), ("ALBUMARTISTSORT", "Paper Lanterns, The"), ("ORIGINALDATE", "1971-05-01"), ("LABEL", "Paper Records"), ("CATALOGNUMBER", "PR-001"), ("BARCODE", "0123456789012"), ("RELEASETYPE", "album; live"), ("MUSICBRAINZ_TRACKID", "recording-1"), ("MUSICBRAINZ_RELEASETRACKID", "track-1"), ], ); let tags = read_song(&path).unwrap().tags; assert_eq!(tags.mb_recording.as_deref(), Some("recording-1"), "MUSICBRAINZ_TRACKID is the recording"); assert_eq!(tags.mb_release_track.as_deref(), Some("track-1")); assert_eq!(tags.artist_sort.as_deref(), Some("Paper Lanterns, The")); assert_eq!(tags.album_artist_sort.as_deref(), Some("Paper Lanterns, The")); assert_eq!(tags.original_date.as_deref(), Some("1971-05-01")); assert_eq!(tags.label.as_deref(), Some("Paper Records")); assert_eq!(tags.catalog_number.as_deref(), Some("PR-001")); assert_eq!(tags.barcode.as_deref(), Some("0123456789012")); assert_eq!(tags.release_type.as_deref(), Some("album; live"));}/// RULE (open standards, 7 Nov 2026): a file carrying only the release-track id has no recording id: the track id is never stored as the recording (the fallback read.rs had).#[test]fn a_release_track_id_alone_is_never_the_recording() { let root = tempfile::tempdir().unwrap(); let path = root.path().join("song.flac"); flac(&path, 2, 1000, 4); vorbis(&path, &[("TITLE", "Low Tide"), ("MUSICBRAINZ_RELEASETRACKID", "track-1")]); let tags = read_song(&path).unwrap().tags; assert_eq!(tags.mb_recording, None); assert_eq!(tags.mb_release_track.as_deref(), Some("track-1"));}/// RULE (open standards, 7 Nov 2026): the same fields from an ID3v2 tag as Picard writes it: UFID for the recording, TSOP, TSO2, TDOR, TPUB and TXXX CATALOGNUMBER, BARCODE, MusicBrainz Album Type and MusicBrainz Release Track Id.#[test]fn a_picard_mp3_says_the_same_from_its_frames() { use lofty::id3::v2::{ExtendedTextFrame, Frame, FrameId, Id3v2Tag, TextInformationFrame, UniqueFileIdentifierFrame}; use lofty::TextEncoding; let root = tempfile::tempdir().unwrap(); let path = root.path().join("song.mp3"); mp3(&path, 2); let mut tag = Id3v2Tag::new(); let text = |id: &'static str, value: &'static str| Frame::Text(TextInformationFrame::new(FrameId::new(id).unwrap(), TextEncoding::UTF8, value)); let user = |name: &'static str, value: &'static str| Frame::UserText(ExtendedTextFrame::new(TextEncoding::UTF8, name, value)); for frame in [ text("TIT2", "Low Tide"), text("TPE1", "The Paper Lanterns"), text("TSOP", "Paper Lanterns, The"), text("TSO2", "Paper Lanterns, The"), text("TDOR", "1971-05-01"), text("TPUB", "Paper Records"), user("CATALOGNUMBER", "PR-001"), user("BARCODE", "0123456789012"), user("MusicBrainz Album Type", "single"), user("MusicBrainz Release Track Id", "track-1"), Frame::UniqueFileIdentifier(UniqueFileIdentifierFrame::new("http://musicbrainz.org", b"recording-1".to_vec())), ] { tag.insert(frame); } tag.save_to_path(&path, WriteOptions::default()).unwrap(); let tags = read_song(&path).unwrap().tags; assert_eq!(tags.title.as_deref(), Some("Low Tide")); assert_eq!(tags.mb_recording.as_deref(), Some("recording-1"), "the UFID is the recording"); assert_eq!(tags.mb_release_track.as_deref(), Some("track-1")); assert_eq!(tags.artist_sort.as_deref(), Some("Paper Lanterns, The")); assert_eq!(tags.album_artist_sort.as_deref(), Some("Paper Lanterns, The")); assert_eq!(tags.original_date.as_deref().map(|date| &date[..4]), Some("1971")); assert_eq!(tags.label.as_deref(), Some("Paper Records")); assert_eq!(tags.catalog_number.as_deref(), Some("PR-001")); assert_eq!(tags.barcode.as_deref(), Some("0123456789012")); assert_eq!(tags.release_type.as_deref(), Some("single"));}/// RULE (open standards, 7 Nov 2026): the release facts land on the album, the release-track id on the song and the sort names on the artists, as the phone's capture writes them.#[test]fn the_release_facts_land_on_the_album_the_song_and_the_artists() { let root = tempfile::tempdir().unwrap(); let album = root.path().join("Lib/The Paper Lanterns/Harbour Lights"); let path = album.join("01 Low Tide.flac"); flac(&path, 2, 1000, 5); vorbis( &path, &[ ("TITLE", "Low Tide"), ("ARTIST", "The Paper Lanterns"), ("ALBUM", "Harbour Lights"), ("ALBUMARTIST", "The Paper Lanterns"), ("ARTISTSORT", "Paper Lanterns, The"), ("ALBUMARTISTSORT", "Paper Lanterns, The"), ("ORIGINALDATE", "1971"), ("LABEL", "Paper Records"), ("CATALOGNUMBER", "PR-001"), ("BARCODE", "0123456789012"), ("RELEASETYPE", "Compilation"), ("MUSICBRAINZ_TRACKID", "recording-1"), ("MUSICBRAINZ_RELEASETRACKID", "track-1"), ], ); let object = Memory::new(DB); run(&object, &root.path().join("Lib/The Paper Lanterns")); let albums = object.table(ALBUM_TABLE); let made = &albums[0]; assert_eq!( (text(made, "original_year"), text(made, "release_type"), text(made, "label"), text(made, "catalog_number"), text(made, "barcode")), ("1971", "compilation", "Paper Records", "PR-001", "0123456789012") ); let song = &object.table(SONG_TABLE)[0]; assert_eq!((text(song, "mb_recording"), text(song, "mb_release_track")), ("recording-1", "track-1")); let artists = object.table(ARTIST_TABLE); assert_eq!(artists.len(), 1); assert_eq!(text(&artists[0], "sort_name"), "Paper Lanterns, The");}// ── the rows ────────────────────────────────────────────────────────────────/// `Lib/Ana Vell/Blue Hours (2001)/`: a tagged FLAC with its own cover, an/// untagged WAV the folder names, and the folder's cover beside them.fn library(root: &Path) -> PathBuf { let album = root.join("Lib/Ana Vell/Blue Hours (2001)"); flac(&album.join("01 Morning.flac"), 3, 400_000, 1); let mut fields = song_tags("Morning", "Ana Vell feat. Oru", "Blue Hours"); fields.extend([(ItemKey::TrackNumber, "1"), (ItemKey::DiscTotal, "1"), (ItemKey::ReplayGainAlbumGain, "-7 dB")]); tag(&album.join("01 Morning.flac"), TagType::VorbisComments, &fields, Some(JPEG)); wav(&album.join("02 Night.wav"), 2); write(&album.join("cover.jpg"), &[JPEG, b"folder"].concat()); root.join("Lib/Ana Vell")}#[test]fn a_folder_makes_its_artist_its_album_and_its_songs_as_the_phone_does() { let root = tempfile::tempdir().unwrap(); let folder = library(root.path()); let object = Memory::new(DB); let report = run(&object, &folder); assert_eq!( outcomes(&report), vec![("added", "Lib/Ana Vell/Blue Hours (2001)/01 Morning.flac"), ("added", "Lib/Ana Vell/Blue Hours (2001)/02 Night.wav")] ); assert_eq!(report.said, "2 songs came in."); assert_eq!((report.albums_made, report.artists_made, report.covers_sent), (1, 1, 1)); let artists = object.table(ARTIST_TABLE); assert_eq!(artists.len(), 1, "the featured credit is its primary artist's song: {artists:?}"); assert_eq!((text(&artists[0], "name"), text(&artists[0], "sort_name")), ("Ana Vell", "Ana Vell")); let albums = object.table(ALBUM_TABLE); assert_eq!(albums.len(), 1); let album = &albums[0]; assert_eq!((text(album, "title"), text(album, "artist_name"), text(album, "year")), ("Blue Hours", "Ana Vell", "2001")); assert_eq!(text(album, "artist"), text(&artists[0], "id")); assert_eq!(album["discs"], json!(1)); assert_eq!(album["album_gain"], json!(-7.0)); assert_eq!(text(album, "added_on"), TODAY); // The first song's own picture is the album's cover, not the folder's. let cover = text(album, "cover"); assert_eq!(cover, format!("{DB}/photos/{}.jpg", cotton_mac::ids::sha256_hex(JPEG))); let songs = object.table(SONG_TABLE); let morning = &songs[0]; assert_eq!((text(morning, "title"), text(morning, "artist_name"), text(morning, "source")), ("Morning", "Ana Vell feat. Oru", "file")); assert_eq!((text(morning, "artist"), text(morning, "album")), (text(&artists[0], "id"), text(album, "id"))); assert_eq!((text(morning, "format"), morning["track_number"].clone(), morning["duration"].clone()), ("flac", json!(1), json!(3.0))); assert_eq!(text(morning, "path"), "Lib/Ana Vell/Blue Hours (2001)/01 Morning.flac"); assert_eq!(text(morning, "added_on"), TODAY); let (sha, _) = cotton_mac::ids::sha256_of_file(&folder.join("Blue Hours (2001)/01 Morning.flac")).unwrap(); assert_eq!(text(morning, "file"), format!("{DB}/music/{sha}.flac")); assert!(!morning.contains_key("album_title") && !morning.contains_key("cover") && !morning.contains_key("on_phone"), "computed and device-local columns are never written"); // The untagged file: its folder and its name say it. let night = &songs[1]; assert_eq!((text(night, "title"), text(night, "artist_name"), text(night, "source"), text(night, "format")), ("Night", "Ana Vell", "folder", "wav")); assert_eq!(night["track_number"], json!(2)); assert_eq!(text(night, "album"), text(album, "id")); let media = object.media.borrow(); assert_eq!(media.get(text(morning, "file")).map(|(_, kind)| kind.as_str()), Some("audio/flac")); assert_eq!(media.get(text(night, "file")).map(|(_, kind)| kind.as_str()), Some("audio/wav")); assert_eq!(media.get(cover).map(|(_, kind)| kind.as_str()), Some("image/jpeg")); drop(media); // The bytes go up before the rows that name them. let writes = object.writes.borrow().clone(); let at = |line: &str| writes.iter().position(|write| write.starts_with(line)).unwrap(); assert!(at(&format!("put {DB}/music/{sha}")) < at("create artist")); assert!(at(&format!("put {DB}/photos/")) < at("create music_album"));}#[test]fn a_second_run_finds_every_song_here_and_writes_nothing() { let root = tempfile::tempdir().unwrap(); let folder = library(root.path()); let object = Memory::new(DB); run(&object, &folder); let before = object.writes.borrow().len(); let again = run(&object, &folder); assert_eq!(again.songs.iter().map(|song| song.outcome).collect::<Vec<_>>(), vec!["here", "here"]); assert_eq!(again.songs[0].line, "Morning is already here."); assert_eq!(object.writes.borrow().len(), before);}#[test]fn the_same_bytes_twice_in_one_folder_are_one_song() { let root = tempfile::tempdir().unwrap(); let album = root.path().join("Ana Vell/Blue Hours"); wav(&album.join("01 Morning.wav"), 1); fs::copy(album.join("01 Morning.wav"), album.join("01 Morning copy.wav")).unwrap(); let object = Memory::new(DB); let report = run(&object, &album); assert_eq!(report.songs.iter().map(|song| song.outcome).collect::<Vec<_>>(), vec!["added", "here"]); assert_eq!(object.table(SONG_TABLE).len(), 1);}#[test]fn the_same_song_in_a_lossless_file_takes_the_lossy_one_s_place_and_a_lossy_one_is_not_kept() { let root = tempfile::tempdir().unwrap(); let object = Memory::new(DB); // First the MP3 alone. let first = root.path().join("one/Ana Vell/Blue Hours"); mp3(&first.join("01 Morning.mp3"), 3); tag(&first.join("01 Morning.mp3"), TagType::Id3v2, &song_tags("Morning", "Ana Vell", "Blue Hours"), None); let report = run(&object, &first); assert_eq!(report.songs[0].outcome, "added"); let mp3_key = report.songs[0].key.clone().unwrap(); let id = report.songs[0].id.clone().unwrap(); // Then the same song as FLAC, a second shorter: the better file. let second = root.path().join("two/Ana Vell/Blue Hours"); flac(&second.join("01 Morning.flac"), 2, 300_000, 3); tag(&second.join("01 Morning.flac"), TagType::VorbisComments, &song_tags("morning ", "ANA VELL", "blue hours"), None); let report = run(&object, &second); let better = &report.songs[0]; assert_eq!((better.outcome, better.id.as_deref(), better.replaced.as_deref()), ("better", Some(id.as_str()), Some(mp3_key.as_str()))); assert_eq!(better.line, "Kept the better file of morning. The MP3 it replaced can go."); let songs = object.table(SONG_TABLE); assert_eq!(songs.len(), 1, "one song, its file replaced"); let song = &songs[0]; assert_eq!((text(song, "format"), song["duration"].clone(), text(song, "path")), ("flac", json!(2.0), "Ana Vell/Blue Hours/01 Morning.flac")); assert_eq!(text(song, "file"), better.key.as_deref().unwrap()); assert_eq!(text(song, "title"), "Morning", "a better file replaces the file, not the row's words"); assert!(object.media.borrow().contains_key(text(song, "file"))); // The MP3 again, under another name: the FLAC is better, so it is not kept. let third = root.path().join("three/Ana Vell/Blue Hours"); mp3(&third.join("01 Morning (radio).mp3"), 3); tag(&third.join("01 Morning (radio).mp3"), TagType::Id3v2, &[song_tags("Morning", "Ana Vell", "Blue Hours"), vec![(ItemKey::Comment, "another rip")]].concat(), None); let writes = object.writes.borrow().len(); let report = run(&object, &third); assert_eq!((report.songs[0].outcome, report.songs[0].id.as_deref()), ("worse", Some(id.as_str()))); assert_eq!(report.songs[0].line, "Morning is here in a better file already."); assert_eq!(object.writes.borrow().len(), writes, "a worse file sends nothing");}#[test]fn songs_more_than_two_seconds_apart_are_two_songs() { let root = tempfile::tempdir().unwrap(); let album = root.path().join("Ana Vell/Blue Hours"); wav(&album.join("01 Morning.wav"), 1); tag(&album.join("01 Morning.wav"), TagType::Id3v2, &song_tags("Morning", "Ana Vell", "Blue Hours"), None); wav(&album.join("02 Morning.wav"), 4); tag(&album.join("02 Morning.wav"), TagType::Id3v2, &song_tags("Morning", "Ana Vell", "Blue Hours"), None); let object = Memory::new(DB); let report = run(&object, &album); assert_eq!(report.songs.iter().map(|song| song.outcome).collect::<Vec<_>>(), vec!["added", "added"]); assert_eq!(object.table(ALBUM_TABLE).len(), 1);}#[test]fn a_held_artist_and_album_are_found_and_the_album_takes_only_what_it_lacks() { let root = tempfile::tempdir().unwrap(); let object = Memory::new(DB); object.seed(ARTIST_TABLE, json!({ "id": "artist-1", "name": "ana VELL" })); object.seed(ALBUM_TABLE, json!({ "id": "album-1", "title": "Blue Hours", "artist_name": "Ana Vell", "artist": "artist-1", "year": "1999", "cover": null })); let album = root.path().join("Ana Vell/Blue Hours (2001)"); wav(&album.join("01 Morning.wav"), 1); write(&album.join("Front.png"), b"\x89PNG\r\n\x1a\nfront"); let report = run(&object, &album); assert_eq!(report.songs[0].outcome, "added"); assert_eq!((report.albums_made, report.artists_made), (0, 0)); let albums = object.table(ALBUM_TABLE); assert_eq!(albums.len(), 1); assert_eq!(text(&albums[0], "year"), "1999", "a held year is never written over"); assert_eq!(text(&albums[0], "cover"), format!("{DB}/photos/{}.png", cotton_mac::ids::sha256_hex(b"\x89PNG\r\n\x1a\nfront"))); let songs = object.table(SONG_TABLE); assert_eq!((text(&songs[0], "artist"), text(&songs[0], "album")), ("artist-1", "album-1"));}#[test]fn a_compilation_s_album_is_various_artists_and_each_song_keeps_its_own_artist() { let root = tempfile::tempdir().unwrap(); let album = root.path().join("Hits/Summer"); for (n, artist) in [(1, "Ana Vell"), (2, "Oru")] { let path = album.join(format!("0{n} Song {n}.wav")); wav(&path, 1); let mut fields = song_tags(&format!("Song {n}"), artist, "Summer"); fields.push((ItemKey::FlagCompilation, "1")); tag(&path, TagType::Id3v2, &fields, None); } let object = Memory::new(DB); run(&object, &album); let albums = object.table(ALBUM_TABLE); assert_eq!(albums.len(), 1); assert_eq!((text(&albums[0], "artist_name"), albums[0]["compilation"].clone()), ("Various Artists", json!(true))); let mut names: Vec<String> = object.table(ARTIST_TABLE).iter().map(|row| text(row, "name").to_string()).collect(); names.sort(); assert_eq!(names, vec!["Ana Vell", "Oru", "Various Artists"]);}#[test]fn an_empty_folder_is_refused_in_the_music_set_s_words() { let root = tempfile::tempdir().unwrap(); write(&root.path().join("x/readme.txt"), b"no songs"); let error = import_folder(&Memory::new(DB), &root.path().join("x"), TODAY, &mut |_| {}).unwrap_err(); assert_eq!(error.to_string(), "That folder holds no songs.");}// ── the object over HTTPS ───────────────────────────────────────────────────#[test]fn the_run_reads_the_kit_s_tables_then_sends_bytes_before_rows_with_the_owner_s_token() { let root = tempfile::tempdir().unwrap(); let folder = library(root.path()); let server = TestServer::start(|request| match (request.method.as_str(), request.path.as_str()) { ("GET", "/v1/definitions") => Answer::json(200, json!({ "business": { "database_id": DB } })), ("POST", "/mcp") => { let table = request.json()["params"]["arguments"]["table"].as_str().unwrap_or_default().to_string(); let records = if table == ARTIST_TABLE { json!([{ "table": "artist", "id": "artist-1", "data": { "name": "Ana Vell" } }]) } else { json!([]) }; let page = json!({ "table": table, "records": records, "next_page": null, "total": 0 }); Answer::json(200, json!({ "jsonrpc": "2.0", "id": 1, "result": { "content": [{ "type": "text", "text": page.to_string() }], "isError": false } })) } ("HEAD", _) => Answer::empty(404), ("PUT", _) => Answer::json(200, json!({ "stored": true })), ("POST", "/v1/act") => Answer::json(200, json!({ "version": 1, "changed": [] })), _ => Answer::json(404, json!({ "code": "not_found", "message": "no route" })), }); let client = ObjectClient::new(server.url.clone(), Some("ctn_test-token".to_string())).unwrap(); // RULE (e2e rulings R2, R6): with no data key on this Mac a song waits here: nothing goes up open, and no row names it. let error = import_folder(&client, &folder, TODAY, &mut |_| {}).unwrap_err(); assert!(error.to_string().contains("seal_key_missing"), "{error}"); assert!(server.requests().iter().all(|request| request.method != "PUT" && request.path != "/v1/act"), "nothing is sent open"); let before = server.requests().len(); let keys = cotton_client::seal::HeldDataKeys::new(); keys.hold(DB, &cotton_core::seal::DataKey::from_bytes([7; 32])); let files = std::sync::Arc::new(cotton_client::media::sealed::PersonFiles::new(DB, keys)); let client = client.sealing_files(files.clone()); let report = import_folder(&client, &folder, TODAY, &mut |_| {}).unwrap(); assert_eq!((report.count("added"), report.albums_made, report.artists_made), (2, 1, 0)); let requests = server.requests()[before..].to_vec(); assert!(requests.iter().all(|request| request.header("authorization") == Some("Bearer ctn_test-token"))); let lists: Vec<String> = requests.iter().filter(|r| r.path == "/mcp").map(|r| r.json()["params"]["arguments"]["table"].as_str().unwrap().to_string()).collect(); assert_eq!(lists, vec!["artist", "music_album", "song"]); let acts: Vec<(String, String)> = requests .iter() .filter(|r| r.path == "/v1/act") .map(|r| { let body = r.json(); (body["act"].as_str().unwrap().to_string(), body["args"]["table"].as_str().unwrap().to_string()) }) .collect(); let expected = [("create", "music_album"), ("create", "song"), ("create", "song")]; assert_eq!(acts, expected.map(|(act, table)| (act.to_string(), table.to_string())), "the held artist is found, not made again"); let song = requests.iter().find(|r| r.path == "/v1/act" && r.json()["args"]["table"] == "song").unwrap().json(); assert_eq!(song["args"]["data"]["artist"], "artist-1"); let puts: Vec<(&str, Option<&str>)> = requests.iter().filter(|r| r.method == "PUT").map(|r| (r.path.as_str(), r.header("content-type"))).collect(); assert_eq!(puts.len(), 3, "two songs and one cover: {puts:?}"); // RULE (e2e rulings R6): a song and its cover leave this Mac as f1 files under the file's own key, never as audio or a picture. assert!(puts[0].0.starts_with(&format!("/v1/media/{DB}/music/")) && puts[0].0.ends_with(".flac")); assert!(puts.iter().any(|(path, _)| path.starts_with(&format!("/v1/media/{DB}/photos/")))); for put in requests.iter().filter(|r| r.method == "PUT") { assert_eq!(put.header("content-type"), Some("application/vnd.cotton.f1"), "{}", put.path); assert!(put.body.starts_with(b"CTF1"), "{}", put.path); let key = put.path.trim_start_matches("/v1/media/"); let mut plain = Vec::new(); cotton_core::seal::file::open_file(&files.file_key(key).unwrap(), key, &mut put.body.as_slice(), &mut plain).unwrap(); assert_eq!(format!("{DB}/{}/{}", key.split('/').nth(1).unwrap(), cotton_mac::ids::sha256_hex(&plain)), key.rsplit_once('.').unwrap().0, "the phone opens it to the bytes its key names"); } let first_put = requests.iter().position(|r| r.method == "PUT").unwrap(); let first_act = requests.iter().position(|r| r.path == "/v1/act").unwrap(); assert!(first_put < first_act, "the bytes go before the row that names them");}#[test]fn a_refused_list_stops_the_run_in_the_object_s_words() { let root = tempfile::tempdir().unwrap(); let folder = library(root.path()); let server = TestServer::start(|request| match (request.method.as_str(), request.path.as_str()) { ("GET", "/v1/definitions") => Answer::json(200, json!({ "business": { "database_id": DB } })), ("POST", "/mcp") => Answer::json(200, json!({ "jsonrpc": "2.0", "id": 1, "result": { "content": [{ "type": "text", "text": "no table artist" }], "isError": true } })), _ => Answer::json(404, json!({ "code": "not_found", "message": "no route" })), }); let client = ObjectClient::new(server.url.clone(), Some("ctn_test-token".to_string())).unwrap(); let error = import_folder(&client, &folder, TODAY, &mut |_| {}).unwrap_err(); assert!(error.to_string().contains("list_records: no table artist"), "{error}"); assert!(server.requests().iter().all(|request| request.method != "PUT" && request.path != "/v1/act"), "nothing is sent");}// ── playlists ───────────────────────────────────────────────────────────────fn lists_of(object: &Memory) -> Vec<(String, Vec<String>)> { let songs = object.table(SONG_TABLE); let title_of = |id: &str| songs.iter().find(|song| text(song, "id") == id).map(|song| text(song, "title").to_string()).unwrap_or_default(); let members = object.table(MEMBER_TABLE); object .table(LIST_TABLE) .iter() .map(|list| { let mut held: Vec<(f64, String)> = members .iter() .filter(|member| text(member, "group") == text(list, "id")) .map(|member| (member["place"].as_f64().unwrap(), title_of(text(member, "record_id")))) .collect(); held.sort_by(|a, b| a.0.total_cmp(&b.0)); assert_eq!(text(list, "table_id"), "song"); (text(list, "name").to_string(), held.into_iter().map(|(_, title)| title).collect()) }) .collect()}/// RULE (open standards, 7 Nov 2026): an .m3u or .m3u8 in a walked folder is a list of songs named after its file: each entry found by its path relative to the list, then by its file name, the rest skipped and counted; #EXTINF names nothing.#[test]fn a_playlist_in_the_folder_becomes_a_list_of_its_songs() { let root = tempfile::tempdir().unwrap(); let lib = root.path().join("Lib/Music"); wav(&lib.join("Ana Vell/Two Rooms/01 Low Tide.wav"), 1); wav(&lib.join("Ana Vell/Two Rooms/02 Morning.wav"), 2); wav(&lib.join("Oru/Night/01 Lamps.wav"), 3); write( &lib.join("playlists/Night Drive.m3u8"), b"#EXTM3U\n#EXTINF:3,Somebody Else - Not The Title\n../Oru/Night/01 Lamps.wav\n../Ana Vell/Two Rooms/01 Low Tide.wav\nC:\\Old PC\\02 Morning.wav\n../Gone/03 Missing.wav\n../Oru/Night/01 Lamps.wav\n", ); let object = Memory::new(DB); let report = run(&object, &lib); assert_eq!(lists_of(&object), vec![("Night Drive".to_string(), vec!["Lamps".to_string(), "Low Tide".into(), "Morning".into()])]); let list = &report.lists[0]; assert_eq!((list.name.as_str(), list.made, list.appended, list.skipped), ("Night Drive", true, 3, 1));}/// RULE (open standards, 7 Nov 2026): a list held by that name only grows: the songs it lacks are appended in the file's order, nothing removed.#[test]fn a_held_list_of_that_name_grows_and_loses_nothing() { let root = tempfile::tempdir().unwrap(); let lib = root.path().join("Lib/Music"); wav(&lib.join("Ana Vell/Two Rooms/01 Low Tide.wav"), 1); wav(&lib.join("Ana Vell/Two Rooms/02 Morning.wav"), 2); write(&lib.join("Night Drive.m3u"), b"Ana Vell/Two Rooms/01 Low Tide.wav\n"); let object = Memory::new(DB); run(&object, &lib); // The owner adds a song of their own to the list by hand. let list = text(&object.table(LIST_TABLE)[0], "id").to_string(); object.seed(MEMBER_TABLE, json!({"id": "by-hand", "group": list, "record_id": "typed-song", "place": 2.0})); write(&lib.join("Night Drive.m3u"), b"Ana Vell/Two Rooms/02 Morning.wav\nAna Vell/Two Rooms/01 Low Tide.wav\n"); let again = run(&object, &lib); assert_eq!(object.table(LIST_TABLE).len(), 1, "one list by its name"); let (made, appended) = (again.lists[0].made, again.lists[0].appended); assert_eq!((made, appended), (false, 1)); let members = object.table(MEMBER_TABLE); let mut placed: Vec<(f64, &str)> = members.iter().map(|m| (m["place"].as_f64().unwrap(), text(m, "record_id"))).collect(); placed.sort_by(|a, b| a.0.total_cmp(&b.0)); let songs = object.table(SONG_TABLE); let id_of = |title: &str| songs.iter().find(|s| text(s, "title") == title).map(|s| text(s, "id")).unwrap(); assert_eq!(placed.iter().map(|(_, id)| *id).collect::<Vec<_>>(), vec![id_of("Low Tide"), "typed-song", id_of("Morning")]);}/// RULE (open standards, 7 Nov 2026): the open bundle's playlists/*.m3u8 round-trip: a list exported with its songs and imported again is the same list, in the same order.#[test]fn an_open_bundles_playlist_imports_as_the_same_list() { use cotton_store::fixtures::open_bundle::{a_record_collection, Shelf}; use cotton_store::fixtures::{file_at_version, NOW, OWNER}; use cotton_store::meta::{seed_meta, Meta}; use cotton_store::open_bundle::{write_open_bundle, Kit}; use cotton_store::schema::ddl::SCHEMA_VERSION; use rusqlite::types::Value as Sql; const COPY: &str = "11111111-1111-4111-8111-111111111111"; let tables: &[(&str, &str)] = &[ ("song", include_str!("../../cotton-core/kits/personal/tables/song.json")), ("music_album", include_str!("../../cotton-core/kits/personal/tables/music_album.json")), ("artist", include_str!("../../cotton-core/kits/personal/tables/artist.json")), ("listen", include_str!("../../cotton-core/kits/personal/tables/listen.json")), ("record_group", include_str!("../../cotton-core/kits/personal/tables/record_group.json")), ("group_member", include_str!("../../cotton-core/kits/personal/tables/group_member.json")), ]; let db = file_at_version(SCHEMA_VERSION); let meta = Meta { workspace_id: COPY.into(), owner_id: OWNER.into(), device_id: "phone".into(), last_server_seq: 0, last_hlc: None }; seed_meta(&db, &meta, SCHEMA_VERSION).unwrap(); let t = |s: &str| Sql::Text(s.to_string()); db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[t(COPY), t("A copy"), t(OWNER), t(NOW)]).unwrap(); for (id, definition) in tables { db.run( "INSERT INTO cotton_table_definitions (id, workspace_id, definition, created_at, updated_at) VALUES (?,?,?,?,?)", &[t(id), t(COPY), t(definition), t(NOW), t(NOW)], ) .unwrap(); } let (_, refused) = cotton_store::schema::package_shape::step_file(&db).unwrap(); assert!(refused.is_empty(), "{refused:?}"); // The store's own synthetic collection, lists in the core's tables: Road // Trip is The Stair, Low Tide, and a song whose bytes are not held. let mut shelf = Shelf::default(); a_record_collection(&db, COPY, &mut shelf); let out = tempfile::tempdir().unwrap(); write_open_bundle(&db, Kit::Music, out.path(), &mut shelf, "2026-11-07T10:00:00.000Z").unwrap(); assert!(out.path().join("Music/playlists/Road Trip.m3u8").is_file()); let object = Memory::new(DB); let report = run(&object, &out.path().join("Music")); assert_eq!(report.lists[0].skipped, 0); assert_eq!(lists_of(&object), vec![("Road Trip".to_string(), vec!["The Stair".to_string(), "Low Tide".into()])]);}// ── this Mac as a device ────────────────────────────────────────────────────/// RULE (e2e rulings R1, R2, R6): music-import runs as a device holding the person's data key. An artist, a sealed table, goes sealed and is read back opened on the next run (so it is found, not made again); every song and cover is stored as an f1 file.#[test]fn a_device_run_seals_the_artist_and_every_file_and_finds_them_again() { use support::object::{kit_table, sealed_table, FakeObject}; let root = tempfile::tempdir().unwrap(); let folder = library(root.path()); let tables = vec![sealed_table(ARTIST_TABLE, &[], &["name"], &[]), kit_table(ALBUM_TABLE), kit_table(SONG_TABLE), kit_table(LIST_TABLE), kit_table(MEMBER_TABLE)]; let object = FakeObject::start(DB, "+15550100001", tables); let device = |dir: &Path| { let keys = cotton_client::seal::HeldDataKeys::new(); keys.hold(DB, &cotton_core::seal::DataKey::from_bytes([7; 32])); let store: std::sync::Arc<dyn cotton_client::seal::DataKeyStore> = keys; let copy = std::sync::Arc::new(cotton_mac::copy::Copy::open(&dir.join("copy.db"), DB, store.clone()).unwrap()); ObjectClient::new(object.server.url.clone(), Some("device".into())) .unwrap() .sealing_with(cotton_mac::copy::SealDoor::over(copy)) .sealing_files(std::sync::Arc::new(cotton_client::media::sealed::PersonFiles::new(DB, store))) }; let first = tempfile::tempdir().unwrap(); let report = import_folder(&device(first.path()), &folder, TODAY, &mut |_| {}).unwrap(); assert_eq!((report.count("added"), report.albums_made, report.artists_made), (2, 1, 1)); { let state = object.state.lock().unwrap(); let artists = state.live(ARTIST_TABLE); assert_eq!(artists.len(), 1); assert!(artists[0].1.data.contains_key("sealed_enc") && !artists[0].1.data.contains_key("name"), "the artist's name is sealed"); assert_eq!(state.media.len(), 3, "two songs and a cover"); assert!(state.media.values().all(|bytes| bytes.starts_with(b"CTF1")), "every file is stored sealed"); } assert!(object.server.requests().iter().all(|r| r.path != "/mcp"), "a device reads its rows over sync"); // A fresh copy on a second run: the sealed artist opens from the object and is found by name. let second = tempfile::tempdir().unwrap(); let again = import_folder(&device(second.path()), &folder, TODAY, &mut |_| {}).unwrap(); assert_eq!((again.count("here"), again.count("added"), again.albums_made, again.artists_made), (2, 0, 0, 0)); assert_eq!(object.state.lock().unwrap().live(ARTIST_TABLE).len(), 1);}/// The library as `Memory` keeps it, where the owner gives the album its cover on the phone once the import has/// read the library, while its first song still goes up.struct OwnerSetsACover<'a> { inner: &'a Memory, set: std::cell::Cell<bool>,}impl cotton_mac::music::import::Object for OwnerSetsACover<'_> { fn database_id(&self) -> Result<String, cotton_mac::object::ObjectError> { self.inner.database_id() } fn rows(&self, table: &str) -> Result<Vec<cotton_mac::music::import::Row>, cotton_mac::object::ObjectError> { self.inner.rows(table) } fn media_held(&self, key: &str) -> Result<bool, cotton_mac::object::ObjectError> { self.inner.media_held(key) } fn put_file(&self, key: &str, path: &Path, size: u64, content_type: &str) -> Result<(), cotton_mac::object::ObjectError> { if !self.set.replace(true) { for row in self.inner.rows.borrow_mut().get_mut(ALBUM_TABLE).into_iter().flatten() { row.insert("cover".into(), json!(format!("{DB}/photos/his-own.jpg"))); } } self.inner.put_file(key, path, size, content_type) } fn put_bytes(&self, key: &str, bytes: Vec<u8>, content_type: &str) -> Result<(), cotton_mac::object::ObjectError> { self.inner.put_bytes(key, bytes, content_type) } fn create(&self, table: &str, id: &str, data: &cotton_mac::music::import::Row) -> Result<(), cotton_mac::object::ObjectError> { self.inner.create(table, id, data) } fn update(&self, table: &str, id: &str, patch: &cotton_mac::music::import::Row) -> Result<(), cotton_mac::object::ObjectError> { self.inner.update(table, id, patch) }}/// RULE (STALE WRITES 2, 25 Nov 2026): an album's cover or field a song brings fills only what the album lacks AS/// IT IS when the import writes, never as the library stood when the import opened: a cover the owner gave it during/// a long import stays his.#[test]fn a_cover_the_owner_set_during_an_import_stays_his() { let root = tempfile::tempdir().unwrap(); let album = root.path().join("Lib/Ana Vell/Blue Hours (2001)"); wav(&album.join("02 Night.wav"), 1); let memory = Memory::new(DB); run(&memory, &root.path().join("Lib/Ana Vell")); assert_eq!(text(&memory.table(ALBUM_TABLE)[0], "cover"), "", "the album came with no cover"); wav(&album.join("03 Dusk.wav"), 2); write(&album.join("cover.jpg"), JPEG); let object = OwnerSetsACover { inner: &memory, set: std::cell::Cell::new(false) }; import_folder(&object, &root.path().join("Lib/Ana Vell"), TODAY, &mut |_| {}).unwrap(); assert_eq!(text(&memory.table(ALBUM_TABLE)[0], "cover"), format!("{DB}/photos/his-own.jpg"), "{:?} {:?}", memory.writes.borrow(), memory.table(ALBUM_TABLE));}