ez-agent-ruby/test/test_helper.rb

# frozen_string_literal: true

require "json"
require "socket"
require "thread"
require "tmpdir"
require "fileutils"

# Isolate before loading the API, including direct runs of individual test files.
# Fixture sockets do not isolate the process-wide incident recorder's state path.
test_xdg_root = Dir.mktmpdir("ez-agent-ruby-test-")
at_exit do
  begin
    if defined?(EzAgent::API::Incidents)
      context = EzAgent::API::Incidents.instance_variable_get(:@context)
      context&.recorder&.close(timeout: 1)
    end
  ensure
    FileUtils.remove_entry(test_xdg_root)
  end
end
%w[XDG_CONFIG_HOME XDG_STATE_HOME XDG_RUNTIME_DIR].each do |key|
  ENV[key] = File.join(test_xdg_root, key)
  Dir.mkdir(ENV[key], 0o700)
end

require "ez_agent/api"

# Test-only wait tuning. Connection#join waits for the reader thread, which
# wakes at most once per READ_POLL_SECONDS to notice a local close; nothing
# interrupts the poll, so every fixture connection pays up to one full tick
# on cleanup. The shipped 2.0s default made the source suite spend ~80s of
# wall clock in these ticks (measured 2026-08-25: 86.2s -> 6.6s with 0.05s).
# This changes no shipped behavior and no contract semantics: it only makes
# the tests observe closes sooner. If a wakeup mechanism ever lands in the
# client, delete this override.
EzAgent::API.send(:remove_const, :READ_POLL_SECONDS)
EzAgent::API.const_set(:READ_POLL_SECONDS, 0.05)

module RubyAPITest
  # Test-only peer simulation. Fixture peers are NOT a Ruby server implementation
  # and must never move into lib/ or runtime packaging.
  class FixturePeer
    def initialize(reader:, writer: reader)
      @reader = reader
      @writer = writer
    end

    def read_hello
      RubyAPITest.read_frame(@reader)
    end

    def acknowledge!(**overrides)
      RubyAPITest.write_frame(@writer, RubyAPITest.valid_hello_ack(**overrides))
    end

    def read_frame
      RubyAPITest.read_frame(@reader)
    end

    def write_frame(frame)
      RubyAPITest.write_frame(@writer, frame)
    end

    def close
      [@reader, @writer].uniq.each { |io| io.close unless io.closed? }
    end
  end

  # Test-only AF_UNIX listener for adapter coverage. It is a fixture peer, not
  # a Ruby server implementation, and must never move into lib/ or runtime packaging.
  class AFUnixFixtureListener
    def initialize(socket_path)
      @listener = UNIXServer.new(socket_path)
    end

    def accept
      @listener.accept
    end

    def close
      @listener.close unless @listener.closed?
    end
  end

  ROOT = File.expand_path("../..", __dir__)
  CONFORMANCE_FIXTURE = File.join(
    ROOT, "pkg/ezagentapi/testdata/conformance/traffic.json"
  )

  @tests = []
  @test_cleanups = []

  class << self
    attr_reader :tests

    def test(name, &block)
      @tests << [name, block]
    end

    def defer_cleanup(&block)
      raise ArgumentError, "cleanup block required" unless block
      @test_cleanups << block
      nil
    end

    def assert(value, message = "assertion failed")
      raise message unless value
    end

    def assert_equal(expected, actual, message = nil)
      raise(message || "expected #{expected.inspect}, got #{actual.inspect}") unless expected == actual
    end

    def assert_outbound_frame(expected, actual)
      assert(actual["itr"].is_a?(Integer), "outbound frame has no integer itr: #{actual.inspect}")
      assert_equal(expected, actual.reject { |key, _| key == "itr" })
    end

    def assert_kind_of(klass, value)
      raise "expected #{klass}, got #{value.class}" unless value.is_a?(klass)
    end

    def assert_raises(klass)
      yield
    rescue Exception => error
      raise "expected #{klass}, got #{error.class}: #{error.message}" unless error.is_a?(klass)
      return error
    else
      raise "expected #{klass}, but nothing was raised"
    end

    def assert_exception_scrubbed(error, secret)
      current = error
      seen = {}
      while current && !seen[current.object_id]
        seen[current.object_id] = true
        assert(!current.is_a?(JSON::ParserError), "raw JSON parser exception escaped")
        [current.message, current.inspect,
         current.full_message(highlight: false, order: :top)].each do |rendered|
          assert(!rendered.include?(secret), "peer bytes leaked through exception rendering")
        end
        current = current.cause
      end
      true
    end

    def wait_until(timeout: 2.0)
      deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
      until yield
        raise "condition timed out" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
        sleep 0.005
      end
    end

    def fixture
      @fixture ||= JSON.parse(File.read(CONFORMANCE_FIXTURE))
    end

    def socket_pair
      Socket.pair(:UNIX, :STREAM, 0)
    end

    def read_frame(io)
      line = io.gets
      raise EOFError, "expected frame" unless line
      JSON.parse(line)
    end

    def write_frame(io, frame)
      io.write(JSON.generate(frame) << "\n")
    end

    def valid_hello_ack(**overrides)
      {
        "type" => "hello_ack", "protocol" => 1, "server_id" => "fixture",
        "state_dir" => "/state"
      }.merge(overrides.transform_keys(&:to_s))
    end

    def open_fixture_connection(reader, writer: reader, close: nil, **options, &block)
      cleanup = close || -> do
        [reader, writer].uniq.each { |io| io.close unless io.closed? }
      end
      EzAgent::API::Connection.open(
        reader: reader, writer: writer, close: cleanup, **options, &block
      )
    end

    def run
      failures = []
      tests.each do |name, test|
        begin
          test.call
        ensure
          run_test_cleanups
        end
        puts "ok - #{name}"
      rescue Exception => error
        failures << [name, error]
        warn "not ok - #{name}: #{error.class}: #{error.message}"
        warn error.backtrace.first(8).map { |line| "  #{line}" }.join("\n")
      end
      puts "#{tests.length} tests, #{failures.length} failures"
      exit 1 unless failures.empty?
    end

    private

    def run_test_cleanups
      cleanups = @test_cleanups.reverse
      @test_cleanups = []
      first_error = nil
      cleanups.each do |cleanup|
        cleanup.call
      rescue Exception => error
        first_error ||= error
      end
      raise first_error if first_error
    end
  end
end

at_exit { RubyAPITest.run if $!.nil? }