lundi 23 novembre 2015

Test Mojolicious app after authentication

I'm using Test::Mojo to test a Mojolicious application JSON endpoints where it has an endpoint that would return different data depending on whether the user was authenticated or not, however, I can't seem to get the unauthenticated test part correctly.

The Mojolicious app is configured with Mojolicious::Plugin::Authentication.

I assumed that I can have the backend authenticated by running authenticate against the controller then test against it using the same Test::Mojo instance after I have extracted the cookie from the controller's response object.

Here's what I've done so far:

use FindBin;
use Test::More;
use Test::Mojo;
use MyApp;

BEGIN {
  $ENV{MOJO_MODE} = 'test';
  $ENV{MOJO_LOG_LEVEL} = 'fatal';
  unshift @INC, "$FindBin::Bin/../../lib", "$FindBin::Bin/../lib";
}

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

subtest 'Accounts endpoint' => sub {
  subtest 'Accounts - Unauthenticated' => sub {
    $t->get_ok('/api/account/' . $id)
      ->status_is(200)
      ->content_type_like(qr/application\/json/, 'JSON Contenet Type')
      ->json_has('/account/_id')
      ->json_hasnt('/account/active')
      ->json_hasnt('/account/subscription');
  };

  subtest 'Accounts - Authenticated' => sub {
    my $c = $t->app->build_controller;
    $c->session(expiration => time + 300);
    $c->render;

    $t->ua->on(start => sub {
      my ($ua, $tx) = @_;
      # $ua->cookie_jar->add($cookie);

      $tx->req->cookies({name => $c->res->cookie('mojolicious')->name, value => $c->res->cookie('mojolicious')->value});

      # print Dumper $tx->req->cookies, " <<< request cookie\n";
      # print ">>> ", $_->name for @{$ua->cookie_jar->all};
    });


    if ($c->authenticate('username', 'password')) {
      ok $c->is_user_authenticated, 'User was authenticated';
      $t->get_ok('/api/account/' . $id)
        ->status_is(200)
        ->content_type_like(qr/application\/json/, 'JSON Contenet Type')
        ->json_has('/account/_id')
        ->json_has('/account/active')
        ->json_has('/account/subscription');
    }
  };
};

done_testing();

I thought that the problem is once authenticated, the session cookie value should change but in my case the cookie remains unchanged and I believe this is causing the request to send the unauthenticated cookie value and hence the resource is not working.

The question is, how can I retrieve the cookie value after the controller was authenticated against?

Any hint is appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire