Skip to content

[Bug]: Possible NullReferenceExcetion on StoppedTime calculation when DockerContainer.StopAsync is called #1496

Description

@alexeideriglazov

Testcontainers version

4.5.0

Using the latest Testcontainers version?

Yes

Host OS

Linux

Host arch

x86_64

.NET version

8.0

Docker version

26.1.4

Docker info

-

What happened?

When DockerContainer.StopAsync is called it can throw NullReferenceException

Problem in StoppedTime calculation. _container can be assigned to empty ContainerInspectResponse after catched DockerContainerNotFoundException. Then, you can't access _container.State.FinishedAt and this causes NRE

      catch (DockerContainerNotFoundException)
      {
        _container = new ContainerInspectResponse(); //When we catch exception, _container.State is null 
      }

      StoppedTime = DateTime.TryParse(_container.State.FinishedAt, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var stoppedTime) ? stoppedTime : DateTime.UtcNow; // then throws NRE, we can't access _container.State.FinishedAt value

Probably Null-conditional operators can be used to avoid NRE

StoppedTime = DateTime.TryParse(_container.State?.FinishedAt, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var stoppedTime) ? stoppedTime : DateTime.UtcNow;

Relevant log output

TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
--TearDown
   at DotNet.Testcontainers.Containers.DockerContainer.UnsafeStopAsync(CancellationToken ct) in /_/src/Testcontainers/Containers/DockerContainer.cs:line 567
   at DotNet.Testcontainers.Containers.DockerContainer.StopAsync(CancellationToken ct) in /_/src/Testcontainers/Containers/DockerContainer.cs:line 319

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions