DiscoveryApiFixture.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Microsoft.AspNetCore.Mvc.Testing;
  2. using Microsoft.Extensions.Configuration;
  3. using RackPeek.Domain.Api;
  4. using RackPeek.Domain.Discovery;
  5. using RackPeek.Web;
  6. namespace Tests.Discovery;
  7. /// <summary>
  8. /// A real RackPeek server backed by a temporary config file, driven through the
  9. /// same <see cref="DiscoveryPublisher" /> the CLI uses. These are the end-to-end
  10. /// tests: discovery YAML goes over HTTP into the inventory API and the assertions
  11. /// are made against what actually lands on disk.
  12. /// </summary>
  13. public sealed class DiscoveryApiFixture : IDisposable {
  14. private const string _apiKey = "discovery-test-key";
  15. private readonly WebApplicationFactory<Program> _factory;
  16. private readonly string _tempDir;
  17. /// <param name="initialConfig">
  18. /// Contents to seed config.yaml with before the server first reads it — the way
  19. /// to test how the server behaves against a file it did not write itself.
  20. /// </param>
  21. public DiscoveryApiFixture(string? initialConfig = null) {
  22. _tempDir = Path.Combine(Path.GetTempPath(), "rackpeek-discovery-tests", Guid.NewGuid().ToString());
  23. Directory.CreateDirectory(_tempDir);
  24. if (initialConfig != null)
  25. File.WriteAllText(Path.Combine(_tempDir, "config.yaml"), initialConfig);
  26. _factory = new WebApplicationFactory<Program>()
  27. .WithWebHostBuilder(builder => {
  28. builder.UseSetting("RPK_YAML_DIR", _tempDir);
  29. builder.ConfigureAppConfiguration((_, config) =>
  30. config.AddInMemoryCollection(new Dictionary<string, string?> {
  31. ["RPK_YAML_DIR"] = _tempDir,
  32. ["RPK_API_KEY"] = _apiKey
  33. }));
  34. });
  35. }
  36. public string StoredYaml => File.ReadAllText(Path.Combine(_tempDir, "config.yaml"));
  37. public void Dispose() {
  38. try {
  39. _factory.Dispose();
  40. if (Directory.Exists(_tempDir))
  41. Directory.Delete(_tempDir, true);
  42. }
  43. catch {
  44. // Cleanup only; a leftover temp directory must never fail a test run.
  45. }
  46. }
  47. public async Task<ImportYamlResponse> PublishAsync(string yaml, bool dryRun = false) {
  48. HttpClient client = _factory.CreateClient();
  49. using var publisher = new DiscoveryPublisher(
  50. client.BaseAddress!.ToString(),
  51. _apiKey,
  52. client);
  53. return await publisher.PublishAsync(yaml, dryRun);
  54. }
  55. }