|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "rails_helper" |
| 4 | +require "webmock/rspec" |
| 5 | + |
| 6 | +RSpec.describe DiscourseAi::Inference::CloudflareWorkersAi do |
| 7 | + subject { described_class.new(account_id, api_token, model) } |
| 8 | + |
| 9 | + let(:account_id) { "test_account_id" } |
| 10 | + let(:api_token) { "test_api_token" } |
| 11 | + let(:model) { "test_model" } |
| 12 | + let(:content) { "test content" } |
| 13 | + let(:endpoint) do |
| 14 | + "https://api.cloudflare.com/client/v4/accounts/#{account_id}/ai/run/@cf/#{model}" |
| 15 | + end |
| 16 | + let(:headers) do |
| 17 | + { |
| 18 | + "Referer" => Discourse.base_url, |
| 19 | + "Content-Type" => "application/json", |
| 20 | + "Authorization" => "Bearer #{api_token}", |
| 21 | + } |
| 22 | + end |
| 23 | + let(:payload) { { text: [content] }.to_json } |
| 24 | + |
| 25 | + before do |
| 26 | + stub_request(:post, endpoint).with(body: payload, headers: headers).to_return( |
| 27 | + status: response_status, |
| 28 | + body: response_body, |
| 29 | + ) |
| 30 | + end |
| 31 | + |
| 32 | + describe "#perform!" do |
| 33 | + context "when the response status is 200" do |
| 34 | + let(:response_status) { 200 } |
| 35 | + let(:response_body) { { result: { data: ["embedding_result"] } }.to_json } |
| 36 | + |
| 37 | + it "returns the embedding result" do |
| 38 | + result = subject.perform!(content) |
| 39 | + expect(result).to eq("embedding_result") |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + context "when the response status is 429" do |
| 44 | + let(:response_status) { 429 } |
| 45 | + let(:response_body) { "" } |
| 46 | + |
| 47 | + it "doesn't raises a Net::HTTPBadResponse error" do |
| 48 | + expect { subject.perform!(content) }.not_to raise_error |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + context "when the response status is not 200 or 429" do |
| 53 | + let(:response_status) { 500 } |
| 54 | + let(:response_body) { "Internal Server Error" } |
| 55 | + |
| 56 | + it "raises a Net::HTTPBadResponse error" do |
| 57 | + allow(Rails.logger).to receive(:warn) |
| 58 | + expect { subject.perform!(content) }.to raise_error(Net::HTTPBadResponse) |
| 59 | + expect(Rails.logger).to have_received(:warn).with( |
| 60 | + "Cloudflare Workers AI Embeddings failed with status: #{response_status} body: #{response_body}", |
| 61 | + ) |
| 62 | + end |
| 63 | + end |
| 64 | + end |
| 65 | +end |
0 commit comments