feat(config): implement configuration system with TOML parser (#2)

- Add LogLevel enum with case-insensitive parsing
- Add OperatingSystem enum with platform detection
- Create config records: Config, ServiceConfig, JobsConfig, CleanupConfig, StorageConfig
- Add ConfigDefaults for platform-specific paths (Unix/Windows)
- Implement TomlParser supporting sections, strings, integers, floats, booleans, arrays
- Create ConfigLoader with:
  - File loading from search paths (system/user config)
  - Environment variable overrides (BARN_SECTION_KEY pattern)
  - Validation of all config values
  - Defaults for missing values
- Add comprehensive tests (93 new tests, 119 total)

Closes #2

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-21 12:59:15 +00:00
1 parent 05937b1f7e
commit 79f89be47c
16 files changed
+2120

No files matched your search

@@ -0,0 +1,80 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Tests for ConfigDefaults.
*/
class ConfigDefaultsTest {
@Test
void getDefaultBaseDir_shouldReturnNonNullPath() {
Path baseDir = ConfigDefaults.getDefaultBaseDir();
assertThat(baseDir).isNotNull();
assertThat(baseDir.toString()).isNotEmpty();
}
@Test
void getDefaultIpcSocket_shouldReturnNonNullPath() {
Path socket = ConfigDefaults.getDefaultIpcSocket();
assertThat(socket).isNotNull();
assertThat(socket.toString()).isNotEmpty();
}
@Test
void getSystemConfigPath_shouldReturnNonNullPath() {
Path configPath = ConfigDefaults.getSystemConfigPath();
assertThat(configPath).isNotNull();
assertThat(configPath.toString()).contains("barn.conf");
}
@Test
void getUserConfigPath_shouldReturnNonNullPath() {
Path configPath = ConfigDefaults.getUserConfigPath();
assertThat(configPath).isNotNull();
assertThat(configPath.toString()).contains("barn.conf");
}
@Test
void getConfigSearchPaths_shouldReturnNonEmptyList() {
List<Path> paths = ConfigDefaults.getConfigSearchPaths();
assertThat(paths).isNotEmpty();
assertThat(paths).hasSize(2);
}
@Test
void getConfigSearchPaths_shouldIncludeSystemAndUserPaths() {
List<Path> paths = ConfigDefaults.getConfigSearchPaths();
assertThat(paths).contains(ConfigDefaults.getSystemConfigPath());
assertThat(paths).contains(ConfigDefaults.getUserConfigPath());
}
@Test
void getDefaultBaseDir_onUnix_shouldBeInTmp() {
if (OperatingSystem.current().isUnixLike()) {
Path baseDir = ConfigDefaults.getDefaultBaseDir();
assertThat(baseDir.toString()).startsWith("/tmp");
}
}
@Test
void getDefaultIpcSocket_onUnix_shouldBeUnixSocket() {
if (OperatingSystem.current().isUnixLike()) {
Path socket = ConfigDefaults.getDefaultIpcSocket();
assertThat(socket.toString()).contains("barn.sock");
}
}
@Test
void getDefaultIpcSocket_onWindows_shouldBeNamedPipe() {
if (OperatingSystem.current() == OperatingSystem.WINDOWS) {
Path socket = ConfigDefaults.getDefaultIpcSocket();
assertThat(socket.toString()).contains("pipe");
}
}
}
@@ -0,0 +1,321 @@
package com.samsonmedia.barn.config;
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.HashMap;
import java.util.Map;
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 ConfigLoader.
*/
class ConfigLoaderTest {
@TempDir
private Path tempDir;
@Nested
class DefaultLoading {
@Test
void load_withNoConfigFiles_shouldReturnDefaults() {
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.load();
assertThat(config.service().logLevel()).isEqualTo(LogLevel.INFO);
assertThat(config.service().maxConcurrentJobs()).isEqualTo(4);
assertThat(config.jobs().maxRetries()).isEqualTo(3);
assertThat(config.cleanup().enabled()).isTrue();
}
}
@Nested
class FileLoading {
@Test
void loadFromFile_withValidFile_shouldParseValues() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
log_level = "debug"
max_concurrent_jobs = 8
[jobs]
max_retries = 5
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.service().logLevel()).isEqualTo(LogLevel.DEBUG);
assertThat(config.service().maxConcurrentJobs()).isEqualTo(8);
assertThat(config.jobs().maxRetries()).isEqualTo(5);
}
@Test
void loadFromFile_withPartialConfig_shouldUseDefaultsForMissing() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
log_level = "warn"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.service().logLevel()).isEqualTo(LogLevel.WARN);
assertThat(config.service().maxConcurrentJobs()).isEqualTo(4); // Default
assertThat(config.jobs().maxRetries()).isEqualTo(3); // Default
}
@Test
void loadFromFile_withNonexistentFile_shouldThrowException() {
Path configFile = tempDir.resolve("nonexistent.conf");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(ConfigLoader.ConfigException.class)
.hasMessageContaining("Failed to read");
}
@Test
void loadFromFile_withInvalidToml_shouldThrowException() throws IOException {
Path configFile = tempDir.resolve("invalid.conf");
Files.writeString(configFile, """
not valid toml
""");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(ConfigLoader.ConfigException.class)
.hasMessageContaining("Failed to parse");
}
}
@Nested
class EnvironmentOverrides {
@Test
void load_withEnvOverride_shouldOverrideFileValue() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
log_level = "info"
""");
Map<String, String> env = new HashMap<>();
env.put("BARN_SERVICE_LOG_LEVEL", "debug");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load(Optional.of(configFile));
assertThat(config.service().logLevel()).isEqualTo(LogLevel.DEBUG);
}
@Test
void load_withEnvOverrideInteger_shouldParseCorrectly() {
Map<String, String> env = new HashMap<>();
env.put("BARN_SERVICE_MAX_CONCURRENT_JOBS", "16");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
assertThat(config.service().maxConcurrentJobs()).isEqualTo(16);
}
@Test
void load_withEnvOverrideBoolean_shouldParseCorrectly() {
Map<String, String> env = new HashMap<>();
env.put("BARN_CLEANUP_ENABLED", "false");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
assertThat(config.cleanup().enabled()).isFalse();
}
@Test
void load_withEnvOverrideFloat_shouldParseCorrectly() {
Map<String, String> env = new HashMap<>();
env.put("BARN_JOBS_RETRY_BACKOFF_MULTIPLIER", "3.5");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
assertThat(config.jobs().retryBackoffMultiplier()).isEqualTo(3.5);
}
@Test
void load_withMultipleEnvOverrides_shouldApplyAll() {
Map<String, String> env = new HashMap<>();
env.put("BARN_SERVICE_LOG_LEVEL", "error");
env.put("BARN_JOBS_MAX_RETRIES", "10");
env.put("BARN_CLEANUP_MAX_AGE_HOURS", "24");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
assertThat(config.service().logLevel()).isEqualTo(LogLevel.ERROR);
assertThat(config.jobs().maxRetries()).isEqualTo(10);
assertThat(config.cleanup().maxAgeHours()).isEqualTo(24);
}
@Test
void load_withNonBarnEnvVars_shouldIgnore() {
Map<String, String> env = new HashMap<>();
env.put("PATH", "/usr/bin");
env.put("HOME", "/home/user");
env.put("SOME_OTHER_VAR", "value");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
// Should load defaults without error
assertThat(config.service().logLevel()).isEqualTo(LogLevel.INFO);
}
}
@Nested
class PathConfiguration {
@Test
void load_withIpcSocketPath_shouldParsePath() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
ipc_socket = "/custom/path/barn.sock"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.service().ipcSocket()).isEqualTo(Path.of("/custom/path/barn.sock"));
}
@Test
void load_withBaseDir_shouldParsePath() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[storage]
base_dir = "/data/barn"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.storage().baseDir()).isEqualTo(Path.of("/data/barn"));
}
}
@Nested
class ValidationErrors {
@Test
void load_withInvalidLogLevel_shouldThrowException() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
log_level = "invalid"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(ConfigLoader.ConfigException.class)
.hasMessageContaining("log_level");
}
@Test
void load_withInvalidMaxConcurrentJobs_shouldThrowException() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
max_concurrent_jobs = 0
""");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxConcurrentJobs");
}
@Test
void load_withInvalidBackoffMultiplier_shouldThrowException() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[jobs]
retry_backoff_multiplier = 0.5
""");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryBackoffMultiplier");
}
}
@Nested
class ExplicitPathLoading {
@Test
void load_withExplicitPath_shouldUseExplicitPath() throws IOException {
Path configFile = tempDir.resolve("custom.conf");
Files.writeString(configFile, """
[service]
log_level = "error"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.load(Optional.of(configFile));
assertThat(config.service().logLevel()).isEqualTo(LogLevel.ERROR);
}
@Test
void load_withEmptyExplicitPath_shouldUseDefaults() {
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.load(Optional.empty());
assertThat(config.service().logLevel()).isEqualTo(LogLevel.INFO);
}
}
@Nested
class RetryOnExitCodes {
@Test
void load_withRetryOnExitCodes_shouldParseList() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[jobs]
retry_on_exit_codes = [1, 2, 255]
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.jobs().retryOnExitCodes()).containsExactly(1, 2, 255);
}
@Test
void load_withEmptyRetryOnExitCodes_shouldReturnEmptyList() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[jobs]
retry_on_exit_codes = []
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.jobs().retryOnExitCodes()).isEmpty();
}
}
}
@@ -0,0 +1,266 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/**
* Tests for configuration record classes.
*/
class ConfigTest {
@Nested
class ServiceConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
ServiceConfig config = new ServiceConfig(
LogLevel.DEBUG, 8, 10, Path.of("/tmp/barn.sock"), 60);
assertThat(config.logLevel()).isEqualTo(LogLevel.DEBUG);
assertThat(config.maxConcurrentJobs()).isEqualTo(8);
assertThat(config.heartbeatIntervalSeconds()).isEqualTo(10);
assertThat(config.ipcSocket()).isEqualTo(Path.of("/tmp/barn.sock"));
assertThat(config.staleHeartbeatThresholdSeconds()).isEqualTo(60);
}
@Test
void constructor_withNullLogLevel_shouldThrowException() {
assertThatThrownBy(() -> new ServiceConfig(
null, 4, 5, Path.of("/tmp/barn.sock"), 30))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("logLevel");
}
@Test
void constructor_withNullIpcSocket_shouldThrowException() {
assertThatThrownBy(() -> new ServiceConfig(
LogLevel.INFO, 4, 5, null, 30))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("ipcSocket");
}
@Test
void constructor_withZeroMaxConcurrentJobs_shouldThrowException() {
assertThatThrownBy(() -> new ServiceConfig(
LogLevel.INFO, 0, 5, Path.of("/tmp/barn.sock"), 30))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxConcurrentJobs");
}
@Test
void constructor_withZeroHeartbeatInterval_shouldThrowException() {
assertThatThrownBy(() -> new ServiceConfig(
LogLevel.INFO, 4, 0, Path.of("/tmp/barn.sock"), 30))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("heartbeatIntervalSeconds");
}
@Test
void withDefaults_shouldReturnConfigWithDefaultValues() {
ServiceConfig config = ServiceConfig.withDefaults();
assertThat(config.logLevel()).isEqualTo(LogLevel.INFO);
assertThat(config.maxConcurrentJobs()).isEqualTo(4);
assertThat(config.heartbeatIntervalSeconds()).isEqualTo(5);
assertThat(config.staleHeartbeatThresholdSeconds()).isEqualTo(30);
assertThat(config.ipcSocket()).isNotNull();
}
}
@Nested
class JobsConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
JobsConfig config = new JobsConfig(7200, 5, 60, 3.0, List.of(1, 2, 3));
assertThat(config.defaultTimeoutSeconds()).isEqualTo(7200);
assertThat(config.maxRetries()).isEqualTo(5);
assertThat(config.retryDelaySeconds()).isEqualTo(60);
assertThat(config.retryBackoffMultiplier()).isEqualTo(3.0);
assertThat(config.retryOnExitCodes()).containsExactly(1, 2, 3);
}
@Test
void constructor_withNullRetryOnExitCodes_shouldThrowException() {
assertThatThrownBy(() -> new JobsConfig(3600, 3, 30, 2.0, null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("retryOnExitCodes");
}
@Test
void constructor_withZeroTimeout_shouldThrowException() {
assertThatThrownBy(() -> new JobsConfig(0, 3, 30, 2.0, List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("defaultTimeoutSeconds");
}
@Test
void constructor_withNegativeMaxRetries_shouldThrowException() {
assertThatThrownBy(() -> new JobsConfig(3600, -1, 30, 2.0, List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxRetries");
}
@Test
void constructor_withBackoffMultiplierLessThanOne_shouldThrowException() {
assertThatThrownBy(() -> new JobsConfig(3600, 3, 30, 0.5, List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryBackoffMultiplier");
}
@Test
void constructor_shouldCreateDefensiveCopyOfExitCodes() {
List<Integer> codes = new java.util.ArrayList<>();
codes.add(1);
JobsConfig config = new JobsConfig(3600, 3, 30, 2.0, codes);
codes.add(2);
assertThat(config.retryOnExitCodes()).containsExactly(1);
}
@Test
void withDefaults_shouldReturnConfigWithDefaultValues() {
JobsConfig config = JobsConfig.withDefaults();
assertThat(config.defaultTimeoutSeconds()).isEqualTo(3600);
assertThat(config.maxRetries()).isEqualTo(3);
assertThat(config.retryDelaySeconds()).isEqualTo(30);
assertThat(config.retryBackoffMultiplier()).isEqualTo(2.0);
assertThat(config.retryOnExitCodes()).isEmpty();
}
}
@Nested
class CleanupConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
CleanupConfig config = new CleanupConfig(false, 24, 30, false, 48);
assertThat(config.enabled()).isFalse();
assertThat(config.maxAgeHours()).isEqualTo(24);
assertThat(config.cleanupIntervalMinutes()).isEqualTo(30);
assertThat(config.keepFailedJobs()).isFalse();
assertThat(config.keepFailedJobsHours()).isEqualTo(48);
}
@Test
void constructor_withZeroMaxAgeHours_shouldThrowException() {
assertThatThrownBy(() -> new CleanupConfig(true, 0, 60, true, 168))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxAgeHours");
}
@Test
void constructor_withZeroCleanupInterval_shouldThrowException() {
assertThatThrownBy(() -> new CleanupConfig(true, 72, 0, true, 168))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cleanupIntervalMinutes");
}
@Test
void withDefaults_shouldReturnConfigWithDefaultValues() {
CleanupConfig config = CleanupConfig.withDefaults();
assertThat(config.enabled()).isTrue();
assertThat(config.maxAgeHours()).isEqualTo(72);
assertThat(config.cleanupIntervalMinutes()).isEqualTo(60);
assertThat(config.keepFailedJobs()).isTrue();
assertThat(config.keepFailedJobsHours()).isEqualTo(168);
}
}
@Nested
class StorageConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
StorageConfig config = new StorageConfig(Path.of("/data/barn"), 100, true);
assertThat(config.baseDir()).isEqualTo(Path.of("/data/barn"));
assertThat(config.maxDiskUsageGb()).isEqualTo(100);
assertThat(config.preserveWorkDir()).isTrue();
}
@Test
void constructor_withNullBaseDir_shouldThrowException() {
assertThatThrownBy(() -> new StorageConfig(null, 50, false))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("baseDir");
}
@Test
void constructor_withZeroMaxDiskUsage_shouldThrowException() {
assertThatThrownBy(() -> new StorageConfig(Path.of("/tmp/barn"), 0, false))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxDiskUsageGb");
}
@Test
void withDefaults_shouldReturnConfigWithDefaultValues() {
StorageConfig config = StorageConfig.withDefaults();
assertThat(config.baseDir()).isNotNull();
assertThat(config.maxDiskUsageGb()).isEqualTo(50);
assertThat(config.preserveWorkDir()).isFalse();
}
}
@Nested
class TopLevelConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
Config config = new Config(
ServiceConfig.withDefaults(),
JobsConfig.withDefaults(),
CleanupConfig.withDefaults(),
StorageConfig.withDefaults()
);
assertThat(config.service()).isNotNull();
assertThat(config.jobs()).isNotNull();
assertThat(config.cleanup()).isNotNull();
assertThat(config.storage()).isNotNull();
}
@Test
void constructor_withNullService_shouldThrowException() {
assertThatThrownBy(() -> new Config(
null,
JobsConfig.withDefaults(),
CleanupConfig.withDefaults(),
StorageConfig.withDefaults()))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("service");
}
@Test
void constructor_withNullJobs_shouldThrowException() {
assertThatThrownBy(() -> new Config(
ServiceConfig.withDefaults(),
null,
CleanupConfig.withDefaults(),
StorageConfig.withDefaults()))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("jobs");
}
@Test
void withDefaults_shouldReturnFullyPopulatedConfig() {
Config config = Config.withDefaults();
assertThat(config.service()).isNotNull();
assertThat(config.jobs()).isNotNull();
assertThat(config.cleanup()).isNotNull();
assertThat(config.storage()).isNotNull();
}
}
}
@@ -0,0 +1,62 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
/**
* Tests for LogLevel enum.
*/
class LogLevelTest {
@Test
void fromString_withValidLowercase_shouldReturnLogLevel() {
assertThat(LogLevel.fromString("debug")).isEqualTo(LogLevel.DEBUG);
assertThat(LogLevel.fromString("info")).isEqualTo(LogLevel.INFO);
assertThat(LogLevel.fromString("warn")).isEqualTo(LogLevel.WARN);
assertThat(LogLevel.fromString("error")).isEqualTo(LogLevel.ERROR);
}
@Test
void fromString_withValidUppercase_shouldReturnLogLevel() {
assertThat(LogLevel.fromString("DEBUG")).isEqualTo(LogLevel.DEBUG);
assertThat(LogLevel.fromString("INFO")).isEqualTo(LogLevel.INFO);
assertThat(LogLevel.fromString("WARN")).isEqualTo(LogLevel.WARN);
assertThat(LogLevel.fromString("ERROR")).isEqualTo(LogLevel.ERROR);
}
@Test
void fromString_withMixedCase_shouldReturnLogLevel() {
assertThat(LogLevel.fromString("Debug")).isEqualTo(LogLevel.DEBUG);
assertThat(LogLevel.fromString("Info")).isEqualTo(LogLevel.INFO);
}
@Test
void fromString_withWhitespace_shouldTrimAndParse() {
assertThat(LogLevel.fromString(" info ")).isEqualTo(LogLevel.INFO);
}
@Test
void fromString_withNull_shouldThrowException() {
assertThatThrownBy(() -> LogLevel.fromString(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cannot be null or blank");
}
@Test
void fromString_withBlank_shouldThrowException() {
assertThatThrownBy(() -> LogLevel.fromString(" "))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cannot be null or blank");
}
@Test
void fromString_withInvalidValue_shouldThrowException() {
assertThatThrownBy(() -> LogLevel.fromString("invalid"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Invalid log level")
.hasMessageContaining("invalid")
.hasMessageContaining("debug, info, warn, error");
}
}
@@ -0,0 +1,40 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* Tests for OperatingSystem enum.
*/
class OperatingSystemTest {
@Test
void current_shouldReturnValidOperatingSystem() {
OperatingSystem os = OperatingSystem.current();
assertThat(os).isNotNull();
assertThat(os).isIn(OperatingSystem.LINUX, OperatingSystem.MACOS, OperatingSystem.WINDOWS);
}
@Test
void current_shouldReturnConsistentValue() {
OperatingSystem first = OperatingSystem.current();
OperatingSystem second = OperatingSystem.current();
assertThat(first).isSameAs(second);
}
@Test
void isUnixLike_forLinux_shouldReturnTrue() {
assertThat(OperatingSystem.LINUX.isUnixLike()).isTrue();
}
@Test
void isUnixLike_forMacOS_shouldReturnTrue() {
assertThat(OperatingSystem.MACOS.isUnixLike()).isTrue();
}
@Test
void isUnixLike_forWindows_shouldReturnFalse() {
assertThat(OperatingSystem.WINDOWS.isUnixLike()).isFalse();
}
}
@@ -0,0 +1,338 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/**
* Tests for TomlParser.
*/
class TomlParserTest {
@Nested
class BasicParsing {
@Test
void parse_withEmptyContent_shouldReturnEmptyMap() {
Map<String, Map<String, Object>> result = TomlParser.parse("");
assertThat(result).isEmpty();
}
@Test
void parse_withOnlyComments_shouldReturnEmptyMap() {
String content = """
# This is a comment
# Another comment
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).isEmpty();
}
@Test
void parse_withOnlyWhitespace_shouldReturnEmptyMap() {
String content = " \n \n ";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).isEmpty();
}
}
@Nested
class SectionParsing {
@Test
void parse_withSingleSection_shouldCreateSection() {
String content = "[service]";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).containsKey("service");
}
@Test
void parse_withMultipleSections_shouldCreateAllSections() {
String content = """
[service]
[jobs]
[cleanup]
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).containsKeys("service", "jobs", "cleanup");
}
}
@Nested
class StringValueParsing {
@Test
void parse_withStringValue_shouldParseCorrectly() {
String content = """
[service]
log_level = "debug"
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("log_level")).isEqualTo("debug");
}
@Test
void parse_withStringContainingSpaces_shouldPreserveSpaces() {
String content = """
[service]
name = "my service name"
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("name")).isEqualTo("my service name");
}
@Test
void parse_withEscapedQuotes_shouldUnescape() {
String content = """
[service]
value = "say \\"hello\\""
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("value")).isEqualTo("say \"hello\"");
}
@Test
void parse_withEscapedNewline_shouldUnescape() {
String content = """
[service]
value = "line1\\nline2"
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("value")).isEqualTo("line1\nline2");
}
}
@Nested
class IntegerValueParsing {
@Test
void parse_withPositiveInteger_shouldParseCorrectly() {
String content = """
[jobs]
max_retries = 5
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("max_retries")).isEqualTo(5);
}
@Test
void parse_withNegativeInteger_shouldParseCorrectly() {
String content = """
[jobs]
value = -10
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("value")).isEqualTo(-10);
}
@Test
void parse_withZero_shouldParseCorrectly() {
String content = """
[jobs]
value = 0
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("value")).isEqualTo(0);
}
}
@Nested
class FloatValueParsing {
@Test
void parse_withPositiveFloat_shouldParseCorrectly() {
String content = """
[jobs]
multiplier = 2.5
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("multiplier")).isEqualTo(2.5);
}
@Test
void parse_withNegativeFloat_shouldParseCorrectly() {
String content = """
[jobs]
value = -1.5
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("value")).isEqualTo(-1.5);
}
}
@Nested
class BooleanValueParsing {
@Test
void parse_withTrueValue_shouldParseCorrectly() {
String content = """
[cleanup]
enabled = true
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("cleanup").get("enabled")).isEqualTo(true);
}
@Test
void parse_withFalseValue_shouldParseCorrectly() {
String content = """
[cleanup]
enabled = false
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("cleanup").get("enabled")).isEqualTo(false);
}
@Test
void parse_withUppercaseBoolean_shouldParseCorrectly() {
String content = """
[cleanup]
enabled = TRUE
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("cleanup").get("enabled")).isEqualTo(true);
}
}
@Nested
class ArrayValueParsing {
@Test
void parse_withEmptyArray_shouldReturnEmptyList() {
String content = """
[jobs]
exit_codes = []
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("exit_codes")).isEqualTo(List.of());
}
@Test
void parse_withIntegerArray_shouldParseCorrectly() {
String content = """
[jobs]
exit_codes = [1, 2, 3]
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("exit_codes")).isEqualTo(List.of(1, 2, 3));
}
@Test
void parse_withStringArray_shouldParseCorrectly() {
String content = """
[jobs]
tags = ["a", "b", "c"]
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("tags")).isEqualTo(List.of("a", "b", "c"));
}
}
@Nested
class CommentHandling {
@Test
void parse_withInlineComment_shouldIgnoreComment() {
String content = """
[service]
max_jobs = 4 # This is a comment
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("max_jobs")).isEqualTo(4);
}
@Test
void parse_withCommentInString_shouldPreserveHash() {
String content = """
[service]
name = "job#123"
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("name")).isEqualTo("job#123");
}
}
@Nested
class ComplexScenarios {
@Test
void parse_withFullConfigFile_shouldParseAllSections() {
String content = """
[service]
log_level = "info"
max_concurrent_jobs = 4
heartbeat_interval_seconds = 5
[jobs]
default_timeout_seconds = 3600
max_retries = 3
retry_delay_seconds = 30
retry_backoff_multiplier = 2.0
retry_on_exit_codes = [1, 2]
[cleanup]
enabled = true
max_age_hours = 72
keep_failed_jobs = true
[storage]
base_dir = "/tmp/barn"
max_disk_usage_gb = 50
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).containsKeys("service", "jobs", "cleanup", "storage");
assertThat(result.get("service").get("log_level")).isEqualTo("info");
assertThat(result.get("jobs").get("retry_on_exit_codes")).isEqualTo(List.of(1, 2));
assertThat(result.get("cleanup").get("enabled")).isEqualTo(true);
assertThat(result.get("storage").get("base_dir")).isEqualTo("/tmp/barn");
}
}
@Nested
class ErrorHandling {
@Test
void parse_withNullContent_shouldThrowException() {
assertThatThrownBy(() -> TomlParser.parse((String) null))
.isInstanceOf(NullPointerException.class);
}
@Test
void parse_withKeyValueOutsideSection_shouldThrowException() {
String content = """
name = "value"
""";
assertThatThrownBy(() -> TomlParser.parse(content))
.isInstanceOf(TomlParser.TomlParseException.class)
.hasMessageContaining("outside of section");
}
@Test
void parse_withInvalidSyntax_shouldThrowException() {
String content = """
[service]
this is not valid
""";
assertThatThrownBy(() -> TomlParser.parse(content))
.isInstanceOf(TomlParser.TomlParseException.class)
.hasMessageContaining("Invalid syntax");
}
@Test
void parse_withUnterminatedString_shouldThrowException() {
String content = """
[service]
value = "unterminated
""";
assertThatThrownBy(() -> TomlParser.parse(content))
.isInstanceOf(TomlParser.TomlParseException.class);
}
}
}