How to use GetContainerGateway method of DotNet.Testcontainers.Containers.TestcontainersContainer class

Best Testcontainers-dotnet code snippet using DotNet.Testcontainers.Containers.TestcontainersContainer.GetContainerGateway

TestcontainersContainer.cs

Source:TestcontainersContainer.cs Github

copy

Full Screen

...83 case "tcp":84 return dockerHostUri.Host;85 case "npipe":86 case "unix":87 return this.GetContainerGateway();88 default:89 throw new InvalidOperationException($"Docker endpoint {dockerHostUri} is not supported.");90 }91 }92 }93 /// <inheritdoc />94 public IDockerImage Image95 {96 get97 {98 return this.configuration.Image;99 }100 }101 /// <inheritdoc />102 public TestcontainersStates State103 {104 get105 {106 if (this.container.State == null)107 {108 return TestcontainersStates.Undefined;109 }110 try111 {112 return (TestcontainersStates)Enum.Parse(typeof(TestcontainersStates), this.container.State.Status, true);113 }114 catch (Exception)115 {116 return TestcontainersStates.Undefined;117 }118 }119 }120 /// <summary>121 /// Gets the logger.122 /// </summary>123 [NotNull]124 internal ILogger Logger { get; }125 /// <inheritdoc />126 public ushort GetMappedPublicPort(int privatePort)127 {128 return this.GetMappedPublicPort(Convert.ToString(privatePort, CultureInfo.InvariantCulture));129 }130 /// <inheritdoc />131 public ushort GetMappedPublicPort(string privatePort)132 {133 this.ThrowIfContainerHasNotBeenCreated();134 if (this.container.NetworkSettings.Ports.TryGetValue($"{privatePort}/tcp", out var portMap) && ushort.TryParse(portMap.First().HostPort, out var publicPort))135 {136 return publicPort;137 }138 else139 {140 throw new InvalidOperationException($"Exposed port {privatePort} is not mapped.");141 }142 }143 /// <inheritdoc />144 public Task<long> GetExitCode(CancellationToken ct = default)145 {146 return this.client.GetContainerExitCode(this.Id, ct);147 }148 /// <inheritdoc />149 public Task<(string Stdout, string Stderr)> GetLogs(DateTime since = default, DateTime until = default, CancellationToken ct = default)150 {151 return this.client.GetContainerLogs(this.Id, since, until, ct);152 }153 /// <inheritdoc />154 public virtual async Task StartAsync(CancellationToken ct = default)155 {156 await this.semaphoreSlim.WaitAsync(ct)157 .ConfigureAwait(false);158 try159 {160 this.container = await this.Create(ct)161 .ConfigureAwait(false);162 this.container = await this.Start(this.Id, ct)163 .ConfigureAwait(false);164 }165 finally166 {167 this.semaphoreSlim.Release();168 }169 }170 /// <inheritdoc />171 public virtual async Task StopAsync(CancellationToken ct = default)172 {173 await this.semaphoreSlim.WaitAsync(ct)174 .ConfigureAwait(false);175 try176 {177 this.container = await this.Stop(this.Id, ct)178 .ConfigureAwait(false);179 }180 catch (DockerContainerNotFoundException)181 {182 this.container = new ContainerInspectResponse();183 }184 finally185 {186 this.semaphoreSlim.Release();187 }188 }189 /// <inheritdoc />190 public Task CopyFileAsync(string filePath, byte[] fileContent, int accessMode = 384, int userId = 0, int groupId = 0, CancellationToken ct = default)191 {192 return this.client.CopyFileAsync(this.Id, filePath, fileContent, accessMode, userId, groupId, ct);193 }194 /// <inheritdoc />195 public Task<byte[]> ReadFileAsync(string filePath, CancellationToken ct = default)196 {197 return this.client.ReadFileAsync(this.Id, filePath, ct);198 }199 /// <inheritdoc />200 public Task<ExecResult> ExecAsync(IList<string> command, CancellationToken ct = default)201 {202 return this.client.ExecAsync(this.Id, command, ct);203 }204 /// <summary>205 /// Removes the Testcontainers.206 /// </summary>207 /// <param name="ct">Cancellation token.</param>208 /// <returns>A task that represents the asynchronous clean up operation of a Testcontainers.</returns>209 public async Task CleanUpAsync(CancellationToken ct = default)210 {211 await this.semaphoreSlim.WaitAsync(ct)212 .ConfigureAwait(false);213 try214 {215 this.container = await this.CleanUp(this.Id, ct)216 .ConfigureAwait(false);217 }218 finally219 {220 this.semaphoreSlim.Release();221 }222 }223 /// <inheritdoc />224 public async ValueTask DisposeAsync()225 {226 await this.DisposeAsyncCore()227 .ConfigureAwait(false);228 GC.SuppressFinalize(this);229 }230 /// <summary>231 /// Releases any resources associated with the instance of <see cref="TestcontainersContainer" />.232 /// </summary>233 /// <returns>Value task that completes when any resources associated with the instance have been released.</returns>234 protected virtual async ValueTask DisposeAsyncCore()235 {236 if (1.Equals(Interlocked.CompareExchange(ref this.disposed, 1, 0)))237 {238 return;239 }240 if (!ContainerHasBeenCreatedStates.HasFlag(this.State))241 {242 return;243 }244 // If someone calls `DisposeAsync`, we can immediately remove the container. We do not need to wait for the Resource Reaper.245 if (Guid.Empty.Equals(this.configuration.SessionId))246 {247 await this.StopAsync()248 .ConfigureAwait(false);249 }250 else251 {252 await this.CleanUpAsync()253 .ConfigureAwait(false);254 }255 this.semaphoreSlim.Dispose();256 }257 private async Task<ContainerInspectResponse> Create(CancellationToken ct = default)258 {259 if (ContainerHasBeenCreatedStates.HasFlag(this.State))260 {261 return this.container;262 }263 var id = await this.client.RunAsync(this.configuration, ct)264 .ConfigureAwait(false);265 return await this.client.InspectContainer(id, ct)266 .ConfigureAwait(false);267 }268 private async Task<ContainerInspectResponse> Start(string id, CancellationToken ct = default)269 {270 await this.client.AttachAsync(id, this.configuration.OutputConsumer, ct)271 .ConfigureAwait(false);272 await this.client.StartAsync(id, ct)273 .ConfigureAwait(false);274 this.container = await this.client.InspectContainer(id, ct)275 .ConfigureAwait(false);276 await this.configuration.StartupCallback(this, ct)277 .ConfigureAwait(false);278 // Do not use a too small frequency. Especially with a lot of containers,279 // we send many operations to the Docker endpoint. The endpoint may cancel operations.280 var frequency = (int)TimeSpan.FromSeconds(1).TotalMilliseconds;281 const int timeout = -1;282 foreach (var waitStrategy in this.configuration.WaitStrategies)283 {284 await WaitStrategy.WaitUntil(285 async () =>286 {287 this.container = await this.client.InspectContainer(id, ct)288 .ConfigureAwait(false);289 return await waitStrategy.Until(this, this.Logger)290 .ConfigureAwait(false);291 },292 frequency,293 timeout,294 ct)295 .ConfigureAwait(false);296 }297 return this.container;298 }299 private async Task<ContainerInspectResponse> Stop(string id, CancellationToken ct = default)300 {301 await this.client.StopAsync(id, ct)302 .ConfigureAwait(false);303 return await this.client.InspectContainer(id, ct)304 .ConfigureAwait(false);305 }306 private async Task<ContainerInspectResponse> CleanUp(string id, CancellationToken ct = default)307 {308 await this.client.RemoveAsync(id, ct)309 .ConfigureAwait(false);310 return new ContainerInspectResponse();311 }312 private void ThrowIfContainerHasNotBeenCreated()313 {314 if (ContainerHasBeenCreatedStates.HasFlag(this.State))315 {316 return;317 }318 throw new InvalidOperationException("Testcontainers has not been created.");319 }320 private string GetContainerGateway()321 {322 const string localhost = "localhost";323 if (!ContainerHasBeenCreatedStates.HasFlag(this.State))324 {325 return localhost;326 }327 if (!this.client.IsRunningInsideDocker)328 {329 return localhost;330 }331 var endpointSettings = this.container.NetworkSettings.Networks.TryGetValue("bridge", out var network) ? network : new EndpointSettings();332 if (!string.IsNullOrWhiteSpace(endpointSettings.Gateway))333 {334 return endpointSettings.Gateway;...

