【发布时间】:2018-07-25 09:06:53
【问题描述】:
Mojolicious 框架 states 下一个:
应用程序的任何方面(帮助程序、插件、路由等)都可以通过应用程序对象从 Test::Mojo 进行内省。
但是当助手,例如,$c->current_user 处理会话时,它会失败。
会话数据不可用,我无法通过测试访问它:
$t->app->session # {}
因此$t->app->current_user 也失败了。
如何从测试中访问会话数据?
UPD测试
use Mojo::Base -strict;
use Mojolicious::Lite;
use Test::More;
use Test::Mojo;
get '/set_session' => sub {
my $c = shift;
$c->session->{ user_id } = 1;
$c->render( text => $c->session->{ user_id } );
};
get '/get_session' => sub {
my $c = shift;
$c->render( text => $c->session->{ user_id } );
};
my $t = Test::Mojo->new;
$t->get_ok( '/set_session' )->status_is(200);
is $t->app->session->{ user_id }, 1, 'Session available from test script';
$t->get_ok( '/get_session' )->status_is(200)
->content_is( 1 );
done_testing();
UPD测试结果
ok 1 - GET /set_session
ok 2 - 200 OK
not ok 3 - Session available from test script
# Failed test 'Session available from test script'
# at t/session.t line 22.
# got: undef
# expected: '1'
ok 4 - GET /get_session
ok 5 - 200 OK
ok 6 - exact match for content
1..6
# Looks like you failed 1 test of 6.
UPD
似乎Mojo::Test对象除了the request and response objects from the previous transaction之外还应该保存会话对象
【问题讨论】:
-
能否提供一个可运行的测试用例?
-
@daxim:已应用测试脚本。
-
对于简单的会话,会话数据存储在客户端的 cookie 中,如果没有客户端使用 cookie 的请求,该 cookie 将不可用。
-
@Pradeep 对于 OP 尝试执行的操作,会话数据如何存储并不重要。他希望此时能够访问当前用户请求的会话。我认为这个问题是
$t->app为您提供了应用程序对象,但没有提供最近完成的请求的上下文。但是您的评论非常有用,因为如果它在客户端的 cookie 中,您可以阅读它。$t->ua毕竟是客户端,在测试中你直接控制它。不过有点hacky。 -
间接相关,我已经用我的模块 Test::WWW::Mechanize::Catalyst::WithContext 为 Catalyst 解决了这个问题。您可能可以采用类似的方法,或者(根据我的经验,Mojo 有时是这样)解决方案可能更简单但并不明显。
标签: perl testing mojolicious