Cover some modules with tests

This commit is contained in:
Nikolai Rodionov 2024-01-10 18:13:45 +01:00
parent 85f1266e82
commit c07e3f57ea
Signed by: allanger
GPG Key ID: 0AA46A90E25592AD
11 changed files with 187 additions and 34 deletions

View File

@ -1,6 +1,6 @@
use log::{info, warn}; use log::{info, warn};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{fs::File, collections::HashMap}; use std::{collections::HashMap, fs::File};
pub(crate) mod extension; pub(crate) mod extension;
pub(crate) mod patch; pub(crate) mod patch;
@ -98,7 +98,7 @@ impl Chart {
Some(mut vars) => { Some(mut vars) => {
vars.extend(global_vars); vars.extend(global_vars);
Some(vars) Some(vars)
}, }
None => Some(global_vars), None => Some(global_vars),
} }
}; };

View File

@ -62,7 +62,12 @@ impl PatchInterface for YqPatch {
fn apply(&self, chart_local_path: String) -> Result<(), Box<dyn std::error::Error>> { fn apply(&self, chart_local_path: String) -> Result<(), Box<dyn std::error::Error>> {
let cmd = match self.op { let cmd = match self.op {
YqOperations::Add => { YqOperations::Add => {
let value = match self.value.clone().unwrap().starts_with(['{', '[', '\"', '\'']) { let value = match self
.value
.clone()
.unwrap()
.starts_with(['{', '[', '\"', '\''])
{
true => self.value.clone().unwrap(), true => self.value.clone().unwrap(),
false => format!("\"{}\"", self.value.clone().unwrap()), false => format!("\"{}\"", self.value.clone().unwrap()),
}; };

View File

@ -1,6 +1,5 @@
use std::process::{Command, ExitStatus};
use log::info; use log::info;
use std::process::Command;
pub(crate) fn cli_exec(command: String) -> Result<String, Box<dyn std::error::Error>> { pub(crate) fn cli_exec(command: String) -> Result<String, Box<dyn std::error::Error>> {
info!("executing: {}", command); info!("executing: {}", command);
@ -37,9 +36,11 @@ pub(crate) fn cli_exec_from_dir(
stdout.pop(); stdout.pop();
Ok(stdout) Ok(stdout)
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::helpers::cli::{cli_exec, cli_exec_from_dir}; use crate::helpers::cli::{cli_exec, cli_exec_from_dir};
use tempfile::TempDir;
#[test] #[test]
fn test_stderr() { fn test_stderr() {
@ -57,10 +58,19 @@ mod tests {
#[test] #[test]
fn test_stdout_current_dir() { fn test_stdout_current_dir() {
let dir = tempfile::tempdir().unwrap(); let dir = TempDir::new().unwrap();
let dir_str = dir.path().to_str().unwrap().to_string();
let command = "echo $PWD"; let command = "echo $PWD";
let dir_str = dir.into_path().into_os_string().into_string().unwrap();
let test = cli_exec_from_dir(command.to_string(), dir_str.clone()); let test = cli_exec_from_dir(command.to_string(), dir_str.clone());
assert!(test.unwrap().to_string().contains(dir_str.as_str())); assert!(test.unwrap().to_string().contains(dir_str.as_str()));
} }
#[test]
fn test_stderr_current_dir() {
let dir = TempDir::new().unwrap();
let dir_str = dir.path().to_str().unwrap().to_string();
let command = ">&2 echo \"error\" && exit 1";
let test = cli_exec_from_dir(command.to_string(), dir_str.clone());
assert_eq!(test.err().unwrap().to_string(), "error\n".to_string());
}
} }

View File

@ -3,6 +3,7 @@ pub(crate) mod helpers;
pub(crate) mod mirror; pub(crate) mod mirror;
pub(crate) mod patch; pub(crate) mod patch;
pub(crate) mod source; pub(crate) mod source;
pub(crate) mod template;
use clap::Parser; use clap::Parser;
use log::{error, info}; use log::{error, info};

View File

@ -1,6 +1,5 @@
use crate::helpers::cli::cli_exec_from_dir;
use super::Target; use super::Target;
use crate::{helpers::cli::cli_exec_from_dir, template};
pub(crate) struct CustomCommands { pub(crate) struct CustomCommands {
pub(crate) package: Vec<String>, pub(crate) package: Vec<String>,
@ -15,14 +14,14 @@ impl Target for CustomCommands {
dry_run: bool, dry_run: bool,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
for cmd_tmpl in self.package.clone() { for cmd_tmpl in self.package.clone() {
let mut reg = super::register_handlebars(); let mut reg = template::register_handlebars();
reg.register_template_string("cmd", cmd_tmpl)?; reg.register_template_string("cmd", cmd_tmpl)?;
let cmd = reg.render("cmd", &chart_local)?; let cmd = reg.render("cmd", &chart_local)?;
cli_exec_from_dir(cmd, workdir_path.clone())?; cli_exec_from_dir(cmd, workdir_path.clone())?;
} }
if !dry_run { if !dry_run {
for cmd_tmpl in self.upload.clone() { for cmd_tmpl in self.upload.clone() {
let mut reg = super::register_handlebars(); let mut reg = template::register_handlebars();
reg.register_template_string("cmd", cmd_tmpl)?; reg.register_template_string("cmd", cmd_tmpl)?;
let cmd = reg.render("cmd", &chart_local)?; let cmd = reg.render("cmd", &chart_local)?;
cli_exec_from_dir(cmd, workdir_path.clone())?; cli_exec_from_dir(cmd, workdir_path.clone())?;
@ -31,3 +30,93 @@ impl Target for CustomCommands {
Ok(()) Ok(())
} }
} }
#[cfg(test)]
mod tests {
use super::CustomCommands;
use crate::{mirror::Target, source::ChartLocal};
use std::{collections::HashMap, fs::create_dir_all, path::Path};
use tempfile::TempDir;
fn get_chart_local() -> crate::source::ChartLocal {
let mut vars: HashMap<String, String> = HashMap::new();
vars.insert("key".to_string(), "value".to_string());
ChartLocal {
name: "chart".to_string(),
version: "1.0.0".to_string(),
path: "chart-1.0.0".to_string(),
repo_url: "https:://helm.repo".to_string(),
vars,
}
}
fn prepare_test_workdir(chart_path: String) -> String {
let workdir = TempDir::new().unwrap().path().to_str().unwrap().to_string();
println!("test workdir is {}", workdir.clone());
create_dir_all(format!("{}/{}", workdir, chart_path)).unwrap();
workdir
}
#[test]
fn test_package_basic() {
let chart_local = get_chart_local();
let workdir = prepare_test_workdir(chart_local.path.clone());
let custom_commands = CustomCommands {
package: vec!["touch package".to_string()],
upload: vec!["touch upload".to_string()],
};
let cc_target: Box<dyn Target> = Box::from(custom_commands);
cc_target.push(workdir.clone(), chart_local, true).unwrap();
assert!(Path::new(&format!("{}/package", workdir)).exists());
assert!(!Path::new(&format!("{}/upload", workdir)).exists());
}
#[test]
fn test_upload_basic() {
let chart_local = get_chart_local();
let workdir = prepare_test_workdir(chart_local.path.clone());
let custom_commands = CustomCommands {
package: vec!["touch package".to_string()],
upload: vec!["touch upload".to_string()],
};
let cc_target: Box<dyn Target> = Box::from(custom_commands);
cc_target.push(workdir.clone(), chart_local, false).unwrap();
assert!(Path::new(&format!("{}/package", workdir)).exists());
assert!(Path::new(&format!("{}/upload", workdir)).exists());
}
#[test]
fn test_templates() {
let chart_local = get_chart_local();
let workdir = prepare_test_workdir(chart_local.path.clone());
let custom_commands = CustomCommands {
package: vec!["touch {{ name }}-{{ version }}".to_string()],
upload: vec!["touch {{ repo_url }}-{{ vars.key }}".to_string()],
};
let cc_target: Box<dyn Target> = Box::from(custom_commands);
cc_target
.push(workdir.clone(), chart_local.clone(), true)
.unwrap();
assert!(Path::new(&format!(
"{}/{}-{}",
workdir, chart_local.name, chart_local.version
))
.exists());
assert!(!Path::new(&format!(
"{}/{}-{}",
workdir,
chart_local.repo_url,
chart_local.vars.get("key").unwrap()
))
.exists());
}
}

View File

@ -1,4 +1,4 @@
use crate::{helpers::cli::cli_exec_from_dir, source::ChartLocal}; use crate::{helpers::cli::cli_exec_from_dir, source::ChartLocal, template};
use dircpy::*; use dircpy::*;
use super::Target; use super::Target;
@ -18,7 +18,7 @@ impl Target for Git {
chart_local: ChartLocal, chart_local: ChartLocal,
dry_run: bool, dry_run: bool,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let mut reg = super::register_handlebars(); let mut reg = template::register_handlebars();
// Prepare the URL // Prepare the URL
reg.register_template_string("url", self.url.clone())?; reg.register_template_string("url", self.url.clone())?;
let url = reg.render("url", &chart_local)?; let url = reg.render("url", &chart_local)?;

View File

@ -1,7 +1,3 @@
use chrono::prelude::*;
use handlebars::{handlebars_helper, Handlebars};
use time::{format_description::parse, OffsetDateTime};
use crate::{config::Mirror, source::ChartLocal}; use crate::{config::Mirror, source::ChartLocal};
pub(crate) mod custom_command; pub(crate) mod custom_command;
@ -44,13 +40,3 @@ pub(crate) fn mirror_from_mirror_obj(
mirror.name mirror.name
))) )))
} }
handlebars_helper!(date_helper: | | Utc::now().format("%Y-%m-%d").to_string());
handlebars_helper!(time_helper: | | Utc::now().format("%H-%M-%S").to_string());
pub(crate) fn register_handlebars() -> Handlebars<'static> {
let mut handlebars = Handlebars::new();
handlebars.register_helper("date", Box::new(date_helper));
handlebars.register_helper("time", Box::new(time_helper));
handlebars
}

View File

@ -1,4 +1,7 @@
use std::{fs::{self, rename}, collections::HashMap}; use std::{
collections::HashMap,
fs::{self, rename},
};
use crate::helpers::cli::{cli_exec, cli_exec_from_dir}; use crate::helpers::cli::{cli_exec, cli_exec_from_dir};
use base64::{engine::general_purpose, Engine as _}; use base64::{engine::general_purpose, Engine as _};
@ -24,7 +27,11 @@ impl From<crate::config::Chart> for Git {
} }
impl Repo for Git { impl Repo for Git {
fn pull(&self, workdir_path: String, vars: HashMap<String, String>) -> Result<ChartLocal, Box<dyn std::error::Error>> { fn pull(
&self,
workdir_path: String,
vars: HashMap<String, String>,
) -> Result<ChartLocal, Box<dyn std::error::Error>> {
let repo_local_name = general_purpose::STANDARD_NO_PAD.encode(self.git_url.clone()); let repo_local_name = general_purpose::STANDARD_NO_PAD.encode(self.git_url.clone());
let cmd = format!( let cmd = format!(
"git clone {} {}/{}", "git clone {} {}/{}",

View File

@ -1,7 +1,7 @@
use super::{ChartLocal, Repo}; use super::{ChartLocal, Repo};
use crate::helpers::cli::{cli_exec, cli_exec_from_dir}; use crate::helpers::cli::{cli_exec, cli_exec_from_dir};
use base64::{engine::general_purpose, Engine as _}; use base64::{engine::general_purpose, Engine as _};
use std::{fs::rename, collections::HashMap}; use std::{collections::HashMap, fs::rename};
pub(crate) enum RepoKind { pub(crate) enum RepoKind {
Default, Default,
@ -46,7 +46,11 @@ impl Helm {
} }
} }
fn pull_default(&self, workdir_path: String, vars: HashMap<String, String>) -> Result<ChartLocal, Box<dyn std::error::Error>> { fn pull_default(
&self,
workdir_path: String,
vars: HashMap<String, String>,
) -> Result<ChartLocal, Box<dyn std::error::Error>> {
// Add repo and update // Add repo and update
let repo_local_name = general_purpose::STANDARD_NO_PAD.encode(self.repository_url.clone()); let repo_local_name = general_purpose::STANDARD_NO_PAD.encode(self.repository_url.clone());
let cmd = format!("helm repo add {} {}", repo_local_name, self.repository_url); let cmd = format!("helm repo add {} {}", repo_local_name, self.repository_url);
@ -93,7 +97,11 @@ impl Helm {
} }
impl Repo for Helm { impl Repo for Helm {
fn pull(&self, workdir_path: String, vars: HashMap<String, String>) -> Result<ChartLocal, Box<dyn std::error::Error>> { fn pull(
&self,
workdir_path: String,
vars: HashMap<String, String>,
) -> Result<ChartLocal, Box<dyn std::error::Error>> {
let repository_kind = self.repo_kind_from_url()?; let repository_kind = self.repo_kind_from_url()?;
let path = match repository_kind { let path = match repository_kind {
RepoKind::Default => self.pull_default(workdir_path, vars)?, RepoKind::Default => self.pull_default(workdir_path, vars)?,

View File

@ -12,7 +12,7 @@ pub(crate) struct ChartLocal {
pub(crate) version: String, pub(crate) version: String,
pub(crate) path: String, pub(crate) path: String,
pub(crate) repo_url: String, pub(crate) repo_url: String,
pub(crate) vars: HashMap<String, String> pub(crate) vars: HashMap<String, String>,
} }
impl ChartLocal { impl ChartLocal {
@ -22,7 +22,11 @@ impl ChartLocal {
} }
pub(crate) trait Repo { pub(crate) trait Repo {
fn pull(&self, workdir_path: String, vars: HashMap<String, String>) -> Result<ChartLocal, Box<dyn std::error::Error>>; fn pull(
&self,
workdir_path: String,
vars: HashMap<String, String>,
) -> Result<ChartLocal, Box<dyn std::error::Error>>;
} }
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]

43
src/template/mod.rs Normal file
View File

@ -0,0 +1,43 @@
use chrono::prelude::*;
use handlebars::{handlebars_helper, Handlebars};
handlebars_helper!(date_helper: | | Utc::now().format("%Y-%m-%d").to_string());
handlebars_helper!(time_helper: | | Utc::now().format("%H-%M-%S").to_string());
pub(crate) fn register_handlebars() -> Handlebars<'static> {
let mut handlebars = Handlebars::new();
handlebars.register_helper("date", Box::new(date_helper));
handlebars.register_helper("time", Box::new(time_helper));
handlebars
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use chrono::Utc;
use crate::template::register_handlebars;
#[test]
fn test_date_helper() {
let mut reg = register_handlebars();
reg.register_template_string("test", "{{ date }}").unwrap();
let result = reg
.render("test", &HashMap::<String, String>::new())
.unwrap();
let expected = Utc::now().format("%Y-%m-%d").to_string();
assert_eq!(result, expected);
}
#[test]
fn test_time_helper() {
let mut reg = register_handlebars();
reg.register_template_string("test", "{{ time }}").unwrap();
let result = reg
.render("test", &HashMap::<String, String>::new())
.unwrap();
let expected = Utc::now().format("%H-%M-%S").to_string();
assert_eq!(result, expected);
}
}