Testing an API client without the network
The Puzzler PHP SDK keeps its cURL calls in one protected method that tests can replace, so signing and error handling can be checked with no credentials and no network.
The offline test run for the Puzzler PHP SDK ends in OK, 27 tests and 57 assertions, without a single credential or network call. The tests check signing, error handling and request bodies on every PHP version from 7.4 to 8.4.
The SDK is my small, unofficial client for the REST API that Puzzler Media uses to supply crosswords, sudoku and other puzzles to publishers. Every call needs a client ID, an API key and a secret key, issued by Puzzler, which makes it awkward to test. I keep the cURL calls in one protected method that the tests replace, and everything the SDK decides happens on either side of it.
Signing a request
Every request carries four headers of its own: X-Client-Id, X-Api-Key, X-Timestamp and X-Signature. The signature is a SHA-256 hash of the API key, client ID, a Unix timestamp and the secret key, joined with underscores and Base64-encoded. This is from src/Http/HttpClient.php:
private function generateSignature($timestamp)
{
$message = $this->apiKey . '_' . $this->clientId . '_' . $timestamp . '_' . $this->secretKey;
$hash = hash('sha256', $message, true);
return base64_encode($hash);
}
The secret key itself is never sent, only the hash it went into. request() calls time() on every request, so even a client that lives for hours signs each call afresh. A signature is good for five minutes, which means a server whose clock has drifted gets 401 responses with correct credentials; the README’s troubleshooting notes cover that.
One seam
request() does everything that belongs to the SDK: it builds the URL, signs the headers, encodes the body and reads the response. The transfer itself is in send():
list($response, $httpCode, $contentType, $error) = $this->send($method, $url, $headers, $jsonBody);
if ($error) {
throw new PuzzlerException('cURL error: ' . $error);
}
return $this->handleResponse($response, $httpCode, $contentType);
send() makes the cURL calls and returns four values: the body, the status code, the content type and cURL’s error message, if there was one. Apart from attaching a body when there is one, it makes no decisions, and replacing it in tests loses very little. Callers never see it, because it’s protected. The SDK needs nothing but the cURL and JSON extensions.
A fake transport
The tests in tests/Unit/Http/HttpClientMockedTest.php replace send() with an anonymous subclass. It records every call and returns a canned reply:
return new class('cid', 'key', 'secret', 'https://api.example.com/', $reply) extends HttpClient {
public $calls = [];
private $reply;
public function __construct($c, $k, $s, $u, array $reply)
{
parent::__construct($c, $k, $s, $u);
$this->reply = $reply;
}
protected function send($method, $url, array $headers, $jsonBody)
{
$this->calls[] = compact('method', 'url', 'headers', 'jsonBody');
return $this->reply;
}
};
The fake’s base URL ends in a slash, and the first test checks that posting to /api/Puzzle/collect still gives https://api.example.com/api/Puzzle/collect, with one slash between them, and that the body is {"a":1}.
The signature check is the part I find most useful. The test can’t control time(). It notes the time before and after the call and checks that the timestamp falls between them. Then it builds the signature itself, from the literal values, rather than calling the SDK’s private method:
$expected = base64_encode(hash('sha256', 'key_cid_' . $headers['X-Timestamp'] . '_secret', true));
$this->assertSame($expected, $headers['X-Signature']);
If someone swapped the order of the fields, or dropped the true that makes hash() return raw bytes, the SDK would still sign every request consistently, and the API would refuse every one. This test catches it first.
Errors that say what happened
handleResponse() treats 200 as the only success. A JSON content type is decoded, and JSON that doesn’t parse throws rather than coming back as null. Anything else comes back as the raw string. Every other status becomes an exception:
switch ($httpCode) {
case 400:
throw new BadRequestException('Bad request', $httpCode, $response);
case 401:
throw new AuthenticationException('Authentication failed', $httpCode, $response);
// ...404, 405, then 500 and 502 as ServerException...
default:
throw new PuzzlerException('Unexpected response', $httpCode, $response);
}
They all extend PuzzlerException, so one catch covers the lot. The status becomes the exception’s code, and the raw body, with the API’s own explanation in it, is kept for getResponseBody(). Any status not in the list, another 2xx included, gets the base class.
A data provider feeds the fake 400, 401, 404, 405, 500, 502 and 418, and checks the class, the code and the body for each. 418 stands in for anything unexpected. Two more tests cover a body that claims to be JSON and isn’t, and a cURL failure, which surfaces as a PuzzlerException whose message starts with cURL error:.
The body collect() sends
The puzzle and health clients take an HttpClient in their constructors, and the same fake works for them. With no filters, the API expects {"model":{}}. PHP’s json_encode() turns an empty array into [], which is why PuzzleClient sends an empty object. Two tests run collect() over a fake of their own and check the exact JSON: {"model":{}} with no filters, and the filters on their own, unwrapped, otherwise.
The live tests
The integration tests run against the real API, and they skip themselves when PUZZLER_CLIENT_ID, PUZZLER_API_KEY or PUZZLER_SECRET_KEY isn’t set. The test for bad credentials skips too: a run without credentials makes no network calls at all. Without credentials the suite is 41 tests: the 27 offline ones pass and the 14 live ones skip. PHPUnit is set to fail on risky tests and on warnings.
GitHub Actions runs the suite on PHP 7.4, 8.0, 8.1, 8.2, 8.3 and 8.4, after composer validate --strict. No credentials are set there: CI checks signing and error handling on every version, and the live tests only run where credentials are.
Using it in a project
composer require tomgould/puzzlerphpsdk
use TomGould\PuzzlerPHPSDK\PuzzlerClient;
use TomGould\PuzzlerPHPSDK\Exception\AuthenticationException;
use TomGould\PuzzlerPHPSDK\Exception\PuzzlerException;
$client = new PuzzlerClient($clientId, $apiKey, $secretKey);
try {
$crosswords = $client->puzzle()->collect([
'puzzleDate' => date('Y-m-d'),
'puzzleTypes' => ['XW'],
]);
} catch (AuthenticationException $e) {
// Wrong credentials, or a clock more than five minutes out.
} catch (PuzzlerException $e) {
echo $e->getCode(), ' ', $e->getResponseBody(), PHP_EOL;
}
To run the offline tests from a clone:
git clone https://github.com/tomgould/PuzzlerPHPSDK.git
cd PuzzlerPHPSDK
composer install
vendor/bin/phpunit --testsuite Unit
Anything beyond the offline tests needs your own credentials from Puzzler Media.
Featured projects
-
Apple News API
Publish articles and live coverage to Apple News from PHP, with the whole Apple News Format built from objects.
-
GitHub Auditor
Health, access and activity reports for more GitHub and Bitbucket repositories than you can keep in your head.
-
PrintMD
Markdown in, and a designed PDF, Word or PowerPoint file out. Its PDF service runs on your own computer.
-
Where Should I Live
Which city would leave you best off? Cities ranked by take-home pay, living costs, visas and the way you live.
-
Solar Calendar
Thirteen months of exactly four weeks, with the year starting on the first Monday on or after the spring equinox.
Latest writing
-
Many sessions at once, and what still needs me
Fifteen coding-agent sessions across two Linux boxes, one session that watches the rest, what it may answer for me, what it never may, and why a yes it passes on gets checked against what I typed.
-
61 public repos of agent tooling, none installed, six ideas kept
One author, 61 public repositories of coding-agent tooling: what I checked before any of it got near my Linux boxes, why none of it was installed, and the six ideas I built my own way.
-
Rules a coding agent cannot talk its way round
The hook that reads every command a coding agent wants to run on my Linux boxes: what it refuses, the 27 proofs that its tests fail when a rule is taken out, and the four lines every report opens with.
-
Dozens of repos, one person
46 repositories and two Linux boxes with nobody else on them: the diary, the decision table, the rebuild guide and the job that keeps both sets of clones in step.