Quoting Peter Mottram <[email protected]>:
On 15/01/16 16:57, Dave Cross wrote:
I've been writing tests for a Dancer2 app. I'm using Plack::Test. One
thing that I wanted to test was that logged in users get a different
view of the app to logged out visitors. For that I need to set cookies
on the requests that I'm sending to the test app.
I found this advent calendar article by SawyerX which looked very useful.
http://advent.perldancer.org/2014/12
Following the instructions in that article, I did this:
my $res = $test->request(POST '/login', [ \%test_user_creds ]);
$jar->extract_cookies($res);
I can look at $jar->as_string before and after that line, and I seen
the session cookie being added to the jar.
Later I do this:
my $req = GET "/$private_page";
$jar->add_cookie_header($req);
my $res = $test->request( $req );
This doesn't work. And it doesn't work because the session cookies
don't get added to the request object. $jar is a HTTP::Cookies object,
so I looked at the add_cookie_header() method, to find this code at
the start:
my $self = shift;
my $request = shift || return;
my $url = $request->uri;
my $scheme = $url->scheme;
unless ($scheme =~ /^https?\z/) {
return;
}
This is where my test goes wrong. My request is just "/$private_page"
- it doesn't have a $scheme (or, indeed, a hostname). And I guess it's
obvious that add_cookie_header needs a domain in order to know which
cookies from the jar to add (my jar only has the correct cookies - but
the method can't know that).
Looking at the cookie jar, I see that the cookies have been given the
domain "localhost.local". Can I just add "http://localhost.local" to
the front of my request URL? Is that guaranteed to work in all test
environments?
Am I missing something here or did that code in the advent calendar
article never work?
Any advice much appreciated.
Cheers,
I'm not sure how the code from the advent calendar worked. I always
prefix the url with 'http://localhost' though perhaps 'http://127.0.0.1'
would be a better option in case resolving localhost is somehow broken.
See current pod:
https://metacpan.org/pod/distribution/Dancer2/lib/Dancer2/Manual/Testing.pod#Cookies
Yep. That fixes the problem. Thanks.
Probably worth patching the advent calendar article so no-one else
gets dragged down that dead-end like I did. I'll look at that next week.
Cheers,
Dave...
_______________________________________________
dancer-users mailing list
[email protected]
http://lists.preshweb.co.uk/mailman/listinfo/dancer-users