1+ <?php
2+
3+ use Joomla \Http \Http ;
4+ use Joomla \Http \HttpFactory ;
5+ use Joomla \Http \Response as HttpResponse ;
6+ use Joomla \AI \Provider \OpenAIProvider ;
7+ use PHPUnit \Framework \TestCase ;
8+
9+ class ChatTest extends TestCase
10+ {
11+ public function testSimpleChatCompletion ()
12+ {
13+ echo "Test 1: Test chat method with a simple prompt \n" ;
14+
15+ $ fakeChatResponseBody = json_encode ([
16+ 'id ' => 'chatcmpl-test ' ,
17+ 'object ' => 'chat.completion ' ,
18+ 'created ' => time (),
19+ 'model ' => 'gpt-4o-mini ' ,
20+ 'usage ' => ['prompt_tokens ' => 5 , 'completion_tokens ' => 7 , 'total_tokens ' => 12 ],
21+ 'choices ' => [
22+ [
23+ 'index ' => 0 ,
24+ 'message ' => ['role ' => 'assistant ' , 'content ' => 'All good here! ' ],
25+ 'finish_reason ' => 'stop ' ,
26+ ],
27+ ],
28+ ]);
29+
30+ $ httpFactoryMock = $ this ->createMock (HttpFactory::class);
31+ $ httpClientMock = $ this ->createMock (Http::class);
32+
33+ $ httpFactoryMock ->method ('getHttp ' )->willReturn ($ httpClientMock );
34+
35+ $ response = new HttpResponse ('php://memory ' , 200 , ['Content-Type ' => 'application/json ' ]);
36+ $ stream = $ response ->getBody ();
37+ $ stream ->write ($ fakeChatResponseBody );
38+
39+ $ httpClientMock ->method ('post ' )->willReturn ($ response );
40+
41+ $ provider = new OpenAIProviderNoModeration (['api_key ' => 'test-api-key ' ], $ httpFactoryMock );
42+
43+ $ response = $ provider ->chat ('Hello! How are you? ' , ['model ' => 'gpt-4o-mini ' ]);
44+
45+ $ this ->assertEquals (200 , $ response ->getStatusCode ());
46+ $ this ->assertSame ('All good here! ' , $ response ->getContent ());
47+ $ metadata = $ response ->getMetadata ();
48+ $ this ->assertArrayHasKey ('model ' , $ metadata );
49+ $ this ->assertArrayHasKey ('usage ' , $ metadata );
50+ }
51+ }
52+
53+ class OpenAIProviderNoModeration extends OpenAIProvider
54+ {
55+ protected function moderateInput ($ input , array $ options = []): bool
56+ {
57+ return false ;
58+ }
59+ }
0 commit comments