c1c7c1cd6191b48dee5351a224682720fd37f684
[dbsrgits/DBIx-Class-Historic.git] / t / multi_create / multilev_single_PKeqFK.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use lib qw(t/lib);
7 use DBICTest;
8
9 sub mc_diag { diag (@_) if $ENV{DBIC_MULTICREATE_DEBUG} };
10
11 plan tests => 16;
12
13 my $schema = DBICTest->init_schema();
14
15 mc_diag (<<'DG');
16 * Test a multilevel might-have/has_one with a PK == FK in the mid-table
17
18 CD -> might have -> Artwork
19     \- has_one -/     \
20                        \
21                         \-> has_many \
22                                       --> Artwork_to_Artist
23                         /-> has_many /
24                        /
25                      Artist
26 DG
27
28 my $rels = {
29   has_one => 'mandatory_artwork',
30   might_have => 'artwork',
31 };
32
33 my $artist_rs = $schema->resultset('Artist');
34
35 for my $type (qw/has_one might_have/) {
36
37   my $rel = $rels->{$type};
38
39   my $cd_title = "Test $type cd";
40   my $artist_names = [ map { "Artist via $type $_" } (1, 2) ];
41
42   my $someartist = $artist_rs->next;
43
44   lives_ok (sub {
45     my $cd = $schema->resultset('CD')->create ({
46       artist => $someartist,
47       title => $cd_title,
48       year => 2008,
49       $rel => {
50       artwork_to_artist => [ map {
51             { artist => { name => $_ } }
52           } (@$artist_names)
53         ]
54       },
55     });
56
57
58     isa_ok ($cd, 'DBICTest::CD', 'Main CD object created');
59     is ($cd->title, $cd_title, 'Correct CD title');
60
61     my $art_obj = $cd->$rel;
62     ok ($art_obj->has_column_loaded ('cd_id'), 'PK/FK present on artwork object');
63     is ($art_obj->artists->count, 2, 'Correct artwork creator count via the new object');
64     is_deeply (
65       [ sort $art_obj->artists->get_column ('name')->all ],
66       $artist_names,
67       'Artists named correctly when queried via object',
68     );
69
70     my $artwork = $schema->resultset('Artwork')->search (
71       { 'cd.title' => $cd_title },
72       { join => 'cd' },
73     )->single;
74     is ($artwork->artists->count, 2, 'Correct artwork creator count via a new search');
75     is_deeply (
76         [ sort $artwork->artists->get_column ('name')->all ],
77       $artist_names,
78       'Artists named correctly queried via a new search',
79     );
80   }, "multilevel $type with a PK == FK in the $type/has_many table ok");
81 }
82
83 1;