ApiTestBase.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using Microsoft.AspNetCore.Mvc.Testing;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using Microsoft.Extensions.Logging;
  5. using RackPeek.Web;
  6. using Shared.Rcl;
  7. using Xunit.Abstractions;
  8. namespace Tests.Api;
  9. public abstract class ApiTestBase : IDisposable {
  10. private readonly string _tempDir;
  11. protected readonly WebApplicationFactory<Program> Factory;
  12. protected readonly ITestOutputHelper Output;
  13. protected ApiTestBase(ITestOutputHelper output) {
  14. Output = output;
  15. _tempDir = Path.Combine(
  16. Path.GetTempPath(),
  17. "rackpeek-tests",
  18. Guid.NewGuid().ToString());
  19. Directory.CreateDirectory(_tempDir);
  20. Factory = new WebApplicationFactory<Program>()
  21. .WithWebHostBuilder(builder => {
  22. builder.UseSetting("RPK_YAML_DIR", _tempDir);
  23. builder.ConfigureAppConfiguration((context, configBuilder) => {
  24. var baseConfig = new Dictionary<string, string?> {
  25. ["RPK_API_KEY"] = "test-key-123"
  26. };
  27. ConfigureTestConfiguration(baseConfig);
  28. configBuilder.AddInMemoryCollection(baseConfig);
  29. IConfigurationRoot configuration = configBuilder.Build();
  30. CliBootstrap.RegisterInternals(
  31. new ServiceCollection(),
  32. configuration,
  33. _tempDir,
  34. "test.yaml")
  35. .GetAwaiter()
  36. .GetResult();
  37. });
  38. builder.ConfigureServices(services => {
  39. services.AddLogging(logging => {
  40. logging.ClearProviders();
  41. logging.AddProvider(
  42. new XUnitLoggerProvider(Output));
  43. });
  44. ConfigureTestServices(services);
  45. });
  46. });
  47. }
  48. public void Dispose() {
  49. try {
  50. Factory.Dispose();
  51. if (Directory.Exists(_tempDir))
  52. Directory.Delete(_tempDir, true);
  53. }
  54. catch {
  55. // ignore cleanup issues
  56. }
  57. }
  58. /// <summary>
  59. /// Override to modify configuration per test class
  60. /// </summary>
  61. protected virtual void ConfigureTestConfiguration(
  62. IDictionary<string, string?> config) {
  63. }
  64. /// <summary>
  65. /// Override to modify services per test class
  66. /// </summary>
  67. protected virtual void ConfigureTestServices(
  68. IServiceCollection services) {
  69. }
  70. protected HttpClient CreateClient(bool withApiKey = false) {
  71. HttpClient client = Factory.CreateClient();
  72. if (withApiKey) client.DefaultRequestHeaders.Add("X-Api-Key", "test-key-123");
  73. return client;
  74. }
  75. }