#!perl
use Cassandane::Tiny;

sub test_top_args ($self)
{
    xlog $self, "Testing whether the TOP command checks its arguments [Bug 3641]";
    # Note, the POP client checks its arguments before sending
    # them so we have to reach around it to do bad things.

    xlog $self, "Ensure a message exists, before logging in to POP";
    my %exp;
    $exp{A} = $self->make_message('Message A');

    my $client = $self->{pop_store}->get_client();

    xlog $self, "TOP with no arguments should return an error";
    my $r = $client->command('TOP')->response();
    $self->assert_equals($r, Net::Cmd::CMD_ERROR);
    $self->assert_equals($client->code(), 500);
    $self->assert_matches(qr/Missing argument/, $client->message());

    xlog $self, "TOP with 1 argument should return an error";
    $r = $client->command('TOP', 1)->response();
    $self->assert_equals($r, Net::Cmd::CMD_ERROR);
    $self->assert_equals($client->code(), 500);
    $self->assert_matches(qr/Missing argument/, $client->message());

    xlog $self, "TOP with 2 correct arguments should actually work";
    $r = $client->command('TOP', 1, 2)->response();
    $self->assert_equals($r, Net::Cmd::CMD_OK);
    $self->assert_equals($client->code(), 200);
    my $lines = $client->read_until_dot();
    my %actual;
    $actual{'Message A'} = Cassandane::Message->new(lines => $lines,
                                                    attrs => { uid => 1 });
    $self->check_messages(\%exp, actual => \%actual);

    xlog $self, "TOP with 2 arguments, first one not a number, should return an error";
    $r = $client->command('TOP', '1xyz', 2)->response();
    $self->assert_equals($r, Net::Cmd::CMD_ERROR);
    $self->assert_equals($client->code(), 500);

    xlog $self, "TOP with 2 arguments, second one not a number, should return an error";
    $r = $client->command('TOP', 1, '2xyz')->response();
    $self->assert_equals($r, Net::Cmd::CMD_ERROR);
    $self->assert_equals($client->code(), 500);

    xlog $self, "TOP with 3 arguments should return an error";
    $r = $client->command('TOP', 1, 2, 3)->response();
    $self->assert_equals($r, Net::Cmd::CMD_ERROR);
    $self->assert_equals($client->code(), 500);
    $self->assert_matches(qr/Unexpected extra argument/, $client->message());
}
