horat1us / yii2-header-environment
从HTTP头部加载环境变量(用于测试目的)
1.0.1
2018-04-15 11:51 UTC
Requires
- php: >=7.1
- yiisoft/yii2: 2.0.15.1
Requires (Dev)
- phpunit/phpunit: ^7.1
- squizlabs/php_codesniffer: ^3.2
Suggests
- horat1us/environment-config: Deal with multiple environment configs with prefixes
This package is auto-updated.
Last update: 2024-09-29 05:01:58 UTC
README
该包的目的是从HTTP头部加载环境变量。
案例:您的API接收哈希值,需要通过存储在环境中的密钥来检查它。由于API和测试API客户端在不同的流程中执行,测试用例不能直接使用putenv
。
注意:您应仅在测试环境中使用此包!
安装
composer require horat1us/yii2-header-environment --dev # Don't forget to do not use it in production
用法
控制器
<?php namespace App\Controllers; use yii\web; use Horat1us\HeaderEnvironment; class SiteController extends web\Controller { public function behaviors() { $behaviors = []; // Some your production behaviors if(YII_ENV_TEST) { $behaviors['environment'] = [ 'class' => HeaderEnvironment\Behavior::class, 'header' => 'Set-Environment', // default ]; } } public function actionIndex() { $request = \Yii::$app->request; $salt = $request->post('salt'); $sign = $request->post('sign'); $secret = getenv('SECRET'); \Yii::$app->response->statusCode = md5($salt . $secret) === $sign ? 200 : 400; } }
测试用例
<?php namespace App\Tests; class ApiTest { public function testSignChecking(\ApiTester $I) { $secret = 'persist-secret'; $salt = mt_rand(); $sign = md5($salt . $secret); $I->haveHttpHeader('Set-Environment', json_encode([ 'SECRET' => $secret, ])); $I->sendPOST('/site/index', [ 'salt' => $salt, 'sign' => $sign, ]); $I->seeResponseCodeIs(200); $I->haveHttpHeader('Set-Environment', json_encode([ 'SECRET' => null, // Delete environment ])); $I->sendPOST('/site/index', [ 'salt' => $salt, 'sign' => $sign, ]); $I->seeResponseCodeIs(400); } }