Fix tests failing due to unspecified resultset retrieval order
[dbsrgits/DBIx-Class.git] / t / relationship / core.t
index 9087333..23d829d 100644 (file)
@@ -5,47 +5,30 @@ use Test::More;
 use Test::Exception;
 use lib qw(t/lib);
 use DBICTest;
+use DBIC::SqlMakerTest;
 
 my $schema = DBICTest->init_schema();
 my $sdebug = $schema->storage->debug;
 
-plan tests => 78;
-
 # has_a test
 my $cd = $schema->resultset("CD")->find(4);
-my ($artist) = ($INC{'DBICTest/HelperRels'}
-                  ? $cd->artist
-                  : $cd->search_related('artist'));
+my ($artist) = $cd->search_related('artist');
 is($artist->name, 'Random Boy Band', 'has_a search_related ok');
 
 # has_many test with an order_by clause defined
 $artist = $schema->resultset("Artist")->find(1);
-my @cds = ($INC{'DBICTest/HelperRels'}
-             ? $artist->cds
-             : $artist->search_related('cds'));
+my @cds = $artist->search_related('cds');
 is( $cds[1]->title, 'Spoonful of bees', 'has_many search_related with order_by ok' );
 
 # search_related with additional abstract query
-@cds = ($INC{'DBICTest/HelperRels'}
-          ? $artist->cds({ title => { like => '%of%' } })
-          : $artist->search_related('cds', { title => { like => '%of%' } } )
-       );
+@cds = $artist->search_related('cds', { title => { like => '%of%' } } );
 is( $cds[1]->title, 'Forkful of bees', 'search_related with abstract query ok' );
 
 # creating a related object
-if ($INC{'DBICTest/HelperRels.pm'}) {
-  $artist->add_to_cds({ title => 'Big Flop', year => 2005 });
-} else {
-  my $big_flop = $artist->create_related( 'cds', {
-      title => 'Big Flop',
-      year => 2005,
-  } );
-
- TODO: {
-    local $TODO = "Can't fix right now" if $DBIx::Class::VERSION < 0.09;
-    lives_ok { $big_flop->genre} "Don't throw exception when col is not loaded after insert";
-  };
-}
+$artist->create_related( 'cds', {
+  title => 'Big Flop',
+  year => 2005,
+} );
 
 my $big_flop_cd = ($artist->search_related('cds'))[3];
 is( $big_flop_cd->title, 'Big Flop', 'create_related ok' );
@@ -80,19 +63,20 @@ my $track = $schema->resultset("Track")->create( {
 } );
 $track->set_from_related( cd => $cd );
 
+# has_relationship
+ok(! $track->has_relationship( 'foo' ), 'Track has no relationship "foo"');
+ok($track->has_relationship( 'disc' ), 'Track has relationship "disk"' );
+
 is($track->disc->cdid, 4, 'set_from_related ok, including alternative accessor' );
 
 $track->set_from_related( cd => undef );
 
 ok( !defined($track->cd), 'set_from_related with undef ok');
 
