InfrastructureFixture.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using DotNet.Testcontainers.Builders;
  2. using DotNet.Testcontainers.Containers;
  3. using DotNet.Testcontainers.Images;
  4. namespace Renci.SshNet.IntegrationTests.TestsFixtures
  5. {
  6. public sealed class InfrastructureFixture : IDisposable
  7. {
  8. private InfrastructureFixture()
  9. {
  10. }
  11. private static readonly Lazy<InfrastructureFixture> InstanceLazy = new Lazy<InfrastructureFixture>(() => new InfrastructureFixture());
  12. public static InfrastructureFixture Instance
  13. {
  14. get
  15. {
  16. return InstanceLazy.Value;
  17. }
  18. }
  19. private IContainer _sshServer;
  20. private IFutureDockerImage _sshServerImage;
  21. public string SshServerHostName { get; set; }
  22. public ushort SshServerPort { get; set; }
  23. public SshUser AdminUser = new SshUser("sshnetadm", "ssh4ever");
  24. public SshUser User = new SshUser("sshnet", "ssh4ever");
  25. // To get the sshd logs (also uncomment WithOutputConsumer below)
  26. private readonly Stream _fsOut = Stream.Null; // File.Create("fsout.txt");
  27. private readonly Stream _fsErr = Stream.Null; // File.Create("fserr.txt");
  28. public async Task InitializeAsync()
  29. {
  30. _sshServerImage = new ImageFromDockerfileBuilder()
  31. .WithName("renci-ssh-tests-server-image")
  32. .WithDockerfileDirectory(CommonDirectoryPath.GetSolutionDirectory(), Path.Combine("test", "Renci.SshNet.IntegrationTests"))
  33. .WithDockerfile("Dockerfile.TestServer")
  34. .WithDeleteIfExists(true)
  35. .Build();
  36. await _sshServerImage.CreateAsync();
  37. _sshServer = new ContainerBuilder()
  38. .WithHostname("renci-ssh-tests-server")
  39. .WithImage(_sshServerImage)
  40. .WithPortBinding(22, true)
  41. //.WithOutputConsumer(Consume.RedirectStdoutAndStderrToStream(_fsOut, _fsErr))
  42. .Build();
  43. await _sshServer.StartAsync();
  44. SshServerPort = _sshServer.GetMappedPublicPort(22);
  45. SshServerHostName = _sshServer.Hostname;
  46. // Socket fails on Linux, reporting inability early. This is the Linux behavior by design.
  47. // https://github.com/dotnet/runtime/issues/47484#issuecomment-769239699
  48. // At this point we have to wait until the ssh server in the container is available
  49. if (Environment.OSVersion.Platform == PlatformID.Unix)
  50. {
  51. await Task.Delay(300);
  52. }
  53. }
  54. public async Task DisposeAsync()
  55. {
  56. if (_sshServer != null)
  57. {
  58. await _sshServer.DisposeAsync();
  59. }
  60. if (_sshServerImage != null)
  61. {
  62. await _sshServerImage.DisposeAsync();
  63. }
  64. _fsOut.Dispose();
  65. _fsErr.Dispose();
  66. }
  67. public void Dispose()
  68. {
  69. }
  70. }
  71. }