smile / httplug-record-and-replay-plugin
HTTPlug 的录制和回放插件
dev-master
2019-02-04 19:51 UTC
Requires
- php: ^7.0
- php-http/cache-plugin: ^1.6
- php-http/discovery: ^1.6
- php-http/httplug: ^2.0
- php-http/message: ^1.7
- psr/http-factory: ^1.0
- psr/simple-cache: ^1.0
Requires (Dev)
- cache/array-adapter: ^1.0
- http-interop/http-factory-guzzle: ^1.0
- php-http/client-common: 2.0.0-RC1
- php-http/mock-client: ^1.2
- phpunit/phpunit: ^7.5
This package is auto-updated.
Last update: 2024-09-16 22:35:11 UTC
README
实现独立的测试套件和可预测的 HTTP 通信。
安装
通过 Composer
$ composer require --prefer-stable smile/httplug-record-and-replay-plugin
使用方法
纯 PHP
使用环境变量 HTTPLUG_RECORDING=1
运行以下命令
/** @var Http\Client\HttpClient $client */ $client = new Client(); /** * You have to provide concrete instances for the following parameters : * @var Psr\SimpleCache\CacheInterface $cachePool * @var Http\Client\Common\Plugin\Cache\Generator\CacheKeyGenerator $cacheKeyGenerator * @var Psr\Http\Message\StreamInterface\StreamFactory $streamFactory */ $plugin = new RecordAndReplayPlugin( $cachePool, $cacheKeyGenerator, $streamFactory, getenv('HTTPLUG_RECORDING') ); /** @var Http\Client\Common\PluginClient $client */ $client = new PluginClient($client, [$plugin]); $request = Psr17FactoryDiscovery::findRequestFactory()->createRequest('GET', 'https://api.somewhere/some_endpoint'); $client->sendRequest($request);
如果再次运行这些命令,但将 HTTPLUG_RECORDING=0
,则插件将回放记录的通信,而不会实际调用远程服务。
HTTPlug Bundle for Symfony
声明插件(及其所需的 PSR-16 存储)
# config/services.yaml services: _defaults: autowire: true public: false Smile\HTTPlugRecordAndReplayPlugin\RecordAndReplayPlugin: arguments: $cachePool: '@app.simple_cache.httplug_records' $isRecording: true app.simple_cache.httplug_records: class: Symfony\Component\Cache\Simple\FilesystemCache arguments: $directory: '%kernel.project_dir%/tests/httplug_records'
将其连接到您的客户端
# config/packages/test/httplug.yaml httplug: clients: default: plugins: - 'Smile\HTTPlugRecordAndReplayPlugin\RecordAndReplayPlugin'
现在您可以运行测试套件,您应该会看到 tests/httplug_records
文件夹被填充了表示记录的缓存文件。
一旦测试套件通过,您可以从服务定义中删除 $isRecording
行,并将所有记录以及更新的配置和 composer 文件一起提交。
稍后,当添加基于第三方请求的其他行为时,您可以将回放模式(通过将插件服务定义中的 $isRecording: true
放回)切换回回放模式,并只运行新的测试,以避免重写所有记录。
自动注入故障排除
根据您应用程序使用的依赖关系版本,您可能需要声明一些额外的服务
# config/services.yaml services: _defaults: autowire: true public: false # PSR-17 and PSR-18 autowiring compat Psr\Http\Client\ClientInterface: '@Http\Client\HttpClient' Psr\Http\Message\RequestFactoryInterface: '@Http\Factory\Guzzle\RequestFactory' Http\Factory\Guzzle\RequestFactory: ~ # HTTPlug record/replay plugin & records storage Http\Client\Common\Plugin\Cache\Generator\CacheKeyGenerator: class: Http\Client\Common\Plugin\Cache\Generator\SimpleGenerator
贡献和测试
$ composer update --prefer-lowest $ ./vendor/bin/phpunit
请维护测试套件:如果您添加了一个功能,证明新行为;如果您修复了一个错误,确保没有回归。
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。