#![cfg(all(feature = "cli", feature = "runner"))]
use std::fs;
use std::path::Path;
use std::process::{Command, Output};
use sha2::{Digest, Sha256};
use tempfile::tempdir;
const TEST_SESSION: &str = "test-session";
const TEST_ACCOUNT_ID: u64 = 123;
const TEST_SOLVER: &str = r#"
use aoc_toolkit::core::Day;
#[derive(Default)]
pub struct Solver {
input: String,
}
impl Day for Solver {
fn parse(&mut self, data: String) {
assert!(
std::env::var_os("SESSION_ID").is_none(),
"Session token must not be forwarded to the runner"
);
self.input = data;
}
fn task1(&self) -> String {
self.input.clone()
}
fn task2(&self) -> String {
"test-part-two".to_owned()
}
}
"#;
fn aoc_command(root: &Path, cache: &Path) -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_aoc"));
command
.current_dir(root)
.env("CARGO_TARGET_DIR", cache.join("test-target"))
.env("CARGO_NET_OFFLINE", "true")
.env("SESSION_ID", TEST_SESSION)
.env("AOC_TOOLKIT_CACHE_DIR", cache)
.env("HTTP_PROXY", "http://127.0.0.1:9")
.env("HTTPS_PROXY", "http://127.0.0.1:9")
.env("http_proxy", "http://127.0.0.1:9")
.env("https_proxy", "http://127.0.0.1:9")
.env("NO_PROXY", "")
.env("no_proxy", "");
command
}
fn aoc(root: &Path, cache: &Path, args: &[&str]) -> Output {
aoc_command(root, cache).args(args).output().unwrap()
}
fn assert_success(output: &Output) {
assert!(
output.status.success(),
"stdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
fn use_local_toolkit(root: &Path) {
let path = root.join("Cargo.toml");
let source = fs::read_to_string(&path).unwrap();
let mut manifest: toml::Value = toml::from_str(&source).unwrap();
let dependency = manifest["dependencies"]["aoc-toolkit"]
.as_table_mut()
.unwrap();
dependency.remove("version");
dependency.insert(
"path".to_owned(),
toml::Value::String(env!("CARGO_MANIFEST_DIR").to_owned()),
);
fs::write(path, toml::to_string(&manifest).unwrap()).unwrap();
fs::copy(
Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock"),
root.join("Cargo.lock"),
)
.unwrap();
}
fn prepare_cache(cache: &Path) {
let sessions = cache.join("sessions");
fs::create_dir_all(&sessions).unwrap();
let fingerprint = format!("{:x}", Sha256::digest(TEST_SESSION.as_bytes()));
fs::write(
sessions.join(format!("{fingerprint}.txt")),
TEST_ACCOUNT_ID.to_string(),
)
.unwrap();
}
fn cache_input(cache: &Path, year: usize, day: usize, input: &str) {
let path = cache
.join("inputs")
.join(TEST_ACCOUNT_ID.to_string())
.join(year.to_string());
fs::create_dir_all(&path).unwrap();
fs::write(path.join(format!("{day}.txt")), input).unwrap();
}
fn assert_stdout_contains(output: &Output, expected: &str) {
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
stdout.contains(expected),
"Expected {expected:?} in stdout:\n{stdout}",
);
}
fn assert_stdout_excludes(output: &Output, unexpected: &str) {
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
!stdout.contains(unexpected),
"Unexpected {unexpected:?} in stdout:\n{stdout}",
);
}
fn assert_failure(output: &Output, expected: &str) {
assert!(!output.status.success(), "Expected command to fail");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains(expected),
"Expected {expected:?} in stderr:\n{stderr}",
);
}
fn verify_runner_failure_paths(root: &Path, cache: &Path) {
let output = aoc(root, cache, &["run", "-y", "2025", "-d", "12"]);
assert_failure(&output, "Day 12 of 2025 is not registered");
let output = aoc(root, cache, &["run", "-y", "2023"]);
assert_failure(&output, "Year 2023 has no implemented days");
assert!(!cache.join("download.lock").exists());
assert_success(&aoc(root, cache, &["new", "-y", "2025", "-d", "3"]));
cache_input(cache, 2025, 3, "synthetic-unimplemented-input");
let output = aoc(root, cache, &["run", "-y", "2025", "-d", "3"]);
assert_failure(&output, "Solver panicked");
let output = aoc(root, cache, &["run", "--all"]);
assert_failure(&output, "Solver panicked");
for input in [
"synthetic-2024-01",
"synthetic-2025-01",
"synthetic-2025-02",
] {
assert_stdout_contains(&output, input);
}
assert_stdout_contains(&output, "Total days : 4");
assert_stdout_contains(&output, "Successful : 3");
assert_stdout_contains(&output, "Failed : 1");
}
fn runner_command(root: &Path, cache: &Path) -> Command {
let mut command = Command::new("cargo");
command
.current_dir(root)
.env("CARGO_TARGET_DIR", cache.join("test-target"))
.env("CARGO_NET_OFFLINE", "true")
.env_remove("SESSION_ID")
.args(["run", "--quiet", "--release", "--", "run"]);
command
}
fn verify_local_runner_failures(root: &Path, cache: &Path) {
let output = runner_command(root, cache)
.args(["-y", "2025", "-d", "1"])
.output()
.unwrap();
assert_failure(&output, "--input-dir");
let empty_inputs = tempdir().unwrap();
let output = runner_command(root, cache)
.args(["-y", "2025", "-d", "1", "--input-dir"])
.arg(empty_inputs.path())
.output()
.unwrap();
assert_failure(&output, "Failed to load puzzle input");
}
#[test]
fn initializes_registers_and_runs_solver() {
let directory = tempdir().unwrap();
let root = directory.path().join("project");
let cache = directory.path().join("global-cache");
fs::create_dir_all(&root).unwrap();
prepare_cache(&cache);
assert_success(&aoc(&root, &cache, &["init", "--name", "test-aoc"]));
use_local_toolkit(&root);
for (year, day, input) in [
(2024, 1, "synthetic-2024-01"),
(2025, 1, "synthetic-2025-01"),
(2025, 2, "synthetic-2025-02"),
] {
assert_success(&aoc(
&root,
&cache,
&[
"new",
"--year",
&year.to_string(),
"--day",
&day.to_string(),
],
));
let path = root
.join("src")
.join(year.to_string())
.join(format!("day{day}.rs"));
fs::write(path, TEST_SOLVER).unwrap();
cache_input(&cache, year, day, input);
}
let output = aoc(&root, &cache, &["run", "-y", "2024", "-d", "1"]);
assert_success(&output);
assert_stdout_contains(&output, "synthetic-2024-01");
assert_stdout_contains(&output, "test-part-two");
let output = aoc(&root, &cache, &["run"]);
assert_success(&output);
assert_stdout_contains(&output, "synthetic-2025-02");
assert_stdout_excludes(&output, "synthetic-2025-01");
let output = aoc(&root, &cache, &["run", "-y", "2025", "-d", "1", "-p", "2"]);
assert_success(&output);
assert_stdout_contains(&output, "test-part-two");
assert_stdout_excludes(&output, "synthetic-2025-01");
let output = aoc(&root, &cache, &["run", "-y", "2025", "--all"]);
assert_success(&output);
assert_stdout_contains(&output, "synthetic-2025-01");
assert_stdout_contains(&output, "synthetic-2025-02");
assert_stdout_excludes(&output, "synthetic-2024-01");
let output = aoc(&root, &cache, &["run", "--all"]);
assert_success(&output);
for input in [
"synthetic-2024-01",
"synthetic-2025-01",
"synthetic-2025-02",
] {
assert_stdout_contains(&output, input);
}
let output = aoc(
&root.join("src/2025"),
&cache,
&["run", "-y", "2025", "-d", "2"],
);
assert_success(&output);
assert_stdout_contains(&output, "synthetic-2025-02");
assert!(
!root.join("inputs").exists(),
"Puzzle inputs must remain outside the project",
);
assert!(
!cache.join("download.lock").exists(),
"Cached execution must not acquire a download lock",
);
let output = runner_command(&root, &cache)
.args(["--plan", "--all"])
.output()
.unwrap();
assert_success(&output);
let plan: Vec<(usize, usize)> = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(plan, vec![(2024, 1), (2025, 1), (2025, 2)],);
verify_runner_failure_paths(&root, &cache);
verify_local_runner_failures(&root, &cache);
}
#[test]
fn fetches_cached_input_without_project() {
let directory = tempdir().unwrap();
let root = directory.path().join("empty");
let cache = directory.path().join("global-cache");
fs::create_dir_all(&root).unwrap();
prepare_cache(&cache);
cache_input(&cache, 2025, 1, "test-input");
let output = aoc(&root, &cache, &["fetch", "-y", "2025", "-d", "1"]);
assert_success(&output);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Cached"));
assert!(stdout.contains("2025 / Day 01"));
assert!(!root.join("aoc.toml").exists());
assert!(!root.join("Cargo.toml").exists());
assert!(!root.join("inputs").exists());
}
#[test]
fn fetches_complete_cached_edition() {
let directory = tempdir().unwrap();
let root = directory.path().join("empty");
let cache = directory.path().join("global-cache");
fs::create_dir_all(&root).unwrap();
prepare_cache(&cache);
for day in 1..=12 {
cache_input(&cache, 2025, day, &format!("synthetic-input-{day}"));
}
let output = aoc(&root, &cache, &["fetch", "--year", "2025", "--all"]);
assert_success(&output);
for day in 1..=12 {
assert_stdout_contains(&output, &format!("2025 / Day {day:02} — Cached"));
}
assert_stdout_contains(&output, "Cached : 12");
assert_stdout_contains(&output, "Downloaded : 0");
assert_stdout_contains(&output, "Failed : 0");
assert!(!cache.join("download.lock").exists());
assert!(!root.join("inputs").exists());
assert!(!root.join("aoc.toml").exists());
}
#[test]
fn rejects_invalid_command_options() {
let directory = tempdir().unwrap();
let root = directory.path().join("empty");
let cache = directory.path().join("global-cache");
fs::create_dir_all(&root).unwrap();
for args in [
&["fetch", "--year", "2014"][..],
&["fetch", "--year", "2025", "--day", "13"],
&["fetch", "--all", "--day", "1"],
&["run", "--part", "3"],
&["run", "--all", "--day", "1"],
&["run", "--year", "2025", "--part", "1"],
] {
let output = aoc(&root, &cache, args);
assert!(
!output.status.success(),
"Invalid arguments accepted: {args:?}",
);
}
assert!(
!cache.exists(),
"Invalid options must not initialize the cache",
);
}
#[test]
fn environment_session_overrides_dotenv() {
let directory = tempdir().unwrap();
let root = directory.path().join("project");
let cache = directory.path().join("global-cache");
fs::create_dir_all(&root).unwrap();
prepare_cache(&cache);
cache_input(&cache, 2025, 1, "synthetic-input");
fs::write(root.join(".env"), "SESSION_ID=\"invalid;session\"\n").unwrap();
let output = aoc(&root, &cache, &["fetch", "-y", "2025", "-d", "1"]);
assert_success(&output);
assert_stdout_contains(&output, "Cached");
assert!(!cache.join("download.lock").exists());
}
#[test]
fn resolves_session_from_dotenv() {
let directory = tempdir().unwrap();
let root = directory.path().join("project");
let cache = directory.path().join("global-cache");
fs::create_dir_all(&root).unwrap();
prepare_cache(&cache);
cache_input(&cache, 2025, 1, "synthetic-input");
fs::write(root.join(".env"), format!("SESSION_ID={TEST_SESSION}\n")).unwrap();
let output = aoc_command(&root, &cache)
.env_remove("SESSION_ID")
.args(["fetch", "-y", "2025", "-d", "1"])
.output()
.unwrap();
assert_success(&output);
assert_stdout_contains(&output, "Cached");
assert!(!cache.join("download.lock").exists());
}
#[test]
fn rejects_invalid_session_override() {
let directory = tempdir().unwrap();
let root = directory.path().join("project");
let cache = directory.path().join("global-cache");
fs::create_dir_all(&root).unwrap();
prepare_cache(&cache);
cache_input(&cache, 2025, 1, "synthetic-input");
fs::write(root.join(".env"), format!("SESSION_ID={TEST_SESSION}\n")).unwrap();
let invalid_session = "invalid;session";
let output = aoc_command(&root, &cache)
.env("SESSION_ID", invalid_session)
.args(["fetch", "-y", "2025", "-d", "1"])
.output()
.unwrap();
assert_failure(&output, "Invalid Advent of Code session token");
assert_stdout_excludes(&output, invalid_session);
assert!(!String::from_utf8_lossy(&output.stderr).contains(invalid_session),);
assert!(!cache.join("download.lock").exists());
}