180 lines
8.6 KiB
PHP
180 lines
8.6 KiB
PHP
<?php
|
|
// Offline tests in plain PHP (no PHPUnit, no network): php tests/run.php
|
|
// A fake transport stands in for the API and keeps every request it receives.
|
|
|
|
require __DIR__ . '/../autoload.php';
|
|
|
|
use MozOut\Whois\Client;
|
|
use MozOut\Whois\Exception\AuthenticationException;
|
|
use MozOut\Whois\Exception\RateLimitException;
|
|
use MozOut\Whois\Exception\ValidationException;
|
|
use MozOut\Whois\Exception\WhoisException;
|
|
|
|
$failures = 0;
|
|
$count = 0;
|
|
|
|
function check(string $name, bool $ok): void
|
|
{
|
|
global $failures, $count;
|
|
$count++;
|
|
if ($ok) {
|
|
echo "ok $name\n";
|
|
} else {
|
|
$failures++;
|
|
echo "FAIL $name\n";
|
|
}
|
|
}
|
|
|
|
function fake(array $responses, array &$log): callable
|
|
{
|
|
return static function (string $method, string $url, array $headers, int $timeout) use (&$responses, &$log) {
|
|
$log[] = ['method' => $method, 'url' => $url, 'headers' => $headers];
|
|
$next = array_shift($responses);
|
|
if ($next instanceof \Throwable) {
|
|
throw $next;
|
|
}
|
|
return $next;
|
|
};
|
|
}
|
|
|
|
function json_response(int $status, array $body, array $headers = []): array
|
|
{
|
|
return [$status, $headers, json_encode($body)];
|
|
}
|
|
|
|
putenv(Client::KEY_ENV); // no key from the environment in these tests
|
|
|
|
$registered = ['data' => [
|
|
'domain' => 'example.com', 'extension' => '.com', 'available' => false, 'status' => 'registered',
|
|
'registration' => [
|
|
'created' => '2022-05-09T14:32:00+02:00', 'expires' => '2027-05-09T14:32:00+02:00',
|
|
'domain_status' => ['active', 'clientTransferProhibited'], 'nameservers' => ['ns1.example.com', 'ns2.example.com'],
|
|
'days_until_expiry' => 165, 'dnssec' => 'unsigned',
|
|
],
|
|
'price' => ['currency' => 'USD', 'register' => 2500.0, 'renew' => 2500.0, 'transfer' => 2500.0, 'premium' => false,
|
|
'prices' => [['years' => 1, 'register' => 2500.0, 'renew' => 2500.0], ['years' => 2, 'register' => 5000.0, 'renew' => 5000.0]]],
|
|
'transfer_url' => 'https://www.example.com/transfer?d=example.com',
|
|
'alternatives' => [['domain' => 'example.net', 'price' => '2,500.00 USD', 'register_url' => 'https://www.example.com/r?d=example.net']],
|
|
], 'meta' => []];
|
|
|
|
// 1. A registered domain, without a key.
|
|
$log = [];
|
|
$c = new Client(['transport' => fake([json_response(200, $registered, ['X-RateLimit-Limit' => '60', 'X-RateLimit-Remaining' => '59'])], $log)]);
|
|
$r = $c->lookup(' https://Example.com/page?x=1 ');
|
|
check('URL of a single lookup', $log[0]['url'] === Client::API_URL . '/v1/whois/example.com');
|
|
check('no Authorization header without a key', !preg_grep('/^Authorization:/i', $log[0]['headers']));
|
|
check('User-Agent sent', (bool) preg_grep('/^User-Agent: .*php-whois\/' . preg_quote(Client::VERSION, '/') . '/', $log[0]['headers']));
|
|
check('registered', $r->isRegistered() && !$r->isAvailable() && $r->status() === 'registered');
|
|
check('expiry date', $r->expiresAt() instanceof \DateTimeImmutable && $r->expiresAt()->format('Y-m-d') === '2027-05-09');
|
|
check('days until expiry', $r->daysUntilExpiry() === 165);
|
|
check('nameservers', $r->nameservers() === ['ns1.example.com', 'ns2.example.com']);
|
|
check('domain status', in_array('clientTransferProhibited', $r->domainStatus(), true));
|
|
check('prices per year', $r->registerPrice() === 2500.0 && $r->registerPrice(2) === 5000.0 && $r->registerPrice(9) === null);
|
|
check('transfer price and currency', $r->transferPrice() === 2500.0 && $r->currency() === 'USD');
|
|
check('alternatives', count($r->alternatives()) === 1 && $r->alternatives()[0]['domain'] === 'example.net');
|
|
check('transfer URL', $r->transferUrl() !== null && $r->registerUrl() === null);
|
|
check('rate limit headers', $c->lastRateLimit() === ['limit' => 60, 'remaining' => 59]);
|
|
|
|
// 2. With a key, currency and language.
|
|
$log = [];
|
|
$c = new Client(['api_key' => 'sandbox_test', 'currency' => 'usd', 'language' => 'pt', 'transport' => fake([
|
|
json_response(200, ['data' => ['domain' => 'free-name.com', 'available' => true, 'status' => 'available',
|
|
'register_url' => 'https://www.example.com/r', 'price' => ['currency' => 'USD', 'register' => 41.68, 'premium' => true]], 'meta' => []]),
|
|
], $log)]);
|
|
$r = $c->lookup('free-name.com');
|
|
check('Bearer key sent', (bool) preg_grep('/^Authorization: Bearer sandbox_test$/', $log[0]['headers']));
|
|
check('currency and language in the query', strpos($log[0]['url'], '?currency=USD&language=pt') !== false);
|
|
check('available', $r->isAvailable() && $r->registerUrl() === 'https://www.example.com/r');
|
|
check('premium and 1-year price without prices list', $r->isPremium() && $r->registerPrice() === 41.68);
|
|
|
|
// 3. The key from the environment.
|
|
putenv(Client::KEY_ENV . '=sandbox_from_env');
|
|
$log = [];
|
|
$c = new Client(['transport' => fake([json_response(200, $registered)], $log)]);
|
|
$c->lookup('example.com');
|
|
check('key read from the environment', $c->hasApiKey() && (bool) preg_grep('/Bearer sandbox_from_env$/', $log[0]['headers']));
|
|
putenv(Client::KEY_ENV);
|
|
|
|
// 4. Several domains.
|
|
$log = [];
|
|
$c = new Client(['transport' => fake([json_response(200, ['data' => [
|
|
['domain' => 'example.com', 'available' => true, 'status' => 'available'],
|
|
['domain' => 'example.xyz', 'status' => 'error', 'error' => ['code' => 'validation_failed', 'message' => 'This extension is not available.',
|
|
'details' => ['field' => 'domain', 'reason' => 'extension_not_supported']]],
|
|
], 'meta' => ['count' => 2]])], $log)]);
|
|
$many = $c->lookupMany(['example.com', 'EXAMPLE.xyz', 'example.com']);
|
|
check('several: one request, names joined', count($log) === 1 && strpos($log[0]['url'], '/v1/whois?domains=example.com%2Cexample.xyz') !== false);
|
|
check('several: order and keys', array_keys($many) === ['example.com', 'example.xyz']);
|
|
check('several: error entry', $many['example.xyz']->isError() && $many['example.xyz']->error()['details']['reason'] === 'extension_not_supported');
|
|
$tooMany = false;
|
|
try {
|
|
$c->lookupMany(array_map(static function ($i) { return "n$i.com"; }, range(1, 11)));
|
|
} catch (\InvalidArgumentException $e) {
|
|
$tooMany = true;
|
|
}
|
|
check('several: more than 10 refused before any request', $tooMany && count($log) === 1);
|
|
|
|
// 5. Errors.
|
|
$error = static function (int $status, string $code, array $details = [], array $headers = []) {
|
|
return json_response($status, ['error' => ['code' => $code, 'message' => 'm', 'correlation_id' => 'cid', 'details' => $details]], $headers);
|
|
};
|
|
$log = [];
|
|
$c = new Client(['transport' => fake([
|
|
$error(422, 'validation_failed', ['reason' => 'extension_not_supported']),
|
|
$error(429, 'rate_limited', [], ['Retry-After' => '120']),
|
|
$error(401, 'unauthorized'),
|
|
$error(503, 'disabled'), $error(503, 'disabled'),
|
|
], $log)]);
|
|
try {
|
|
$c->lookup('example.xyz');
|
|
check('422 throws', false);
|
|
} catch (ValidationException $e) {
|
|
check('422 throws ValidationException with reason', $e->getReason() === 'extension_not_supported' && $e->getHttpStatus() === 422 && $e->getCorrelationId() === 'cid');
|
|
}
|
|
try {
|
|
$c->lookup('example.com');
|
|
check('429 throws', false);
|
|
} catch (RateLimitException $e) {
|
|
check('429 throws RateLimitException with retry after from the header', $e->getRetryAfter() === 120);
|
|
}
|
|
try {
|
|
$c->lookup('example.com');
|
|
check('401 throws', false);
|
|
} catch (AuthenticationException $e) {
|
|
check('401 throws AuthenticationException', $e->getErrorCode() === 'unauthorized');
|
|
check('401 message says the key is not valid', strpos($e->getMessage(), 'The API key is not valid') === 0 && $e->getHttpStatus() === 401);
|
|
}
|
|
$log403 = [];
|
|
$c403 = new Client(['api_key' => 'prod_x', 'transport' => fake([$error(403, 'ip_not_allowed')], $log403)]);
|
|
try {
|
|
$c403->lookup('example.com');
|
|
check('403 throws', false);
|
|
} catch (AuthenticationException $e) {
|
|
check('403 throws AuthenticationException', $e->getErrorCode() === 'ip_not_allowed' && strpos($e->getMessage(), 'refused the key') !== false);
|
|
}
|
|
try {
|
|
$c->lookup('example.com');
|
|
check('503 throws', false);
|
|
} catch (WhoisException $e) {
|
|
check('5xx retried once, then WhoisException', $e->getHttpStatus() === 503 && count($log) === 5);
|
|
}
|
|
|
|
// 6. Network failure, then success.
|
|
$log = [];
|
|
$c = new Client(['transport' => fake([new WhoisException('down', 'network_error'), json_response(200, $registered)], $log)]);
|
|
check('network failure retried', $c->lookup('example.com')->isRegistered() && count($log) === 2);
|
|
|
|
// 7. Invalid names never reach the API.
|
|
$log = [];
|
|
$c = new Client(['transport' => fake([], $log)]);
|
|
foreach (['', 'example', ' ', 'http://'] as $bad) {
|
|
try {
|
|
$c->lookup($bad);
|
|
check("invalid name '$bad' refused", false);
|
|
} catch (\InvalidArgumentException $e) {
|
|
check("invalid name '$bad' refused", count($log) === 0);
|
|
}
|
|
}
|
|
|
|
echo "\n$count checks, $failures failed.\n";
|
|
exit($failures ? 1 : 0);
|