cucumber/messages

Cucumber 的进程间通信使用的基于 JSON 模式的消息

v26.0.1 2024-09-20 10:31 UTC

README

这是 Cucumber 消息协议的 PHP 实现 Cucumber Messages 协议

要求

  • PHP 8.1
  • Ext-JSON

安装

使用 composer 安装。

composer require cucumber/messages

用法

消费消息

Cucumber 消息在序列化时包含在顶级 Envelope 对象中。成员通过公共只读属性公开。由于许多属性是可空的,因此使用 nullsafe 操作符 访问它们可能很方便

/** @var string|null $line */
$line = $envelope->gherkinDocument?->feature?->keyword;

解码 JSON 字符串

您可以从 JSON 字符串构建一个 Envelope

use Cucumber\Messages\DecodingException;
use Cucumber\Messages\Envelope;

try {
    $envelope = Envelope::fromJson($json);
}
catch (DecodingException $e) {
    // handle the error
}

处理 NDJSON 流

Cucumber 消息以 Newline Delimited JSON (NDJSON) 的形式流式传输。

您可以使用 NdJsonStreamReader 获取一个生成器,它会产生 Envelopes。重要的是要记住,任何解码错误将在生成器被消耗时抛出,而不是在它返回时。

use Cucumber\Messages\DecodingException;
use Cucumber\Messages\Streams\NdJson\NdJsonStreamReader;
use Cucumber\Messages\Envelope;

$fh = fopen('messages.ndjson', 'r');
$reader = new NdJsonStreamReader($fh);

/** @var Generator<Envelope> $envelopes */
$envelopes = $reader->envelopes();

try {
    foreach ($envelopes as $envelope) {
        /** @var Envelope $envelope */
        // process the message
    }
}
catch (DecodingException $e) {
    // handle any errors here
}

生成消息

Cucumber 消息的所有参数都是可选的,但任何非可空字段都将具有默认值。

由于消息通常具有大量的参数,因此建议使用命名字段来构建它们

use Cucumber\Messages\Envelope;
use Cucumber\Messages\TestCaseFinished;
use Cucumber\Messages\Timestamp;

$envelope = new Envelope(
    testCaseFinished: new TestCaseFinished(
        timestamp: new Timestamp(
            seconds: 100
        )
    )
);

编码 JSON 字符串

Envelope 可以编码为 JSON 字符串

$json = $envelope->asJson();

不要 使用 json_encode() 对象外部编码,因为可能未设置正确的编码选项。

生成 JSON 流

Cucumber 消息以 Newline Delimited JSON (NDJSON) 的形式流式传输。

您可以使用 NdJsonStreamReader 将 Envelope 列表的内容写入流。

use Cucumber\Messages\Streams\NdJson\NdJsonStreamReader;

$fh = fopen('php://stdout', 'w');

$writer = new NdJsonStreamWriter($fh)

// write a fixed array of envelopes
$envArray = [
    new Envelope('gherkinDocument': new GherkinDocument()),
    new Envelope('gherkinDocument': new GherkinDocument()),
];
$writer->write($envArray);

// write lazily-evaluated envelopes
$envGenerator = (function() {
    while ($envelope = Database::fetchNextEnvelope()) {
        yield $envelope;
    }
})();
$writer->write($envGenerator);