# frozen_string_literal: true

require_relative 'bootstrap'

class LegacyExperimentCookieTest < Minitest::Test
  def twitch
    Faraday.new(TWITCH_URL) do |conn|
      conn.use :cookie_jar
      conn.adapter Faraday.default_adapter
    end
  end

  def teardown
    sleep 0.25
  end

  def test_random_distribution
    included = 0
    total = 0
    1000.times do
      res = twitch.get('/')
      refute_nil res.headers['Set-Cookie'], 'Expected Set-Cookie header to be present'
      included += 1 if res.headers['Set-Cookie'].include?('impact_included=')
      total += 1
      sleep 0.25
    end

    redirect_rate = (included.to_f / total).round(3)
    expected_weight = 0.02
    expected_delta = 0.005
    assert_in_delta redirect_rate, expected_weight, expected_delta,
      "Inclusion rate of #{redirect_rate} is not within #{expected_delta} of expected rate #{expected_weight}"
  end

  def test_no_cookie_on_included_or_excluded
    10.times do
      t = twitch
      res = t.get('/') # get a cookie
      assert res.headers['Set-Cookie'].include?('impact_included') || res.headers['Set-Cookie'].include?('impact_excluded')
      sleep 0.25
      10.times do
        res = t.get('/')
        assert_nil res.headers['Set-Cookie']
        sleep 0.25
      end
    end
  end
end
