lib/gitlab/qa/component/mock_server.rb



# frozen_string_literal: true

module Gitlab
  module QA
    module Component
      # General purpose http mock server
      # see: https://smocker.dev/
      #
      class MockServer < Base
        DOCKER_IMAGE = "thiht/smocker"
        DOCKER_IMAGE_TAG = "0.18.2"

        def initialize
          super

          @tls = false
          @name = "smocker"
          @tls_path = "/etc/smocker/tls"
          @ports = [80, 8081]
          @environment = { "SMOCKER_MOCK_SERVER_LISTEN_PORT" => 80 }
          @log_volume = {}
        end

        attr_reader :name
        attr_writer :tls

        def prepare
          super

          setup_tls if tls
        end

        # Print smocker log output by using docker logs command because smocker only logs to stdout
        #
        # @return [void]
        def teardown!
          Docker::Command.execute("logs #{name}")

          super
        end

        private

        attr_reader :tls_path, :tls

        # Set up tls certs
        #
        # @return [void]
        def setup_tls
          @volumes = { "smocker-ssl" => tls_path }
          @ports = [443, 8081]
          @environment = {
            "SMOCKER_MOCK_SERVER_LISTEN_PORT" => 443,
            "SMOCKER_TLS_ENABLE" => "true",
            "SMOCKER_TLS_CERT_FILE" => "#{@tls_path}/smocker.crt",
            "SMOCKER_TLS_PRIVATE_KEY_FILE" => "#{@tls_path}/smocker.key"
          }

          Alpine.perform do |alpine|
            alpine.volumes = volumes

            alpine.start_instance
            docker.copy(alpine.name, "#{CERTIFICATES_PATH}/smocker/.", tls_path)
          ensure
            alpine.teardown! # always remove container, even when global `--no-tests` flag was provided
          end
        end
      end
    end
  end
end