Skip to content

Commit

Permalink
add few test update
Browse files Browse the repository at this point in the history
  • Loading branch information
doziestar committed Jun 24, 2024
1 parent 9167761 commit 51887ee
Show file tree
Hide file tree
Showing 18 changed files with 1,164 additions and 921 deletions.
23 changes: 23 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Use an Ubuntu base image
FROM ubuntu:20.04

# Avoid prompts from apt
ENV DEBIAN_FRONTEND=noninteractive

# Install necessary packages
RUN apt-get update && apt-get install -y \
curl \
build-essential \
pkg-config \
libssl-dev \
&& rm -rf /var/lib/apt/lists/*

# Install Rust
RUN curl https://sh.rustup.rs -sSf | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"

WORKDIR /app

COPY . /app

CMD ["cargo", "test"]
45 changes: 0 additions & 45 deletions src/rollback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,48 +101,3 @@ impl RollbackManager {
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;

#[test]
fn test_create_snapshot() {
let manager = RollbackManager::new();
let snapshot_id = manager.create_snapshot().unwrap();
assert_eq!(snapshot_id, 0);
}

#[test]
fn test_add_file_change() {
let manager = RollbackManager::new();
let snapshot_id = manager.create_snapshot().unwrap();

let temp_file = NamedTempFile::new().unwrap();
let file_path = temp_file.path().to_str().unwrap();

fs::write(file_path, b"original content").unwrap();
manager.add_file_change(snapshot_id, file_path).unwrap();

fs::write(file_path, b"modified content").unwrap();

manager.rollback_all().unwrap();

let content = fs::read_to_string(file_path).unwrap();
assert_eq!(content, "original content");
}

#[test]
fn test_add_package_installed() {
let manager = RollbackManager::new();
let snapshot_id = manager.create_snapshot().unwrap();

manager
.add_package_installed(snapshot_id, "test-package")
.unwrap();

let snapshots = manager.snapshots.borrow();
assert_eq!(snapshots[0].packages_installed[0], "test-package");
}
}
10 changes: 5 additions & 5 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::fs;
use std::io::{self, Write};
use std::process::Command;

pub(crate) fn setup_logging() -> Result<(), Box<dyn Error>> {
pub fn setup_logging() -> Result<(), Box<dyn Error>> {
let log_file = format!(
"/var/log/server_setup_{}.log",
Local::now().format("%Y%m%d_%H%M%S")
Expand All @@ -29,7 +29,7 @@ pub(crate) fn setup_logging() -> Result<(), Box<dyn Error>> {
Ok(())
}

pub(crate) fn get_user_input() -> Result<Config, Box<dyn Error>> {
pub fn get_user_input() -> Result<Config, Box<dyn Error>> {
let mut config = Config::default();

config.linux_distro = prompt("Enter Linux distribution (ubuntu/centos/fedora): ")?;
Expand Down Expand Up @@ -67,15 +67,15 @@ fn prompt(question: &str) -> Result<String, Box<dyn Error>> {
Ok(input.trim().to_string())
}

pub(crate) fn save_config(config: &Config) -> Result<(), Box<dyn Error>> {
pub fn save_config(config: &Config) -> Result<(), Box<dyn Error>> {
let config_path = "/etc/server_setup_config.json";
let config_json = serde_json::to_string_pretty(config)?;
fs::write(config_path, config_json)?;
info!("Configuration saved to {}", config_path);
Ok(())
}

pub(crate) fn run_command(command: &str, args: &[&str]) -> Result<(), Box<dyn Error>> {
pub fn run_command(command: &str, args: &[&str]) -> Result<(), Box<dyn Error>> {
info!("Running command: {} {:?}", command, args);
let output = Command::new(command).args(args).output()?;
if !output.status.success() {
Expand All @@ -91,7 +91,7 @@ pub(crate) fn run_command(command: &str, args: &[&str]) -> Result<(), Box<dyn Er
Ok(())
}

pub(crate) fn generate_report(config: &Config) -> Result<(), Box<dyn Error>> {
pub fn generate_report(config: &Config) -> Result<(), Box<dyn Error>> {
let report_path = "/root/server_setup_report.txt";
let mut report = String::new();

Expand Down
1 change: 1 addition & 0 deletions test_log_20240624_215458.log
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2024-06-24T21:54:58.246935+02:00 - INFO - Test log message
1 change: 1 addition & 0 deletions test_log_20240624_220838.log
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2024-06-24T22:08:38.539979+02:00 - INFO - Test log message
101 changes: 57 additions & 44 deletions tests/backup_tests.rs
Original file line number Diff line number Diff line change
@@ -1,63 +1,76 @@
use crate::common;
use crate::common::{MockConfig, MockRollbackManager};
use server_forge::backup::{
configure_backup_schedule, install_backup_tools, setup_backup_locations, setup_backup_system,
};
use std::ptr::eq;
use server_forge::backup;
use server_forge::config::Config;
use server_forge::rollback::RollbackManager;
use std::fs;
use std::os::unix::fs::PermissionsExt;

#[test]
fn test_setup_backup_system() {
let mut mock = common::CommandRunner::new();
let config = MockConfig {
backup_frequency: "daily".to_string(),
server_role: "web".to_string(),
fn test_install_backup_tools() {
assert!(backup::install_backup_tools().is_ok());

// Verify restic installation
let restic_status = std::process::Command::new("restic")
.arg("version")
.status()
.unwrap();
assert!(restic_status.success());
}

#[test]
fn test_configure_backup_schedule() {
let config = Config {
backup_frequency: String::from("daily"),
..Default::default()
};
let rollback = MockRollbackManager::new();

mock.expect_run().times(4).returning(|_, _| Ok(()));
assert!(backup::configure_backup_schedule(&config).is_ok());

assert!(setup_backup_system(&config, &rollback).is_ok());
// Verify cron job creation
let cron_content = fs::read_to_string("/etc/cron.d/restic-backup").unwrap();
assert!(cron_content.contains("0 2 * * * root /usr/bin/restic backup"));
}

#[test]
fn test_install_backup_tools() {
let mut mock = common::CommandRunner::new();
fn test_setup_backup_locations() {
let config = Config {
server_role: String::from("web"),
..Default::default()
};

mock.expect_run()
.with(eq("apt", ()), eq(&["install", "-y", "restic"], ()))
.times(1)
.returning(|_, _| Ok(()));
assert!(backup::setup_backup_locations(&config).is_ok());

assert!(install_backup_tools().is_ok());
}
// Verify backup script creation
let script_content = fs::read_to_string("/usr/local/bin/run-backup.sh").unwrap();
assert!(script_content.contains("restic backup"));
assert!(script_content.contains("/var/www"));
assert!(script_content.contains("/etc/nginx"));

// #[test]
// fn test_configure_backup_schedule() {
// let config = MockConfig {
// backup_frequency: "daily".to_string(),
// ..Default::default()
// };
//
// assert!(configure_backup_schedule(&config).is_ok());
//
// // Test invalid frequency
// let invalid_config = MockConfig {
// backup_frequency: "invalid".to_string(),
// ..Default::default()
// };
// assert!(configure_backup_schedule(&invalid_config).is_err());
// }
// Verify script permissions
let script_metadata = fs::metadata("/usr/local/bin/run-backup.sh").unwrap();
assert!(script_metadata.permissions().mode() & 0o111 != 0);
}

#[test]
fn test_setup_backup_locations() {
let mut mock = common::CommandRunner::new();
let config = MockConfig {
server_role: "web".to_string(),
fn test_setup_backup_system() {
let config = Config {
backup_frequency: String::from("daily"),
server_role: String::from("web"),
..Default::default()
};
let rollback_manager = RollbackManager::new();

assert!(backup::setup_backup_system(&config, &rollback_manager).is_ok());

// Verify restic installation
assert!(std::process::Command::new("restic")
.arg("version")
.status()
.unwrap()
.success());

mock.expect_run().times(2).returning(|_, _| Ok(()));
// Verify cron job creation
assert!(fs::read_to_string("/etc/cron.d/restic-backup").is_ok());

assert!(setup_backup_locations(&config).is_ok());
// Verify backup script creation
assert!(fs::read_to_string("/usr/local/bin/run-backup.sh").is_ok());
}
43 changes: 0 additions & 43 deletions tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,44 +1 @@
use mockall::automock;
use std::error::Error;

pub trait CommandRunner {
fn run(&self, command: &str, args: &[&str]) -> Result<(), Box<dyn Error>>;
}

pub struct MockCommandRunner;
#[automock]
impl CommandRunner for MockCommandRunner {
fn run(&self, command: &str, args: &[&str]) -> Result<(), Box<dyn Error>> {
Ok(())
}
}

#[derive(Clone, Default)]
pub struct MockConfig {
pub linux_distro: String,
pub server_role: String,
pub security_level: String,
pub monitoring: bool,
pub backup_frequency: String,
pub deployed_apps: Vec<String>,
pub custom_firewall_rules: Vec<String>,
pub update_schedule: String,
pub use_containers: bool,
pub use_kubernetes: bool,
}

pub struct MockRollbackManager;

impl MockRollbackManager {
pub fn new() -> Self {
MockRollbackManager
}

pub fn create_snapshot(&self) -> Result<usize, Box<dyn Error>> {
Ok(0)
}

pub fn commit_snapshot(&self, _snapshot_id: usize) -> Result<(), Box<dyn Error>> {
Ok(())
}
}
Loading

0 comments on commit 51887ee

Please sign in to comment.