This is a documentation oriented testing framework for from PHP 5.3 to 7.x. Its purpose is ensure your example codes works by unit testing. Inspired by Golang testing "Examples".
See an example below. The first section is example code which will be tested. The comment which begins with Output
is test code.
<?php
function hello(string $name): string {
return 'hello ' . $name;
}
echo hello('alice') . "\n";
echo hello('bob') . "\n";
// Output:
// hello alice
// hello carol
This example code is broken. The word "carol" is expected as output, however it does not appear. This test case fails, but you are able to know the example code has a problem and you may fix it.
Livexample does following steps:
- Find
Output
statement in the example code by parsing it. - Run the code in PHPUnit and capture the output.
- Compare the expected output and the actual output.
Sometimes example codes are broken, by adding new features, forgetting to update them, pull-requests which don't take care of example codes and so on.
Broken example codes are bad experience for library users.
By using Livexample, you will get benefits:
- ๐ Your example codes are protected from unexpected regression.
- ๐ You can easily check your example codes are valid.
- ๐ Your library users can use the valid example codes by copy and paste.
- ๐ You don't have to add big change to your existing sample codes; just adding some comments.
- Livexample works a part of PHPUnit.
- Very low learning cost.
Install suin/livexample
via Composer:
composer require --dev suin/livexample
Add ExampleTest.php
to your tests directory:
use Livexample\PHPUnit\ExampleTestCase;
class ExampleTest extends ExampleTestCase
{
public function exampleFiles()
{
// specify your example code directory.
return self::exampleDirectory('example');
}
}
Run phpunit:
phpunit
There are two syntax for assertion:
- Long:
// Output: {expected output}
- Short:
//=> {expected output}
echo 1; // Output: 1
echo "hello"; //=> hello
var_dump([1, 2, 3]);
// Output:
// array(3) {
// [0] =>
// int(1)
// [1] =>
// int(2)
// [2] =>
// int(3)
// }
The var_dump()
function prints object identifiers, which is #some-number
next to the class name. Since the identifiers depend on execution environment, you can not hard-code it in the Output:
statement. Instead of hard-coding the identifier, you may use a placeholder %d
for number:
<?php
var_dump(new stdClass);
// Output:
// object(stdClass)#%d (0) {
// }
php -d auto_prepend_file=vendor/autoload.php \
-d xdebug.overload_var_dump=0 \
example/simple-usage.php
The official support for PHP 5.3 has ended, however, RHEL/CentOS keeps supporting PHP 5.3 even in 2017. The old PHP environments still remain in the running service today. Livexample is also suppoed to be used for refactoring such old environments.
Please see CHANGELOG for more details.
Please see CONTRIBUTING for more details. Please fix my English ๐.