gpt4 book ai didi

php - 如何在 Laravel 测试中代表另一个 session 发出 HTTP 请求?

转载 作者:行者123 更新时间:2023-11-28 20:37:04 24 4
gpt4 key购买 nike

当我使用 built-in tools 在 Laravel 5 中执行 HTTP 测试时,框架会记住请求之间的 session 数据。

class HttpTest extends TestCase
{
public function testApplication()
{
// Suppose this endpoint creates a session and adds some data to it
$this->get('/action/fillSession');

// Suppose this endpoint reads the session data
$this->get('/action/readSession'); // The session data from the first request is available here
}
}

如何在不破坏原始第一个 session 的情况下,在上述请求之间用另一个 session 执行请求?

最佳答案

记住第一个 session 数据,刷新应用程序 session ,发出“另一个 session ”请求并将原始 session 数据返回给应用程序:

class HttpTest extends TestCase
{
public function testApplication()
{
// Suppose this endpoint creates a session and adds some data to it
$this->get('/action/fillSession');

$session = $this->app['session']->all();
$this->flushSession();
$this->get('/noSessionHere');
$this->flushSession();
$this->session($session);

// Suppose this endpoint reads the session data
$this->get('/action/readSession'); // The session data from the first request is available here
}
}

您可以将此算法执行到一个单独的方法中以便轻松地重用它:

class HttpTest extends TestCase
{
public function testApplication()
{
// Suppose this endpoint creates a session and adds some data to it
$this->get('/action/fillSession');

$this->asAnotherSession(function () {
$this->get('/noSessionHere');
});

// Suppose this endpoint reads the session data
$this->get('/action/readSession'); // The session data from the first request is available here
}

protected function asAnotherSession(callable $action)
{
$session = $this->app['session']->all();
$this->flushSession();

$action();

$this->flushSession();
$this->session($session);
}
}

关于php - 如何在 Laravel 测试中代表另一个 session 发出 HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50423853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com