Archived
feat(service): add IPC communication and service management
Implement proper CLI-to-service communication via Unix domain sockets, fixing issue where CLI commands couldn't see jobs managed by the service. Key changes: - Add IPC client/server for CLI-service communication - Fix directory mismatch (CLI used java.io.tmpdir, service used /tmp/barn) - Add service management commands (start, stop, restart, reload, logs) - Add service installation for macOS (launchd), Linux (systemd), Windows - Add process usage monitoring (barn usage command) - Add job state breakdown in service status (succeeded, failed, canceled) - Add output formatters (human, JSON, XML) - Add crash recovery and heartbeat checking - Add structured logging with MDC context The CLI commands now properly communicate with the running service via IPC, ensuring consistent job state visibility. Fixes #24 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
818c45de0a
commit
92810cabee
103 files changed
+17457
-101
No files matched your search
@@ -2,11 +2,15 @@ package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
@@ -15,17 +19,23 @@ import picocli.CommandLine;
|
||||
*/
|
||||
class BarnCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private CommandLine commandLine;
|
||||
private StringWriter outWriter;
|
||||
private StringWriter errWriter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
void setUp() throws IOException {
|
||||
commandLine = new CommandLine(new BarnCommand());
|
||||
outWriter = new StringWriter();
|
||||
errWriter = new StringWriter();
|
||||
commandLine.setOut(new PrintWriter(outWriter));
|
||||
commandLine.setErr(new PrintWriter(errWriter));
|
||||
|
||||
// Initialize barn directories in temp location
|
||||
Files.createDirectories(tempDir.resolve("jobs"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -172,58 +182,59 @@ class BarnCommandTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void runSubcommand_shouldShowNotImplementedMessage() {
|
||||
void runSubcommand_withNoArgs_shouldShowUsageError() {
|
||||
// Arrange & Act
|
||||
int exitCode = commandLine.execute("run");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Run command not yet implemented");
|
||||
// Assert - run with no command args shows usage help (required parameter missing)
|
||||
assertThat(exitCode).isNotZero();
|
||||
// Picocli shows usage when required parameter is missing
|
||||
String output = errWriter.toString();
|
||||
assertThat(output).contains("run");
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusSubcommand_shouldShowNotImplementedMessage() {
|
||||
// Arrange & Act
|
||||
int exitCode = commandLine.execute("status");
|
||||
void statusSubcommand_withoutOffline_shouldIndicateServiceNeeded() {
|
||||
// Arrange & Act - use temp dir to ensure no service is running there
|
||||
int exitCode = commandLine.execute("status", "--barn-dir", tempDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Status command not yet implemented");
|
||||
// Assert - without --offline, should fail with service not running message
|
||||
assertThat(exitCode).isNotZero();
|
||||
String output = errWriter.toString();
|
||||
assertThat(output).containsIgnoringCase("service");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeSubcommand_shouldShowNotImplementedMessage() {
|
||||
void describeSubcommand_withNoJobId_shouldShowUsageError() {
|
||||
// Arrange & Act
|
||||
int exitCode = commandLine.execute("describe");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Describe command not yet implemented");
|
||||
// Assert - describe without job ID shows usage help (required parameter missing)
|
||||
assertThat(exitCode).isNotZero();
|
||||
String output = errWriter.toString();
|
||||
assertThat(output).contains("describe");
|
||||
}
|
||||
|
||||
@Test
|
||||
void killSubcommand_shouldShowNotImplementedMessage() {
|
||||
void killSubcommand_withNoJobId_shouldShowUsageError() {
|
||||
// Arrange & Act
|
||||
int exitCode = commandLine.execute("kill");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Kill command not yet implemented");
|
||||
// Assert - kill without job ID shows usage help (required parameter missing)
|
||||
assertThat(exitCode).isNotZero();
|
||||
String output = errWriter.toString();
|
||||
assertThat(output).contains("kill");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanSubcommand_shouldShowNotImplementedMessage() {
|
||||
// Arrange & Act
|
||||
int exitCode = commandLine.execute("clean");
|
||||
void cleanSubcommand_withoutOptions_shouldIndicateServiceNeeded() {
|
||||
// Arrange & Act - use temp dir to ensure no service is running there
|
||||
int exitCode = commandLine.execute("clean", "--barn-dir", tempDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Clean command not yet implemented");
|
||||
// Assert - clean without --offline fails with service not running
|
||||
assertThat(exitCode).isNotZero();
|
||||
String output = errWriter.toString();
|
||||
assertThat(output).containsIgnoringCase("service");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for CleanCommand.
|
||||
*/
|
||||
class CleanCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter stdout;
|
||||
private StringWriter stderr;
|
||||
private CommandLine cmd;
|
||||
private BarnDirectories dirs;
|
||||
private JobRepository repository;
|
||||
private JobsConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
repository = new JobRepository(dirs);
|
||||
config = JobsConfig.withDefaults();
|
||||
|
||||
stdout = new StringWriter();
|
||||
stderr = new StringWriter();
|
||||
|
||||
CleanCommand cleanCommand = new CleanCommand();
|
||||
cleanCommand.setBarnDir(tempDir);
|
||||
|
||||
cmd = new CommandLine(cleanCommand);
|
||||
cmd.setOut(new PrintWriter(stdout));
|
||||
cmd.setErr(new PrintWriter(stderr));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class NoJobs {
|
||||
|
||||
@Test
|
||||
void clean_withNoJobs_shouldSucceed() {
|
||||
int exitCode = cmd.execute("--offline", "--all");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).containsIgnoringCase("0");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CleanCompleted {
|
||||
|
||||
@Test
|
||||
void clean_succeededJob_shouldRemove() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(repository.findById(job.id())).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clean_canceledJob_shouldRemove() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCanceled(job.id());
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(repository.findById(job.id())).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clean_failedJob_withoutIncludeFailed_shouldNotRemove() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 1, "Error");
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Failed jobs are NOT removed without --include-failed
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clean_failedJob_withIncludeFailed_shouldRemove() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 1, "Error");
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all", "--include-failed");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(repository.findById(job.id())).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ProtectActiveJobs {
|
||||
|
||||
@Test
|
||||
void clean_runningJob_shouldNotRemove() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Running jobs should NEVER be removed
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clean_queuedJob_shouldNotRemove() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Queued jobs should NEVER be removed
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class SpecificJob {
|
||||
|
||||
@Test
|
||||
void clean_specificJob_shouldRemoveOnlyThatJob() throws IOException {
|
||||
Job job1 = repository.create(List.of("echo", "one"), "test", config);
|
||||
repository.markStarted(job1.id(), 12345L);
|
||||
repository.markCompleted(job1.id(), 0, null);
|
||||
|
||||
Job job2 = repository.create(List.of("echo", "two"), "test", config);
|
||||
repository.markStarted(job2.id(), 12346L);
|
||||
repository.markCompleted(job2.id(), 0, null);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--job-id", job1.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(repository.findById(job1.id())).isEmpty();
|
||||
assertThat(repository.findById(job2.id())).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clean_nonExistentJob_shouldFail() {
|
||||
int exitCode = cmd.execute("--offline", "--job-id", "job-nonexistent");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("not found");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clean_runningSpecificJob_shouldFail() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--job-id", job.id());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("cannot");
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class DryRun {
|
||||
|
||||
@Test
|
||||
void clean_dryRun_shouldNotRemove() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all", "--dry-run");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Job should still exist
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
assertThat(stdout.toString()).containsIgnoringCase("would");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OlderThan {
|
||||
|
||||
@Test
|
||||
void clean_olderThan_shouldFilterByAge() throws IOException {
|
||||
// Create a succeeded job
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
// Use a very long duration so job is NOT older than that
|
||||
int exitCode = cmd.execute("--offline", "--older-than", "9999d");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Job is not old enough, should still exist
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void clean_olderThan_veryShort_shouldRemove() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
// Sleep briefly so job is older than 1 minute... but instead we'll use 0 logic
|
||||
// Actually for testing, use a very short duration that any job will be older than
|
||||
// ... but that requires mocking. For now, just test the command runs.
|
||||
int exitCode = cmd.execute("--offline", "--older-than", "1m");
|
||||
|
||||
// Depending on timing, job might or might not be removed
|
||||
assertThat(exitCode).isZero();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OutputFormats {
|
||||
|
||||
@Test
|
||||
void clean_withJsonOutput_shouldProduceJson() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all", "--output", "JSON");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("{");
|
||||
assertThat(output).contains("\"cleaned\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clean_withXmlOutput_shouldProduceXml() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--all", "--output", "XML");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("<?xml");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceMode {
|
||||
|
||||
@Test
|
||||
void clean_withoutOffline_shouldIndicateServiceNeeded() {
|
||||
int exitCode = cmd.execute("--all");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("service");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for ConfigCommand and its subcommands.
|
||||
*/
|
||||
class ConfigCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter outWriter;
|
||||
private StringWriter errWriter;
|
||||
private CommandLine cmd;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
outWriter = new StringWriter();
|
||||
errWriter = new StringWriter();
|
||||
cmd = new CommandLine(new BarnCommand());
|
||||
cmd.setOut(new PrintWriter(outWriter));
|
||||
cmd.setErr(new PrintWriter(errWriter));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConfigParentCommand {
|
||||
|
||||
@Test
|
||||
void config_withoutSubcommand_shouldShowUsage() {
|
||||
int exitCode = cmd.execute("config");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("show");
|
||||
assertThat(outWriter.toString()).contains("validate");
|
||||
assertThat(outWriter.toString()).contains("init");
|
||||
}
|
||||
|
||||
@Test
|
||||
void config_withHelp_shouldShowUsage() {
|
||||
int exitCode = cmd.execute("config", "--help");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("Configuration management");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConfigShowCommandTests {
|
||||
|
||||
@Test
|
||||
void show_withDefaults_shouldShowDefaultConfiguration() {
|
||||
int exitCode = cmd.execute("config", "show", "--defaults");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Barn Configuration");
|
||||
assertThat(output).contains("[service]");
|
||||
assertThat(output).contains("[jobs]");
|
||||
assertThat(output).contains("[cleanup]");
|
||||
assertThat(output).contains("[storage]");
|
||||
assertThat(output).contains("Showing default values");
|
||||
}
|
||||
|
||||
@Test
|
||||
void show_withDefaults_shouldShowLogLevel() {
|
||||
int exitCode = cmd.execute("config", "show", "--defaults");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("log_level = info");
|
||||
}
|
||||
|
||||
@Test
|
||||
void show_withDefaults_shouldShowMaxConcurrentJobs() {
|
||||
int exitCode = cmd.execute("config", "show", "--defaults");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("max_concurrent_jobs = 4");
|
||||
}
|
||||
|
||||
@Test
|
||||
void show_withJsonFormat_shouldOutputJson() {
|
||||
int exitCode = cmd.execute("config", "show", "--defaults", "--output", "JSON");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("\"service\"");
|
||||
assertThat(output).contains("\"log_level\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void show_withXmlFormat_shouldOutputXml() {
|
||||
int exitCode = cmd.execute("config", "show", "--defaults", "--output", "XML");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("<service>");
|
||||
assertThat(output).contains("</service>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void show_withNonExistentConfig_shouldShowDefaultsMessage() {
|
||||
int exitCode = cmd.execute("config", "show");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("(none found, using defaults)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void show_withConfigFile_shouldShowConfigPath() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, "[service]\nlog_level = \"debug\"\n");
|
||||
|
||||
int exitCode = cmd.execute("config", "show", "--config", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("Config file:");
|
||||
assertThat(outWriter.toString()).contains(configFile.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void show_withHelp_shouldShowUsage() {
|
||||
int exitCode = cmd.execute("config", "show", "--help");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("Show effective configuration");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConfigValidateCommandTests {
|
||||
|
||||
@Test
|
||||
void validate_withValidConfig_shouldSucceed() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[service]
|
||||
log_level = "info"
|
||||
max_concurrent_jobs = 4
|
||||
|
||||
[jobs]
|
||||
default_timeout_seconds = 3600
|
||||
max_retries = 3
|
||||
|
||||
[cleanup]
|
||||
enabled = true
|
||||
max_age_hours = 168
|
||||
|
||||
[storage]
|
||||
base_dir = "/tmp/barn"
|
||||
max_disk_usage_gb = 100
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("Configuration is valid");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withNonExistentFile_shouldFail() {
|
||||
Path nonExistent = tempDir.resolve("nonexistent.toml");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", nonExistent.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(errWriter.toString()).contains("Configuration file not found");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withInvalidSection_shouldReportError() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[unknown_section]
|
||||
foo = "bar"
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(outWriter.toString()).contains("Unknown section");
|
||||
assertThat(outWriter.toString()).contains("unknown_section");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withInvalidKey_shouldReportError() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[service]
|
||||
invalid_key = "value"
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(outWriter.toString()).contains("Unknown key");
|
||||
assertThat(outWriter.toString()).contains("invalid_key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withInvalidLogLevel_shouldReportError() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[service]
|
||||
log_level = "invalid"
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(outWriter.toString()).contains("Invalid value for 'log_level'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withNegativeInteger_shouldReportError() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[service]
|
||||
max_concurrent_jobs = -1
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(outWriter.toString()).contains("max_concurrent_jobs");
|
||||
assertThat(outWriter.toString()).contains("must be positive");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withInvalidBackoffMultiplier_shouldReportError() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[jobs]
|
||||
retry_backoff_multiplier = 0.5
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(outWriter.toString()).contains("retry_backoff_multiplier");
|
||||
assertThat(outWriter.toString()).contains("at least 1.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withInvalidRetryOnExitCodes_shouldReportError() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[jobs]
|
||||
retry_on_exit_codes = "not a list"
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(outWriter.toString()).contains("retry_on_exit_codes");
|
||||
assertThat(outWriter.toString()).contains("must be a list");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withInvalidBoolean_shouldReportError() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[cleanup]
|
||||
enabled = "yes"
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate", "--file", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(outWriter.toString()).contains("enabled");
|
||||
assertThat(outWriter.toString()).contains("must be true or false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withJsonFormat_shouldOutputJson() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, """
|
||||
[unknown]
|
||||
foo = "bar"
|
||||
""");
|
||||
|
||||
int exitCode = cmd.execute("config", "validate",
|
||||
"--file", configFile.toString(), "--output", "JSON");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("\"valid\"");
|
||||
assertThat(output).contains("\"errors\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validate_withHelp_shouldShowUsage() {
|
||||
int exitCode = cmd.execute("config", "validate", "--help");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("Validate configuration file");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConfigInitCommandTests {
|
||||
|
||||
@Test
|
||||
void init_shouldCreateConfigFile() {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
|
||||
int exitCode = cmd.execute("config", "init", "--path", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(Files.exists(configFile)).isTrue();
|
||||
assertThat(outWriter.toString()).contains("Configuration file created");
|
||||
}
|
||||
|
||||
@Test
|
||||
void init_shouldCreateValidToml() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
|
||||
cmd.execute("config", "init", "--path", configFile.toString());
|
||||
|
||||
String content = Files.readString(configFile);
|
||||
assertThat(content).contains("[service]");
|
||||
assertThat(content).contains("[jobs]");
|
||||
assertThat(content).contains("[cleanup]");
|
||||
assertThat(content).contains("[storage]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void init_shouldIncludeComments() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
|
||||
cmd.execute("config", "init", "--path", configFile.toString());
|
||||
|
||||
String content = Files.readString(configFile);
|
||||
assertThat(content).contains("# Barn Configuration");
|
||||
assertThat(content).contains("# Logging verbosity");
|
||||
}
|
||||
|
||||
@Test
|
||||
void init_existingFile_withoutForce_shouldFail() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, "existing content");
|
||||
|
||||
int exitCode = cmd.execute("config", "init", "--path", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(errWriter.toString()).contains("already exists");
|
||||
assertThat(errWriter.toString()).contains("--force");
|
||||
}
|
||||
|
||||
@Test
|
||||
void init_existingFile_withForce_shouldOverwrite() throws IOException {
|
||||
Path configFile = tempDir.resolve("barn.toml");
|
||||
Files.writeString(configFile, "old content");
|
||||
|
||||
int exitCode = cmd.execute("config", "init", "--path", configFile.toString(), "--force");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String content = Files.readString(configFile);
|
||||
assertThat(content).contains("[service]");
|
||||
assertThat(content).doesNotContain("old content");
|
||||
}
|
||||
|
||||
@Test
|
||||
void init_shouldCreateParentDirectories() {
|
||||
Path configFile = tempDir.resolve("subdir/nested/barn.toml");
|
||||
|
||||
int exitCode = cmd.execute("config", "init", "--path", configFile.toString());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(Files.exists(configFile)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void init_withHelp_shouldShowUsage() {
|
||||
int exitCode = cmd.execute("config", "init", "--help");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("Create default configuration file");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for DescribeCommand.
|
||||
*/
|
||||
class DescribeCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter stdout;
|
||||
private StringWriter stderr;
|
||||
private CommandLine cmd;
|
||||
private BarnDirectories dirs;
|
||||
private JobRepository repository;
|
||||
private JobsConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
repository = new JobRepository(dirs);
|
||||
config = JobsConfig.withDefaults();
|
||||
|
||||
stdout = new StringWriter();
|
||||
stderr = new StringWriter();
|
||||
|
||||
DescribeCommand describeCommand = new DescribeCommand();
|
||||
describeCommand.setBarnDir(tempDir);
|
||||
|
||||
cmd = new CommandLine(describeCommand);
|
||||
cmd.setOut(new PrintWriter(stdout));
|
||||
cmd.setErr(new PrintWriter(stderr));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class BasicDescribe {
|
||||
|
||||
@Test
|
||||
void describe_existingJob_shouldShowDetails() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test-tag", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains(job.id());
|
||||
assertThat(output).contains("test-tag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describe_shouldShowState() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString().toLowerCase()).contains("queued");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describe_shouldShowCommand() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello", "world"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("echo");
|
||||
assertThat(output).contains("hello");
|
||||
assertThat(output).contains("world");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describe_shouldShowTimestamps() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).containsIgnoringCase("created");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class NotFound {
|
||||
|
||||
@Test
|
||||
void describe_nonExistentJob_shouldFail() {
|
||||
int exitCode = cmd.execute("--offline", "job-nonexistent");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("not found");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describe_withNoJobId_shouldFail() {
|
||||
int exitCode = cmd.execute("--offline");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class LogsOption {
|
||||
|
||||
@Test
|
||||
void describe_withLogs_shouldIncludeLogContent() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
// Create a log file with content
|
||||
Path logsDir = dirs.getJobLogsDir(job.id());
|
||||
Files.writeString(logsDir.resolve("stdout.log"), "Log line 1\nLog line 2\n");
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--logs", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("Log line");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describe_withLogsNoContent_shouldHandleGracefully() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--logs", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Should not error even if no logs
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ManifestOption {
|
||||
|
||||
@Test
|
||||
void describe_withManifest_shouldShowFullManifest() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--manifest", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).containsIgnoringCase("manifest");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OutputFormats {
|
||||
|
||||
@Test
|
||||
void describe_withJsonOutput_shouldProduceJson() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--output", "JSON", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("{");
|
||||
assertThat(output).contains("\"id\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describe_withXmlOutput_shouldProduceXml() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--output", "XML", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("<?xml");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceMode {
|
||||
|
||||
@Test
|
||||
void describe_withoutOffline_shouldIndicateServiceNeeded() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute(job.id());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("service");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for GlobalOptions.
|
||||
*/
|
||||
class GlobalOptionsTest {
|
||||
|
||||
@Nested
|
||||
class Defaults {
|
||||
|
||||
@Test
|
||||
void globalOptions_shouldHaveHumanFormatByDefault() {
|
||||
GlobalOptions options = new GlobalOptions();
|
||||
|
||||
assertThat(options.getOutputFormat()).isEqualTo(OutputFormat.HUMAN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void globalOptions_shouldHaveNoConfigPathByDefault() {
|
||||
GlobalOptions options = new GlobalOptions();
|
||||
|
||||
assertThat(options.getConfigPath()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void globalOptions_shouldNotBeOfflineByDefault() {
|
||||
GlobalOptions options = new GlobalOptions();
|
||||
|
||||
assertThat(options.isOffline()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OutputFormatOption {
|
||||
|
||||
@Test
|
||||
void outputFormat_withHuman_shouldSetHuman() {
|
||||
GlobalOptions options = parseOptions("-o", "HUMAN");
|
||||
|
||||
assertThat(options.getOutputFormat()).isEqualTo(OutputFormat.HUMAN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputFormat_withJson_shouldSetJson() {
|
||||
GlobalOptions options = parseOptions("-o", "JSON");
|
||||
|
||||
assertThat(options.getOutputFormat()).isEqualTo(OutputFormat.JSON);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputFormat_withXml_shouldSetXml() {
|
||||
GlobalOptions options = parseOptions("-o", "XML");
|
||||
|
||||
assertThat(options.getOutputFormat()).isEqualTo(OutputFormat.XML);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputFormat_withLongOption_shouldWork() {
|
||||
GlobalOptions options = parseOptions("--output", "JSON");
|
||||
|
||||
assertThat(options.getOutputFormat()).isEqualTo(OutputFormat.JSON);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConfigOption {
|
||||
|
||||
@Test
|
||||
void config_withPath_shouldSetConfigPath() {
|
||||
GlobalOptions options = parseOptions("--config", "/etc/barn/barn.conf");
|
||||
|
||||
assertThat(options.getConfigPath()).isPresent();
|
||||
assertThat(options.getConfigPath().get()).isEqualTo(Path.of("/etc/barn/barn.conf"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void config_withoutPath_shouldReturnEmpty() {
|
||||
GlobalOptions options = parseOptions();
|
||||
|
||||
assertThat(options.getConfigPath()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OfflineOption {
|
||||
|
||||
@Test
|
||||
void offline_withFlag_shouldBeTrue() {
|
||||
GlobalOptions options = parseOptions("--offline");
|
||||
|
||||
assertThat(options.isOffline()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void offline_withoutFlag_shouldBeFalse() {
|
||||
GlobalOptions options = parseOptions();
|
||||
|
||||
assertThat(options.isOffline()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CombinedOptions {
|
||||
|
||||
@Test
|
||||
void allOptions_shouldWorkTogether() {
|
||||
GlobalOptions options = parseOptions(
|
||||
"-o", "JSON",
|
||||
"--config", "/path/to/config",
|
||||
"--offline"
|
||||
);
|
||||
|
||||
assertThat(options.getOutputFormat()).isEqualTo(OutputFormat.JSON);
|
||||
assertThat(options.getConfigPath()).contains(Path.of("/path/to/config"));
|
||||
assertThat(options.isOffline()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to parse options using picocli
|
||||
private GlobalOptions parseOptions(String... args) {
|
||||
TestCommand cmd = new TestCommand();
|
||||
new CommandLine(cmd).parseArgs(args);
|
||||
return cmd.getGlobalOptions();
|
||||
}
|
||||
|
||||
@CommandLine.Command(name = "test")
|
||||
static class TestCommand implements Runnable {
|
||||
@CommandLine.Mixin
|
||||
private GlobalOptions globalOptions;
|
||||
|
||||
GlobalOptions getGlobalOptions() {
|
||||
return globalOptions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// No-op
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Tests for HumanFormatter.
|
||||
*/
|
||||
class HumanFormatterTest {
|
||||
|
||||
private HumanFormatter formatter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Disable colors for testing
|
||||
formatter = new HumanFormatter(false);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Format {
|
||||
|
||||
@Test
|
||||
void format_withNull_shouldReturnEmpty() {
|
||||
assertThat(formatter.format(null)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withString_shouldReturnString() {
|
||||
assertThat(formatter.format("hello")).isEqualTo("hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withJob_shouldFormatJobDetails() {
|
||||
Job job = createJob("job-12345678", JobState.RUNNING, "test-tag");
|
||||
|
||||
String result = formatter.format(job);
|
||||
|
||||
assertThat(result).contains("Job: job-12345678");
|
||||
assertThat(result).contains("State:");
|
||||
assertThat(result).contains("running");
|
||||
assertThat(result).contains("Tag:");
|
||||
assertThat(result).contains("test-tag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withCompletedJob_shouldShowExitCode() {
|
||||
Job job = createCompletedJob("job-12345678", 0);
|
||||
|
||||
String result = formatter.format(job);
|
||||
|
||||
assertThat(result).contains("Exit:");
|
||||
assertThat(result).contains("0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withFailedJob_shouldShowError() {
|
||||
Job job = createFailedJob("job-12345678", 1, "Process failed");
|
||||
|
||||
String result = formatter.format(job);
|
||||
|
||||
assertThat(result).contains("Exit:");
|
||||
assertThat(result).contains("1");
|
||||
assertThat(result).contains("Error:");
|
||||
assertThat(result).contains("Process failed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withMap_shouldFormatKeyValues() {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
|
||||
String result = formatter.format(map);
|
||||
|
||||
assertThat(result).contains("key1:");
|
||||
assertThat(result).contains("value1");
|
||||
assertThat(result).contains("key2:");
|
||||
assertThat(result).contains("value2");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FormatList {
|
||||
|
||||
@Test
|
||||
void formatList_withNull_shouldReturnNoResults() {
|
||||
assertThat(formatter.formatList(null)).isEqualTo("No results found.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withEmpty_shouldReturnNoResults() {
|
||||
assertThat(formatter.formatList(List.of())).isEqualTo("No results found.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withJobs_shouldFormatTable() {
|
||||
List<Job> jobs = List.of(
|
||||
createJob("job-11111111", JobState.RUNNING, "tag1"),
|
||||
createJob("job-22222222", JobState.QUEUED, "tag2")
|
||||
);
|
||||
|
||||
String result = formatter.formatList(jobs);
|
||||
|
||||
assertThat(result).contains("ID");
|
||||
assertThat(result).contains("STATE");
|
||||
assertThat(result).contains("TAG");
|
||||
assertThat(result).contains("job-11111111");
|
||||
assertThat(result).contains("job-22222222");
|
||||
assertThat(result).contains("running");
|
||||
assertThat(result).contains("queued");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withStrings_shouldFormatEach() {
|
||||
List<String> strings = List.of("item1", "item2", "item3");
|
||||
|
||||
String result = formatter.formatList(strings);
|
||||
|
||||
assertThat(result).contains("item1");
|
||||
assertThat(result).contains("item2");
|
||||
assertThat(result).contains("item3");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FormatError {
|
||||
|
||||
@Test
|
||||
void formatError_withMessageOnly_shouldFormatError() {
|
||||
String result = formatter.formatError("Something went wrong", null);
|
||||
|
||||
assertThat(result).contains("Error:");
|
||||
assertThat(result).contains("Something went wrong");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatError_withCause_shouldIncludeCause() {
|
||||
Exception cause = new RuntimeException("Root cause");
|
||||
String result = formatter.formatError("Something went wrong", cause);
|
||||
|
||||
assertThat(result).contains("Error:");
|
||||
assertThat(result).contains("Something went wrong");
|
||||
assertThat(result).contains("Cause:");
|
||||
assertThat(result).contains("Root cause");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Colors {
|
||||
|
||||
@Test
|
||||
void constructor_withColors_shouldUseAnsiCodes() {
|
||||
HumanFormatter colorFormatter = new HumanFormatter(true);
|
||||
|
||||
String result = colorFormatter.formatError("Error message", null);
|
||||
|
||||
// Should contain ANSI escape codes
|
||||
assertThat(result).contains("\u001B[");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withoutColors_shouldNotUseAnsiCodes() {
|
||||
String result = formatter.formatError("Error message", null);
|
||||
|
||||
// Should not contain ANSI escape codes
|
||||
assertThat(result).doesNotContain("\u001B[");
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private Job createJob(String id, JobState state, String tag) {
|
||||
return new Job(
|
||||
id,
|
||||
state,
|
||||
List.of("echo", "test"),
|
||||
tag,
|
||||
Instant.now(),
|
||||
state == JobState.RUNNING ? Instant.now().minus(Duration.ofMinutes(1)) : null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
state == JobState.RUNNING ? 12345L : null,
|
||||
null,
|
||||
0,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
private Job createCompletedJob(String id, int exitCode) {
|
||||
return new Job(
|
||||
id,
|
||||
JobState.SUCCEEDED,
|
||||
List.of("echo", "test"),
|
||||
"tag",
|
||||
Instant.now().minus(Duration.ofMinutes(5)),
|
||||
Instant.now().minus(Duration.ofMinutes(4)),
|
||||
Instant.now(),
|
||||
exitCode,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
private Job createFailedJob(String id, int exitCode, String error) {
|
||||
return new Job(
|
||||
id,
|
||||
JobState.FAILED,
|
||||
List.of("echo", "test"),
|
||||
"tag",
|
||||
Instant.now().minus(Duration.ofMinutes(5)),
|
||||
Instant.now().minus(Duration.ofMinutes(4)),
|
||||
Instant.now(),
|
||||
exitCode,
|
||||
error,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
null
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Tests for JsonFormatter.
|
||||
*/
|
||||
class JsonFormatterTest {
|
||||
|
||||
private JsonFormatter formatter;
|
||||
private ObjectMapper mapper;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
formatter = new JsonFormatter();
|
||||
mapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Format {
|
||||
|
||||
@Test
|
||||
void format_withNull_shouldReturnNull() {
|
||||
assertThat(formatter.format(null)).isEqualTo("null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withString_shouldReturnQuotedString() throws JsonProcessingException {
|
||||
String result = formatter.format("hello");
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.asText()).isEqualTo("hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withNumber_shouldReturnNumber() throws JsonProcessingException {
|
||||
String result = formatter.format(42);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.asInt()).isEqualTo(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withJob_shouldProduceValidJson() throws JsonProcessingException {
|
||||
Job job = createJob("job-12345678", JobState.RUNNING, "test-tag");
|
||||
|
||||
String result = formatter.format(job);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.get("id").asText()).isEqualTo("job-12345678");
|
||||
assertThat(node.get("state").asText()).isEqualTo("RUNNING");
|
||||
assertThat(node.get("tag").asText()).isEqualTo("test-tag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withJob_shouldFormatDatesAsIso8601() throws JsonProcessingException {
|
||||
Job job = createJob("job-12345678", JobState.RUNNING, "test-tag");
|
||||
|
||||
String result = formatter.format(job);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
// ISO-8601 format ends with Z for UTC
|
||||
String createdAt = node.get("createdAt").asText();
|
||||
assertThat(createdAt).matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withMap_shouldProduceValidJson() throws JsonProcessingException {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", 42);
|
||||
|
||||
String result = formatter.format(map);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.get("key1").asText()).isEqualTo("value1");
|
||||
assertThat(node.get("key2").asInt()).isEqualTo(42);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FormatList {
|
||||
|
||||
@Test
|
||||
void formatList_withNull_shouldReturnEmptyArray() throws JsonProcessingException {
|
||||
String result = formatter.formatList(null);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.isArray()).isTrue();
|
||||
assertThat(node.size()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withEmpty_shouldReturnEmptyArray() throws JsonProcessingException {
|
||||
String result = formatter.formatList(List.of());
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.isArray()).isTrue();
|
||||
assertThat(node.size()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withJobs_shouldProduceValidJsonArray() throws JsonProcessingException {
|
||||
List<Job> jobs = List.of(
|
||||
createJob("job-11111111", JobState.RUNNING, "tag1"),
|
||||
createJob("job-22222222", JobState.QUEUED, "tag2")
|
||||
);
|
||||
|
||||
String result = formatter.formatList(jobs);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.isArray()).isTrue();
|
||||
assertThat(node.size()).isEqualTo(2);
|
||||
assertThat(node.get(0).get("id").asText()).isEqualTo("job-11111111");
|
||||
assertThat(node.get(1).get("id").asText()).isEqualTo("job-22222222");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withStrings_shouldProduceValidJsonArray() throws JsonProcessingException {
|
||||
List<String> strings = List.of("one", "two", "three");
|
||||
|
||||
String result = formatter.formatList(strings);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.isArray()).isTrue();
|
||||
assertThat(node.size()).isEqualTo(3);
|
||||
assertThat(node.get(0).asText()).isEqualTo("one");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FormatError {
|
||||
|
||||
@Test
|
||||
void formatError_withMessageOnly_shouldProduceValidJson() throws JsonProcessingException {
|
||||
String result = formatter.formatError("Something went wrong", null);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.get("error").asBoolean()).isTrue();
|
||||
assertThat(node.get("message").asText()).isEqualTo("Something went wrong");
|
||||
assertThat(node.has("cause")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatError_withCause_shouldIncludeCauseInJson() throws JsonProcessingException {
|
||||
Exception cause = new RuntimeException("Root cause");
|
||||
String result = formatter.formatError("Something went wrong", cause);
|
||||
JsonNode node = mapper.readTree(result);
|
||||
|
||||
assertThat(node.get("error").asBoolean()).isTrue();
|
||||
assertThat(node.get("message").asText()).isEqualTo("Something went wrong");
|
||||
assertThat(node.get("cause").asText()).isEqualTo("Root cause");
|
||||
assertThat(node.get("type").asText()).isEqualTo("RuntimeException");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatError_shouldAlwaysBeValidJson() throws JsonProcessingException {
|
||||
String result = formatter.formatError("Error with \"quotes\"", null);
|
||||
|
||||
// Should not throw when parsing
|
||||
JsonNode node = mapper.readTree(result);
|
||||
assertThat(node.get("message").asText()).isEqualTo("Error with \"quotes\"");
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private Job createJob(String id, JobState state, String tag) {
|
||||
return new Job(
|
||||
id,
|
||||
state,
|
||||
List.of("echo", "test"),
|
||||
tag,
|
||||
Instant.now(),
|
||||
state == JobState.RUNNING ? Instant.now().minus(Duration.ofMinutes(1)) : null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
state == JobState.RUNNING ? 12345L : null,
|
||||
null,
|
||||
0,
|
||||
null
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for KillCommand.
|
||||
*/
|
||||
class KillCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter stdout;
|
||||
private StringWriter stderr;
|
||||
private CommandLine cmd;
|
||||
private BarnDirectories dirs;
|
||||
private JobRepository repository;
|
||||
private JobsConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
repository = new JobRepository(dirs);
|
||||
config = JobsConfig.withDefaults();
|
||||
|
||||
stdout = new StringWriter();
|
||||
stderr = new StringWriter();
|
||||
|
||||
KillCommand killCommand = new KillCommand();
|
||||
killCommand.setBarnDir(tempDir);
|
||||
|
||||
cmd = new CommandLine(killCommand);
|
||||
cmd.setOut(new PrintWriter(stdout));
|
||||
cmd.setErr(new PrintWriter(stderr));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class NotFound {
|
||||
|
||||
@Test
|
||||
void kill_nonExistentJob_shouldFail() {
|
||||
int exitCode = cmd.execute("--offline", "job-nonexistent");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("not found");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kill_withNoJobId_shouldFail() {
|
||||
int exitCode = cmd.execute("--offline");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class NotRunning {
|
||||
|
||||
@Test
|
||||
void kill_queuedJob_shouldFail() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("not running");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kill_succeededJob_shouldFail() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("not running");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kill_failedJob_shouldFail() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 1, "Error");
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("not running");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kill_canceledJob_shouldFail() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCanceled(job.id());
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("not running");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class KillRunningJob {
|
||||
|
||||
@Test
|
||||
void kill_runningJobWithNoPid_shouldUpdateState() throws IOException {
|
||||
// A running job might have no PID recorded yet (edge case)
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.updateState(job.id(), JobState.RUNNING);
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Verify state changed to CANCELED
|
||||
Job updated = repository.findById(job.id()).orElseThrow();
|
||||
assertThat(updated.state()).isEqualTo(JobState.CANCELED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void kill_runningJobWithDeadPid_shouldUpdateState() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
// Use a PID that doesn't exist (high value unlikely to be real)
|
||||
repository.markStarted(job.id(), 999999999L);
|
||||
|
||||
int exitCode = cmd.execute("--offline", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Verify state changed to CANCELED even if process not found
|
||||
Job updated = repository.findById(job.id()).orElseThrow();
|
||||
assertThat(updated.state()).isEqualTo(JobState.CANCELED);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class QuietMode {
|
||||
|
||||
@Test
|
||||
void kill_withQuiet_shouldProduceNoOutput() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.updateState(job.id(), JobState.RUNNING);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--quiet", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void kill_withQuietError_shouldStillShowError() throws IOException {
|
||||
int exitCode = cmd.execute("--offline", "--quiet", "job-nonexistent");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
// Errors still shown even in quiet mode
|
||||
assertThat(stderr.toString()).containsIgnoringCase("not found");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OutputFormats {
|
||||
|
||||
@Test
|
||||
void kill_withJsonOutput_shouldProduceJson() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.updateState(job.id(), JobState.RUNNING);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--output", "JSON", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("{");
|
||||
assertThat(output).contains("\"id\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kill_withXmlOutput_shouldProduceXml() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.updateState(job.id(), JobState.RUNNING);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--output", "XML", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("<?xml");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kill_withHumanOutput_shouldShowMessage() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.updateState(job.id(), JobState.RUNNING);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--output", "HUMAN", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).containsIgnoringCase("killed");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ForceOption {
|
||||
|
||||
@Test
|
||||
void kill_withForce_shouldUpdateState() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.updateState(job.id(), JobState.RUNNING);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--force", job.id());
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
Job updated = repository.findById(job.id()).orElseThrow();
|
||||
assertThat(updated.state()).isEqualTo(JobState.CANCELED);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceMode {
|
||||
|
||||
@Test
|
||||
void kill_withoutOffline_shouldIndicateServiceNeeded() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "hello"), "test", config);
|
||||
repository.updateState(job.id(), JobState.RUNNING);
|
||||
|
||||
int exitCode = cmd.execute(job.id());
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("service");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for OutputFormatter.
|
||||
*/
|
||||
class OutputFormatterTest {
|
||||
|
||||
@Nested
|
||||
class ForFormat {
|
||||
|
||||
@Test
|
||||
void forFormat_withHuman_shouldReturnHumanFormatter() {
|
||||
OutputFormatter formatter = OutputFormatter.forFormat(OutputFormat.HUMAN);
|
||||
|
||||
assertThat(formatter).isInstanceOf(HumanFormatter.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void forFormat_withJson_shouldReturnJsonFormatter() {
|
||||
OutputFormatter formatter = OutputFormatter.forFormat(OutputFormat.JSON);
|
||||
|
||||
assertThat(formatter).isInstanceOf(JsonFormatter.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void forFormat_withXml_shouldReturnXmlFormatter() {
|
||||
OutputFormatter formatter = OutputFormatter.forFormat(OutputFormat.XML);
|
||||
|
||||
assertThat(formatter).isInstanceOf(XmlFormatter.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for RunCommand.
|
||||
*/
|
||||
class RunCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter stdout;
|
||||
private StringWriter stderr;
|
||||
private CommandLine cmd;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
// Initialize barn directories for testing
|
||||
BarnDirectories dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
|
||||
stdout = new StringWriter();
|
||||
stderr = new StringWriter();
|
||||
|
||||
RunCommand runCommand = new RunCommand();
|
||||
runCommand.setBarnDir(tempDir);
|
||||
|
||||
cmd = new CommandLine(runCommand);
|
||||
cmd.setOut(new PrintWriter(stdout));
|
||||
cmd.setErr(new PrintWriter(stderr));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CommandParsing {
|
||||
|
||||
@Test
|
||||
void run_withSimpleCommand_shouldSucceed() {
|
||||
int exitCode = cmd.execute("--offline", "echo", "hello");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_withTag_shouldSetTag() {
|
||||
int exitCode = cmd.execute("--offline", "--tag", "test-tag", "echo", "hello");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).contains("test-tag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_withShortTag_shouldSetTag() {
|
||||
int exitCode = cmd.execute("--offline", "-t", "my-tag", "echo", "hello");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).contains("my-tag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_withNoCommand_shouldFail() {
|
||||
int exitCode = cmd.execute("--offline");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OfflineMode {
|
||||
|
||||
@Test
|
||||
void run_inOfflineMode_shouldRunJob() {
|
||||
int exitCode = cmd.execute("--offline", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).contains("Job created:");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_inOfflineMode_shouldShowJobId() {
|
||||
int exitCode = cmd.execute("--offline", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).matches("(?s).*job-[a-f0-9]+.*");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_inOfflineMode_shouldShowState() {
|
||||
int exitCode = cmd.execute("--offline", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString().toLowerCase()).contains("queued");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OutputFormats {
|
||||
|
||||
@Test
|
||||
void run_withJsonOutput_shouldProduceJson() {
|
||||
int exitCode = cmd.execute("--offline", "--output", "JSON", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("{");
|
||||
assertThat(output).contains("\"id\"");
|
||||
assertThat(output).contains("\"state\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_withXmlOutput_shouldProduceXml() {
|
||||
int exitCode = cmd.execute("--offline", "--output", "XML", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("<?xml");
|
||||
assertThat(output).contains("<job>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_withHumanOutput_shouldProduceReadableOutput() {
|
||||
int exitCode = cmd.execute("--offline", "--output", "HUMAN", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).contains("Job created:");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class RetryOptions {
|
||||
|
||||
@Test
|
||||
void run_withMaxRetries_shouldAcceptOption() {
|
||||
int exitCode = cmd.execute("--offline", "--max-retries", "5", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_withRetryDelay_shouldAcceptOption() {
|
||||
int exitCode = cmd.execute("--offline", "--retry-delay", "60", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_withTimeout_shouldAcceptOption() {
|
||||
int exitCode = cmd.execute("--offline", "--timeout", "3600", "echo", "test");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceMode {
|
||||
|
||||
@Test
|
||||
void run_withoutOffline_shouldIndicateServiceNeeded() {
|
||||
int exitCode = cmd.execute("echo", "test");
|
||||
|
||||
// Without --offline and without service, should fail gracefully
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("service");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for service commands.
|
||||
*/
|
||||
class ServiceCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter stdout;
|
||||
private StringWriter stderr;
|
||||
private CommandLine cmd;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
stdout = new StringWriter();
|
||||
stderr = new StringWriter();
|
||||
cmd = new CommandLine(new BarnCommand());
|
||||
cmd.setCaseInsensitiveEnumValuesAllowed(true);
|
||||
cmd.setOut(new PrintWriter(stdout));
|
||||
cmd.setErr(new PrintWriter(stderr));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceParentCommand {
|
||||
|
||||
@Test
|
||||
void service_withoutSubcommand_shouldShowUsage() {
|
||||
// Act
|
||||
int exitCode = cmd.execute("service");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("Manage the Barn service");
|
||||
}
|
||||
|
||||
@Test
|
||||
void service_withHelp_shouldShowUsage() {
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "--help");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString())
|
||||
.contains("service")
|
||||
.contains("start")
|
||||
.contains("stop")
|
||||
.contains("status");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceStartCommand {
|
||||
|
||||
@Test
|
||||
void start_shouldOutputStartMessage() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "start", "--barn-dir", barnDir.toString(), "--foreground-test");
|
||||
|
||||
// Assert
|
||||
assertThat(stdout.toString()).contains("started");
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_withForeground_shouldRunInForeground() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "start", "--barn-dir", barnDir.toString(), "--foreground", "--dry-run");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_whenAlreadyRunning_shouldShowError() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Create a fake PID file with current process PID
|
||||
Path pidFile = barnDir.resolve("barn.pid");
|
||||
Files.writeString(pidFile, String.valueOf(ProcessHandle.current().pid()));
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "start", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isNotEqualTo(0);
|
||||
assertThat(stderr.toString()).contains("already running");
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_withDryRun_shouldNotActuallyStart() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "start", "--barn-dir", barnDir.toString(), "--dry-run");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("dry run");
|
||||
// PID file should not exist after dry run
|
||||
assertThat(Files.exists(barnDir.resolve("barn.pid"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_withStalePidFile_shouldSucceed() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Create a PID file with non-existent PID
|
||||
Path pidFile = barnDir.resolve("barn.pid");
|
||||
Files.writeString(pidFile, "999999999");
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "start", "--barn-dir", barnDir.toString(), "--foreground-test");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("started");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceStopCommand {
|
||||
|
||||
@Test
|
||||
void stop_whenNotRunning_shouldShowError() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "stop", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isNotEqualTo(0);
|
||||
assertThat(stderr.toString()).contains("not running");
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_withForce_shouldForceStop() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act - force stop even when not running should not error
|
||||
int exitCode = cmd.execute("service", "stop", "--barn-dir", barnDir.toString(), "--force");
|
||||
|
||||
// Assert
|
||||
// Force stop without running service just succeeds silently
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("not running");
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_withStalePidFile_shouldCleanupAndShowError() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Create a PID file with a non-existent PID
|
||||
Path pidFile = barnDir.resolve("barn.pid");
|
||||
Files.writeString(pidFile, "999999999");
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "stop", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isNotEqualTo(0);
|
||||
assertThat(stderr.toString()).contains("not running");
|
||||
assertThat(Files.exists(pidFile)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_withForceAndStalePidFile_shouldSucceed() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Create a PID file with a non-existent PID
|
||||
Path pidFile = barnDir.resolve("barn.pid");
|
||||
Files.writeString(pidFile, "999999999");
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "stop", "--barn-dir", barnDir.toString(), "--force");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("not running");
|
||||
assertThat(Files.exists(pidFile)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_withInvalidPidFile_shouldShowError() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Create a PID file with invalid content
|
||||
Path pidFile = barnDir.resolve("barn.pid");
|
||||
Files.writeString(pidFile, "not-a-number");
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "stop", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isNotEqualTo(0);
|
||||
assertThat(stderr.toString()).contains("Failed");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceStatusCommand {
|
||||
|
||||
@Test
|
||||
void status_whenNotRunning_shouldShowStopped() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "status", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString().toLowerCase()).contains("stopped");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_withJsonFormat_shouldOutputJson() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "status", "--barn-dir", barnDir.toString(), "--output", "json");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("\"status\"");
|
||||
assertThat(stdout.toString()).contains("\"running\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_withXmlFormat_shouldOutputXml() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "status", "--barn-dir", barnDir.toString(), "--output", "xml");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("<status>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_withStalePidFile_shouldShowStopped() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
Path pidFile = barnDir.resolve("barn.pid");
|
||||
Files.writeString(pidFile, "999999999");
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "status", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert - also verifies data directory is shown
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString().toLowerCase()).contains("stopped");
|
||||
assertThat(stdout.toString()).contains(barnDir.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_whenRunning_shouldShowRunningStatus() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
// Use current process PID to simulate a running service
|
||||
Path pidFile = barnDir.resolve("barn.pid");
|
||||
Files.writeString(pidFile, String.valueOf(ProcessHandle.current().pid()));
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "status", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString().toLowerCase()).contains("running");
|
||||
assertThat(stdout.toString()).contains("PID");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceRestartCommand {
|
||||
|
||||
@Test
|
||||
void restart_whenNotRunning_shouldShowError() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "restart", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isNotEqualTo(0);
|
||||
assertThat(stderr.toString()).contains("not running");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceReloadCommand {
|
||||
|
||||
@Test
|
||||
void reload_whenNotRunning_shouldShowError() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "reload", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isNotEqualTo(0);
|
||||
assertThat(stderr.toString()).contains("not running");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceLogsCommand {
|
||||
|
||||
@Test
|
||||
void logs_whenNoLogFile_shouldShowMessage() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Files.createDirectories(barnDir);
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "logs", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
// Exit code 0 if no logs exist, with message
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("No log file found");
|
||||
}
|
||||
|
||||
@Test
|
||||
void logs_withLines_shouldLimitOutput() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Path logsDir = barnDir.resolve("logs");
|
||||
Files.createDirectories(logsDir);
|
||||
Path logFile = logsDir.resolve("barn.log");
|
||||
|
||||
// Create a log file with multiple lines
|
||||
StringBuilder logContent = new StringBuilder();
|
||||
for (int i = 1; i <= 100; i++) {
|
||||
logContent.append("Log line ").append(i).append("\n");
|
||||
}
|
||||
Files.writeString(logFile, logContent.toString());
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "logs", "--barn-dir", barnDir.toString(), "--lines", "10");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
String output = stdout.toString();
|
||||
// Should contain last 10 lines
|
||||
assertThat(output).contains("Log line 91");
|
||||
assertThat(output).contains("Log line 100");
|
||||
// Should not contain line 90 or earlier
|
||||
assertThat(output).doesNotContain("Log line 90");
|
||||
}
|
||||
|
||||
@Test
|
||||
void logs_withDefaultLines_shouldShowLast100() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Path logsDir = barnDir.resolve("logs");
|
||||
Files.createDirectories(logsDir);
|
||||
Path logFile = logsDir.resolve("barn.log");
|
||||
|
||||
// Create a log file with multiple lines
|
||||
StringBuilder logContent = new StringBuilder();
|
||||
for (int i = 1; i <= 200; i++) {
|
||||
logContent.append("Log line ").append(i).append("\n");
|
||||
}
|
||||
Files.writeString(logFile, logContent.toString());
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "logs", "--barn-dir", barnDir.toString());
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
String output = stdout.toString();
|
||||
// Should contain last 100 lines
|
||||
assertThat(output).contains("Log line 101");
|
||||
assertThat(output).contains("Log line 200");
|
||||
// Should not contain line 100 or earlier
|
||||
assertThat(output).doesNotContain("Log line 100\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void logs_withFewerLinesThanRequested_shouldShowAllLines() throws IOException {
|
||||
// Arrange
|
||||
Path barnDir = tempDir.resolve("barn");
|
||||
Path logsDir = barnDir.resolve("logs");
|
||||
Files.createDirectories(logsDir);
|
||||
Path logFile = logsDir.resolve("barn.log");
|
||||
|
||||
// Create a small log file
|
||||
Files.writeString(logFile, "Line 1\nLine 2\nLine 3\n");
|
||||
|
||||
// Act
|
||||
int exitCode = cmd.execute("service", "logs", "--barn-dir", barnDir.toString(), "--lines", "100");
|
||||
|
||||
// Assert
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("Line 1");
|
||||
assertThat(output).contains("Line 2");
|
||||
assertThat(output).contains("Line 3");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for ServiceInstallCommand.
|
||||
*/
|
||||
class ServiceInstallCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter stdout;
|
||||
private StringWriter stderr;
|
||||
private CommandLine cmd;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
stdout = new StringWriter();
|
||||
stderr = new StringWriter();
|
||||
cmd = new CommandLine(new BarnCommand());
|
||||
cmd.setCaseInsensitiveEnumValuesAllowed(true);
|
||||
cmd.setOut(new PrintWriter(stdout));
|
||||
cmd.setErr(new PrintWriter(stderr));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class InstallCommand {
|
||||
|
||||
@Test
|
||||
void install_showsInHelp() {
|
||||
int exitCode = cmd.execute("service", "--help");
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("install");
|
||||
}
|
||||
|
||||
@Test
|
||||
void install_withHelp_shouldShowUsage() {
|
||||
int exitCode = cmd.execute("service", "install", "--help");
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("Install Barn as a system service");
|
||||
assertThat(stdout.toString()).contains("--user");
|
||||
}
|
||||
|
||||
@Test
|
||||
void install_withBinaryOption_shouldAcceptPath() {
|
||||
int exitCode = cmd.execute("service", "install", "--help");
|
||||
assertThat(stdout.toString()).contains("--binary");
|
||||
}
|
||||
|
||||
@Test
|
||||
void install_withBarnDirOption_shouldAcceptPath() {
|
||||
int exitCode = cmd.execute("service", "install", "--help");
|
||||
assertThat(stdout.toString()).contains("--barn-dir");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class UninstallCommand {
|
||||
|
||||
@Test
|
||||
void uninstall_showsInHelp() {
|
||||
int exitCode = cmd.execute("service", "--help");
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("uninstall");
|
||||
}
|
||||
|
||||
@Test
|
||||
void uninstall_withHelp_shouldShowUsage() {
|
||||
int exitCode = cmd.execute("service", "uninstall", "--help");
|
||||
assertThat(exitCode).isEqualTo(0);
|
||||
assertThat(stdout.toString()).contains("Uninstall Barn system service");
|
||||
assertThat(stdout.toString()).contains("--user");
|
||||
assertThat(stdout.toString()).contains("--force");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for StatusCommand.
|
||||
*/
|
||||
class StatusCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter stdout;
|
||||
private StringWriter stderr;
|
||||
private CommandLine cmd;
|
||||
private BarnDirectories dirs;
|
||||
private JobRepository repository;
|
||||
private JobsConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
repository = new JobRepository(dirs);
|
||||
config = JobsConfig.withDefaults();
|
||||
|
||||
stdout = new StringWriter();
|
||||
stderr = new StringWriter();
|
||||
|
||||
StatusCommand statusCommand = new StatusCommand();
|
||||
statusCommand.setBarnDir(tempDir);
|
||||
|
||||
cmd = new CommandLine(statusCommand);
|
||||
cmd.setOut(new PrintWriter(stdout));
|
||||
cmd.setErr(new PrintWriter(stderr));
|
||||
}
|
||||
|
||||
@Nested
|
||||
class NoJobs {
|
||||
|
||||
@Test
|
||||
void status_withNoJobs_shouldShowEmptyMessage() {
|
||||
int exitCode = cmd.execute("--offline");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).containsIgnoringCase("no jobs");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class WithJobs {
|
||||
|
||||
@Test
|
||||
void status_withJobs_shouldShowAllJobs() throws IOException {
|
||||
// Create some jobs
|
||||
repository.create(List.of("echo", "test1"), "tag1", config);
|
||||
repository.create(List.of("echo", "test2"), "tag2", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("tag1");
|
||||
assertThat(output).contains("tag2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_shouldShowJobIds() throws IOException {
|
||||
repository.create(List.of("echo", "test"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString()).matches("(?s).*job-[a-f0-9]+.*");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_shouldShowJobState() throws IOException {
|
||||
repository.create(List.of("echo", "test"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(stdout.toString().toLowerCase()).contains("queued");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Filtering {
|
||||
|
||||
@Test
|
||||
void status_withTagFilter_shouldOnlyShowMatchingJobs() throws IOException {
|
||||
repository.create(List.of("echo", "test1"), "alpha", config);
|
||||
repository.create(List.of("echo", "test2"), "beta", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--tag", "alpha");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("alpha");
|
||||
assertThat(output).doesNotContain("beta");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_withStateFilter_shouldOnlyShowMatchingJobs() throws IOException {
|
||||
repository.create(List.of("echo", "test1"), "tag1", config);
|
||||
repository.create(List.of("echo", "test2"), "tag2", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--state", "QUEUED");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Both jobs are queued so both should show
|
||||
assertThat(stdout.toString()).contains("tag1");
|
||||
assertThat(stdout.toString()).contains("tag2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_withLimit_shouldLimitResults() throws IOException {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
repository.create(List.of("echo", "test" + i), "tag" + i, config);
|
||||
}
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--limit", "2");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Should only show 2 jobs (most recent ones)
|
||||
String output = stdout.toString();
|
||||
// Count job-id occurrences - should be exactly 2
|
||||
long jobIdCount = output.lines()
|
||||
.filter(line -> line.contains("job-"))
|
||||
.count();
|
||||
assertThat(jobIdCount).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class OutputFormats {
|
||||
|
||||
@Test
|
||||
void status_withJsonOutput_shouldProduceJson() throws IOException {
|
||||
repository.create(List.of("echo", "test"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--output", "JSON");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("{");
|
||||
assertThat(output).contains("\"jobs\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_withXmlOutput_shouldProduceXml() throws IOException {
|
||||
repository.create(List.of("echo", "test"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--output", "XML");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
assertThat(output).contains("<?xml");
|
||||
}
|
||||
|
||||
@Test
|
||||
void status_withHumanOutput_shouldShowTable() throws IOException {
|
||||
repository.create(List.of("echo", "test"), "test", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline", "--output", "HUMAN");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString();
|
||||
// Should have table headers
|
||||
assertThat(output.toUpperCase()).contains("ID");
|
||||
assertThat(output.toUpperCase()).contains("STATE");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Summary {
|
||||
|
||||
@Test
|
||||
void status_shouldShowSummary() throws IOException {
|
||||
repository.create(List.of("echo", "test1"), "tag1", config);
|
||||
repository.create(List.of("echo", "test2"), "tag2", config);
|
||||
|
||||
int exitCode = cmd.execute("--offline");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = stdout.toString().toLowerCase();
|
||||
assertThat(output).contains("total");
|
||||
assertThat(output).contains("2");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceMode {
|
||||
|
||||
@Test
|
||||
void status_withoutOffline_shouldIndicateServiceNeeded() {
|
||||
int exitCode = cmd.execute();
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(stderr.toString()).containsIgnoringCase("service");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.monitoring.UsageLogger;
|
||||
import com.samsonmedia.barn.monitoring.UsageRecord;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
import picocli.CommandLine;
|
||||
|
||||
/**
|
||||
* Tests for UsageCommand.
|
||||
*/
|
||||
class UsageCommandTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private StringWriter outWriter;
|
||||
private StringWriter errWriter;
|
||||
private CommandLine cmd;
|
||||
private BarnDirectories dirs;
|
||||
private JobRepository repository;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
outWriter = new StringWriter();
|
||||
errWriter = new StringWriter();
|
||||
cmd = new CommandLine(new BarnCommand());
|
||||
cmd.setOut(new PrintWriter(outWriter));
|
||||
cmd.setErr(new PrintWriter(errWriter));
|
||||
|
||||
dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
repository = new JobRepository(dirs);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class UsageOutput {
|
||||
|
||||
@Test
|
||||
void usage_withNoJob_shouldShowError() {
|
||||
int exitCode = cmd.execute("usage", "nonexistent-job", "--offline");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(errWriter.toString()).contains("Job not found");
|
||||
}
|
||||
|
||||
@Test
|
||||
void usage_withNoUsageData_shouldShowError() throws IOException {
|
||||
// Create job without usage data
|
||||
final var job = repository.create(List.of("echo", "test"), null, JobsConfig.withDefaults());
|
||||
|
||||
// Use custom command with barn dir set
|
||||
UsageCommand usageCmd = new UsageCommand();
|
||||
usageCmd.setBarnDir(tempDir);
|
||||
|
||||
CommandLine customCmd = new CommandLine(usageCmd);
|
||||
customCmd.setOut(new PrintWriter(outWriter));
|
||||
customCmd.setErr(new PrintWriter(errWriter));
|
||||
|
||||
int exitCode = customCmd.execute(job.id(), "--offline");
|
||||
|
||||
assertThat(exitCode).isNotZero();
|
||||
assertThat(errWriter.toString()).contains("No usage data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void usage_withValidData_shouldShowSummary() throws Exception {
|
||||
// Create job with usage data
|
||||
var job = repository.create(List.of("echo", "test"), null, JobsConfig.withDefaults());
|
||||
createUsageData(job.id());
|
||||
|
||||
// Execute command with custom barn dir
|
||||
UsageCommand usageCmd = new UsageCommand();
|
||||
usageCmd.setBarnDir(tempDir);
|
||||
|
||||
CommandLine customCmd = new CommandLine(usageCmd);
|
||||
customCmd.setOut(new PrintWriter(outWriter));
|
||||
customCmd.setErr(new PrintWriter(errWriter));
|
||||
|
||||
int exitCode = customCmd.execute(job.id(), "--offline");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Resource Usage for Job");
|
||||
assertThat(output).contains("Summary");
|
||||
assertThat(output).contains("CPU");
|
||||
assertThat(output).contains("Memory");
|
||||
}
|
||||
|
||||
@Test
|
||||
void usage_withSummaryOnly_shouldNotShowSamples() throws Exception {
|
||||
var job = repository.create(List.of("echo", "test"), null, JobsConfig.withDefaults());
|
||||
createUsageData(job.id());
|
||||
|
||||
UsageCommand usageCmd = new UsageCommand();
|
||||
usageCmd.setBarnDir(tempDir);
|
||||
|
||||
CommandLine customCmd = new CommandLine(usageCmd);
|
||||
customCmd.setOut(new PrintWriter(outWriter));
|
||||
customCmd.setErr(new PrintWriter(errWriter));
|
||||
|
||||
int exitCode = customCmd.execute(job.id(), "--offline", "--summary");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Summary");
|
||||
assertThat(output).doesNotContain("Recent Samples");
|
||||
}
|
||||
|
||||
@Test
|
||||
void usage_withCsvFlag_shouldOutputRawCsv() throws Exception {
|
||||
var job = repository.create(List.of("echo", "test"), null, JobsConfig.withDefaults());
|
||||
createUsageData(job.id());
|
||||
|
||||
UsageCommand usageCmd = new UsageCommand();
|
||||
usageCmd.setBarnDir(tempDir);
|
||||
|
||||
CommandLine customCmd = new CommandLine(usageCmd);
|
||||
customCmd.setOut(new PrintWriter(outWriter));
|
||||
customCmd.setErr(new PrintWriter(errWriter));
|
||||
|
||||
int exitCode = customCmd.execute(job.id(), "--offline", "--csv");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains(UsageRecord.csvHeader());
|
||||
assertThat(output).contains(","); // CSV format
|
||||
}
|
||||
|
||||
@Test
|
||||
void usage_withLimit_shouldLimitRecords() throws Exception {
|
||||
var job = repository.create(List.of("echo", "test"), null, JobsConfig.withDefaults());
|
||||
createUsageData(job.id(), 10); // Create 10 records
|
||||
|
||||
UsageCommand usageCmd = new UsageCommand();
|
||||
usageCmd.setBarnDir(tempDir);
|
||||
|
||||
CommandLine customCmd = new CommandLine(usageCmd);
|
||||
customCmd.setOut(new PrintWriter(outWriter));
|
||||
customCmd.setErr(new PrintWriter(errWriter));
|
||||
|
||||
int exitCode = customCmd.execute(job.id(), "--offline", "--limit", "3");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
// Output should mention limited records
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("Summary");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JsonOutput {
|
||||
|
||||
@Test
|
||||
void usage_withJsonFormat_shouldOutputJson() throws Exception {
|
||||
var job = repository.create(List.of("echo", "test"), null, JobsConfig.withDefaults());
|
||||
createUsageData(job.id());
|
||||
|
||||
UsageCommand usageCmd = new UsageCommand();
|
||||
usageCmd.setBarnDir(tempDir);
|
||||
|
||||
CommandLine customCmd = new CommandLine(usageCmd);
|
||||
customCmd.setOut(new PrintWriter(outWriter));
|
||||
customCmd.setErr(new PrintWriter(errWriter));
|
||||
|
||||
int exitCode = customCmd.execute(job.id(), "--offline", "--output", "JSON");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("\"jobId\"");
|
||||
assertThat(output).contains("\"summary\"");
|
||||
assertThat(output).contains("\"samples\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void usage_withJsonAndSummaryOnly_shouldNotIncludeSamples() throws Exception {
|
||||
var job = repository.create(List.of("echo", "test"), null, JobsConfig.withDefaults());
|
||||
createUsageData(job.id());
|
||||
|
||||
UsageCommand usageCmd = new UsageCommand();
|
||||
usageCmd.setBarnDir(tempDir);
|
||||
|
||||
CommandLine customCmd = new CommandLine(usageCmd);
|
||||
customCmd.setOut(new PrintWriter(outWriter));
|
||||
customCmd.setErr(new PrintWriter(errWriter));
|
||||
|
||||
int exitCode = customCmd.execute(job.id(), "--offline", "--output", "JSON", "--summary");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
String output = outWriter.toString();
|
||||
assertThat(output).contains("\"jobId\"");
|
||||
assertThat(output).contains("\"summary\"");
|
||||
assertThat(output).doesNotContain("\"samples\"");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Help {
|
||||
|
||||
@Test
|
||||
void usage_withHelp_shouldShowUsage() {
|
||||
int exitCode = cmd.execute("usage", "--help");
|
||||
|
||||
assertThat(exitCode).isZero();
|
||||
assertThat(outWriter.toString()).contains("Show resource usage for a job");
|
||||
assertThat(outWriter.toString()).contains("--limit");
|
||||
assertThat(outWriter.toString()).contains("--csv");
|
||||
assertThat(outWriter.toString()).contains("--summary");
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private void createUsageData(String jobId) throws IOException {
|
||||
createUsageData(jobId, 5);
|
||||
}
|
||||
|
||||
private void createUsageData(String jobId, int recordCount) throws IOException {
|
||||
Path logsDir = dirs.getJobLogsDir(jobId);
|
||||
Files.createDirectories(logsDir);
|
||||
|
||||
try (UsageLogger logger = UsageLogger.forJobLogsDir(logsDir)) {
|
||||
Instant base = Instant.now();
|
||||
for (int i = 0; i < recordCount; i++) {
|
||||
UsageRecord record = UsageRecord.withoutGpu(
|
||||
base.plusSeconds(i * 5),
|
||||
20.0 + i * 5, // CPU: 20%, 25%, 30%, ...
|
||||
1024 * 1024 * (i + 1), // Memory: 1MB, 2MB, 3MB, ...
|
||||
512 * 1024 * (i + 1) // Disk: 512KB, 1MB, 1.5MB, ...
|
||||
);
|
||||
logger.log(record);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Tests for XmlFormatter.
|
||||
*/
|
||||
class XmlFormatterTest {
|
||||
|
||||
private XmlFormatter formatter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
formatter = new XmlFormatter();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Format {
|
||||
|
||||
@Test
|
||||
void format_withNull_shouldReturnNullElement() {
|
||||
String result = formatter.format(null);
|
||||
|
||||
assertThat(result).contains("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
|
||||
assertThat(result).contains("<null/>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withString_shouldReturnResultElement() {
|
||||
String result = formatter.format("hello");
|
||||
|
||||
assertThat(result).contains("<result>hello</result>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withJob_shouldProduceValidXml() {
|
||||
Job job = createJob("job-12345678", JobState.RUNNING, "test-tag");
|
||||
|
||||
String result = formatter.format(job);
|
||||
|
||||
assertThat(result).contains("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
|
||||
assertThat(result).contains("<job>");
|
||||
assertThat(result).contains("<id>job-12345678</id>");
|
||||
assertThat(result).contains("<state>running</state>");
|
||||
assertThat(result).contains("<tag>test-tag</tag>");
|
||||
assertThat(result).contains("</job>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withJob_shouldIncludeCommand() {
|
||||
Job job = createJob("job-12345678", JobState.RUNNING, "test-tag");
|
||||
|
||||
String result = formatter.format(job);
|
||||
|
||||
assertThat(result).contains("<command>");
|
||||
assertThat(result).contains("<arg>echo</arg>");
|
||||
assertThat(result).contains("<arg>test</arg>");
|
||||
assertThat(result).contains("</command>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withJob_shouldFormatDatesAsIso8601() {
|
||||
Job job = createJob("job-12345678", JobState.RUNNING, "test-tag");
|
||||
|
||||
String result = formatter.format(job);
|
||||
|
||||
assertThat(result).contains("<created_at>");
|
||||
// ISO-8601 format
|
||||
assertThat(result).matches("(?s).*<created_at>\\d{4}-\\d{2}-\\d{2}T.*</created_at>.*");
|
||||
}
|
||||
|
||||
@Test
|
||||
void format_withMap_shouldProduceValidXml() {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
|
||||
String result = formatter.format(map);
|
||||
|
||||
assertThat(result).contains("<result>");
|
||||
assertThat(result).contains("<key1>value1</key1>");
|
||||
assertThat(result).contains("<key2>value2</key2>");
|
||||
assertThat(result).contains("</result>");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FormatList {
|
||||
|
||||
@Test
|
||||
void formatList_withNull_shouldReturnEmptyResults() {
|
||||
String result = formatter.formatList(null);
|
||||
|
||||
assertThat(result).contains("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
|
||||
assertThat(result).contains("<results/>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withEmpty_shouldReturnEmptyResults() {
|
||||
String result = formatter.formatList(List.of());
|
||||
|
||||
assertThat(result).contains("<results/>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withJobs_shouldProduceValidXml() {
|
||||
List<Job> jobs = List.of(
|
||||
createJob("job-11111111", JobState.RUNNING, "tag1"),
|
||||
createJob("job-22222222", JobState.QUEUED, "tag2")
|
||||
);
|
||||
|
||||
String result = formatter.formatList(jobs);
|
||||
|
||||
assertThat(result).contains("<results>");
|
||||
assertThat(result).contains("<job>");
|
||||
assertThat(result).contains("<id>job-11111111</id>");
|
||||
assertThat(result).contains("<id>job-22222222</id>");
|
||||
assertThat(result).contains("</results>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatList_withStrings_shouldProduceValidXml() {
|
||||
List<String> strings = List.of("one", "two", "three");
|
||||
|
||||
String result = formatter.formatList(strings);
|
||||
|
||||
assertThat(result).contains("<results>");
|
||||
assertThat(result).contains("<item>one</item>");
|
||||
assertThat(result).contains("<item>two</item>");
|
||||
assertThat(result).contains("<item>three</item>");
|
||||
assertThat(result).contains("</results>");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FormatError {
|
||||
|
||||
@Test
|
||||
void formatError_withMessageOnly_shouldProduceValidXml() {
|
||||
String result = formatter.formatError("Something went wrong", null);
|
||||
|
||||
assertThat(result).contains("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
|
||||
assertThat(result).contains("<error>");
|
||||
assertThat(result).contains("<message>Something went wrong</message>");
|
||||
assertThat(result).contains("</error>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatError_withCause_shouldIncludeCause() {
|
||||
Exception cause = new RuntimeException("Root cause");
|
||||
String result = formatter.formatError("Something went wrong", cause);
|
||||
|
||||
assertThat(result).contains("<message>Something went wrong</message>");
|
||||
assertThat(result).contains("<cause>Root cause</cause>");
|
||||
assertThat(result).contains("<type>RuntimeException</type>");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class XmlEscaping {
|
||||
|
||||
@Test
|
||||
void format_withSpecialCharacters_shouldEscapeThem() {
|
||||
String result = formatter.format("<script>alert('xss')</script>");
|
||||
|
||||
assertThat(result).contains("<script>");
|
||||
assertThat(result).contains("'xss'");
|
||||
assertThat(result).doesNotContain("<script>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatError_withSpecialCharacters_shouldEscapeThem() {
|
||||
String result = formatter.formatError("Error: <test> & \"quotes\"", null);
|
||||
|
||||
assertThat(result).contains("<test>");
|
||||
assertThat(result).contains("&");
|
||||
assertThat(result).contains(""quotes"");
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private Job createJob(String id, JobState state, String tag) {
|
||||
return new Job(
|
||||
id,
|
||||
state,
|
||||
List.of("echo", "test"),
|
||||
tag,
|
||||
Instant.now(),
|
||||
state == JobState.RUNNING ? Instant.now().minus(Duration.ofMinutes(1)) : null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
state == JobState.RUNNING ? 12345L : null,
|
||||
null,
|
||||
0,
|
||||
null
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package com.samsonmedia.barn.execution;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
import com.samsonmedia.barn.state.StateFiles;
|
||||
|
||||
/**
|
||||
* Tests for CrashRecovery.
|
||||
*/
|
||||
class CrashRecoveryTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private BarnDirectories dirs;
|
||||
private JobRepository repository;
|
||||
private HeartbeatChecker heartbeatChecker;
|
||||
private CrashRecovery crashRecovery;
|
||||
private JobsConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
repository = new JobRepository(dirs);
|
||||
heartbeatChecker = new HeartbeatChecker(Duration.ofSeconds(30));
|
||||
crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs);
|
||||
config = JobsConfig.withDefaults();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Constructor {
|
||||
|
||||
@Test
|
||||
void constructor_withNullRepository_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new CrashRecovery(null, heartbeatChecker, dirs))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullHeartbeatChecker_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new CrashRecovery(repository, null, dirs))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullDirs_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new CrashRecovery(repository, heartbeatChecker, null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class RecoverOrphanedJobs {
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withNoJobs_shouldReturnEmpty() throws IOException {
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
assertThat(recovered).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withQueuedJobs_shouldNotRecover() throws IOException {
|
||||
repository.create(List.of("echo", "test"), "test", config);
|
||||
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
assertThat(recovered).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withCompletedJobs_shouldNotRecover() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
||||
repository.markStarted(job.id(), 12345);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
assertThat(recovered).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withRunningJobFreshHeartbeat_shouldNotRecover() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
||||
repository.markStarted(job.id(), ProcessUtils.getCurrentPid()); // Use current PID (alive)
|
||||
repository.updateHeartbeat(job.id(), Instant.now()); // Fresh heartbeat
|
||||
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
assertThat(recovered).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withRunningJobStaleHeartbeatDeadProcess_shouldRecover() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
||||
// Use a PID that's unlikely to exist (very high number)
|
||||
repository.markStarted(job.id(), 999999999L);
|
||||
// Set a stale heartbeat
|
||||
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
||||
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
assertThat(recovered).hasSize(1);
|
||||
assertThat(recovered.get(0).id()).isEqualTo(job.id());
|
||||
|
||||
// Verify job is now marked as failed
|
||||
Job updatedJob = repository.findById(job.id()).orElseThrow();
|
||||
assertThat(updatedJob.state()).isEqualTo(JobState.FAILED);
|
||||
assertThat(updatedJob.error()).contains("orphaned");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withRunningJobNoHeartbeatDeadProcess_shouldRecover() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
||||
repository.markStarted(job.id(), 999999999L);
|
||||
// Clear heartbeat to simulate crash before first heartbeat
|
||||
clearHeartbeat(job.id());
|
||||
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
assertThat(recovered).hasSize(1);
|
||||
assertThat(recovered.get(0).id()).isEqualTo(job.id());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withRunningJobStaleHeartbeatAliveProcess_shouldNotRecover() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
||||
// Use current process PID which is definitely alive
|
||||
repository.markStarted(job.id(), ProcessUtils.getCurrentPid());
|
||||
// Set a stale heartbeat
|
||||
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
||||
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
// Should not recover because process is still alive
|
||||
assertThat(recovered).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withRunningJobNoPid_shouldRecover() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
||||
// Manually set running state without PID (simulates partial write)
|
||||
StateFiles stateFiles = new StateFiles(dirs.getJobDir(job.id()));
|
||||
stateFiles.writeState(JobState.RUNNING);
|
||||
stateFiles.writeStartedAt(Instant.now().minus(Duration.ofMinutes(10)));
|
||||
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
assertThat(recovered).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_withMultipleOrphanedJobs_shouldRecoverAll() throws IOException {
|
||||
// Create 3 orphaned jobs
|
||||
for (int i = 0; i < 3; i++) {
|
||||
Job job = repository.create(List.of("echo", "test" + i), "test", config);
|
||||
repository.markStarted(job.id(), 999999999L + i);
|
||||
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
||||
}
|
||||
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
assertThat(recovered).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverOrphanedJobs_shouldSetCorrectExitCode() throws IOException {
|
||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
||||
repository.markStarted(job.id(), 999999999L);
|
||||
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
||||
|
||||
crashRecovery.recoverOrphanedJobs();
|
||||
|
||||
Job updatedJob = repository.findById(job.id()).orElseThrow();
|
||||
// Exit code is stored as symbolic string, so we check error message
|
||||
assertThat(updatedJob.error()).contains("orphaned");
|
||||
assertThat(updatedJob.finishedAt()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class IsOrphaned {
|
||||
|
||||
@Test
|
||||
void isOrphaned_withNullJob_shouldThrowException() {
|
||||
assertThatThrownBy(() -> crashRecovery.isOrphaned(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isOrphaned_withQueuedJob_shouldReturnFalse() {
|
||||
Job job = createJob(JobState.QUEUED, null, null);
|
||||
|
||||
assertThat(crashRecovery.isOrphaned(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isOrphaned_withRunningJobAliveProcess_shouldReturnFalse() {
|
||||
Job job = createJob(JobState.RUNNING, ProcessUtils.getCurrentPid(), Instant.now());
|
||||
|
||||
assertThat(crashRecovery.isOrphaned(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isOrphaned_withRunningJobDeadProcessStaleHeartbeat_shouldReturnTrue() {
|
||||
Instant stale = Instant.now().minus(Duration.ofMinutes(5));
|
||||
Job job = createJob(JobState.RUNNING, 999999999L, stale);
|
||||
|
||||
assertThat(crashRecovery.isOrphaned(job)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isOrphaned_withRunningJobDeadProcessFreshHeartbeat_shouldReturnFalse() {
|
||||
// Fresh heartbeat + dead process = weird state, but fresh heartbeat wins
|
||||
Job job = createJob(JobState.RUNNING, 999999999L, Instant.now());
|
||||
|
||||
assertThat(crashRecovery.isOrphaned(job)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private void setStaleHeartbeat(String jobId, Duration age) throws IOException {
|
||||
StateFiles stateFiles = new StateFiles(dirs.getJobDir(jobId));
|
||||
stateFiles.writeHeartbeat(Instant.now().minus(age));
|
||||
}
|
||||
|
||||
private void clearHeartbeat(String jobId) throws IOException {
|
||||
StateFiles stateFiles = new StateFiles(dirs.getJobDir(jobId));
|
||||
stateFiles.writeHeartbeat(null);
|
||||
}
|
||||
|
||||
private Job createJob(JobState state, Long pid, Instant heartbeat) {
|
||||
return new Job(
|
||||
"job-12345678",
|
||||
state,
|
||||
List.of("echo", "test"),
|
||||
null, // tag
|
||||
Instant.now(), // createdAt
|
||||
state == JobState.RUNNING ? Instant.now().minus(Duration.ofMinutes(1)) : null, // startedAt
|
||||
null, // finishedAt
|
||||
null, // exitCode
|
||||
null, // error
|
||||
pid,
|
||||
heartbeat,
|
||||
0, // retryCount
|
||||
null // retryAt
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.samsonmedia.barn.execution;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Tests for HeartbeatChecker.
|
||||
*/
|
||||
class HeartbeatCheckerTest {
|
||||
|
||||
private static final Duration DEFAULT_THRESHOLD = Duration.ofSeconds(30);
|
||||
|
||||
private HeartbeatChecker checker;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
checker = new HeartbeatChecker(DEFAULT_THRESHOLD);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Constructor {
|
||||
|
||||
@Test
|
||||
void constructor_withNullThreshold_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new HeartbeatChecker(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withZeroThreshold_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new HeartbeatChecker(Duration.ZERO))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNegativeThreshold_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new HeartbeatChecker(Duration.ofSeconds(-1)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withValidThreshold_shouldSucceed() {
|
||||
HeartbeatChecker hc = new HeartbeatChecker(Duration.ofSeconds(10));
|
||||
assertThat(hc.getThreshold()).isEqualTo(Duration.ofSeconds(10));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class IsStale {
|
||||
|
||||
@Test
|
||||
void isStale_withQueuedJob_shouldReturnFalse() {
|
||||
Job job = createJob(JobState.QUEUED, null);
|
||||
|
||||
assertThat(checker.isStale(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withSucceededJob_shouldReturnFalse() {
|
||||
Job job = createJob(JobState.SUCCEEDED, null);
|
||||
|
||||
assertThat(checker.isStale(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withFailedJob_shouldReturnFalse() {
|
||||
Job job = createJob(JobState.FAILED, null);
|
||||
|
||||
assertThat(checker.isStale(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withCanceledJob_shouldReturnFalse() {
|
||||
Job job = createJob(JobState.CANCELED, null);
|
||||
|
||||
assertThat(checker.isStale(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withRunningJobNoHeartbeat_shouldReturnTrue() {
|
||||
Job job = createJob(JobState.RUNNING, null);
|
||||
|
||||
assertThat(checker.isStale(job)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withRunningJobFreshHeartbeat_shouldReturnFalse() {
|
||||
Instant recent = Instant.now().minus(Duration.ofSeconds(5));
|
||||
Job job = createJob(JobState.RUNNING, recent);
|
||||
|
||||
assertThat(checker.isStale(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withRunningJobStaleHeartbeat_shouldReturnTrue() {
|
||||
Instant stale = Instant.now().minus(Duration.ofSeconds(60));
|
||||
Job job = createJob(JobState.RUNNING, stale);
|
||||
|
||||
assertThat(checker.isStale(job)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withRunningJobBoundaryHeartbeat_shouldReturnFalse() {
|
||||
// Heartbeat just inside threshold boundary should not be stale
|
||||
// Add 100ms buffer to account for test execution time
|
||||
Instant boundary = Instant.now().minus(DEFAULT_THRESHOLD).plusMillis(100);
|
||||
Job job = createJob(JobState.RUNNING, boundary);
|
||||
|
||||
// Just inside the boundary is acceptable
|
||||
assertThat(checker.isStale(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withRunningJobJustPastThreshold_shouldReturnTrue() {
|
||||
Instant pastThreshold = Instant.now().minus(DEFAULT_THRESHOLD).minusMillis(1);
|
||||
Job job = createJob(JobState.RUNNING, pastThreshold);
|
||||
|
||||
assertThat(checker.isStale(job)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStale_withNullJob_shouldThrowException() {
|
||||
assertThatThrownBy(() -> checker.isStale(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetThreshold {
|
||||
|
||||
@Test
|
||||
void getThreshold_shouldReturnConfiguredThreshold() {
|
||||
HeartbeatChecker hc = new HeartbeatChecker(Duration.ofMinutes(5));
|
||||
|
||||
assertThat(hc.getThreshold()).isEqualTo(Duration.ofMinutes(5));
|
||||
}
|
||||
}
|
||||
|
||||
private Job createJob(JobState state, Instant heartbeat) {
|
||||
return new Job(
|
||||
"job-12345678",
|
||||
state,
|
||||
List.of("echo", "test"),
|
||||
null, // tag
|
||||
Instant.now(), // createdAt
|
||||
state == JobState.RUNNING ? Instant.now().minus(Duration.ofMinutes(1)) : null, // startedAt
|
||||
null, // finishedAt
|
||||
null, // exitCode
|
||||
null, // error
|
||||
state == JobState.RUNNING ? 12345L : null, // pid
|
||||
heartbeat,
|
||||
0, // retryCount
|
||||
null // retryAt
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -177,7 +177,7 @@ class JobRunnerTest {
|
||||
ProcessExecutor executor = new ProcessExecutor();
|
||||
ProcessMonitor monitor = new ProcessMonitor();
|
||||
|
||||
JobRunner customRunner = new JobRunner(executor, monitor, repository, dirs);
|
||||
JobRunner customRunner = new JobRunner(executor, monitor, repository, dirs, null);
|
||||
|
||||
assertThat(customRunner).isNotNull();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
package com.samsonmedia.barn.execution;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
/**
|
||||
* Tests for JobScheduler.
|
||||
*/
|
||||
class JobSchedulerTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private BarnDirectories dirs;
|
||||
private JobRepository repository;
|
||||
private JobRunner runner;
|
||||
private JobScheduler scheduler;
|
||||
private JobsConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
repository = new JobRepository(dirs);
|
||||
runner = new JobRunner(repository, dirs);
|
||||
config = JobsConfig.withDefaults();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (scheduler != null && scheduler.isRunning()) {
|
||||
scheduler.stopNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class StartAndStop {
|
||||
|
||||
@Test
|
||||
void start_shouldAcquireLock() throws IOException {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
scheduler.start();
|
||||
|
||||
assertThat(scheduler.isRunning()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_whenAlreadyRunning_shouldThrowException() throws IOException {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
scheduler.start();
|
||||
|
||||
assertThatThrownBy(() -> scheduler.start())
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("already running");
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_withLockHeld_shouldThrowException() throws IOException {
|
||||
// First scheduler acquires lock
|
||||
JobScheduler firstScheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
firstScheduler.start();
|
||||
|
||||
// Second scheduler should fail
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
try {
|
||||
assertThatThrownBy(() -> scheduler.start())
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("Another scheduler");
|
||||
} finally {
|
||||
firstScheduler.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_shouldReleaseLock() throws IOException {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
scheduler.start();
|
||||
scheduler.stop();
|
||||
|
||||
assertThat(scheduler.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_whenNotRunning_shouldNotThrow() {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
scheduler.stop(); // Should not throw
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopNow_shouldTerminateImmediately() throws IOException {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
scheduler.start();
|
||||
scheduler.stopNow();
|
||||
|
||||
assertThat(scheduler.isRunning()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JobExecution {
|
||||
|
||||
@Test
|
||||
void scheduler_shouldExecuteQueuedJobs() throws IOException, InterruptedException {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(50), Duration.ofSeconds(10));
|
||||
|
||||
// Create a quick job
|
||||
Job job = repository.create(getEchoCommand("test"), "test", config);
|
||||
|
||||
scheduler.start();
|
||||
|
||||
// Wait for job to complete
|
||||
assertThat(waitForJobCompletion(job.id(), Duration.ofSeconds(10))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduler_shouldExecuteJobsInFIFO() throws IOException, InterruptedException {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(50), Duration.ofSeconds(10));
|
||||
|
||||
// Create multiple jobs with slight delays to ensure different creation times
|
||||
final String jobId1 = repository.create(getEchoCommand("first"), "tag1", config).id();
|
||||
Thread.sleep(10);
|
||||
final String jobId2 = repository.create(getEchoCommand("second"), "tag2", config).id();
|
||||
Thread.sleep(10);
|
||||
final String jobId3 = repository.create(getEchoCommand("third"), "tag3", config).id();
|
||||
|
||||
scheduler.start();
|
||||
|
||||
// Jobs should complete in order (first created, first executed)
|
||||
assertThat(waitForJobCompletion(jobId1, Duration.ofSeconds(10))).isTrue();
|
||||
assertThat(waitForJobCompletion(jobId2, Duration.ofSeconds(10))).isTrue();
|
||||
assertThat(waitForJobCompletion(jobId3, Duration.ofSeconds(10))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduler_shouldRespectMaxConcurrentJobs() throws IOException, InterruptedException {
|
||||
int maxConcurrent = 2;
|
||||
scheduler = new JobScheduler(repository, runner, dirs, maxConcurrent,
|
||||
Duration.ofMillis(50), Duration.ofSeconds(10));
|
||||
|
||||
// Create jobs that take some time (short duration for test reliability)
|
||||
for (int i = 0; i < 4; i++) {
|
||||
repository.create(getEchoCommand("job" + i), "tag" + i, config);
|
||||
}
|
||||
|
||||
scheduler.start();
|
||||
|
||||
// Allow scheduler to pick up jobs
|
||||
Thread.sleep(200);
|
||||
JobScheduler.SchedulerStatus status = scheduler.getStatus();
|
||||
|
||||
// Running jobs should never exceed max concurrent limit
|
||||
assertThat(status.runningJobs()).isLessThanOrEqualTo(maxConcurrent);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetStatus {
|
||||
|
||||
@Test
|
||||
void getStatus_whenNotRunning_shouldShowNotRunning() {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 2,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
JobScheduler.SchedulerStatus status = scheduler.getStatus();
|
||||
|
||||
assertThat(status.isRunning()).isFalse();
|
||||
assertThat(status.maxConcurrentJobs()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getStatus_withQueuedJobs_shouldShowCount() throws IOException {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 2,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
repository.create(getEchoCommand("test1"), "tag1", config);
|
||||
repository.create(getEchoCommand("test2"), "tag2", config);
|
||||
|
||||
JobScheduler.SchedulerStatus status = scheduler.getStatus();
|
||||
|
||||
assertThat(status.queuedJobs()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Submit {
|
||||
|
||||
@Test
|
||||
void submit_withNullJob_shouldThrowException() {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
assertThatThrownBy(() -> scheduler.submit(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_shouldAcceptJob() throws IOException {
|
||||
scheduler = new JobScheduler(repository, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||
|
||||
Job job = repository.create(getEchoCommand("test"), "test", config);
|
||||
|
||||
scheduler.submit(job); // Should not throw
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Constructor {
|
||||
|
||||
@Test
|
||||
void constructor_withNullRepository_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new JobScheduler(null, runner, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5)))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullRunner_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new JobScheduler(repository, null, dirs, 1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5)))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withZeroMaxConcurrent_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new JobScheduler(repository, runner, dirs, 0,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNegativeMaxConcurrent_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new JobScheduler(repository, runner, dirs, -1,
|
||||
Duration.ofMillis(100), Duration.ofSeconds(5)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class SchedulerStatusRecord {
|
||||
|
||||
@Test
|
||||
void schedulerStatus_shouldContainAllFields() {
|
||||
JobScheduler.SchedulerStatus status = new JobScheduler.SchedulerStatus(5, 10, 8, true);
|
||||
|
||||
assertThat(status.runningJobs()).isEqualTo(5);
|
||||
assertThat(status.queuedJobs()).isEqualTo(10);
|
||||
assertThat(status.maxConcurrentJobs()).isEqualTo(8);
|
||||
assertThat(status.isRunning()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private boolean waitForJobCompletion(String jobId, Duration timeout) throws IOException, InterruptedException {
|
||||
long endTime = System.currentTimeMillis() + timeout.toMillis();
|
||||
while (System.currentTimeMillis() < endTime) {
|
||||
Job job = repository.findById(jobId).orElse(null);
|
||||
if (job != null && job.isTerminal()) {
|
||||
return true;
|
||||
}
|
||||
Thread.sleep(100);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private List<String> getEchoCommand(String message) {
|
||||
if (isWindows()) {
|
||||
return List.of("cmd", "/c", "echo", message);
|
||||
}
|
||||
return List.of("echo", message);
|
||||
}
|
||||
|
||||
private boolean isWindows() {
|
||||
return System.getProperty("os.name").toLowerCase().contains("win");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.samsonmedia.barn.execution;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Tests for SchedulerLock.
|
||||
*/
|
||||
class SchedulerLockTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
@Nested
|
||||
class TryAcquire {
|
||||
|
||||
@Test
|
||||
void tryAcquire_withNoExistingLock_shouldSucceed() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
Optional<SchedulerLock> lock = SchedulerLock.tryAcquire(lockFile);
|
||||
|
||||
assertThat(lock).isPresent();
|
||||
assertThat(lock.get().isValid()).isTrue();
|
||||
lock.get().close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryAcquire_shouldCreateLockFile() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
try (SchedulerLock lock = SchedulerLock.tryAcquire(lockFile).orElseThrow()) {
|
||||
assertThat(lock).isNotNull();
|
||||
assertThat(Files.exists(lockFile)).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryAcquire_shouldCreateParentDirectories() throws IOException {
|
||||
Path lockFile = tempDir.resolve("locks/nested/scheduler.lock");
|
||||
|
||||
try (SchedulerLock lock = SchedulerLock.tryAcquire(lockFile).orElseThrow()) {
|
||||
assertThat(lock).isNotNull();
|
||||
assertThat(Files.exists(lockFile.getParent())).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryAcquire_withExistingLock_shouldReturnEmpty() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
try (SchedulerLock firstLock = SchedulerLock.tryAcquire(lockFile).orElseThrow()) {
|
||||
assertThat(firstLock).isNotNull();
|
||||
Optional<SchedulerLock> secondLock = SchedulerLock.tryAcquire(lockFile);
|
||||
|
||||
assertThat(secondLock).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryAcquire_afterRelease_shouldSucceed() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
// First acquire and release
|
||||
SchedulerLock firstLock = SchedulerLock.tryAcquire(lockFile).orElseThrow();
|
||||
firstLock.close();
|
||||
|
||||
// Should be able to acquire again
|
||||
Optional<SchedulerLock> secondLock = SchedulerLock.tryAcquire(lockFile);
|
||||
|
||||
assertThat(secondLock).isPresent();
|
||||
secondLock.get().close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryAcquire_withNullLockFile_shouldThrowException() {
|
||||
assertThatThrownBy(() -> SchedulerLock.tryAcquire(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetLockFile {
|
||||
|
||||
@Test
|
||||
void getLockFile_shouldReturnLockFilePath() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
try (SchedulerLock lock = SchedulerLock.tryAcquire(lockFile).orElseThrow()) {
|
||||
assertThat(lock.getLockFile()).isEqualTo(lockFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class IsValid {
|
||||
|
||||
@Test
|
||||
void isValid_withActiveLock_shouldReturnTrue() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
try (SchedulerLock lock = SchedulerLock.tryAcquire(lockFile).orElseThrow()) {
|
||||
assertThat(lock.isValid()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void isValid_afterClose_shouldReturnFalse() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
SchedulerLock lock = SchedulerLock.tryAcquire(lockFile).orElseThrow();
|
||||
lock.close();
|
||||
|
||||
assertThat(lock.isValid()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Close {
|
||||
|
||||
@Test
|
||||
void close_shouldReleaseLock() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
SchedulerLock lock = SchedulerLock.tryAcquire(lockFile).orElseThrow();
|
||||
lock.close();
|
||||
|
||||
// Should be able to acquire again
|
||||
Optional<SchedulerLock> newLock = SchedulerLock.tryAcquire(lockFile);
|
||||
assertThat(newLock).isPresent();
|
||||
newLock.get().close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void close_canBeCalledMultipleTimes() throws IOException {
|
||||
Path lockFile = tempDir.resolve("scheduler.lock");
|
||||
|
||||
SchedulerLock lock = SchedulerLock.tryAcquire(lockFile).orElseThrow();
|
||||
lock.close();
|
||||
lock.close(); // Should not throw
|
||||
lock.close(); // Should not throw
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Tests for IpcClient.
|
||||
*/
|
||||
class IpcClientTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
@Nested
|
||||
class Construction {
|
||||
|
||||
@Test
|
||||
void constructor_shouldStoreSocketPath() {
|
||||
Path socketPath = tempDir.resolve("test.sock");
|
||||
var client = new IpcClient(socketPath);
|
||||
|
||||
assertThat(client.getSocketPath()).isEqualTo(socketPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullPath_shouldThrow() {
|
||||
assertThatThrownBy(() -> new IpcClient(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceRunningCheck {
|
||||
|
||||
@Test
|
||||
void isServiceRunning_withNoSocket_shouldReturnFalse() {
|
||||
Path socketPath = tempDir.resolve("nonexistent.sock");
|
||||
var client = new IpcClient(socketPath);
|
||||
|
||||
assertThat(client.isServiceRunning()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Connection {
|
||||
|
||||
@Test
|
||||
void ensureConnected_withNoSocket_shouldThrow() {
|
||||
Path socketPath = tempDir.resolve("nonexistent.sock");
|
||||
var client = new IpcClient(socketPath);
|
||||
|
||||
assertThatThrownBy(client::ensureConnected)
|
||||
.isInstanceOf(IpcException.class)
|
||||
.hasFieldOrPropertyWithValue("code", IpcErrorCode.SERVICE_NOT_RUNNING);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class DefaultSocketPath {
|
||||
|
||||
@Test
|
||||
void getDefaultSocketPath_shouldReturnNonNull() {
|
||||
Path path = IpcClient.getDefaultSocketPath();
|
||||
|
||||
assertThat(path).isNotNull();
|
||||
assertThat(path.toString()).contains("barn");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Close {
|
||||
|
||||
@Test
|
||||
void close_withoutConnection_shouldNotThrow() {
|
||||
Path socketPath = tempDir.resolve("test.sock");
|
||||
var client = new IpcClient(socketPath);
|
||||
|
||||
// Should not throw even if never connected
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void close_multipleTimes_shouldNotThrow() {
|
||||
Path socketPath = tempDir.resolve("test.sock");
|
||||
var client = new IpcClient(socketPath);
|
||||
|
||||
client.close();
|
||||
client.close(); // Second close should be safe
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for IpcException.
|
||||
*/
|
||||
class IpcExceptionTest {
|
||||
|
||||
@Nested
|
||||
class Construction {
|
||||
|
||||
@Test
|
||||
void constructor_shouldStoreCodeAndMessage() {
|
||||
var ex = new IpcException("TEST_CODE", "Test message");
|
||||
|
||||
assertThat(ex.getCode()).isEqualTo("TEST_CODE");
|
||||
assertThat(ex.getMessage()).isEqualTo("Test message");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withCause_shouldStoreCause() {
|
||||
var cause = new RuntimeException("Underlying error");
|
||||
var ex = new IpcException("TEST_CODE", "Test message", cause);
|
||||
|
||||
assertThat(ex.getCode()).isEqualTo("TEST_CODE");
|
||||
assertThat(ex.getMessage()).isEqualTo("Test message");
|
||||
assertThat(ex.getCause()).isSameAs(cause);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullCode_shouldThrow() {
|
||||
assertThatThrownBy(() -> new IpcException(null, "message"))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullMessage_shouldNotThrow() {
|
||||
var ex = new IpcException("CODE", null);
|
||||
|
||||
assertThat(ex.getCode()).isEqualTo("CODE");
|
||||
assertThat(ex.getMessage()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ErrorCodes {
|
||||
|
||||
@Test
|
||||
void errorCodes_shouldBeAccessible() {
|
||||
assertThat(IpcErrorCode.SERVICE_NOT_RUNNING).isEqualTo("SERVICE_NOT_RUNNING");
|
||||
assertThat(IpcErrorCode.JOB_NOT_FOUND).isEqualTo("JOB_NOT_FOUND");
|
||||
assertThat(IpcErrorCode.INVALID_REQUEST).isEqualTo("INVALID_REQUEST");
|
||||
assertThat(IpcErrorCode.INTERNAL_ERROR).isEqualTo("INTERNAL_ERROR");
|
||||
assertThat(IpcErrorCode.JOB_NOT_RUNNING).isEqualTo("JOB_NOT_RUNNING");
|
||||
assertThat(IpcErrorCode.CONNECTION_FAILED).isEqualTo("CONNECTION_FAILED");
|
||||
assertThat(IpcErrorCode.TIMEOUT).isEqualTo("TIMEOUT");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Integration tests for IPC client-server communication.
|
||||
*/
|
||||
class IpcIntegrationTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private Path socketPath;
|
||||
private IpcServer server;
|
||||
private IpcClient client;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException, InterruptedException {
|
||||
socketPath = tempDir.resolve("test.sock");
|
||||
|
||||
// Create a simple echo handler
|
||||
server = new IpcServer(socketPath, (type, payload) -> {
|
||||
if ("echo".equals(type)) {
|
||||
return payload;
|
||||
}
|
||||
if ("error".equals(type)) {
|
||||
throw new IpcException("TEST_ERROR", "Test error message");
|
||||
}
|
||||
if ("slow".equals(type)) {
|
||||
// Simulate slow operation
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return Map.of("result", "slow_done");
|
||||
}
|
||||
return Map.of("type", type, "received", true);
|
||||
});
|
||||
|
||||
server.start();
|
||||
|
||||
// Give server time to start accepting connections
|
||||
Thread.sleep(100);
|
||||
|
||||
client = new IpcClient(socketPath);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
if (server != null) {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class BasicCommunication {
|
||||
|
||||
@Test
|
||||
void send_shouldReceiveResponse() throws Exception {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> response = client.send("test", null, Map.class);
|
||||
|
||||
assertThat(response).containsEntry("type", "test");
|
||||
assertThat(response).containsEntry("received", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_withPayload_shouldEchoPayload() throws Exception {
|
||||
Map<String, String> payload = Map.of("key", "value");
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> response = client.send("echo", payload, Map.class);
|
||||
|
||||
assertThat(response).containsEntry("key", "value");
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_errorRequest_shouldThrowIpcException() {
|
||||
assertThatThrownBy(() -> client.send("error", null, Map.class))
|
||||
.isInstanceOf(IpcException.class)
|
||||
.hasFieldOrPropertyWithValue("code", "TEST_ERROR")
|
||||
.hasMessage("Test error message");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConnectionState {
|
||||
|
||||
@Test
|
||||
void isServiceRunning_withRunningServer_shouldReturnTrue() {
|
||||
assertThat(client.isServiceRunning()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isServiceRunning_afterServerStop_shouldReturnFalse() {
|
||||
server.stop();
|
||||
|
||||
assertThat(client.isServiceRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void close_shouldDisconnect() throws Exception {
|
||||
// First request should work
|
||||
client.send("test", null, Map.class);
|
||||
|
||||
// Close and recreate client
|
||||
client.close();
|
||||
|
||||
// Should be able to reconnect with new client
|
||||
client = new IpcClient(socketPath);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> response = client.send("test", null, Map.class);
|
||||
assertThat(response).containsEntry("received", true);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConcurrentRequests {
|
||||
|
||||
@Test
|
||||
void multipleConcurrentRequests_shouldAllSucceed() throws Exception {
|
||||
int numRequests = 5;
|
||||
CountDownLatch latch = new CountDownLatch(numRequests);
|
||||
boolean[] results = new boolean[numRequests];
|
||||
|
||||
for (int i = 0; i < numRequests; i++) {
|
||||
final int index = i;
|
||||
new Thread(() -> {
|
||||
try (IpcClient threadClient = new IpcClient(socketPath)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> response = threadClient.send("test", null, Map.class);
|
||||
results[index] = response.containsKey("received");
|
||||
} catch (Exception e) {
|
||||
results[index] = false;
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
latch.await(10, TimeUnit.SECONDS);
|
||||
|
||||
for (boolean result : results) {
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* Tests for IpcMessage.
|
||||
*/
|
||||
class IpcMessageTest {
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Nested
|
||||
class RequestMessage {
|
||||
|
||||
@Test
|
||||
void request_shouldSetTypeAndPayload() {
|
||||
var message = IpcMessage.request("run_job", Map.of("command", "echo"));
|
||||
|
||||
assertThat(message.getType()).isEqualTo("run_job");
|
||||
assertThat(message.getPayload()).isEqualTo(Map.of("command", "echo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void request_shouldAllowNullPayload() {
|
||||
var message = IpcMessage.request("shutdown", null);
|
||||
|
||||
assertThat(message.getType()).isEqualTo("shutdown");
|
||||
assertThat(message.getPayload()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ResponseMessage {
|
||||
|
||||
@Test
|
||||
void okResponse_shouldSetStatusAndPayload() {
|
||||
var message = IpcMessage.okResponse(Map.of("job_id", "job-123"));
|
||||
|
||||
assertThat(message.getStatus()).isEqualTo("ok");
|
||||
assertThat(message.getPayload()).isEqualTo(Map.of("job_id", "job-123"));
|
||||
assertThat(message.isOk()).isTrue();
|
||||
assertThat(message.isError()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorResponse_shouldSetStatusAndError() {
|
||||
var message = IpcMessage.errorResponse("JOB_NOT_FOUND", "Job not found");
|
||||
|
||||
assertThat(message.getStatus()).isEqualTo("error");
|
||||
assertThat(message.isOk()).isFalse();
|
||||
assertThat(message.isError()).isTrue();
|
||||
assertThat(message.getErrorCode()).isEqualTo("JOB_NOT_FOUND");
|
||||
assertThat(message.getErrorMessage()).isEqualTo("Job not found");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JsonSerialization {
|
||||
|
||||
@Test
|
||||
void request_shouldSerializeToJson() throws Exception {
|
||||
var message = IpcMessage.request("run_job", Map.of("tag", "test"));
|
||||
|
||||
String json = objectMapper.writeValueAsString(message);
|
||||
|
||||
assertThat(json).contains("\"type\":\"run_job\"");
|
||||
assertThat(json).contains("\"tag\":\"test\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void okResponse_shouldSerializeToJson() throws Exception {
|
||||
var message = IpcMessage.okResponse(Map.of("job_id", "job-123"));
|
||||
|
||||
String json = objectMapper.writeValueAsString(message);
|
||||
|
||||
assertThat(json).contains("\"status\":\"ok\"");
|
||||
assertThat(json).contains("\"job_id\":\"job-123\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorResponse_shouldSerializeToJson() throws Exception {
|
||||
var message = IpcMessage.errorResponse("TEST_ERROR", "Test message");
|
||||
|
||||
String json = objectMapper.writeValueAsString(message);
|
||||
|
||||
assertThat(json).contains("\"status\":\"error\"");
|
||||
assertThat(json).contains("\"code\":\"TEST_ERROR\"");
|
||||
assertThat(json).contains("\"message\":\"Test message\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void request_shouldDeserializeFromJson() throws Exception {
|
||||
String json = "{\"type\":\"get_status\",\"payload\":{\"limit\":10}}";
|
||||
|
||||
IpcMessage message = objectMapper.readValue(json, IpcMessage.class);
|
||||
|
||||
assertThat(message.getType()).isEqualTo("get_status");
|
||||
assertThat(message.getPayload()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void okResponse_shouldDeserializeFromJson() throws Exception {
|
||||
String json = "{\"status\":\"ok\",\"payload\":{\"count\":5}}";
|
||||
|
||||
IpcMessage message = objectMapper.readValue(json, IpcMessage.class);
|
||||
|
||||
assertThat(message.getStatus()).isEqualTo("ok");
|
||||
assertThat(message.isOk()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorResponse_shouldDeserializeFromJson() throws Exception {
|
||||
String json = "{\"status\":\"error\",\"error\":{\"code\":\"TEST\",\"message\":\"Fail\"}}";
|
||||
|
||||
IpcMessage message = objectMapper.readValue(json, IpcMessage.class);
|
||||
|
||||
assertThat(message.getStatus()).isEqualTo("error");
|
||||
assertThat(message.isError()).isTrue();
|
||||
assertThat(message.getErrorCode()).isEqualTo("TEST");
|
||||
assertThat(message.getErrorMessage()).isEqualTo("Fail");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ErrorHelpers {
|
||||
|
||||
@Test
|
||||
void getErrorCode_withNoError_shouldReturnNull() {
|
||||
var message = IpcMessage.okResponse(null);
|
||||
|
||||
assertThat(message.getErrorCode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getErrorMessage_withNoError_shouldReturnNull() {
|
||||
var message = IpcMessage.okResponse(null);
|
||||
|
||||
assertThat(message.getErrorMessage()).isNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for IpcRequest types.
|
||||
*/
|
||||
class IpcRequestTest {
|
||||
|
||||
@Nested
|
||||
class RunJobRequest {
|
||||
|
||||
@Test
|
||||
void runJob_shouldStoreAllFields() {
|
||||
var request = new IpcRequest.RunJob(
|
||||
List.of("echo", "hello"),
|
||||
"test-tag",
|
||||
3,
|
||||
30
|
||||
);
|
||||
|
||||
assertThat(request.command()).containsExactly("echo", "hello");
|
||||
assertThat(request.tag()).isEqualTo("test-tag");
|
||||
assertThat(request.maxRetries()).isEqualTo(3);
|
||||
assertThat(request.retryDelaySeconds()).isEqualTo(30);
|
||||
}
|
||||
|
||||
@Test
|
||||
void runJob_shouldAllowNullTag() {
|
||||
var request = new IpcRequest.RunJob(
|
||||
List.of("echo", "hello"),
|
||||
null,
|
||||
0,
|
||||
0
|
||||
);
|
||||
|
||||
assertThat(request.tag()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetStatusRequest {
|
||||
|
||||
@Test
|
||||
void getStatus_shouldStoreAllFields() {
|
||||
var request = new IpcRequest.GetStatus("my-tag", "RUNNING", 10);
|
||||
|
||||
assertThat(request.tag()).isEqualTo("my-tag");
|
||||
assertThat(request.state()).isEqualTo("RUNNING");
|
||||
assertThat(request.limit()).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getStatus_shouldAllowNullFilters() {
|
||||
var request = new IpcRequest.GetStatus(null, null, null);
|
||||
|
||||
assertThat(request.tag()).isNull();
|
||||
assertThat(request.state()).isNull();
|
||||
assertThat(request.limit()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetJobRequest {
|
||||
|
||||
@Test
|
||||
void getJob_shouldStoreAllFields() {
|
||||
var request = new IpcRequest.GetJob("job-123", true, true);
|
||||
|
||||
assertThat(request.jobId()).isEqualTo("job-123");
|
||||
assertThat(request.includeLogs()).isTrue();
|
||||
assertThat(request.includeManifest()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class KillJobRequest {
|
||||
|
||||
@Test
|
||||
void killJob_shouldStoreAllFields() {
|
||||
var request = new IpcRequest.KillJob("job-123", true);
|
||||
|
||||
assertThat(request.jobId()).isEqualTo("job-123");
|
||||
assertThat(request.force()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CleanJobsRequest {
|
||||
|
||||
@Test
|
||||
void cleanJobs_shouldStoreAllFields() {
|
||||
var request = new IpcRequest.CleanJobs(true, "24h", true, "job-123", false);
|
||||
|
||||
assertThat(request.all()).isTrue();
|
||||
assertThat(request.olderThan()).isEqualTo("24h");
|
||||
assertThat(request.includeFailed()).isTrue();
|
||||
assertThat(request.jobId()).isEqualTo("job-123");
|
||||
assertThat(request.dryRun()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceRequests {
|
||||
|
||||
@Test
|
||||
void getServiceStatus_shouldBeInstantiable() {
|
||||
var request = new IpcRequest.GetServiceStatus();
|
||||
assertThat(request).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdown_shouldBeInstantiable() {
|
||||
var request = new IpcRequest.Shutdown();
|
||||
assertThat(request).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void reload_shouldBeInstantiable() {
|
||||
var request = new IpcRequest.Reload();
|
||||
assertThat(request).isNotNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for IpcResponse types.
|
||||
*/
|
||||
class IpcResponseTest {
|
||||
|
||||
@Nested
|
||||
class OkResponse {
|
||||
|
||||
@Test
|
||||
void ok_shouldStorePayload() {
|
||||
var response = new IpcResponse.Ok<>("test-payload");
|
||||
|
||||
assertThat(response.payload()).isEqualTo("test-payload");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ok_shouldAllowNullPayload() {
|
||||
var response = new IpcResponse.Ok<String>(null);
|
||||
|
||||
assertThat(response.payload()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void okFactory_shouldCreateOkResponse() {
|
||||
IpcResponse<String> response = IpcResponse.ok("test");
|
||||
|
||||
assertThat(response).isInstanceOf(IpcResponse.Ok.class);
|
||||
assertThat(((IpcResponse.Ok<String>) response).payload()).isEqualTo("test");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ErrorResponse {
|
||||
|
||||
@Test
|
||||
void error_shouldStoreCodeAndMessage() {
|
||||
var response = new IpcResponse.Error<String>("TEST_ERROR", "Test message");
|
||||
|
||||
assertThat(response.code()).isEqualTo("TEST_ERROR");
|
||||
assertThat(response.message()).isEqualTo("Test message");
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorFactory_shouldCreateErrorResponse() {
|
||||
IpcResponse<String> response = IpcResponse.error("TEST_ERROR", "Test message");
|
||||
|
||||
assertThat(response).isInstanceOf(IpcResponse.Error.class);
|
||||
IpcResponse.Error<String> error = (IpcResponse.Error<String>) response;
|
||||
assertThat(error.code()).isEqualTo("TEST_ERROR");
|
||||
assertThat(error.message()).isEqualTo("Test message");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Tests for IpcServer.
|
||||
*/
|
||||
class IpcServerTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private Path socketPath;
|
||||
private IpcServer server;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
socketPath = tempDir.resolve("test.sock");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (server != null) {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Construction {
|
||||
|
||||
@Test
|
||||
void constructor_shouldStoreSocketPath() {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
|
||||
assertThat(server.getSocketPath()).isEqualTo(socketPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullPath_shouldThrow() {
|
||||
assertThatThrownBy(() -> new IpcServer(null, (type, payload) -> null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullHandler_shouldThrow() {
|
||||
assertThatThrownBy(() -> new IpcServer(socketPath, null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class StartStop {
|
||||
|
||||
@Test
|
||||
void start_shouldCreateSocketFile() throws IOException {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
|
||||
server.start();
|
||||
|
||||
assertThat(Files.exists(socketPath)).isTrue();
|
||||
assertThat(server.isRunning()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_whenAlreadyRunning_shouldThrow() throws IOException {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
server.start();
|
||||
|
||||
assertThatThrownBy(() -> server.start())
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_shouldRemoveSocketFile() throws IOException {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
server.start();
|
||||
|
||||
server.stop();
|
||||
|
||||
assertThat(Files.exists(socketPath)).isFalse();
|
||||
assertThat(server.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_whenNotRunning_shouldNotThrow() {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
|
||||
// Should not throw
|
||||
server.stop();
|
||||
assertThat(server.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_multipleTimes_shouldNotThrow() throws IOException {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
server.start();
|
||||
|
||||
server.stop();
|
||||
server.stop(); // Second stop should be safe
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class IsRunning {
|
||||
|
||||
@Test
|
||||
void isRunning_beforeStart_shouldReturnFalse() {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
|
||||
assertThat(server.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isRunning_afterStart_shouldReturnTrue() throws IOException {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
server.start();
|
||||
|
||||
assertThat(server.isRunning()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isRunning_afterStop_shouldReturnFalse() throws IOException {
|
||||
server = new IpcServer(socketPath, (type, payload) -> null);
|
||||
server.start();
|
||||
server.stop();
|
||||
|
||||
assertThat(server.isRunning()).isFalse();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package com.samsonmedia.barn.jobs;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Tests for RetryCalculator.
|
||||
*/
|
||||
class RetryCalculatorTest {
|
||||
|
||||
private JobsConfig defaultConfig;
|
||||
private RetryCalculator calculator;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
defaultConfig = JobsConfig.withDefaults();
|
||||
calculator = new RetryCalculator(defaultConfig);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Constructor {
|
||||
|
||||
@Test
|
||||
void constructor_withNullConfig_shouldThrow() {
|
||||
assertThatThrownBy(() -> new RetryCalculator(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("config");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ShouldRetry {
|
||||
|
||||
@Test
|
||||
void shouldRetry_withNullJob_shouldThrow() {
|
||||
assertThatThrownBy(() -> calculator.shouldRetry(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withFailedJobUnderMaxRetries_shouldReturnTrue() {
|
||||
Job job = createJobWithExitCode(1, 0); // First attempt (0 retries)
|
||||
assertThat(calculator.shouldRetry(job)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withFailedJobAtMaxRetries_shouldReturnFalse() {
|
||||
Job job = createJobWithExitCode(1, 3); // Already retried 3 times (max)
|
||||
assertThat(calculator.shouldRetry(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withSuccessfulJob_shouldReturnFalse() {
|
||||
Job job = createJobWithExitCode(0, 0);
|
||||
assertThat(calculator.shouldRetry(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withNullExitCode_shouldReturnFalse() {
|
||||
Job job = createJobWithNullExitCode(0);
|
||||
assertThat(calculator.shouldRetry(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withMaxRetriesZero_shouldReturnFalse() {
|
||||
JobsConfig noRetryConfig = new JobsConfig(3600, 0, 30, 2.0, List.of());
|
||||
RetryCalculator noRetryCalc = new RetryCalculator(noRetryConfig);
|
||||
Job job = createJobWithExitCode(1, 0);
|
||||
assertThat(noRetryCalc.shouldRetry(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withExitCodeInRetryList_shouldReturnTrue() {
|
||||
JobsConfig config = new JobsConfig(3600, 3, 30, 2.0, List.of(1, 2, 3));
|
||||
RetryCalculator calc = new RetryCalculator(config);
|
||||
Job job = createJobWithExitCode(2, 0);
|
||||
assertThat(calc.shouldRetry(job)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withExitCodeNotInRetryList_shouldReturnFalse() {
|
||||
JobsConfig config = new JobsConfig(3600, 3, 30, 2.0, List.of(1, 2, 3));
|
||||
RetryCalculator calc = new RetryCalculator(config);
|
||||
Job job = createJobWithExitCode(127, 0); // Exit code not in list
|
||||
assertThat(calc.shouldRetry(job)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withEmptyRetryList_shouldRetryAllNonZero() {
|
||||
Job job = createJobWithExitCode(127, 0);
|
||||
assertThat(calculator.shouldRetry(job)).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ShouldRetryWithOverrides {
|
||||
|
||||
@Test
|
||||
void shouldRetry_withOverride_underMaxRetries_shouldReturnTrue() {
|
||||
Job job = createJobWithExitCode(1, 2);
|
||||
assertThat(calculator.shouldRetry(job, 5, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withOverride_atMaxRetries_shouldReturnFalse() {
|
||||
Job job = createJobWithExitCode(1, 5);
|
||||
assertThat(calculator.shouldRetry(job, 5, null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withOverride_exitCodeInList_shouldReturnTrue() {
|
||||
Job job = createJobWithExitCode(42, 0);
|
||||
assertThat(calculator.shouldRetry(job, 3, List.of(42, 43))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRetry_withOverride_exitCodeNotInList_shouldReturnFalse() {
|
||||
Job job = createJobWithExitCode(99, 0);
|
||||
assertThat(calculator.shouldRetry(job, 3, List.of(42, 43))).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CalculateDelay {
|
||||
|
||||
@Test
|
||||
void calculateDelay_firstRetry_shouldReturnBaseDelay() {
|
||||
Duration delay = calculator.calculateDelayWithoutJitter(0);
|
||||
// 30 * 2^0 = 30 seconds
|
||||
assertThat(delay).isEqualTo(Duration.ofSeconds(30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateDelay_secondRetry_shouldReturnDoubledDelay() {
|
||||
Duration delay = calculator.calculateDelayWithoutJitter(1);
|
||||
// 30 * 2^1 = 60 seconds
|
||||
assertThat(delay).isEqualTo(Duration.ofSeconds(60));
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateDelay_thirdRetry_shouldReturnQuadrupledDelay() {
|
||||
Duration delay = calculator.calculateDelayWithoutJitter(2);
|
||||
// 30 * 2^2 = 120 seconds
|
||||
assertThat(delay).isEqualTo(Duration.ofSeconds(120));
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateDelay_withNegativeRetryCount_shouldThrow() {
|
||||
assertThatThrownBy(() -> calculator.calculateDelay(-1))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("retryCount");
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateDelay_shouldIncludeJitter() {
|
||||
// Run multiple times to verify jitter is applied
|
||||
Duration delay1 = calculator.calculateDelay(0);
|
||||
Duration delay2 = calculator.calculateDelay(0);
|
||||
Duration delay3 = calculator.calculateDelay(0);
|
||||
|
||||
// All delays should be within ±20% of base (30s)
|
||||
// 30 * 0.8 = 24, 30 * 1.2 = 36
|
||||
assertThat(delay1.toSeconds()).isBetween(24L, 36L);
|
||||
assertThat(delay2.toSeconds()).isBetween(24L, 36L);
|
||||
assertThat(delay3.toSeconds()).isBetween(24L, 36L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateDelay_shouldCapAtMaxDelay() {
|
||||
// Very high retry count to test cap
|
||||
Duration delay = calculator.calculateDelayWithoutJitter(100);
|
||||
// Should be capped at 3600 seconds (1 hour)
|
||||
assertThat(delay).isLessThanOrEqualTo(Duration.ofHours(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateDelay_withCustomSettings_shouldUseProvidedValues() {
|
||||
Duration delay = calculator.calculateDelayWithoutJitter(2, 10, 3.0);
|
||||
// 10 * 3^2 = 90 seconds
|
||||
assertThat(delay).isEqualTo(Duration.ofSeconds(90));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CalculateRetryAt {
|
||||
|
||||
@Test
|
||||
void calculateRetryAt_withNullJob_shouldThrow() {
|
||||
assertThatThrownBy(() -> calculator.calculateRetryAt(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateRetryAt_shouldReturnFutureInstant() {
|
||||
Job job = createJobWithExitCode(1, 0);
|
||||
Instant before = Instant.now();
|
||||
Instant retryAt = calculator.calculateRetryAt(job);
|
||||
Instant after = Instant.now();
|
||||
|
||||
// Should be at least base delay in the future (minus jitter)
|
||||
assertThat(retryAt).isAfter(before);
|
||||
assertThat(retryAt).isBefore(after.plusSeconds(40)); // 30 + some buffer
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculateRetryAt_withHigherRetryCount_shouldReturnLaterInstant() {
|
||||
Job job0 = createJobWithExitCode(1, 0);
|
||||
Job job2 = createJobWithExitCode(1, 2);
|
||||
|
||||
Instant retryAt0 = calculator.calculateRetryAt(job0);
|
||||
Instant retryAt2 = calculator.calculateRetryAt(job2);
|
||||
|
||||
// Higher retry count should result in later retry time
|
||||
// Allow some tolerance for jitter
|
||||
assertThat(Duration.between(Instant.now(), retryAt2).toSeconds())
|
||||
.isGreaterThan(Duration.between(Instant.now(), retryAt0).toSeconds() / 2);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetMaxRetries {
|
||||
|
||||
@Test
|
||||
void getMaxRetries_shouldReturnConfiguredValue() {
|
||||
assertThat(calculator.getMaxRetries()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMaxRetries_withCustomConfig_shouldReturnConfiguredValue() {
|
||||
JobsConfig customConfig = new JobsConfig(3600, 5, 30, 2.0, List.of());
|
||||
RetryCalculator customCalc = new RetryCalculator(customConfig);
|
||||
assertThat(customCalc.getMaxRetries()).isEqualTo(5);
|
||||
}
|
||||
}
|
||||
|
||||
private Job createJobWithExitCode(int exitCode, int retryCount) {
|
||||
return new Job(
|
||||
"job-test",
|
||||
JobState.FAILED,
|
||||
List.of("echo", "test"),
|
||||
null,
|
||||
Instant.now(),
|
||||
Instant.now(),
|
||||
Instant.now(),
|
||||
exitCode,
|
||||
"error",
|
||||
12345L,
|
||||
Instant.now(),
|
||||
retryCount,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
private Job createJobWithNullExitCode(int retryCount) {
|
||||
return new Job(
|
||||
"job-test",
|
||||
JobState.RUNNING,
|
||||
List.of("echo", "test"),
|
||||
null,
|
||||
Instant.now(),
|
||||
Instant.now(),
|
||||
null,
|
||||
null, // null exit code
|
||||
null,
|
||||
12345L,
|
||||
Instant.now(),
|
||||
retryCount,
|
||||
null
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.samsonmedia.barn.logging;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Tests for JobContext.
|
||||
*/
|
||||
@SuppressWarnings("try")
|
||||
class JobContextTest {
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
MDC.clear();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ForJob {
|
||||
|
||||
@Test
|
||||
void forJob_shouldSetJobIdInMdc() {
|
||||
Job job = createJob("job-123", null);
|
||||
|
||||
try (JobContext ctx = JobContext.forJob(job)) {
|
||||
assertThat(ctx).isNotNull();
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_ID)).isEqualTo("job-123");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forJob_withTag_shouldSetJobTagInMdc() {
|
||||
Job job = createJob("job-123", "test-tag");
|
||||
|
||||
try (JobContext ctx = JobContext.forJob(job)) {
|
||||
assertThat(ctx).isNotNull();
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_TAG)).isEqualTo("test-tag");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forJob_withoutTag_shouldNotSetJobTagInMdc() {
|
||||
Job job = createJob("job-123", null);
|
||||
|
||||
try (JobContext ctx = JobContext.forJob(job)) {
|
||||
assertThat(ctx).isNotNull();
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_TAG)).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forJob_whenClosed_shouldClearMdc() {
|
||||
Job job = createJob("job-123", "test-tag");
|
||||
|
||||
try (JobContext ctx = JobContext.forJob(job)) {
|
||||
assertThat(ctx).isNotNull();
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_ID)).isNotNull();
|
||||
}
|
||||
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_ID)).isNull();
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_TAG)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void forJob_withNull_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobContext.forJob(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ForJobId {
|
||||
|
||||
@Test
|
||||
void forJobId_shouldSetJobIdInMdc() {
|
||||
try (JobContext ctx = JobContext.forJobId("job-456")) {
|
||||
assertThat(ctx).isNotNull();
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_ID)).isEqualTo("job-456");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forJobId_whenClosed_shouldClearMdc() {
|
||||
try (JobContext ctx = JobContext.forJobId("job-456")) {
|
||||
assertThat(ctx).isNotNull();
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_ID)).isNotNull();
|
||||
}
|
||||
|
||||
assertThat(MDC.get(JobContext.KEY_JOB_ID)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void forJobId_withNull_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobContext.forJobId(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("jobId");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetCurrentJobId {
|
||||
|
||||
@Test
|
||||
void getCurrentJobId_withinContext_shouldReturnJobId() {
|
||||
try (JobContext ctx = JobContext.forJobId("job-789")) {
|
||||
assertThat(ctx).isNotNull();
|
||||
assertThat(JobContext.getCurrentJobId()).isEqualTo("job-789");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCurrentJobId_outsideContext_shouldReturnNull() {
|
||||
assertThat(JobContext.getCurrentJobId()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetCurrentJobTag {
|
||||
|
||||
@Test
|
||||
void getCurrentJobTag_withinContext_shouldReturnJobTag() {
|
||||
Job job = createJob("job-123", "my-tag");
|
||||
|
||||
try (JobContext ctx = JobContext.forJob(job)) {
|
||||
assertThat(ctx).isNotNull();
|
||||
assertThat(JobContext.getCurrentJobTag()).isEqualTo("my-tag");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCurrentJobTag_outsideContext_shouldReturnNull() {
|
||||
assertThat(JobContext.getCurrentJobTag()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class NestedContexts {
|
||||
|
||||
@Test
|
||||
void nestedContexts_shouldOverwritePreviousValues() {
|
||||
Job job1 = createJob("job-1", "tag-1");
|
||||
Job job2 = createJob("job-2", "tag-2");
|
||||
|
||||
try (JobContext ctx1 = JobContext.forJob(job1)) {
|
||||
assertThat(ctx1).isNotNull();
|
||||
assertThat(JobContext.getCurrentJobId()).isEqualTo("job-1");
|
||||
|
||||
try (JobContext ctx2 = JobContext.forJob(job2)) {
|
||||
assertThat(ctx2).isNotNull();
|
||||
assertThat(JobContext.getCurrentJobId()).isEqualTo("job-2");
|
||||
}
|
||||
|
||||
// After inner context closes, values are cleared (not restored)
|
||||
assertThat(JobContext.getCurrentJobId()).isNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test helper methods
|
||||
|
||||
private Job createJob(String id, String tag) {
|
||||
return new Job(
|
||||
id,
|
||||
JobState.QUEUED,
|
||||
List.of("echo", "test"),
|
||||
tag,
|
||||
Instant.now(),
|
||||
null, // startedAt
|
||||
null, // finishedAt
|
||||
null, // exitCode
|
||||
null, // error
|
||||
null, // pid
|
||||
null, // heartbeat
|
||||
0, // retryCount
|
||||
null // retryAt
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.samsonmedia.barn.logging;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Tests for JobLogEvents.
|
||||
*/
|
||||
class JobLogEventsTest {
|
||||
|
||||
@Nested
|
||||
class JobCreated {
|
||||
|
||||
@Test
|
||||
void jobCreated_withValidJob_shouldLogWithoutError() {
|
||||
Job job = createJob("job-123", JobState.QUEUED, null);
|
||||
|
||||
assertThatCode(() -> JobLogEvents.jobCreated(job))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobCreated_withNullJob_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobLogEvents.jobCreated(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobCreated_withTaggedJob_shouldLogWithoutError() {
|
||||
Job job = createJob("job-123", JobState.QUEUED, "test-tag");
|
||||
|
||||
assertThatCode(() -> JobLogEvents.jobCreated(job))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JobStarted {
|
||||
|
||||
@Test
|
||||
void jobStarted_withValidJob_shouldLogWithoutError() {
|
||||
Job job = createRunningJob("job-123", 12345L);
|
||||
|
||||
assertThatCode(() -> JobLogEvents.jobStarted(job))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobStarted_withNullJob_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobLogEvents.jobStarted(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JobCompleted {
|
||||
|
||||
@Test
|
||||
void jobCompleted_withSuccessfulJob_shouldLogWithoutError() {
|
||||
Job job = createCompletedJob("job-123", JobState.SUCCEEDED, 0, null);
|
||||
|
||||
assertThatCode(() -> JobLogEvents.jobCompleted(job, Duration.ofSeconds(10)))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobCompleted_withFailedJob_shouldLogWithoutError() {
|
||||
Job job = createCompletedJob("job-123", JobState.FAILED, 1, "Command failed");
|
||||
|
||||
assertThatCode(() -> JobLogEvents.jobCompleted(job, Duration.ofSeconds(10)))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobCompleted_withNullJob_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobLogEvents.jobCompleted(null, Duration.ofSeconds(10)))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobCompleted_withNullDuration_shouldThrowException() {
|
||||
Job job = createCompletedJob("job-123", JobState.SUCCEEDED, 0, null);
|
||||
|
||||
assertThatThrownBy(() -> JobLogEvents.jobCompleted(job, null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("duration");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JobRetryScheduled {
|
||||
|
||||
@Test
|
||||
void jobRetryScheduled_withValidJob_shouldLogWithoutError() {
|
||||
Job job = createJob("job-123", JobState.QUEUED, null);
|
||||
Instant retryAt = Instant.now().plusSeconds(60);
|
||||
|
||||
assertThatCode(() -> JobLogEvents.jobRetryScheduled(job, retryAt))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobRetryScheduled_withNullJob_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobLogEvents.jobRetryScheduled(null, Instant.now()))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobRetryScheduled_withNullRetryAt_shouldThrowException() {
|
||||
Job job = createJob("job-123", JobState.QUEUED, null);
|
||||
|
||||
assertThatThrownBy(() -> JobLogEvents.jobRetryScheduled(job, null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("retryAt");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JobCancelled {
|
||||
|
||||
@Test
|
||||
void jobCancelled_withValidJob_shouldLogWithoutError() {
|
||||
Job job = createJob("job-123", JobState.CANCELED, null);
|
||||
|
||||
assertThatCode(() -> JobLogEvents.jobCancelled(job))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobCancelled_withNullJob_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobLogEvents.jobCancelled(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JobTimedOut {
|
||||
|
||||
@Test
|
||||
void jobTimedOut_withValidJob_shouldLogWithoutError() {
|
||||
Job job = createJob("job-123", JobState.FAILED, null);
|
||||
|
||||
assertThatCode(() -> JobLogEvents.jobTimedOut(job))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobTimedOut_withNullJob_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobLogEvents.jobTimedOut(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("job");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JobCleaned {
|
||||
|
||||
@Test
|
||||
void jobCleaned_withValidJobId_shouldLogWithoutError() {
|
||||
assertThatCode(() -> JobLogEvents.jobCleaned("job-123"))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobCleaned_withNullJobId_shouldThrowException() {
|
||||
assertThatThrownBy(() -> JobLogEvents.jobCleaned(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("jobId");
|
||||
}
|
||||
}
|
||||
|
||||
// Test helper methods
|
||||
|
||||
private Job createJob(String id, JobState state, String tag) {
|
||||
return new Job(
|
||||
id,
|
||||
state,
|
||||
List.of("echo", "test"),
|
||||
tag,
|
||||
Instant.now(),
|
||||
null, // startedAt
|
||||
null, // finishedAt
|
||||
null, // exitCode
|
||||
null, // error
|
||||
null, // pid
|
||||
null, // heartbeat
|
||||
0, // retryCount
|
||||
null // retryAt
|
||||
);
|
||||
}
|
||||
|
||||
private Job createRunningJob(String id, Long pid) {
|
||||
return new Job(
|
||||
id,
|
||||
JobState.RUNNING,
|
||||
List.of("echo", "test"),
|
||||
null, // tag
|
||||
Instant.now(),
|
||||
Instant.now(), // startedAt
|
||||
null, // finishedAt
|
||||
null, // exitCode
|
||||
null, // error
|
||||
pid,
|
||||
Instant.now(), // heartbeat
|
||||
0, // retryCount
|
||||
null // retryAt
|
||||
);
|
||||
}
|
||||
|
||||
private Job createCompletedJob(String id, JobState state, Integer exitCode, String error) {
|
||||
return new Job(
|
||||
id,
|
||||
state,
|
||||
List.of("echo", "test"),
|
||||
null, // tag
|
||||
Instant.now(),
|
||||
Instant.now(), // startedAt
|
||||
Instant.now(), // finishedAt
|
||||
exitCode,
|
||||
error,
|
||||
null, // pid
|
||||
null, // heartbeat
|
||||
0, // retryCount
|
||||
null // retryAt
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.samsonmedia.barn.logging;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.LogLevel;
|
||||
|
||||
/**
|
||||
* Tests for LoggingConfig.
|
||||
*/
|
||||
class LoggingConfigTest {
|
||||
|
||||
private LogLevel originalLevel;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
originalLevel = LoggingConfig.getLogLevel();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
LoggingConfig.setLogLevel(originalLevel);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class SetLogLevel {
|
||||
|
||||
@Test
|
||||
void setLogLevel_withDebug_shouldChangeLevel() {
|
||||
LoggingConfig.setLogLevel(LogLevel.DEBUG);
|
||||
|
||||
assertThat(LoggingConfig.getLogLevel()).isEqualTo(LogLevel.DEBUG);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setLogLevel_withInfo_shouldChangeLevel() {
|
||||
LoggingConfig.setLogLevel(LogLevel.INFO);
|
||||
|
||||
assertThat(LoggingConfig.getLogLevel()).isEqualTo(LogLevel.INFO);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setLogLevel_withWarn_shouldChangeLevel() {
|
||||
LoggingConfig.setLogLevel(LogLevel.WARN);
|
||||
|
||||
assertThat(LoggingConfig.getLogLevel()).isEqualTo(LogLevel.WARN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setLogLevel_withError_shouldChangeLevel() {
|
||||
LoggingConfig.setLogLevel(LogLevel.ERROR);
|
||||
|
||||
assertThat(LoggingConfig.getLogLevel()).isEqualTo(LogLevel.ERROR);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setLogLevel_withNull_shouldThrowException() {
|
||||
assertThatThrownBy(() -> LoggingConfig.setLogLevel(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("level");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetLogLevel {
|
||||
|
||||
@Test
|
||||
void getLogLevel_shouldReturnCurrentLevel() {
|
||||
LoggingConfig.setLogLevel(LogLevel.WARN);
|
||||
|
||||
LogLevel level = LoggingConfig.getLogLevel();
|
||||
|
||||
assertThat(level).isEqualTo(LogLevel.WARN);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class EnsureLogDirectory {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
@Test
|
||||
void ensureLogDirectory_withNonExistentDirectory_shouldCreateIt() throws IOException {
|
||||
Path logDir = tempDir.resolve("logs");
|
||||
|
||||
LoggingConfig.ensureLogDirectory(logDir);
|
||||
|
||||
assertThat(Files.exists(logDir)).isTrue();
|
||||
assertThat(Files.isDirectory(logDir)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureLogDirectory_withExistingDirectory_shouldNotFail() throws IOException {
|
||||
Path logDir = tempDir.resolve("logs");
|
||||
Files.createDirectories(logDir);
|
||||
|
||||
LoggingConfig.ensureLogDirectory(logDir);
|
||||
|
||||
assertThat(Files.exists(logDir)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureLogDirectory_withNestedPath_shouldCreateAllDirectories() throws IOException {
|
||||
Path logDir = tempDir.resolve("a/b/c/logs");
|
||||
|
||||
LoggingConfig.ensureLogDirectory(logDir);
|
||||
|
||||
assertThat(Files.exists(logDir)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureLogDirectory_withNull_shouldThrowException() {
|
||||
assertThatThrownBy(() -> LoggingConfig.ensureLogDirectory(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("logDir");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetDefaultLogDirectory {
|
||||
|
||||
@Test
|
||||
void getDefaultLogDirectory_shouldReturnPath() {
|
||||
Path logDir = LoggingConfig.getDefaultLogDirectory();
|
||||
|
||||
assertThat(logDir).isNotNull();
|
||||
assertThat(logDir.toString()).contains("barn");
|
||||
assertThat(logDir.toString()).contains("logs");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getDefaultLogDirectory_withSystemProperty_shouldUseIt() {
|
||||
String original = System.getProperty("BARN_LOG_DIR");
|
||||
try {
|
||||
System.setProperty("BARN_LOG_DIR", "/custom/log/dir");
|
||||
|
||||
Path logDir = LoggingConfig.getDefaultLogDirectory();
|
||||
|
||||
assertThat(logDir.toString()).isEqualTo("/custom/log/dir");
|
||||
} finally {
|
||||
if (original != null) {
|
||||
System.setProperty("BARN_LOG_DIR", original);
|
||||
} else {
|
||||
System.clearProperty("BARN_LOG_DIR");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package com.samsonmedia.barn.monitoring;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Tests for UsageCollector.
|
||||
*/
|
||||
class UsageCollectorTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private UsageCollector collector;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
collector = new UsageCollector();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Collect {
|
||||
|
||||
@Test
|
||||
void collect_withValidPid_shouldReturnRecord() {
|
||||
// Use current process PID
|
||||
long pid = ProcessHandle.current().pid();
|
||||
|
||||
UsageRecord record = collector.collect(pid, tempDir);
|
||||
|
||||
assertThat(record).isNotNull();
|
||||
assertThat(record.timestamp()).isNotNull();
|
||||
// CPU and memory should be non-negative (may be 0 if collection fails)
|
||||
assertThat(record.cpuPercent()).isGreaterThanOrEqualTo(0);
|
||||
assertThat(record.memoryBytes()).isGreaterThanOrEqualTo(0);
|
||||
assertThat(record.diskBytes()).isGreaterThanOrEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void collect_withNonExistentPid_shouldReturnZeroValues() {
|
||||
// Use a PID that almost certainly doesn't exist
|
||||
long invalidPid = 999999999L;
|
||||
|
||||
UsageRecord record = collector.collect(invalidPid, tempDir);
|
||||
|
||||
assertThat(record).isNotNull();
|
||||
assertThat(record.cpuPercent()).isEqualTo(0.0);
|
||||
assertThat(record.memoryBytes()).isEqualTo(0L);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CollectDiskUsage {
|
||||
|
||||
@Test
|
||||
void collectDiskUsage_withEmptyDirectory_shouldReturnZero() {
|
||||
long bytes = collector.collectDiskUsage(tempDir);
|
||||
|
||||
assertThat(bytes).isEqualTo(0L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectDiskUsage_withFiles_shouldReturnTotalSize() throws IOException {
|
||||
// Create some files
|
||||
Path file1 = tempDir.resolve("file1.txt");
|
||||
Path file2 = tempDir.resolve("file2.txt");
|
||||
Files.writeString(file1, "Hello");
|
||||
Files.writeString(file2, "World!");
|
||||
|
||||
long bytes = collector.collectDiskUsage(tempDir);
|
||||
|
||||
// Should be at least the size of our content
|
||||
assertThat(bytes).isGreaterThanOrEqualTo(11L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectDiskUsage_withNestedFiles_shouldIncludeAll() throws IOException {
|
||||
// Create nested structure
|
||||
Path subDir = tempDir.resolve("subdir");
|
||||
Files.createDirectories(subDir);
|
||||
Files.writeString(tempDir.resolve("root.txt"), "root");
|
||||
Files.writeString(subDir.resolve("nested.txt"), "nested");
|
||||
|
||||
long bytes = collector.collectDiskUsage(tempDir);
|
||||
|
||||
// Should include both files
|
||||
assertThat(bytes).isGreaterThanOrEqualTo(10L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectDiskUsage_withNonExistentPath_shouldReturnZero() {
|
||||
Path nonExistent = tempDir.resolve("does-not-exist");
|
||||
|
||||
long bytes = collector.collectDiskUsage(nonExistent);
|
||||
|
||||
assertThat(bytes).isEqualTo(0L);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CollectCpuUsage {
|
||||
|
||||
@Test
|
||||
void collectCpuUsage_withCurrentProcess_shouldReturnNonNegative() {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
|
||||
double cpu = collector.collectCpuUsage(pid);
|
||||
|
||||
assertThat(cpu).isGreaterThanOrEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectCpuUsage_withInvalidPid_shouldReturnZero() {
|
||||
double cpu = collector.collectCpuUsage(999999999L);
|
||||
|
||||
assertThat(cpu).isEqualTo(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CollectMemoryUsage {
|
||||
|
||||
@Test
|
||||
void collectMemoryUsage_withCurrentProcess_shouldReturnPositive() {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
|
||||
long memory = collector.collectMemoryUsage(pid);
|
||||
|
||||
// Current process should have some memory
|
||||
assertThat(memory).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void collectMemoryUsage_withInvalidPid_shouldReturnZero() {
|
||||
long memory = collector.collectMemoryUsage(999999999L);
|
||||
|
||||
assertThat(memory).isEqualTo(0L);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CollectGpuUsage {
|
||||
|
||||
@Test
|
||||
void collectGpuUsage_shouldReturnNullIfNoGpu() {
|
||||
// Most test environments won't have nvidia-smi
|
||||
Double gpu = collector.collectGpuUsage();
|
||||
|
||||
// Either null (no GPU) or a valid percentage
|
||||
if (gpu != null) {
|
||||
assertThat(gpu).isGreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CollectGpuMemory {
|
||||
|
||||
@Test
|
||||
void collectGpuMemory_shouldReturnNullIfNoGpu() {
|
||||
// Most test environments won't have nvidia-smi
|
||||
Long gpuMemory = collector.collectGpuMemory();
|
||||
|
||||
// Either null (no GPU) or a valid value
|
||||
if (gpuMemory != null) {
|
||||
assertThat(gpuMemory).isGreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package com.samsonmedia.barn.monitoring;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Tests for UsageLogger.
|
||||
*/
|
||||
class UsageLoggerTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
@Nested
|
||||
class Constructor {
|
||||
|
||||
@Test
|
||||
void constructor_withValidPath_shouldCreateLogger() {
|
||||
Path logFile = tempDir.resolve("usage.csv");
|
||||
|
||||
UsageLogger logger = new UsageLogger(logFile);
|
||||
|
||||
assertThat(logger.getLogFile()).isEqualTo(logFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullPath_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageLogger(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("logFile");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ForJobLogsDir {
|
||||
|
||||
@Test
|
||||
void forJobLogsDir_shouldCreateLoggerWithCorrectPath() {
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
UsageLogger logger = UsageLogger.forJobLogsDir(logsDir);
|
||||
|
||||
assertThat(logger.getLogFile()).isEqualTo(logsDir.resolve(UsageLogger.USAGE_LOG_FILENAME));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Log {
|
||||
|
||||
@Test
|
||||
void log_singleRecord_shouldWriteHeaderAndData() throws IOException {
|
||||
Path logFile = tempDir.resolve("usage.csv");
|
||||
UsageRecord record = UsageRecord.withoutGpu(Instant.parse("2024-01-15T10:30:00Z"), 50.5, 1024, 2048);
|
||||
|
||||
try (UsageLogger logger = new UsageLogger(logFile)) {
|
||||
logger.log(record);
|
||||
}
|
||||
|
||||
List<String> lines = Files.readAllLines(logFile);
|
||||
assertThat(lines).hasSize(2);
|
||||
assertThat(lines.get(0)).isEqualTo(UsageRecord.csvHeader());
|
||||
assertThat(lines.get(1)).contains("2024-01-15T10:30:00Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
void log_multipleRecords_shouldAppendData() throws IOException {
|
||||
Path logFile = tempDir.resolve("usage.csv");
|
||||
UsageRecord record1 = UsageRecord.withoutGpu(Instant.parse("2024-01-15T10:30:00Z"), 50.5, 1024, 2048);
|
||||
UsageRecord record2 = UsageRecord.withoutGpu(Instant.parse("2024-01-15T10:30:05Z"), 60.0, 2048, 4096);
|
||||
|
||||
try (UsageLogger logger = new UsageLogger(logFile)) {
|
||||
logger.log(record1);
|
||||
logger.log(record2);
|
||||
}
|
||||
|
||||
List<String> lines = Files.readAllLines(logFile);
|
||||
assertThat(lines).hasSize(3);
|
||||
assertThat(lines.get(0)).isEqualTo(UsageRecord.csvHeader());
|
||||
assertThat(lines.get(1)).contains("10:30:00");
|
||||
assertThat(lines.get(2)).contains("10:30:05");
|
||||
}
|
||||
|
||||
@Test
|
||||
void log_withNullRecord_shouldThrowException() throws IOException {
|
||||
Path logFile = tempDir.resolve("usage.csv");
|
||||
|
||||
try (UsageLogger logger = new UsageLogger(logFile)) {
|
||||
assertThatThrownBy(() -> logger.log(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("record");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void log_shouldCreateParentDirectories() throws IOException {
|
||||
Path logFile = tempDir.resolve("nested/dir/usage.csv");
|
||||
UsageRecord record = UsageRecord.withoutGpu(Instant.now(), 50.0, 1024, 2048);
|
||||
|
||||
try (UsageLogger logger = new UsageLogger(logFile)) {
|
||||
logger.log(record);
|
||||
}
|
||||
|
||||
assertThat(Files.exists(logFile)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void log_toExistingFile_shouldNotDuplicateHeader() throws IOException {
|
||||
Path logFile = tempDir.resolve("usage.csv");
|
||||
|
||||
// First logger writes header and record
|
||||
try (UsageLogger logger = new UsageLogger(logFile)) {
|
||||
logger.log(UsageRecord.withoutGpu(Instant.now(), 50.0, 1024, 2048));
|
||||
}
|
||||
|
||||
// Second logger should append without header
|
||||
try (UsageLogger logger = new UsageLogger(logFile)) {
|
||||
logger.log(UsageRecord.withoutGpu(Instant.now(), 60.0, 2048, 4096));
|
||||
}
|
||||
|
||||
List<String> lines = Files.readAllLines(logFile);
|
||||
long headerCount = lines.stream()
|
||||
.filter(line -> line.startsWith("timestamp,"))
|
||||
.count();
|
||||
assertThat(headerCount).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Flush {
|
||||
|
||||
@Test
|
||||
void flush_afterLog_shouldPersistData() throws IOException {
|
||||
Path logFile = tempDir.resolve("usage.csv");
|
||||
|
||||
try (UsageLogger logger = new UsageLogger(logFile)) {
|
||||
logger.log(UsageRecord.withoutGpu(Instant.now(), 50.0, 1024, 2048));
|
||||
logger.flush();
|
||||
|
||||
assertThat(Files.exists(logFile)).isTrue();
|
||||
assertThat(Files.size(logFile)).isGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void flush_beforeAnyLog_shouldNotFail() throws IOException {
|
||||
Path logFile = tempDir.resolve("usage.csv");
|
||||
|
||||
try (UsageLogger logger = new UsageLogger(logFile)) {
|
||||
logger.flush(); // Should not throw
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Close {
|
||||
|
||||
@Test
|
||||
void close_shouldAllowMultipleCalls() throws IOException {
|
||||
Path logFile = tempDir.resolve("usage.csv");
|
||||
UsageLogger logger = new UsageLogger(logFile);
|
||||
logger.log(UsageRecord.withoutGpu(Instant.now(), 50.0, 1024, 2048));
|
||||
|
||||
logger.close();
|
||||
logger.close(); // Should not throw
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.samsonmedia.barn.monitoring;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Tests for UsageMonitor.
|
||||
*/
|
||||
class UsageMonitorTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
@Nested
|
||||
class Constructor {
|
||||
|
||||
@Test
|
||||
void constructor_withValidArgs_shouldCreateMonitor() {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir);
|
||||
|
||||
assertThat(monitor).isNotNull();
|
||||
assertThat(monitor.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withInvalidPid_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageMonitor(0, tempDir, tempDir))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("pid");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNegativePid_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageMonitor(-1, tempDir, tempDir))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("pid");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withInvalidInterval_shouldThrowException() {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
|
||||
assertThatThrownBy(() -> new UsageMonitor(pid, tempDir, tempDir, 0))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("intervalSeconds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullWorkDir_shouldThrowException() {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
|
||||
assertThatThrownBy(() -> new UsageMonitor(pid, null, tempDir))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("workDir");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class StartAndStop {
|
||||
|
||||
@Test
|
||||
void start_shouldSetRunningToTrue() throws IOException {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
try (UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir, 1)) {
|
||||
monitor.start();
|
||||
|
||||
assertThat(monitor.isRunning()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_shouldSetRunningToFalse() throws IOException {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
try (UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir, 1)) {
|
||||
monitor.start();
|
||||
monitor.stop();
|
||||
|
||||
assertThat(monitor.isRunning()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_twice_shouldBeIdempotent() throws IOException {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
try (UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir, 1)) {
|
||||
monitor.start();
|
||||
monitor.start(); // Should not throw
|
||||
|
||||
assertThat(monitor.isRunning()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_withoutStart_shouldBeIdempotent() throws IOException {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
try (UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir)) {
|
||||
monitor.stop(); // Should not throw
|
||||
|
||||
assertThat(monitor.isRunning()).isFalse();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Logging {
|
||||
|
||||
@Test
|
||||
void monitor_shouldCreateLogFile() throws Exception {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
try (UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir, 1)) {
|
||||
monitor.start();
|
||||
// Wait for at least one collection
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
monitor.stop();
|
||||
}
|
||||
|
||||
Path logFile = logsDir.resolve(UsageLogger.USAGE_LOG_FILENAME);
|
||||
assertThat(Files.exists(logFile)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void monitor_shouldWriteRecords() throws Exception {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
try (UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir, 1)) {
|
||||
monitor.start();
|
||||
// Wait for initial collection plus one interval
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
monitor.stop();
|
||||
}
|
||||
|
||||
Path logFile = logsDir.resolve(UsageLogger.USAGE_LOG_FILENAME);
|
||||
List<String> lines = Files.readAllLines(logFile);
|
||||
// Should have header + at least 2 records (initial + one interval)
|
||||
assertThat(lines.size()).isGreaterThanOrEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLogFile_shouldReturnCorrectPath() throws IOException {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
try (UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir)) {
|
||||
Path logFile = monitor.getLogFile();
|
||||
|
||||
assertThat(logFile).isEqualTo(logsDir.resolve(UsageLogger.USAGE_LOG_FILENAME));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Close {
|
||||
|
||||
@Test
|
||||
void close_shouldStopMonitor() throws IOException {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir, 1);
|
||||
monitor.start();
|
||||
assertThat(monitor.isRunning()).isTrue();
|
||||
|
||||
monitor.close();
|
||||
|
||||
assertThat(monitor.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void close_shouldBeIdempotent() throws IOException {
|
||||
long pid = ProcessHandle.current().pid();
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
|
||||
UsageMonitor monitor = new UsageMonitor(pid, tempDir, logsDir);
|
||||
monitor.close();
|
||||
monitor.close(); // Should not throw
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.samsonmedia.barn.monitoring;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for UsageRecord.
|
||||
*/
|
||||
class UsageRecordTest {
|
||||
|
||||
@Nested
|
||||
class Constructor {
|
||||
|
||||
@Test
|
||||
void constructor_withValidValues_shouldCreateRecord() {
|
||||
Instant timestamp = Instant.now();
|
||||
|
||||
UsageRecord record = new UsageRecord(timestamp, 50.5, 1024 * 1024, 2048, 75.0, 512L);
|
||||
|
||||
assertThat(record.timestamp()).isEqualTo(timestamp);
|
||||
assertThat(record.cpuPercent()).isEqualTo(50.5);
|
||||
assertThat(record.memoryBytes()).isEqualTo(1024 * 1024);
|
||||
assertThat(record.diskBytes()).isEqualTo(2048);
|
||||
assertThat(record.gpuPercent()).isEqualTo(75.0);
|
||||
assertThat(record.gpuMemoryBytes()).isEqualTo(512L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullTimestamp_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageRecord(null, 50.0, 1024, 2048, null, null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("timestamp");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNegativeCpu_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageRecord(Instant.now(), -1.0, 1024, 2048, null, null))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("cpuPercent");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNegativeMemory_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageRecord(Instant.now(), 50.0, -1, 2048, null, null))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("memoryBytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNegativeDisk_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageRecord(Instant.now(), 50.0, 1024, -1, null, null))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("diskBytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNegativeGpuPercent_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageRecord(Instant.now(), 50.0, 1024, 2048, -1.0, null))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("gpuPercent");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNegativeGpuMemory_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new UsageRecord(Instant.now(), 50.0, 1024, 2048, 75.0, -1L))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("gpuMemoryBytes");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class WithoutGpu {
|
||||
|
||||
@Test
|
||||
void withoutGpu_shouldCreateRecordWithNullGpuValues() {
|
||||
Instant timestamp = Instant.now();
|
||||
|
||||
UsageRecord record = UsageRecord.withoutGpu(timestamp, 50.0, 1024, 2048);
|
||||
|
||||
assertThat(record.timestamp()).isEqualTo(timestamp);
|
||||
assertThat(record.cpuPercent()).isEqualTo(50.0);
|
||||
assertThat(record.memoryBytes()).isEqualTo(1024);
|
||||
assertThat(record.diskBytes()).isEqualTo(2048);
|
||||
assertThat(record.gpuPercent()).isNull();
|
||||
assertThat(record.gpuMemoryBytes()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ToCsvLine {
|
||||
|
||||
@Test
|
||||
void toCsvLine_withoutGpu_shouldFormatCorrectly() {
|
||||
Instant timestamp = Instant.parse("2024-01-15T10:30:00Z");
|
||||
UsageRecord record = UsageRecord.withoutGpu(timestamp, 50.5, 1048576, 2048);
|
||||
|
||||
String csv = record.toCsvLine();
|
||||
|
||||
assertThat(csv).isEqualTo("2024-01-15T10:30:00Z,50.50,1048576,2048,,");
|
||||
}
|
||||
|
||||
@Test
|
||||
void toCsvLine_withGpu_shouldIncludeGpuValues() {
|
||||
Instant timestamp = Instant.parse("2024-01-15T10:30:00Z");
|
||||
UsageRecord record = new UsageRecord(timestamp, 50.5, 1048576, 2048, 75.25, 524288L);
|
||||
|
||||
String csv = record.toCsvLine();
|
||||
|
||||
assertThat(csv).isEqualTo("2024-01-15T10:30:00Z,50.50,1048576,2048,75.25,524288");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CsvHeader {
|
||||
|
||||
@Test
|
||||
void csvHeader_shouldReturnCorrectFormat() {
|
||||
String header = UsageRecord.csvHeader();
|
||||
|
||||
assertThat(header).isEqualTo("timestamp,cpu_percent,memory_bytes,disk_bytes,gpu_percent,gpu_memory_bytes");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FromCsvLine {
|
||||
|
||||
@Test
|
||||
void fromCsvLine_withoutGpu_shouldParseCorrectly() {
|
||||
String csv = "2024-01-15T10:30:00Z,50.50,1048576,2048,,";
|
||||
|
||||
UsageRecord record = UsageRecord.fromCsvLine(csv);
|
||||
|
||||
assertThat(record.timestamp()).isEqualTo(Instant.parse("2024-01-15T10:30:00Z"));
|
||||
assertThat(record.cpuPercent()).isEqualTo(50.5);
|
||||
assertThat(record.memoryBytes()).isEqualTo(1048576);
|
||||
assertThat(record.diskBytes()).isEqualTo(2048);
|
||||
assertThat(record.gpuPercent()).isNull();
|
||||
assertThat(record.gpuMemoryBytes()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fromCsvLine_withGpu_shouldParseCorrectly() {
|
||||
String csv = "2024-01-15T10:30:00Z,50.50,1048576,2048,75.25,524288";
|
||||
|
||||
UsageRecord record = UsageRecord.fromCsvLine(csv);
|
||||
|
||||
assertThat(record.timestamp()).isEqualTo(Instant.parse("2024-01-15T10:30:00Z"));
|
||||
assertThat(record.cpuPercent()).isEqualTo(50.5);
|
||||
assertThat(record.memoryBytes()).isEqualTo(1048576);
|
||||
assertThat(record.diskBytes()).isEqualTo(2048);
|
||||
assertThat(record.gpuPercent()).isEqualTo(75.25);
|
||||
assertThat(record.gpuMemoryBytes()).isEqualTo(524288L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fromCsvLine_withNullLine_shouldThrowException() {
|
||||
assertThatThrownBy(() -> UsageRecord.fromCsvLine(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fromCsvLine_withInvalidLine_shouldThrowException() {
|
||||
assertThatThrownBy(() -> UsageRecord.fromCsvLine("invalid"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FormatBytes {
|
||||
|
||||
@Test
|
||||
void formatBytes_withBytes_shouldFormatAsBytes() {
|
||||
assertThat(UsageRecord.formatBytes(512)).isEqualTo("512 B");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatBytes_withKilobytes_shouldFormatAsKB() {
|
||||
assertThat(UsageRecord.formatBytes(2048)).isEqualTo("2.0 KB");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatBytes_withMegabytes_shouldFormatAsMB() {
|
||||
assertThat(UsageRecord.formatBytes(2 * 1024 * 1024)).isEqualTo("2.0 MB");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatBytes_withGigabytes_shouldFormatAsGB() {
|
||||
assertThat(UsageRecord.formatBytes(2L * 1024 * 1024 * 1024)).isEqualTo("2.00 GB");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package com.samsonmedia.barn.platform.linux;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Tests for SystemdManager.
|
||||
*/
|
||||
class SystemdManagerTest {
|
||||
|
||||
private SystemdManager manager;
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
manager = new SystemdManager();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetPaths {
|
||||
|
||||
@Test
|
||||
void getSystemServicePath_shouldReturnCorrectPath() {
|
||||
Path path = manager.getSystemServicePath();
|
||||
assertThat(path.toString()).isEqualTo("/etc/systemd/system/barn.service");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserServicePath_shouldReturnPathInUserConfig() {
|
||||
Path path = manager.getUserServicePath();
|
||||
assertThat(path.toString()).contains(".config/systemd/user");
|
||||
assertThat(path.toString()).endsWith("barn.service");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class HasSystemd {
|
||||
|
||||
@Test
|
||||
void hasSystemd_shouldReturnBoolean() {
|
||||
// This test just verifies the method doesn't throw
|
||||
boolean result = SystemdManager.hasSystemd();
|
||||
assertThat(result).isIn(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class IsUnderSystemd {
|
||||
|
||||
@Test
|
||||
void isUnderSystemd_shouldReturnBoolean() {
|
||||
// This test just verifies the method doesn't throw
|
||||
boolean result = SystemdManager.isUnderSystemd();
|
||||
assertThat(result).isIn(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GenerateUnitFile {
|
||||
|
||||
@Test
|
||||
void generateUnitFile_system_shouldContainDescription() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("Description=Barn Job Daemon");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_user_shouldContainDescription() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, true);
|
||||
assertThat(unit).contains("Description=Barn Job Daemon (User)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_shouldContainBinaryPath() {
|
||||
Path binary = Path.of("/usr/local/bin/barn");
|
||||
String unit = manager.generateUnitFile(binary, tempDir, false);
|
||||
assertThat(unit).contains("ExecStart=/usr/local/bin/barn");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_shouldContainServiceCommand() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("service start --foreground");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_shouldContainBarnDir() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("--barn-dir " + tempDir.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_system_shouldContainSecurityHardening() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("NoNewPrivileges=true");
|
||||
assertThat(unit).contains("ProtectSystem=strict");
|
||||
assertThat(unit).contains("ProtectHome=read-only");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_user_shouldNotContainSecurityHardening() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, true);
|
||||
assertThat(unit).doesNotContain("NoNewPrivileges");
|
||||
assertThat(unit).doesNotContain("ProtectSystem");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_shouldContainRestart() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("Restart=on-failure");
|
||||
assertThat(unit).contains("RestartSec=5");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_system_shouldContainJournalLogging() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("StandardOutput=journal");
|
||||
assertThat(unit).contains("StandardError=journal");
|
||||
assertThat(unit).contains("SyslogIdentifier=barn");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_system_shouldContainMultiUserTarget() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("WantedBy=multi-user.target");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_user_shouldContainDefaultTarget() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, true);
|
||||
assertThat(unit).contains("WantedBy=default.target");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_shouldContainExecStop() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("ExecStop=/usr/local/bin/barn service stop");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_withNullBinaryPath_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.generateUnitFile(null, tempDir, false))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_withNullBarnDir_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.generateUnitFile(Path.of("/usr/local/bin/barn"), null, false))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_shouldContainDocumentation() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("Documentation=https://github.com/samson-media/barn");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateUnitFile_shouldContainUnitServiceInstallSections() {
|
||||
String unit = manager.generateUnitFile(Path.of("/usr/local/bin/barn"), tempDir, false);
|
||||
assertThat(unit).contains("[Unit]");
|
||||
assertThat(unit).contains("[Service]");
|
||||
assertThat(unit).contains("[Install]");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class WriteUnitFile {
|
||||
|
||||
@Test
|
||||
void writeUnitFile_shouldCreateFile() throws IOException {
|
||||
Path unitPath = tempDir.resolve("test.service");
|
||||
String content = "[Unit]\nDescription=Test";
|
||||
|
||||
manager.writeUnitFile(unitPath, content);
|
||||
|
||||
assertThat(Files.exists(unitPath)).isTrue();
|
||||
assertThat(Files.readString(unitPath)).isEqualTo(content);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeUnitFile_shouldCreateParentDirectories() throws IOException {
|
||||
Path unitPath = tempDir.resolve("nested/dir/test.service");
|
||||
String content = "[Unit]\nDescription=Test";
|
||||
|
||||
manager.writeUnitFile(unitPath, content);
|
||||
|
||||
assertThat(Files.exists(unitPath)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeUnitFile_withNullPath_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.writeUnitFile(null, "content"))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeUnitFile_withNullContent_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.writeUnitFile(tempDir.resolve("test.service"), null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class DeleteUnitFile {
|
||||
|
||||
@Test
|
||||
void deleteUnitFile_shouldRemoveFile() throws IOException {
|
||||
Path unitPath = tempDir.resolve("test.service");
|
||||
Files.writeString(unitPath, "content");
|
||||
|
||||
boolean result = manager.deleteUnitFile(unitPath);
|
||||
|
||||
assertThat(result).isTrue();
|
||||
assertThat(Files.exists(unitPath)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteUnitFile_withNonExistentFile_shouldReturnTrue() {
|
||||
Path unitPath = tempDir.resolve("nonexistent.service");
|
||||
|
||||
boolean result = manager.deleteUnitFile(unitPath);
|
||||
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteUnitFile_withNullPath_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.deleteUnitFile(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class SystemdExceptionTest {
|
||||
|
||||
@Test
|
||||
void constructor_withMessage_shouldSetMessage() {
|
||||
var exception = new SystemdManager.SystemdException("test message");
|
||||
assertThat(exception.getMessage()).isEqualTo("test message");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withCause_shouldSetCause() {
|
||||
var cause = new RuntimeException("cause");
|
||||
var exception = new SystemdManager.SystemdException("test message", cause);
|
||||
assertThat(exception.getMessage()).isEqualTo("test message");
|
||||
assertThat(exception.getCause()).isEqualTo(cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package com.samsonmedia.barn.platform.macos;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Tests for LaunchdManager.
|
||||
*/
|
||||
class LaunchdManagerTest {
|
||||
|
||||
private LaunchdManager manager;
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
manager = new LaunchdManager();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetLabel {
|
||||
|
||||
@Test
|
||||
void getLabel_shouldReturnCorrectLabel() {
|
||||
assertThat(manager.getLabel()).isEqualTo("com.samsonmedia.barn");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetPaths {
|
||||
|
||||
@Test
|
||||
void getSystemDaemonPath_shouldReturnCorrectPath() {
|
||||
Path path = manager.getSystemDaemonPath();
|
||||
assertThat(path.toString()).isEqualTo("/Library/LaunchDaemons/com.samsonmedia.barn.plist");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserAgentPath_shouldReturnPathInUserLibrary() {
|
||||
Path path = manager.getUserAgentPath();
|
||||
assertThat(path.toString()).contains("Library/LaunchAgents");
|
||||
assertThat(path.toString()).endsWith("com.samsonmedia.barn.plist");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GeneratePlist {
|
||||
|
||||
@Test
|
||||
void generatePlist_shouldContainLabel() {
|
||||
String plist = manager.generatePlist(Path.of("/usr/local/bin/barn"), tempDir);
|
||||
assertThat(plist).contains("<string>com.samsonmedia.barn</string>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePlist_shouldContainBinaryPath() {
|
||||
Path binary = Path.of("/usr/local/bin/barn");
|
||||
String plist = manager.generatePlist(binary, tempDir);
|
||||
assertThat(plist).contains("<string>/usr/local/bin/barn</string>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePlist_shouldContainServiceCommand() {
|
||||
String plist = manager.generatePlist(Path.of("/usr/local/bin/barn"), tempDir);
|
||||
assertThat(plist).contains("<string>service</string>");
|
||||
assertThat(plist).contains("<string>start</string>");
|
||||
assertThat(plist).contains("<string>--foreground</string>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePlist_shouldContainBarnDir() {
|
||||
String plist = manager.generatePlist(Path.of("/usr/local/bin/barn"), tempDir);
|
||||
assertThat(plist).contains("<string>--barn-dir</string>");
|
||||
assertThat(plist).contains("<string>" + tempDir.toString() + "</string>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePlist_shouldContainLogPaths() {
|
||||
String plist = manager.generatePlist(Path.of("/usr/local/bin/barn"), tempDir);
|
||||
Path logsDir = tempDir.resolve("logs");
|
||||
assertThat(plist).contains(logsDir.toString() + "/barn.log");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePlist_shouldContainRunAtLoad() {
|
||||
String plist = manager.generatePlist(Path.of("/usr/local/bin/barn"), tempDir);
|
||||
assertThat(plist).contains("<key>RunAtLoad</key>");
|
||||
assertThat(plist).contains("<true/>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePlist_shouldContainKeepAlive() {
|
||||
String plist = manager.generatePlist(Path.of("/usr/local/bin/barn"), tempDir);
|
||||
assertThat(plist).contains("<key>KeepAlive</key>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePlist_shouldBeValidXml() {
|
||||
String plist = manager.generatePlist(Path.of("/usr/local/bin/barn"), tempDir);
|
||||
assertThat(plist).startsWith("<?xml version=\"1.0\"");
|
||||
assertThat(plist).contains("<!DOCTYPE plist");
|
||||
assertThat(plist).contains("<plist version=\"1.0\">");
|
||||
assertThat(plist).contains("</plist>");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class WritePlist {
|
||||
|
||||
@Test
|
||||
void writePlist_shouldCreateFile() throws IOException {
|
||||
Path plistPath = tempDir.resolve("test.plist");
|
||||
String content = "<plist>test</plist>";
|
||||
|
||||
manager.writePlist(plistPath, content);
|
||||
|
||||
assertThat(Files.exists(plistPath)).isTrue();
|
||||
assertThat(Files.readString(plistPath)).isEqualTo(content);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writePlist_shouldCreateParentDirectories() throws IOException {
|
||||
Path plistPath = tempDir.resolve("nested/dir/test.plist");
|
||||
String content = "<plist>test</plist>";
|
||||
|
||||
manager.writePlist(plistPath, content);
|
||||
|
||||
assertThat(Files.exists(plistPath)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void writePlist_withNullPath_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.writePlist(null, "content"))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writePlist_withNullContent_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.writePlist(tempDir.resolve("test.plist"), null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class DeletePlist {
|
||||
|
||||
@Test
|
||||
void deletePlist_shouldRemoveFile() throws IOException {
|
||||
Path plistPath = tempDir.resolve("test.plist");
|
||||
Files.writeString(plistPath, "content");
|
||||
|
||||
boolean result = manager.deletePlist(plistPath);
|
||||
|
||||
assertThat(result).isTrue();
|
||||
assertThat(Files.exists(plistPath)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePlist_withNonExistentFile_shouldReturnTrue() {
|
||||
Path plistPath = tempDir.resolve("nonexistent.plist");
|
||||
|
||||
boolean result = manager.deletePlist(plistPath);
|
||||
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePlist_withNullPath_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.deletePlist(null))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class IsUnderLaunchd {
|
||||
|
||||
@Test
|
||||
void isUnderLaunchd_shouldReturnBoolean() {
|
||||
// This test just verifies the method doesn't throw
|
||||
boolean result = LaunchdManager.isUnderLaunchd();
|
||||
assertThat(result).isIn(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class LaunchdExceptionTest {
|
||||
|
||||
@Test
|
||||
void constructor_withMessage_shouldSetMessage() {
|
||||
var exception = new LaunchdManager.LaunchdException("test message");
|
||||
assertThat(exception.getMessage()).isEqualTo("test message");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withCause_shouldSetCause() {
|
||||
var cause = new RuntimeException("cause");
|
||||
var exception = new LaunchdManager.LaunchdException("test message", cause);
|
||||
assertThat(exception.getMessage()).isEqualTo("test message");
|
||||
assertThat(exception.getCause()).isEqualTo(cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.samsonmedia.barn.platform.windows;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for WindowsServiceManager.
|
||||
*/
|
||||
class WindowsServiceManagerTest {
|
||||
|
||||
private WindowsServiceManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
manager = new WindowsServiceManager();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetServiceName {
|
||||
|
||||
@Test
|
||||
void getServiceName_shouldReturnBarn() {
|
||||
assertThat(manager.getServiceName()).isEqualTo("barn");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetDisplayName {
|
||||
|
||||
@Test
|
||||
void getDisplayName_shouldReturnCorrectName() {
|
||||
assertThat(manager.getDisplayName()).isEqualTo("Barn Job Daemon");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class HasWindowsServices {
|
||||
|
||||
@Test
|
||||
void hasWindowsServices_shouldReturnBoolean() {
|
||||
// This test just verifies the method doesn't throw
|
||||
boolean result = WindowsServiceManager.hasWindowsServices();
|
||||
assertThat(result).isIn(true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hasWindowsServices_shouldReturnTrueOnWindows() {
|
||||
String osName = System.getProperty("os.name", "").toLowerCase();
|
||||
boolean expected = osName.contains("windows");
|
||||
assertThat(WindowsServiceManager.hasWindowsServices()).isEqualTo(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class IsUnderServiceManager {
|
||||
|
||||
@Test
|
||||
void isUnderServiceManager_shouldReturnBoolean() {
|
||||
// This test just verifies the method doesn't throw
|
||||
boolean result = WindowsServiceManager.isUnderServiceManager();
|
||||
assertThat(result).isIn(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class IsAdmin {
|
||||
|
||||
@Test
|
||||
void isAdmin_shouldReturnBoolean() {
|
||||
// This test just verifies the method doesn't throw
|
||||
// On non-Windows, this will return false
|
||||
boolean result = WindowsServiceManager.isAdmin();
|
||||
assertThat(result).isIn(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class InstallValidation {
|
||||
|
||||
@Test
|
||||
void install_withNullBinaryPath_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.install(null, "/tmp/barn"))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("binaryPath");
|
||||
}
|
||||
|
||||
@Test
|
||||
void install_withNullBarnDir_shouldThrow() {
|
||||
assertThatThrownBy(() -> manager.install("/usr/local/bin/barn", null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("barnDir");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceState {
|
||||
|
||||
@Test
|
||||
void serviceState_shouldHaveExpectedValues() {
|
||||
assertThat(WindowsServiceManager.ServiceState.RUNNING).isNotNull();
|
||||
assertThat(WindowsServiceManager.ServiceState.STOPPED).isNotNull();
|
||||
assertThat(WindowsServiceManager.ServiceState.START_PENDING).isNotNull();
|
||||
assertThat(WindowsServiceManager.ServiceState.STOP_PENDING).isNotNull();
|
||||
assertThat(WindowsServiceManager.ServiceState.PAUSED).isNotNull();
|
||||
assertThat(WindowsServiceManager.ServiceState.UNKNOWN).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceState_shouldHaveSixValues() {
|
||||
assertThat(WindowsServiceManager.ServiceState.values()).hasSize(6);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class WindowsServiceExceptionTest {
|
||||
|
||||
@Test
|
||||
void constructor_withMessage_shouldSetMessage() {
|
||||
var exception = new WindowsServiceManager.WindowsServiceException("test message");
|
||||
assertThat(exception.getMessage()).isEqualTo("test message");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withCause_shouldSetCause() {
|
||||
var cause = new RuntimeException("cause");
|
||||
var exception = new WindowsServiceManager.WindowsServiceException("test message", cause);
|
||||
assertThat(exception.getMessage()).isEqualTo("test message");
|
||||
assertThat(exception.getCause()).isEqualTo(cause);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ServiceOperationsOnNonWindows {
|
||||
|
||||
@Test
|
||||
void isInstalled_onNonWindows_shouldReturnFalse() {
|
||||
if (!WindowsServiceManager.hasWindowsServices()) {
|
||||
// On non-Windows, this should return false (service not installed)
|
||||
assertThat(manager.isInstalled()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void isRunning_onNonWindows_shouldReturnFalse() {
|
||||
if (!WindowsServiceManager.hasWindowsServices()) {
|
||||
// On non-Windows, this should return false
|
||||
assertThat(manager.isRunning()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getState_onNonWindows_shouldReturnNull() {
|
||||
if (!WindowsServiceManager.hasWindowsServices()) {
|
||||
// On non-Windows, this should return null
|
||||
assertThat(manager.getState()).isNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package com.samsonmedia.barn.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.CleanupConfig;
|
||||
import com.samsonmedia.barn.config.Config;
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.config.LogLevel;
|
||||
import com.samsonmedia.barn.config.ServiceConfig;
|
||||
import com.samsonmedia.barn.config.StorageConfig;
|
||||
|
||||
/**
|
||||
* Tests for {@link BarnService}.
|
||||
*/
|
||||
class BarnServiceTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private Config config;
|
||||
private Path socketPath;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
socketPath = tempDir.resolve("barn.sock");
|
||||
|
||||
ServiceConfig serviceConfig = new ServiceConfig(
|
||||
LogLevel.INFO,
|
||||
2,
|
||||
5,
|
||||
socketPath,
|
||||
30
|
||||
);
|
||||
|
||||
JobsConfig jobsConfig = JobsConfig.withDefaults();
|
||||
CleanupConfig cleanupConfig = new CleanupConfig(false, 60, 24, false, 168);
|
||||
StorageConfig storageConfig = new StorageConfig(tempDir, 50, false);
|
||||
|
||||
config = new Config(serviceConfig, jobsConfig, cleanupConfig, storageConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullConfig_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new BarnService(null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("config");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withValidConfig_shouldCreateService() {
|
||||
// Act
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
// Assert
|
||||
assertThat(service).isNotNull();
|
||||
assertThat(service.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isRunning_beforeStart_shouldReturnFalse() {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
// Assert
|
||||
assertThat(service.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHealth_beforeStart_shouldReturnStopped() {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
// Act
|
||||
ServiceHealth health = service.getHealth();
|
||||
|
||||
// Assert
|
||||
assertThat(health.running()).isFalse();
|
||||
assertThat(health.activeJobs()).isZero();
|
||||
assertThat(health.queuedJobs()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRepository_shouldReturnRepository() {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
// Assert
|
||||
assertThat(service.getRepository()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getScheduler_shouldReturnScheduler() {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
// Assert
|
||||
assertThat(service.getScheduler()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getDirectories_shouldReturnDirectories() {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
// Assert
|
||||
assertThat(service.getDirectories()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_withValidConfig_shouldStartService() throws IOException {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
try {
|
||||
// Act
|
||||
service.start();
|
||||
|
||||
// Assert
|
||||
assertThat(service.isRunning()).isTrue();
|
||||
assertThat(service.getHealth().running()).isTrue();
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_whenAlreadyRunning_shouldThrowException() throws IOException {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
service.start();
|
||||
|
||||
try {
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.start())
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("already running");
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_whenRunning_shouldStopService() throws IOException {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
service.start();
|
||||
assertThat(service.isRunning()).isTrue();
|
||||
|
||||
// Act
|
||||
service.stop();
|
||||
|
||||
// Assert
|
||||
assertThat(service.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_whenNotRunning_shouldBeNoOp() {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
// Act - should not throw
|
||||
service.stop();
|
||||
|
||||
// Assert
|
||||
assertThat(service.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void reload_shouldLogMessage() throws IOException {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
service.start();
|
||||
|
||||
try {
|
||||
// Act - should not throw
|
||||
service.reload();
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_shouldInitializeDirectories() throws IOException {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
|
||||
try {
|
||||
// Act
|
||||
service.start();
|
||||
|
||||
// Assert
|
||||
assertThat(Files.exists(tempDir.resolve("jobs"))).isTrue();
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHealth_whenRunning_shouldReturnHealthStatus() throws IOException {
|
||||
// Arrange
|
||||
BarnService service = new BarnService(config);
|
||||
service.start();
|
||||
|
||||
try {
|
||||
// Act
|
||||
ServiceHealth health = service.getHealth();
|
||||
|
||||
// Assert
|
||||
assertThat(health.running()).isTrue();
|
||||
assertThat(health.startedAt()).isNotNull();
|
||||
assertThat(health.uptimeSeconds()).isGreaterThanOrEqualTo(0);
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package com.samsonmedia.barn.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.samsonmedia.barn.config.CleanupConfig;
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
/**
|
||||
* Tests for {@link CleanupScheduler}.
|
||||
*/
|
||||
class CleanupSchedulerTest {
|
||||
|
||||
@TempDir
|
||||
private Path tempDir;
|
||||
|
||||
private JobRepository repository;
|
||||
private BarnDirectories dirs;
|
||||
private CleanupConfig config;
|
||||
private JobsConfig jobsConfig;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
dirs = new BarnDirectories(tempDir);
|
||||
dirs.initialize();
|
||||
repository = new JobRepository(dirs);
|
||||
// maxAgeHours=24, cleanupIntervalMinutes=60, keepFailedJobsHours=168
|
||||
config = new CleanupConfig(true, 24, 60, true, 168);
|
||||
jobsConfig = JobsConfig.withDefaults();
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullRepository_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new CleanupScheduler(null, config))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("repository");
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructor_withNullConfig_shouldThrowException() {
|
||||
assertThatThrownBy(() -> new CleanupScheduler(repository, null))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageContaining("config");
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_whenNotRunning_shouldStartSuccessfully() {
|
||||
// Arrange
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act
|
||||
scheduler.start();
|
||||
|
||||
// Assert
|
||||
assertThat(scheduler.isRunning()).isTrue();
|
||||
|
||||
// Cleanup
|
||||
scheduler.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void start_whenAlreadyRunning_shouldThrowException() {
|
||||
// Arrange
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
scheduler.start();
|
||||
|
||||
try {
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> scheduler.start())
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("already running");
|
||||
} finally {
|
||||
scheduler.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_whenRunning_shouldStopSuccessfully() {
|
||||
// Arrange
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
scheduler.start();
|
||||
|
||||
// Act
|
||||
scheduler.stop();
|
||||
|
||||
// Assert
|
||||
assertThat(scheduler.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stop_whenNotRunning_shouldBeNoOp() {
|
||||
// Arrange
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act - should not throw
|
||||
scheduler.stop();
|
||||
|
||||
// Assert
|
||||
assertThat(scheduler.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isRunning_whenNotStarted_shouldReturnFalse() {
|
||||
// Arrange
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Assert
|
||||
assertThat(scheduler.isRunning()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runNow_withNoJobs_shouldNotFail() throws IOException {
|
||||
// Arrange
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act - should not throw
|
||||
scheduler.runNow();
|
||||
|
||||
// Assert
|
||||
assertThat(repository.findAll()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runNow_withRunningJob_shouldNotDeleteIt() throws IOException {
|
||||
// Arrange
|
||||
Job job = repository.create(List.of("sleep", "100"), "test", jobsConfig);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act
|
||||
scheduler.runNow();
|
||||
|
||||
// Assert - job should still exist
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runNow_withQueuedJob_shouldNotDeleteIt() throws IOException {
|
||||
// Arrange
|
||||
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||
// Job is QUEUED by default after creation
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act
|
||||
scheduler.runNow();
|
||||
|
||||
// Assert - job should still exist
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runNow_withOldSucceededJob_shouldDeleteIt() throws IOException {
|
||||
// Arrange
|
||||
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
|
||||
// Manually make the job old by modifying its state file
|
||||
makeJobOld(job.id(), 30); // 30 hours old, config maxAgeHours is 24
|
||||
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act
|
||||
scheduler.runNow();
|
||||
|
||||
// Assert - job should be deleted
|
||||
assertThat(repository.findById(job.id())).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runNow_withRecentSucceededJob_shouldNotDeleteIt() throws IOException {
|
||||
// Arrange
|
||||
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markCompleted(job.id(), 0, null);
|
||||
// Job just finished, so it's recent
|
||||
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act
|
||||
scheduler.runNow();
|
||||
|
||||
// Assert - job should still exist
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runNow_withOldFailedJob_shouldRespectKeepFailedJobsHours() throws IOException {
|
||||
// Arrange
|
||||
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markFailed(job.id(), "error", "test error");
|
||||
|
||||
// Make job older than keepFailedJobsHours (168 hours = 7 days)
|
||||
makeJobOld(job.id(), 200); // 200 hours old
|
||||
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act
|
||||
scheduler.runNow();
|
||||
|
||||
// Assert - job should be deleted
|
||||
assertThat(repository.findById(job.id())).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runNow_withRecentFailedJob_shouldNotDeleteIt() throws IOException {
|
||||
// Arrange
|
||||
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||
repository.markStarted(job.id(), 12345L);
|
||||
repository.markFailed(job.id(), "error", "test error");
|
||||
|
||||
// Make job 48 hours old - still within keepFailedJobsHours (168)
|
||||
makeJobOld(job.id(), 48);
|
||||
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act
|
||||
scheduler.runNow();
|
||||
|
||||
// Assert - job should still exist (within 168 hours)
|
||||
assertThat(repository.findById(job.id())).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runNow_withMultipleJobs_shouldDeleteOnlyOldCompletedJobs() throws IOException {
|
||||
// Arrange
|
||||
Job oldSucceeded = repository.create(List.of("echo", "1"), "old-succeeded", jobsConfig);
|
||||
repository.markStarted(oldSucceeded.id(), 1L);
|
||||
repository.markCompleted(oldSucceeded.id(), 0, null);
|
||||
makeJobOld(oldSucceeded.id(), 30);
|
||||
|
||||
Job recentSucceeded = repository.create(List.of("echo", "2"), "recent-succeeded", jobsConfig);
|
||||
repository.markStarted(recentSucceeded.id(), 2L);
|
||||
repository.markCompleted(recentSucceeded.id(), 0, null);
|
||||
|
||||
Job running = repository.create(List.of("echo", "3"), "running", jobsConfig);
|
||||
repository.markStarted(running.id(), 3L);
|
||||
|
||||
CleanupScheduler scheduler = new CleanupScheduler(repository, config);
|
||||
|
||||
// Act
|
||||
scheduler.runNow();
|
||||
|
||||
// Assert
|
||||
assertThat(repository.findById(oldSucceeded.id())).isEmpty();
|
||||
assertThat(repository.findById(recentSucceeded.id())).isPresent();
|
||||
assertThat(repository.findById(running.id())).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a job appear old by modifying its finishedAt timestamp file.
|
||||
*/
|
||||
private void makeJobOld(String jobId, int hoursOld) throws IOException {
|
||||
Path finishedAtFile = dirs.getJobDir(jobId).resolve("finished_at");
|
||||
Instant oldTime = Instant.now().minusSeconds(hoursOld * 3600L);
|
||||
Files.writeString(finishedAtFile, oldTime.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.samsonmedia.barn.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for {@link ServiceHealth}.
|
||||
*/
|
||||
class ServiceHealthTest {
|
||||
|
||||
@Test
|
||||
void running_shouldCreateHealthRecordWithCorrectValues() {
|
||||
// Arrange
|
||||
Instant startedAt = Instant.now().minusSeconds(3600);
|
||||
|
||||
// Act
|
||||
ServiceHealth health = ServiceHealth.running(5, 10, startedAt);
|
||||
|
||||
// Assert
|
||||
assertThat(health.running()).isTrue();
|
||||
assertThat(health.activeJobs()).isEqualTo(5);
|
||||
assertThat(health.queuedJobs()).isEqualTo(10);
|
||||
assertThat(health.startedAt()).isEqualTo(startedAt);
|
||||
assertThat(health.uptimeSeconds()).isGreaterThanOrEqualTo(3600);
|
||||
}
|
||||
|
||||
@Test
|
||||
void running_withZeroJobs_shouldCreateHealthRecord() {
|
||||
// Arrange
|
||||
Instant startedAt = Instant.now();
|
||||
|
||||
// Act
|
||||
ServiceHealth health = ServiceHealth.running(0, 0, startedAt);
|
||||
|
||||
// Assert
|
||||
assertThat(health.running()).isTrue();
|
||||
assertThat(health.activeJobs()).isZero();
|
||||
assertThat(health.queuedJobs()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopped_shouldCreateHealthRecordWithDefaults() {
|
||||
// Act
|
||||
ServiceHealth health = ServiceHealth.stopped();
|
||||
|
||||
// Assert
|
||||
assertThat(health.running()).isFalse();
|
||||
assertThat(health.activeJobs()).isZero();
|
||||
assertThat(health.queuedJobs()).isZero();
|
||||
assertThat(health.startedAt()).isNull();
|
||||
assertThat(health.uptimeSeconds()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uptimeSeconds_shouldBeCalculatedFromStartTime() {
|
||||
// Arrange
|
||||
Instant twoMinutesAgo = Instant.now().minusSeconds(120);
|
||||
|
||||
// Act
|
||||
ServiceHealth health = ServiceHealth.running(1, 2, twoMinutesAgo);
|
||||
|
||||
// Assert
|
||||
// Allow for slight timing differences
|
||||
assertThat(health.uptimeSeconds()).isBetween(119L, 122L);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.samsonmedia.barn.util;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for DurationParser.
|
||||
*/
|
||||
class DurationParserTest {
|
||||
|
||||
@Nested
|
||||
class ValidDurations {
|
||||
|
||||
@Test
|
||||
void parse_minutes_shouldReturnCorrectDuration() {
|
||||
Duration result = DurationParser.parse("30m");
|
||||
|
||||
assertThat(result).isEqualTo(Duration.ofMinutes(30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_hours_shouldReturnCorrectDuration() {
|
||||
Duration result = DurationParser.parse("24h");
|
||||
|
||||
assertThat(result).isEqualTo(Duration.ofHours(24));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_days_shouldReturnCorrectDuration() {
|
||||
Duration result = DurationParser.parse("7d");
|
||||
|
||||
assertThat(result).isEqualTo(Duration.ofDays(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_weeks_shouldReturnCorrectDuration() {
|
||||
Duration result = DurationParser.parse("2w");
|
||||
|
||||
assertThat(result).isEqualTo(Duration.ofDays(14));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_singleDigit_shouldWork() {
|
||||
Duration result = DurationParser.parse("1h");
|
||||
|
||||
assertThat(result).isEqualTo(Duration.ofHours(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_multiDigit_shouldWork() {
|
||||
Duration result = DurationParser.parse("168h");
|
||||
|
||||
assertThat(result).isEqualTo(Duration.ofHours(168));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_withWhitespace_shouldTrim() {
|
||||
Duration result = DurationParser.parse(" 24h ");
|
||||
|
||||
assertThat(result).isEqualTo(Duration.ofHours(24));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_uppercaseUnit_shouldWork() {
|
||||
Duration result = DurationParser.parse("24H");
|
||||
|
||||
assertThat(result).isEqualTo(Duration.ofHours(24));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class InvalidDurations {
|
||||
|
||||
@Test
|
||||
void parse_null_shouldThrow() {
|
||||
assertThatThrownBy(() -> DurationParser.parse(null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_empty_shouldThrow() {
|
||||
assertThatThrownBy(() -> DurationParser.parse(""))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_blank_shouldThrow() {
|
||||
assertThatThrownBy(() -> DurationParser.parse(" "))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_invalidUnit_shouldThrow() {
|
||||
assertThatThrownBy(() -> DurationParser.parse("24x"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Invalid");
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_noNumber_shouldThrow() {
|
||||
assertThatThrownBy(() -> DurationParser.parse("h"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_noUnit_shouldThrow() {
|
||||
assertThatThrownBy(() -> DurationParser.parse("24"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_negativeNumber_shouldThrow() {
|
||||
assertThatThrownBy(() -> DurationParser.parse("-24h"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_zeroValue_shouldThrow() {
|
||||
assertThatThrownBy(() -> DurationParser.parse("0h"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user