Update release notes for 22.05.22 release
[koha.git] / t / db_dependent / Breeding.t
1 #!/usr/bin/perl
2
3 # Copyright 2014 Rijksmuseum
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 # Main object of this unit test is the Breeding module and its subroutines
21 # A start has been made to define tests for subroutines of Z3950Search.
22 # These subroutines are actually internal, but these tests may pave the way for
23 # a more comprehensive test of Z3950Search itself.
24
25 use Modern::Perl;
26 use File::Temp qw/tempfile/;
27 use Test::More tests => 5;
28 use Test::Warn;
29
30 use t::lib::Mocks qw( mock_preference );
31 use t::lib::TestBuilder;
32
33 use C4::Context;
34 use C4::Breeding;
35 use Koha::Database;
36 use Koha::XSLT::Base;
37
38 my $schema = Koha::Database->new->schema;
39 my $builder = t::lib::TestBuilder->new;
40 $schema->storage->txn_begin;
41
42 #Group 1: testing _build_query and _translate_query (part of Z3950Search)
43 subtest '_build_query' => sub {
44     plan tests => 14;
45     test_build_translate_query();
46 };
47 #Group 2: testing _create_connection (part of Z3950Search)
48 subtest '_create_connection' => sub {
49     plan tests => 5;
50     test_create_connection();
51 };
52 #Group 3: testing _do_xslt_proc (part of Z3950Search)
53 subtest '_do_xslt_proc' => sub {
54     plan tests => 6;
55     test_do_xslt();
56 };
57 #Group 4: testing _add_rowdata (part of Z3950Search)
58 subtest '_add_rowdata' => sub {
59     plan tests => 5;
60     test_add_rowdata();
61 };
62
63 subtest BreedingSearch => sub {
64     plan tests => 5;
65
66     my $import_biblio_1 = $builder->build({ source => 'ImportBiblio', value => {
67             title => 'Unique title the first adventure',
68             author => 'Firstnamey Surnamey',
69             isbn  => '1407239961'
70         }
71     });
72     my $import_biblio_2 = $builder->build({ source => 'ImportBiblio', value => {
73             title => 'Unique title the adventure continues',
74             author => 'Firstnamey Surnamey',
75             isbn  => '9798200834976'
76         }
77     });
78
79     my ($count, @results) = C4::Breeding::BreedingSearch("Firstnamey Surnamey");
80     is( $count, 2, "Author search returns two results");
81
82     ($count, @results) = C4::Breeding::BreedingSearch("first adventure");
83     is( $count, 1, "Title search returns one result");
84
85     ($count, @results) = C4::Breeding::BreedingSearch("adventure continues");
86     is( $count, 1, "Title search returns one result");
87
88     ($count, @results) = C4::Breeding::BreedingSearch("9781407239965");
89     is( $count, 1, "ISBN search matches normalized DB value");
90
91     ($count, @results) = C4::Breeding::BreedingSearch("9798200834976");
92     is( $count, 1, "ISBN search for 13 digit ISBN matches 13 digit ISBN in database");
93     # FIXME - Import doesn't currently store these, but this proves the search works
94 };
95
96 $schema->storage->txn_rollback;
97
98 #-------------------------------------------------------------------------------
99
100 sub test_build_translate_query {
101     my $str;
102     #First pass no parameters
103     my @queries= C4::Breeding::_bib_build_query( {} );
104     is( defined $queries[0] && $queries[0] eq '' && defined $queries[1] &&
105         $queries[1] eq '', 1, '_bib_build_query gets no parameters');
106
107     #We now pass one parameter
108     my $pars1= { isbn => '234567' };
109     @queries= C4::Breeding::_bib_build_query( $pars1 );
110     #Passed only one par: zquery should start with @attr 1=\d+
111     is( $queries[0] =~ /^\@attr 1=\d+/, 1, 'Z39.50 query with one parameter');
112     $str=$pars1->{isbn};
113     #Find back ISBN?
114     is( $queries[0] =~ /$str/, 1, 'First Z39.50 query contains ISBN');
115     #SRU query should contain translation for ISBN
116     my $server= { sru_fields => 'isbn=ie-es-bee-en,srchany=overal' };
117     my $squery= C4::Breeding::_translate_query( $server, $queries[1] );
118     is( $squery =~ /ie-es-bee-en/, 1, 'SRU query has translated ISBN index');
119     #Another try with fallback to any
120     $server= { sru_fields => 'srchany=overal' };
121     $squery= C4::Breeding::_translate_query( $server, $queries[1] );
122     is( $squery =~ /overal/, 1, 'SRU query fallback to translated any');
123     #Another try even without any
124     $server= { sru_fields => 'this,is,bad,input' };
125     $squery= C4::Breeding::_translate_query( $server, $queries[1] );
126     is( $squery =~ /$str/ && $squery !~ /=/, 1, 'SRU query without indexes');
127
128     #We now pass two parameters
129     my $pars2= { isbn => '123456', title => 'You should read this.' };
130     @queries= C4::Breeding::_bib_build_query( $pars2 );
131     #The Z39.50 query should start with @and (we passed two pars)
132     is( $queries[0] =~ /^\@and/, 1, 'Second Z39.50 query starts with @and');
133     #We should also find two @attr 1=\d+
134     my @matches= $queries[0] =~ /\@attr 1=\d+/g;
135     is( @matches == 2, 1, 'Second Z39.50 query includes two @attr 1=');
136     #We should find text of both parameters in the query
137     $str= $pars2->{isbn};
138     is( $queries[0] =~ /\"$str\"/, 1,
139         'Second query contains ISBN enclosed by double quotes');
140     $str= $pars2->{title};
141     is( $queries[0] =~ /\"$str\"/, 1,
142         'Second query contains title enclosed by double quotes');
143
144     #SRU revisited
145     $server= { sru_fields => 'isbn=nb,title=dc.title,srchany=overal' };
146     $squery= C4::Breeding::_translate_query( $server, $queries[1] );
147     is ( $squery =~ /dc.title/ && $squery =~ / and / &&
148         $squery =~ /nb=/, 1, 'SRU query with two parameters');
149
150     #We now pass a third wrong parameter (should not make a difference)
151     my $pars3= { isbn => '123456', title => 'You should read this.', xyz => 1 };
152     my @queries2= C4::Breeding::_bib_build_query( $pars3 );
153     is( $queries[0] eq $queries2[0] && $queries[1] eq $queries2[1], 1,
154         'Third query makes no difference');
155
156     # Check that indexes with equal signs are ok
157     $server = { sru_fields => 'subjectsubdiv=aut.type=ram_pe and aut.accesspoint' };
158     my $pars4 = { subjectsubdiv => 'mysubjectsubdiv' };
159     @queries = C4::Breeding::_auth_build_query( $pars4 );
160     my $zquery = C4::Breeding::_translate_query( $server, $queries[1] );
161     is ( $zquery, 'aut.type=ram_pe and aut.accesspoint="mysubjectsubdiv"', 'SRU query with equal sign in index');
162
163     # Check that indexes with double-quotes are ok
164     $server = { sru_fields => 'subject=(aut.type any "geo ram_nc ram_ge ram_pe ram_co") and aut.accesspoint' };
165     my $pars5 = { subject => 'mysubject' };
166     @queries = C4::Breeding::_auth_build_query( $pars5 );
167     $zquery = C4::Breeding::_translate_query( $server, $queries[1] );
168     is ( $zquery, '(aut.type any "geo ram_nc ram_ge ram_pe ram_co") and aut.accesspoint="mysubject"', 'SRU query with double quotes in index');
169 }
170
171 sub test_create_connection {
172     #TODO This is just a *simple* start
173
174     my $str;
175     my $server= { servertype => 'zed', db => 'MyDatabase',
176         host => 'really-not-a-domain-i-hope.nl', port => 80,
177     };
178     my $obj= C4::Breeding::_create_connection( $server );
179
180     #We should get back an object, even if it did not connect
181     is( ref $obj eq 'ZOOM::Connection', 1, 'Got back a ZOOM connection');
182
183     #Remember: it is async
184     my $i= ZOOM::event( [ $obj ] );
185     if( $i == 1 ) {
186         #We could examine ZOOM::event_str( $obj->last_event )
187         #For now we are satisfied with an error message
188         #Probably: Connect failed
189         is( ($obj->errmsg//'') ne '', 1, 'Connection failed as expected');
190
191     } else {
192         ok( 1, 'No ZOOM event found: skipped errmsg' );
193     }
194
195     #Checking the databaseName for Z39.50 server
196     $str=$obj->option('databaseName')//'';
197     is( $str eq $server->{db}, 1, 'Check ZOOM option for database');
198
199     #Another test for SRU
200     $obj->destroy();
201     $server->{ servertype } = 'sru';
202     $server->{ sru_options } =  'just_testing=fun';
203     $obj= C4::Breeding::_create_connection( $server );
204     #In this case we expect no databaseName, but we expect just_testing
205     $str=$obj->option('databaseName');
206     is( $str, undef, 'No databaseName for SRU connection');
207     $str=$obj->option('just_testing')//'';
208     is( $str eq 'fun', 1, 'Additional ZOOM option for SRU found');
209     $obj->destroy();
210 }
211
212 sub test_do_xslt {
213     my $biblio = MARC::Record->new();
214     $biblio->append_fields(
215         MARC::Field->new('100', ' ', ' ', a => 'John Writer'),
216         MARC::Field->new('245', ' ', ' ', a => 'Just a title'),
217     );
218     my $file= xsl_file();
219     my $server= { add_xslt => $file };
220     my $engine=Koha::XSLT::Base->new;
221
222     #ready for the main test
223     my @res = C4::Breeding::_do_xslt_proc( $biblio, $server, $engine );
224     is( $res[1], undef, 'No error returned' );
225     is( ref $res[0], 'MARC::Record', 'Got back MARC record');
226     is( $res[0]->subfield('990','a'), 'I saw you', 'Found 990a in the record');
227
228     #forcing an error on the xslt side
229     $server->{add_xslt} = 'notafile.xsl';
230     @res = C4::Breeding::_do_xslt_proc( $biblio, $server, $engine );
231     is( $res[1], Koha::XSLT::Base::XSLTH_ERR_2, 'Error code found' );
232     #We still expect the original record back
233     is( ref $res[0], 'MARC::Record', 'Still got back MARC record' );
234     is ( $res[0]->subfield('245','a'), 'Just a title',
235         'At least the title is the same :)' );
236 }
237
238 sub test_add_rowdata {
239     t::lib::Mocks::mock_preference('AdditionalFieldsInZ3950ResultSearch','');
240
241     my $row = {
242        biblionumber => 0,
243        server => "testServer",
244        breedingid => 0
245    };
246
247     my $biblio = MARC::Record->new();
248     $biblio->append_fields(
249         MARC::Field->new('245', ' ', ' ', a => 'Just a title'), #title
250     );
251
252     my $returned_row = C4::Breeding::_add_rowdata($row, $biblio);
253
254     is($returned_row->{title}, "Just a title", "_add_rowdata returns the title of a biblio");
255     is($returned_row->{addnumberfields}[0], undef, "_add_rowdata returns undef if it has no additionnal field");
256
257     t::lib::Mocks::mock_preference('AdditionalFieldsInZ3950ResultSearch',"245\$a, 035\$a");
258
259     $row = {
260        biblionumber => 0,
261        server => "testServer",
262        breedingid => 0
263    };
264    $biblio = MARC::Record->new();
265    $biblio->append_fields(
266         MARC::Field->new('245', ' ', ' ', a => 'Just a title'), #title
267         MARC::Field->new('035', ' ', ' ', a => 'First 035'),
268         MARC::Field->new('035', ' ', ' ', a => 'Second 035')
269    );
270    $returned_row = C4::Breeding::_add_rowdata($row, $biblio);
271
272    is($returned_row->{title}, "Just a title", "_add_rowdata returns the title of a biblio");
273    is($returned_row->{addnumberfields}[0], "245\$a", "_add_rowdata returns the field number chosen in the AdditionalFieldsInZ3950ResultSearch preference");
274
275    # Test repeatble tags,the trailing whitespace is a normal side-effect of _add_custom_row_data
276    is_deeply(\$returned_row->{"035\$a"}, \["First 035 ", "Second 035 "],"_add_rowdata supports repeatable tags");
277 }
278
279 sub xsl_file {
280     return mytempfile( q{<xsl:stylesheet version="1.0"
281     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
282     xmlns:marc="http://www.loc.gov/MARC21/slim"
283 >
284   <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
285
286   <xsl:template match="record|marc:record">
287       <record>
288       <xsl:apply-templates/>
289       <datafield tag="990" ind1='' ind2=''>
290         <subfield code="a">
291           <xsl:text>I saw you</xsl:text>
292         </subfield>
293       </datafield>
294       </record>
295   </xsl:template>
296
297   <xsl:template match="node()">
298     <xsl:copy select=".">
299       <xsl:copy-of select="@*"/>
300       <xsl:apply-templates/>
301     </xsl:copy>
302   </xsl:template>
303 </xsl:stylesheet>} );
304 }
305
306 sub mytempfile {
307     my ( $fh, $fn ) = tempfile( SUFFIX => '.xsl', UNLINK => 1 );
308     print $fh $_[0]//'';
309     close $fh;
310     return $fn;
311 }