ApiTestBase.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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.ConfigureAppConfiguration((context, configBuilder) => {
  23. var baseConfig = new Dictionary<string, string?> {
  24. ["RPK_API_KEY"] = "test-key-123"
  25. };
  26. ConfigureTestConfiguration(baseConfig);
  27. configBuilder.AddInMemoryCollection(baseConfig);
  28. IConfigurationRoot configuration = configBuilder.Build();
  29. CliBootstrap.RegisterInternals(
  30. new ServiceCollection(),
  31. configuration,
  32. _tempDir,
  33. "test.yaml")
  34. .GetAwaiter()
  35. .GetResult();
  36. });
  37. builder.ConfigureServices(services => {
  38. services.AddLogging(logging => {
  39. logging.ClearProviders();
  40. logging.AddProvider(
  41. new XUnitLoggerProvider(Output));
  42. });
  43. ConfigureTestServices(services);
  44. });
  45. });
  46. }
  47. public void Dispose() {
  48. try {
  49. Factory.Dispose();
  50. if (Directory.Exists(_tempDir))
  51. Directory.Delete(_tempDir, true);
  52. }
  53. catch {
  54. // ignore cleanup issues
  55. }
  56. }
  57. /// <summary>
  58. /// Override to modify configuration per test class
  59. /// </summary>
  60. protected virtual void ConfigureTestConfiguration(
  61. IDictionary<string, string?> config) {
  62. }
  63. /// <summary>
  64. /// Override to modify services per test class
  65. /// </summary>
  66. protected virtual void ConfigureTestServices(
  67. IServiceCollection services) {
  68. }
  69. protected HttpClient CreateClient(bool withApiKey = false) {
  70. HttpClient client = Factory.CreateClient();
  71. if (withApiKey) client.DefaultRequestHeaders.Add("X-Api-Key", "test-key-123");
  72. return client;
  73. }
  74. }