Skip to content

Commit

Permalink
Add tests for OpenAIEndpoint class
Browse files Browse the repository at this point in the history
  • Loading branch information
thekid committed Oct 19, 2024
1 parent fd6c604 commit eb8897c
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ OpenAI APIs for XP
[![Supports PHP 8.0+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-8_0plus.svg)](http://php.net/)
[![Latest Stable Version](https://poser.pugx.org/xp-forge/openai/version.svg)](https://packagist.org/packages/xp-forge/openai)

This library implements OpenAI APIs.
This library implements OpenAI APIs with a low-level abstraction approach.

TikToken
--------
Expand Down
1 change: 1 addition & 0 deletions src/main/php/com/openai/rest/OpenAIEndpoint.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use util\log\Traceable;
use webservices\rest\Endpoint;

/** @test com.openai.unittest.OpenAIEndpointTest */
class OpenAIEndpoint implements Traceable {
private $endpoint;

Expand Down
53 changes: 53 additions & 0 deletions src/test/php/com/openai/unittest/OpenAIEndpointTest.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php namespace com\openai\unittest;

use com\openai\rest\OpenAIEndpoint;
use test\{Assert, Test};
use webservices\rest\TestEndpoint;

class OpenAIEndpointTest {
const URI= 'https://[email protected]/v1';

/** Returns a testing API endpoint */
private function testingEndpoint(): TestEndpoint {
return new TestEndpoint([
'POST /chat/completions' => function($call) {
if ($call->request()->payload()->value()['stream'] ?? false) {
$headers= ['Content-Type' => 'text/event-stream'];
$payload= implode("\n", [
'data: {"choices":[{"delta":{"role":"assistant"}}]}',
'data: {"choices":[{"delta":{"content":"Test"}}]}',
'data: [DONE]',
]);
} else {
$headers= ['Content-Type' => 'application/json'];
$payload= '{"choices":[{"message":{"role":"assistant","content":"Test"}}]}';
}

return $call->respond(200, 'OK', $headers, $payload);
}
]);
}

#[Test]
public function can_create() {
new OpenAIEndpoint(self::URI);
}

#[Test]
public function invoke() {
$endpoint= new OpenAIEndpoint($this->testingEndpoint());
Assert::equals(
['choices' => [['message' => ['role' => 'assistant', 'content' => 'Test']]]],
$endpoint->api('/chat/completions')->invoke(['stream' => false])
);
}

#[Test]
public function stream() {
$endpoint= new OpenAIEndpoint($this->testingEndpoint());
Assert::equals(
['choices' => [['message' => ['role' => 'assistant', 'content' => 'Test']]]],
$endpoint->api('/chat/completions')->stream(['stream' => true])->result()
);
}
}

0 comments on commit eb8897c

Please sign in to comment.