Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Tests\Unit;
use GuzzleHttp\Exception\ConnectException;use GuzzleHttp\Psr7\HttpFactory;use GuzzleHttp\Psr7\NoSeekStream;use GuzzleHttp\Psr7\Request;use GuzzleHttp\Psr7\Response;use GuzzleHttp\Psr7\Utils;use PHPUnit\Framework\TestCase;use Wotnak\Atproto\Client\RawXrpcResponse;use Wotnak\Atproto\Client\XrpcClient;use Wotnak\Atproto\Client\XrpcOptions;use Wotnak\Atproto\Client\XrpcRequestSenderInterface;use Wotnak\Atproto\Client\XrpcResponse;use Wotnak\Atproto\Exception\LexiconValidationException;use Wotnak\Atproto\Exception\XrpcDecodeException;use Wotnak\Atproto\Exception\XrpcException;use Wotnak\Atproto\Exception\XrpcHttpException;use Wotnak\Atproto\Exception\XrpcProtocolException;use Wotnak\Atproto\Lexicon\InMemoryLexiconRepository;use Wotnak\Atproto\Lexicon\LexiconDocument;use Wotnak\Atproto\Lexicon\LexiconParser;use Wotnak\Atproto\Lexicon\SchemaCompiler;use Wotnak\Atproto\LexiconXrpcClient;use Wotnak\Atproto\Security\OutboundUrlPolicy;use Wotnak\Atproto\Tests\Support\FailingXrpcRequestSender;use Wotnak\Atproto\Tests\Support\TestXrpcRequestSender;
/** * Request bodies use PSR-7 strings and headers. */final class LexiconXrpcClientTest extends TestCase {
private const RAW_CID = 'bafkreifjjcie6lypi6ny7amxnfftagclbuxndqonfipmb64f2km2devei4';
private const CBOR_CID = 'bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a';
public function testReturnsParsedJsonBodyForQuery(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'hello'])]);
$response = self::client($sender, self::queryDefinition()) ->call( 'io.example.testQuery', ['limit' => 10], );
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(200, $response->statusCode); static::assertSame(['value' => 'hello'], $response->data); static::assertTrue($response->hasBody); }
public function testReturnsParsedJsonBodyForProcedure(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['id' => 'abc123'])]);
$response = self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 'hello world'], );
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['id' => 'abc123'], $response->data); }
public function testReturnsBinaryBodyForQuery(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/octet-stream'], "\x01\x02\x03\x04"), ]);
$response = self::client($sender, self::binaryQueryDefinition())->call('io.example.testBinaryQuery');
static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame("\x01\x02\x03\x04", $response->body); }
public function testReturnsBinaryBodyForProcedure(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/octet-stream'], "\x0A\x14\x1E"), ]);
$response = self::client($sender, self::binaryProcedureDefinition()) ->call( 'io.example.testBinaryProcedure', input: "\x63", );
static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame("\x0A\x14\x1E", $response->body); static::assertSame('image/png', $sender->lastRequest?->getHeaderLine('Content-Type')); }
public function testReturnsNoBodyForNoOutputQuery(): void { $sender = new TestXrpcRequestSender([new Response(200)]);
$response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery');
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(200, $response->statusCode); static::assertFalse($response->hasBody); }
public function testPassesQueryParamsAsUrlSearchParams(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]);
self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 25]);
static::assertSame( 'https://service.example/xrpc/io.example.testQuery?limit=25', (string) $sender->lastRequest?->getUri(), ); }
public function testSendsPostWithJsonBodyForProcedure(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['id' => 'new-id'])]);
self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 'test content'], );
static::assertSame('POST', $sender->lastRequest?->getMethod()); static::assertSame('application/json', $sender->lastRequest?->getHeaderLine('Content-Type')); static::assertSame('{"text":"test content"}', (string) $sender->lastRequest?->getBody()); }
public function testForwardsCustomHeaders(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]);
self::client($sender, self::queryDefinition()) ->call( 'io.example.testQuery', ['limit' => 1], options: new XrpcOptions(headers: ['Authorization' => 'Bearer token123']), );
static::assertSame('Bearer token123', $sender->lastRequest?->getHeaderLine('Authorization')); }
public function testAcceptsOptionalParamsAsOmitted(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]);
$response = self::client($sender, self::queryDefinition())->call('io.example.testQuery');
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['value' => 'ok'], $response->data); static::assertSame('', $sender->lastRequest?->getUri()->getQuery()); }
public function testIgnoresSchemaOutputForNoOutputQuery(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['unexpected' => 'data'])]);
$response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery');
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['unexpected' => 'data'], $response->data); }
public function testAppliesAllCallerProvidedHeaders(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]);
self::client($sender, self::queryDefinition()) ->call( 'io.example.testQuery', options: new XrpcOptions(headers: [ 'Atproto-Proxy' => 'did:plc:foo#bar', 'Atproto-Accept-Labelers' => 'did:plc:labeler1#a,did:plc:labeler2#b', 'X-Custom-Header' => 'custom-value', ]), );
static::assertSame('custom-value', $sender->lastRequest?->getHeaderLine('X-Custom-Header')); static::assertSame('did:plc:foo#bar', $sender->lastRequest?->getHeaderLine('Atproto-Proxy')); static::assertSame( 'did:plc:labeler1#a,did:plc:labeler2#b', $sender->lastRequest?->getHeaderLine('Atproto-Accept-Labelers'), ); }
public function testWrapsFetchHandlerTypeError(): void { $sender = new FailingXrpcRequestSender(new ConnectException('fetch failed', new Request('GET', '/')));
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected the transport exception.'); } catch (XrpcException $exception) { static::assertSame('fetch failed', $exception->getPrevious()?->getMessage()); static::assertStringContainsString('fetch failed', $exception->getMessage()); } }
public function testWrapsRejectedFetchPromise(): void { $sender = new FailingXrpcRequestSender(new ConnectException('network timeout', new Request('GET', '/')));
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected the transport exception.'); } catch (XrpcException $exception) { static::assertSame('network timeout', $exception->getPrevious()?->getMessage()); static::assertStringContainsString('network timeout', $exception->getMessage()); } }
public function testThrowsFor400WithValidErrorPayload(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['error' => 'TestError', 'message' => 'bad request'], 400), ]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected an XRPC error.'); } catch (XrpcHttpException $exception) { static::assertSame(400, $exception->statusCode); static::assertSame('TestError', $exception->xrpcError); static::assertSame('bad request', $exception->xrpcMessage); } }
public function testThrowsFor401AuthenticationError(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['error' => 'AuthenticationRequired', 'message' => 'Token expired'], 401), ]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected an authentication error.'); } catch (XrpcHttpException $exception) { static::assertSame(401, $exception->statusCode); static::assertSame('AuthenticationRequired', $exception->xrpcError); static::assertSame('Token expired', $exception->xrpcMessage); } }
public function testThrowsForNonXrpcErrorResponse(): void { $sender = new TestXrpcRequestSender([ new Response(404, ['Content-Type' => 'text/plain'], 'Not Found'), ]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected an HTTP error.'); } catch (XrpcHttpException $exception) { static::assertSame(404, $exception->statusCode); static::assertNull($exception->xrpcError); static::assertSame('Not Found', $exception->responseBody); } }
public function testThrowsFor500WithoutValidErrorPayload(): void { $sender = new TestXrpcRequestSender([ new Response(500, ['Content-Type' => 'text/html'], 'Internal Server Error'), ]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected an HTTP error.'); } catch (XrpcHttpException $exception) { static::assertSame(500, $exception->statusCode); static::assertNull($exception->decodedBody); static::assertSame('Internal Server Error', $exception->responseBody); } }
public function testReflectsUpstream5xxWithValidXrpcPayload(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['error' => 'ServerError', 'message' => 'Something went wrong'], 502), ]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected an HTTP error.'); } catch (XrpcHttpException $exception) { static::assertSame(502, $exception->statusCode); static::assertSame('ServerError', $exception->xrpcError); static::assertSame('Something went wrong', $exception->xrpcMessage); } }
public function testRejectsResponseBodyThatFailsSchemaValidation(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 123])]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected response validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('output', $exception->phase); } }
public function testRejectsWrongResponseContentTypeBeforeParsing(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'text/plain'], 'binary data'), ]);
$this->expectException(XrpcProtocolException::class); $this->expectExceptionMessage('Content-Type');
self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); }
public function testRejectsCallerProvidedContentTypeHeader(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]);
$this->expectException(\InvalidArgumentException::class);
self::client($sender, self::queryDefinition()) ->call( 'io.example.testQuery', ['limit' => 10], options: new XrpcOptions(headers: ['Content-Type' => 'application/json']), ); }
public function testUnparseableJsonErrorResponseRemainsAnHttpException(): void { $sender = new TestXrpcRequestSender([ new Response(400, ['Content-Type' => 'application/json'], 'not valid json'), ]);
$this->expectException(XrpcHttpException::class);
self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); }
public function testRejectsUnparseableJsonSuccessResponse(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], 'not valid json'), ]);
$this->expectException(XrpcDecodeException::class);
self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); }
public function testRejectsEmptyResponseWhenSchemaExpectsPayload(): void { $sender = new TestXrpcRequestSender([new Response(200)]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected empty output validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('output', $exception->phase); } }
public function testParsesContentTypeWithCharsetParameter(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json; charset=utf-8'], '{"value":"hello"}'), ]);
$response = self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]);
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['value' => 'hello'], $response->data); }
public function testHandlesNoContentTypeAndEmptyBodyAsNoPayload(): void { $sender = new TestXrpcRequestSender([new Response(200, [], '')]);
$response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery');
static::assertSame(200, $response->statusCode); }
public function testTreatsNoContentTypeNonemptyBinaryResponseAsBinary(): void { $sender = new TestXrpcRequestSender([new Response(200, [], "\x01\x02\x03")]);
$response = self::client($sender, self::binaryQueryDefinition())->call('io.example.testBinaryQuery');
static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame("\x01\x02\x03", $response->body); }
public function testRejects3xxStatusCode(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'redirect'], 302)]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected a redirect response error.'); } catch (XrpcHttpException $exception) { static::assertSame(302, $exception->statusCode); } }
public function testRejectsInvalidQueryParamsWhenValidationIsEnabled(): void { $sender = new TestXrpcRequestSender([]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 'not-a-number']); static::fail('Expected parameter validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('parameters', $exception->phase); static::assertSame(0, $sender->requestCount); } }
public function testRejectsInvalidProcedureBodyWhenValidationIsEnabled(): void { $sender = new TestXrpcRequestSender([]);
try { self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 123], options: new XrpcOptions(validateRequest: TRUE), ); static::fail('Expected input validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('input', $exception->phase); static::assertSame(0, $sender->requestCount); } }
public function testSkipsProcedureBodyValidationByDefault(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['id' => 'ok'])]);
$response = self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 123], );
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['id' => 'ok'], $response->data); static::assertSame('{"text":123}', (string) $sender->lastRequest?->getBody()); }
public function testSucceedsWithValidProcedureBodyWhenValidationIsEnabled(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['id' => 'valid'])]);
$response = self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 'hello'], options: new XrpcOptions(validateRequest: TRUE), );
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['id' => 'valid'], $response->data); }
public function testRejectsInvalidResponseBodyByDefault(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 123])]);
$this->expectException(LexiconValidationException::class);
self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); }
public function testSucceedsWithValidResponseBodyWhenValidationIsEnabled(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'hello'])]);
$response = self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]);
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['value' => 'hello'], $response->data); }
public function testRejectsInvalidLexDataByDefault(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['value' => 'hello', 'extra' => 1.5]), ]);
$this->expectException(LexiconValidationException::class);
self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); }
public function testRejectsErrorResponseWithInvalidLexDataByDefault(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse([ 'error' => 'TestError', 'message' => 'test-error-description', 'extra' => 1.5, ], 400), ]);
try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected an XRPC error.'); } catch (XrpcHttpException $exception) { static::assertSame(400, $exception->statusCode); static::assertSame('test-error-description', $exception->xrpcMessage); } }
public function testBinaryResponsesDoNotUseJsonValidation(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/octet-stream'], "\x01\x02\x03"), ]);
$response = self::client($sender, self::binaryQueryDefinition())->call('io.example.testBinaryQuery');
static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame("\x01\x02\x03", $response->body); }
public function testAppliesRequestAndResponseDefaults(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['foo' => 'foo-value'])]);
$response = self::client($sender, self::defaultsQueryDefinition())->call('io.example.testQueryWithDefaults');
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame('foo=foo-default', $sender->lastRequest?->getUri()->getQuery()); static::assertSame(['foo' => 'foo-value', 'bar' => 'bar-default'], $response->data); }
public function testRejectsInvalidBlobReference(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['blobRef' => ['$type' => 'blob']]), ]);
$this->expectException(LexiconValidationException::class);
self::client($sender, self::blobQueryDefinition())->call('io.example.testQueryGetBlobRef'); }
public function testRejectsBlobReferenceWithCborCid(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['blobRef' => self::blob(self::CBOR_CID, 'image/png', 1)]), ]);
$this->expectException(LexiconValidationException::class);
self::client($sender, self::blobQueryDefinition())->call('io.example.testQueryGetBlobRef'); }
public function testEnforcesBlobMimeTypeConstraintByDefault(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['blobRef' => self::blob(self::RAW_CID, 'invalid/mime', 10)]), ]);
try { self::client($sender, self::blobQueryDefinition())->call('io.example.testQueryGetBlobRef'); static::fail('Expected blob MIME validation to fail.'); } catch (LexiconValidationException $exception) { static::assertStringContainsString('MIME type', $exception->getMessage()); } }
public function testEnforcesBlobSizeConstraintByDefault(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['blobRef' => self::blob(self::RAW_CID, 'image/png', 100)]), ]);
try { self::client($sender, self::blobQueryDefinition())->call('io.example.testQueryGetBlobRef'); static::fail('Expected blob size validation to fail.'); } catch (LexiconValidationException $exception) { static::assertStringContainsString('10 bytes', $exception->getMessage()); } }
/** * Derived from the official no-output payload rule and its explicit * unexpected-JSON-object case. */ public function testDerivedNoOutputQueryAcceptsBinaryBody(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/octet-stream'], "\x01\x02\x03"), ]);
$response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery');
static::assertSame(200, $response->statusCode); }
/** * Derived from the official no-output payload rule and its explicit * unexpected-JSON-object case. */ public function testDerivedNoOutputQueryAcceptsJsonScalar(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], '"unexpected"'), ]);
$response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery');
static::assertSame(200, $response->statusCode); }
/** * Derived from the official no-output payload rule and its explicit * unexpected-JSON-object case. */ public function testDerivedNoOutputQueryAcceptsJsonList(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], '[1,2,3]'), ]);
$response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery');
static::assertSame(200, $response->statusCode); }
/** * Derived from the official no-output payload rule and the official * content-type inference case for a non-empty response. */ public function testDerivedNoOutputQueryAcceptsBodyWithoutContentType(): void { $sender = new TestXrpcRequestSender([new Response(200, [], "\x01\x02\x03")]);
$response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery');
static::assertSame(200, $response->statusCode); }
/** * @param array<string, mixed> $definition */ private static function client( XrpcRequestSenderInterface $sender, array $definition, ): LexiconXrpcClient { $factory = new HttpFactory(); $repository = new InMemoryLexiconRepository(); $repository->add(self::document($definition)); return new LexiconXrpcClient( new XrpcClient( $sender, $factory, $factory, 'https://service.example', new OutboundUrlPolicy(), ), new SchemaCompiler($repository), ); }
/** * @param array<string, mixed> $definition */ private static function document(array $definition): LexiconDocument { $result = new LexiconParser()->parse([ 'lexicon' => 1, 'id' => $definition['id'], 'defs' => ['main' => $definition['main']], ]); static::assertInstanceOf(LexiconDocument::class, $result->value, \implode('; ', $result->messages())); return $result->value; }
/** @return array{id: string, main: array<string, mixed>} */ private static function queryDefinition(): array { return [ 'id' => 'io.example.testQuery', 'main' => [ 'type' => 'query', 'parameters' => [ 'type' => 'params', 'properties' => ['limit' => ['type' => 'integer']], ], 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['value'], 'properties' => ['value' => ['type' => 'string']], ], ], 'errors' => [['name' => 'TestError']], ], ]; }
/** @return array{id: string, main: array<string, mixed>} */ private static function procedureDefinition(): array { return [ 'id' => 'io.example.testProcedure', 'main' => [ 'type' => 'procedure', 'input' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['text'], 'properties' => ['text' => ['type' => 'string']], ], ], 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['id'], 'properties' => ['id' => ['type' => 'string']], ], ], 'errors' => [['name' => 'ProcedureError']], ], ]; }
/** @return array{id: string, main: array<string, mixed>} */ private static function binaryQueryDefinition(): array { return [ 'id' => 'io.example.testBinaryQuery', 'main' => [ 'type' => 'query', 'output' => ['encoding' => 'application/octet-stream'], ], ]; }
/** @return array{id: string, main: array<string, mixed>} */ private static function binaryProcedureDefinition(): array { return [ 'id' => 'io.example.testBinaryProcedure', 'main' => [ 'type' => 'procedure', 'input' => ['encoding' => 'image/png'], 'output' => ['encoding' => 'application/octet-stream'], ], ]; }
/** @return array{id: string, main: array<string, mixed>} */ private static function noOutputQueryDefinition(): array { return [ 'id' => 'io.example.testNoOutputQuery', 'main' => ['type' => 'query'], ]; }
/** @return array{id: string, main: array<string, mixed>} */ private static function defaultsQueryDefinition(): array { return [ 'id' => 'io.example.testQueryWithDefaults', 'main' => [ 'type' => 'query', 'parameters' => [ 'type' => 'params', 'required' => ['foo'], 'properties' => [ 'foo' => ['type' => 'string', 'default' => 'foo-default'], ], ], 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['foo'], 'properties' => [ 'foo' => ['type' => 'string'], 'bar' => ['type' => 'string', 'default' => 'bar-default'], ], ], ], ], ]; }
/** @return array{id: string, main: array<string, mixed>} */ private static function blobQueryDefinition(): array { return [ 'id' => 'io.example.testQueryGetBlobRef', 'main' => [ 'type' => 'query', 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['blobRef'], 'properties' => [ 'blobRef' => [ 'type' => 'blob', 'accept' => ['image/png'], 'maxSize' => 10, ], ], ], ], ], ]; }
/** @return array<string, mixed> */ private static function blob(string $cid, string $mimeType, int $size): array { return [ '$type' => 'blob', 'ref' => ['$link' => $cid], 'mimeType' => $mimeType, 'size' => $size, ]; }
/** @param array<string, mixed> $data */ private static function jsonResponse(array $data, int $status = 200): Response { return new Response( $status, ['Content-Type' => 'application/json'], \json_encode($data, JSON_THROW_ON_ERROR), ); }
public function testQueryAppliesDeclaredDefaultsAndValidatesOutput(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], '{"name":"Alice","followers":1.0}'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'parameters' => [ 'type' => 'params', 'properties' => [ 'limit' => ['type' => 'integer', 'default' => 50], 'reverse' => ['type' => 'boolean', 'default' => FALSE], ], ], 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['name', 'followers'], 'properties' => [ 'name' => ['type' => 'string'], 'followers' => ['type' => 'integer'], ], ], ], 'errors' => [['name' => 'NotFound']], ]));
$response = $client->call('com.example.getProfile');
static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['name' => 'Alice', 'followers' => 1], $response->data); static::assertSame( 'https://service.example/xrpc/com.example.getProfile?limit=50&reverse=false', (string) $sender->lastRequest?->getUri(), ); }
public function testQueryRejectsInvalidUndeclaredParametersBeforeSending(): void { $sender = new TestXrpcRequestSender([]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'parameters' => [ 'type' => 'params', 'properties' => [], ], ]));
try { $client->call('com.example.getProfile', ['filter' => ['nested' => 'value']]); static::fail('Expected parameter validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('parameters', $exception->phase); static::assertSame(0, $sender->requestCount); } }
public function testProcedureValidatesJsonInputBeforeSending(): void { $sender = new TestXrpcRequestSender([]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'procedure', 'input' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['text'], 'properties' => ['text' => ['type' => 'string']], ], ], 'output' => ['encoding' => 'application/json'], ]));
try { $client->call( 'com.example.getProfile', input: ['text' => 1], options: new \Wotnak\Atproto\Client\XrpcOptions(validateRequest: TRUE), ); static::fail('Expected input validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('input', $exception->phase); static::assertSame(0, $sender->requestCount); } }
public function testRejectsJsonOutputThatViolatesLexicon(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], '{"count":"many"}'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['count'], 'properties' => ['count' => ['type' => 'integer']], ], ], ]));
try { $client->call('com.example.getProfile'); static::fail('Expected output validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('output', $exception->phase); static::assertSame(1, $sender->requestCount); } }
public function testRejectsResponseBodyWithoutDeclaredContentType(): void { $sender = new TestXrpcRequestSender([ new Response(200, [], '{"name":"Alice"}'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['name'], 'properties' => ['name' => ['type' => 'string']], ], ], ]));
$this->expectException(XrpcProtocolException::class); $this->expectExceptionMessage('without Content-Type');
$client->call('com.example.getProfile'); }
public function testAllowsEmptyResponseWithoutContentType(): void { $sender = new TestXrpcRequestSender([new Response(200)]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'output' => ['encoding' => 'application/json'], ]));
$response = $client->call('com.example.getProfile');
static::assertInstanceOf(XrpcResponse::class, $response); static::assertFalse($response->hasBody); }
public function testExecutesRawProcedureUsingDeclaredContentTypes(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'image/png'], 'png-bytes'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'procedure', 'input' => ['encoding' => 'application/octet-stream'], 'output' => ['encoding' => 'image/*'], ]));
$response = $client->call('com.example.getProfile', input: 'source-bytes');
static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame('png-bytes', $response->body); static::assertNotNull($sender->lastRequest); static::assertSame('application/octet-stream', $sender->lastRequest->getHeaderLine('Content-Type')); static::assertSame('image/*', $sender->lastRequest->getHeaderLine('Accept')); }
public function testExecutesRawProcedureWithCallerProvidedStream(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'image/png'], 'png-bytes'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'procedure', 'input' => ['encoding' => 'application/octet-stream'], 'output' => ['encoding' => 'image/*'], ])); $stream = new NoSeekStream(Utils::streamFor('source-bytes'));
$response = $client->call('com.example.getProfile', input: $stream);
static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame($stream, $sender->lastRequest?->getBody()); }
private static function existingClient(TestXrpcRequestSender $sender, LexiconDocument $document): LexiconXrpcClient { $factory = new HttpFactory(); $repository = new InMemoryLexiconRepository(); $repository->add($document); return new LexiconXrpcClient( new XrpcClient( $sender, $factory, $factory, 'https://service.example', new OutboundUrlPolicy(), ), new SchemaCompiler($repository), ); }
/** * @param array<string, mixed> $definition */ private static function existingDocument(array $definition): LexiconDocument { $result = new LexiconParser()->parse([ 'lexicon' => 1, 'id' => 'com.example.getProfile', 'defs' => ['main' => $definition], ]); static::assertInstanceOf(LexiconDocument::class, $result->value, \implode('; ', $result->messages())); return $result->value; }
}