【问题标题】:Testing URL generation with Test::Mojo使用 Test::Mojo 测试 URL 生成
【发布时间】:2023-03-18 22:37:01
【问题描述】:

我正在为我的 Mojolicious 应用程序编写一堆测试,我想使用 json_is 断言来检查应用程序返回的输出。问题是该应用程序返回一些像这样的绝对 URL:

http://localhost:56144/foo

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

【问题讨论】:

  • 正如 Logionitz 指出的那样,您可以告诉测试使用 URL 的最后部分,而“host:port”部分由 Test::Mojo 处理(请参阅该链接上的文档)。但这是您真正的问题还是还有更多问题?
  • 我不知道我可以从 $t->tx 中提取内容,所以 Logioniz 的回答有所帮助。不过,在我的情况下,从用户代理读取服务器根 URL 会更短 - 请参阅我自己的答案。谢谢!

标签: perl testing mojolicious


【解决方案1】:

如果我理解您的问题,您可以像这样检查您的随机网址:

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');

【讨论】:

  • 谢谢,这很有帮助(我什至不知道$t->tx)。
【解决方案2】:

在对源代码进行了一些挖掘之后,我发现我可以从用户代理中提取服务器 URL:

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

【讨论】:

    【解决方案3】:

    为了进一步混淆,如果您在应用中使用用户代理,您会发现应用的用户代理与 Test::Mojo 的用户代理是分开的:

       my $t = Test::Mojo->new('MyApp');
       isnt($t->ua->server->url, $t->app->ua->server->url);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多