Perl 使用Test::Mojo测试URL生成

Perl 使用Test::Mojo测试URL生成,perl,testing,mojolicious,Perl,Testing,Mojolicious,我正在为我的mojolicous应用程序编写一系列测试,我想使用json\u is断言来检查应用程序返回的输出。问题是该应用程序返回一些绝对URL,如下所示: http://localhost:56144/foo …而且TCP端口是随机的,所以我不知道要根据什么检查输出。有没有办法找到根应用程序URL?或者用另一种方式编写测试?如果我理解你的问题,你可以检查你的随机url,如下所示: use Test::More; use Test::Mojo; use Mojo::URL; my $t =

我正在为我的mojolicous应用程序编写一系列测试,我想使用
json\u is
断言来检查应用程序返回的输出。问题是该应用程序返回一些绝对URL,如下所示:

http://localhost:56144/foo

…而且TCP端口是随机的,所以我不知道要根据什么检查输出。有没有办法找到根应用程序URL?或者用另一种方式编写测试?

如果我理解你的问题,你可以检查你的随机url,如下所示:

use Test::More;
use Test::Mojo;
use Mojo::URL;

my $t = Test::Mojo->new('MyApp');

$t->post_ok('/search.json')->status_is(200);
# suppose that result something like this {"url":"http://random_domain.ru:1234/foo/bar"}
my $params = $t->tx->res->json;
my $url = Mojo::URL->new($params->{url});
is($url->path, '/foo/bar', 'test url path');
like($url->port, qr/^\d+$/, 'test port');
is($url->scheme, 'http', 'test scheme');

在深入挖掘源代码后,我发现我可以从用户代理中提取服务器URL:

my $t = Test::Mojo->new('MyAppName');
diag $t->ua->server->url; # http://localhost:59475/
   my $t = Test::Mojo->new('MyApp');
   isnt($t->ua->server->url, $t->app->ua->server->url);

只是为了进一步混淆,如果你在应用程序中添加了一个用户代理,你会发现应用程序的用户代理与Test::Mojo的用户代理是分开的:

my $t = Test::Mojo->new('MyAppName');
diag $t->ua->server->url; # http://localhost:59475/
   my $t = Test::Mojo->new('MyApp');
   isnt($t->ua->server->url, $t->app->ua->server->url);

正如Logionitz指出的,您可以告诉测试使用URL的最后一部分,“主机:端口”部分由负责(请参阅该链接处的文档)。但这是你真正的问题还是有更多的问题?我不知道我可以从
$t->tx
中提取东西,所以Logioniz的答案很有帮助。在我的例子中,从用户代理读取服务器根URL要短一些——请参阅我自己的答案。谢谢谢谢,这很有帮助(我甚至不知道
$t->tx
)。