texthtml/doctest

在 PHP 注释中测试代码示例

安装: 570

依赖项: 3

建议者: 0

安全: 0

星星: 8

关注者: 1

分支: 1

开放问题: 1

类型:项目

v0.2.3 2023-12-09 12:04 UTC

README

测试您的 docblock 代码示例。

doctest 会查找您函数、方法、类和接口注释中的 PHP 示例,并执行它们以确保它们正确无误。

如何编写示例

最简单的方法是在注释中添加代码块,并使用 assert() 检查不变量。如果执行示例时出现异常,示例将被标记为失败。

/**
 * Compute the factorial of a non-negative $n
 *
 * ```
 * assert(factorial(0) === 1);
 * assert(factorial(5) === 120);
 * ```
 */
function factorial(int $n): int {
    if ($n === 0) {
        return 1;
    }

    if ($n < 0) {
        throw new \InvalidArgumentException("unexpected negative integer: $n");
    }

    return $n * factorial($n - 1);
}

断言

当遇到意外情况时,一个简单的方法是使用 assert() 抛出异常。但为了使断言更易于编写并具有更好的错误消息,您可以调用 来自 webmozart/assert 的断言助手,使用 self::assert* 速记。

self::assertEq(factorial(0), 1);
self::assertEq(factorial(5), 120);

测试异常

有时我们想要展示某些代码 确实 会抛出异常,我们可以通过在示例中的任何位置添加以下格式的内联注释来完成: // @throws [exception class] [exception message]

// @throws InvalidArgumentException unexpected negative integer: -10
factorial(-10);

注意:异常之后的代码将不会执行,因此任何在第一个异常之后的代码中的 in-code 断言都不会被验证。

测试输出

默认情况下,doctest 将使示例失败,除非它通过一个或多个以下格式的内联注释 @prints 进行文档化:`// @prints [text]`。这是为了确保产生的任何输出都是预期的。

echo factorial(6); // @prints 720
echo factorial(10);
// the @prints annotations can be anywhere, only their order is important, not their exact positions
// @prints 3628800

安装

composer req --dev texthtml/doctest

使用方法

只需运行 doctest 命令,它将在您的 src/ 文件夹中查找要测试的示例。要自定义查找示例的位置和其他选项,请运行 doctest --help

$ ./bin/doctest examples/factorial.php
 [OK] factorial#1 (examples/factorial.php:7)
 [OK] factorial#2 (examples/factorial.php:14)
 [ERROR] factorial#3 (examples/factorial.php:20)
         Expected output to be "". Got: "720"
 [OK] factorial#4 (examples/factorial.php:25)
 [ERROR] factorial#5 (examples/factorial.php:30)
         unexpected negative integer: -10
 [OK] factorial#6 (examples/factorial.php:35)
 [ERROR] factorial#7 (examples/factorial.php:43)
         Expected a value equal to 3628890. Got: 3628800
 [OK] Number of success: 4
 [ERROR] Number of failures: 3

待办事项

  • Junit 输出
  • 在 markdown 中查找 PHP 示例