using Microsoft.Extensions.Configuration;
namespace CaddyManager.Tests.TestUtilities;
///
/// Helper class for common test utilities
///
public static class TestHelper
{
///
/// Creates a temporary directory for testing file operations
///
/// Path to the temporary directory
public static string CreateTempDirectory()
{
var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
return tempPath;
}
///
/// Creates a temporary file with the specified content
///
/// Content to write to the file
/// Optional file name, generates random if not provided
/// Path to the created file
public static string CreateTempFile(string content, string? fileName = null)
{
var tempDir = CreateTempDirectory();
var filePath = Path.Combine(tempDir, fileName ?? $"{Guid.NewGuid()}.txt");
File.WriteAllText(filePath, content);
return filePath;
}
///
/// Creates an IConfiguration instance from a dictionary
///
/// Configuration key-value pairs
/// IConfiguration instance
public static IConfiguration CreateConfiguration(Dictionary configValues)
{
return new ConfigurationBuilder()
.AddInMemoryCollection(configValues)
.Build();
}
///
/// Creates an IConfiguration instance from JSON content
///
/// JSON configuration content
/// IConfiguration instance
public static IConfiguration CreateConfigurationFromJson(string jsonContent)
{
var tempFile = CreateTempFile(jsonContent, "appsettings.json");
return new ConfigurationBuilder()
.AddJsonFile(tempFile)
.Build();
}
///
/// Sample Caddyfile content for testing
///
public static class SampleCaddyfiles
{
public const string SimpleReverseProxy = @"
example.com {
reverse_proxy localhost:8080
}";
public const string MultipleHosts = @"
example.com, www.example.com {
reverse_proxy localhost:8080
}";
public const string ComplexConfiguration = @"
api.example.com {
route /v1/* {
reverse_proxy localhost:3000
}
route /v2/* {
reverse_proxy localhost:3001
}
}
app.example.com {
reverse_proxy localhost:8080
encode gzip
}";
public const string WithMultiplePorts = @"
example.com {
reverse_proxy localhost:8080
}
api.example.com {
reverse_proxy localhost:3000
}";
}
///
/// Cleans up a directory and all its contents
///
/// Path to the directory to clean up
public static void CleanupDirectory(string directoryPath)
{
if (Directory.Exists(directoryPath))
{
try
{
Directory.Delete(directoryPath, true);
}
catch
{
// Ignore cleanup errors in tests
}
}
}
}