# frozen_string_literal: true

require "helper"
require "support/sandbox_project"

# The old_coverage_json project ships a .resultset.json generated by
# simplecov 0.17.1 (the file format changed in 0.18). As long as we want
# a hassle-free upgrade path from 0.17 and below, running against that
# stale file must keep working. See issue #820.
RSpec.describe "resultsets from simplecov 0.17 and below", :sandbox do
  before do
    setup_project("old_coverage_json")
    adjust_old_resultset_paths
  end

  # The fixture records absolute paths under a $$path placeholder;
  # point them at the sandbox so they refer to real files.
  def adjust_old_resultset_paths
    path = "coverage/.resultset.json"
    write_file(path, read_file(path).gsub("$$path", sandbox_dir))
  end

  def expect_line_summary(data, covered, total)
    files = data.fetch("coverage").values
    expect(files.sum { |file| file.fetch("covered_lines") }).to eq(covered)
    expect(files.sum { |file| file.fetch("total_lines") }).to eq(total)
  end

  def expect_old_json_report(result)
    expect_coverage_report_generated(result)
    data = html_report_data
    expect(reported_total_percent(data)).to eq(80.00)
    # Only lib/code.rb: the spec file is filtered by the default profile.
    expect(data.fetch("coverage").size).to eq(1)
    expect_line_summary(data, 4, 5)
  end

  it "runs the tests and reports despite the pre-0.18 resultset" do
    expect_old_json_report(run_command_and_expect_success("bundle exec rspec spec"))
  end

  it "runs the tests even when the old resultset's timestamp is current" do
    data = resultset_json
    # The fixture's command name is distinct from "RSpec" on purpose, so
    # the fresh run cannot simply overwrite the old entry.
    data.fetch("RSpec Different Name to avoid overriding")["timestamp"] = Time.now.to_i
    write_file("coverage/.resultset.json", JSON.pretty_generate(data))

    expect_old_json_report(run_command_and_expect_success("bundle exec rspec spec"))
  end
end
