<commit_before>$: << File.expand_path('..', __FILE__)

require File.expand_path('../../../spec/shared/spec_helper', __FILE__)
require File.expand_path('../../../spec/support/new_deployments.rb', __FILE__)

require 'digest/sha1'
require 'fileutils'
require 'logging'
require 'pg'
require 'tempfile'
require 'tmpdir'
require 'zlib'
require 'timecop'

require 'archive/tar/minitar'
require 'machinist/sequel'
require 'sham'
require 'support/buffered_logger'

Dir.glob(File.expand_path('../support/**/*.rb', __FILE__)).each { |f| require(f) }

DIRECTOR_TEST_CERTS="these\nare\nthe\ncerts"
DIRECTOR_TEST_CERTS_SHA1=::Digest::SHA1.hexdigest DIRECTOR_TEST_CERTS

RSpec.configure do |config|
  config.include Bosh::Director::Test::TaskHelpers
end

module SpecHelper
  class << self
    include BufferedLogger

    attr_accessor :temp_dir

    def init
      ENV['RACK_ENV'] = 'test'
      configure_init_logger
      configure_temp_dir

      require 'bosh/director'

      init_database

      require 'blueprints'
    end

    # init_logger is only used before the tests start.
    # Inside each test BufferedLogger will be used.
    def configure_init_logger
      file_path = File.expand_path('/tmp/spec.log', __FILE__)

      @init_logger = Logging::Logger.new('TestLogger')
      @init_logger.add_appenders(
        Logging.appenders.file(
          'TestLogFile',
          filename: file_path,
          layout: ThreadFormatter.layout
        )
      )
      @init_logger.level = :debug
    end

    def configure_temp_dir
      @temp_dir = Bosh::Director::Config.generate_temp_dir
    end

    def spec_get_director_config
      config = YAML.load_file(File.expand_path('assets/test-director-config.yml', File.dirname(__FILE__)))

      config['nats']['server_ca_path'] = File.expand_path('assets/nats/nats_ca.pem', File.dirname(__FILE__))
      config['nats']['client_ca_certificate_path'] = File.expand_path('assets/nats/nats_ca_certificate.pem', File.dirname(__FILE__))
      config['nats']['client_ca_private_key_path'] = File.expand_path('assets/nats/nats_ca_private_key.pem', File.dirname(__FILE__))
      config['db']['adapter'] = @director_db_helper.adapter
      config['db']['host'] = @director_db_helper.host
      config['db']['database'] = @director_db_helper.db_name
      config['db']['user'] = @director_db_helper.username
      config['db']['password'] = <PASSWORD>
      config['db']['port'] = @director_db_helper.port

      config
    end

    def init_database
      @db_name = SecureRandom.uuid.gsub('-', '')

      db_options = {
        username: ENV['DB_USER'],
        password: ENV['<PASSWORD>'],
        host: ENV['DB_HOST'] || '127.0.0.1',
      }.compact

      case ENV.fetch('DB', 'sqlite')
        when 'postgresql'
          require File.expand_path('../../bosh-dev/lib/bosh/dev/sandbox/postgresql', File.dirname(__FILE__))
          db_options[:port] = 5432

          @director_db_helper = Bosh::Dev::Sandbox::Postgresql.new("#{@db_name}_director", Bosh::Core::Shell.new, @init_logger, db_options)
          @dns_db_helper = Bosh::Dev::Sandbox::Postgresql.new("#{@db_name}_dns", Bosh::Core::Shell.new, @init_logger, db_options)
        when 'mysql'
          require File.expand_path('../../bosh-dev/lib/bosh/dev/sandbox/mysql', File.dirname(__FILE__))
          db_options[:port] = 3306

          @director_db_helper = Bosh::Dev::Sandbox::Mysql.new("#{@db_name}_director",  Bosh::Core::Shell.new, @init_logger, db_options)
          @dns_db_helper = Bosh::Dev::Sandbox::Mysql.new("#{@db_name}_dns",  Bosh::Core::Shell.new, @init_logger, db_options)
        when 'sqlite'
          require File.expand_path('../../bosh-dev/lib/bosh/dev/sandbox/sqlite', File.dirname(__FILE__))
          @director_db_helper = Bosh::Dev::Sandbox::Sqlite.new(File.join(@temp_dir, "#{@db_name}_director.sqlite"), @init_logger)
          @dns_db_helper = Bosh::Dev::Sandbox::Sqlite.new(File.join(@temp_dir, "#{@db_name}_dns.sqlite"), @init_logger)
        else
          raise "Unsupported DB value: #{ENV['DB']}"
      end

      @director_db_helper.create_db
      @dns_db_helper.create_db

      @dns_migrations = File.expand_path('../../db/migrations/dns', __FILE__)
      @director_migrations = File.expand_path('../../db/migrations/director', __FILE__)
      Sequel.extension :migration

      connect_database

      Sequel::Deprecation.output = false
      Delayed::Worker.backend = :sequel
      Sequel::Deprecation.output = $stderr

      run_migrations
    end

    def connect_database
      db_opts = {:max_connections => 32, :pool_timeout => 10}

      Sequel.default_timezone = :utc
      @director_db = Sequel.connect(@director_db_helper.connection_string, db_opts)
      @director_db.loggers << (logger || @init_logger)
      Bosh::Director::Config.db = @director_db

      @dns_db = Sequel.connect(@dns_db_helper.connection_string, db_opts)
      @dns_db.loggers << (logger || @init_logger)
      Bosh::Director::Config.dns_db = @dns_db
    end

    def disconnect_database
      if @director_db
        @director_db.disconnect<commit_msg>Include database connection ID in spec logs<commit_after>$: << File.expand_path('..', __FILE__)

