I'm trying to automate a test-case in perl using LWP::UserAgent. I need to check the cookie value post login to the application. Have tried the following sample perl script, but while printing I'm getting output in HASH value :
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1 ");
my $req = HTTP::Request->new(POST => 'http://' . $test_IP . '/login');
$req->content_type('application/x-www-form-urlencoded');
my $postdata = 'object={"login":{"username":"test","password":"test"}}';
$req->content($postdata);
print "REQUEST is";
print $req;
my $res = $ua->request($req);
print "RESPONSE is";
print $res;
# Check the outcome of the response
if ($res->is_success) {
print LOG $res->headers()->as_string();
}
else {
print $res->status_line, "\n";
}
my $cookie_jar = HTTP::Cookies->new();
print "cookie is";
$cookie_jar->extract_cookies( $res );
print $cookie_jar->extract_cookies( $res );
print $cookie_jar->as_string;
if( $cookie_jar->as_string =~ m/httponly/i )
{
print "Success";
}
else
{
print "FAILED";
}
Have received the output in HASH value :
REQUEST isHTTP::Request=HASH(0x69e85a0)RESPONSE isHTTP::Response=HASH(0x6aa1d98)cookie isHTTP::Response=HASH(0x6aa1d98)
Please suggest how can I login to the application and can check for the required values (here cookie value).
You're talking about these lines:
Both
$req
and$res
are objects. If you print an object, you get the type of object that it is ("HTTP::Request" for$req
and "HTTP::Response" for$res
). You also see the reference to the object. And as both of these classes implement their objects as hash references, you get two hash references displayed.I'm not sure what you expected to see, but there are two ways to get more useful information from an object.
You can call methods to access the attributes of the object. For example, later in your code, you use both
$res->headers
and$res->status_line
. Both of these classes are subclasses of HTTP::Message, so they both inherit that class'sas_string()
method. So if you just want to see the string that gets sent as your HTTP request or the string that you get back as the HTTP response, you can call$req->as_string()
or$res->as_string()
.You can use a module like Data::Dumper to see all of the internals of your objects. You should really be treating objects as black boxes and just using their published interfaces (the methods as discussed above) but it can sometimes be useful to use a quick 'n' dirty statement like
print Dumper $req
.As for creating a cookie jar, the synopsis for HTTP::Cookies is pretty clear. You create a cookie jar (almost) in the way that you do it and then associate that with your UserAgent object by calling the UA's
cookie_jar()
method. But you need to do that as soon as your UA is created - certainly before you use the UA to make any requests.