Skip to content

Core\Test::answerHttp

Core\Test::answerHttp(string $url, uint $status, {…}): voidCore\Test::answerHttp(
    string $url,
    uint $status,
    {…},
): void

Core\Test::answerHttp() gives a fixed reply to the web calls your program makes with Core\Http\Client. You give it a URL, a status such as 200 or 404, and the body of the reply. An answer can have json or body, but not both.

After the first call to answerHttp, the program makes no network connections. A call that matches no answer throws a LogicError. So a test never reaches a real service by mistake.

A URL that ends in * matches every URL that starts with the text before it. An exact URL wins, and then the longest prefix wins.

You can call answerHttp in a test and in a command-line program. In server code, it throws a LogicError. Server code is a request, a connection, a scheduled task or a queued job. So test code left in your program cannot fake a real service. There is one exception: a request that a test sends with Core\Test::request may call it.

The examples below show a reply with JSON, which answer a URL gets, and a client that handles error statuses.

Parameters

  • $urlstringThe URL this reply is for. Give the whole URL, or a prefix that ends in *. A prefix matches every URL that starts with the text before the *. Each call's URL is compared with this text, and no host is looked up.
  • $statusuintThe status code of the reply. It has three digits, from 100 to 999.

Options

  • jsonmixedoptionalA value that the reply sends as a JSON document. It is written exactly as Core\Json::encode writes it. The reply has the content type application/json, unless headers sets a content type.
  • bodystring|bytesoptionalThe body of a reply that is not JSON. It can be text, or the bytes of a reply that is not text. Core\Http\Response::bytes reads such a body, and ::text throws an error for it. Give body or json, not both.
  • headersarray<string|array<string>>optionalThe headers of the reply, with the header name as the key. Each value is a string, or an array of strings. With an array, the reply has that header once for each string, and Core\Http\Response::headers returns them as an array. Upper and lower case do not matter in a header name.
  • tlsCore\Http\TlsInfooptionalThe TLS session the reply reports. A TLS session is the details of an encrypted https:// connection. Build one with Core\Test::tlsSession. Core\Http\Response::tls returns it for every call this answer serves. Without it, tls() returns null.

Return value

Returns void. Nothing. Each call adds one more reply, so a test can give a reply for each call it makes. An exact URL wins over a prefix, and the longest prefix wins among prefixes.

Errors

  • LogicErrorThe call gives both json and body, which are two ways to write one body. Or the status is not from 100 to 999. Or the call gives a tls session for an http:// URL, which has no TLS. Or the call runs in a server, such as in a request, a connection, a scheduled task or a queued job. There is one exception: a request that a test sends with Core\Test::request may call it. Tests and command-line programs may always call it.

Changelog

VersionChange
0.0.6Core\Test::answerHttp, Core\Test::answerSocket, Core\Test::tlsSession and Core\Test::scriptAnswers throw a LogicError in a request, a connection, a scheduled task and a queued job. They work in a test, and in a request or a program that a test starts. They also work in a command-line program.

Examples

A reply with json

<?nvs
// Shows how to give a program a fixed reply from a web service. After the first
// `Core\Test::answerHttp` call, the program makes no network connections.
#[Core\Json\Derive]
class Weather
{
public int $celsius;
public int $humidity;
public function constructor(int $celsius, int $humidity)
{
$this->celsius = $celsius;
$this->humidity = $humidity;
}
}
// `json` is the body of the reply. The reply also gets the header
// `content-type: application/json`.
Core\Test::answerHttp('https://weather.example.com/today', 200, {
json: ['celsius' => 21, 'humidity' => 40],
});
Core\Http\Response $response = Core\Http\Client::get('https://weather.example.com/today');
// This prints `200`.
echo $response->status(), "\n";
// `jsonAs<Weather>` reads the body into a `Weather`. This prints `21 C, 40 %`.
Weather $weather = $response->jsonAs<Weather>();
echo $weather->celsius, ' C, ', $weather->humidity, " %\n";
Output
200
21 C, 40 %

Which answer a url gets

<?nvs
// Shows which answer a call gets when several URLs could match it.
use Core\Http\Client;
use Core\Test;
// A URL that ends in `*` answers every URL that starts with the text before it.
Test::answerHttp('https://shop.example.com/*', 503, { body: 'down' });
Test::answerHttp('https://shop.example.com/products/*', 404, { body: 'no such product' });
Test::answerHttp('https://shop.example.com/products/7', 200, { body: 'Blue mug' });
// The whole URL matches the third answer. An exact match always wins.
// This prints `200`.
echo Client::get('https://shop.example.com/products/7')->status(), "\n";
// Two prefixes match. The longer one wins, so this prints `404`.
echo Client::get('https://shop.example.com/products/8')->status(), "\n";
// Only the first prefix matches. This prints `503`.
echo Client::get('https://shop.example.com/cart')->status(), "\n";
// No answer matches this URL, so the call throws a `LogicError`.
// The program does not use the network for it.
try {
Client::get('https://api.example.com/users');
} catch (LogicError $error) {
echo "LogicError\n";
}
Output
200
404
503
LogicError

A client that handles errors

<?nvs
// Shows how to test that your code handles every reply a service can give.
// This includes errors that are hard to get from the real service.
use Core\Http\Client;
use Core\Http\Response;
use Core\Test;
#[Core\Json\Derive]
class Stock
{
public int $count;
public function constructor(int $count)
{
$this->count = $count;
}
}
class StockClient
{
public static function describe(string $sku): string
{
Response $response = Client::get('https://stock.example.com/items/' . $sku);
if ($response->status() == 404) {
return $sku . ': unknown item';
}
if ($response->status() >= 500) {
return $sku . ': try again later';
}
Stock $stock = $response->jsonAs<Stock>();
return $sku . ': ' . $stock->count . ' in stock';
}
}
// One answer for each case the code must handle.
Test::answerHttp('https://stock.example.com/items/mug', 200, { json: ['count' => 12] });
Test::answerHttp('https://stock.example.com/items/lamp', 404);
Test::answerHttp('https://stock.example.com/items/desk', 503);
// This prints one line for each item.
array<string> $skus = ['mug', 'lamp', 'desk'];
foreach ($skus as string $sku) {
echo StockClient::describe($sku), "\n";
}
Output
mug: 12 in stock
lamp: unknown item
desk: try again later