Repository navigation
Expand file tree
/
Copy pathClientTest.php
More file actions
346 lines (314 loc) · 14.7 KB
/
Copy pathClientTest.php
File metadata and controls
346 lines (314 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<?php
declare(strict_types=1);
namespace ChartQuery\Tests;
use ChartQuery\BatchResult;
use ChartQuery\BinaryResponse;
use ChartQuery\Client;
use ChartQuery\Endpoints;
use ChartQuery\Exception\ApiException;
use ChartQuery\Exception\ConfigurationException;
use ChartQuery\Exception\ResponseDecodingException;
use ChartQuery\Exception\SerializationException;
use ChartQuery\Exception\TransportException;
use ChartQuery\JsonResponse;
use ChartQuery\RequestOptions;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
final class ClientTest extends TestCase
{
private RecordingHttpClient $http;
private Client $client;
protected function setUp(): void
{
$this->http = new RecordingHttpClient();
$this->client = new Client('test-key', ['http_client' => $this->http, 'retry_delay' => 0.001]);
}
public function testRequiresApiKey(): void
{
putenv('CHARTQUERY_API_KEY');
$this->expectException(ConfigurationException::class);
new Client();
}
public function testRejectsInvalidBaseUrl(): void
{
$this->expectException(ConfigurationException::class);
new Client('k', ['base_url' => 'ftp://example.test']);
}
public function testReadsApiKeyFromEnvironment(): void
{
putenv('CHARTQUERY_API_KEY=env-key');
try {
(new Client(null, ['http_client' => $this->http]))->request('GET', '/v1/usage');
} finally {
putenv('CHARTQUERY_API_KEY');
}
self::assertSame('env-key', $this->http->requests[0]->getHeaderLine('x-api-key'));
}
public function testFeaturedOperation(): void
{
$this->http->respondWith(RecordingHttpClient::json(['hello' => 'world']));
$response = $this->client->chartAi(['prompt' => 'Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18']);
self::assertSame(['hello' => 'world'], $response->data);
$request = $this->http->requests[0];
self::assertSame('GET', $request->getMethod());
self::assertSame('https://api.chartquery.com/v1/chart/ai', explode('?', (string) $request->getUri())[0]);
self::assertSame('test-key', $request->getHeaderLine('x-api-key'));
self::assertStringStartsWith('chartquery-php/', $request->getHeaderLine('User-Agent'));
}
public function testQuerySerialization(): void
{
$client = new Client('k', ['http_client' => $this->http, 'base_url' => 'https://example.test/']);
$client->request('GET', '/v1/anything', [
'text' => 'a b&c', 'flag' => false, 'count' => 0, 'ratio' => 1.5, 'whole' => 2.0, 'list' => ['x', 'y'], 'nothing' => null,
]);
self::assertSame(
'https://example.test/v1/anything?text=a%20b%26c&flag=false&count=0&ratio=1.5&whole=2&list=x&list=y',
(string) $this->http->requests[0]->getUri(),
);
}
public function testPostSendsJsonBody(): void
{
$this->client->request('POST', '/v1/anything', ['query' => 'x', 'page' => 2, 'gone' => null]);
$request = $this->http->requests[0];
self::assertSame('POST', $request->getMethod());
self::assertSame('application/json', $request->getHeaderLine('Content-Type'));
self::assertSame(['query' => 'x', 'page' => 2], json_decode((string) $request->getBody(), true));
self::assertSame('', $request->getUri()->getQuery());
}
public function testPostKeepsGlobalParametersInQuery(): void
{
$this->client->request('POST', '/v1/anything', ['query' => 'x', 'is_async' => true, 'fields' => 'a']);
$request = $this->http->requests[0];
self::assertSame(['query' => 'x'], json_decode((string) $request->getBody(), true));
self::assertSame('fields=a&is_async=true', $request->getUri()->getQuery());
}
public function testPathParameters(): void
{
$this->client->request('GET', '/v1/items/{id}', ['id' => 'a/b c', 'other' => 1]);
self::assertSame('https://api.chartquery.com/v1/items/a%2Fb%20c?other=1', (string) $this->http->requests[0]->getUri());
$this->expectException(SerializationException::class);
$this->client->request('GET', '/v1/items/{id}');
}
public function testRequiredParameters(): void
{
try {
$this->client->chartAi([]); // @phpstan-ignore argument.type
self::fail('Expected SerializationException');
} catch (SerializationException) {
}
try {
$this->client->chartAi(['prompt' => 'Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18', 'not_a_parameter' => 1]);
self::fail('Expected SerializationException');
} catch (SerializationException $exception) {
self::assertSame('not_a_parameter', $exception->param);
}
self::assertSame([], $this->http->requests);
}
public function testUnsupportedMethod(): void
{
$this->expectException(ConfigurationException::class);
$this->client->chartRender(['id' => 'test'], new RequestOptions(method: 'POST'));
}
public function testDualOperationCanUsePost(): void
{
$this->client->barcode(['data' => 'test'], new RequestOptions(method: 'POST'));
$request = $this->http->requests[0];
self::assertSame('POST', $request->getMethod());
self::assertSame(['data' => 'test'], json_decode((string) $request->getBody(), true));
}
public function testEveryEndpoint(): void
{
foreach (Endpoints::ALL as $name => $endpoint) {
$method = lcfirst(str_replace('_', '', ucwords($name, '_')));
if (!method_exists($this->client, $method)) {
$method .= 'Endpoint';
}
$this->client->{$method}(self::REQUIRED[$name] ?? []);
$request = $this->http->requests[\count($this->http->requests) - 1];
self::assertSame('https://api.chartquery.com' . str_replace('{id}', 'test', $endpoint['path']), explode('?', (string) $request->getUri())[0], $name);
self::assertSame($endpoint['methods'][0], $request->getMethod(), $name);
}
self::assertCount(\count(Endpoints::ALL), $this->http->requests);
}
public function testBinaryResponse(): void
{
$this->http->respondWith(new Response(200, ['Content-Type' => 'image/png'], "\x89PNG"));
$response = $this->client->request('GET', '/v1/anything');
self::assertInstanceOf(BinaryResponse::class, $response);
self::assertSame("\x89PNG", $response->bytes);
self::assertSame('image/png', $response->contentType);
}
public function testNonJsonSuccessForJsonOperation(): void
{
$this->http->respondWith(new Response(200, ['Content-Type' => 'text/html'], '<html>'));
$this->expectException(ResponseDecodingException::class);
$this->client->chartAi(['prompt' => 'Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18']);
}
public function testApiError(): void
{
$this->http->respondWith(RecordingHttpClient::json(['error' => 'Invalid API Key'], 401));
try {
$this->client->request('GET', '/v1/usage');
self::fail('Expected ApiException');
} catch (ApiException $exception) {
self::assertSame(401, $exception->status);
self::assertSame('Invalid API Key', $exception->getMessage());
self::assertSame(['error' => 'Invalid API Key'], $exception->responseBody);
}
}
public function testNonJsonErrorBody(): void
{
$this->http->respondWith(new Response(502, [], 'Bad gateway'));
try {
$this->client->request('GET', '/v1/usage');
self::fail('Expected ApiException');
} catch (ApiException $exception) {
self::assertSame(502, $exception->status);
self::assertSame('Bad gateway', $exception->rawResponse->body);
}
}
public function testTransportError(): void
{
$this->http->failWith(new \RuntimeException('network down'));
$this->expectException(TransportException::class);
$this->client->request('GET', '/v1/usage');
}
public function testJsonResponseType(): void
{
$response = $this->client->request('GET', '/v1/usage');
self::assertInstanceOf(JsonResponse::class, $response);
}
public function testRetriesThenSucceeds(): void
{
$this->http->queue(RecordingHttpClient::json(['error' => 'busy'], 503));
$this->http->queue(new Response(429, ['Retry-After' => '0', 'Content-Type' => 'application/json'], '{}'));
$this->http->queue(RecordingHttpClient::json(['ok' => true]));
$response = $this->client->request('GET', '/v1/usage');
self::assertInstanceOf(JsonResponse::class, $response);
self::assertCount(3, $this->http->requests);
}
public function testRetryLimitsAndClientErrors(): void
{
$client = new Client('k', ['http_client' => $this->http, 'retry_delay' => 0.001, 'max_retries' => 2]);
$this->http->respondWith(RecordingHttpClient::json(['error' => 'busy'], 503));
try {
$client->request('GET', '/v1/usage');
self::fail('Expected ApiException');
} catch (ApiException) {
}
self::assertCount(3, $this->http->requests);
$this->http->respondWith(RecordingHttpClient::json(['error' => 'Payment required'], 402));
try {
$client->request('GET', '/v1/usage');
} catch (ApiException) {
}
self::assertCount(4, $this->http->requests);
$this->http->respondWith(RecordingHttpClient::json([], 500));
try {
$client->request('GET', '/v1/usage', [], new RequestOptions(maxRetries: 0));
} catch (ApiException) {
}
self::assertCount(5, $this->http->requests);
}
public function testRateLimitsAreRetriedButNotQuotas(): void
{
$cases = [
"Rate limit exceeded: You've exceeded the rate limit on your subscription" => 2,
'Rate limit exceeded for the API key: quota daily' => 1,
'Invalid API Key' => 1,
];
foreach ($cases as $message => $expected) {
$http = new RecordingHttpClient();
$http->queue(RecordingHttpClient::json(['error' => $message], 401));
$http->respondWith(RecordingHttpClient::json([]));
$client = new Client('k', ['http_client' => $http, 'retry_delay' => 0.001]);
try {
$client->request('GET', '/v1/usage');
} catch (ApiException) {
}
self::assertCount($expected, $http->requests, $message);
}
}
public function testGlobalParameters(): void
{
$this->client->chartAi(['prompt' => 'Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18', 'fields' => 'a,b.c', 'is_async' => true, 'soft_fail' => false]);
parse_str($this->http->requests[0]->getUri()->getQuery(), $query);
self::assertSame('a,b.c', $query['fields']);
self::assertSame('true', $query['is_async']);
self::assertSame('false', $query['soft_fail']);
}
public function testBatchWithPsr18Client(): void
{
$results = $this->client->batch([
['chartAi', ['prompt' => 'Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18']],
['chartAi', []],
['chart_ai', ['prompt' => 'Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18']],
]);
self::assertCount(3, $results);
self::assertTrue($results[0]->ok());
self::assertInstanceOf(SerializationException::class, $results[1]->error);
self::assertTrue($results[2]->ok());
self::assertSame([0, 1, 2], array_map(static fn(BatchResult $r): int => $r->index, $results));
self::assertCount(2, $this->http->requests);
}
public function testBatchWithGuzzlePoolRetries(): void
{
$mock = new MockHandler([
RecordingHttpClient::json(['n' => 1]),
RecordingHttpClient::json(['error' => 'busy'], 503),
RecordingHttpClient::json(['n' => 2]),
]);
$guzzle = new GuzzleClient(['handler' => HandlerStack::create($mock), 'http_errors' => false]);
$client = new Client('k', ['http_client' => $guzzle, 'retry_delay' => 0.001]);
$results = $client->batch([['chartAi', ['prompt' => 'Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18']], ['chartAi', ['prompt' => 'Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18']]], 2);
self::assertTrue($results[0]->ok() && $results[1]->ok());
self::assertInstanceOf(JsonResponse::class, $results[1]->value);
self::assertSame(['n' => 2], $results[1]->value->data);
self::assertSame(0, $mock->count());
}
public function testWaitForJob(): void
{
foreach (['Queued', 'Running', 'CompletedJob'] as $status) {
$this->http->queue(RecordingHttpClient::json(['status' => $status, 'progress' => 50]));
}
$seen = 0;
$job = $this->client->waitForJob('abc', 0.001, 60.0, static function () use (&$seen): void {
++$seen;
});
self::assertIsArray($job->data);
self::assertSame('CompletedJob', $job->data['status']);
self::assertCount(3, $this->http->requests);
self::assertSame('/v1/jobs/abc', $this->http->requests[0]->getUri()->getPath());
self::assertSame(3, $seen);
}
public function testWaitForJobTimesOut(): void
{
$this->http->respondWith(RecordingHttpClient::json(['status' => 'Running']));
$this->expectException(\ChartQuery\Exception\JobTimeoutException::class);
$this->client->waitForJob('abc', 0.01, 0.001);
}
/** @var array<string, array<string, mixed>> */
private const REQUIRED = [
'barcode' => ['data' => 'test'],
'chart' => ['query' => 'test'],
'chart_ai' => ['prompt' => 'test'],
'chart_render' => ['id' => 'test'],
'chart_view' => ['id' => 'test'],
'diagram' => ['type' => 'mermaid', 'query' => 'test'],
'diagram_ai' => ['prompt' => 'test'],
'diagram_render' => ['id' => 'test'],
'diagram_view' => ['id' => 'test'],
'jobs' => ['id' => 'test'],
'label' => ['query' => 'test'],
'label_compile' => ['width' => 1, 'elements' => ['test'], 'language' => 'zpl or tsc. Do not omit.'],
'label_convert' => ['source' => 'test', 'from' => 'tsc', 'to' => 'tsc'],
'label_parse' => ['source' => 'test', 'language' => 'tsc or zpl.'],
'label_render' => ['id' => 'test'],
'label_validate' => ['source' => 'test', 'language' => 'tsc or zpl.'],
'label_view' => ['id' => 'test'],
'qrcode' => ['data' => 'test'],
];
}