diff options
| -rw-r--r-- | morphology-img/Cargo.toml | 2 | ||||
| -rw-r--r-- | morphology-img/README.md | 86 | ||||
| -rw-r--r-- | morphology-img/src/file_gen.rs | 179 | ||||
| -rw-r--r-- | morphology-img/src/lib.rs | 197 | ||||
| -rw-r--r-- | morphology-img/src/render.rs | 180 | ||||
| -rw-r--r-- | morphology-img/src/template.rs | 52 | ||||
| -rw-r--r-- | morphology-img/tests/config.rs | 185 | ||||
| -rw-r--r-- | morphology-img/tests/file_gen.rs | 533 | ||||
| -rw-r--r-- | morphology-img/tests/integration.rs | 365 | ||||
| -rw-r--r-- | morphology-img/tests/render.rs | 548 | ||||
| -rw-r--r-- | morphology-img/tests/template.rs | 144 |
11 files changed, 2470 insertions, 1 deletions
diff --git a/morphology-img/Cargo.toml b/morphology-img/Cargo.toml index 5abe376..0c7a734 100644 --- a/morphology-img/Cargo.toml +++ b/morphology-img/Cargo.toml @@ -8,6 +8,6 @@ authors.workspace = true morphology = { path = "../morphology" } thiserror = "2.0" itertools = "0.13" +tempfile = "3" [dev-dependencies] -tempfile = "3" diff --git a/morphology-img/README.md b/morphology-img/README.md new file mode 100644 index 0000000..2b0ab5e --- /dev/null +++ b/morphology-img/README.md @@ -0,0 +1,86 @@ +# morphology-img + +Convert meta-affine sequences to SVG visualizations using LilyPond. + +## Prerequisites + +This library requires **LilyPond** to be installed and available in your system PATH. + +## Overview + +The `morphology-img` crate transforms meta-affine sequences from the `morphology` crate into musical notation rendered as SVG images. It uses LilyPond's typesetting engine to generate high-quality visualizations. + +## Example + +### Basic Usage + +```rust +use morphology::{Sequence, Value}; +use morphology_img::sequence_to_markup; + +// Create a meta-affine sequence +let seq = Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), +]); + +// Convert to LilyPond markup +let markup = sequence_to_markup(&seq); +println!("{}", markup); // Output: f'4 f4 e4 b4 +``` + +## API + +### Converting Sequences to Markup + +The main public API converts sequences directly to LilyPond markup strings: + +```rust +use morphology_img::sequence_to_markup; + +let markup = sequence_to_markup(&sequence); +``` + +## Testing + +Run tests with: +```bash +cargo test +``` + +Some tests require LilyPond to be installed and are marked with `#[ignore]`. To run these: +```bash +cargo test -- --ignored +``` + +## Module Structure + +``` +morphology-img/src/ +├── lib.rs // Public API, re-exports +├── error.rs // Error types using thiserror +├── note.rs // Integer → LilyPond pitch conversion +├── template.rs // Template handling & substitution +├── file_gen.rs // .ly file generation +└── render.rs // LilyPond CLI invocation +``` + +## Troubleshooting + +### "LilyPond not found" + +If you see this error, ensure: +1. LilyPond is installed (see installation instructions above) +2. The `lilypond` command is in your PATH +3. You can run `lilypond --version` from your terminal + +### "LilyPond execution failed" + +This can happen if: +- The generated .ly file has syntax errors +- LilyPond encountered an internal error +- File permissions prevent LilyPond from writing output + +Check the error message for specific details. diff --git a/morphology-img/src/file_gen.rs b/morphology-img/src/file_gen.rs index c429719..edeeeeb 100644 --- a/morphology-img/src/file_gen.rs +++ b/morphology-img/src/file_gen.rs @@ -1 +1,180 @@ // .ly file generation and temp directory management + +use std::path::{Path, PathBuf}; +use std::fs; +use tempfile::TempDir; +use morphology::Sequence; +use crate::error::RenderError; +use crate::template; +use crate::note::{sequence_to_notes, notes_to_markup}; + +/// Generates a filename for a sequence with proper zero-padding. +/// +/// The padding width is determined by the total number of sequences, +/// ensuring that all filenames sort correctly in lexicographic order. +/// +/// # Arguments +/// - `index`: The sequence index (0-based) +/// - `total_count`: Total number of sequences (used to determine padding) +/// +/// # Examples +/// ``` +/// use morphology_img::file_gen::generate_filename; +/// +/// assert_eq!(generate_filename(0, 10).to_str().unwrap(), "sequence-00.ly"); +/// assert_eq!(generate_filename(5, 10).to_str().unwrap(), "sequence-05.ly"); +/// assert_eq!(generate_filename(42, 1000).to_str().unwrap(), "sequence-0042.ly"); +/// ``` +pub fn generate_filename(index: usize, total_count: usize) -> PathBuf { + let width = total_count.to_string().len(); + PathBuf::from(format!("sequence-{:0width$}.ly", index, width = width)) +} + +/// Creates a temporary directory for .ly files. +/// +/// The directory will be automatically cleaned up when the TempDir is dropped, +/// unless explicitly persisted using `TempDir::into_path()`. +/// +/// # Returns +/// A TempDir handle that manages cleanup +/// +/// # Errors +/// Returns `RenderError::FileIO` if the temporary directory cannot be created +pub fn create_temp_dir() -> Result<TempDir, RenderError> { + TempDir::new().map_err(RenderError::from) +} + +/// Writes the .ily support files to the specified directory. +/// +/// This function writes the three LilyPond include files that are referenced +/// by the main template: +/// - `format.ily`: Format definitions +/// - `entry.ily`: Entry block definitions +/// - `elements.ily`: Element definitions +/// +/// # Arguments +/// - `dir`: The directory to write files to +/// +/// # Returns +/// Ok(()) on success +/// +/// # Errors +/// Returns `RenderError::FileIO` if any file cannot be written +pub fn write_support_files(dir: &Path) -> Result<(), RenderError> { + let files = [ + ("format.ily", template::get_format_ily()), + ("entry.ily", template::get_entry_ily()), + ("elements.ily", template::get_elements_ily()), + ]; + + for (filename, content) in files { + let path = dir.join(filename); + fs::write(&path, content)?; + } + + Ok(()) +} + +/// Generates a .ly file for a single sequence. +/// +/// This function performs the complete transformation pipeline: +/// 1. Convert sequence to notes +/// 2. Convert notes to markup string +/// 3. Substitute markup into template +/// 4. Write the complete .ly file to the specified path +/// +/// # Arguments +/// - `sequence`: The meta-affine sequence to render +/// - `output_path`: Path where the .ly file should be written +/// +/// # Returns +/// Ok(()) on success +/// +/// # Errors +/// - `RenderError::Template` if template substitution fails +/// - `RenderError::FileIO` if file cannot be written +/// +/// # Examples +/// ```no_run +/// use morphology::{Sequence, Value}; +/// use morphology_img::file_gen::{generate_ly_file, create_temp_dir}; +/// use std::path::Path; +/// +/// let seq = Sequence::new(vec![Value::origin()]); +/// let temp_dir = create_temp_dir().unwrap(); +/// let output_path = temp_dir.path().join("test.ly"); +/// +/// generate_ly_file(&seq, &output_path).unwrap(); +/// assert!(output_path.exists()); +/// ``` +pub fn generate_ly_file( + sequence: &Sequence, + output_path: &Path, +) -> Result<(), RenderError> { + // Convert sequence to notes + let notes = sequence_to_notes(sequence); + + // Convert notes to markup string + let markup = notes_to_markup(¬es); + + // Substitute into template + let ly_content = template::substitute_template(&markup)?; + + // Write to file (UTF-8) + fs::write(output_path, ly_content)?; + + Ok(()) +} + +/// Generates .ly files for multiple sequences in a specified directory. +/// +/// This function generates numbered .ly files for each sequence in the input, +/// with filenames automatically padded based on the total count. +/// +/// # Arguments +/// - `sequences`: The sequences to generate files for +/// - `temp_dir`: The directory to write files to +/// +/// # Returns +/// A vector of paths to the generated .ly files, in the same order as input +/// +/// # Errors +/// - `RenderError::Template` if template substitution fails +/// - `RenderError::FileIO` if any file cannot be written +/// +/// # Examples +/// ```no_run +/// use morphology::{Sequence, Value}; +/// use morphology_img::file_gen::{generate_ly_files, create_temp_dir}; +/// +/// let sequences = vec![ +/// Sequence::new(vec![Value::origin()]), +/// Sequence::new(vec![Value::new(1, 0)]), +/// ]; +/// +/// let temp_dir = create_temp_dir().unwrap(); +/// let paths = generate_ly_files(&sequences, temp_dir.path()).unwrap(); +/// +/// assert_eq!(paths.len(), 2); +/// for path in paths { +/// assert!(path.exists()); +/// } +/// ``` +pub fn generate_ly_files( + sequences: &[Sequence], + temp_dir: &Path, +) -> Result<Vec<PathBuf>, RenderError> { + let total_count = sequences.len(); + let mut paths = Vec::with_capacity(total_count); + + for (index, sequence) in sequences.iter().enumerate() { + let filename = generate_filename(index, total_count); + let output_path = temp_dir.join(&filename); + + generate_ly_file(sequence, &output_path)?; + + paths.push(output_path); + } + + Ok(paths) +} diff --git a/morphology-img/src/lib.rs b/morphology-img/src/lib.rs index b94bb5c..3ba78f2 100644 --- a/morphology-img/src/lib.rs +++ b/morphology-img/src/lib.rs @@ -32,3 +32,200 @@ pub mod render; // Public API - only export what external clients should use pub use error::RenderError; pub use note::sequence_to_markup; + +use std::path::PathBuf; + +/// Configuration for rendering sequences to SVGs. +/// +/// This struct uses the builder pattern to configure how sequences are rendered +/// to SVG files using LilyPond. +/// +/// # Examples +/// +/// ``` +/// use morphology_img::RenderConfig; +/// +/// // Basic configuration with default settings +/// let config = RenderConfig::new("output"); +/// +/// // Advanced configuration with custom settings +/// let config = RenderConfig::new("output") +/// .keep_temp_files(true) +/// .lilypond_binary("/usr/local/bin/lilypond"); +/// ``` +#[derive(Debug, Clone)] +pub struct RenderConfig { + /// Directory where SVG files should be created + pub output_dir: PathBuf, + + /// Whether to keep temporary .ly files for debugging + pub keep_temp_files: bool, + + /// Path to the LilyPond binary (default: "lilypond") + pub lilypond_binary: PathBuf, +} + +impl Default for RenderConfig { + fn default() -> Self { + Self { + output_dir: PathBuf::from("output"), + keep_temp_files: false, + lilypond_binary: PathBuf::from("lilypond"), + } + } +} + +impl RenderConfig { + /// Creates a new RenderConfig with the specified output directory. + /// + /// All other settings use their default values: + /// - `keep_temp_files`: false + /// - `lilypond_binary`: "lilypond" + /// + /// # Examples + /// + /// ``` + /// use morphology_img::RenderConfig; + /// + /// let config = RenderConfig::new("my-output"); + /// assert_eq!(config.output_dir.to_str().unwrap(), "my-output"); + /// ``` + pub fn new(output_dir: impl Into<PathBuf>) -> Self { + Self { + output_dir: output_dir.into(), + ..Default::default() + } + } + + /// Sets whether to keep temporary .ly files for debugging. + /// + /// By default, temporary files are automatically cleaned up. Setting this + /// to `true` will preserve them for inspection. + /// + /// # Examples + /// + /// ``` + /// use morphology_img::RenderConfig; + /// + /// let config = RenderConfig::new("output") + /// .keep_temp_files(true); + /// + /// assert!(config.keep_temp_files); + /// ``` + pub fn keep_temp_files(mut self, keep: bool) -> Self { + self.keep_temp_files = keep; + self + } + + /// Sets the path to the LilyPond binary. + /// + /// By default, this is "lilypond", which will be found in the system PATH. + /// Use this method to specify a custom path to the LilyPond executable. + /// + /// # Examples + /// + /// ``` + /// use morphology_img::RenderConfig; + /// + /// let config = RenderConfig::new("output") + /// .lilypond_binary("/usr/local/bin/lilypond"); + /// + /// assert_eq!(config.lilypond_binary.to_str().unwrap(), "/usr/local/bin/lilypond"); + /// ``` + pub fn lilypond_binary(mut self, path: impl Into<PathBuf>) -> Self { + self.lilypond_binary = path.into(); + self + } +} + +/// Renders multiple sequences to SVG files. +/// +/// This is the main public API for converting meta-affine sequences into +/// SVG visualizations using LilyPond. The function handles the complete pipeline: +/// 1. Creates temporary directory for .ly files +/// 2. Writes LilyPond support files (.ily) +/// 3. Generates .ly files from sequences +/// 4. Invokes LilyPond to render SVGs +/// 5. Cleans up temporary files (unless configured to keep them) +/// +/// # Arguments +/// - `sequences`: The meta-affine sequences to render +/// - `config`: Configuration for output directory, LilyPond binary, etc. +/// +/// # Returns +/// Vector of paths to generated SVG files, in the same order as input sequences +/// +/// # Errors +/// - `RenderError::FileIO` if directories cannot be created or files cannot be written +/// - `RenderError::LilyPondNotFound` if LilyPond is not available +/// - `RenderError::LilyPondExecution` if LilyPond fails to render any sequence +/// - `RenderError::Template` if template processing fails +/// +/// # Examples +/// +/// ```no_run +/// use morphology::{Sequence, Value}; +/// use morphology_img::{render_sequences, RenderConfig}; +/// +/// // Create some sequences +/// let sequences = vec![ +/// Sequence::new(vec![Value::origin()]), +/// Sequence::new(vec![Value::new(1, 0)]), +/// ]; +/// +/// // Configure rendering +/// let config = RenderConfig::new("output"); +/// +/// // Render to SVGs +/// let svg_paths = render_sequences(&sequences, &config).unwrap(); +/// println!("Generated {} SVG files", svg_paths.len()); +/// ``` +/// +/// # Advanced Configuration +/// +/// ```no_run +/// use morphology::{Sequence, Value}; +/// use morphology_img::{render_sequences, RenderConfig}; +/// +/// let sequences = vec![Sequence::new(vec![Value::origin()])]; +/// +/// // Keep temporary .ly files for debugging +/// let config = RenderConfig::new("output") +/// .keep_temp_files(true) +/// .lilypond_binary("/usr/local/bin/lilypond"); +/// +/// let svg_paths = render_sequences(&sequences, &config).unwrap(); +/// ``` +pub fn render_sequences( + sequences: &[morphology::Sequence], + config: &RenderConfig, +) -> Result<Vec<PathBuf>, RenderError> { + // Check if LilyPond is available before doing any work + render::check_lilypond_available()?; + + // Create temporary directory for .ly files + let temp_dir = file_gen::create_temp_dir()?; + + // Write support files (.ily) to temp directory + file_gen::write_support_files(temp_dir.path())?; + + // Generate .ly files from sequences + let ly_files = file_gen::generate_ly_files(sequences, temp_dir.path())?; + + // Render .ly files to SVGs + let svg_paths = render::render_ly_files_to_svg( + &ly_files, + &config.output_dir, + &config.lilypond_binary, + )?; + + // Handle temp directory cleanup + if config.keep_temp_files { + // Persist the temp directory by keeping it + let temp_path = temp_dir.keep(); + eprintln!("Temporary files kept at: {}", temp_path.display()); + } + // Otherwise, temp_dir will be automatically dropped and cleaned up + + Ok(svg_paths) +} diff --git a/morphology-img/src/render.rs b/morphology-img/src/render.rs index cd5b293..189dd61 100644 --- a/morphology-img/src/render.rs +++ b/morphology-img/src/render.rs @@ -1 +1,181 @@ // LilyPond CLI invocation for SVG generation + +use std::process::Command; +use std::path::{Path, PathBuf}; +use std::fs; +use crate::error::RenderError; + +/// Checks if LilyPond is available on the system. +/// +/// This function attempts to run `lilypond --version` to detect if LilyPond +/// is installed and accessible in the system PATH. +/// +/// # Returns +/// - `Ok(version_string)` if LilyPond is found and responds successfully +/// - `Err(RenderError::LilyPondNotFound)` if LilyPond is not found or fails to execute +/// +/// # Examples +/// ```no_run +/// use morphology_img::render::check_lilypond_available; +/// +/// match check_lilypond_available() { +/// Ok(version) => println!("LilyPond is available: {}", version), +/// Err(e) => eprintln!("LilyPond not found: {}", e), +/// } +/// ``` +/// +/// # Installation Instructions +/// If LilyPond is not found, install it from: +/// - **macOS**: `brew install lilypond` +/// - **Ubuntu/Debian**: `sudo apt-get install lilypond` +/// - **Windows**: Download from <https://lilypond.org/download.html> +pub fn check_lilypond_available() -> Result<String, RenderError> { + let output = Command::new("lilypond") + .arg("--version") + .output(); + + match output { + Ok(output) => { + if output.status.success() { + let version = String::from_utf8_lossy(&output.stdout); + Ok(version.lines().next().unwrap_or("Unknown version").to_string()) + } else { + Err(RenderError::LilyPondNotFound( + "LilyPond command failed".to_string() + )) + } + } + Err(e) => { + Err(RenderError::LilyPondNotFound( + format!("LilyPond not found in PATH: {}. Please install LilyPond from https://lilypond.org", e) + )) + } + } +} + +/// Renders a single .ly file to SVG using LilyPond. +/// +/// This function invokes the LilyPond CLI to convert a LilyPond source file +/// into an SVG image. The SVG file will be created in the specified output directory. +/// +/// # Arguments +/// - `ly_file`: Path to the .ly file to render +/// - `output_dir`: Directory where the SVG should be created +/// - `lilypond_binary`: Path to the LilyPond binary (typically "lilypond") +/// +/// # Returns +/// Path to the generated SVG file +/// +/// # Errors +/// - `RenderError::FileIO` if the output directory cannot be created +/// - `RenderError::LilyPondExecution` if LilyPond fails to execute or produce output +/// - `RenderError::Template` if the .ly filename is invalid +/// +/// # Examples +/// ```no_run +/// use morphology_img::render::render_ly_to_svg; +/// use std::path::Path; +/// +/// let ly_file = Path::new("/tmp/sequence-0.ly"); +/// let output_dir = Path::new("output"); +/// let lilypond = Path::new("lilypond"); +/// +/// let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond).unwrap(); +/// println!("Generated SVG: {}", svg_path.display()); +/// ``` +/// +/// # Notes +/// - LilyPond creates `filename.svg` from `filename.ly` in the output directory +/// - The function verifies that the expected SVG file was actually created +/// - LilyPond must be installed and the binary must be accessible +pub fn render_ly_to_svg( + ly_file: &Path, + output_dir: &Path, + lilypond_binary: &Path, +) -> Result<PathBuf, RenderError> { + // Ensure output directory exists + fs::create_dir_all(output_dir)?; + + // Build the command: lilypond --svg -o output_dir ly_file + let output = Command::new(lilypond_binary) + .arg("--svg") + .arg("-o") + .arg(output_dir) + .arg(ly_file) + .output()?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(RenderError::LilyPondExecution(stderr.to_string())); + } + + // Determine the output SVG path + // LilyPond creates filename.svg from filename.ly + let svg_filename = ly_file + .file_stem() + .ok_or_else(|| RenderError::Template("Invalid .ly filename".to_string()))? + .to_string_lossy() + .to_string() + ".svg"; + + let svg_path = output_dir.join(svg_filename); + + // Verify the SVG was created + if !svg_path.exists() { + return Err(RenderError::LilyPondExecution( + format!("Expected SVG not created: {}", svg_path.display()) + )); + } + + Ok(svg_path) +} + +/// Renders multiple .ly files to SVGs using LilyPond. +/// +/// This function processes multiple LilyPond source files sequentially, +/// converting each to an SVG image in the specified output directory. +/// +/// # Arguments +/// - `ly_files`: Paths to the .ly files to render +/// - `output_dir`: Directory where SVGs should be created +/// - `lilypond_binary`: Path to the LilyPond binary +/// +/// # Returns +/// Vector of paths to generated SVG files, in the same order as input +/// +/// # Errors +/// Returns an error if any file fails to render. Processing stops at the first error. +/// +/// # Examples +/// ```no_run +/// use morphology_img::render::render_ly_files_to_svg; +/// use std::path::{Path, PathBuf}; +/// +/// let ly_files = vec![ +/// PathBuf::from("/tmp/sequence-0.ly"), +/// PathBuf::from("/tmp/sequence-1.ly"), +/// ]; +/// let output_dir = Path::new("output"); +/// let lilypond = Path::new("lilypond"); +/// +/// let svg_paths = render_ly_files_to_svg(&ly_files, output_dir, lilypond).unwrap(); +/// println!("Generated {} SVG files", svg_paths.len()); +/// ``` +/// +/// # Notes +/// - Files are processed sequentially (not in parallel) +/// - All SVGs are created in the same output directory +/// - If any file fails, an error is returned immediately +pub fn render_ly_files_to_svg( + ly_files: &[PathBuf], + output_dir: &Path, + lilypond_binary: &Path, +) -> Result<Vec<PathBuf>, RenderError> { + let mut svg_paths = Vec::with_capacity(ly_files.len()); + + for ly_file in ly_files { + let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond_binary)?; + svg_paths.push(svg_path); + } + + Ok(svg_paths) +} diff --git a/morphology-img/src/template.rs b/morphology-img/src/template.rs index afa091b..15a47d5 100644 --- a/morphology-img/src/template.rs +++ b/morphology-img/src/template.rs @@ -1 +1,53 @@ // Template handling and substitution + +use crate::error::RenderError; + +/// Template files embedded at compile time +const TEMPLATE_LY: &str = include_str!("../static/template.ly"); +const FORMAT_ILY: &str = include_str!("../static/format.ily"); +const ENTRY_ILY: &str = include_str!("../static/entry.ily"); +const ELEMENTS_ILY: &str = include_str!("../static/elements.ily"); + +const PLACEHOLDER: &str = "%%%"; + +/// Returns the template .ly content +pub fn get_template() -> &'static str { + TEMPLATE_LY +} + +/// Returns the format.ily content +pub fn get_format_ily() -> &'static str { + FORMAT_ILY +} + +/// Returns the entry.ily content +pub fn get_entry_ily() -> &'static str { + ENTRY_ILY +} + +/// Returns the elements.ily content +pub fn get_elements_ily() -> &'static str { + ELEMENTS_ILY +} + +/// Substitutes the placeholder in the template with the provided markup. +/// +/// # Arguments +/// - `markup`: The LilyPond markup to substitute into the template +/// +/// # Returns +/// The complete .ly file content with substitution applied +/// +/// # Errors +/// Returns `RenderError::Template` if the placeholder is not found +pub fn substitute_template(markup: &str) -> Result<String, RenderError> { + let template = get_template(); + + if !template.contains(PLACEHOLDER) { + return Err(RenderError::Template( + "Template does not contain placeholder '%%%'".to_string() + )); + } + + Ok(template.replace(PLACEHOLDER, markup)) +} diff --git a/morphology-img/tests/config.rs b/morphology-img/tests/config.rs new file mode 100644 index 0000000..9b47ed5 --- /dev/null +++ b/morphology-img/tests/config.rs @@ -0,0 +1,185 @@ +use morphology_img::RenderConfig; +use std::path::PathBuf; + +#[test] +fn test_default_config() { + let config = RenderConfig::default(); + + assert_eq!(config.output_dir, PathBuf::from("output")); + assert!(!config.keep_temp_files); + assert_eq!(config.lilypond_binary, PathBuf::from("lilypond")); +} + +#[test] +fn test_new_config() { + let config = RenderConfig::new("my-output"); + + assert_eq!(config.output_dir, PathBuf::from("my-output")); + assert!(!config.keep_temp_files); + assert_eq!(config.lilypond_binary, PathBuf::from("lilypond")); +} + +#[test] +fn test_new_config_with_pathbuf() { + let path = PathBuf::from("/absolute/path/to/output"); + let config = RenderConfig::new(path.clone()); + + assert_eq!(config.output_dir, path); +} + +#[test] +fn test_builder_keep_temp_files() { + let config = RenderConfig::new("output") + .keep_temp_files(true); + + assert!(config.keep_temp_files); + assert_eq!(config.output_dir, PathBuf::from("output")); +} + +#[test] +fn test_builder_keep_temp_files_false() { + let config = RenderConfig::new("output") + .keep_temp_files(false); + + assert!(!config.keep_temp_files); +} + +#[test] +fn test_builder_lilypond_binary_str() { + let config = RenderConfig::new("output") + .lilypond_binary("/usr/local/bin/lilypond"); + + assert_eq!(config.lilypond_binary, PathBuf::from("/usr/local/bin/lilypond")); + assert_eq!(config.output_dir, PathBuf::from("output")); +} + +#[test] +fn test_builder_lilypond_binary_pathbuf() { + let lilypond_path = PathBuf::from("/custom/path/lilypond"); + let config = RenderConfig::new("output") + .lilypond_binary(lilypond_path.clone()); + + assert_eq!(config.lilypond_binary, lilypond_path); +} + +#[test] +fn test_builder_method_chaining() { + let config = RenderConfig::new("my-output") + .keep_temp_files(true) + .lilypond_binary("/usr/bin/lilypond"); + + assert_eq!(config.output_dir, PathBuf::from("my-output")); + assert!(config.keep_temp_files); + assert_eq!(config.lilypond_binary, PathBuf::from("/usr/bin/lilypond")); +} + +#[test] +fn test_builder_order_independence() { + // Test that builder methods work in any order + let config1 = RenderConfig::new("output") + .keep_temp_files(true) + .lilypond_binary("/usr/bin/lilypond"); + + let config2 = RenderConfig::new("output") + .lilypond_binary("/usr/bin/lilypond") + .keep_temp_files(true); + + assert_eq!(config1.output_dir, config2.output_dir); + assert_eq!(config1.keep_temp_files, config2.keep_temp_files); + assert_eq!(config1.lilypond_binary, config2.lilypond_binary); +} + +#[test] +fn test_config_is_clonable() { + let config1 = RenderConfig::new("output") + .keep_temp_files(true) + .lilypond_binary("/usr/bin/lilypond"); + + let config2 = config1.clone(); + + assert_eq!(config1.output_dir, config2.output_dir); + assert_eq!(config1.keep_temp_files, config2.keep_temp_files); + assert_eq!(config1.lilypond_binary, config2.lilypond_binary); +} + +#[test] +fn test_config_is_debuggable() { + let config = RenderConfig::new("output"); + let debug_str = format!("{:?}", config); + + // Should contain the struct name and fields + assert!(debug_str.contains("RenderConfig")); +} + +#[test] +fn test_multiple_configs_independent() { + let config1 = RenderConfig::new("output1") + .keep_temp_files(true); + + let config2 = RenderConfig::new("output2") + .keep_temp_files(false); + + // Verify they're independent + assert_eq!(config1.output_dir, PathBuf::from("output1")); + assert_eq!(config2.output_dir, PathBuf::from("output2")); + assert!(config1.keep_temp_files); + assert!(!config2.keep_temp_files); +} + +#[test] +fn test_config_with_relative_path() { + let config = RenderConfig::new("./relative/path"); + + assert_eq!(config.output_dir, PathBuf::from("./relative/path")); +} + +#[test] +fn test_config_with_absolute_path() { + let config = RenderConfig::new("/absolute/path"); + + assert_eq!(config.output_dir, PathBuf::from("/absolute/path")); +} + +#[test] +fn test_builder_overwrites_previous_values() { + let config = RenderConfig::new("output") + .keep_temp_files(true) + .keep_temp_files(false); // Override previous value + + assert!(!config.keep_temp_files); +} + +#[test] +fn test_config_fields_are_public() { + let config = RenderConfig::new("output"); + + // Should be able to access fields directly + let _output_dir = &config.output_dir; + let _keep_temp = config.keep_temp_files; + let _binary = &config.lilypond_binary; +} + +#[test] +fn test_default_values_are_sensible() { + let config = RenderConfig::default(); + + // Default output directory should be "output" + assert_eq!(config.output_dir, PathBuf::from("output")); + + // Should not keep temp files by default (for cleanliness) + assert!(!config.keep_temp_files); + + // Should use system lilypond by default + assert_eq!(config.lilypond_binary, PathBuf::from("lilypond")); +} + +#[test] +fn test_new_is_equivalent_to_default_with_custom_output() { + let config_new = RenderConfig::new("custom-output"); + let mut config_default = RenderConfig::default(); + config_default.output_dir = PathBuf::from("custom-output"); + + assert_eq!(config_new.output_dir, config_default.output_dir); + assert_eq!(config_new.keep_temp_files, config_default.keep_temp_files); + assert_eq!(config_new.lilypond_binary, config_default.lilypond_binary); +} diff --git a/morphology-img/tests/file_gen.rs b/morphology-img/tests/file_gen.rs new file mode 100644 index 0000000..e459688 --- /dev/null +++ b/morphology-img/tests/file_gen.rs @@ -0,0 +1,533 @@ +use morphology_img::file_gen::{generate_filename, create_temp_dir, write_support_files, generate_ly_file, generate_ly_files}; +use morphology::{Sequence, Value}; +use std::fs; +use std::path::PathBuf; + +// Tests for generate_filename + +#[test] +fn test_generate_filename_single_digit_padding() { + // With 10 sequences (1-9, plus 0), we need 2-digit padding + let filename = generate_filename(0, 10); + assert_eq!(filename.to_str().unwrap(), "sequence-00.ly"); + + let filename = generate_filename(5, 10); + assert_eq!(filename.to_str().unwrap(), "sequence-05.ly"); + + let filename = generate_filename(9, 10); + assert_eq!(filename.to_str().unwrap(), "sequence-09.ly"); +} + +#[test] +fn test_generate_filename_double_digit_padding() { + // With 100 sequences, we need 3-digit padding + let filename = generate_filename(0, 100); + assert_eq!(filename.to_str().unwrap(), "sequence-000.ly"); + + let filename = generate_filename(42, 100); + assert_eq!(filename.to_str().unwrap(), "sequence-042.ly"); + + let filename = generate_filename(99, 100); + assert_eq!(filename.to_str().unwrap(), "sequence-099.ly"); +} + +#[test] +fn test_generate_filename_triple_digit_padding() { + // With 1000 sequences, we need 4-digit padding + let filename = generate_filename(0, 1000); + assert_eq!(filename.to_str().unwrap(), "sequence-0000.ly"); + + let filename = generate_filename(42, 1000); + assert_eq!(filename.to_str().unwrap(), "sequence-0042.ly"); + + let filename = generate_filename(123, 1000); + assert_eq!(filename.to_str().unwrap(), "sequence-0123.ly"); + + let filename = generate_filename(999, 1000); + assert_eq!(filename.to_str().unwrap(), "sequence-0999.ly"); +} + +#[test] +fn test_generate_filename_single_sequence() { + // With just 1 sequence, we only need 1-digit padding + let filename = generate_filename(0, 1); + assert_eq!(filename.to_str().unwrap(), "sequence-0.ly"); +} + +#[test] +fn test_generate_filename_ten_sequences_boundary() { + // At exactly 10, we need 2 digits + let filename = generate_filename(0, 10); + assert_eq!(filename.to_str().unwrap(), "sequence-00.ly"); +} + +#[test] +fn test_generate_filename_lexicographic_ordering() { + // Verify that filenames sort correctly + let names: Vec<PathBuf> = (0..15).map(|i| generate_filename(i, 15)).collect(); + + let mut sorted_names = names.clone(); + sorted_names.sort(); + + // If padding is correct, the sorted order should be the same as generated order + assert_eq!(names, sorted_names); +} + +#[test] +fn test_generate_filename_has_ly_extension() { + let filename = generate_filename(5, 10); + assert!(filename.to_str().unwrap().ends_with(".ly")); +} + +#[test] +fn test_generate_filename_different_counts_same_index() { + // Same index but different total counts should have different padding + let name_10 = generate_filename(5, 10); + let name_100 = generate_filename(5, 100); + let name_1000 = generate_filename(5, 1000); + + assert_eq!(name_10.to_str().unwrap(), "sequence-05.ly"); + assert_eq!(name_100.to_str().unwrap(), "sequence-005.ly"); + assert_eq!(name_1000.to_str().unwrap(), "sequence-0005.ly"); +} + +// Tests for create_temp_dir + +#[test] +fn test_create_temp_dir_success() { + // Test that we can create a temp directory + let temp_dir = create_temp_dir(); + assert!(temp_dir.is_ok(), "should successfully create temp directory"); + + let dir = temp_dir.unwrap(); + let path = dir.path(); + + // Verify the directory exists + assert!(path.exists(), "temp directory should exist"); + assert!(path.is_dir(), "temp path should be a directory"); + + // TempDir will be dropped here and automatically cleaned up +} + +#[test] +fn test_create_temp_dir_is_empty() { + // Test that the newly created temp directory is empty + let temp_dir = create_temp_dir().unwrap(); + let entries = fs::read_dir(temp_dir.path()).unwrap(); + + assert_eq!(entries.count(), 0, "new temp directory should be empty"); +} + +#[test] +fn test_create_temp_dir_automatic_cleanup() { + let path; + { + let temp_dir = create_temp_dir().unwrap(); + path = temp_dir.path().to_path_buf(); + assert!(path.exists(), "temp directory should exist while TempDir is in scope"); + } // TempDir dropped here + + // After TempDir is dropped, directory should be cleaned up + assert!(!path.exists(), "temp directory should be cleaned up after drop"); +} + +#[test] +fn test_create_temp_dir_multiple_independent() { + // Test that we can create multiple independent temp directories + let dir1 = create_temp_dir().unwrap(); + let dir2 = create_temp_dir().unwrap(); + + assert_ne!(dir1.path(), dir2.path(), "temp directories should be different"); + assert!(dir1.path().exists()); + assert!(dir2.path().exists()); +} + +// Tests for write_support_files + +#[test] +fn test_write_support_files_success() { + let temp_dir = create_temp_dir().unwrap(); + + // Write support files + let result = write_support_files(temp_dir.path()); + assert!(result.is_ok(), "should successfully write support files"); + + // Verify all three files exist + let format_path = temp_dir.path().join("format.ily"); + let entry_path = temp_dir.path().join("entry.ily"); + let elements_path = temp_dir.path().join("elements.ily"); + + assert!(format_path.exists(), "format.ily should exist"); + assert!(entry_path.exists(), "entry.ily should exist"); + assert!(elements_path.exists(), "elements.ily should exist"); +} + +#[test] +fn test_write_support_files_content_correctness() { + let temp_dir = create_temp_dir().unwrap(); + + write_support_files(temp_dir.path()).unwrap(); + + // Read back the files and verify they have the correct content + let format_content = fs::read_to_string(temp_dir.path().join("format.ily")).unwrap(); + let entry_content = fs::read_to_string(temp_dir.path().join("entry.ily")).unwrap(); + let elements_content = fs::read_to_string(temp_dir.path().join("elements.ily")).unwrap(); + + // Verify content is non-empty + assert!(!format_content.is_empty(), "format.ily should have content"); + assert!(!entry_content.is_empty(), "entry.ily should have content"); + assert!(!elements_content.is_empty(), "elements.ily should have content"); + + // Verify content matches the embedded templates + use morphology_img::template::{get_format_ily, get_entry_ily, get_elements_ily}; + + assert_eq!(format_content, get_format_ily(), "format.ily content should match template"); + assert_eq!(entry_content, get_entry_ily(), "entry.ily content should match template"); + assert_eq!(elements_content, get_elements_ily(), "elements.ily content should match template"); +} + +#[test] +fn test_write_support_files_are_readable() { + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + // Verify files are readable + let format_path = temp_dir.path().join("format.ily"); + let entry_path = temp_dir.path().join("entry.ily"); + let elements_path = temp_dir.path().join("elements.ily"); + + assert!(fs::read_to_string(&format_path).is_ok(), "format.ily should be readable"); + assert!(fs::read_to_string(&entry_path).is_ok(), "entry.ily should be readable"); + assert!(fs::read_to_string(&elements_path).is_ok(), "elements.ily should be readable"); +} + +#[test] +fn test_write_support_files_count() { + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + // Count files in directory + let entries: Vec<_> = fs::read_dir(temp_dir.path()) + .unwrap() + .filter_map(|e| e.ok()) + .collect(); + + assert_eq!(entries.len(), 3, "should have exactly 3 support files"); +} + +#[test] +fn test_write_support_files_overwrite() { + let temp_dir = create_temp_dir().unwrap(); + + // Write support files first time + write_support_files(temp_dir.path()).unwrap(); + + // Write again (should overwrite) + let result = write_support_files(temp_dir.path()); + assert!(result.is_ok(), "should be able to overwrite existing files"); + + // Verify files still exist and have correct content + let format_content = fs::read_to_string(temp_dir.path().join("format.ily")).unwrap(); + assert!(!format_content.is_empty()); +} + +// Integration test + +#[test] +fn test_complete_file_generation_workflow() { + // Test the complete workflow of creating temp dir and writing support files + let temp_dir = create_temp_dir().unwrap(); + let temp_path = temp_dir.path(); + + // Directory should be empty initially + assert_eq!(fs::read_dir(temp_path).unwrap().count(), 0); + + // Write support files + write_support_files(temp_path).unwrap(); + + // Directory should now have 3 files + assert_eq!(fs::read_dir(temp_path).unwrap().count(), 3); + + // Generate some filenames + let filenames: Vec<_> = (0..5).map(|i| generate_filename(i, 5)).collect(); + + // Verify filenames are correctly padded + assert_eq!(filenames[0].to_str().unwrap(), "sequence-0.ly"); + assert_eq!(filenames[4].to_str().unwrap(), "sequence-4.ly"); + + // Simulate writing .ly files + for filename in &filenames { + let path = temp_path.join(filename); + fs::write(&path, "test content").unwrap(); + } + + // Now we should have 3 .ily files + 5 .ly files = 8 files + assert_eq!(fs::read_dir(temp_path).unwrap().count(), 8); +} + +// Tests for generate_ly_file + +#[test] +fn test_generate_ly_file_simple_sequence() { + // Create a simple test sequence + let seq = Sequence::new(vec![Value::origin()]); + + let temp_dir = create_temp_dir().unwrap(); + let output_path = temp_dir.path().join("test.ly"); + + // Generate .ly file + let result = generate_ly_file(&seq, &output_path); + assert!(result.is_ok(), "should successfully generate .ly file"); + + // Verify file exists + assert!(output_path.exists(), "generated file should exist"); + + // Verify file is readable + let content = fs::read_to_string(&output_path).unwrap(); + assert!(!content.is_empty(), "file should not be empty"); +} + +#[test] +fn test_generate_ly_file_content_structure() { + // Create the example sequence from the preliminary overview + let seq = Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), + ]); + + let temp_dir = create_temp_dir().unwrap(); + let output_path = temp_dir.path().join("test.ly"); + + generate_ly_file(&seq, &output_path).unwrap(); + + // Read the file and verify its content + let content = fs::read_to_string(&output_path).unwrap(); + + // Verify it contains the template structure + assert!(content.contains(r#"\version "2.24.0""#), "should have version declaration"); + assert!(content.contains(r#"\score"#), "should have score block"); + assert!(content.contains(r#"\entry"#), "should have entry block"); + assert!(content.contains(r#"\include "format.ily""#), "should include format.ily"); + assert!(content.contains(r#"\include "entry.ily""#), "should include entry.ily"); + assert!(content.contains(r#"\include "elements.ily""#), "should include elements.ily"); + + // Verify it contains the expected markup + assert!(content.contains("f'4 f4 e4 b4"), "should contain the generated markup"); + + // Verify the placeholder is gone + assert!(!content.contains("%%%"), "should not contain placeholder"); +} + +#[test] +fn test_generate_ly_file_is_valid_utf8() { + let seq = Sequence::new(vec![Value::new(1, 0)]); + + let temp_dir = create_temp_dir().unwrap(); + let output_path = temp_dir.path().join("test.ly"); + + generate_ly_file(&seq, &output_path).unwrap(); + + // Verify file is valid UTF-8 + let result = fs::read_to_string(&output_path); + assert!(result.is_ok(), "file should be valid UTF-8"); +} + +#[test] +fn test_generate_ly_file_overwrite() { + let seq1 = Sequence::new(vec![Value::origin()]); + let seq2 = Sequence::new(vec![Value::new(1, 0)]); + + let temp_dir = create_temp_dir().unwrap(); + let output_path = temp_dir.path().join("test.ly"); + + // Generate first file + generate_ly_file(&seq1, &output_path).unwrap(); + let content1 = fs::read_to_string(&output_path).unwrap(); + + // Generate second file (overwrite) + generate_ly_file(&seq2, &output_path).unwrap(); + let content2 = fs::read_to_string(&output_path).unwrap(); + + // Contents should be different + assert_ne!(content1, content2, "overwrite should change file content"); +} + +// Tests for generate_ly_files (batch) + +#[test] +fn test_generate_ly_files_multiple_sequences() { + // Create multiple test sequences + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + Sequence::new(vec![Value::new(-1, 0)]), + ]; + + let temp_dir = create_temp_dir().unwrap(); + + // Generate .ly files + let result = generate_ly_files(&sequences, temp_dir.path()); + assert!(result.is_ok(), "should successfully generate all files"); + + let paths = result.unwrap(); + + // Verify we got the correct number of paths + assert_eq!(paths.len(), 3, "should return 3 paths"); + + // Verify all files exist + for path in &paths { + assert!(path.exists(), "each generated file should exist"); + } +} + +#[test] +fn test_generate_ly_files_correct_filenames() { + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + Sequence::new(vec![Value::new(-1, 0)]), + ]; + + let temp_dir = create_temp_dir().unwrap(); + let paths = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + + // Verify filenames are correctly generated + assert!(paths[0].ends_with("sequence-0.ly")); + assert!(paths[1].ends_with("sequence-1.ly")); + assert!(paths[2].ends_with("sequence-2.ly")); +} + +#[test] +fn test_generate_ly_files_each_has_unique_content() { + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + ]; + + let temp_dir = create_temp_dir().unwrap(); + let paths = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + + // Read content of both files + let content1 = fs::read_to_string(&paths[0]).unwrap(); + let content2 = fs::read_to_string(&paths[1]).unwrap(); + + // Contents should be different + assert_ne!(content1, content2, "each file should have unique content based on its sequence"); +} + +#[test] +fn test_generate_ly_files_empty_slice() { + let sequences: Vec<Sequence> = vec![]; + + let temp_dir = create_temp_dir().unwrap(); + let result = generate_ly_files(&sequences, temp_dir.path()); + + assert!(result.is_ok(), "should handle empty slice"); + assert_eq!(result.unwrap().len(), 0, "should return empty vector"); +} + +#[test] +fn test_generate_ly_files_single_sequence() { + let sequences = vec![Sequence::new(vec![Value::origin()])]; + + let temp_dir = create_temp_dir().unwrap(); + let paths = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + + assert_eq!(paths.len(), 1); + assert!(paths[0].exists()); + assert!(paths[0].ends_with("sequence-0.ly")); +} + +#[test] +fn test_generate_ly_files_preserves_order() { + let sequences = vec![ + Sequence::new(vec![Value::new(5, 0)]), + Sequence::new(vec![Value::new(3, 0)]), + Sequence::new(vec![Value::new(1, 0)]), + ]; + + let temp_dir = create_temp_dir().unwrap(); + let paths = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + + // Read the markup from each file + for (i, path) in paths.iter().enumerate() { + let content = fs::read_to_string(path).unwrap(); + + // Verify the content corresponds to the right sequence + // Sequence with Value::new(outer, 0) and length 1 gives pitch = outer * 1 + 0 = outer + // Then integer_to_pitch_name: 5→g', 3→e', 1→c' + // (5+6=11, 11%7=4→"g", 11/7=1→') (3+6=9, 9%7=2→"e", 9/7=1→') (1+6=7, 7%7=0→"c", 7/7=1→') + match i { + 0 => assert!(content.contains("g'4"), "first file should have sequence 0 content"), + 1 => assert!(content.contains("e'4"), "second file should have sequence 1 content"), + 2 => assert!(content.contains("c'4"), "third file should have sequence 2 content"), + _ => panic!("unexpected index"), + } + } +} + +// Integration test: Complete pipeline + +#[test] +fn test_complete_ly_generation_pipeline() { + // Test the complete workflow from sequence to .ly file + + // Create test sequences + let sequences = vec![ + Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), + ]), + Sequence::new(vec![ + Value::origin(), + Value::new(1, 0), + ]), + ]; + + // Create temp directory + let temp_dir = create_temp_dir().unwrap(); + + // Write support files + write_support_files(temp_dir.path()).unwrap(); + + // Generate .ly files + let ly_paths = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + + // Verify we have 2 .ly files + assert_eq!(ly_paths.len(), 2); + + // Verify directory now has 5 files total (3 .ily + 2 .ly) + assert_eq!(fs::read_dir(temp_dir.path()).unwrap().count(), 5); + + // Verify each .ly file has correct structure + for path in &ly_paths { + let content = fs::read_to_string(path).unwrap(); + + // All files should have the template structure + assert!(content.contains(r#"\version"#)); + assert!(content.contains(r#"\score"#)); + assert!(content.contains(r#"\entry"#)); + + // All files should reference the .ily files + assert!(content.contains(r#"\include "format.ily""#)); + assert!(content.contains(r#"\include "entry.ily""#)); + assert!(content.contains(r#"\include "elements.ily""#)); + + // Should not contain placeholder + assert!(!content.contains("%%%")); + } + + // Verify specific content for first file + let content0 = fs::read_to_string(&ly_paths[0]).unwrap(); + assert!(content0.contains("f'4 f4 e4 b4"), "first file should have correct markup"); + + // Verify specific content for second file + // Sequence has length 2: [(0,0), (1,0)] + // Pitches: 0*2+0=0→b4, 1*2+0=2→d'4 + let content1 = fs::read_to_string(&ly_paths[1]).unwrap(); + assert!(content1.contains("b4 d'4"), "second file should have correct markup"); +} diff --git a/morphology-img/tests/integration.rs b/morphology-img/tests/integration.rs new file mode 100644 index 0000000..e6db544 --- /dev/null +++ b/morphology-img/tests/integration.rs @@ -0,0 +1,365 @@ +use morphology_img::{render_sequences, RenderConfig}; +use morphology::{Sequence, Value}; +use tempfile::TempDir; +use std::fs; + +/// Test the complete pipeline with basic configuration +#[test] +#[ignore] +fn test_render_sequences_basic() { + // Create test sequences + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + ]; + + // Use temp directory for output + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + // Render sequences + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + // Verify correct number of SVGs + assert_eq!(svg_paths.len(), 2, "should generate 2 SVG files"); + + // Verify all SVGs exist + for svg_path in &svg_paths { + assert!(svg_path.exists(), "SVG should exist: {}", svg_path.display()); + + // Verify SVG has content + let content = fs::read_to_string(svg_path).unwrap(); + assert!(content.contains("<svg"), "should contain SVG markup"); + assert!(!content.is_empty(), "SVG should not be empty"); + } + + // Verify SVGs are in output directory + for svg_path in &svg_paths { + assert!(svg_path.starts_with(output_dir.path())); + } +} + +/// Test with the example sequence from preliminary overview +#[test] +#[ignore] +fn test_render_sequences_example() { + let sequences = vec![ + Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), + ]), + ]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + assert_eq!(svg_paths.len(), 1); + assert!(svg_paths[0].exists()); + + // Verify substantial content + let content = fs::read_to_string(&svg_paths[0]).unwrap(); + assert!(content.len() > 1000, "should have substantial SVG content"); +} + +/// Test with empty sequence list +#[test] +#[ignore] +fn test_render_sequences_empty() { + let sequences: Vec<Sequence> = vec![]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + assert_eq!(svg_paths.len(), 0, "should return empty vector for empty input"); +} + +/// Test with single sequence +#[test] +#[ignore] +fn test_render_sequences_single() { + let sequences = vec![Sequence::new(vec![Value::origin()])]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + assert_eq!(svg_paths.len(), 1); + assert!(svg_paths[0].exists()); +} + +/// Test with many sequences +#[test] +#[ignore] +fn test_render_sequences_many() { + // Create 10 sequences + let sequences: Vec<Sequence> = (0..10) + .map(|i| Sequence::new(vec![Value::new(i, 0)])) + .collect(); + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + assert_eq!(svg_paths.len(), 10); + + // Verify all exist and have content + for svg_path in &svg_paths { + assert!(svg_path.exists()); + let content = fs::read_to_string(svg_path).unwrap(); + assert!(content.contains("<svg")); + } +} + +/// Test that temporary files are cleaned up by default +#[test] +#[ignore] +fn test_render_sequences_temp_cleanup() { + let sequences = vec![Sequence::new(vec![Value::origin()])]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let _svg_paths = render_sequences(&sequences, &config).unwrap(); + + // Temporary files should not be visible after function returns + // (they're cleaned up automatically) + // We can't directly test this without implementation details, + // but we can verify the function completed successfully +} + +/// Test with custom LilyPond binary path +#[test] +#[ignore] +fn test_render_sequences_custom_binary() { + let sequences = vec![Sequence::new(vec![Value::origin()])]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()) + .lilypond_binary("lilypond"); // Use system lilypond + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + assert_eq!(svg_paths.len(), 1); + assert!(svg_paths[0].exists()); +} + +/// Test that output directory is created if it doesn't exist +#[test] +#[ignore] +fn test_render_sequences_creates_output_dir() { + let sequences = vec![Sequence::new(vec![Value::origin()])]; + + let temp_base = TempDir::new().unwrap(); + let output_dir = temp_base.path().join("nested").join("output"); + + assert!(!output_dir.exists(), "output directory should not exist yet"); + + let config = RenderConfig::new(&output_dir); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + assert!(output_dir.exists(), "output directory should be created"); + assert_eq!(svg_paths.len(), 1); + assert!(svg_paths[0].exists()); +} + +/// Test SVG filenames match expected pattern +#[test] +#[ignore] +fn test_render_sequences_filenames() { + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + Sequence::new(vec![Value::new(2, 0)]), + ]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + // With 3 sequences, we should have sequence-0.svg, sequence-1.svg, sequence-2.svg + assert_eq!(svg_paths[0].file_name().unwrap().to_str().unwrap(), "sequence-0.svg"); + assert_eq!(svg_paths[1].file_name().unwrap().to_str().unwrap(), "sequence-1.svg"); + assert_eq!(svg_paths[2].file_name().unwrap().to_str().unwrap(), "sequence-2.svg"); +} + +/// Test that sequences are rendered in order +#[test] +#[ignore] +fn test_render_sequences_preserves_order() { + let sequences = vec![ + Sequence::new(vec![Value::new(5, 0)]), + Sequence::new(vec![Value::new(3, 0)]), + Sequence::new(vec![Value::new(1, 0)]), + ]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + // Verify order is preserved + assert_eq!(svg_paths.len(), 3); + assert_eq!(svg_paths[0].file_name().unwrap().to_str().unwrap(), "sequence-0.svg"); + assert_eq!(svg_paths[1].file_name().unwrap().to_str().unwrap(), "sequence-1.svg"); + assert_eq!(svg_paths[2].file_name().unwrap().to_str().unwrap(), "sequence-2.svg"); +} + +/// Test with different sequence lengths +#[test] +#[ignore] +fn test_render_sequences_different_lengths() { + let sequences = vec![ + Sequence::new(vec![Value::origin()]), // length 1 + Sequence::new(vec![Value::origin(), Value::new(1, 0)]), // length 2 + Sequence::new(vec![Value::origin(), Value::new(1, 0), Value::new(2, 0)]), // length 3 + ]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + assert_eq!(svg_paths.len(), 3); + + // All should be rendered successfully + for svg_path in &svg_paths { + assert!(svg_path.exists()); + let content = fs::read_to_string(svg_path).unwrap(); + assert!(content.contains("<svg")); + } +} + +/// Test that each SVG has unique content +#[test] +#[ignore] +fn test_render_sequences_unique_content() { + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + ]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + let content1 = fs::read_to_string(&svg_paths[0]).unwrap(); + let content2 = fs::read_to_string(&svg_paths[1]).unwrap(); + + // Contents should be different + assert_ne!(content1, content2, "each SVG should have unique content"); +} + +/// Test complete pipeline with complex sequences +#[test] +#[ignore] +fn test_render_sequences_complex() { + let sequences = vec![ + Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), + ]), + Sequence::new(vec![ + Value::new(2, 0), + Value::new(-2, 0), + ]), + Sequence::new(vec![ + Value::origin(), + Value::new(1, 0), + Value::new(2, 0), + Value::new(3, 0), + ]), + ]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + assert_eq!(svg_paths.len(), 3); + + // Verify all have substantial content + for svg_path in &svg_paths { + let content = fs::read_to_string(svg_path).unwrap(); + assert!(content.len() > 1000, "SVG should have substantial content"); + assert!(content.contains("<svg")); + assert!(content.contains("</svg>")); + } +} + +/// Test that function returns error if LilyPond is not available +#[test] +fn test_render_sequences_requires_lilypond() { + let sequences = vec![Sequence::new(vec![Value::origin()])]; + + let output_dir = TempDir::new().unwrap(); + + // Use a non-existent binary + let config = RenderConfig::new(output_dir.path()) + .lilypond_binary("/this/does/not/exist/lilypond"); + + let result = render_sequences(&sequences, &config); + + // Should fail with LilyPondNotFound or execution error + assert!(result.is_err(), "should fail when LilyPond is not available"); +} + +/// Integration test: Complete realistic workflow +#[test] +#[ignore] +fn test_render_sequences_realistic_workflow() { + // Create a realistic set of sequences + let sequences: Vec<Sequence> = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0), Value::new(-1, 0)]), + Sequence::new(vec![Value::new(2, 0), Value::origin(), Value::new(-2, 0)]), + Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), + ]), + ]; + + let output_dir = TempDir::new().unwrap(); + let config = RenderConfig::new(output_dir.path()); + + // Render all sequences + let svg_paths = render_sequences(&sequences, &config).unwrap(); + + // Verify results + assert_eq!(svg_paths.len(), 4, "should generate 4 SVGs"); + + // Verify all files exist and are valid + for (i, svg_path) in svg_paths.iter().enumerate() { + assert!(svg_path.exists(), "SVG {} should exist", i); + + // Verify in correct directory + assert!(svg_path.starts_with(output_dir.path())); + + // Verify content is valid SVG + let content = fs::read_to_string(svg_path).unwrap(); + assert!(content.contains("<svg"), "SVG {} should have svg tag", i); + assert!(content.contains("</svg>"), "SVG {} should have closing tag", i); + assert!(content.contains("xmlns"), "SVG {} should have XML namespace", i); + + // Verify substantial content + assert!(content.len() > 500, "SVG {} should have substantial content", i); + } + + // Verify correct filenames + assert_eq!(svg_paths[0].file_name().unwrap().to_str().unwrap(), "sequence-0.svg"); + assert_eq!(svg_paths[3].file_name().unwrap().to_str().unwrap(), "sequence-3.svg"); +} diff --git a/morphology-img/tests/render.rs b/morphology-img/tests/render.rs new file mode 100644 index 0000000..dc2c54a --- /dev/null +++ b/morphology-img/tests/render.rs @@ -0,0 +1,548 @@ +use morphology_img::render::{check_lilypond_available, render_ly_to_svg, render_ly_files_to_svg}; +use morphology_img::error::RenderError; +use morphology_img::file_gen::{create_temp_dir, generate_ly_file, write_support_files, generate_ly_files}; +use morphology::{Sequence, Value}; +use std::path::Path; +use tempfile::TempDir; + +/// This test requires LilyPond to be installed on the system. +/// Run with: cargo test -- --ignored +#[test] +#[ignore] +fn test_lilypond_available() { + let result = check_lilypond_available(); + + assert!(result.is_ok(), "LilyPond should be available for this test"); + + let version = result.unwrap(); + println!("LilyPond version: {}", version); + + // Verify the version string is not empty + assert!(!version.is_empty(), "version string should not be empty"); + + // Verify it contains "LilyPond" or starts with "GNU" + assert!( + version.contains("LilyPond") || version.starts_with("GNU"), + "version string should contain 'LilyPond' or start with 'GNU', got: {}", + version + ); +} + +/// Test that verifies the error type when LilyPond is not found. +/// This test will pass if LilyPond is NOT installed, or will be skipped if it is. +#[test] +fn test_lilypond_not_found_error_type() { + // Try to check for LilyPond + let result = check_lilypond_available(); + + // If it fails, verify it's the right error type + if let Err(e) = result { + match e { + RenderError::LilyPondNotFound(msg) => { + // Verify the error message is helpful + assert!(!msg.is_empty(), "error message should not be empty"); + assert!( + msg.contains("LilyPond") || msg.contains("PATH"), + "error message should mention LilyPond or PATH" + ); + } + _ => panic!("Expected RenderError::LilyPondNotFound, got: {:?}", e), + } + } else { + // If LilyPond is available, we can't test the error case, so skip + println!("LilyPond is installed, skipping error test"); + } +} + +/// Test that we handle the case where the command exists but fails +#[test] +fn test_command_failure_handling() { + use std::process::Command; + + // Use a command that exists but will fail with --version + // (most systems have 'false' which always returns non-zero) + let output = Command::new("false") + .output(); + + if output.is_ok() { + let out = output.unwrap(); + // If false command exists, verify we can detect failure status + assert!(!out.status.success(), "false command should have non-success status"); + } +} + +// Tests for render_ly_to_svg (single file SVG generation) + +/// Test rendering a single .ly file to SVG +#[test] +#[ignore] +fn test_render_single_svg() { + // Create a simple sequence + let seq = Sequence::new(vec![Value::origin()]); + + // Generate .ly file + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let ly_path = temp_dir.path().join("test.ly"); + generate_ly_file(&seq, &ly_path).unwrap(); + + // Render to SVG + let output_dir = TempDir::new().unwrap(); + let svg_path = render_ly_to_svg( + &ly_path, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + // Verify SVG exists + assert!(svg_path.exists(), "SVG file should exist"); + + // Verify SVG has content + let svg_content = std::fs::read_to_string(&svg_path).unwrap(); + assert!(svg_content.contains("<svg"), "file should contain SVG markup"); + assert!(!svg_content.is_empty(), "SVG file should not be empty"); +} + +/// Test rendering with the example sequence +#[test] +#[ignore] +fn test_render_example_sequence() { + // Create the example sequence + let seq = Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), + ]); + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let ly_path = temp_dir.path().join("example.ly"); + generate_ly_file(&seq, &ly_path).unwrap(); + + let output_dir = TempDir::new().unwrap(); + let svg_path = render_ly_to_svg( + &ly_path, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + // Verify SVG was created + assert!(svg_path.exists()); + + // Verify it contains SVG content + let svg_content = std::fs::read_to_string(&svg_path).unwrap(); + assert!(svg_content.contains("<svg")); + assert!(svg_content.len() > 1000, "SVG should have substantial content"); +} + +/// Test that output directory is created if it doesn't exist +#[test] +#[ignore] +fn test_creates_output_directory() { + let seq = Sequence::new(vec![Value::origin()]); + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let ly_path = temp_dir.path().join("test.ly"); + generate_ly_file(&seq, &ly_path).unwrap(); + + // Use a nested directory that doesn't exist yet + let output_base = TempDir::new().unwrap(); + let output_dir = output_base.path().join("nested").join("output"); + + assert!(!output_dir.exists(), "output directory should not exist yet"); + + let svg_path = render_ly_to_svg( + &ly_path, + &output_dir, + Path::new("lilypond"), + ).unwrap(); + + // Verify directory was created + assert!(output_dir.exists(), "output directory should be created"); + assert!(svg_path.exists(), "SVG should be in created directory"); +} + +/// Test rendering multiple different sequences +#[test] +#[ignore] +fn test_render_multiple_different_sequences() { + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + Sequence::new(vec![Value::new(-1, 0)]), + ]; + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let output_dir = TempDir::new().unwrap(); + + for (i, seq) in sequences.iter().enumerate() { + let ly_path = temp_dir.path().join(format!("seq-{}.ly", i)); + generate_ly_file(seq, &ly_path).unwrap(); + + let svg_path = render_ly_to_svg( + &ly_path, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + assert!(svg_path.exists()); + assert_eq!(svg_path.file_name().unwrap().to_str().unwrap(), format!("seq-{}.svg", i)); + } + + // Verify all 3 SVGs were created + let entries: Vec<_> = std::fs::read_dir(output_dir.path()) + .unwrap() + .filter_map(|e| e.ok()) + .collect(); + assert_eq!(entries.len(), 3, "should have 3 SVG files"); +} + +/// Test that SVG content is valid and contains expected elements +#[test] +#[ignore] +fn test_svg_content_validity() { + let seq = Sequence::new(vec![Value::origin()]); + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let ly_path = temp_dir.path().join("test.ly"); + generate_ly_file(&seq, &ly_path).unwrap(); + + let output_dir = TempDir::new().unwrap(); + let svg_path = render_ly_to_svg( + &ly_path, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + let svg_content = std::fs::read_to_string(&svg_path).unwrap(); + + // Verify SVG structure + assert!(svg_content.contains("<svg"), "should contain <svg tag"); + assert!(svg_content.contains("</svg>"), "should contain closing </svg> tag"); + assert!(svg_content.contains("xmlns"), "should contain XML namespace"); + + // LilyPond SVGs typically contain these elements + assert!(svg_content.contains("<g"), "should contain <g> group elements"); +} + +/// Test rendering with relative path for lilypond binary +#[test] +#[ignore] +fn test_render_with_relative_lilypond_path() { + let seq = Sequence::new(vec![Value::origin()]); + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let ly_path = temp_dir.path().join("test.ly"); + generate_ly_file(&seq, &ly_path).unwrap(); + + let output_dir = TempDir::new().unwrap(); + + // Use just "lilypond" as the binary name (will be found in PATH) + let svg_path = render_ly_to_svg( + &ly_path, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + assert!(svg_path.exists()); +} + +/// Test that the function returns an error if LilyPond fails +#[test] +#[ignore] +fn test_render_error_on_invalid_ly_file() { + use std::fs; + + let temp_dir = create_temp_dir().unwrap(); + + // Create an invalid .ly file (missing required structure) + let ly_path = temp_dir.path().join("invalid.ly"); + fs::write(&ly_path, "this is not valid lilypond syntax!!!").unwrap(); + + let output_dir = TempDir::new().unwrap(); + + let result = render_ly_to_svg( + &ly_path, + output_dir.path(), + Path::new("lilypond"), + ); + + // Should return an error + assert!(result.is_err(), "should fail on invalid .ly file"); + + match result { + Err(RenderError::LilyPondExecution(msg)) => { + assert!(!msg.is_empty(), "error message should not be empty"); + } + _ => panic!("expected LilyPondExecution error"), + } +} + +// Tests for render_ly_files_to_svg (batch SVG generation) + +/// Test rendering multiple .ly files to SVGs in batch +#[test] +#[ignore] +fn test_render_multiple_svgs_batch() { + // Create multiple sequences + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + Sequence::new(vec![Value::new(-1, 0)]), + ]; + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + // Generate .ly files + let ly_files = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + + // Render all to SVGs + let output_dir = TempDir::new().unwrap(); + let svg_paths = render_ly_files_to_svg( + &ly_files, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + // Verify all SVGs were created + assert_eq!(svg_paths.len(), 3, "should create 3 SVG files"); + + for svg_path in &svg_paths { + assert!(svg_path.exists(), "each SVG should exist"); + + // Verify SVG has content + let content = std::fs::read_to_string(svg_path).unwrap(); + assert!(content.contains("<svg"), "should contain SVG markup"); + } +} + +/// Test that batch rendering preserves order +#[test] +#[ignore] +fn test_batch_render_preserves_order() { + let sequences = vec![ + Sequence::new(vec![Value::new(5, 0)]), + Sequence::new(vec![Value::new(3, 0)]), + Sequence::new(vec![Value::new(1, 0)]), + ]; + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let ly_files = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + + let output_dir = TempDir::new().unwrap(); + let svg_paths = render_ly_files_to_svg( + &ly_files, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + // Verify filenames are in order + assert_eq!(svg_paths[0].file_name().unwrap().to_str().unwrap(), "sequence-0.svg"); + assert_eq!(svg_paths[1].file_name().unwrap().to_str().unwrap(), "sequence-1.svg"); + assert_eq!(svg_paths[2].file_name().unwrap().to_str().unwrap(), "sequence-2.svg"); + + // Verify all files exist + for path in &svg_paths { + assert!(path.exists()); + } +} + +/// Test batch rendering with empty list +#[test] +#[ignore] +fn test_batch_render_empty_list() { + let ly_files: Vec<std::path::PathBuf> = vec![]; + + let output_dir = TempDir::new().unwrap(); + let svg_paths = render_ly_files_to_svg( + &ly_files, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + assert_eq!(svg_paths.len(), 0, "should return empty vector for empty input"); +} + +/// Test batch rendering with single file +#[test] +#[ignore] +fn test_batch_render_single_file() { + let seq = Sequence::new(vec![Value::origin()]); + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let ly_path = temp_dir.path().join("single.ly"); + generate_ly_file(&seq, &ly_path).unwrap(); + + let ly_files = vec![ly_path]; + + let output_dir = TempDir::new().unwrap(); + let svg_paths = render_ly_files_to_svg( + &ly_files, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + assert_eq!(svg_paths.len(), 1); + assert!(svg_paths[0].exists()); + assert_eq!(svg_paths[0].file_name().unwrap().to_str().unwrap(), "single.svg"); +} + +/// Test that batch rendering stops on first error +#[test] +#[ignore] +fn test_batch_render_stops_on_error() { + use std::fs; + + let temp_dir = create_temp_dir().unwrap(); + + // Create one valid and one invalid .ly file + let seq = Sequence::new(vec![Value::origin()]); + write_support_files(temp_dir.path()).unwrap(); + + let valid_ly = temp_dir.path().join("valid.ly"); + generate_ly_file(&seq, &valid_ly).unwrap(); + + let invalid_ly = temp_dir.path().join("invalid.ly"); + fs::write(&invalid_ly, "invalid lilypond syntax!!!").unwrap(); + + let ly_files = vec![valid_ly, invalid_ly]; + + let output_dir = TempDir::new().unwrap(); + let result = render_ly_files_to_svg( + &ly_files, + output_dir.path(), + Path::new("lilypond"), + ); + + // Should fail due to invalid file + assert!(result.is_err(), "should fail on invalid file"); + + match result { + Err(RenderError::LilyPondExecution(_)) => { + // Expected error type + } + _ => panic!("expected LilyPondExecution error"), + } +} + +/// Test batch rendering with large number of files +#[test] +#[ignore] +fn test_batch_render_many_files() { + // Create 10 sequences + let sequences: Vec<Sequence> = (0..10) + .map(|i| Sequence::new(vec![Value::new(i, 0)])) + .collect(); + + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + let ly_files = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + + let output_dir = TempDir::new().unwrap(); + let svg_paths = render_ly_files_to_svg( + &ly_files, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + // Verify all 10 SVGs were created + assert_eq!(svg_paths.len(), 10, "should create 10 SVG files"); + + for (i, svg_path) in svg_paths.iter().enumerate() { + assert!(svg_path.exists()); + // With 10 files, we need 2-digit padding: 00, 01, 02, ..., 09 + assert_eq!( + svg_path.file_name().unwrap().to_str().unwrap(), + format!("sequence-{:02}.svg", i) + ); + } + + // Verify all files have content + for svg_path in &svg_paths { + let content = std::fs::read_to_string(svg_path).unwrap(); + assert!(content.contains("<svg")); + assert!(content.len() > 100, "SVG should have substantial content"); + } +} + +/// Integration test: Complete pipeline from sequences to SVGs +#[test] +#[ignore] +fn test_complete_pipeline_batch_rendering() { + // Create test sequences + let sequences = vec![ + Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), + ]), + Sequence::new(vec![ + Value::origin(), + Value::new(1, 0), + ]), + Sequence::new(vec![ + Value::new(2, 0), + ]), + ]; + + // Create temp directory and write support files + let temp_dir = create_temp_dir().unwrap(); + write_support_files(temp_dir.path()).unwrap(); + + // Generate .ly files + let ly_files = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + assert_eq!(ly_files.len(), 3); + + // Render all to SVGs + let output_dir = TempDir::new().unwrap(); + let svg_paths = render_ly_files_to_svg( + &ly_files, + output_dir.path(), + Path::new("lilypond"), + ).unwrap(); + + // Verify complete pipeline + assert_eq!(svg_paths.len(), 3); + + // Verify each SVG + for (i, svg_path) in svg_paths.iter().enumerate() { + // File exists + assert!(svg_path.exists(), "SVG {} should exist", i); + + // Correct filename + assert_eq!( + svg_path.file_name().unwrap().to_str().unwrap(), + format!("sequence-{}.svg", i) + ); + + // Has valid SVG content + let content = std::fs::read_to_string(svg_path).unwrap(); + assert!(content.contains("<svg"), "SVG {} should have svg tag", i); + assert!(content.contains("</svg>"), "SVG {} should have closing tag", i); + } + + // Verify all files are in output directory + let entries: Vec<_> = std::fs::read_dir(output_dir.path()) + .unwrap() + .filter_map(|e| e.ok()) + .collect(); + assert_eq!(entries.len(), 3, "output directory should have exactly 3 files"); +} diff --git a/morphology-img/tests/template.rs b/morphology-img/tests/template.rs new file mode 100644 index 0000000..60ef20e --- /dev/null +++ b/morphology-img/tests/template.rs @@ -0,0 +1,144 @@ +use morphology_img::template::{ + get_template, get_format_ily, get_entry_ily, get_elements_ily, substitute_template +}; +use morphology_img::error::RenderError; + +#[test] +fn test_embedded_templates_non_empty() { + // Test that all embedded templates are non-empty + assert!(!get_template().is_empty(), "template.ly should not be empty"); + assert!(!get_format_ily().is_empty(), "format.ily should not be empty"); + assert!(!get_entry_ily().is_empty(), "entry.ily should not be empty"); + assert!(!get_elements_ily().is_empty(), "elements.ily should not be empty"); +} + +#[test] +fn test_template_contains_placeholder() { + // Verify the template contains the placeholder + let template = get_template(); + assert!(template.contains("%%%"), "template should contain '%%%' placeholder"); +} + +#[test] +fn test_successful_substitution() { + // Test successful substitution with simple markup + let markup = "c'4 d'4 e'4"; + let result = substitute_template(markup); + + assert!(result.is_ok(), "substitution should succeed"); + + let substituted = result.unwrap(); + + // Verify the markup is present in the result + assert!(substituted.contains(markup), "result should contain the markup"); + + // Verify the placeholder is no longer present + assert!(!substituted.contains("%%%"), "result should not contain placeholder"); + + // Verify the template structure is preserved + assert!(substituted.contains(r#"\version "2.24.0""#), "version should be preserved"); + assert!(substituted.contains(r#"\score"#), "score block should be preserved"); + assert!(substituted.contains(r#"\entry"#), "entry should be preserved"); +} + +#[test] +fn test_substitution_with_empty_markup() { + // Test with empty markup string + let markup = ""; + let result = substitute_template(markup); + + assert!(result.is_ok(), "substitution with empty string should succeed"); + + let substituted = result.unwrap(); + + // Placeholder should be replaced with empty string + assert!(!substituted.contains("%%%")); +} + +#[test] +fn test_error_when_placeholder_missing() { + // This test simulates what would happen if the placeholder was missing + // We'll test this by creating a mock template without the placeholder + + // Note: We can't easily modify the embedded template at runtime, + // so we'll just verify the error handling works as designed + // by checking that our current template DOES have the placeholder + let template = get_template(); + + if !template.contains("%%%") { + // If this branch were taken, substitute_template would return an error + let result = substitute_template("test"); + assert!(result.is_err()); + + if let Err(RenderError::Template(msg)) = result { + assert!(msg.contains("placeholder")); + } else { + panic!("Expected RenderError::Template"); + } + } else { + // Current template has placeholder, which is correct + assert!(template.contains("%%%")); + } +} + +#[test] +fn test_template_structure() { + // Verify the template has the expected structure + let template = get_template(); + + assert!(template.contains(r#"\version"#), "should have version declaration"); + assert!(template.contains(r#"\include "format.ily""#), "should include format.ily"); + assert!(template.contains(r#"\include "elements.ily""#), "should include elements.ily"); + assert!(template.contains(r#"\include "entry.ily""#), "should include entry.ily"); + assert!(template.contains(r#"\score"#), "should have score block"); + assert!(template.contains(r#"\entry"#), "should have entry block"); +} + +#[test] +fn test_substitution_preserves_whitespace() { + // Test that substitution preserves indentation and whitespace + let markup = "c'4 d'4"; + let result = substitute_template(markup).unwrap(); + + // The indented structure should be preserved + // The markup should be indented within the entry block + assert!(result.contains(" \\entry")); +} + +#[test] +fn test_multiple_substitutions_independent() { + // Test that multiple calls to substitute_template are independent + let markup1 = "c'4 d'4"; + let markup2 = "e'4 f'4"; + + let result1 = substitute_template(markup1).unwrap(); + let result2 = substitute_template(markup2).unwrap(); + + assert!(result1.contains(markup1)); + assert!(!result1.contains(markup2)); + + assert!(result2.contains(markup2)); + assert!(!result2.contains(markup1)); +} + +#[test] +fn test_substitution_with_actual_sequence_markup() { + // Test with markup that would come from the actual transformation pipeline + // This is the example from the development plan + let markup = "f'4 f4 e4 b4"; + + let result = substitute_template(markup); + assert!(result.is_ok()); + + let substituted = result.unwrap(); + + // Verify it creates valid LilyPond syntax structure + assert!(substituted.contains(r#"\entry { "#)); + assert!(substituted.contains(markup)); + assert!(substituted.contains("}")); + + // The substituted markup should be between the entry braces + let entry_start = substituted.find(r#"\entry { "#).unwrap(); + let markup_pos = substituted.find(markup).unwrap(); + assert!(markup_pos > entry_start, "markup should be inside entry block"); +} |