Skip to content

Commit

Permalink
test(ssg): ✅ Add new unit tests for ssg-template
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastienrousseau committed Sep 18, 2024
1 parent 94b1939 commit 730c241
Show file tree
Hide file tree
Showing 4 changed files with 650 additions and 24 deletions.
83 changes: 59 additions & 24 deletions ssg-template/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,19 +117,26 @@ impl Engine {
template: &str,
context: &HashMap<&str, &str>,
) -> Result<String, TemplateError> {
if template.trim().is_empty() {
return Err(TemplateError::RenderError(
"Template is empty".to_string(),
));
}

let mut output = template.to_owned();
for (key, value) in context {
output = output.replace(&format!("{{{{{}}}}}", key), value);
}
// Check if all keys have been replaced
if output.contains("{{") {
Err(TemplateError::RenderError(format!(
"Failed to render template, unresolved template tags: {}",
output
)))
} else {
Ok(output)

// Check if all keys have been replaced or if the template contains unresolved or invalid tags
if output.contains("{{") || output.contains("{") {
return Err(TemplateError::RenderError(format!(
"Failed to render template, unresolved or invalid template tags: {}",
output
)));
}

Ok(output)
}

/// Creates a template folder based on the provided template path or uses the default template folder.
Expand Down Expand Up @@ -241,24 +248,52 @@ impl Engine {

Ok(template_dir_path)
}

Check warning on line 250 in ssg-template/src/engine.rs

View check run for this annotation

Codecov / codecov/patch

ssg-template/src/engine.rs#L249-L250

Added lines #L249 - L250 were not covered by tests
}

#[cfg(test)]
mod tests {
use super::*;
/// Downloads a set of template files from a given URL into a temporary directory.
///
/// # Arguments
///
/// * `url` - The base URL to download the files from.
///
/// # Returns
///
/// A `Result` containing the path to the downloaded files, or a `TemplateError` if something goes wrong.
///
/// # Errors
///
/// This function returns an error if the URL is invalid or if the files fail to download.
///
/// # Example
///
/// ```
/// use ssg_template::Engine;
/// let engine = Engine::new("dummy/path");
/// let result = engine.download_template_files("https://example.com/templates");
/// ```
pub fn download_template_files(
&self,
url: &str,
) -> Result<PathBuf, TemplateError> {
let tempdir = tempfile::Builder::new()
.prefix("templates")
.tempdir()
.map_err(TemplateError::Io)?;

Check warning on line 280 in ssg-template/src/engine.rs

View check run for this annotation

Codecov / codecov/patch

ssg-template/src/engine.rs#L280

Added line #L280 was not covered by tests
let template_dir_path = tempdir.path().to_owned();

#[test]
fn test_render_template() {
let engine = Engine::new("dummy/path");
let mut context = HashMap::new();
context.insert("name", "World");
context.insert("greeting", "Hello");
let files =
["contact.html", "index.html", "page.html", "post.html"];
for file in files.iter() {
let file_url = format!("{}/{}", url, file);
let file_path = template_dir_path.join(file);
let mut response = reqwest::blocking::get(&file_url)
.map_err(TemplateError::Reqwest)?;

Check warning on line 289 in ssg-template/src/engine.rs

View check run for this annotation

Codecov / codecov/patch

ssg-template/src/engine.rs#L289

Added line #L289 was not covered by tests
let mut file =
File::create(&file_path).map_err(TemplateError::Io)?;
response
.copy_to(&mut file)
.map_err(TemplateError::Reqwest)?;

Check warning on line 294 in ssg-template/src/engine.rs

View check run for this annotation

Codecov / codecov/patch

ssg-template/src/engine.rs#L294

Added line #L294 was not covered by tests
}

let template = "{{greeting}}, {{name}}!";
let result =
engine.render_template(template, &context).unwrap();
assert_eq!(result, "Hello, World!");
Ok(template_dir_path)
}

// Add more tests for other methods
}
37 changes: 37 additions & 0 deletions ssg-template/tests/context_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use ssg_template::Context;

#[test]
fn test_context_new() {
let context = Context::new();
assert!(context.elements.is_empty());
}

#[test]
fn test_context_set_and_get() {
let mut context = Context::new();
context.set("name", "Alice");
assert_eq!(context.get("name"), Some(&"Alice"));
}

#[test]
fn test_context_update_existing_key() {
let mut context = Context::new();
context.set("name", "Alice");
context.set("name", "Bob");
assert_eq!(context.get("name"), Some(&"Bob"));
}

#[test]
fn test_context_get_nonexistent_key() {
let context = Context::new();
assert_eq!(context.get("nonexistent"), None);
}

#[test]
fn test_context_multiple_entries() {
let mut context = Context::new();
context.set("name", "Alice");
context.set("age", "30");
assert_eq!(context.get("name"), Some(&"Alice"));
assert_eq!(context.get("age"), Some(&"30"));
}
Loading

0 comments on commit 730c241

Please sign in to comment.