Bug 27673: Replace YAML with YAML::XS
[koha-ffzg.git] / t / db_dependent / Search.t
old mode 100644 (file)
new mode 100755 (executable)
index 60da046..3b4e6d3
@@ -19,18 +19,18 @@ use Modern::Perl;
 
 use utf8;
 
-use YAML;
-
 use C4::Debug;
+use C4::AuthoritiesMarc qw( SearchAuthorities );
 use C4::XSLT;
 require C4::Context;
 
 # work around spurious wide character warnings
 use open ':std', ':encoding(utf8)';
 
-use Test::More tests => 2;
+use Test::More tests => 3;
 use Test::MockModule;
 use Test::Warn;
+use t::lib::Mocks;
 
 use Koha::Caches;
 
@@ -93,11 +93,16 @@ END {
     cleanup();
 }
 
+sub matchesExplodedTerms {
+    my ($message, $query, @terms) = @_;
+    my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}";
+    like($query, qr/$match/, $message);
+}
+
 our $QueryStemming = 0;
 our $QueryAutoTruncate = 0;
 our $QueryWeightFields = 0;
 our $QueryFuzzy = 0;
-our $UseQueryParser = 0;
 our $SearchEngine = 'Zebra';
 our $marcflavour = 'MARC21';
 our $htdocs = File::Spec->rel2abs(dirname($0));
@@ -105,7 +110,7 @@ my @htdocs = split /\//, $htdocs;
 $htdocs[-2] = 'koha-tmpl';
 $htdocs[-1] = 'opac-tmpl';
 $htdocs = join '/', @htdocs;
