mecomp_storage/
test_utils.rs

1use std::{
2    ops::{Range, RangeInclusive},
3    path::PathBuf,
4    str::FromStr,
5    sync::Arc,
6    time::Duration,
7};
8
9use anyhow::Result;
10use lofty::{config::WriteOptions, file::TaggedFileExt, prelude::*, probe::Probe, tag::Accessor};
11use one_or_many::OneOrMany;
12use rand::{seq::IteratorRandom, Rng};
13#[cfg(feature = "db")]
14use surrealdb::{
15    engine::local::{Db, Mem},
16    sql::Id,
17    Connection, Surreal,
18};
19
20#[cfg(feature = "analysis")]
21use crate::db::schemas::analysis::Analysis;
22#[cfg(not(feature = "db"))]
23use crate::db::schemas::Id;
24use crate::db::schemas::{
25    album::Album,
26    artist::Artist,
27    collection::Collection,
28    playlist::Playlist,
29    song::{Song, SongChangeSet, SongMetadata},
30};
31
32pub const ARTIST_NAME_SEPARATOR: &str = ", ";
33
34/// Initialize a test database with the same tables as the main database.
35/// This is useful for testing queries and mutations.
36///
37/// # Errors
38///
39/// This function will return an error if the database cannot be initialized.
40#[cfg(feature = "db")]
41#[allow(clippy::missing_inline_in_public_items)]
42pub async fn init_test_database() -> surrealdb::Result<Surreal<Db>> {
43    use crate::db::schemas::dynamic::DynamicPlaylist;
44
45    let db = Surreal::new::<Mem>(()).await?;
46    db.use_ns("test").use_db("test").await?;
47
48    crate::db::register_custom_analyzer(&db).await?;
49    surrealqlx::register_tables!(
50        &db,
51        Album,
52        Artist,
53        Song,
54        Collection,
55        Playlist,
56        DynamicPlaylist
57    )?;
58    #[cfg(feature = "analysis")]
59    surrealqlx::register_tables!(&db, Analysis)?;
60
61    Ok(db)
62}
63
64/// Initialize a test database with some basic state
65///
66/// # What will be created:
67///
68/// - a playlist named "Playlist 0"
69/// - a collection named "Collection 0"
70/// - optionally, a passed `DynamicPlaylist`
71/// - `song_count` arbitrary songs whose values are determined by the given `song_case_func`
72/// - a file in the given `TempDir` for each song
73///
74/// Can optionally also create a dynamic playlist with given information
75///
76/// You can pass functions to be used to create the songs and playlists
77///
78/// `song_case_func` signature
79/// `FnMut(usize) -> (SongCase, bool, bool)`
80/// - `i`: which song this is, 0..`song_count`
81/// - returns: `(the song_case to use when generating the song, whether the song should be added to the playlist, whether it should be added to the collection`
82///
83/// Note: will actually create files for the songs in the passed `TempDir`
84///
85/// # Panics
86///
87/// Panics if an error occurs during the above process, this is intended to only be used for testing
88/// so panicking when something goes wrong ensures that tests will fail and the backtrace will point
89/// to whatever line caused the panic in here.
90#[cfg(feature = "db")]
91#[allow(clippy::missing_inline_in_public_items)]
92pub async fn init_test_database_with_state<SCF>(
93    song_count: std::num::NonZero<usize>,
94    mut song_case_func: SCF,
95    dynamic: Option<crate::db::schemas::dynamic::DynamicPlaylist>,
96    tempdir: &tempfile::TempDir,
97) -> Arc<Surreal<Db>>
98where
99    SCF: FnMut(usize) -> (SongCase, bool, bool) + Send + Sync,
100{
101    use anyhow::Context;
102
103    use crate::db::schemas::dynamic::DynamicPlaylist;
104
105    let db = Arc::new(init_test_database().await.unwrap());
106
107    // create the playlist, collection, and optionally the dynamic playlist
108    let playlist = Playlist {
109        id: Playlist::generate_id(),
110        name: "Playlist 0".into(),
111        runtime: Duration::from_secs(0),
112        song_count: 0,
113    };
114    let playlist = Playlist::create(&db, playlist).await.unwrap().unwrap();
115
116    let collection = Collection {
117        id: Collection::generate_id(),
118        name: "Collection 0".into(),
119        runtime: Duration::from_secs(0),
120        song_count: 0,
121    };
122    let collection = Collection::create(&db, collection).await.unwrap().unwrap();
123
124    if let Some(dynamic) = dynamic {
125        let _ = DynamicPlaylist::create(&db, dynamic)
126            .await
127            .unwrap()
128            .unwrap();
129    }
130
131    // create the songs
132    for i in 0..(song_count.get()) {
133        let (song_case, add_to_playlist, add_to_collection) = song_case_func(i);
134
135        let metadata = create_song_metadata(tempdir, song_case.clone())
136            .context(format!(
137                "failed to create metadata for song case {song_case:?}"
138            ))
139            .unwrap();
140
141        let song = Song::try_load_into_db(&db, metadata)
142            .await
143            .context(format!(
144                "Failed to load into db the song case: {song_case:?}"
145            ))
146            .unwrap();
147
148        if add_to_playlist {
149            Playlist::add_songs(&db, playlist.id.clone(), vec![song.id.clone()])
150                .await
151                .unwrap();
152        }
153        if add_to_collection {
154            Collection::add_songs(&db, collection.id.clone(), vec![song.id.clone()])
155                .await
156                .unwrap();
157        }
158    }
159
160    db
161}
162
163/// Create a song with the given case, and optionally apply the given overrides.
164///
165/// The created song is shallow, meaning that the artists, album artists, and album are not created in the database.
166///
167/// # Errors
168///
169/// This function will return an error if the song cannot be created.
170///
171/// # Panics
172///
173/// Panics if the song can't be read from the database after creation.
174#[cfg(feature = "db")]
175#[allow(clippy::missing_inline_in_public_items)]
176pub async fn create_song_with_overrides<C: Connection>(
177    db: &Surreal<C>,
178    SongCase {
179        song,
180        artists,
181        album_artists,
182        album,
183        genre,
184    }: SongCase,
185    overrides: SongChangeSet,
186) -> Result<Song> {
187    let id = Song::generate_id();
188    let song = Song {
189        id: id.clone(),
190        title: Into::into(format!("Song {song}").as_str()),
191        artist: artists
192            .iter()
193            .map(|a| format!("Artist {a}"))
194            .collect::<Vec<_>>()
195            .into(),
196        album_artist: album_artists
197            .iter()
198            .map(|a| format!("Artist {a}"))
199            .collect::<Vec<_>>()
200            .into(),
201        album: format!("Album {album}"),
202        genre: OneOrMany::One(format!("Genre {genre}")),
203        runtime: Duration::from_secs(120),
204        track: None,
205        disc: None,
206        release_year: None,
207        extension: "mp3".into(),
208        path: PathBuf::from_str(&format!("{}.mp3", id.id))?,
209    };
210
211    Song::create(db, song.clone()).await?;
212    if overrides != SongChangeSet::default() {
213        Song::update(db, song.id.clone(), overrides).await?;
214    }
215    let song = Song::read(db, song.id).await?.expect("Song should exist");
216    Ok(song)
217}
218
219/// Creates a song file with the given case and overrides.
220/// The song file is created in a temporary directory.
221/// The song metadata is created from the song file.
222/// The song is not added to the database.
223///
224/// # Errors
225///
226/// This function will return an error if the song metadata cannot be created.
227#[allow(clippy::missing_inline_in_public_items)]
228pub fn create_song_metadata(
229    tempdir: &tempfile::TempDir,
230    SongCase {
231        song,
232        artists,
233        album_artists,
234        album,
235        genre,
236    }: SongCase,
237) -> Result<SongMetadata> {
238    // we have an example mp3 in `assets/`, we want to take that and create a new audio file with psuedorandom id3 tags
239    let base_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
240        .join("../assets/music.mp3")
241        .canonicalize()?;
242
243    let mut tagged_file = Probe::open(&base_path)?.read()?;
244    let tag = match tagged_file.primary_tag_mut() {
245        Some(primary_tag) => primary_tag,
246        // If the "primary" tag doesn't exist, we just grab the
247        // first tag we can find. Realistically, a tag reader would likely
248        // iterate through the tags to find a suitable one.
249        None => tagged_file
250            .first_tag_mut()
251            .ok_or_else(|| anyhow::anyhow!("ERROR: No tags found"))?,
252    };
253
254    tag.insert_text(
255        ItemKey::AlbumArtist,
256        album_artists
257            .iter()
258            .map(|a| format!("Artist {a}"))
259            .collect::<Vec<_>>()
260            .join(ARTIST_NAME_SEPARATOR),
261    );
262
263    tag.remove_artist();
264    tag.set_artist(
265        artists
266            .iter()
267            .map(|a| format!("Artist {a}"))
268            .collect::<Vec<_>>()
269            .join(ARTIST_NAME_SEPARATOR),
270    );
271
272    tag.remove_album();
273    tag.set_album(format!("Album {album}"));
274
275    tag.remove_title();
276    tag.set_title(format!("Song {song}"));
277
278    tag.remove_genre();
279    tag.set_genre(format!("Genre {genre}"));
280
281    let new_path = tempdir.path().join(format!("song_{}.mp3", Id::ulid()));
282    // copy the base file to the new path
283    std::fs::copy(&base_path, &new_path)?;
284    // write the new tags to the new file
285    tag.save_to_path(&new_path, WriteOptions::default())?;
286
287    // now, we need to load a SongMetadata from the new file
288    Ok(SongMetadata::load_from_path(
289        new_path,
290        &OneOrMany::One(ARTIST_NAME_SEPARATOR.to_string()),
291        None,
292    )?)
293}
294
295#[derive(Debug, Clone)]
296pub struct SongCase {
297    pub song: u8,
298    pub artists: Vec<u8>,
299    pub album_artists: Vec<u8>,
300    pub album: u8,
301    pub genre: u8,
302}
303
304impl SongCase {
305    #[must_use]
306    #[inline]
307    pub const fn new(
308        song: u8,
309        artists: Vec<u8>,
310        album_artists: Vec<u8>,
311        album: u8,
312        genre: u8,
313    ) -> Self {
314        Self {
315            song,
316            artists,
317            album_artists,
318            album,
319            genre,
320        }
321    }
322}
323
324#[inline]
325pub const fn arb_song_case() -> impl Fn() -> SongCase {
326    || {
327        let artist_item_strategy = move || {
328            (0..=10u8)
329                .choose(&mut rand::thread_rng())
330                .unwrap_or_default()
331        };
332        let rng = &mut rand::thread_rng();
333        let artists = arb_vec(&artist_item_strategy, 1..=10)()
334            .into_iter()
335            .collect::<std::collections::HashSet<_>>()
336            .into_iter()
337            .collect::<Vec<_>>();
338        let album_artists = arb_vec(&artist_item_strategy, 1..=10)()
339            .into_iter()
340            .collect::<std::collections::HashSet<_>>()
341            .into_iter()
342            .collect::<Vec<_>>();
343        let song = (0..=10u8).choose(rng).unwrap_or_default();
344        let album = (0..=10u8).choose(rng).unwrap_or_default();
345        let genre = (0..=10u8).choose(rng).unwrap_or_default();
346
347        SongCase::new(song, artists, album_artists, album, genre)
348    }
349}
350
351#[inline]
352pub const fn arb_vec<T>(
353    item_strategy: &impl Fn() -> T,
354    range: RangeInclusive<usize>,
355) -> impl Fn() -> Vec<T> + '_
356where
357    T: Clone + std::fmt::Debug + Sized,
358{
359    move || {
360        let size = range
361            .clone()
362            .choose(&mut rand::thread_rng())
363            .unwrap_or_default();
364        std::iter::repeat_with(item_strategy).take(size).collect()
365    }
366}
367
368pub enum IndexMode {
369    InBounds,
370    OutOfBounds,
371}
372
373#[inline]
374pub const fn arb_vec_and_index<T>(
375    item_strategy: &impl Fn() -> T,
376    range: RangeInclusive<usize>,
377    index_mode: IndexMode,
378) -> impl Fn() -> (Vec<T>, usize) + '_
379where
380    T: Clone + std::fmt::Debug + Sized,
381{
382    move || {
383        let vec = arb_vec(item_strategy, range.clone())();
384        let index = match index_mode {
385            IndexMode::InBounds => 0..vec.len(),
386            #[allow(clippy::range_plus_one)]
387            IndexMode::OutOfBounds => vec.len()..(vec.len() + vec.len() / 2 + 1),
388        }
389        .choose(&mut rand::thread_rng())
390        .unwrap_or_default();
391        (vec, index)
392    }
393}
394
395pub enum RangeStartMode {
396    Standard,
397    Zero,
398    OutOfBounds,
399}
400
401pub enum RangeEndMode {
402    Start,
403    Standard,
404    OutOfBounds,
405}
406
407pub enum RangeIndexMode {
408    InBounds,
409    InRange,
410    AfterRangeInBounds,
411    OutOfBounds,
412    BeforeRange,
413}
414
415// Returns a tuple of a Vec of T and a Range<usize>
416// where the start is a random index in the Vec
417// and the end is a random index in the Vec that is greater than or equal to the start
418#[inline]
419pub const fn arb_vec_and_range_and_index<T>(
420    item_strategy: &impl Fn() -> T,
421    range: RangeInclusive<usize>,
422    range_start_mode: RangeStartMode,
423    range_end_mode: RangeEndMode,
424    index_mode: RangeIndexMode,
425) -> impl Fn() -> (Vec<T>, Range<usize>, Option<usize>) + '_
426where
427    T: Clone + std::fmt::Debug + Sized,
428{
429    move || {
430        let rng = &mut rand::thread_rng();
431        let vec = arb_vec(item_strategy, range.clone())();
432        let start = match range_start_mode {
433            RangeStartMode::Standard => 0..vec.len(),
434            #[allow(clippy::range_plus_one)]
435            RangeStartMode::OutOfBounds => vec.len()..(vec.len() + vec.len() / 2 + 1),
436            RangeStartMode::Zero => 0..1,
437        }
438        .choose(rng)
439        .unwrap_or_default();
440        let end = match range_end_mode {
441            RangeEndMode::Standard => start..vec.len(),
442            #[allow(clippy::range_plus_one)]
443            RangeEndMode::OutOfBounds => vec.len()..(vec.len() + vec.len() / 2 + 1).max(start),
444            #[allow(clippy::range_plus_one)]
445            RangeEndMode::Start => start..(start + 1),
446        }
447        .choose(rng)
448        .unwrap_or_default();
449
450        let index = match index_mode {
451            RangeIndexMode::InBounds => 0..vec.len(),
452            RangeIndexMode::InRange => start..end,
453            RangeIndexMode::AfterRangeInBounds => end..vec.len(),
454            #[allow(clippy::range_plus_one)]
455            RangeIndexMode::OutOfBounds => vec.len()..(vec.len() + vec.len() / 2 + 1),
456            RangeIndexMode::BeforeRange => 0..start,
457        }
458        .choose(rng);
459
460        (vec, start..end, index)
461    }
462}
463
464#[inline]
465pub const fn arb_analysis_features() -> impl Fn() -> [f64; 20] {
466    move || {
467        let rng = &mut rand::thread_rng();
468        let mut features = [0.0; 20];
469        for feature in &mut features {
470            *feature = rng.gen_range(-1.0..1.0);
471        }
472        features
473    }
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479    use pretty_assertions::assert_eq;
480
481    #[tokio::test]
482    async fn test_create_song() {
483        let db = init_test_database().await.unwrap();
484        // Create a test case
485        let song_case = SongCase::new(0, vec![0], vec![0], 0, 0);
486
487        // Call the create_song function
488        let result = create_song_with_overrides(&db, song_case, SongChangeSet::default()).await;
489
490        // Assert that the result is Ok
491        if let Err(e) = result {
492            panic!("Error creating song: {e:?}");
493        }
494
495        // Get the Song from the result
496        let song = result.unwrap();
497
498        // Assert that we can get the song from the database
499        let song_from_db = Song::read(&db, song.id.clone()).await.unwrap().unwrap();
500
501        // Assert that the song from the database is the same as the song we created
502        assert_eq!(song, song_from_db);
503    }
504}