EasyFixture/Tutorial.pm untested

filter: Statementstmt 0.0% 0 / 2 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 0.0% 0 / 2 SCAR -
1 package DBIx::Class::EasyFixture::Tutorial;
2 $DBIx::Class::EasyFixture::Tutorial::VERSION = '0.12';
3 # ABSTRACT: what it says on the tin
4  
5 # this is not a .pod file because various repos replace the primary
6 # documentation with a .pod file.
7  
8 1;
9  
10 __END__
11  
12 =pod
13  
14 =encoding UTF-8
15  
16 =head1 NAME
17  
18 DBIx::Class::EasyFixture::Tutorial - what it says on the tin
19  
20 =head1 VERSION
21  
22 version 0.12
23  
24 =head1 RATIONALE
25  
26 Managing test data is hard enough without having a clean way of maintaining
27 fixtures. L<DBIx::Class::EasyFixture> makes it easy to define fixtures.
28 Different scenarios can be loaded on demand to test different facets of your
29 system. Fixtures can take a while to write, but once defined, there's less
30 cutting and pasting of code.
31  
32 =head1 CREATING YOUR FIXTURE CLASS
33  
34 To use C<DBIx::Class::EasyFixture>, you must first create a subclass of it.
35 It's required to define two methods: C<get_fixture> and C<all_fixture_names>.
36 You may implement those any way you wish and you're not locked into a
37 particular format. Here's one way to do it, using a big hash (there are plenty
38 of other ways to do this, but this is easy for a tutorial.
39  
40 package My::Fixtures;
41 use Moose;
42 extends 'DBIx::Class::EasyFixture';
43  
44 my %definition_for = (
45 # keys are fixture names, values are the fixture definitions
46 );
47  
48 sub get_definition {
49 my ( $self, $name ) = @_;
50 return $definition_for{$name};
51 }
52  
53 sub all_fixture_names { return keys %definition_for }
54  
55 __PACKAGE__->meta->make_immutable;
56  
57 1;
58  
59 =head2 A stand-alone fixture
60  
61 Writing fixtures is easy, so let's start with something simple.
62  
63 Imagine you have the following table:
64  
65 CREATE TABLE people (
66 person_id INTEGER PRIMARY KEY AUTOINCREMENT,
67 name VARCHAR(255) NOT NULL,
68 email VARCHAR(255) NULL UNIQUE,
69 birthday DATETIME NOT NULL
70 );
71  
72 Its C<DBIx::Class> definition might look like this:
73  
74 package Sample::Schema::Result::Person;
75 use strict;
76 use warnings;
77 use base 'DBIx::Class::Core';
78 __PACKAGE__->load_components("InflateColumn::DateTime");
79  
80 __PACKAGE__->table("people");
81  
82 __PACKAGE__->add_columns(
83 "person_id",
84 { data_type => "integer", is_auto_increment => 1, is_nullable => 0 },
85 "name",
86 { data_type => "varchar", is_nullable => 0, size => 255 },
87 "email",
88 { data_type => "varchar", is_nullable => 1, size => 255 },
89 "birthday",
90 { data_type => "datetime", is_nullable => 0 },
91 );
92  
93 __PACKAGE__->set_primary_key("person_id");
94 __PACKAGE__->add_unique_constraint( "email_unique", ["email"] );
95  
96 1;
97  
98 (After this, we won't show much of the C<DBIx::Class> code).
99  
100 To define a fixture with a birthday, the email C<not@home.com> and the name
101 C<bob>, you might have this:
102  
103 basic_person => {
104 new => 'Person',
105 using => {
106 name => 'Bob',
107 email => 'not@home.com',
108 birthday => $datetime_object,
109 },
110 }
111  
112 The format of simple fixture is:
113  
114 $fixture_name => {
115 new => $dbix_class_resultsource_name,
116 using => $arguments_to_constructor,
117 }
118  
119 Putting the above together, we get this:
120  
121 package My::Fixtures;
122 use Moose;
123 use DateTime;
124 extends 'DBIx::Class::EasyFixture';
125 use namespace::autoclean;
126  
127 my %definition_for = (
128 basic_person => {
129 new => 'Person',
130 using => {
131 name => 'Bob',
132 email => 'not@home.com',
133 birthday => DateTime->new(
134 year => 1983,
135 month => 12,
136 day => 25,
137 ),
138 },
139 },
140 );
141  
142 sub get_definition {
143 my ( $self, $name ) = @_;
144 return $definition_for{$name};
145 }
146  
147 sub all_fixture_names { return keys %definition_for }
148  
149 __PACKAGE__->meta->make_immutable;
150  
151 1;
152  
153 To use that in your test code:
154  
155 use Test::More;
156 use My::Schema;
157 my $schema = My::Schema->new;
158  
159 use My::Fixtures;
160 my $fixtures = My::Fixtures->new( { schema => $schema } );
161 $fixtures->load('basic_person');
162  
163 my $person = $schema->resultset('Person')->find( { email => 'not@home.com' } );
164 is $person->name 'bob', 'Everything is OK. We found bob';
165  
166 $fixtures->unload; # fixtures removed (transaction is rolled back)
167  
168 done_testing;
169  
170 As a convenience, you can also get "bob" by doing this:
171  
172 $fixtures->load('basic_person');
173 my $person = $fixtures->get_result('basic_person');
174  
175 Or by doing this:
176  
177 my $person = $fixtures->load('basic_person');
178  
179 =head2 One-to-one relationships
180  
181 OK, that was easy, but what about this?
182  
183 CREATE TABLE customers (
184 customer_id INTEGER PRIMARY KEY AUTOINCREMENT,
185 person_id INTEGER NOT NULL UNIQUE,
186 first_purchase DATETIME NOT NULL,
187 FOREIGN KEY(person_id) REFERENCES people(person_id)
188 );
189  
190 The C<customers> table has a unique constraint against C<person_id>. That
191 means each person might be a customer in a one-to-one relation (to be fair,
192 one-to-one relationships are merely a special case of one-to-many
193 relationships and works the same way in this module). We can turn 'bob' into a
194 customer by adding a new fixture, but for this example, 'bob' won't be a
195 customer. Instead, we'll create a separate person, 'sally', and make them a
196 customer:
197  
198 person_with_customer => {
199 new => 'Person',
200 using => {
201 name => "sally",
202 email => 'person@customer.com',
203 birthday => $birthday,
204 },
205 next => [qw/basic_customer/],
206 },
207 basic_customer => {
208 new => 'Customer',
209 using => {
210 first_purchase => $datetime_object,
211 person_id => { person_with_customer => 'person_id' },
212 },
213 },
214  
215 =head3 C<next>
216  
217 If you have a C<next> key in your fixture definition, it takes an array
218 reference of fixture names and tells us to load those fixtures I<after> the
219 current one.
220  
221 =head3 C<requires>
222  
223 If you have a C<requires> key, it takes a hash refence. They keys are fixtures
224 to be loaded I<before> the current fixture. The values are hash references of
225 attribute mappings. The C<our> key is our attribute name and the C<their> key
226 is the required fixture's method name. The required fixture(s) is loaded and
227 the C<their> method is called. The resulting value is passed to the C<using>
228 attribute of the fixture you're loading.
229  
230 For example, for the C<basic_customer>, we have to have a C<person_id>. The
231 C<requires> section says "load the C<person_with_customer> fixture". Then, if
232 the C<person_with_customer.person_id> is 3, the C<basic_customer>'s C<using>
233 block effectively becomes this:
234  
235 using => {
236 first_purchase => $datetime_object,
237 person_id => 3,
238 }
239  
240 That allows you to create your fixture correctly since the
241 C<customer.person_id> is required.
242  
243 As a short-cut, if C<our> attribute name is the same as C<their> attribute
244 name, you can just do this:
245  
246 requires => {
247 person_with_customer => 'person_id',
248 }
249  
250 The reason the C<our> and C<their> are separate is because many people just
251 use a primary key name of C<id>. This let's you do this:
252  
253 requires => {
254 person_with_customer => {
255 our => 'person_id',
256 their => 'id',
257 }
258 }
259  
260 Naturally, you can supply multiple "required" objects.
261  
262 If the "required" objects don't have attribute values that need to be passed
263 to the current object, they should probably be passed in the C<next> parameter
264 instead.
265  
266 If all of that for the C<requires> section seems complicated, just forget
267 about it. We also let you do this:
268  
269 {
270 new => 'Customer',
271 using => {
272 first_purchase => $datetime_object,
273 person_id => { some_person => 'id' },
274 },
275 }
276  
277 In other words, if the value of a C<using> attribute is a hashref, we assume
278 that the single key is the name of another fixture and we using that fixture's
279 attribute to populate the current fixture's attribute. Internally, it's
280 converted to a C<requires> block, but you don't need to know about that.
281  
282 If both the current fixture and the other fixture it requires have the same
283 name for the attribute, a reference to the other fixture name (scalar
284 reference) will suffice:
285  
286 an_order_item => {
287 new => 'OrderItem',
288 using => {
289 price => $some_price,
290 order_id => \'basic_order',
291 item_id => \'item_screwdriver',
292 },
293 }
294  
295 In the above example, we have a fixture named C<an_order_item> that will
296 create a new C<OrderItem> object and its C<order_id> will be the C<order_id>
297 from the C<basic_order> fixture and the C<item_id> will be the C<item_id> from
298 the C<item_screwdriver> fixture.
299  
300 =head3 Loading your one-to-one relationships.
301  
302 This is the same as loading a standalone object:
303  
304 my $fixtures = My::Fixtures->new( { schema => $schema } );
305 $fixtures->load('basic_customer');
306  
307 # this is equivalent since these two fixtures require each other
308 $fixtures->load('person_with_customer');
309  
310 # of course, you can still use $schema->resultset(...)->find to get these
311 my $person = $fixtures->get_fixture('person_with_customer');
312 my $customer = $fixtures->get_fixture('basic_customer');
313  
314 is $person->id, $customer->person_id, 'One-to-one relationships work';
315  
316 The main difference between those two C<load> calls is that the first returns
317 a the C<basic_customer> fixture and the second returns the
318 C<person_with_customer> fixture, though both load the same data:
319  
320 my $customer = $fixtures->load('basic_customer');
321 my $person = $fixtures->load('person_with_customer');
322  
323 =head2 One-to-many relationships
324  
325 You actually know everything there is to know about defining fixtures, but
326 we'll give some more concrete examples.
327  
328 Let's look at an orders table. A customer might have many orders.
329  
330 CREATE TABLE orders (
331 order_id INTEGER PRIMARY KEY AUTOINCREMENT,
332 customer_id INTEGER NOT NULL,
333 order_date DATETIME NOT NULL,
334 FOREIGN KEY(customer_id) REFERENCES customers(customer_id)
335 );
336  
337 Let's add two orders for our C<basic_customer>.
338  
339 order_without_items => {
340 new => 'Order',
341 using => {
342 order_date => $purchase_date,
343 customer_id => { basic_customer => 'customer_id' },
344 },
345 },
346 second_order_without_items => {
347 new => 'Order',
348 using => {
349 order_date => $purchase_date,
350 customer_id => { basic_customer => 'customer_id' },
351 },
352 },
353  
354 And if you want to load both in your test code:
355  
356 my @orders = $fixtures->load(qw/
357 order_without_items
358 second_order_without_items
359 /);
360  
361 That will properly load the C<basic_customer> (and, of course, the
362 C<person_with_customer>). However, because C<basic_customer> did not have a
363 C<next> key, loading the C<basic_customer> by itself does not load orders:
364  
365 $fixtures->load('basic_person'); # doesn't load orders
366  
367 If you want to force the customer to have these two orders, add the C<next>
368 key:
369  
370 basic_customer => {
371 new => 'Customer',
372 using => {
373 first_purchase => $datetime_object,
374 person_id => { person_with_customer => 'person_id' },
375 },
376 next => [qw/order_without_items second_order_without_items/],
377 },
378  
379 =head2 Many-to-many relationhips.
380  
381 Orders aren't useful without items on them, so let's add two more tables:
382  
383 CREATE TABLE items (
384 item_id INTEGER PRIMARY KEY AUTOINCREMENT,
385 name VARCHAR(255) NOT NULL,
386 price REAL NOT NULL
387 );
388  
389 CREATE TABLE order_item (
390 order_item_id INTEGER PRIMARY KEY AUTOINCREMENT,
391 item_id INTEGER NOT NULL,
392 order_id INTEGER NOT NULL,
393 price REAL NOT NULL,
394 FOREIGN KEY(item_id) REFERENCES items(item_id),
395 FOREIGN KEY(order_id) REFERENCES orders(order_id)
396 );
397  
398 (Side note about database normalization: the C<order_item> table also has a
399 C<price> column because the the price of the item might change over time, or
400 might be on sale. Fetching the price of orders should rely on the price the
401 time the order was placed, not on the current item price)
402  
403 So let's create hammer and screwdriver items, create an order for them and
404 two order items.
405  
406 # create an order with two items on it
407 item_hammer => {
408 new => 'Item',
409 using => { name => "Hammer", price => 1.2 },
410 },
411 item_screwdriver => {
412 new => 'Item',
413 using => { name => "Screwdriver", price => 1.4 },
414 },
415 order_item_hammer => {
416 new => 'OrderItem',
417 using => {
418 price => 1.2,
419 item_id => \'item_hammer',
420 order_id => \'order_with_items',
421 },
422 },
423 order_item_screwdriver => {
424 new => 'OrderItem',
425 using => {
426 price => .7,
427 item_id => \'item_screwdriver',
428 order_id => \'order_with_items',
429 },
430 },
431 order_with_items => {
432 new => 'Order',
433 using => {
434 order_date => $purchase_date,
435 customer_id => \'basic_customer',
436 },
437 next => [qw/order_item_hammer order_item_screwdriver/],
438 },
439  
440 Note that the C<order_with_items> also uses the basic customer. You can reuse
441 fixtures like this because internally we cache created fixtures.
442  
443 =head2 Bi-directional relationships (deferred requires).
444  
445 Occasionally you might need two entities that relate to each other,
446 signifying different relationships:
447  
448 CREATE TABLE people (
449 person_id INTEGER PRIMARY KEY AUTOINCREMENT,
450 name VARCHAR(255) NOT NULL,
451 favorite_album_id INTEGER,
452 FOREIGN KEY(favorite_album_id) REFERENCES album(album_id)
453 );
454  
455 CREATE TABLE album (
456 album_id INTEGER PRIMARY KEY AUTOINCREMENT,
457 name VARCHAR(255) NOT NULL,
458 producer_id INTEGER,
459 FOREIGN KEY(producer_id) REFERENCES people(person_id)
460 );
461  
462 Say producer Rick Rubin produced ZZ Top's album "La Futura", and that it is his
463 favorite album. You would specify that relationship in this way:
464  
465 person_rick_rubin => {
466 new => 'Person',
467 using => { name => 'Rick Rubin' },
468 requires => {
469 album_la_futura => {
470 our => 'favorite_album_id'
471 their => 'album_id',
472 deferred => 1,
473 },
474 },
475 },
476 album_la_futura => {
477 new => 'Album',
478 using => { name => 'La Futura' },
479 requires => {
480 person_rick_rubin => {
481 our => 'producer_id',
482 their => 'person_id',
483 deferred => 1,
484 },
485 },
486 },
487  
488 This has the net effect of creating both results, then backfilling the
489 appropriate values on each result. Note that both sides of the relationship
490 are marked as C<deferred>.
491  
492 If the foreign key on one of the two tables was defined as C<NOT NULL>:
493  
494 CREATE TABLE album (
495 album_id INTEGER PRIMARY KEY AUTOINCREMENT,
496 name VARCHAR(255) NOT NULL,
497 producer_id INTEGER NOT NULL,
498 FOREIGN KEY(producer_id) REFERENCES people(person_id)
499 );
500  
501 Then that side of the relationship would not be deferrable, and should be
502 defined thusly:
503  
504 person_rick_rubin => {
505 # same as above
506 },
507 album_la_futura => {
508 new => 'Album',
509 using => { name => 'La Futura' },
510 requires => {
511 person_rick_rubin => {
512 our => 'producer_id',
513 their => 'person_id',
514 # Nope!
515 # deferred => 1,
516 },
517 },
518 },
519  
520 This would have the net effect of creating the C<person_rick_rubin> result,
521 then creating the C<album_la_futura> result including the foreign key to it's
522 producer, and finally backfilling the C<favorite_album_id> foreign key on the
523 C<producer_rick_rubin> result.
524  
525 =head2 Groups
526  
527 Sometimes you want to load multiple fixtures at once. One way to do this is
528 like this:
529  
530 $fixtures->load(@list_of_fixtures_to_load);
531  
532 However, if you do this a lot, just create a group in your fixtures
533 definition:
534  
535 people => [qw/basic_person person_with_customer/]
536  
537 Instead of a hashref for the key, have an array reference with all fixtures
538 listed.
539  
540 =head1 NOTES
541  
542 As a general rule, when you call C<< $fixtures->load(@fixture_names) >>, any
543 fixtures loaded will be cached. If a subsequent fixture attempts to load a
544 fixture already loaded, it won't be reloaded.
545  
546 Calling C<< $fixtures->unload >> (or letting the C<$fixtures> object drop out
547 of scope) will clear the cache and allow you to start fresh,
548  
549 =head1 AUTHOR
550  
551 Curtis "Ovid" Poe <ovid@cpan.org>
552  
553 =head1 COPYRIGHT AND LICENSE
554  
555 This software is copyright (c) 2014 by Curtis "Ovid" Poe.
556  
557 This is free software; you can redistribute it and/or modify it under
558 the same terms as the Perl 5 programming language system itself.
559  
560 =cut