-our $contextmodule = new Test::MockModule('C4::Context');
+our $contextmodule = Test::MockModule->new('C4::Context');
 $contextmodule->mock('preference', sub {
     my ($self, $pref) = @_;
     if ($pref eq 'marcflavour') {
@@ -118,8 +123,6 @@ $contextmodule->mock('preference', sub {
         return $QueryWeightFields;
     } elsif ($pref eq 'QueryFuzzy') {
         return $QueryFuzzy;
-    } elsif ($pref eq 'UseQueryParser') {
-        return $UseQueryParser;
     } elsif ($pref eq 'SearchEngine') {
         return $SearchEngine;
     } elsif ($pref eq 'maxRecordsForFacets') {
@@ -132,7 +135,7 @@ $contextmodule->mock('preference', sub {
         return '';
     } elsif ($pref eq 'opacthemes') {
         return 'bootstrap';
-    } elsif ($pref eq 'opaclanguages') {
+    } elsif ($pref eq 'OPACLanguages') {
         return 'en';
     } elsif ($pref eq 'AlternateHoldingsField') {
         return '490av';
@@ -174,7 +177,7 @@ $contextmodule->mock('preference', sub {
         return '1';
     } elsif ($pref eq 'UseControlNumber') {
         return '0';
-    } elsif ($pref eq 'UseICU') {
+    } elsif ($pref eq 'UseICUStyleQuotes') {
         return '0';
     } elsif ($pref eq 'viewISBD') {
         return '1';
@@ -196,13 +199,8 @@ $contextmodule->mock('preference', sub {
         return 0;
     }
 });
-$contextmodule->mock('queryparser', sub {
-    my $QParser     = Koha::QueryParser::Driver::PQF->new();
-    $QParser->load_config("$datadir/etc/searchengine/queryparser.yaml");
-    return $QParser;
-});
 
-our $bibliomodule = new Test::MockModule('C4::Biblio');
+our $bibliomodule = Test::MockModule->new('C4::Biblio');
 
 sub mock_GetMarcSubfieldStructure {
     my $marc_type = shift;
@@ -212,6 +210,7 @@ sub mock_GetMarcSubfieldStructure {
                     'biblio.biblionumber' => [{ tagfield =>  '999', tagsubfield => 'c' }],
                     'biblio.isbn' => [{ tagfield => '020', tagsubfield => 'a' }],
                     'biblio.title' => [{ tagfield => '245', tagsubfield => 'a' }],
+                    'biblio.author' => [{ tagfield => '100', tagsubfield => 'a' }],
                     'biblio.notes' => [{ tagfield => '500', tagsubfield => 'a' }],
                     'items.barcode' => [{ tagfield => '952', tagsubfield => 'p' }],
                     'items.booksellerid' => [{ tagfield => '952', tagsubfield => 'e' }],
@@ -259,7 +258,7 @@ sub run_marc21_search_tests {
     Koha::Caches->get_instance('config')->flush_all;
 
     mock_GetMarcSubfieldStructure('marc21');
-    my $context = new C4::Context("$datadir/etc/koha-conf.xml");
+    my $context = C4::Context->new("$datadir/etc/koha-conf.xml");
     $context->set_context();
 
     use_ok('C4::Search');
@@ -269,7 +268,6 @@ sub run_marc21_search_tests {
     $QueryAutoTruncate = 0;
     $QueryWeightFields = 0;
     $QueryFuzzy = 0;
-    $UseQueryParser = 0;
     $marcflavour = 'MARC21';
 
     my $indexes = C4::Search::getIndexes();
@@ -277,7 +275,7 @@ sub run_marc21_search_tests {
     is(scalar(grep(/^arl$/, @$indexes)), 1, "Accelerated reading level index supported");
     is(scalar(grep(/^arp$/, @$indexes)), 1, "Accelerated reading point index supported");
 
-    my $bibliomodule = new Test::MockModule('C4::Biblio');
+    my $bibliomodule = Test::MockModule->new('C4::Biblio');
 
     my %branches = (
         'CPL' => { 'branchaddress1' => 'Jefferson Summit', 'branchcode' => 'CPL', 'branchname' => 'Centerville', },
@@ -295,14 +293,14 @@ sub run_marc21_search_tests {
         'UPL' => { 'branchaddress1' => 'Chestnut Hollow', 'branchcode' => 'UPL', 'branchname' => 'Union', },
     );
     my %itemtypes = (
-        'BK' => { 'imageurl' => 'bridge/book.gif', 'summary' => '', 'itemtype' => 'BK', 'description' => 'Books' },
-        'CF' => { 'imageurl' => 'bridge/computer_file.gif', 'summary' => '', 'itemtype' => 'CF', 'description' => 'Computer Files' },
-        'CR' => { 'imageurl' => 'bridge/periodical.gif', 'summary' => '', 'itemtype' => 'CR', 'description' => 'Continuing Resources' },
-        'MP' => { 'imageurl' => 'bridge/map.gif', 'summary' => '', 'itemtype' => 'MP', 'description' => 'Maps' },
-        'MU' => { 'imageurl' => 'bridge/sound.gif', 'summary' => '', 'itemtype' => 'MU', 'description' => 'Music' },
-        'MX' => { 'imageurl' => 'bridge/kit.gif', 'summary' => '', 'itemtype' => 'MX', 'description' => 'Mixed Materials' },
+        'BK' => { 'imageurl' => 'bridge/book.png', 'summary' => '', 'itemtype' => 'BK', 'description' => 'Books' },
+        'CF' => { 'imageurl' => 'bridge/computer_file.png', 'summary' => '', 'itemtype' => 'CF', 'description' => 'Computer Files' },
+        'CR' => { 'imageurl' => 'bridge/periodical.png', 'summary' => '', 'itemtype' => 'CR', 'description' => 'Continuing Resources' },
+        'MP' => { 'imageurl' => 'bridge/map.png', 'summary' => '', 'itemtype' => 'MP', 'description' => 'Maps' },
+        'MU' => { 'imageurl' => 'bridge/sound.png', 'summary' => '', 'itemtype' => 'MU', 'description' => 'Music' },
+        'MX' => { 'imageurl' => 'bridge/kit.png', 'summary' => '', 'itemtype' => 'MX', 'description' => 'Mixed Materials' },
         'REF' => { 'imageurl' => '', 'summary' => '', 'itemtype' => 'REF', 'description' => 'Reference' },
-        'VM' => { 'imageurl' => 'bridge/dvd.gif', 'summary' => '', 'itemtype' => 'VM', 'description' => 'Visual Materials' },
+        'VM' => { 'imageurl' => 'bridge/dvd.png', 'summary' => '', 'itemtype' => 'VM', 'description' => 'Visual Materials' },
     );
 
     index_sample_records_and_launch_zebra($datadir, 'marc21');
@@ -485,19 +483,6 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'
     is($results_hashref->{biblioserver}->{hits}, 12,
        'search using index whose name contains "ns" returns expected results (bug 10271)');
 
-    $UseQueryParser = 1;
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ 'book' ], [ 'kw' ], [], [], 0, 'en');
-    ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
-    is($results_hashref->{biblioserver}->{hits}, 101, "Search for 'book' with index set to 'kw' returns 101 hits");
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([ 'and' ], [ 'book', 'another' ], [ 'kw', 'kw' ], [], [], 0, 'en');
-    ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
-    is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'kw:book && kw:another' returns 1 hit");
-    $UseQueryParser = 0;
-
     ( $error, $query, $simple_query, $query_cgi,
     $query_desc, $limit, $limit_cgi, $limit_desc,
     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'available' ], [], 0, 'en');
@@ -513,6 +498,64 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'
     }
     is ($allavailable, 'true', 'All records have at least one item available');
 
+    my $mocked_xslt = Test::MockModule->new('Koha::XSLT::Base');
+    $mocked_xslt->mock( 'transform', sub {
+        my ($self, $xml) = @_;
+        return $xml;
+    });
+
+    @newresults = searchResults({'interface'=>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
+        $results_hashref->{'biblioserver'}->{"RECORDS"}, { anonymous_session => 1 });
+
+    like( $newresults[0]->{XSLTResultsRecord}, qr/<variable name="anonymous_session">1<\/variable>/, "Variable injected correctly" );
+
+    my $biblio_id = $newresults[0]->{biblionumber};
+    my $fw = C4::Biblio::GetFrameworkCode($biblio_id);
+
+    my $dbh = C4::Context->dbh;
+    # Hide subfield 'p' in OPAC
+    $dbh->do(qq{
+        UPDATE marc_subfield_structure
+        SET hidden=4
+        WHERE frameworkcode='$fw' AND
+              tagfield=952 AND
+              tagsubfield='p';
+    });
+
+    # Hide subfield 'y' in Staff
+    $dbh->do(qq{
+        UPDATE marc_subfield_structure
+        SET hidden=-7
+        WHERE frameworkcode='$fw' AND
+              tagfield=952 AND
+              tagsubfield='y';
+    });
+
+    Koha::Caches->get_instance->flush_all;
+
+    @newresults = searchResults(
+        { 'interface' => 'opac' },
+        $query_desc,
+        $results_hashref->{'biblioserver'}->{'hits'},
+        17,
+        0,
+        0,
+        $results_hashref->{'biblioserver'}->{"RECORDS"}
+    );
+
+    unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="p">TEST11111<\/subfield>/, '952\$p hidden in OPAC' );
+
+    @newresults = searchResults(
+        { 'interface' => 'intranet' },
+        $query_desc,
+        $results_hashref->{'biblioserver'}->{'hits'},
+        17,
+        0,
+        0,
+        $results_hashref->{'biblioserver'}->{"RECORDS"}
+    );
+
+    unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="y">Books<\/subfield>/, '952\$y hidden on staff interface' );
 
     ( $error, $query, $simple_query, $query_cgi,
     $query_desc, $limit, $limit_cgi, $limit_desc,
@@ -623,7 +666,13 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'
     ( $error, $query, $simple_query, $query_cgi,
     $query_desc, $limit, $limit_cgi, $limit_desc,
     $query_type ) = buildQuery([], [ 0 ], [ 'su,phr' ], [], [], 0, 'en');
-    is($query, 'su,phr=0 ', 'buildQuery should keep 0 value');
+    is($query, 'su,phr=(rk=(0)) ', 'buildQuery should keep 0 value');
+
+    # Bug 23086
+    ( $error, $query, $simple_query, $query_cgi,
+    $query_desc, $limit, $limit_cgi, $limit_desc,
+    $query_type ) = buildQuery([], [], [], [ 'mc-ccode:NF(IC'], [], 0, 'en');
+    like($query, qr/ccode="NF\(IC"/, "Limit quoted correctly");
 
     # Let's see what happens when we pass bad data into these routines.
     # We have to catch warnings since we're not very good about returning errors.
@@ -651,7 +700,7 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'
     ## Regression test for Bug 10741
 
     # make one of the test items appear to be in transit
-    my $circ_module = new Test::MockModule('C4::Circulation');
+    my $circ_module = Test::MockModule->new('C4::Circulation');
     $circ_module->mock('GetTransfers', sub {
         my $itemnumber = shift // -1;
         if ($itemnumber == 11) {
@@ -677,89 +726,6 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'
                 "Warning is raised correctly for invalid tags in MARC::Record";
     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
 
-    # Testing exploding indexes
-    my $term;
-    my $searchmodule = new Test::MockModule('C4::Search');
-    $searchmodule->mock('SimpleSearch', sub {
-        my $query = shift;
-
-        is($query, "he:$term", "Searching for expected term '$term' for exploding") or return '', [], 0;
-
-        my $record = MARC::Record->new;
-        if ($query =~ m/Arizona/) {
-            $record->add_fields(
-                [ '001', '1234' ],
-                [ '151', ' ', ' ', a => 'Arizona' ],
-                [ '551', ' ', ' ', a => 'United States', w => 'g' ],
-                [ '551', ' ', ' ', a => 'Maricopa County', w => 'h' ],
-                [ '551', ' ', ' ', a => 'Navajo County', w => 'h' ],
-                [ '551', ' ', ' ', a => 'Pima County', w => 'h' ],
-                [ '551', ' ', ' ', a => 'New Mexico' ],
-                );
-        }
-        return '', [ $record->as_usmarc() ], 1;
-    });
-
-    $UseQueryParser = 1;
-    $term = 'Arizona';
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ $term ], [ 'su-br' ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Advanced search for broader subjects", $query, 'Arizona', 'United States');
-
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ $term ], [ 'su-na' ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Advanced search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
-
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ $term ], [ 'su-rl' ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Advanced search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
-
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ "$term", 'history' ], [ 'su-rl', 'kw' ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Advanced search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
-    like($query, qr/history/, "Advanced search for related subjects and keyword 'history' searches for 'history'");
-
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ 'history', "$term" ], [ 'kw', 'su-rl' ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Order of terms doesn't matter for advanced search", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
-    like($query, qr/history/, "Order of terms doesn't matter for advanced search");
-
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ "su-br($term)" ], [  ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Simple search for broader subjects", $query, 'Arizona', 'United States');
-
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ "su-na($term)" ], [  ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Simple search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
-
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ "su-rl($term)" ], [  ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Simple search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
-
-    ( $error, $query, $simple_query, $query_cgi,
-    $query_desc, $limit, $limit_cgi, $limit_desc,
-    $query_type ) = buildQuery([], [ "history && su-rl($term)" ], [  ], [  ], [], 0, 'en');
-    matchesExplodedTerms("Simple search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
-    like($query, qr/history/, "Simple search for related subjects and keyword 'history' searches for 'history'");
-
-    sub matchesExplodedTerms {
-        my ($message, $query, @terms) = @_;
-        my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}";
-        like($query, qr/$match/, $message);
-    }
-
-    # authority records
-    use_ok('C4::AuthoritiesMarc');
-    $UseQueryParser = 0;
-
     my ($auths, $count) = SearchAuthorities(
         ['mainentry'], ['and'], [''], ['starts'],
         ['shakespeare'], 0, 10, '', '', 1
@@ -791,29 +757,6 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'
     );
     is($count, 1, 'MARC21 authorities: one hit on "all" (entire record) contains "professional wrestler"');
 
-    $UseQueryParser = 1;
-
-    ($auths, $count) = SearchAuthorities(
-        ['mainentry'], ['and'], [''], ['starts'],
-        ['shakespeare'], 0, 10, '', '', 1
-    );
-    is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" (QP)');
-    ($auths, $count) = SearchAuthorities(
-        ['mainentry'], ['and'], [''], ['starts'],
-        ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
-    );
-    is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending (QP)');
-    ($auths, $count) = SearchAuthorities(
-        ['mainentry'], ['and'], [''], ['starts'],
-        ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
-    );
-    is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending (QP)');
-    ($auths, $count) = SearchAuthorities(
-        ['match'], ['and'], [''], ['contains'],
-        ['沙士北亞威廉姆'], 0, 10, '', '', 1
-    );
-    is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆" (QP)');
-
     # retrieve records that are larger than the MARC limit of 99,999 octets
     ( undef, $results_hashref, $facets_loop ) =
         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef);
@@ -889,7 +832,7 @@ sub run_unimarc_search_tests {
     Koha::Caches->get_instance('config')->flush_all;
 
     mock_GetMarcSubfieldStructure('unimarc');
-    my $context = new C4::Context("$datadir/etc/koha-conf.xml");
+    my $context = C4::Context->new("$datadir/etc/koha-conf.xml");
     $context->set_context();
 
     use_ok('C4::Search');
@@ -899,7 +842,6 @@ sub run_unimarc_search_tests {
     $QueryAutoTruncate = 0;
     $QueryWeightFields = 0;
     $QueryFuzzy = 0;
-    $UseQueryParser = 0;
     $marcflavour = 'UNIMARC';
 
     index_sample_records_and_launch_zebra($datadir, 'unimarc');
@@ -917,7 +859,6 @@ sub run_unimarc_search_tests {
 
     # authority records
     use_ok('C4::AuthoritiesMarc');
-    $UseQueryParser = 0;
 
     my ($auths, $count) = SearchAuthorities(
         ['mainentry'], ['and'], [''], ['contains'],
@@ -971,7 +912,7 @@ sub run_unimarc_search_tests {
 }
 
 subtest 'MARC21 + DOM' => sub {
-    plan tests => 112;
+    plan tests => 88;
     run_marc21_search_tests();
 };
 
@@ -980,6 +921,42 @@ subtest 'UNIMARC + DOM' => sub {
     run_unimarc_search_tests();
 };
 
+
+subtest 'FindDuplicate' => sub {
+    plan tests => 3;
+    Koha::Caches->get_instance('config')->flush_all;
+    t::lib::Mocks::mock_preference('marcflavour', 'marc21' );
+    mock_GetMarcSubfieldStructure('marc21');
+    my $searcher = Test::MockModule->new('C4::Search');
+    $searcher->mock('SimpleSearch', sub {
+        warn shift @_;
+        return 1;
+    });
+
+    my $record = MARC::Record->new;
+    $record->add_fields(
+            [ '100', '0', '0', a => 'Morgenstern, Erin' ],
+            [ '245', '0', '0', a => 'The night circus /' ]
+    );
+    warning_is { C4::Search::FindDuplicate($record);}
+        q/ti,ext:"The night circus \/" and au,ext:"Morgenstern, Erin"/,"Term correctly formed";
+
+    $record = MARC::Record->new;
+    $record->add_fields(
+            [ '245', '0', '0', a => 'The book of nothing /' ]
+    );
+    warning_is { C4::Search::FindDuplicate($record);}
+        q/ti,ext:"The book of nothing \/"/,"Term correctly formed";
+
+    $record = MARC::Record->new;
+    $record->add_fields(
+            [ '245', '0', '0', a => 'Frog and toad all year /' ]
+    );
+    warning_is { C4::Search::FindDuplicate($record);}
+        q/ti,ext:"Frog and toad all year \/"/,"Term correctly formed";
+
+};
+
 # Make sure that following tests are not using our config settings
 Koha::Caches->get_instance('config')->flush_all;