PlaywrightFixture.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Text;
  2. using DotNet.Testcontainers.Builders;
  3. using DotNet.Testcontainers.Containers;
  4. using Microsoft.Playwright;
  5. namespace Tests.E2e.Infra;
  6. public class PlaywrightFixture : IAsyncLifetime {
  7. // Change this if needed
  8. private const string _dockerImage = "rackpeek:ci";
  9. private IContainer _container = default!;
  10. private IPlaywright _playwright = default!;
  11. public IBrowser Browser { get; private set; } = default!;
  12. public string BaseUrl { get; private set; } = default!;
  13. public async Task InitializeAsync() {
  14. _container = new ContainerBuilder(_dockerImage)
  15. .WithPortBinding(8080, true) // random host port
  16. .WithWaitStrategy(
  17. Wait.ForUnixContainer()
  18. .UntilHttpRequestIsSucceeded(r => r
  19. .ForPort(8080)
  20. .ForPath("/")))
  21. .Build();
  22. await _container.StartAsync();
  23. var mappedPort = _container.GetMappedPublicPort(8080);
  24. BaseUrl = $"http://127.0.0.1:{mappedPort}";
  25. Console.WriteLine($"RackPeek running at: {BaseUrl}");
  26. _playwright = await Playwright.CreateAsync();
  27. Browser = await _playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {
  28. Headless = true,
  29. SlowMo = 400,
  30. //Headless = false,
  31. //SlowMo = 1500,
  32. Args = new[]
  33. {
  34. "--disable-dev-shm-usage",
  35. "--no-sandbox"
  36. }
  37. });
  38. Assertions.SetDefaultExpectTimeout(15000);
  39. }
  40. /// <summary>
  41. /// Replaces the container's config.yaml wholesale. Used to stage a damaged
  42. /// config, which cannot be produced through the UI (the editor validates
  43. /// before saving) but is exactly what an interrupted write leaves behind.
  44. /// </summary>
  45. public async Task WriteConfigAsync(string contents) {
  46. await _container.CopyAsync(
  47. Encoding.UTF8.GetBytes(contents),
  48. "/app/config/config.yaml");
  49. }
  50. public async Task<string> ReadConfigAsync() {
  51. var bytes = await _container.ReadFileAsync("/app/config/config.yaml");
  52. return Encoding.UTF8.GetString(bytes);
  53. }
  54. public async Task<(string Stdout, string Stderr)> ReadLogsAsync() => await _container.GetLogsAsync();
  55. public async Task DisposeAsync() {
  56. if (Browser != null)
  57. await Browser.DisposeAsync();
  58. _playwright?.Dispose();
  59. if (_container != null)
  60. await _container.DisposeAsync();
  61. }
  62. }