Bug 32030: fix test builder for boolean
[srvgit] / t / lib / TestBuilder.pm
index 260da2b..e066c2f 100644 (file)
@@ -2,15 +2,15 @@ package t::lib::TestBuilder;
 
 use Modern::Perl;
 
-use Koha::Database;
-use C4::Biblio;
-use C4::Items;
-use Koha::Biblios;
-use Koha::Items;
+use Koha::Database qw( schema );
+use C4::Biblio qw( AddBiblio );
+use Koha::Biblios qw( _type );
+use Koha::Items qw( _type );
+use Koha::DateUtils qw( dt_from_string );
 
 use Bytes::Random::Secure;
-use Carp;
-use Module::Load;
+use Carp qw( carp );
+use Module::Load qw( load );
 use String::Random;
 
 use constant {
@@ -75,19 +75,28 @@ sub build_object {
         return;
     }
 
+    my @unknowns = grep( !/^(class|value)$/, keys %{ $params });
+    carp "Unknown parameter(s): ", join( ', ', @unknowns ) if scalar @unknowns;
+
     load $class;
     my $source = $class->_type;
-    my @pks = $self->schema->source( $class->_type )->primary_columns;
 
     my $hashref = $self->build({ source => $source, value => $value });
-    my @ids;
+    my $object;
+    if ( $class eq 'Koha::Old::Patrons' ) {
+        $object = $class->search({ borrowernumber => $hashref->{borrowernumber} })->next;
+    } elsif ( $class eq 'Koha::Statistics' ) {
+        $object = $class->search({ datetime => $hashref->{datetime} })->next;
+    } else {
+        my @ids;
+        my @pks = $self->schema->source( $class->_type )->primary_columns;
+        foreach my $pk ( @pks ) {
+            push @ids, $hashref->{ $pk };
+        }
 
-    foreach my $pk ( @pks ) {
-        push @ids, $hashref->{ $pk };
+        $object = $class->find( @ids );
     }
 
-    my $object = $class->find( @ids );
-
     return $object;
 }
 
@@ -114,9 +123,16 @@ sub build {
     # loop thru all fk and create linked records if needed
     # fills remaining entries in $col_values
     my $foreign_keys = $self->_getForeignKeys( { source => $source } );
+    my $col_names = {};
     for my $fk ( @$foreign_keys ) {
         # skip when FK points to itself: e.g. borrowers:guarantorid
         next if $fk->{source} eq $source;
+
+        # If we have more than one FK on the same column, we only generate values for the first one
+        next
+          if scalar @{ $fk->{keys} } == 1
+          && exists $col_names->{ $fk->{keys}->[0]->{col_name} };
+
         my $keys = $fk->{keys};
         my $tbl = $fk->{source};
         my $res = $self->_create_links( $tbl, $keys, $col_values, $value );
@@ -124,6 +140,9 @@ sub build {
         foreach( keys %$res ) { # save new values
             $col_values->{$_} = $res->{$_};
         }
+
+        $col_names->{ $fk->{keys}->[0]->{col_name} } = 1
+          if scalar @{ $fk->{keys} } == 1
     }
 
     # store this record and return hashref
@@ -145,6 +164,8 @@ sub build_sample_biblio {
     my $marcflavour = C4::Context->preference('marcflavour');
 
     my $record = MARC::Record->new();
+    $record->encoding( 'UTF-8' );
+
     my ( $tag, $subfield ) = $marcflavour eq 'UNIMARC' ? ( 200, 'a' ) : ( 245, 'a' );
     $record->append_fields(
         MARC::Field->new( $tag, ' ', ' ', $subfield => $title ),
@@ -172,23 +193,20 @@ sub build_sample_item {
     my $library = delete $args->{library}
       || $self->build_object( { class => 'Koha::Libraries' } )->branchcode;
 
-    my $itype = delete $args->{itype}
-      || $self->build_object( { class => 'Koha::ItemTypes' } )->itemtype;
+    # If itype is not passed it will be picked from the biblio (see Koha::Item->store)
 
     my $barcode = delete $args->{barcode}
       || $self->_gen_text( { info => { size => SIZE_BARCODE } } );
 
-    my ( undef, undef, $itemnumber ) = C4::Items::AddItem(
+    return Koha::Item->new(
         {
+            biblionumber  => $biblionumber,
             homebranch    => $library,
             holdingbranch => $library,
             barcode       => $barcode,
-            itype         => $itype,
             %$args,
-        },
-        $biblionumber
-    );
-    return Koha::Items->find($itemnumber);
+        }
+    )->store->get_from_storage;
 }
 
 # ------------------------------------------------------------------------------
@@ -222,8 +240,15 @@ sub _create_links {
     if( $cnt_scalar == @$keys ) {
         # if one or more fk cols are null, the FK constraint will not be forced
         return {} if $cnt_null > 0;
+
         # does the record exist already?
-        return {} if $self->schema->resultset($linked_tbl)->find( $fk_value );
+        my @pks = $self->schema->source( $linked_tbl )->primary_columns;
+        my %fk_pk_value;
+        for (@pks) {
+            $fk_pk_value{$_} = $fk_value->{$_} if defined $fk_value->{$_};
+        }
+        return {} if !(keys %fk_pk_value);
+        return {} if $self->schema->resultset($linked_tbl)->find( \%fk_pk_value );
     }
     # create record with a recursive build call
     my $row = $self->build({ source => $linked_tbl, value => $fk_value });
@@ -397,7 +422,9 @@ sub _buildColumnValue {
         }
         push @$retvalue, $value->{$col_name};
     } elsif( exists $self->{default_values}{$source}{$col_name} ) {
-        push @$retvalue, $self->{default_values}{$source}{$col_name};
+        my $v = $self->{default_values}{$source}{$col_name};
+        $v = &$v() if ref($v) eq 'CODE';
+        push @$retvalue, $v;
     } else {
         my $data_type = $col_info->{data_type};
         $data_type =~ s| |_|;
@@ -416,14 +443,15 @@ sub _should_be_fk {
 # A column is not marked as FK, but a belongs_to relation is defined
     my ( $source, $column ) = @_;
     my $inconsistencies = {
-        'Item.biblionumber' => 1, #FIXME: Please remove me when I become FK
+        'Item.biblionumber'           => 1, #FIXME: Please remove me when I become FK
+        'CheckoutRenewal.checkout_id' => 1, #FIXME: Please remove when issues and old_issues are merged
     };
     return $inconsistencies->{ "$source.$column" };
 }
 
 sub _gen_type {
     return {
-        tinyint   => \&_gen_int,
+        tinyint   => \&_gen_bool,
         smallint  => \&_gen_int,
         mediumint => \&_gen_int,
         integer   => \&_gen_int,
@@ -454,6 +482,11 @@ sub _gen_type {
     };
 };
 
+sub _gen_bool {
+    my ($self, $params) = @_;
+    return int( rand(2) );
+}
+
 sub _gen_int {
     my ($self, $params) = @_;
     my $data_type = $params->{info}->{data_type};
@@ -483,17 +516,18 @@ sub _gen_real {
     if( defined( $params->{info}->{size} ) ) {
         $max = 10 ** ($params->{info}->{size}->[0] - $params->{info}->{size}->[1]);
     }
+    $max = 10 ** 5 if $max > 10 ** 5;
     return sprintf("%.2f", rand($max-0.1));
 }
 
 sub _gen_date {
     my ($self, $params) = @_;
-    return $self->schema->storage->datetime_parser->format_date(DateTime->now())
+    return $self->schema->storage->datetime_parser->format_date(dt_from_string)
 }
 
 sub _gen_datetime {
     my ($self, $params) = @_;
-    return $self->schema->storage->datetime_parser->format_datetime(DateTime->now());
+    return $self->schema->storage->datetime_parser->format_datetime(dt_from_string);
 }
 
 sub _gen_text {
@@ -529,23 +563,40 @@ sub _gen_blob {
 sub _gen_default_values {
     my ($self) = @_;
     return {
+        BackgroundJob => {
+            context => '{}'
+        },
         Borrower => {
             login_attempts => 0,
             gonenoaddress  => undef,
             lost           => undef,
             debarred       => undef,
             borrowernotes  => '',
+            secret         => undef,
+            password_expiration_date => undef,
         },
         Item => {
             notforloan         => 0,
             itemlost           => 0,
             withdrawn          => 0,
             restricted         => 0,
+            damaged            => 0,
+            materials          => undef,
             more_subfields_xml => undef,
         },
         Category => {
             enrolmentfee => 0,
             reservefee   => 0,
+            # Not X, used for statistics
+            category_type => sub { return [ qw( A C S I P ) ]->[int(rand(5))] },
+            min_password_length => undef,
+            require_strong_password => undef,
+        },
+        Branch => {
+            pickup_location => 0,
+        },
+        Reserve => {
+            non_priority => 0,
         },
         Itemtype => {
             rentalcharge => 0,
@@ -553,14 +604,39 @@ sub _gen_default_values {
             rentalcharge_hourly => 0,
             defaultreplacecost => 0,
             processfee => 0,
+            notforloan => 0,
         },
         Aqbookseller => {
             tax_rate => 0,
             discount => 0,
+            url  => undef,
+        },
+        Aqbudget => {
+            sort1_authcat => undef,
+            sort2_authcat => undef,
         },
         AuthHeader => {
             marcxml => '',
         },
+        BorrowerAttributeType => {
+            mandatory => 0,
+        },
+        Suggestion => {
+            suggesteddate => dt_from_string()->ymd,
+            STATUS        => 'ASKED'
+        },
+        ReturnClaim => {
+            issue_id => undef, # It should be a FK but we removed it
+                               # We don't want to generate a random value
+        },
+        ImportItem => {
+            status => 'staged',
+            import_error => undef
+        },
+        SearchFilter => {
+            opac => 1,
+            staff_client => 1
+        },
     };
 }