0

Error Log:

Standard Output Messages:
[testcontainers.org 00:00:03.98] Reuse is an experimental feature. For more information, visit: https://dotnet.testcontainers.org/api/resource_reuse/
-> warning: The previous ScenarioContext was already disposed.
   Failed EmailAddressesAreValidatedByTheForgottenPasswordScreen("it uses unquoted backslashes",null) [26 ms]
Error Message:
System.InvalidOperationException : Sequence contains more than one element
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
Stack Trace:
 at System.Linq.ThrowHelper.ThrowMoreThanOneElementException()
 at System.Linq.Enumerable.TryGetSingle[TSource](IEnumerable`1 source, Boolean& found)
 at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
 at DotNet.Testcontainers.Containers.DockerContainer.UnsafeCreateAsync(CancellationToken ct) in /_/src/Testcontainers/Containers/DockerContainer.cs:line 441
 at DotNet.Testcontainers.Containers.DockerContainer.StartAsync(CancellationToken ct) in /_/src/Testcontainers/Containers/DockerContainer.cs:line 306
 at [MYCOMPANY].[MYAPP].UI.Tests.Hooks.ConfigurationHooks.SetConfiguration(IObjectContainer objectContainer) in /home/runner/actions-runner/_work/[MYAPP]/[MYAPP]/Tests/[MYCOMPANY].[MYAPP].UI.Tests/Hooks/ConfigurationHooks.cs:line 48
 at Reqnroll.Bindings.AsyncMethodHelper.ConvertTaskOfT(Task task, Boolean getValue)
 at Reqnroll.Bindings.BindingDelegateInvoker.InvokeDelegateAsync(Delegate bindingDelegate, Object[] invokeArgs, ExecutionContextHolder executionContext)
 at Reqnroll.Bindings.BindingInvoker.InvokeBindingAsync(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, DurationHolder durationHolder)
 at Reqnroll.Infrastructure.TestExecutionEngine.InvokeHookAsync(IAsyncBindingInvoker invoker, IHookBinding hookBinding, HookType hookType)
 at Reqnroll.Infrastructure.TestExecutionEngine.FireEventsAsync(HookType hookType)
 at Reqnroll.Infrastructure.TestExecutionEngine.FireEventsAsync(HookType hookType)
 at Reqnroll.Infrastructure.TestExecutionEngine.OnFeatureStartAsync(FeatureInfo featureInfo)
 at Reqnroll.TestRunner.OnFeatureStartAsync(FeatureInfo featureInfo)
 at [MYCOMPANY].[MYAPP].UI.Tests.Features.PasswordAndEmailValidationFeature.TestInitializeAsync()
 at NUnit.Framework.Internal.TaskAwaitAdapter.GenericAdapter`1.BlockUntilCompleted()
 at NUnit.Framework.Internal.MessagePumpStrategy.NoMessagePumpStrategy.WaitForCompletion(AwaitAdapter awaiter)
 at NUnit.Framework.Internal.AsyncToSyncAdapter.Await[TResult](TestExecutionContext context, Func`1 invoke)
 at NUnit.Framework.Internal.AsyncToSyncAdapter.Await(TestExecutionContext context, Func`1 invoke)
 at NUnit.Framework.Internal.Commands.SetUpTearDownItem.RunSetUpOrTearDownMethod(TestExecutionContext context, IMethodInfo method)
 at NUnit.Framework.Internal.Commands.SetUpTearDownItem.RunSetUp(TestExecutionContext context)
 at NUnit.Framework.Internal.Commands.BeforeAndAfterTestCommand.<>c__DisplayClass1_0.<Execute>b__0()
 at NUnit.Framework.Internal.Commands.DelegatingTestCommand.RunTestMethodInThreadAbortSafeZone(TestExecutionContext context, Action action)
--TearDown
 at Reqnroll.Infrastructure.TestExecutionEngine.OnScenarioEndAsync()
 at Reqnroll.TestRunner.OnScenarioEndAsync()
 at [MYCOMPANY].[MYAPP].UI.Tests.Features.PasswordAndEmailValidationFeature.TestTearDownAsync()
 at NUnit.Framework.Internal.TaskAwaitAdapter.GenericAdapter`1.GetResult()
 at NUnit.Framework.Internal.AsyncToSyncAdapter.Await[TResult](TestExecutionContext context, Func`1 invoke)
 at NUnit.Framework.Internal.AsyncToSyncAdapter.Await(TestExecutionContext context, Func`1 invoke)
 at NUnit.Framework.Internal.Commands.SetUpTearDownItem.RunSetUpOrTearDownMethod(TestExecutionContext context, IMethodInfo method)
 at NUnit.Framework.Internal.Commands.SetUpTearDownItem.RunTearDown(TestExecutionContext context)

The above error message occurs when I try to setup a TestContainer in my automation test script for running a MailDev server to intercept email for a mail sender for users logins/password resets for my company.

Here's my codebase:

[BeforeFeature(Order = TestRunSequence.RegisterObjectContainer)]
public static async Task SetConfiguration(IObjectContainer objectContainer)
{
  var configuration = new ConfigurationBuilder()
    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables() // Load environment variables
    .AddUserSecrets<IdentityProviderConfiguration>()
    .Build();
  objectContainer?.RegisterInstanceAs(configuration);

  var mailDevContainer= new ContainerBuilder()
    .WithImage("maildev/maildev:latest")
    .WithPortBinding(1080, true)
    .WithPortBinding(1025, true)
    .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(1080))
    .WithReuse(true)
    .WithLabel("maildev-container", "MailDev")
    .WithPortBinding(1080, 1080)
    .WithPortBinding(1025, 1025)
    .Build();

  if (!isStarted)
  {
      await mailDevContainer.StartAsync();
      isStarted = true;
  }

  objectContainer?.RegisterInstanceAs(mailDevContainer);

  ***(More code irrelevant to this issue is here)***
}

It seems like it's complaining about Line 48 (Tests/[MYCOMPANY].[MYAPP].UI.Tests/Hooks/ConfigurationHooks.cs:line 48) ; which reflects the line await mailDevContainer.StartAsync();

I don't know why this is occurring, but I'm also seeing an error before this mentioning Error Message: Docker.DotNet.DockerApiException : Docker API responded with status code=InternalServerError, response={"message":"failed to set up container networking: driver failed programming external connectivity on endpoint adoring_hopper (397aeaf67af9014dc4341dfedc0494e52219ceb718d00fce6160bd81e8c69a74): Bind for 0.0.0.0:1025 failed: port is already allocated"} so maybe this is affecting things? Can you guys help identify this?

3
  • So I would try to run those containers without binding or use automatic one instead, I remember that testcontainers has this feature. Just to see if this the source of the problem. Commented Jul 14 at 9:19
  • The error you're encountering comes from this line: WithPortBinding(1025, 1025). It binds port 1025 from the container to port 1025 on your host. Since ports can only be used by one process at a time, something else or another container is already using port 1025 on your host. As @monsieur-merso pointed out, you should use the random host port feature instead. There are plenty of examples of this in the Testcontainers docs. Commented Jul 21 at 13:30
  • Wish that I could. it's a company firewall issue. Only certain ports are whitelisted and this is the only one Commented Jul 22 at 8:37

2 Answers 2

1

It seems that exception that you get is result of failed environment setup. As you already mentioned - there was a failure that prevented network of containers to setup correctly due to port already in use.

I remember I had such issue once and it was solved with automatic bind. Actually testcontainers documentation mentions it, see #2.

  1. Avoid assigning static port bindings to containers. Instead, use random assigned host ports _builder.WithPortBinding(ushort, true) and retrieve the mapped port with _container.GetMappedPublicPort(ushort).

It solves lots of pain points managing ports in a test container setup.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately my company only whitelists certain ports through its firewall, and I can't just use a random ushort port and hope. Insted I ensured that the port would be free by killing all processes on that port
glad you found a solution. good job.
0

I found a solution that works for this issue, in which I ensured that the port I wanted to use was actually free and available to use by killing all processes trying to use that port before starting my tests.

I am doing this over trying to ushort a random port as the Testcontainer documentation mentions because I am doing this for my company, who only allow certain ports whitelisted through their firewall.

Here's how I am ensuring that my docker is clear of all ports on 1025/1080:

          # Clean up any containers created during testing
          docker stop $(docker ps -q) 2>/dev/null || true
          docker rm $(docker ps -a -q) 2>/dev/null || true
          docker network prune -f
          docker volume prune -f
          
          # Kill any remaining processes on port 14333
          sudo lsof -ti:14333 | xargs -r sudo kill -9 2>/dev/null || true
          
          # Force cleanup of any lingering SQL Server containers
          docker ps -a --filter "ancestor=mcr.microsoft.com/mssql/server" -q | xargs -r docker rm -f 2>/dev/null || true
          
          # Clean up testcontainer networks and volumes
          docker network ls --filter "name=testcontainers" -q | xargs -r docker network rm 2>/dev/null || true
          docker volume ls --filter "name=testcontainers" -q | xargs -r docker volume rm 2>/dev/null || true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.