yuloh/expect

此包已被废弃,不再维护。未建议替代包。

脚本与交互式终端应用程序的交互。

v0.1.0 2016-03-29 06:03 UTC

This package is auto-updated.

Last update: 2021-11-23 07:05:55 UTC


README

此包是Unix工具expect的纯PHP替代品。此包也不依赖于PECL包

Expect允许您编写与交互式终端应用程序的交互脚本。

为什么?

我编写这个是因为我编写了一个交互式CLI程序,并需要为它编写自动化测试。显然,人们使用真正的expect进行脚本化ftp和telnet工作流程,所以我猜你也可以用它来做。

安装

composer require yuloh/expect

API

注意:所有方法都返回 $this 以进行流畅的链式调用。

spawn(string $cmd, string $cwd = null, LoggerInterface $logger = null)

为给定的命令启动expect的新实例。您可以可选地指定工作目录和要使用的PSR兼容日志记录器。

expect(string $output, $timeout = 9999999)

期望在stdout上出现给定的文本。Expect将阻塞并持续检查stdout缓冲区,直到期望出现或超时,以先到者为准。

您可以使用shell通配符来匹配输出的一部分。

send(string $msg)

在stdin上发送给定的文本。每个字符串都会添加一个换行符以模拟按回车。如果您只想发送回车,则可以这样做 send(PHP_EOL)

示例

简单示例

此示例以没有任何参数的方式打开cat,它将简单地回显您输入的任何内容。

Yuloh\Expect\Expect::spawn('cat')
    ->send('hi')
    ->expect('hi')
    ->send('yo')
    ->expect('yo')
    ->run();

Npm init

此示例演示了使用npm创建新的package.json。我们使用glob来匹配期望,所以我们不需要完全输入它们。

Yuloh\Expect\Expect::spawn('npm init')
    ->expect('*name:*')
    ->send('package')
    ->expect('version*')
    ->send('1.0.0')
    ->expect('description*')
    ->send('awesome')
    ->expect('entry point*')
    ->send('index.js')
    ->expect('test command*')
    ->send('test')
    ->expect('git repository*')
    ->send('yuloh/expect')
    ->expect('keywords*')
    ->send('awesome')
    ->expect('author*')
    ->send('matt')
    ->expect('license*')
    ->send('ISC')
    ->expect('*')
    ->send('yes')
    ->run();

日志记录

您可能需要日志记录来了解正在发生的事情。Expect在实例化时接受PSR兼容的日志记录器。您可以使用Yuloh\Expect\ConsoleLogger在编写脚本或调试时获得可读的输出。例如,像这样实例化Expect

Yuloh\Expect\Expect::spawn('cat', getcwd(), new Yuloh\Expect\ConsoleLogger())
    ->send('hi')
    ->expect('hi')
    ->run();

...将在终端输出以下内容

* Sending 'hi⏎'
* Expected 'hi', got 'hi'

异常

在运行您的进程时可能会发生一些错误

  • 进程可能无法启动。
  • 进程可能在期望发生之前超时。
  • 进程可能意外终止。
  • 进程可能在期望发生之前发送EOF。

如果进程启动失败,将抛出一个 RuntimeExceptionYuloh\Expect\Exceptions 命名空间 包含其他三种情况下的异常。所有这些异常都扩展自 Yuloh\Expect\FailedExpectationException,所以如果您愿意,可以只捕获这个异常。

缓冲

一些程序,如 Composer,会缓冲输出,因此除非您取消缓冲输出,否则 Expect 将无法正常工作。最简单的方法可能是使用 脚本。修改您的命令,通过脚本进行管道操作,如下所示

# FreeBSD/Darwin (Mac OSX)
script -q /dev/null {your-command}
# Linux
script -c {your-command} /dev/null

然后您可以将它传递给 Expect

Expect::spawn('script -q /dev/null ssh localhost')
    ->expect('*password:')
    ->send('hunter 2')
    ->run();

在脚本中使用时,您可能需要修改期望,因为您输入的内容也会显示在标准输出中。

测试

composer test
composer cs