From a7d6e356a35924a21b2eaafee978eeb8f6626c9e Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Wed, 3 Jun 2015 15:54:57 -0300 Subject: [PATCH] Bug 14256: (followup) check for unique constrainta to regenerate random data Unique constraints should be checked when creating random data. Otherwise we get failures when the generated data already exists on the DB. This patch takes advantage of ->unique_constraints() to do the job, looping through all the unique constraints defined for the source. --- t/lib/TestBuilder.pm | 64 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/t/lib/TestBuilder.pm b/t/lib/TestBuilder.pm index 826ab1a..ef0f9c4 100644 --- a/t/lib/TestBuilder.pm +++ b/t/lib/TestBuilder.pm @@ -155,13 +155,63 @@ sub _buildColumnValues { my $col_values; my @columns = $self->schema->source($source)->columns; - for my $col_name( @columns ) { - my $col_value = $self->_buildColumnValue({ - source => $source, - column_name => $col_name, - value => $value, - }); - $col_values->{$col_name} = $col_value if( defined( $col_value ) ); + my @primary_columns = $self->schema->source($source)->primary_columns(); + my %unique_constraints = $self->schema->source($source)->unique_constraints(); + + my $values_ok = 0; + my $at_least_one_constraint_failed; + + while ( not $values_ok ) { + + $at_least_one_constraint_failed = 0; + # generate random values + for my $col_name( @columns ) { + my $col_value = $self->_buildColumnValue({ + source => $source, + column_name => $col_name, + value => $value, + }); + $col_values->{$col_name} = $col_value if( defined( $col_value ) ); + } + + # If default values are set, maybe the data exist in the DB + # But no need to wait for another value + last if exists( $default_value->{$source} ); + + if ( scalar keys %unique_constraints > 0 ) { + + # verify the data would respect each unique constraint + foreach my $constraint (keys %unique_constraints) { + + my $condition; + my @constraint_columns = $unique_constraints{$constraint}; + # loop through all constraint columns and build the condition + foreach my $constraint_column ( @constraint_columns ) { + # build the filter + $condition->{ $constraint_column } = + $col_values->{ $constraint_column }; + } + + my $count = $self->schema + ->resultset( $source ) + ->search( $condition ) + ->count(); + if ( $count > 0 ) { + $at_least_one_constraint_failed = 1; + # no point checking more stuff, exit the loop + last; + } + } + + if ( $at_least_one_constraint_failed ) { + $values_ok = 0; + } else { + $values_ok = 1; + } + + } else { + $values_ok = 1; + } } return $col_values; } -- 2.4.2