【问题标题】:How do I enable VerifyCsrfToken for some tests?如何为某些测试启用 VerifyCsrfToken?
【发布时间】:2017-04-07 16:13:00
【问题描述】:

如果运行测试,Laravel 默认为 disables VerifyCsrfToken 中间件。结果我没有注意到 api 路由需要 csrf 令牌才能成功。有没有办法在某些测试中启用它?喜欢

function withVerifyCsrfTokenMiddleware()
{
    $this->app...   // here we're passing something to the app
}

并在VerifyCsrfTokenhandle方法中进行修改。在一个定制的。一个,覆盖框架中的方法。但这只是我的想法。有更好的吗?

【问题讨论】:

  • 你用的是哪个版本的 laravel?
  • @tomirons Laravel 5.2.

标签: php laravel automated-tests csrf-protection


【解决方案1】:

好的,这就是我所做的:

app/Http/Middleware/VerifyCsrfToken.php:

function handle($request, Closure $next)
{
    $dontSkipCsrfVerificationWhenRunningTests
        = $this->app->bound('dontSkipCsrfVerificationWhenRunningTests')
            && $this->app->make('dontSkipCsrfVerificationWhenRunningTests');
    if (
        $this->isReading($request) ||
        ! $dontSkipCsrfVerificationWhenRunningTests && $this->runningUnitTests() ||
        $this->shouldPassThrough($request) ||
        $this->tokensMatch($request)
    ) {
        return $this->addCookieToResponse($request, $next($request));
    }

    throw new TokenMismatchException;
}

tests/TestCase.php:

function withVerifyCsrfTokenMiddleware()
{
    $this->app->instance('dontSkipCsrfVerificationWhenRunningTests', TRUE);
}

【讨论】:

    【解决方案2】:

    对上述答案的小改动,而不是更改句柄方法,我更新了 runningUnitTests 方法以减少升级时出现问题的机会:

    <?php
    
    namespace App\Http\Middleware;
    
    use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
    
    class VerifyCsrfToken extends Middleware
    {
        /**
         * The URIs that should be excluded from CSRF verification.
         *
         * @var array
         */
        protected $except = [
        ];
    
        /**
         * Determine if the application is running unit tests.
         *
         * @return bool
         */
        protected function runningUnitTests()
        {
            $dontSkip
            = $this->app->bound('dontSkipCsrfVerificationWhenRunningTests')
            && $this->app->make('dontSkipCsrfVerificationWhenRunningTests');
    
            return $this->app->runningInConsole() && $this->app->runningUnitTests() && !$dontSkip;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-29
      • 2016-06-16
      • 2021-03-21
      • 2017-07-03
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多