require File.expand_path('../../../spec/shared/spec_helper', __FILE__)
require File.expand_path('../../../spec/support/new_deployments.rb', __FILE__)

require 'digest/sha1'
require 'fileutils'
require 'logging'
require 'pg'
require 'tempfile'
require 'tmpdir'
require 'zlib'
require 'timecop'

require 'archive/tar/minitar'
require 'machinist/sequel'
require 'sham'
require 'support/buffered_logger'

Dir.glob(File.expand_path('../support/**/*.rb', __FILE__)).each { |f| require(f) }

DIRECTOR_TEST_CERTS="these\nare\nthe\ncerts"
DIRECTOR_TEST_CERTS_SHA1=::Digest::SHA1.hexdigest DIRECTOR_TEST_CERTS

RSpec.configure do |config|
  config.include Bosh::Director::Test::TaskHelpers
end

module SpecHelper
  class << self
    include BufferedLogger

    attr_accessor :temp_dir

    def init
      ENV['RACK_ENV'] = 'test'
      configure_init_logger
      configure_temp_dir

      require 'bosh/director'

      init_database

      require 'blueprints'
    end

    # init_logger is only used before the tests start.
    # Inside each test BufferedLogger will be used.
    def configure_init_logger
      file_path = File.expand_path('/tmp/spec.log', __FILE__)

      @init_logger = Logging::Logger.new('TestLogger')
      @init_logger.add_appenders(
        Logging.appenders.file(
          'TestLogFile',
          filename: file_path,
          layout: ThreadFormatter.layout
        )
      )
      @init_logger.level = :debug
    end

    def configure_temp_dir
      @temp_dir = Bosh::Director::Config.generate_temp_dir
    end

    def spec_get_director_config
      config = YAML.load_file(File.expand_path('assets/test-director-config.yml', File.dirname(__FILE__)))

      config['nats']['server_ca_path'] = File.expand_path('assets/nats/nats_ca.pem', File.dirname(__FILE__))
      config['nats']['client_ca_certificate_path'] = File.expand_path('assets/nats/nats_ca_certificate.pem', File.dirname(__FILE__))
      config['nats']['client_ca_private_key_path'] = File.expand_path('assets/nats/nats_ca_private_key.pem', File.dirname(__FILE__))
      config['db']['adapter'] = @director_db_helper.adapter
      config['db']['host'] = @director_db_helper.host
      config['db']['database'] = @director_db_helper.db_name
      config['db']['user'] = @director_db_helper.username
      config['db']['password'] = @<PASSWORD>db_helper.password
      config['db']['port'] = @director_db_helper.port

      config
    end

    def init_database
      @db_name = SecureRandom.uuid.gsub('-', '')

      db_options = {
        username: ENV['DB_USER'],
        password: ENV['<PASSWORD>'],
        host: ENV['DB_HOST'] || '127.0.0.1',
      }.compact

      case ENV.fetch('DB', 'sqlite')
        when 'postgresql'
          require File.expand_path('../../bosh-dev/lib/bosh/dev/sandbox/postgresql', File.dirname(__FILE__))
          db_options[:port] = 5432

          @director_db_helper = Bosh::Dev::Sandbox::Postgresql.new("#{@db_name}_director", Bosh::Core::Shell.new, @init_logger, db_options)
          @dns_db_helper = Bosh::Dev::Sandbox::Postgresql.new("#{@db_name}_dns", Bosh::Core::Shell.new, @init_logger, db_options)
        when 'mysql'
          require File.expand_path('../../bosh-dev/lib/bosh/dev/sandbox/mysql', File.dirname(__FILE__))
          db_options[:port] = 3306

          @director_db_helper = Bosh::Dev::Sandbox::Mysql.new("#{@db_name}_director",  Bosh::Core::Shell.new, @init_logger, db_options)
          @dns_db_helper = Bosh::Dev::Sandbox::Mysql.new("#{@db_name}_dns",  Bosh::Core::Shell.new, @init_logger, db_options)
        when 'sqlite'
          require File.expand_path('../../bosh-dev/lib/bosh/dev/sandbox/sqlite', File.dirname(__FILE__))
          @director_db_helper = Bosh::Dev::Sandbox::Sqlite.new(File.join(@temp_dir, "#{@db_name}_director.sqlite"), @init_logger)
          @dns_db_helper = Bosh::Dev::Sandbox::Sqlite.new(File.join(@temp_dir, "#{@db_name}_dns.sqlite"), @init_logger)
        else
          raise "Unsupported DB value: #{ENV['DB']}"
      end

      @director_db_helper.create_db
      @dns_db_helper.create_db

      @dns_migrations = File.expand_path('../../db/migrations/dns', __FILE__)
      @director_migrations = File.expand_path('../../db/migrations/director', __FILE__)
      Sequel.extension :migration

      connect_database

      Sequel::Deprecation.output = false
      Delayed::Worker.backend = :sequel
      Sequel::Deprecation.output = $stderr

      run_migrations
    end

    def connect_database
      db_opts = {:max_connections => 32, :pool_timeout => 10}

      Sequel.default_timezone = :utc
      @director_db = Sequel.connect(@director_db_helper.connection_string, db_opts)
      @director_db.loggers << (logger || @init_logger)
      @director_db.log_connection_info = true
      Bosh::Director::Config.db = @director_db

      @dns_db = Sequel.connect(@dns_db_helper.connection_string, db_opts)
      @dns_db.loggers << (logger || @init_logger)
      @dns_db.log_connection_info = true
      Bosh::Director::Config.dns_db = @dns_db
    end

    def disconnect_database
      if @director_db
        @director_db.disconnect
{'fraction_non_alphanumeric': 0.1454686892259821, 'fraction_numerical': 0.004084014002333722, 'mean_word_length': 3.5833333333333335, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1994354', 'n_tokens_mistral': 3589, 'n_tokens_neox': 3423, 'n_words': 511}