Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion core/lib/testcontainers/docker_container.rb
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,18 @@ def start

connection = Docker::Connection.new(Docker.url, Docker.options)

Docker::Image.create({"fromImage" => @image}.merge(@image_create_options), connection)
image_options = {"fromImage" => @image}.merge(@image_create_options)
image_reference = (image_options["fromImage"] || image_options[:fromImage] || @image).to_s
tag_option = image_options["tag"] || image_options[:tag]
if tag_option && !image_reference.end_with?(":#{tag_option}")
image_reference = "#{image_reference}:#{tag_option}"
end

begin
Docker::Image.get(image_reference, {}, connection)
rescue Docker::Error::NotFoundError
Docker::Image.create(image_options, connection)
end

@_container ||= Docker::Container.create(_container_create_options)
@_container.start
Expand Down
34 changes: 34 additions & 0 deletions core/test/docker_container_test.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# frozen_string_literal: true

require "test_helper"
require "tmpdir"
require "securerandom"

class DockerContainerTest < TestcontainersTest
def before_all
Expand Down Expand Up @@ -44,6 +46,38 @@ def test_it_creates_an_image_with_options
bad_container.remove if bad_container.exists?
end

def test_it_uses_locally_built_image_before_pulling
image_repo = "testcontainers-local-#{SecureRandom.hex(6)}"
image_tag = "latest"
image_reference = "#{image_repo}:#{image_tag}"
container = nil

Dir.mktmpdir do |dir|
dockerfile_path = File.join(dir, "Dockerfile")
File.write(dockerfile_path, <<~DOCKERFILE)
FROM alpine:latest
CMD ["sleep", "60"]
DOCKERFILE

Docker::Image.build_from_dir(dir, {"t" => image_reference, "dockerfile" => "Dockerfile"})
end

container = Testcontainers::DockerContainer.new(image_reference)
container.start

assert container.running?
ensure
if container
container.stop if container.running?
container.remove if container.exists?
end
begin
Docker::Image.get(image_reference).remove(force: true)
rescue Docker::Error::NotFoundError
# image already removed
end
end

def test_it_returns_the_container_image
assert_equal "hello-world", @container.image
end
Expand Down
Loading