Skip to content

Core\Test::request

Core\Test::request() sends one request to your own program and returns the response. It opens no network connection. Novis runs your program file again from its first line, and the Core\Request methods read the request you sent.

You give the HTTP method and the path, such as /orders/7. Options set headers, cookies, the client address clientIp and the scheme. The body options body, json, form and multipart are the same as in Core\Http\Client. mount and captures set a path prefix, such as /shop.

The result is a Core\Test\Response with status(), body(), json(), headers() and cookies(). It is the same response a real server sends. A request that throws gets 500, and error() returns the class and message of the error.

Good to know: the call returns only when all work the program started has ended. Code that handles such a request cannot call Core\Test::request again. A file sent with Core\Response::sendFile is read into the test's memory. If the file is larger than the memory the test may still use, the test ends with a memory error.

Parameters

  • $methodCore\Http\MethodThe HTTP method of the request, such as Core\Http\Method::Get.
  • $pathstringThe path of the request, such as /orders/7. A ? and the text after it are the query string.

Options

  • headersarray<string>optionalThe headers of the request, with the header name as the key. If you give no content-type or content-length, the length is set from body.
  • bodystring|bytes|Core\Http\PartoptionalThe body of the request, as a string, as bytes or as a Core\Http\Part. It is sent exactly as given, with the media type in contentType. If you give no body, the request has no body. An empty string is a body of length 0. Only one of body, json, form and multipart may be given. Two of them do not compile.
  • mountstringoptionalThe prefix the program is served under, such as /shop. Core\Request::mount() returns it, and Core\Router::url adds it in front of each link. The default is "", which means the root.
  • capturesarray<string>optionalThe parts of the prefix that the mount's pattern matched, in order. For the pattern /shops/{1} and mount: "/shops/acme", this is ["acme"]. Core\Request::mount()->captures() returns this list. The default is an empty list. You need mount to give captures.
  • cookiesarray<string>optionalThe cookies the request sends, with the cookie name as the key, such as ["sid" => "abc"]. Core\Request::cookie() reads them. Each call sends only the cookies you give it.
  • clientIpstringoptionalThe address of the client, such as "203.0.113.9". Core\Request::clientIp() returns it. It must be one IPv4 or IPv6 address, or the call throws a LogicError. If you give none, Core\Request::clientIp() returns null.
  • schemestringoptional"http" or "https". Core\Request::scheme() returns it. Any other value throws a LogicError. The default is "http".
  • jsonmixedoptionalThe value to send as application/json. Core\Request::json() reads it. A null value sends the JSON document null.
  • formarray<string>optionalThe fields to send as application/x-www-form-urlencoded, with the field name as the key. Core\Request::formField() reads them.
  • contentTypestringoptionalThe media type of body, sent as the Content-Type header. Giving it without body does not compile.
  • multipartarray<string|Core\Http\Part>optionalThe parts to send as multipart/form-data, with the field name as the key. A string is a form field, and a Core\Http\Part is a file. Core\Request::files() reads the files.

Return value

Returns Core\Test\Response. A Core\Test\Response. status() returns the status the program set, or 200 if it set none. body() returns the text the program wrote, and json() and jsonAs() decode it. header(), headers() and cookies() return the headers and cookies the program set. A path that no route matches still returns a response, because your program decides what to do with it. A body that is not text, such as a PDF file, also returns a response. For such a body, body(), json() and jsonAs() throw an error. A HEAD request gets no body, the same as from the server. If the program starts work with Core\Task::runAfterResponse, request returns only when that work has ended.

Errors

  • LogicErrorcaptures is not empty and mount is "". The root has no pattern, so it has no captures. captures is also an error when it is not a list.
  • RuntimeErrorThere is no program to answer, because the call is not in nvs test or nvs run. The call is also an error inside a request that request sent, because a request cannot send another request.

Changelog

VersionChange
0.0.5Core\Test::request has new options: clientIp, scheme, cookies, and the body options json, form, multipart and contentType of Core\Http\Client. The response is the one a server sends. A write from another site gets 403, and a HEAD request gets no body.
0.0.6A file that a response sends with Core\Response::sendFile counts toward the test's memory limit. A file that does not fit ends the test with a memory error.

Examples

Send one request

<?nvs
// Shows how to send one request to your own program and read the answer.
use Core\Http\Method;
use Core\Test;
// `Core\Test::request` runs this file again for the request. In that run,
// `Core\Env::context()` returns `Request`, and this part writes the answer.
if (Core\Env::context() == Core\Env::Context::Request) {
var $path = Core\Request::path();
echo 'Hello from ', $path;
} else {
// From the command line, this part sends the request and reads the answer.
var $response = Test::request(Method::Get, '/hello');
// The program set no status, so this prints `200`.
echo $response->status(), "\n";
// `body()` returns what the program wrote. This prints `Hello from /hello`.
echo $response->body(), "\n";
}
Output
200
Hello from /hello

A request with a header and a body

<?nvs
// Shows how to send a request with a header and a body.
use Core\Http\Method;
use Core\Test;
if (Core\Env::context() == Core\Env::Context::Request) {
// This part answers the request. It reads one header and the body,
// and sets the status to 201.
var $language = Core\Request::header('accept-language') ?? 'none';
var $body = Core\Request::body();
Core\Response::setStatus(201);
echo 'language ', $language, ', note ', $body;
} else {
// This part sends a `POST` request with one header and a body.
var $response = Test::request(Method::Post, '/notes', {
headers: ['Accept-Language' => 'de'],
body: 'Buy milk',
});
// This prints `201 language de, note Buy milk`.
echo $response->status(), ' ', $response->body(), "\n";
}
Output
201 language de, note Buy milk

Test a page and a missing page

<?nvs
// Shows how to test that a shop answers a product page, and answers 404 for a path it does not know.
use Core\Http\Method;
use Core\Test;
class Shop
{
#[Core\Route(path: '/products/{id}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function product(uint $id): string
{
return 'product';
}
}
if (Core\Env::context() == Core\Env::Context::Request) {
// This part answers each request. A path with no route gets the status 404.
?Core\Router\Match $matched = Core\Request::route();
if ($matched == null) {
Core\Response::setStatus(404);
echo 'not found';
} else {
echo 'product page';
}
} else {
// This part is the test. It sends two requests and checks each answer.
var $found = Test::request(Method::Get, '/products/7');
Test::assertEquals($found->status(), 200);
Test::assertSame($found->body(), 'product page');
var $missing = Test::request(Method::Get, '/basket/7');
Test::assertEquals($missing->status(), 404);
Test::assertSame($missing->body(), 'not found');
// Both checks passed, so this prints `both pages answer correctly`.
echo "both pages answer correctly\n";
}
Output
both pages answer correctly

A mount with a pattern

<?nvs
// Shows how to test a program that the server mounts through a pattern, one shop for each name.
use Core\Http\Method;
use Core\Test;
if (Core\Env::context() == Core\Env::Context::Request) {
// This part answers each request. The server mounts it at `/shops/{1}`,
// so `captures()[0]` is the name of the shop.
var $shop = Core\Request::mount()->captures()[0];
echo 'Welcome to ', $shop;
} else {
// `mount` is the prefix of this request. `captures` is the part of the
// prefix that `{1}` matched.
var $response = Test::request(Method::Get, '/', { mount: '/shops/blue', captures: ['blue'] });
// This prints `Welcome to blue`.
echo $response->body(), "\n";
// `captures` needs `mount`. This prints `captures need a mount`.
try {
Test::request(Method::Get, '/', { captures: ['blue'] });
} catch (LogicError $error) {
echo "captures need a mount\n";
}
}
Output
Welcome to blue
captures need a mount

A limit for each client address

<?nvs
// Shows how to test a limit of two requests per minute for each client address.
use Core\Http\Method;
use Core\Test;
if (Core\Env::context() == Core\Env::Context::Request) {
// This part answers each request. The limit counts the requests of each
// client address. The third request in one minute gets the status `429`.
var $address = Core\Request::clientIp() ?? 'unknown';
var $decision = Core\RateLimit::consumeLocally('search:' . $address, 2, 1m);
if (!$decision->isAllowed()) {
Core\Response::setStatus(429);
}
echo $address;
} else {
// `clientIp` is the address of the client that sends the request.
// This prints `200`, `200` and then `429`.
uint $try = 0;
while ($try < 3) {
echo Test::request(Method::Get, '/search', { clientIp: '203.0.113.9' })->status(), "\n";
$try = $try + 1;
}
// Another address has its own limit, so this prints `200`.
echo Test::request(Method::Get, '/search', { clientIp: '198.51.100.4' })->status(), "\n";
}
Output
200
200
429
200

A session cookie over https

<?nvs
// Shows how to test a login cookie that the browser sends only over `https`.
use Core\Http\Method;
use Core\Test;
if (Core\Env::context() == Core\Env::Context::Request) {
// This part answers each request. A cookie whose name starts with
// `__Host-` is read only from a request over `https`.
echo Core\Request::cookie('__Host-session') ?? 'not logged in';
} else {
// `cookies` sends the cookie, and `scheme` says the request came over `https`.
// This prints `user-7`.
var $secure = Test::request(Method::Get, '/account', {
scheme: 'https',
cookies: ['__Host-session' => 'user-7'],
});
echo $secure->body(), "\n";
// Without `scheme`, the request is `http`. This prints `not logged in`.
var $plain = Test::request(Method::Get, '/account', {
cookies: ['__Host-session' => 'user-7'],
});
echo $plain->body(), "\n";
}
Output
user-7
not logged in

Post json to an api

<?nvs
// Shows how to test an API that reads a JSON body and returns JSON.
use Core\Http\Method;
use Core\Test;
if (Core\Env::context() == Core\Env::Context::Request) {
// This part answers each request. It reads the order from the JSON body
// and returns the total price.
var $order = Core\Request::json() as array<mixed>;
int $total = ($order['price'] as int) * ($order['quantity'] as int);
Core\Response::setStatus(201);
Core\Response::sendJson(['total' => $total]);
} else {
// `json` encodes the value as the body and sets the `Content-Type` header.
var $response = Test::request(Method::Post, '/orders', {
json: ['price' => 250, 'quantity' => 3],
});
// This prints `201 750`.
var $answer = $response->json() as array<mixed>;
echo $response->status(), ' ', $answer['total'], "\n";
}
Output
201 750

Upload a file

<?nvs
// Shows how to test a form that uploads a file together with a text field.
use Core\Http\Method;
use Core\Http\Part;
use Core\Test;
if (Core\Env::context() == Core\Env::Context::Request) {
// This part answers each request. It writes the name, the type and the size
// of each uploaded file, and then the text field `title`.
foreach (Core\Request::files() as Core\Request\Part $part) {
echo $part->filename() ?? 'no name', ' ', $part->contentType(), ' ';
echo Core\Bytes::length($part->readAll({ max: 100000 })), " bytes\n";
}
echo 'title: ', Core\Request::formField('title') ?? 'none';
} else {
// `multipart` sends a form with a file, the same way a browser does.
// `Part::bytes` creates the file from its content, its name and its type.
var $response = Test::request(Method::Post, '/invoices', {
multipart: [
'title' => 'March invoice',
'scan' => Part::bytes('%PDF-1.7 invoice', 'march.pdf', { contentType: 'application/pdf' }),
],
});
// This prints `march.pdf application/pdf 16 bytes` and `title: March invoice`.
echo $response->body(), "\n";
}
Output
march.pdf application/pdf 16 bytes
title: March invoice

A write from another site

<?nvs
// Shows that a form post from another site gets the status `403`, the same as on the server.
use Core\Http\Method;
use Core\Test;
if (Core\Env::context() == Core\Env::Context::Request) {
// This part answers each request. It saves the comment.
echo 'saved';
} else {
// The browser sends the `origin` header. It names the site that sent the form.
// Here it is the same site, so the program saves the comment. This prints `200 saved`.
var $same = Test::request(Method::Post, '/comments', {
scheme: 'https',
headers: ['host' => 'blog.example.com', 'origin' => 'https://blog.example.com'],
form: ['text' => 'Nice post'],
});
echo $same->status(), ' ', $same->body(), "\n";
// Here the form comes from another site. The program does not run,
// and the response has no body. This prints `403 ''`.
var $forged = Test::request(Method::Post, '/comments', {
scheme: 'https',
headers: ['host' => 'blog.example.com', 'origin' => 'https://other.example.com'],
form: ['text' => 'Buy cheap watches'],
});
echo $forged->status(), " '", $forged->body(), "'\n";
}
Output
200 saved
403 ''