3 # This file is part of Koha.
5 # Copyright 2014 - Biblibre SARL
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.
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.
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>.
24 use Test::More tests => 15;
26 use File::Basename qw(dirname);
32 use_ok('t::lib::TestBuilder');
35 our $schema = Koha::Database->new->schema;
38 subtest 'Start with some trivial tests' => sub {
41 $schema->storage->txn_begin;
43 $builder = t::lib::TestBuilder->new;
44 isnt( $builder, undef, 'We got a builder' );
47 warning_like { $data = $builder->build; } qr/.+/, 'Catch a warning';
48 is( $data, undef, 'build without arguments returns undef' );
49 is( ref( $builder->schema ), 'Koha::Schema', 'check schema' );
50 is( ref( $builder->can('delete') ), 'CODE', 'found delete method' );
53 warning_like { $builder->build({
55 value => { surname => { invalid_hash => 1 } },
56 }) } qr/^Hash not allowed for surname/,
57 'Build should not accept a hash for this column';
59 # return undef if a record exists
60 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
61 my $param = { source => 'Branch', value => { branchcode => $branchcode } };
62 warning_like { $builder->build( $param ) }
63 qr/Violation of unique constraint/,
64 'Catch warn on adding existing record';
66 $schema->storage->txn_rollback;
70 subtest 'Build all sources' => sub {
73 $schema->storage->txn_begin;
75 my @sources = $builder->schema->sources;
76 my @source_in_failure;
77 for my $source ( @sources ) {
79 # Skip the source if it is a view
80 next if $schema->source($source)->isa('DBIx::Class::ResultSource::View');
81 eval { $res = $builder->build( { source => $source } ); };
82 push @source_in_failure, $source if $@ || !defined( $res );
84 is( @source_in_failure, 0,
85 'TestBuilder should be able to create an object for every source' );
86 if ( @source_in_failure ) {
87 diag( "The following sources have not been generated correctly: " .
88 join ', ', @source_in_failure );
91 $schema->storage->txn_rollback;
95 subtest 'Test length of some generated fields' => sub {
98 $schema->storage->txn_begin;
100 # Test the length of a returned character field
101 my $bookseller = $builder->build({ source => 'Aqbookseller' });
102 my $max = $schema->source('Aqbookseller')->column_info('phone')->{size};
103 is( length( $bookseller->{phone} ) > 0, 1,
104 'The length for a generated string (phone) should not be zero' );
105 is( length( $bookseller->{phone} ) <= $max, 1,
106 'Check maximum length for a generated string (phone)' );
108 my $item = $builder->build({ source => 'Item' });
109 is( $item->{replacementprice}, sprintf("%.2f", $item->{replacementprice}), "The number of decimals for floats should not be more than 2" );
111 $schema->storage->txn_rollback;
115 subtest 'Test FKs in overduerules_transport_type' => sub {
118 $schema->storage->txn_begin;
120 my $my_overduerules_transport_type = {
121 message_transport_type => {
122 message_transport_type => 'my msg_t_t',
125 branchcode => 'codeB',
126 categorycode => 'codeC',
130 my $overduerules_transport_type = $builder->build({
131 source => 'OverduerulesTransportType',
132 value => $my_overduerules_transport_type,
135 $overduerules_transport_type->{message_transport_type},
136 $my_overduerules_transport_type->{message_transport_type}->{message_transport_type},
137 'build stores the message_transport_type correctly'
140 $schema->resultset('Overduerule')->find( $overduerules_transport_type->{overduerules_id} )->branchcode,
141 $my_overduerules_transport_type->{overduerules_id}->{branchcode},
142 'build stores the branchcode correctly'
145 $schema->resultset('Overduerule')->find( $overduerules_transport_type->{overduerules_id} )->categorycode,
146 $my_overduerules_transport_type->{overduerules_id}->{categorycode},
147 'build stores the categorycode correctly'
150 $schema->resultset('MessageTransportType')->find( $overduerules_transport_type->{message_transport_type} )->message_transport_type,
151 $overduerules_transport_type->{message_transport_type},
152 'build stores the foreign key message_transport_type correctly'
155 $schema->resultset('Overduerule')->find( $my_overduerules_transport_type->{overduerules_id} )->letter2,
157 'build generates values if they are not given'
160 $schema->storage->txn_rollback;
164 subtest 'Tests with composite FK in userpermission' => sub {
167 $schema->storage->txn_begin;
169 my $my_user_permission = default_userpermission();
170 my $user_permission = $builder->build({
171 source => 'UserPermission',
172 value => $my_user_permission,
175 # Checks on top level of userpermission
177 $user_permission->{borrowernumber},
179 'build generates a borrowernumber correctly'
182 $user_permission->{code},
183 $my_user_permission->{code}->{code},
184 'build stores code correctly'
187 # Checks one level deeper userpermission -> borrower
188 my $patron = $schema->resultset('Borrower')->find({ borrowernumber => $user_permission->{borrowernumber} });
191 $my_user_permission->{borrowernumber}->{surname},
192 'build stores surname correctly'
197 'build generated cardnumber'
200 # Checks two levels deeper userpermission -> borrower -> branch
201 my $branch = $schema->resultset('Branch')->find({ branchcode => $patron->branchcode->branchcode });
204 $my_user_permission->{borrowernumber}->{branchcode}->{branchname},
205 'build stores branchname correctly'
208 $branch->branchaddress1,
210 'build generated branch address'
213 # Checks with composite FK: userpermission -> permission
214 my $perm = $schema->resultset('Permission')->find({ module_bit => $user_permission->{module_bit}, code => $my_user_permission->{code}->{code} });
215 isnt( $perm, undef, 'build generated record for composite FK' );
218 $my_user_permission->{code}->{code},
219 'build stored code correctly'
223 $my_user_permission->{code}->{description},
224 'build stored description correctly'
227 $schema->storage->txn_rollback;
230 sub default_userpermission {
233 surname => 'my surname',
234 address => 'my adress',
237 branchname => 'my branchname',
241 category_type => 'A',
242 default_privacy => 'default',
251 description => 'my desc',
257 subtest 'Test build with NULL values' => sub {
260 $schema->storage->txn_begin;
262 # PK should not be null
263 my $params = { source => 'Branch', value => { branchcode => undef }};
264 warning_like { $builder->build( $params ) }
265 qr/Null value for branchcode/,
266 'Catch warn on adding branch with a null branchcode';
268 my $info = $schema->source( 'Item' )->column_info( 'barcode' );
269 $params = { source => 'Item', value => { barcode => undef }};
270 my $item = $builder->build( $params );
271 is( $info->{is_nullable} && $item && !defined( $item->{barcode} ), 1,
272 'Barcode can be NULL' );
274 $params = { source => 'Reserve', value => { itemnumber => undef }};
275 my $reserve = $builder->build( $params );
276 $info = $schema->source( 'Reserve' )->column_info( 'itemnumber' );
277 is( $reserve && $info->{is_nullable} && $info->{is_foreign_key} &&
278 !defined( $reserve->{itemnumber} ), 1, 'Nullable FK' );
280 $schema->storage->txn_rollback;
284 subtest 'Tests for delete method' => sub {
287 $schema->storage->txn_begin;
289 # Test delete with single and multiple records
290 my $basket1 = $builder->build({ source => 'Aqbasket' });
291 my $basket2 = $builder->build({ source => 'Aqbasket' });
292 my $basket3 = $builder->build({ source => 'Aqbasket' });
293 my ( $id1, $id2 ) = ( $basket1->{basketno}, $basket2->{basketno} );
294 $builder->delete({ source => 'Aqbasket', records => $basket1 });
295 isnt( exists $basket1->{basketno}, 1, 'Delete cleared PK hash value' );
297 is( $builder->schema->resultset('Aqbasket')->search({ basketno => $id1 })->count, 0, 'Basket1 is no longer found' );
298 is( $builder->schema->resultset('Aqbasket')->search({ basketno => $id2 })->count, 1, 'Basket2 is still found' );
299 is( $builder->delete({ source => 'Aqbasket', records => [ $basket2, $basket3 ] }), 2, "Returned two delete attempts" );
300 is( $builder->schema->resultset('Aqbasket')->search({ basketno => $id2 })->count, 0, 'Basket2 is no longer found' );
303 # Test delete in table without primary key (..)
304 is( $schema->source('TmpHoldsqueue')->primary_columns, 0,
305 'Table without primary key detected' );
306 my $bibno = $builder->build_sample_biblio->biblionumber;
307 my $cnt1 = $schema->resultset('TmpHoldsqueue')->count;
308 # Insert a new record in TmpHoldsqueue with that biblionumber
309 my $val = { biblionumber => $bibno };
310 my $rec = $builder->build({ source => 'TmpHoldsqueue', value => $val });
311 my $cnt2 = $schema->resultset('TmpHoldsqueue')->count;
312 is( defined($rec) && $cnt2 == $cnt1 + 1 , 1, 'Created a record' );
313 is( $builder->delete({ source => 'TmpHoldsqueue', records => $rec }),
314 undef, 'delete returns undef' );
315 is( $rec->{biblionumber}, $bibno, 'Hash value untouched' );
316 is( $schema->resultset('TmpHoldsqueue')->count, $cnt2,
317 "Method did not delete record in table without PK" );
319 # Test delete with NULL values
320 $val = { branchcode => undef };
321 is( $builder->delete({ source => 'Branch', records => $val }), 0,
322 'delete returns zero for an undef search with one key' );
323 $val = { module_bit => 1, #catalogue
325 is( $builder->delete({ source => 'Permission', records => $val }), 0,
326 'delete returns zero for an undef search with a composite PK' );
328 $schema->storage->txn_rollback;
331 subtest 'Auto-increment values tests' => sub {
334 $schema->storage->txn_begin;
336 # Pick a table with AI PK
337 my $source = 'Biblio'; # table
338 my $column = 'biblionumber'; # ai column
340 my $col_info = $schema->source( $source )->column_info( $column );
341 is( $col_info->{is_auto_increment}, 1, "biblio.biblionumber is detected as autoincrement");
344 my $biblio_1 = $builder->build({ source => $source });
346 my $ai_value = $biblio_1->{ biblionumber };
348 my $biblio_2 = $builder->build({ source => $source });
349 # Get the next AI value
350 my $next_ai_value = $biblio_2->{ biblionumber };
351 is( $ai_value + 1, $next_ai_value, "AI values are consecutive");
353 # respect autoincr column
354 warning_like { $builder->build({
356 value => { biblionumber => 123 },
357 }) } qr/^Value not allowed for auto_incr/,
358 'Build should not overwrite an auto_incr column';
360 $schema->storage->txn_rollback;
363 subtest 'Date handling' => sub {
366 $schema->storage->txn_begin;
368 $builder = t::lib::TestBuilder->new;
370 my $patron = $builder->build( { source => 'Borrower' } );
371 is( length( $patron->{updated_on} ), 19, 'A timestamp column value should be YYYY-MM-DD HH:MM:SS' );
372 is( length( $patron->{dateofbirth} ), 10, 'A date column value should be YYYY-MM-DD' );
374 $schema->storage->txn_rollback;
377 subtest 'Default values' => sub {
380 $schema->storage->txn_begin;
382 $builder = t::lib::TestBuilder->new;
383 my $item = $builder->build( { source => 'Item' } );
384 is( $item->{more_subfields_xml}, undef, 'This xml field should be undef' );
385 $item = $builder->build( { source => 'Item', value => { more_subfields_xml => 'some xml' } } );
386 is( $item->{more_subfields_xml}, 'some xml', 'Default should not overwrite assigned value' );
388 subtest 'generated dynamically (coderef)' => sub {
390 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
391 like( $patron->category->category_type, qr{^(A|C|S|I|P|)$}, );
393 my $patron_category_X = $builder->build_object({ class => 'Koha::Patron::Categories', value => { category_type => 'X' } });
394 $patron = $builder->build_object({ class => 'Koha::Patrons', value => {categorycode => $patron_category_X->categorycode} });
395 is( $patron->category->category_type, 'X', );
398 $schema->storage->txn_rollback;
401 subtest 'build_object() tests' => sub {
405 $schema->storage->txn_begin;
407 $builder = t::lib::TestBuilder->new();
409 my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode};
410 my $categorycode = $builder->build( { source => 'Category' } )->{categorycode};
411 my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype};
413 my $issuing_rule = $builder->build_object(
414 { class => 'Koha::CirculationRules',
416 branchcode => $branchcode,
417 categorycode => $categorycode,
418 itemtype => $itemtype
423 is( ref($issuing_rule), 'Koha::CirculationRule', 'Type is correct' );
424 is( $issuing_rule->categorycode,
425 $categorycode, 'Category code correctly set' );
426 is( $issuing_rule->itemtype, $itemtype, 'Item type correctly set' );
428 subtest 'Test all classes' => sub {
429 my $Koha_modules_dir = dirname(__FILE__) . '/../../Koha';
430 my @koha_object_based_modules = `/bin/grep -rl -e '^sub object_class' $Koha_modules_dir`;
431 my @source_in_failure;
432 for my $module_filepath ( @koha_object_based_modules ) {
433 chomp $module_filepath;
434 next unless $module_filepath =~ m|\.pm$|;
435 my $module = $module_filepath;
436 $module =~ s|^.*/(Koha.*)\.pm$|$1|;
438 next if $module eq 'Koha::Objects';
439 eval "require $module";
440 my $object = $builder->build_object( { class => $module } );
441 is( ref($object), $module->object_class, "Testing $module" );
442 if ( ! grep {$module eq $_ } qw( Koha::Old::Patrons Koha::Statistics ) ) { # FIXME deletedborrowers and statistics do not have a PK
443 eval {$object->get_from_storage};
444 is( $@, '', "Module $module should have koha_object[s]_class method if needed" );
447 # Testing koha_object_class and koha_objects_class
448 my $object_class = Koha::Object::_get_object_class($object->_result->result_class);
449 eval "require $object_class";
450 is( $@, '', "Module $object_class should be defined");
451 my $objects_class = Koha::Objects::_get_objects_class($object->_result->result_class);
452 eval "require $objects_class";
453 is( $@, '', "Module $objects_class should be defined");
457 subtest 'test parameters' => sub {
460 warning_is { $issuing_rule = $builder->build_object( {} ); }
461 { carped => 'Missing class param' },
462 'The class parameter is mandatory, raises a warning if absent';
463 is( $issuing_rule, undef,
464 'If the class parameter is missing, undef is returned' );
467 $builder->build_object(
468 { class => 'Koha::Patrons', categorycode => 'foobar' } );
469 } qr{Unknown parameter\(s\): categorycode}, "Unknown parameter detected";
472 $schema->storage->txn_rollback;
475 subtest '->build parameter' => sub {
478 $schema->storage->txn_begin;
480 # Test to make sure build() warns user of unknown parameters.
485 branchcode => 'BRANCH_1'
488 } [], "No warnings on correct use";
493 branchcode => 'BRANCH_2' # This is wrong!
495 } qr/unknown param/i, "Carp unknown parameters";
499 zource => 'Branch', # Intentional spelling error
501 } qr/Source parameter not specified/, "Catch warning on missing source";
505 { source => 'Borrower', categorycode => 'foobar' } );
506 } qr{Unknown parameter\(s\): categorycode}, "Unkown parameter detected";
508 $schema->storage->txn_rollback;
511 subtest 'build_sample_biblio() tests' => sub {
515 $schema->storage->txn_begin;
518 { $builder->build_sample_biblio({ title => 'hell❤️' }); }
520 "No encoding warnings!";
522 $schema->storage->txn_rollback;
525 subtest 'Existence of object is only checked using primary keys' => sub {
529 $schema->storage->txn_begin;
531 my $biblio = $builder->build_sample_biblio();
532 my $item1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
533 my $item2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
535 $builder->build_object({
536 class => 'Koha::Holds',
538 biblionumber => $biblio->biblionumber
541 } [], "No warning about query returning more than one row";
543 $schema->storage->txn_rollback;