Full Screen

Full Screen

GetContainerGateway

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using DotNet.Testcontainers.Containers.Builders;4using DotNet.Testcontainers.Containers.Modules;5using DotNet.Testcontainers.Containers.Modules.Databases;6using DotNet.Testcontainers.Containers.WaitStrategies;7{8 {9 static async Task Main(string[] args)10 {11 var containerBuilder = new TestcontainersBuilder<MsSqlTestcontainer>()12 .WithDatabase(new MsSqlTestcontainerConfiguration())13 .WithName("testcontainer")14 .WithPortBinding(1433)15 .WithWaitStrategy(Wait.ForUnixContainer()16 .UntilCommandIsCompleted("sqlcmd -S localhost -U SA -P 'yourStrong(!)Password' -Q 'SELECT 1'"));17 using (var container = containerBuilder.Build())18 {19 await container.StartAsync();20 var gateway = container.GetContainerGateway();21 var host = gateway.Hostname;22 var port = gateway.Port;23 Console.WriteLine($"Host: {host}, Port: {port}");24 }25 }26 }27}

Full Screen

Full Screen

GetContainerGateway

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using DotNet.Testcontainers.Containers;4using DotNet.Testcontainers.Containers.Builders;5using DotNet.Testcontainers.Containers.Configurations;6using DotNet.Testcontainers.Containers.Modules;7using DotNet.Testcontainers.Containers.WaitStrategies;8using DotNet.Testcontainers.Images;9using DotNet.Testcontainers.Images.Builders;10using DotNet.Testcontainers.Images.Configurations;11{12 {13 static async Task Main(string[] args)14 {15 var container = new TestcontainersBuilder<TestcontainersContainer>()16 .WithImage("mcr.microsoft.com/mssql/server:2019-latest")17 .WithEnvironment("ACCEPT_EULA", "Y")18 .WithEnvironment("SA_PASSWORD", "MyStrongPassword")19 .WithEnvironment("MSSQL_PID", "Developer")20 .WithPortBinding(1433)21 .Build();22 await container.StartAsync();23 var gateway = container.GetContainerGateway();24 Console.WriteLine(gateway);25 Console.ReadLine();26 }27 }28}29using System;30using System.Threading.Tasks;31using DotNet.Testcontainers.Containers;32using DotNet.Testcontainers.Containers.Builders;33using DotNet.Testcontainers.Containers.Configurations;34using DotNet.Testcontainers.Containers.Modules;35using DotNet.Testcontainers.Images;36using DotNet.Testcontainers.Images.Builders;37using DotNet.Testcontainers.Images.Configurations;38{39 {40 static async Task Main(string[] args)41 {42 var container = new TestcontainersBuilder<TestcontainersContainer>()43 .WithImage("mcr.microsoft.com/mssql/server:2019-latest")44 .WithEnvironment("ACCEPT_EULA", "Y")45 .WithEnvironment("SA_PASSWORD", "MyStrongPassword")46 .WithEnvironment("MSSQL_PID", "Developer")47 .WithPortBinding(1433)48 .Build();49 await container.StartAsync();50 var gateway = container.GetContainerGateway();51 Console.WriteLine(gateway);52 Console.ReadLine();53 }54 }55}56using System;57using System.Threading.Tasks;58using DotNet.Testcontainers.Containers;

Full Screen

Full Screen

GetContainerGateway

Using AI Code Generation

copy

Full Screen

1using DotNet.Testcontainers.Containers;2using DotNet.Testcontainers.Containers.Builders;3using DotNet.Testcontainers.Containers.Modules;4using DotNet.Testcontainers.Containers.WaitStrategies;5using DotNet.Testcontainers.Images;6using System;7using System.Threading.Tasks;8{9 {10 static async Task Main(string[] args)11 {12 var container = new TestcontainersBuilder<GenericContainer>()13 .WithImage("mcr.microsoft.com/mssql/server:2017-latest")14 .WithEnvironment("ACCEPT_EULA", "Y")15 .WithEnvironment("SA_PASSWORD", "MyComplexPassword")16 .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(1433))17 .Build();18 await container.StartAsync();19 var gateway = container.GetContainerGateway();20 Console.WriteLine($"Server={gateway.Host};Database=master;User Id=sa;Password={gateway.Port};");21 await container.StopAsync();22 }23 }24}

Full Screen

Full Screen

GetContainerGateway

Using AI Code Generation

copy

Full Screen

1using DotNet.Testcontainers.Containers.Builders;2using DotNet.Testcontainers.Containers.Modules;3using DotNet.Testcontainers.Containers.WaitStrategies;4using DotNet.Testcontainers.Images;5using DotNet.Testcontainers.Images.Builders;6using System;7using System.Threading.Tasks;8using System.Threading;9{10 {11 static async Task Main(string[] args)12 {13 var image = new TestcontainersImageBuilder()14 .WithName("mcr.microsoft.com/mssql/server:2019-latest")15 .WithEnv("ACCEPT_EULA=Y")16 .WithEnv("SA_PASSWORD=Test1234")17 .WithEnv("MSSQL_PID=Developer")18 .Build();19 var container = new TestcontainersBuilder<TestcontainersContainer>()20 .WithImage(image)21 .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(1433))22 .Build();23 await container.StartAsync();24 var gateway = await container.GetContainerGatewayAsync();25 Console.WriteLine(gateway);26 await container.StopAsync();27 }28 }29}

Full Screen

Full Screen

GetContainerGateway

Using AI Code Generation

copy

Full Screen

1var container = new TestcontainersContainerBuilder<GenericContainer>()2 .WithImage("alpine")3 .Build();4await container.StartAsync();5var gateway = await container.GetContainerGateway();6await container.StopAsync();7container.Dispose();

Full Screen

Full Screen

GetContainerGateway

Using AI Code Generation

copy

Full Screen

1using System.Threading.Tasks;2using DotNet.Testcontainers.Containers.Builders;3using DotNet.Testcontainers.Containers.Modules;4using DotNet.Testcontainers.Containers.WaitStrategies;5{6 {7 static async Task Main(string[] args)8 {9 var container = new TestcontainersBuilder<GenericContainer>()10 .WithImage("alpine")11 .WithCommand("tail -f /dev/null")12 .WithWaitStrategy(Wait.ForUnixContainer().UntilCommandIsCompleted("echo hello world"))13 .Build();14 await container.StartAsync();15 var gateway = container.GetContainerGateway();16 await container.StopAsync();17 }18 }19}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful