Writing and running tests
A test is a method with the attribute #[Test]. You can write it in any class. nvs test file.nvs
runs every test in the program.
A test is a method with #[Test]
A test is a method with #[Test] written above it.
Any class in your program may have tests. There is no base class to extend, and no name a test class or a test method has to have. You write use Core\Test; once, put #[Test] above a method, and run nvs test yourfile.nvs. The compiler collects every #[Test] method while it checks your program.
A test method is public, is not static, and returns void. A method that breaks one of those three rules does not compile. A test that checks nothing fails, so every test calls at least one assertion.
Good to know: nvs run on the same file runs your program and runs no test.
A test beside the code it checks
<?nvs// Shows how to write a test. `#[Test]` above a method makes that method a// test. `nvs test` on this file runs every `#[Test]` method it finds.
use Core\Test;
class Slug{ public static function of(string $title): string { return Core\Str::replace(Core\Str::lower($title), ' ', '-'); }}
class SlugTest{ #[Test] public function spacesBecomeDashes(): void { Test::assertSame(Slug::of('Hello World'), 'hello-world'); }
#[Test] public function capitalsBecomeSmallLetters(): void { Test::assertSame(Slug::of('ORDER Form'), 'order-form'); }}
// `nvs run` runs the program and leaves the tests alone.// This prints `hello-world`.echo Slug::of('Hello World'), "\n";hello-worldA class that holds its own tests
<?nvs// Shows that any class may have tests. There is no base class to extend and no// name a test class must have, so a small class can keep its tests inside it.
use Core\Test;
class Basket{ public static function shippingCents(int $totalCents): int { if ($totalCents >= 5000) { return 0; } return 499; }
#[Test] public function aSmallBasketPaysForShipping(): void { Test::assertSame(Basket::shippingCents(1200), 499); }
#[Test] public function theLimitItselfShipsFree(): void { Test::assertSame(Basket::shippingCents(5000), 0); }}
// This prints 499 and then 0.echo Basket::shippingCents(1200), "\n";echo Basket::shippingCents(9900), "\n";4990One marked method for each rule
<?nvs// Shows a test class written the way you would write one at work. Every rule// gets its own `#[Test]` method, and the name of the method says what the rule// is. A method without `#[Test]` is an ordinary method.
use Core\Test;
class PasswordPolicy{ public static function problem(string $password): string { if (Core\Str::length($password) < 12) { return 'too short'; } if (Core\Str::lower($password) == $password) { return 'needs a capital letter'; } return 'none'; }}
class PasswordPolicyTest{ #[Test] public function aShortPasswordIsRefused(): void { Test::assertSame($this->problemFor('Short1'), 'too short'); }
#[Test] public function aPasswordWithoutCapitalsIsRefused(): void { Test::assertSame($this->problemFor('correcthorsebattery'), 'needs a capital letter'); }
#[Test] public function aLongPasswordWithACapitalLetterPasses(): void { Test::assertSame($this->problemFor('CorrectHorseBattery'), 'none'); }
// This method has no `#[Test]`, so `nvs test` does not run it. The tests // above call it like any other method. private function problemFor(string $password): string { return PasswordPolicy::problem($password); }}
// This prints `too short` and then `none`.echo PasswordPolicy::problem('Short1'), "\n";echo PasswordPolicy::problem('CorrectHorseBattery'), "\n";too shortnoneThe report of a run
<?nvs// Shows the report `nvs test` prints for a test that passes, one that is// skipped and one that fails.// proof: test// proof: exit 1
use Core\Test;
final class ArithmeticTest{ // The report shows `✓` for this test. #[Test] public function additionCommutes(): void { Test::assertSame(2 + 3, 3 + 2); }
// The report shows `-` for this test, and prints the reason. #[Test(skip: 'division is not written yet')] public function divisionRounds(): void { Test::assertSame(7 / 2, 4.0); }
// The report shows `✗` for this test, and prints both values. #[Test] public function thisOneFails(): void { Test::assertSame(2 + 2, 5); }}
// `nvs test` does not run this line.echo 'this line runs only under nvs run', "\n"; ArithmeticTest ✓ additionCommutes - divisionRounds skipped: division is not written yet ✗ thisOneFails Core\Test::assertSame failed: `$actual` is 4, `$expected` is 5
1 failed, 1 passed, 1 skipped, 0 flakyA static test does not compile
<?nvs// Shows that a test method cannot be `static`. The runner calls each test on a// new object of its class.// proof: compile-error
use Core\Test;
final class ShapeTest{ #[Test] public static function aTestIsNotStatic(): void { Test::assertTrue(true); }}error[E0733]: the `#[Test]` method `aTestIsNotStatic` is `static` --> 05-a-static-test-does-not-compile.nvs:11:28 |11 | public static function aTestIsNotStatic(): void | ^^^^^^^^^^^^^^^^ is `static` = help: a test is run against a fresh instance, so drop the `static`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
#[Test] and #[Core\Test] are the same attribute. use Core\Test; makes the short name work for the attribute and for the assertions, such as Test::assertSame.
A #[Test] method that is static, private or protected, or that returns a value, is E0733. The message names the rule the method breaks.
A test method may declare parameters. A fixture or a data row fills each one. A parameter that nothing fills is E0736.
The report lists the classes in name order. Inside a class, the tests run in the order they are written. Each test line starts with a mark: ✓ passed, ✗ failed, - skipped and ! flaky.
A test that calls no assertion fails with the message it asserted nothing. To test that a call finishes without an error, write Core\Test::assertDoesNotThrow.
A test that throws an error fails, and the error's message is printed under the test.
What a test prints with echo is not shown when the test passes. When the test fails, its output is printed under the failure, after output:. nvs test --show-output prints the output of every test.
A #[Test] method in an abstract class runs only in each class that extends it. A #[Test] on a method of an interface does nothing.
A file with no #[Test] method runs no test. The summary is 0 failed, 0 passed, 0 skipped, 0 flaky, and the exit status is 0.
nvs run on a file with tests runs the statements outside the classes and runs no test.
Each test starts with new objects
Every test runs on its own, and shares no stored value with any other test.
A static value that one test writes is back at its declared starting value in the next test. The test class is built again for every test, so a property one test changes starts fresh in the next one. The constructor of a test class is where you prepare what a test needs. It runs once before every test body.
A test class constructor takes no parameters. One that takes a parameter is reported as that test failing. Values that a test method itself needs come from a fixture or from a data row.
The examples below show a static that starts fresh in each test, a constructor that prepares the same starting point for every test, and two tests that register the same address.
A static starts fresh in each test
<?nvs// Shows that one test cannot change what another test sees. A `static` value// written by one test is back at its declared value in the next test.
use Core\Test;
class Counter{ public static int $hits = 0;}
class CounterTest{ #[Test] public function theFirstTestWrites(): void { Counter::$hits = Counter::$hits + 1; Test::assertSame(Counter::$hits, 1); }
#[Test] public function theSecondTestStartsFresh(): void { // The test above added one. This test reads `0` again. Test::assertSame(Counter::$hits, 0); }}
// Outside a test there is one counter for the whole program, so it keeps both// of these. This prints `2`.Counter::$hits = Counter::$hits + 1;Counter::$hits = Counter::$hits + 1;echo Counter::$hits, "\n";2The constructor prepares each test
<?nvs// Shows the constructor of a test class. It runs once before every test, so// every test starts from the same prepared state.
use Core\Test;
class Basket{ public array<string> $items;
public function constructor() { $this->items = []; }
public function add(string $item): void { $this->items[] = $item; }}
class BasketTest{ private Basket $basket;
// This runs again before each test below, so each test gets a new basket. public function constructor() { $this->basket = new Basket(); $this->basket->add('bread'); }
#[Test] public function itStartsWithThePreparedItem(): void { Test::assertCount($this->basket->items, 1); }
#[Test] public function itAddsToThePreparedItem(): void { // The item this test adds is gone before the next test starts. $this->basket->add('milk'); Test::assertCount($this->basket->items, 2); }}
// This prints `2`.var $basket = new Basket();$basket->add('bread');$basket->add('milk');echo Core\Arr::count($basket->items), "\n";2Two tests that register the same address
<?nvs// Shows why this matters at work. Two tests register the same address, and// both expect one account, because neither test sees the other's account.
use Core\Test;
class Registry{ public static array<string> $accounts = [];
public static function register(string $email): void { Registry::$accounts[] = $email; }
public static function count(): uint { return Core\Arr::count(Registry::$accounts); }}
class RegistryTest{ #[Test] public function itRegistersAnAddress(): void { Registry::register('ada@example.com'); Test::assertSame(Registry::count(), 1); }
// The same address again. This test starts with an empty registry, so it // needs no code to remove what the test above registered. #[Test] public function itRegistersTheSameAddressAgain(): void { Registry::register('ada@example.com'); Test::assertSame(Registry::count(), 1); }}
// Outside a test the registry keeps both addresses. This prints `2`.Registry::register('ada@example.com');Registry::register('grace@example.com');echo Registry::count(), "\n";2Details
Each row of a #[TestWith] test runs on its own too. A static value one row writes is back at its declared value in the next row.
The attempts of one test share their static values. With retries:, a counter that the first attempt raised still has that value in the second attempt.
A constructor that throws an error makes the test fail, with the error's message.
A fixture is built outside the tests. A static value that a fixture method writes is back at its declared value in every test.
A test that starts a script with spawn script and does not await it fails. The message says the test left a task still running. Core\Task::all and Core\Task::map wait for every task they start, so a test that uses them does not fail this way.
Test options
#[Test(...)] takes options that change how one test runs. Every option is optional. A test that needs none is plain #[Test].
skip: gives a reason, and the test is reported as skipped and does not run. at: sets the clock to one time that does not change, so every run reads the same time. Core\Test::advance moves that clock forward. seed: makes Core\Random give the same numbers on every run. retries: allows more attempts after a failure, and needs because: to say why. A test that passes only on a retry is reported as flaky. It does not count as passed.
timeout: sets a time limit for one test. tags: labels a test, and nvs test --tag runs only the tests with that label. env: sets environment variables for the test, such as ['API_KEY' => 'test']. The requests the test sends with Core\Test::request and the programs it runs with Core\Test::run get them too.
Good to know: an option with a wrong name does not compile.
The examples below show a skipped test, a fixed clock, several options together, a flaky test, retries that need a reason, a time limit, and tags.
Skip a test and say why
<?nvs// Shows how to skip a test and say why. `skip:` needs a reason. The runner// reports the test as skipped and does not run its body.
use Core\Test;
class Coupon{ public static function percentFor(string $code): uint { if ($code == 'SPRING24') { return 15; } return 0; }}
class CouponTest{ #[Test] public function itGivesFifteenPercentForTheSpringCode(): void { Test::assertSame(Coupon::percentFor('SPRING24'), 15); }
// The reason is part of the report, so anybody reading a run sees why // this test did not run. #[Test(skip: 'the refund table is not written yet')] public function itGivesNothingOnARefundedOrder(): void { Test::assertSame(Coupon::percentFor('SPRING24'), 0); }}
// This prints `15 0`.echo Coupon::percentFor('SPRING24'), ' ', Coupon::percentFor('AUTUMN24'), "\n";15 0A fixed clock for one test
<?nvs// Shows how to fix the time a test reads. `at:` sets the clock at one instant// for that test. `Core\Test::advance` then moves the clock forward.
use Core\Test;use Core\Time;
class Receipt{ public static function stampedAt(string $iso): string { return 'receipt at ' . $iso; }}
class ReceiptTest{ // The clock stands still at this instant, for this test only. #[Test(at: '2026-01-01T00:00:00Z')] public function itStampsTheTimeTheClockShows(): void { string $first = Receipt::stampedAt(Time::now()->toIso()); Test::assertSame($first, 'receipt at 2026-01-01T00:00:00Z');
// This moves the fixed clock forward by 90 minutes. Test::advance(90m);
string $later = Receipt::stampedAt(Time::now()->toIso()); Test::assertSame($later, 'receipt at 2026-01-01T01:30:00Z'); }}
// This prints `receipt at 2026-01-01T00:00:00Z`, the text the test checks first.echo Receipt::stampedAt('2026-01-01T00:00:00Z'), "\n";receipt at 2026-01-01T00:00:00ZOptions in a real test class
<?nvs// Shows the options a real test class uses: a fixed clock, a fixed seed, an// allowance of extra attempts with the reason for it, and a skip.
use Core\Random;use Core\Test;use Core\Time;
class Invite{ public static function code(string $draw): string { return 'INV-' . $draw; }
public static function isWellFormed(string $code): bool { return Core\Str::length($code) == 8; }}
class InviteTest{ // With `at:` this test reads the same time on every run. #[Test(at: '2026-03-01T09:00:00Z')] public function itReadsOneFixedTime(): void { Test::assertSame(Time::now()->toIso(), '2026-03-01T09:00:00Z'); }
// With `seed:` `Core\Random` draws the same numbers on every run. #[Test(seed: 42)] public function itBuildsACodeFromADrawnNumber(): void { int $draw = Random::int(1000, 9999); Test::assertTrue(Invite::isWellFormed(Invite::code($draw as string))); }
// The payment sandbox fails now and then, so this test gets two more // attempts. `because:` is what a reader of the report has instead of the run. #[Test(retries: 2, because: 'the payment sandbox is slow to start')] public function itAcceptsACodeTheSandboxReturns(): void { Test::assertTrue(Invite::isWellFormed('INV-1234')); }
// This test waits for work that is not done. It is reported as skipped. #[Test(skip: 'the refund endpoint is not built yet')] public function itRefundsAnInvite(): void { Test::assertTrue(Invite::isWellFormed('INV-0000')); }}
// This prints `INV-1234`.echo Invite::code('1234'), "\n";INV-1234A test reported as flaky
<?nvs// Shows a fixed clock, a fixed seed, and a test that passes on its second// attempt. The report shows `!` for that test, because it is flaky.// proof: test
use Core\Random;use Core\Test;use Core\Time;
final class DeterminismTest{ // `Core\Test::advance` moves the fixed clock forward by 90 minutes. #[Test(at: '2026-01-01T00:00:00Z')] public function theClockIsFixedAndMovable(): void { Test::assertSame(Time::now()->toIso(), '2026-01-01T00:00:00Z'); Test::advance(90m); Test::assertSame(Time::now()->toIso(), '2026-01-01T01:30:00Z'); }
// With the same seed, `Random::int` returns the same number on every run. #[Test(seed: 42)] public function aSeedIsRepeatable(): void { int $first = Random::int(0, 999); Test::assertTrue($first >= 0); }
// The attempts of one test share their `static` values. The first // attempt fails, and the second one passes. #[Test(retries: 2, because: 'a counter replaces a slow network')] public function itPassesOnTheSecondAttempt(): void { Attempts::$n = Attempts::$n + 1; Test::assertSame(Attempts::$n, 2); }}
final class Attempts{ public static int $n = 0;} DeterminismTest ✓ theClockIsFixedAndMovable ✓ aSeedIsRepeatable ! itPassesOnTheSecondAttempt flaky: it passed on attempt 2, having failed with: Core\Test::assertSame failed: `$actual` is 1, `$expected` is 2
0 failed, 2 passed, 0 skipped, 1 flakyRetries need a reason
<?nvs// Shows that `retries:` needs `because:` beside it. Without a reason, the test// does not compile.// proof: compile-error
use Core\Test;
final class NetworkTest{ #[Test(retries: 2)] public function itReachesTheServer(): void { Test::assertTrue(true); }}error[E0734]: `retries` is given with no `because` --> 05-retries-need-a-reason.nvs:10:12 |10 | #[Test(retries: 2)] | ^^^^^^^^^^ retried for no stated reason = help: a test that passes only after a retry is reported as flaky. Write the reason for the retries: `#[Test(retries: 2, because: "real DNS")]`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A time limit for one test
<?nvs// Shows how to give one test a time limit. `timeout:` sets the limit for that// test. A test that runs past it is stopped, and the report shows it as failed.// proof: test// proof: exit 1
use Core\Test;
class Basket{ public static function total(array<int> $prices): int { int $sum = 0; foreach ($prices as int $price) { $sum = $sum + $price; } return $sum; }}
class BasketTest{ // This test finishes long before its limit of 2 seconds. #[Test(timeout: '2s')] public function itAddsThePrices(): void { Test::assertSame(Basket::total([4, 8, 15]), 27); }
// This loop never ends. The test is stopped after 50 milliseconds. #[Test(timeout: '50ms')] public function itStopsALoopThatNeverEnds(): void { int $count = 0; while (true) { $count = $count + 1; } }} BasketTest ✓ itAddsThePrices ✗ itStopsALoopThatNeverEnds the test ran past its wall-time limit of 50ms, set by `#[Test(timeout: "50ms")]`
1 failed, 1 passed, 0 skipped, 0 flakyTags select which tests run
<?nvs// Shows how to label tests with `tags:`. `nvs test --tag db` runs only the tests// labelled `db`, and `nvs test --skip-tag slow` runs every test except the slow ones.// proof: test
use Core\Test;
class Order{ public static function withShipping(int $cents): int { return $cents + 500; }}
class OrderTest{ // A test without `tags:` runs when no `--tag` is given. #[Test] public function itAddsTheShippingCost(): void { Test::assertSame(Order::withShipping(1000), 1500); }
// A test may have several tags. `--tag db` and `--tag slow` both select it. #[Test(tags: ['db', 'slow'])] public function itAddsShippingToEveryStoredOrder(): void { array<int> $stored = [500, 1000, 2500]; int $total = 0; foreach ($stored as int $cents) { $total = $total + Order::withShipping($cents); } Test::assertSame($total, 5500); }
// `--skip-tag slow` leaves out this test. #[Test(tags: ['slow'])] public function itAddsShippingToAMillionOrders(): void { int $total = 0; for (int $i = 0; $i < 1000000; $i++) { $total = $total + Order::withShipping(100); } Test::assertSame($total, 600000000); }} OrderTest ✓ itAddsTheShippingCost ✓ itAddsShippingToEveryStoredOrder ✓ itAddsShippingToAMillionOrders
0 failed, 3 passed, 0 skipped, 0 flakyDetails
The options are skip: string, at: string, seed: int, retries: int, because: string, db: string, server: bool, timeout: string, tags: array<string> and env: array<string>. An option with another name is E0454, and its help lists them. A value of the wrong type is E0401, so skip: true does not compile. An option given twice is E0304.
A skipped test is not built, so its constructor does not run. The fixtures only it needs are not built either. The report prints the reason after skipped:.
at: takes a time in the RFC 3339 format, such as "2026-01-01T00:00:00Z". Core\Time::now() returns that time in the test. A text in another format compiles, and the test fails with a message that shows the format.
Core\Test::advance moves the fixed clock forward by a duration, such as 90m. In a test without at:, it throws a LogicError. It throws the same error under nvs run. The clock of the computer does not change.
With seed:, Core\Random and Core\Uuid::v7 give the same values on every run. Two tests with the same seed get the same values. A test without seed: gets different values on every run.
retries: without because: is E0734. because: without retries: compiles and has no effect.
A test that fails and then passes is reported as flaky. The report shows ! in front of it, and prints the message of the failed attempt. A test that fails every attempt is reported as failed, with the message of the last attempt.
db: "main" opens a transaction on the database connection [db.main] before the test, and rolls it back after the test. The test sees the database as it was, and leaves no change in it. If no [db.main] block is configured, the test fails with a message that says so.
server: true starts a real HTTP server for the test, on a free port of the local computer. Core\Test::serverUrl() returns its address. In a test without server: true, it returns null.
Running tests
nvs test main.nvs compiles a program and runs every method that has the #[Test] attribute. It prints one line for each test and a count at the end.
Tests can be in the same file as the code, or in a class of their own. The statements outside a class do not run under nvs test.
nvs test . runs every .nvs file in a folder and its subfolders as one program. Run it in your project folder, so every test can use the classes your autoload line loads. A tests folder needs one file that requires your entry file.
--filter <text> runs only the tests whose name, Class::method, contains that text. --list prints each test and its file, and runs none. --format json and --format junit print a report for a build server. The exit status is 1 when a test failed, and 0 otherwise.
The examples show two tests, two test classes with a filter, and a report for a build server.
Run the tests of a program
<?nvs// Shows the program you give to `nvs test`. `nvs test 01-run-the-tests-of-a-program.nvs`// compiles it, runs both tests below, and prints a line for each one.
use Core\Test;
class Greeting{ public static function forName(string $name): string { if ($name == '') { return 'Hello!'; } return 'Hello, ' . $name . '!'; }}
class GreetingTest{ #[Test] public function itGreetsSomebodyByName(): void { Test::assertSame(Greeting::forName('Ada'), 'Hello, Ada!'); }
#[Test] public function itGreetsSomebodyWithNoName(): void { Test::assertSame(Greeting::forName(''), 'Hello!'); }}
// The lines outside a class do not run under `nvs test`. Under `nvs run` they// do, and this prints `Hello, Ada! Hello!`.echo Greeting::forName('Ada'), ' ', Greeting::forName(''), "\n";Hello, Ada! Hello!Run only some of the tests
<?nvs// Shows how to run part of a test suite. A test's name is `Class::method`, so// `nvs test --filter CartTest::` runs the three tests of `CartTest` and none// of `ShippingTest`.
use Core\Test;
class Cart{ public static function total(array<uint> $prices): uint { uint $sum = 0; foreach ($prices as uint $price) { $sum = $sum + $price; } return $sum; }}
class Shipping{ public static function costFor(uint $total): uint { if ($total >= 5000) { return 0; } return 499; }}
class CartTest{ #[Test] public function itAddsNothingForAnEmptyCart(): void { Test::assertSame(Cart::total([]), 0); }
#[Test] public function itAddsOnePrice(): void { Test::assertSame(Cart::total([1250]), 1250); }
#[Test] public function itAddsSeveralPrices(): void { Test::assertSame(Cart::total([1250, 750, 3000]), 5000); }}
class ShippingTest{ // `--filter CartTest::` does not run this test, and its class is not // printed at all. #[Test] public function itShipsALargeOrderForFree(): void { Test::assertSame(Shipping::costFor(5000), 0); }}
// This prints `5000 0`.echo Cart::total([1250, 750, 3000]), ' ', Shipping::costFor(5000), "\n";5000 0The report a build server reads
<?nvs// Shows the program a build server runs. `nvs test --format json` prints one// JSON document holding every test and its result. The exit status is `1`// when a test failed, which is what stops the build.
use Core\Test;
class Password{ public static function isStrongEnough(string $text): bool { return Core\Str::length($text) >= 12; }}
class PasswordTest{ #[Test] public function itAcceptsALongPassword(): void { Test::assertSame(Password::isStrongEnough('correct horse battery'), true); }
#[Test] public function itRejectsAShortPassword(): void { Test::assertSame(Password::isStrongEnough('horse'), false); }
// `--list` prints this test and where it is written, without running it. #[Test] public function itRejectsAnEmptyPassword(): void { Test::assertSame(Password::isStrongEnough(''), false); }}
// This prints `strong weak weak`.echo (Password::isStrongEnough('correct horse battery') ? 'strong' : 'weak'), ' ', (Password::isStrongEnough('horse') ? 'strong' : 'weak'), ' ', (Password::isStrongEnough('') ? 'strong' : 'weak'), "\n";strong weak weakDetails
nvs test main.nvs runs the tests in main.nvs and in the files it loads. autoload loads only the classes the program uses. A test class that the program never names does not run. nvs test . runs it.
nvs test tests/ runs every .nvs file in tests/ and its subfolders as one program. One file there requires the entry file of your application, and its name can be anything. The statements outside the classes do not run, in any of the files.
A .nvst file, or a folder of .nvst files, is a different kind of test. Each file has a --TEST-- title, a program under --FILE-- and its expected output under --EXPECT--. The report is one line, such as 1 passed, 0 failed, 0 skipped.
A folder with both .nvs and .nvst files is an error. nvs test takes one program at a time, so a .nvs path and a .nvst path in one call are an error too. --format, --list and --update do not work with .nvst files.
--format json prints one JSON document at the end. It has schemaVersion 2, a summary with total, passed, failed, skipped, flaky and durationMs, and a tests list. Each test has class, method, file, line, column, verdict and durationMs. line and column are where the method's name is written, counted from 1. A skipped test also has reason. A failed or flaky test has failures, and a flaky test has attempts.
--coverage-lcov, --coverage-clover and --coverage-cobertura write which lines the tests ran. With one of them, the JSON document has schemaVersion 3, and each test has coverage. It maps each file name to the lines that test ran.
--format junit prints JUnit XML, with one <testsuite> for each class and one <testcase> for each test. A test has <skipped>, <failure> or <flakyFailure> inside it. The message of a failure is its first message, and the text inside is every message.
With --format json or --format junit, standard output has only the document. The output of a test that fails goes to standard error.
--list prints each test and where it is written, such as T::a main.nvs:6, and runs nothing. A test with data rows has one line for each row. With --format json, it prints a document with schemaVersion 2 and a listed list of class, method, file, line and column.
--filter is case-sensitive, so --filter t:: does not select the class T. A data row is Class::method#0, Class::method#1 and so on. A class with no selected test is not printed, and its fixtures are not built.
The exit status is 1 when a test failed, and 0 otherwise. It is the same in every format.
Benchmarks
#[Bench] marks a method as a bench. A bench measures how much work a piece of code does. nvs test --bench main.nvs runs every bench in the program, one at a time. It runs no test, and a plain nvs test runs no bench.
A bench method has the same shape as a #[Test] method. Write use Core\Test\Bench; at the top of the file, and #[Bench] above the method.
The report prints a count: line under each bench. It counts statements, calls, allocations, allocated bytes and runs of the garbage collector. These counts are the same on every run and on every computer. The line also prints the time the bench took, marked (advisory), because that time changes on every run.
A bench passes without an assertion. With --format json, a build server can compare the counts with the last run.
Good to know: a new version of Novis can give the same program different counts.
The examples show a bench beside a test, two ways to write the same work, and benches that a build server checks.
A bench beside a test
<?nvs// Shows a bench beside a test. `nvs test --bench` runs the bench and not the test.// proof: test --bench
use Core\Test;use Core\Test\Bench;
final class Slug{ public static function of(string $title): string { return Core\Str::replace(Core\Str::lower(Core\Str::trim($title)), ' ', '-'); }}
final class SlugTest{ // `nvs test` runs this test. `nvs test --bench` does not. #[Test] public function itJoinsTheWordsWithDashes(): void { Test::assertSame(Slug::of(' Hello World '), 'hello-world'); }
// A bench needs no assertion. The report prints a `count:` line under it. // `statements` is how many statements ran, and `calls` is how many calls were made. #[Bench] public function slugsOfOneHundredTitles(): void { for (int $i = 0; $i < 100; $i++) { Slug::of('Release Notes ' . $i); } }} SlugTest ✓ slugsOfOneHundredTitles count: statements=302 calls=400 allocations=304 bytes=17878 gc=0
0 failed, 1 passed, 0 skipped, 0 flakyTwo ways to build one line
<?nvs// Shows two benches that compare two ways to build one line of a CSV file.// proof: test --bench
use Core\Test\Bench;
final class CsvLine{ // This method adds one cell at a time, in a loop. public static function byLoop(array<string> $cells): string { string $line = ''; foreach ($cells as string $cell) { if ($line != '') { $line = $line . ','; } $line = $line . $cell; } return $line; }
// This method makes one call to `Core\Str::join`. public static function byJoin(array<string> $cells): string { return Core\Str::join($cells, ','); }}
final class CsvLineBench{ // Both benches build the same 200 cells first. // So the difference in their counts is the work of building the line. private static function cells(): array<string> { array<string> $cells = []; for (int $i = 0; $i < 200; $i++) { $cells[] = 'cell' . $i; } return $cells; }
#[Bench] public function byLoop(): void { CsvLine::byLoop(CsvLineBench::cells()); }
// This bench runs 1000 fewer statements than the bench above. #[Bench] public function byJoin(): void { CsvLine::byJoin(CsvLineBench::cells()); }} CsvLineBench ✓ byLoop count: statements=1406 calls=2 allocations=422 bytes=35661 gc=0 ✓ byJoin count: statements=406 calls=3 allocations=417 bytes=33584 gc=0
0 failed, 2 passed, 0 skipped, 0 flakyBenches a build server checks
<?nvs// Shows benches that a build server checks on every change to the program.// proof: test --bench
use Core\Test\Bench;use Core\Test\Fixture;
final class Catalog{ public function constructor(public array<int> $prices) {}
public function priceOf(string $sku): ?int { if (!Core\Arr::hasKey($this->prices, $sku)) { return null; } return $this->prices[$sku]; }}
final class CatalogBench{ // A fixture is built before the counting starts. // So the 500 prices it adds are not part of the counts below. #[Fixture] public static function catalog(): Catalog { array<int> $prices = []; for (int $i = 0; $i < 500; $i++) { $prices['sku-' . $i] = 100 + $i; } return new Catalog($prices); }
// `nvs test --bench --format json` prints a `counts` object for this bench. // The counts are the same on every machine. A build server can compare them with the last run. #[Bench] public function oneHundredLookups(Catalog $catalog): void { for (int $i = 0; $i < 100; $i++) { $catalog->priceOf('sku-' . $i); } }
// `skip:` stops a bench from running, and the report prints the reason. #[Bench(skip: 'the import file is not in this repository')] public function importTheWholeCatalog(): void {}} CatalogBench ✓ oneHundredLookups count: statements=402 calls=200 allocations=204 bytes=10470 gc=0 - importTheWholeCatalog skipped: the import file is not in this repository
0 failed, 1 passed, 1 skipped, 0 flakyDetails
A bench method is public, it is not static, and it returns void. If an assertion inside a bench fails, the bench fails. #[Bench(skip: "reason")] skips a bench and prints the reason.
The counts tell you if your code does more work. They do not tell you if Novis got faster.
Each bench runs once. Its counts are the same on every run, so a second run gives no new information.
Each bench runs on its own, the same way each test does. A value that one bench puts in a static property is not there when the next bench runs. So the counts of a bench do not depend on the benches that ran before it.
A bench can have a #[Fixture] parameter. The fixture is built before the counting starts, so its work is not part of the counts.
A bench cannot fix the clock or the random numbers. A bench that reads Core\Time::now() or calls Core\Random can do different work on each run, and then its counts change too.
#[Bench] has two options, skip: and because:. Both are strings. Every other option of #[Test], such as retries:, seed: or at:, does not compile on a bench. A #[TestWith] row on a bench does not compile either. A method that has #[Bench] and also #[Test] or #[Fixture] does not compile.
--filter works with --bench and selects benches by Class::method. --bench does not work with --jobs or --mutate, and it does not work with a .nvst file.
In the JSON report, a bench that ran has counts with statements, calls, allocations, bytes and gc. It also has advisoryWallMs, the time it took in milliseconds. A skipped bench has reason and no counts.
The exit status is 1 when a bench failed, and 0 otherwise.
A test can also get values from a fixture or a data row. The page Fixtures, data rows and assertions explains them.
Use this when you check your own code
Section titled “Use this when you check your own code”Write #[Test] methods to test the classes of your program. A .nvst file is a different kind of
test: it runs a whole program and compares its output with the text the file expects. Use it only
to check the exact text a whole program prints.
Do and don’t
Section titled “Do and don’t”- Do use
at:andseed:in a test that reads the time or random numbers. - Do use
env:to set an environment variable for one test. Other tests do not see it. - Do write a reason in every
skip:, such asskip: "until the new API is live". Say when the test will run again. - Do give a slow test a
tags:label, such as"slow".nvs test --skip-tag slowthen runs every other test. - Don’t use
retries:to hide a bug. A test that fails and then passes on a retry is called flaky. The report always lists it as flaky. - Don’t share state between tests through a static property. Each test starts fresh.