-TODO: {
-    local $TODO = 'accessing $object->rel and set_from_related';
-    my $track = $schema->resultset("Track")->new( {} );
-    $track->cd;
-    $track->set_from_related( cd => $cd ); 
-    ok ($track->cd, 'set_from_related ok after using the accessor' );
-};
+$track = $schema->resultset("Track")->new( {} );
+$track->cd;
+$track->set_from_related( cd => $cd );
+ok ($track->cd, 'set_from_related ok after using the accessor' );
 
 # update_from_related, the same as set_from_related, but it calls update afterwards
 $track = $schema->resultset("Track")->create( {
@@ -102,7 +86,7 @@ $track = $schema->resultset("Track")->create( {
 } );
 $track->update_from_related( cd => $cd );
 
-my $t_cd = ($schema->resultset("Track")->search( cd => 4, title => 'Hidden Track 2' ))[0]->cd;
+my $t_cd = ($schema->resultset("Track")->search({ cd => 4, title => 'Hidden Track 2' }))[0]->cd;
 
 is( $t_cd->cdid, 4, 'update_from_related ok' );
 
@@ -121,7 +105,7 @@ is( $cd->title, 'Greatest Hits', 'find_or_create_related new record ok' );
 is( ($artist->search_related('cds'))[4]->title, 'Greatest Hits', 'find_or_create_related new record search ok' );
 
 $artist->delete_related( cds => { title => 'Greatest Hits' });
-cmp_ok( $schema->resultset("CD")->search( title => 'Greatest Hits' ), '==', 0, 'delete_related ok' );
+cmp_ok( $schema->resultset("CD")->search({ title => 'Greatest Hits' }), '==', 0, 'delete_related ok' );
 
 # find_or_new_related with an existing record
 $cd = $artist->find_or_new_related( 'cds', { title => 'Big Flop' } );
@@ -134,7 +118,7 @@ $cd = $artist->find_or_new_related( 'cds', {
   year => 2007,
 } );
 is( $cd->title, 'Greatest Hits 2: Louder Than Ever', 'find_or_new_related new record ok' );
-ok( ! $cd->in_storage, 'find_or_new_related on a new record: not in_storage' );
+is( $cd->in_storage, 0, 'find_or_new_related on a new record: not in_storage' );
 
 $cd->artist(undef);
 my $newartist = $cd->find_or_new_related( 'artist', {
@@ -144,8 +128,8 @@ my $newartist = $cd->find_or_new_related( 'artist', {
 is($newartist->name, 'Random Boy Band Two', 'find_or_new_related new artist record with id');
 is($newartist->id, 200, 'find_or_new_related new artist id set');
 
-lives_ok( 
-    sub { 
+lives_ok(
+    sub {
         my $new_bookmark = $schema->resultset("Bookmark")->new_result( {} );
         my $new_related_link = $new_bookmark->new_related( 'link', {} );
     },
@@ -153,31 +137,29 @@ lives_ok(
 );
 
 
-TODO: {
+{
   local $TODO = "relationship checking needs fixing";
   # try to add a bogus relationship using the wrong cols
-  eval {
+  throws_ok {
       DBICTest::Schema::Artist->add_relationship(
           tracks => 'DBICTest::Schema::Track',
           { 'foreign.cd' => 'self.cdid' }
       );
-  };
-  like($@, qr/Unknown column/, 'failed when creating a rel with invalid key, ok');
+  } qr/Unknown column/, 'failed when creating a rel with invalid key, ok';
 }
-  
+
 # another bogus relationship using no join condition
-eval {
+throws_ok {
     DBICTest::Schema::Artist->add_relationship( tracks => 'DBICTest::Track' );
-};
-like($@, qr/join condition/, 'failed when creating a rel without join condition, ok');
+} qr/join condition/, 'failed when creating a rel without join condition, ok';
 
 # many_to_many helper tests
 $cd = $schema->resultset("CD")->find(1);
-my @producers = $cd->producers();
+my @producers = $cd->producers(undef, { order_by => 'producerid'} );
 is( $producers[0]->name, 'Matt S Trout', 'many_to_many ok' );
 is( $cd->producers_sorted->next->name, 'Bob The Builder',
     'sorted many_to_many ok' );
-is( $cd->producers_sorted(producerid => 3)->next->name, 'Fred The Phenotype',
+is( $cd->producers_sorted({producerid => 3})->next->name, 'Fred The Phenotype',
     'sorted many_to_many with search condition ok' );
 
 $cd = $schema->resultset('CD')->find(2);
@@ -210,22 +192,23 @@ is( $prod_rs->first->name, 'Testy McProducer',
 $cd->add_to_producers({ name => 'Jack Black' });
 is( $prod_rs->count(), 2, 'many_to_many add_to_$rel($hash) count ok' );
 $cd->set_producers($schema->resultset('Producer')->all);
-is( $cd->producers->count(), $prod_before_count+2, 
+is( $cd->producers->count(), $prod_before_count+2,
     'many_to_many set_$rel(@objs) count ok' );
 $cd->set_producers($schema->resultset('Producer')->find(1));
 is( $cd->producers->count(), 1, 'many_to_many set_$rel($obj) count ok' );
 $cd->set_producers([$schema->resultset('Producer')->all]);
-is( $cd->producers->count(), $prod_before_count+2, 
+is( $cd->producers->count(), $prod_before_count+2,
     'many_to_many set_$rel(\@objs) count ok' );
 $cd->set_producers([$schema->resultset('Producer')->find(1)]);
 is( $cd->producers->count(), 1, 'many_to_many set_$rel([$obj]) count ok' );
 
-eval { $cd->remove_from_producers({ fake => 'hash' }); };
-like( $@, qr/needs an object/, 'remove_from_$rel($hash) dies correctly' );
+throws_ok {
+  $cd->remove_from_producers({ fake => 'hash' })
+} qr/needs an object/, 'remove_from_$rel($hash) dies correctly';
 
-eval { $cd->add_to_producers(); };
-like( $@, qr/needs an object or hashref/,
-      'add_to_$rel(undef) dies correctly' );
+throws_ok {
+  $cd->add_to_producers()
+} qr/needs an object or hashref/, 'add_to_$rel(undef) dies correctly';
 
 # many_to_many stresstest
 my $twokey = $schema->resultset('TwoKeys')->find(1,1);
@@ -247,10 +230,9 @@ is( $twokey->fourkeys_to_twokeys->count, 0,
 my $undef_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007 });
 is($undef_artist_cd->has_column_loaded('artist'), '', 'FK not loaded');
 is($undef_artist_cd->search_related('artist')->count, 0, '0=1 search when FK does not exist and object not yet in db');
-eval{ 
+lives_ok {
      $undef_artist_cd->related_resultset('artist')->new({name => 'foo'});
-};
-is( $@, '', "Object created on a resultset related to not yet inserted object");
+} 'Object created on a resultset related to not yet inserted object';
 lives_ok{
   $schema->resultset('Artwork')->new_result({})->cd;
 } 'undef_on_null_fk does not choke on empty conds';
@@ -260,8 +242,23 @@ is($def_artist_cd->has_column_loaded('artist'), 1, 'FK loaded');
 is($def_artist_cd->search_related('artist')->count, 0, 'closed search on null FK');
 
 # test undirected many-to-many relationship (e.g. "related artists")
-my $undir_maps = $schema->resultset("Artist")->find(1)->artist_undirected_maps;
+my $undir_maps = $schema->resultset("Artist")
+                          ->search ({artistid => 1})
+                            ->search_related ('artist_undirected_maps');
 is($undir_maps->count, 1, 'found 1 undirected map for artist 1');
+is_same_sql_bind (
+  $undir_maps->as_query,
+  '(
+    SELECT artist_undirected_maps.id1, artist_undirected_maps.id2
+      FROM artist me
+      JOIN artist_undirected_map artist_undirected_maps
+        ON artist_undirected_maps.id1 = me.artistid OR artist_undirected_maps.id2 = me.artistid
+    WHERE ( artistid = ? )
+  )',
+  [[ { sqlt_datatype => 'integer', dbic_colname => 'artistid' }
+      => 1 ]],
+  'expected join sql produced',
+);
 
 $undir_maps = $schema->resultset("Artist")->find(2)->artist_undirected_maps;
 is($undir_maps->count, 1, 'found 1 undirected map for artist 2');
@@ -276,10 +273,11 @@ my $searched = $mapped_rs->search({'mapped_artists.artistid' => {'!=', undef}});
 
 cmp_ok($searched->count, '==', 2, "Both artist returned from map after adding another condition");
 
-# check join through cascaded has_many relationships
+# check join through cascaded has_many relationships (also empty has_many rels)
 $artist = $schema->resultset("Artist")->find(1);
 my $trackset = $artist->cds->search_related('tracks');
-cmp_ok($trackset->count, '==', 10, "Correct number of tracks for artist");
+is($trackset->count, 10, "Correct number of tracks for artist");
+is($trackset->all, 10, "Correct number of track objects for artist");
 
 # now see about updating eveything that belongs to artist 2 to artist 3
 $artist = $schema->resultset("Artist")->find(2);
@@ -299,7 +297,7 @@ my $rs_overridden = $schema->source('ForceForeign');
 my $relinfo_with_attr = $rs_overridden->relationship_info ('cd_3');
 cmp_ok($relinfo_with_attr->{attrs}{is_foreign_key_constraint}, '==', 0, "is_foreign_key_constraint defined for belongs_to relationships with attr.");
 
-# check that relationships below left join relationships are forced to left joins 
+# check that relationships below left join relationships are forced to left joins
 # when traversing multiple belongs_to
 my $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => 'cd' } });
 is($cds->count, 1, "subjoins under left joins force_left (string)");
@@ -309,3 +307,5 @@ is($cds->count, 1, "subjoins under left joins force_left (arrayref)");
 
 $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => { cd => {} } } });
 is($cds->count, 1, "subjoins under left joins force_left (hashref)");
+
+done_testing;