Added search API and tests.

This commit is contained in:
Paul Dill 2017-02-20 04:23:14 +00:00
parent 67d764638a
commit ed5bbda6db
3 changed files with 396 additions and 8 deletions

View file

@ -33,10 +33,81 @@ helper db => sub { $dbh };
any '/' => sub {
my $self = shift;
return $self->render(text => 'If you are seeing this, then the server is running.', success => Mojo::JSON->true);
};
#TODO this should limit the number of responses returned, when location is implemented that would be the main way of filtering.
post '/search' => sub {
my $self = shift;
my $userId = $self->get_active_user_id();
my $json = $self->req->json;
if ( ! defined $json ) {
$self->app->log->debug('Path Error: file:' . __FILE__ . ', line: ' . __LINE__);
return $self->render( json => {
success => Mojo::JSON->false,
message => 'JSON is missing.',
},
status => 400,); #Malformed request
}
my $searchName = $json->{searchName};
if ( ! defined $searchName ) {
$self->app->log->debug('Path Error: file:' . __FILE__ . ', line: ' . __LINE__);
return $self->render( json => {
success => Mojo::JSON->false,
message => 'searchName is missing.',
},
status => 400,); #Malformed request
}
#Is blank
elsif ( $searchName =~ m/^\s*$/) {
$self->app->log->debug('Path Error: file:' . __FILE__ . ', line: ' . __LINE__);
return $self->render( json => {
success => Mojo::JSON->false,
message => 'searchName is blank.',
},
status => 400,); #Malformed request
}
#Currently ingnored
#TODO implement further.
my $searchLocation = $json->{searchLocation};
my @validatedOrgs = ();
{
my $statementValidated = $dbh->prepare("SELECT OrganisationalId, Name, FullAddress, PostCode FROM Organisations WHERE Name LIKE ?");
$statementValidated->execute('%'.$searchName.'%');
while (my ($id, $name, $address, $postcode) = $statementValidated->fetchrow_array()) {
push(@validatedOrgs, $self->create_hash_valid($id,$name,$address,$postcode));
}
}
#$self->app->log->debug( "Orgs: " . Dumper @validatedOrgs );
my @unvalidatedOrgs = ();
{
my $statementUnvalidated = $dbh->prepare("SELECT PendingOrganisationId, Name, StreetName, Town, Postcode FROM PendingOrganisations WHERE Name LIKE ? AND UserSubmitted_FK = ?");
$statementUnvalidated->execute('%'.$searchName.'%', $userId);
while (my ($id, $name, $streetName, $town, $postcode) = $statementUnvalidated->fetchrow_array()) {
push(@unvalidatedOrgs, $self->create_hash_unvalid($id, $name, $streetName, $town, $postcode));
}
}
$self->app->log->debug('Path Success: file:' . __FILE__ . ', line: ' . __LINE__);
return $self->render( json => {
success => Mojo::JSON->true,
unvalidated => \@unvalidatedOrgs,
validated => \@validatedOrgs,
},
status => 200,);
};
post '/upload' => sub {
my $self = shift;
@ -712,6 +783,53 @@ post '/fetchuser' => sub {
});
};
helper create_hash_valid => sub{
my ($self, $id, $name, $fullAddress, $postcode) = @_;
my $hash = {};
$hash->{'id'} = $id;
$hash->{'name'} = $name;
$hash->{'fullAddress'} = $fullAddress . ", " . $postcode;
return $hash;
};
helper create_hash_unvalid => sub{
my ($self, $id, $name, $streetName, $town, $postcode) = @_;
my $hash = {};
$hash->{'id'} = $id;
$hash->{'name'} = $name;
my $fullAddress = "";
if (defined $streetName && ! ($streetName =~ m/^\s+$/)){
$fullAddress = $streetName;
}
if (defined $town && ! ($town =~ m/^\s+$/)){
if ($fullAddress eq ""){
$fullAddress = $town;
}
else{
$fullAddress = $fullAddress . ", " . $town;
}
}
if (defined $postcode && ! ($postcode =~ m/^\s+$/)){
if ($fullAddress eq ""){
$fullAddress = $postcode;
}
else{
$fullAddress = $fullAddress . ", " . $postcode;
}
}
$hash->{'fullAddress'} = $fullAddress;
return $hash;
};
helper valid_username => sub {
my ($self, $username) = @_;

View file

@ -1,8 +1,8 @@
CREATE TABLE Organisations (
OrganisationalId INTEGER PRIMARY KEY UNIQUE NOT NULL,
Name TEXT NOT NULL,
FullAddress TEXT NOT NULL,
PostCode TEXT NOT NULL
Name TEXT NOT NULL COLLATE nocase,
FullAddress TEXT NOT NULL COLLATE nocase,
PostCode TEXT NOT NULL COLLATE nocase
);
CREATE TABLE AgeRanges (
@ -63,10 +63,10 @@ CREATE TABLE PendingOrganisations (
PendingOrganisationId INTEGER PRIMARY KEY UNIQUE NOT NULL,
UserSubmitted_FK INTEGER NOT NULL,
TimeDateSubmitted INTEGER NOT NULL,
Name TEXT NOT NULL,
StreetName TEXT,
Town TEXT,
Postcode TEXT,
Name TEXT NOT NULL COLLATE nocase,
StreetName TEXT COLLATE nocase,
Town TEXT COLLATE nocase,
Postcode TEXT COLLATE nocase,
FOREIGN KEY (UserSubmitted_FK) REFERENCES Users (UserId)
);

270
t/search.t Normal file
View file

@ -0,0 +1,270 @@
use Test::More;
use Test::Mojo;
use Mojo::JSON;
use Text::ParseWords;
use FindBin;
$ENV{MOJO_MODE} = 'development';
$ENV{MOJO_LOG_LEVEL} = 'debug';
require "$FindBin::Bin/../foodloopserver.pl";
my $t = Test::Mojo->new;
my $dbh = $t->app->db;
#Dump all pf the test tables and start again.
my $sqlDeployment = Mojo::File->new("$FindBin::Bin/../dropschema.sql")->slurp;
for (split ';', $sqlDeployment){
$dbh->do($_) or die $dbh->errstr;
}
my $sqlDeployment = Mojo::File->new("$FindBin::Bin/../schema.sql")->slurp;
for (split ';', $sqlDeployment){
$dbh->do($_) or die $dbh->errstr;
}
my @accountTokens = ('a', 'b');
my $tokenStatement = $dbh->prepare('INSERT INTO AccountTokens (AccountTokenName) VALUES (?)');
foreach (@accountTokens){
my $rowsAdded = $tokenStatement->execute($_);
}
#TODO this should be done via the API but as that does not exist at the moment, just add them manually.
my $statement = $dbh->prepare("INSERT INTO Organisations (OrganisationalId, Name, FullAddress, PostCode) VALUES (?, ?, ?, ?)");
my $value = 1;
my ($name, $address, $postcode) = ("Avanti Bar & Restaurant","57 Main St, Kirkby Lonsdale, Cumbria","LA6 2AH");
$statement->execute($value, $name, $address, $postcode);
$value++;
my ($name, $address, $postcode) = ("Full House Noodle Bar","21 Common Garden St, Lancaster, Lancashire","LA1 1XD");
$statement->execute($value, $name, $address, $postcode);
$value++;
my ($name, $address, $postcode) = ("The Quay's Fishbar","1 Adcliffe Rd, Lancaster","LA1 1SS");
$statement->execute($value, $name, $address, $postcode);
$value++;
my ($name, $address, $postcode) = ("Dan's Fishop","56 North Rd, Lancaster","LA1 1LT");
$statement->execute($value, $name, $address, $postcode);
$value++;
my ($name, $address, $postcode) = ("Hodgeson's Chippy","96 Prospect St, Lancaster","LA1 3BH");
$statement->execute($value, $name, $address, $postcode);
#This depends on "register.t", "login.t" and "upload.t" working.
#test with a customer.
print "test 1 - Create customer user account (Rufus)\n";
my $emailRufus = 'rufus@shinra.energy';
my $passwordRufus = 'MakoGold';
my $testJson = {
'usertype' => 'customer',
'token' => shift(@accountTokens),
'username' => 'RufusShinra',
'email' => $emailRufus,
'postcode' => 'LA1 1CF',
'password' => $passwordRufus,
'age' => '20-35'
};
$t->post_ok('/register' => json => $testJson)
->status_is(200)
->json_is('/success', Mojo::JSON->true);
#test with an organisation.
print "test 2 - Create organisation user account (Choco Billy)\n";
my $emailBilly = 'choco.billy@chocofarm.org';
my $passwordBilly = 'Choco';
my $testJson = {
'usertype' => 'organisation',
'token' => shift(@accountTokens),
'username' => 'ChocoBillysGreens',
'email' => $emailBilly,
'postcode' => 'LA1 1HT',
'password' => $passwordBilly,
'fulladdress' => 'Market St, Lancaster'
};
$t->post_ok('/register' => json => $testJson)
->status_is(200)
->json_is('/success', Mojo::JSON->true);
sub login_rufus {
$testJson = {
'email' => $emailRufus,
'password' => $passwordRufus,
};
$t->post_ok('/login' => json => $testJson)
->status_is(200)
->json_is('/success', Mojo::JSON->true);
};
sub login_billy {
$testJson = {
'email' => $emailBilly,
'password' => $passwordBilly,
};
$t->post_ok('/login' => json => $testJson)
->status_is(200)
->json_is('/success', Mojo::JSON->true);
};
sub log_out{
$t->post_ok('/logout')
->status_is(200)
->json_is('/success', Mojo::JSON->true);
}
######################################################
#Login as Rufus (customer)
print "test 3 - Login - Rufus (cookies, customer)\n";
login_rufus();
print "test 4 - Added something containing 'fish'\n";
$json = {
microCurrencyValue => 10,
transactionAdditionType => 3,
organisationName => 'Shoreway Fisheries',
streetName => "2 James St",
town => "Lancaster",
postcode => "LA1 1UP"
};
my $upload = {json => Mojo::JSON::encode_json($json), file2 => {file => './t/test.jpg'}};
$t->post_ok('/upload' => form => $upload )
->status_is(200)
->json_is('/success', Mojo::JSON->true);
print "test 5 - Logout Rufus \n";
log_out();
#End of Rufus (customer)
######################################################
#Login as Choco billy (organisation)
print "test 6 - Login - Choco billy (cookies, organisation)\n";
login_billy();
print "test 7 - Added something containing 'bar'\n";
$json = {
microCurrencyValue => 10,
transactionAdditionType => 3,
organisationName => 'The Palatine Bar',
streetName => "The Crescent",
town => "Morecambe",
postcode => "LA4 5BZ"
};
my $upload = {json => Mojo::JSON::encode_json($json), file2 => {file => './t/test.jpg'}};
$t->post_ok('/upload' => form => $upload )
->status_is(200)
->json_is('/success', Mojo::JSON->true);
print "test 8 - Added another thing containing 'bar'\n";
$json = {
microCurrencyValue => 10,
transactionAdditionType => 3,
organisationName => 'The Sun Hotel & Bar',
streetName => "63-65 Church Street",
town => "Lancaster",
postcode => "LA1 1ET"
};
my $upload = {json => Mojo::JSON::encode_json($json), file2 => {file => './t/test.jpg'}};
$t->post_ok('/upload' => form => $upload )
->status_is(200)
->json_is('/success', Mojo::JSON->true);
print "test 9 - Logout Choco billy \n";
log_out();
#End of Choco billy (organisation)
######################################################
#Login as Rufus (customer)
print "test 10 - Login - Rufus (cookies, customer)\n";
login_rufus();
print "test 11 - search blank\n";
$t->post_ok('/search' => json => {searchName => " "})
->status_is(400)
->json_is('/success', Mojo::JSON->false)
->content_like(qr/searchName is blank/i);
sub check_vars{
my ($searchTerm, $numValidated, $numUnvalidated) = @_;
$t->post_ok('/search' => json => {searchName => $searchTerm})
->status_is(200)
->json_is('/success', Mojo::JSON->true)
->json_has("unvalidated")
->json_has("validated");
my $sessionJsonTest = $t->tx->res->json;
my $validated = $sessionJsonTest->{validated};
my $unvalidated = $sessionJsonTest->{unvalidated};
my $validSize = scalar @$validated;
my $unvalidSize = scalar @$unvalidated;
is $validSize,$numValidated,"validated returned - " . $searchTerm;
is $unvalidSize,$numUnvalidated,"unvalidated returned - " . $searchTerm;
};
print "test 12 - Testing expected values with 'booths'\n";
#Expect 0 validated and 0 unvalidated with "bar".
check_vars("booths", 0, 0);
print "test 13 - Testing expected values with 'chip'\n";
#Expect 2 validated and 0 unvalidated with "chip".
check_vars("chip", 1, 0);
print "test 14 - Testing expected values with 'fish, with one unvalidated organisation'\n";
#Expect 2 validated and 1 unvalidated with "fish".
check_vars("fish", 2, 1);
print "test 15 - Testing expected values with 'bar'\n";
#Expect 3 validated and 0 unvalidated with "bar".
check_vars("bar", 3, 0);
print "test 16 - Logout Rufus \n";
log_out();
#End of Rufus (customer)
######################################################
#Login as Choco billy (organisation)
print "test 17 - Login - Choco billy (cookies, organisation)\n";
login_billy();
print "test 18 - Testing expected values with 'booths'\n";
#Expect 0 validated and 0 unvalidated with "bar".
check_vars("booths", 0, 0);
print "test 19 - Testing expected values with 'chip'\n";
#Expect 2 validated and 0 unvalidated with "chip".
check_vars("chip", 1, 0);
print "test 20 - Testing expected values with 'fish'\n";
#Expect 2 validated and 0 unvalidated with "fish".
check_vars("fish", 2, 0);
print "test 21 - Testing expected values with 'bar', with two unvalidated organisations\n";
#Expect 3 validated and 2 unvalidated with "bar".
check_vars("bar", 3, 2);
print "test 22 - Logout Choco billy \n";
log_out();
done_testing();