How do I fake the client IP address in a unit test for a Mojolicious app?

让人想犯罪 __ 提交于 2019-12-04 00:30:32

The author of Mojolicious pointed out on IRC to look at the unit tests in the Mojo dist for the X-Forwarded-For header implementation, so I did.

We need to set the $ENV{MOJO_REVERSE_PROXY} to a true value in the unit test and restart the server, then send an X-Forwarded-For header with the new IP address and things will just work.

use strict;
use warnings;
use Test::More;
use Test::Mojo;
use Mojolicious::Lite;

get '/foo' => sub { my $c = shift; $c->render( text => $c->tx->remote_address ) };

my $t = Test::Mojo->new;
$t->get_ok('/foo')->content_like(qr/\Q127.0.0.1/);

{
    local $ENV{MOJO_REVERSE_PROXY} = 1;
    $t->ua->server->restart;
    $t->get_ok( '/foo' => { 'X-Forwarded-For' => '10.1.1.1' } )->content_like(qr/\Q10.1.1.1/);
}

done_testing;

The tests now pass.

ok 1 - GET /foo
ok 2 - content is similar
ok 3 - GET /foo
ok 4 - content is similar
1..4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!