karmabunny / visor
PHP-CLI 服务器管理器
v1.1.0
2023-08-03 04:45 UTC
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-03 07:04:36 UTC
README
这是一个包装内置 PHP cli-server 功能的小工具。
此库有三个部分
-
一个抽象的 '服务器' 实例,它将管理任何与 cli-server 兼容脚本的生命周期。
-
一个 'echo 服务器' 实现,它会回声。你对它说的话,它就会原样回声。
-
一个 '模拟服务器' 实现,它将返回预定义的响应。
安装
使用 Composer
composer require karmabunny/visor
用法
这对于创建与本地应用程序的集成测试或创建模拟服务器并测试 HTTP 库来说非常理想。
服务器实例
use karmabunny\visor\Server; use PHPUnit\Framework\TestCase; /** * The application bootstrap is found at: 'index.php'. This must be capable * of accepting cli-server requests. */ class MyServer extends Server { protected function getTargetScript(): string { return __DIR__ . '/index.php'; } } class MyServerTest extends TestCase { public function testThings() { // This create a server at localhost:8080 $server = MyServer::create(); // One can then perform tests against the application. $res = file_get_contents($server->getHostUrl() . '/health'); $this->assertEquals('ok', $res); } }
echo 服务器
use karmabunny\visor\EchoServer; use PHPUnit\Framework\TestCase; class ClientTest extends TestCase { public function testThings() { // This creates an echo server at localhost:8080 $server = EchoServer::create(); // Imagine this to be some kind of client that hits a remote // server of sorts. $res = file_get_contents($server->getHostUrl() . '/hello?test=123'); // Not only is 'res' a JSON body of the payload, the payload is // also accessible from the the server instance. $payload = $server->getLatestPayload(); $this->assertEquals('/hello', $payload['path']); $this->assertEquals(['test' => '123'], $payload['query']); } }
模拟服务器
use karmabunny\visor\MockServer; use PHPUnit\Framework\TestCase; class FakeTest extends TestCase { public function testThings() { // This creates a mock server at localhost:8080 $server = MockServer::create(); $server->setMock('/mock-this', [], 'a fake response'); $res = file_get_contents($server->getHostUrl() . '/mock-this'); $payload = $server->getLatestPayload(); $this->assertEquals('/mock-this', $payload['path']); $this->assertEquals('a fake response', $res); } }
配置
默认情况下,日志文件路径是在临时系统目录中随机生成的。
日志文件
服务器生成日志文件以帮助测试和调试。
这包括来自服务器进程、应用程序和 visor 自身的日志。
扩展基本类的服务器可以使用 Server::log()
。应用程序可以使用本地的 error_log()
。
模拟 + echo 服务器
包含的实现还将记录额外的数据。
latest.json
是存储以供检查的请求数据。由getLastPayload()
使用。mocks.json
是模拟服务器的响应对象存储。
echo (+ 模拟) 有效载荷
模拟和 echo 服务器都将以特定格式存储请求对象。
注意,正文没有变化,如果你发送了 JSON 或 URL 有效载荷,这将以其编码的字符串形式 'as is'。
path
- 请求路径,不带查询字符串query
- 键值数组,来自parse_str()
method
- 总是大写headers
- 键值对,键为小写body
- 字符串正文,来自php://input
JSON 编码的日志文件看起来像这样
{ "path": "/hello-world.json", "query": { "rando1": "7bb1166f0cf451cc3eb4cbb977ad932f674aac6c" }, "method": "POST", "headers": { "host": "localhost:8080", "connection": "close", "content-length": "53", "content-type": "application/json" }, "body": "{\"rando2\":\"267f3bf70d8939c2c7e77d1f8ea164e1df071bba\"}" }