use std::fs; use std::io::{BufRead, BufReader, Read, Write}; use std::os::unix::net::UnixStream; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, bail}; struct TestDir(PathBuf); impl TestDir { fn new() -> Result { // long TMPDIRs like unsandboxed Nix build dirs // can exceed max path size limits so we'll use /tmp here // if we'd overshoot, but use the regular tmpdir instead let temp = std::env::temp_dir(); let base = if temp.as_os_str().len() > 72 && Path::new("/tmp").is_dir() { PathBuf::from("/tmp") } else { temp }; let pid = std::process::id(); for attempt in 0u32..64 { let nanos = SystemTime::now().duration_since(UNIX_EPOCH)?.subsec_nanos(); let path = base.join(format!("s-{pid:x}-{:x}", nanos.wrapping_add(attempt))); match fs::create_dir(&path) { Ok(()) => return Ok(Self(path)), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => return Err(error.into()), } } bail!("could not create test directory in {}", base.display()); } } impl Drop for TestDir { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } } struct Daemon(Child); impl Drop for Daemon { fn drop(&mut self) { if self.0.try_wait().ok().flatten().is_none() { let _ = Command::new("kill") .arg("-TERM") .arg(self.0.id().to_string()) .status(); let _ = self.0.wait(); } } } fn git(repo: &Path, args: &[&str]) -> Result<()> { let status = Command::new("git") .arg("-C") .arg(repo) .args(args) .env("GIT_AUTHOR_NAME", "test") .env("GIT_AUTHOR_EMAIL", "test@example.com") .env("GIT_COMMITTER_NAME", "test") .env("GIT_COMMITTER_EMAIL", "test@example.com") .stdout(Stdio::null()) .status()?; if !status.success() { bail!("git {args:?} exited with {status}"); } Ok(()) } fn refresh(socket: &Path, path: &Path) -> Result { let mut stream = UnixStream::connect(socket)?; stream.set_read_timeout(Some(Duration::from_secs(30)))?; writeln!(stream, "{}", path.display())?; let mut reply = String::new(); BufReader::new(stream).read_line(&mut reply)?; Ok(reply) } fn http(socket: &Path, path: &str) -> Result { let mut stream = UnixStream::connect(socket)?; stream.set_read_timeout(Some(Duration::from_secs(10)))?; write!( stream, "GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n" )?; let mut response = String::new(); stream.read_to_string(&mut response)?; Ok(response) } #[test] fn refreshes_published_repositories_and_reports_their_urls() -> Result<()> { let root = TestDir::new()?; let repo = root.0.join("repos/alice/thing"); fs::create_dir_all(&repo)?; git(&repo, &["init", "-q", "-b", "main"])?; fs::write(repo.join("README"), "hello")?; git(&repo, &["add", "README"])?; git(&repo, &["commit", "-q", "-m", "initial"])?; let socket = root.0.join("http.sock"); let control = root.0.join("control.sock"); let cache = root.0.join("cache"); let mut command = Command::new(env!("CARGO_BIN_EXE_sorceryd")); for (key, _) in std::env::vars_os() { if key.to_string_lossy().starts_with("SORCERY_") { command.env_remove(key); } } let mut daemon = Daemon( command .arg("serve") .arg("--config") .arg("/dev/null") .arg("--repositories") .arg(root.0.join("repos")) .arg("--cache") .arg(&cache) .arg("--socket") .arg(&socket) .arg("--control-socket") .arg(&control) .arg("--instance-name=test") .arg("--clone-url-base=https://git.example") .arg("--x-accel=false") .stdout(Stdio::null()) .spawn()?, ); let deadline = Instant::now() + Duration::from_secs(30); while !socket.exists() || !control.exists() { if let Some(status) = daemon.0.try_wait()? { bail!("daemon exited with {status}"); } if Instant::now() >= deadline { bail!("daemon sockets did not appear"); } std::thread::sleep(Duration::from_millis(20)); } assert_eq!( refresh(&control, &repo)?, "ok https://git.example/alice/thing\n" ); assert_eq!(refresh(&control, &root.0.join("repos/alice"))?, "ok\n"); assert!(refresh(&control, &root.0.join("missing"))?.starts_with("error ")); assert!(cache.join("alice/thing/.sorcery-state").is_file()); let page = http(&socket, "/alice/thing/")?; assert!(page.starts_with("HTTP/1.1 200"), "{page}"); assert!(page.contains("alice/thing")); let health = http(&socket, "/-/health")?; assert!( health.starts_with("HTTP/1.1 200") && health.contains("ok\n"), "{health}" ); let status = Command::new("kill") .arg("-TERM") .arg(daemon.0.id().to_string()) .status()?; assert!(status.success()); let status = daemon.0.wait().context("waiting for daemon shutdown")?; assert!(status.success(), "daemon exited with {status}"); assert!(!socket.exists() && !control.exists()); Ok(()) }