SPB Git

Repository Public

examples_catalog.rs 4.2 KB 76 lines rust

1//! ORIX Sonata2//! File: crates/sonata-compiler/tests/examples_catalog.rs3//! Description: Examples/catalog.json (generated by Scripts/gen-examples-catalog.py) agrees with4//! the example files: same set of files, valid categories, unique titles, and the tracks and5//! notes recorded for each one are what the compiler produces.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use sonata_compiler::{compile, CompileOptions, DirLoader};11use std::collections::BTreeSet;12use std::path::PathBuf;1314const CATEGORIES: [&str; 9] = ["Getting started", "Rhythm", "Harmony", "Algorithmic", "Instruments", "Effects and mixing", "Pieces", "Studies", "Language"];1516fn examples_dir() -> PathBuf {17    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../Examples")18}1920#[test]21fn the_catalog_matches_the_examples() {22    let dir = examples_dir();23    let text = std::fs::read_to_string(dir.join("catalog.json")).expect("Examples/catalog.json exists (run Scripts/gen-examples-catalog.py)");24    let catalog: serde_json::Value = serde_json::from_str(&text).expect("the catalog is JSON");25    assert_eq!(catalog["format"], 1);26    let entries = catalog["examples"].as_array().expect("examples is a list");27    assert!(entries.len() >= 76, "at least 76 examples, found {}", entries.len());2829    // The same set of files on disk and in the catalog.30    let on_disk: BTreeSet<String> = std::fs::read_dir(&dir)31        .unwrap()32        .filter_map(|e| e.ok().map(|e| e.path()))33        .filter(|p| p.extension().is_some_and(|e| e == "sonata"))34        .map(|p| p.file_name().unwrap().to_string_lossy().to_string())35        .collect();36    let listed: BTreeSet<String> = entries.iter().map(|e| e["file"].as_str().expect("file is a string").to_string()).collect();37    assert_eq!(listed.len(), entries.len(), "a file is listed twice");38    let missing: Vec<_> = on_disk.difference(&listed).collect();39    let stale: Vec<_> = listed.difference(&on_disk).collect();40    assert!(missing.is_empty() && stale.is_empty(), "not in the catalog: {missing:?}; in the catalog but not on disk: {stale:?}");4142    let mut titles = BTreeSet::new();43    let mut last_rank = 0usize;44    let loader = DirLoader::new(&dir);45    for e in entries {46        let file = e["file"].as_str().unwrap();47        let title = e["title"].as_str().unwrap_or("");48        assert!(!title.is_empty() && titles.insert(title.to_string()), "{file}: empty or repeated title '{title}'");49        let category = e["category"].as_str().unwrap_or("");50        let rank = CATEGORIES.iter().position(|c| *c == category).unwrap_or_else(|| panic!("{file}: unknown category '{category}'"));51        assert!(rank >= last_rank, "{file}: the catalog is not sorted by category");52        last_rank = rank;53        assert!(e["description"].as_str().is_some_and(|d| d.len() >= 20), "{file}: no description");54        assert!(55            e["teaches"].as_array().is_some_and(|t| !t.is_empty() && t.iter().all(|x| x.as_str().is_some_and(|s| !s.is_empty()))),56            "{file}: nothing in 'teaches'"57        );5859        // What the compiler produces is what the catalog says.60        let source = std::fs::read_to_string(dir.join(file)).unwrap();61        let out = compile(file, &source, &loader, &CompileOptions::default());62        let errors: Vec<String> = out.errors().map(|d| format!("{}: {}", d.code, d.message)).collect();63        assert!(errors.is_empty(), "{file} does not compile: {errors:?}");64        assert!(out.diagnostics.is_empty(), "{file} compiles with warnings: {:?}", out.diagnostics.iter().map(|d| &d.code).collect::<Vec<_>>());65        let program = out.program.as_deref().unwrap_or_else(|| panic!("{file} has no composition"));66        assert_eq!(e["tracks"].as_u64(), Some(program.tracks.len() as u64), "{file}: tracks");67        assert_eq!(e["notes"].as_u64(), Some(program.stats.notes), "{file}: notes");68        let duration = e["duration_sec"].as_f64().unwrap_or(-1.0);69        assert!((duration - program.end_sec).abs() < 1e-3, "{file}: duration {duration} vs {}", program.end_sec);70        assert!((1.0..=70.0).contains(&duration), "{file}: {duration} s is outside what an example should last");71    }72    for c in CATEGORIES {73        assert!(entries.iter().filter(|e| e["category"] == c).count() >= 5, "category '{c}' has fewer than five examples");74    }75}76
Files main
Menu

Theme