Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
9.1 KB
Raw Blame
require "test_helper"
require "ostruct"

class Provider::Anthropic::PdfProcessorTest < ActiveSupport::TestCase
  setup do
    @pdf_content = "%PDF-1.4 fake bytes".b
  end

  [ {}, { cache_creation_input_tokens: 30, cache_read_input_tokens: 50 } ].each do |cache_usage|
    test "exports token usage with #{cache_usage.empty? ? 'missing' : 'populated'} cache fields" do
      response = build_response(content: [ tool_use_block(id: "toolu_1", name: "report_document_analysis",
        input: { "summary" => "Statement", "document_type" => "bank_statement" }) ],
        usage: { input_tokens: 10, output_tokens: 20 }.merge(cache_usage))
      span = mock
      span.expects(:end).with do |args|
        args[:usage] == { "input_tokens" => 10, "output_tokens" => 20, "total_tokens" => 30,
          "cache_creation_input_tokens" => cache_usage.fetch(:cache_creation_input_tokens, 0),
          "cache_read_input_tokens" => cache_usage.fetch(:cache_read_input_tokens, 0) }
      end
      result = Provider::Anthropic::PdfProcessor.new(stub_client(response), model: "claude-sonnet-4-6",
        pdf_content: @pdf_content, langfuse_trace: stub(generation: span)).process

      assert_equal "Statement", result.summary
    end
  end

  test "sends PDF as native document content block and parses tool response" do
    fake_response = build_response(content: [
      tool_use_block(
        id: "toolu_1",
        name: "report_document_analysis",
        input: {
          "document_type" => "bank_statement",
          "summary" => "Bank of Example, Mar 2026 statement.",
          "extracted_data" => {
            "institution_name" => "Bank of Example",
            "statement_period_start" => "2026-03-01",
            "statement_period_end" => "2026-03-31",
            "transaction_count" => 42,
            "opening_balance" => 1000.0,
            "closing_balance" => 1500.0,
            "currency" => "USD",
            "account_holder" => "Account Holder"
          }
        }
      )
    ])
    captured = nil
    client = stub_client(fake_response) { |params| captured = params }

    result = Provider::Anthropic::PdfProcessor.new(
      client,
      model: "claude-sonnet-4-6",
      pdf_content: @pdf_content
    ).process

    document_block = captured[:messages].first[:content].first
    assert_equal "document", document_block[:type]
    assert_equal "application/pdf", document_block[:source][:media_type]
    assert_equal "base64", document_block[:source][:type]
    assert_equal Base64.strict_encode64(@pdf_content), document_block[:source][:data]

    assert_equal "report_document_analysis", captured[:tool_choice][:name]
    assert captured[:tool_choice][:disable_parallel_tool_use]

    assert_equal "bank_statement", result.document_type
    assert_equal "Bank of Example, Mar 2026 statement.", result.summary
    assert_equal 42, result.extracted_data["transaction_count"]
  end

  test "stringifies symbol keys in extracted_data" do
    # The Anthropic SDK returns tool input with symbol keys, so the JSON.parse
    # branch is skipped; without stringifying, every string-keyed reader of
    # the result (e.g. the AI health probe) sees nil.
    fake_response = build_response(content: [
      tool_use_block(
        id: "toolu_1",
        name: "report_document_analysis",
        input: {
          document_type: :bank_statement,
          summary: "Bank of Example, Mar 2026 statement.",
          extracted_data: {
            institution_name: "Bank of Example",
            transaction_count: 42,
            account_holder: "Account Holder"
          }
        }
      )
    ])
    client = stub_client(fake_response)

    result = Provider::Anthropic::PdfProcessor.new(
      client,
      model: "claude-sonnet-4-6",
      pdf_content: @pdf_content
    ).process

    assert_equal "bank_statement", result.document_type
    assert_equal "Bank of Example", result.extracted_data["institution_name"]
    assert_equal 42, result.extracted_data["transaction_count"]
    assert_equal "Account Holder", result.extracted_data["account_holder"]
  end

  test "normalizes unknown document_type to other" do
    fake_response = build_response(content: [
      tool_use_block(
        id: "toolu_2",
        name: "report_document_analysis",
        input: {
          "document_type" => "alien_invasion_form",
          "summary" => "Unknown.",
          "extracted_data" => {}
        }
      )
    ])
    client = stub_client(fake_response)

    result = Provider::Anthropic::PdfProcessor.new(
      client,
      model: "claude-sonnet-4-6",
      pdf_content: @pdf_content
    ).process

    assert_equal "other", result.document_type
  end

  test "raises when pdf_content is blank" do
    err = assert_raises(Provider::Anthropic::Error) do
      Provider::Anthropic::PdfProcessor.new(
        mock,
        model: "claude-sonnet-4-6",
        pdf_content: ""
      ).process
    end
    assert_match(/PDF content is required/i, err.message)
  end

  test "raises before any API call when pdf_content exceeds the base64-adjusted cap" do
    oversized = "a".b * (Provider::Anthropic::PdfProcessor::MAX_PDF_BYTES + 1)
    client = mock
    client.expects(:messages).never

    err = assert_raises(Provider::Anthropic::Error) do
      Provider::Anthropic::PdfProcessor.new(
        client,
        model: "claude-sonnet-4-6",
        pdf_content: oversized
      ).process
    end
    assert_match(/32 MB request limit/i, err.message)
  end

  test "extracts only allowlisted error fields into span output when the API call fails" do
    error = StandardError.new("boom")
    def error.body
      {
        "type" => "error",
        "error" => { "type" => "invalid_request_error", "message" => "invalid request" },
        "request" => { "document" => "base64-pdf-contents-that-should-never-leak" }
      }
    end

    client = stub_failing_client(error)
    captured_output = nil
    trace = stub_trace { |output| captured_output = output }

    assert_raises(StandardError) do
      Provider::Anthropic::PdfProcessor.new(
        client,
        model: "claude-sonnet-4-6",
        pdf_content: @pdf_content,
        langfuse_trace: trace
      ).process
    end

    assert_equal({ type: "invalid_request_error", message: "invalid request" }, captured_output[:error_detail])
  end

  test "error_detail is nil in span output when the error exposes no body" do
    error = StandardError.new("boom")

    client = stub_failing_client(error)
    captured_output = nil
    trace = stub_trace { |output| captured_output = output }

    assert_raises(StandardError) do
      Provider::Anthropic::PdfProcessor.new(
        client,
        model: "claude-sonnet-4-6",
        pdf_content: @pdf_content,
        langfuse_trace: trace
      ).process
    end

    assert_nil captured_output[:error_detail]
  end

  test "error_detail falls back to a placeholder when reading the body itself raises" do
    error = StandardError.new("boom")
    def error.body
      raise "body accessor exploded"
    end

    client = stub_failing_client(error)
    captured_output = nil
    trace = stub_trace { |output| captured_output = output }

    assert_raises(StandardError) do
      Provider::Anthropic::PdfProcessor.new(
        client,
        model: "claude-sonnet-4-6",
        pdf_content: @pdf_content,
        langfuse_trace: trace
      ).process
    end

    assert_match(/detail unavailable/i, captured_output[:error_detail])
  end

  test "sends tool_choice auto to a model that rejects a forced tool" do
    fake_response = build_response(content: [
      tool_use_block(
        id: "toolu_4",
        name: "report_document_analysis",
        input: { "document_type" => "bank_statement", "summary" => "Statement.", "extracted_data" => {} }
      )
    ])
    captured = nil
    client = stub_client(fake_response) { |params| captured = params }

    result = Provider::Anthropic::PdfProcessor.new(
      client,
      model: "claude-sonnet-5-5",
      pdf_content: @pdf_content
    ).process

    assert_equal({ type: "auto", disable_parallel_tool_use: true }, captured[:tool_choice])
    assert_includes captured[:system_], "calling the report_document_analysis tool"
    assert_equal "bank_statement", result.document_type
  end

  private
    def stub_failing_client(error)
      messages = mock
      messages.expects(:create).raises(error)
      client = mock
      client.stubs(:messages).returns(messages)
      client
    end

    def stub_trace
      span = mock
      span.expects(:end).with { |args| yield(args[:output]); true }
      trace = mock
      trace.stubs(:generation).returns(span)
      trace
    end

    def stub_client(response)
      messages = mock
      messages.expects(:create).with do |params|
        yield(params) if block_given?
        true
      end.returns(response)
      client = mock
      client.stubs(:messages).returns(messages)
      client
    end

    def build_response(content:, usage: { input_tokens: 800, output_tokens: 200 })
      OpenStruct.new(
        id: "msg_test",
        model: "claude-sonnet-4-6",
        content: content,
        usage: OpenStruct.new(usage)
      )
    end

    def tool_use_block(id:, name:, input:)
      OpenStruct.new(type: :tool_use, id: id, name: name, input: input)
    end
end