Skip to content

Instantly share code, notes, and snippets.

@preaction
Created May 7, 2014 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save preaction/ba101a3a1ffad604470e to your computer and use it in GitHub Desktop.
Save preaction/ba101a3a1ffad604470e to your computer and use it in GitHub Desktop.
Test an app that uses Mojo::UserAgent as a proxy
use MyApp;
use Test::Mojo;
{
package MyRESTApp;
# A fake REST app to proxy to
use Mojo::Base 'Mojolicious';
has 'data';
sub startup {
my ( $app ) = @_;
$app->routes->post('/test/proxy')->to( cb => sub {
my ( $self ) = @_;
my $req = $self->req->json;
my $path = join "/", @{ $req->{paths}[0] };
$self->render( json => $app->data->{$path} );
} );
};
}
my $mock_data = {
'md/RSF/EUR=' => {
BID => 1,
ASK => 2,
},
};
my $t = Test::Mojo->new(
MyApp->new(
rest_url => '/test/proxy',
# Set up a UA that accesses our fake Guts REST app
proxy_ua => Mojo::UserAgent->new(
server => Mojo::UserAgent::Server->new(
app => MyRESTApp->new( data => $mock_data ),
),
),
),
);
subtest '/ redirects to application' => sub {
$t->get_ok( '/' )->status_is( 302 )->header_like( Location => qr{/market-data[.]html$} );
};
subtest 'POST proxies to REST app' => sub {
my $req = {
paths => [ [ 'md', 'RSF', 'EUR=' ] ],
};
$t->post_ok( '/' => json => $req )->status_is( 200 )->json_is( $mock_data->{'md/RSF/EUR='} );
};
done_testing;
package MyApp;
use Mojo::Base 'Mojolicious';
=attr rest_url
The URL to the REST API
=cut
has rest_url => 'http://127.0.0.1:8001';
=attr proxy_ua
A Mojo::UserAgent to use for the proxy to the REST API. To be overridden
during testing.
=cut
has proxy_ua => sub { Mojo::UserAgent->new };
sub startup {
my ( $app ) = @_;
my $r = $app->routes;
$r->get( '/' )->to( cb => sub { $_[0]->redirect_to( 'market-data.html' ) } );
# Act as a proxy to get around Cross-Origin Request Security
$r->post('/')->to( cb => sub {
my ( $self ) = @_;
$app->proxy_ua->post(
$app->rest_url => $self->req->body,
sub {
my ( $ua, $tx ) = @_;
$self->render(
format => 'json',
data => $tx->res->body,
);
},
);
} );
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment