root/branches/release-40/t/driver-tests.pl @ 2585

Revision 2585, 28.7 kB (checked in by mpaschal, 18 months ago)

Move sorting and range tests into Test::Search
BugzID: 79953

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#!/usr/bin/perl
2
3# Movable Type (r) Open Source (C) 2001-2008 Six Apart, Ltd.
4# This program is distributed under the terms of the
5# GNU General Public License, version 2.
6#
7# $Id$
8
9use strict;
10use warnings;
11use Data::Dumper;
12use English qw( -no_match_vars );
13
14$OUTPUT_AUTOFLUSH = 1;
15
16# Run this script as a symlink, in the form of 99-driver.t, ie:
17# ln -s driver-tests.pl 99-driver.t
18
19BEGIN {
20    # Set config to driver-test.cfg when run as /path/to/99-driver.t
21    $ENV{MT_CONFIG} = "$1-test.cfg"
22        if __FILE__ =~ m{ [\\/] \d+- ([^\\/]+) \.t \z }xms;
23}
24
25use Test::More;
26use lib 't/lib';
27
28BEGIN {
29    plan skip_all => "Configuration file $ENV{MT_CONFIG} not found"
30        if !-r "t/$ENV{MT_CONFIG}";
31}
32
33use MT::Test qw(:testdb :time);
34
35
36package Zot;
37use base 'MT::Object';
38__PACKAGE__->install_properties({
39    column_defs => {
40        'id' => 'integer not null auto_increment',
41        'x' => 'string(255)',
42    },
43    primary_key => 'id',
44    datasource => 'zot',
45});
46
47
48package Test::GroupBy;
49use base qw( Test::Class MT::Test );
50use Test::More;
51use POSIX qw(strftime);
52
53sub reset_db : Test(setup) {
54    my $self = shift;
55    $self->clean_db();
56
57    my @obj_data = (
58        { class => 'Foo',
59          id => 1,
60          name => 'foo',
61          text => 'bar',
62          status => 2, },
63        { class => 'Foo',
64          id => 2,
65          name => 'baz',
66          text => 'quux',
67          status => 1, },
68        { class => 'Bar',
69          id => 1,
70          foo_id => 2,
71          name => 'bar0',
72          status => 0, },
73        { class => 'Bar',
74          id => 2,
75          foo_id => 2,
76          name => 'bar1',
77          status => 1, },
78        { class => 'Bar',
79          id => 3,
80          foo_id => 1,
81          name => 'bar2',
82          status => 0, },
83    );
84
85    for my $data (@obj_data) {
86        my $class = delete $data->{class};
87        my $obj = $class->new;
88        $obj->set_values($data);
89        $obj->save();
90    }
91}
92
93sub count_group_by : Tests(26) {
94    # legacy way of specifying sort direction
95    my $cgb_iter = Bar->count_group_by({
96            status => '0',
97        }, {
98            group => [ 'foo_id' ],
99            sort => 'foo_id desc',
100        });
101    my ($count, $bfid, $month);
102    isa_ok($cgb_iter, 'CODE');
103    ok(($count, $bfid) = $cgb_iter->(), 'set');
104    is($bfid, 2, 'id');
105    is($count, 1, 'count4');
106    ok(($count, $bfid) = $cgb_iter->(), 'set');
107    is($bfid, 1, 'id');
108    is($count, 1, 'count5');
109    ok(!$cgb_iter->(), 'no $iter');
110
111    # new way of specifying sort direction
112    my $cgb_iter2 = Bar->count_group_by({
113            status => '0',
114        }, {
115            group => [ 'foo_id' ],
116            sort => 'foo_id',
117            direction => 'descend'
118        });
119
120    isa_ok($cgb_iter2, 'CODE');
121    ok(($count, $bfid) = $cgb_iter2->(), 'set');
122    is($bfid, 2, 'id');
123    is($count, 1, 'count4');
124    ok(($count, $bfid) = $cgb_iter2->(), 'set');
125    is($bfid, 1, 'id');
126    is($count, 1, 'count5');
127    ok(!$cgb_iter2->(), 'no $iter');
128
129    # legacy way of specifying sort direction
130    my $cgb_iter3 = Bar->count_group_by(undef, {
131            group => [ 'extract(month from created_on)' ],
132            sort => 'extract(month from created_on) desc',
133        });
134    isa_ok($cgb_iter3, 'CODE');
135    ok(($count, $month) = $cgb_iter3->(), 'set');
136    is(int($month), int(strftime("%m", localtime)), 'month');
137    is($count, 3, 'count6');
138    ok(!$cgb_iter3->(), 'no $iter');
139
140    # new way of specifying sort direction
141    my $cgb_iter4 = Bar->count_group_by(undef, {
142            group => [ 'extract(month from created_on)' ],
143            sort => [{ column => 'extract(month from created_on)',
144                desc => 'desc' }]
145        });
146    isa_ok($cgb_iter4, 'CODE');
147    ok(($count, $month) = $cgb_iter4->(), 'set');
148    is(int($month), int(strftime("%m", localtime)), 'month');
149    is($count, 3, 'count6');
150    ok(!$cgb_iter4->(), 'no $iter');
151}
152
153sub sum_group_by : Tests(7) {
154    # Sum status values across groups of ids (that is, a group for each Foo).
155    my $sgb = Foo->sum_group_by(undef, {
156        sum       => 'status',
157        group     => ['id'],
158        direction => 'ascend',
159    });
160
161    my ($status, $id) = $sgb->();
162    ok($status && $id, 'sum_group_by results had a first result');
163    is($status, 1, q{sum_group_by result #1's status is 1});
164    is($id, 2, 'sum_group_by result #1 was for Foo #2');
165   
166    ($status, $id) = $sgb->();
167    ok($status && $id, 'sum_group_by results had a second result');
168    is($status, 2, q{sum_group_by result #2's status is 2});
169    is($id, 1, 'sum_group_by result #2 was for Foo #1');
170   
171    ($status, $id) = $sgb->();
172    ok(!$status, 'sum_group_by only had two results');
173}
174
175sub avg_group_by : Tests(7) {
176    my $agb = Foo->avg_group_by(undef, {
177        avg => 'status',
178        group => ['id'],
179        direction => 'ascend',
180    });
181   
182    my ($status, $id) = $agb->();
183    ok($status && $id, 'avg_group_by results had a first result');
184    # Compare numerically; is() will compare stringwise.
185    ok($status == 1, q{avg_group_by result #1's status is 1});
186    is($id, 2, 'avg_group_by result #1 was for Foo #2');
187   
188    ($status, $id) = $agb->();
189    ok($status && $id, 'avg_group_by results had a second result');
190    # Compare numerically; is() will compare stringwise.
191    ok($status == 2, q{avg_group_by result #2's status is 2});
192    is($id, 1, 'avg_group_by result #2 was for Foo #1');
193   
194    ($status, $id) = $agb->();
195    ok(!$status, 'avg_group_by only had two results');
196}
197
198sub clean_db : Test(teardown) {
199    MT::Test->reset_table_for(qw( Foo Bar ));
200}
201
202
203package Test::Search;
204use Test::More;
205use MT::Test;
206use base qw( Test::Class MT::Test );
207
208sub make_foos : Test(setup) {
209    MT::Test->reset_table_for('Foo');
210
211    sleep(1);
212    my $foo = Foo->new;
213    $foo->set_values({
214        name   => 'foo',
215        status => 2,
216        text   => 'bar',
217    });
218    $foo->save or die "Could not save test Foo: ", $foo->errstr, "\n";
219   
220    sleep(3);
221    $foo = Foo->new;
222    $foo->set_values({
223        name   => 'baz',
224        status => 1,
225        text   => 'quux',
226    });
227    $foo->save or die "Could not save test Foo #2: ", $foo->errstr, "\n";
228}
229
230sub basic : Tests(5) {
231    my $foo = Foo->load(1);  # not a search
232   
233    is_object(scalar Foo->load({ id => 1 }), $foo, 'Foo #1 by id hash is Foo #1');
234    is_object(scalar Foo->load({ id => 1, name => 'foo' }), $foo, 'Foo #1 by id-name hash is Foo #1');
235    is_object(scalar Foo->load({ name => 'foo' }), $foo, 'Foo #1 by name hash is Foo #1');
236    is_object(scalar Foo->load({ created_on => $foo->created_on }), $foo, 'Foo #1 by created_on hash is Foo #1');
237    is_object(scalar Foo->load({ status => 2 }), $foo, 'Foo #1 by status hash is Foo #1');
238}
239
240sub sorting : Tests(6) {
241    my ($tmp, @tmp);
242    my @foo = map { Foo->load($_) } (1..2);
243
244    ## Load using descending sort (newest)
245    $tmp = Foo->load(undef, {
246        sort => 'created_on',
247        direction => 'descend',
248        limit => 1 });
249    is_object($tmp, $foo[1], 'Newest Foo is Foo #2');
250
251    ## Load using ascending sort (oldest)
252    $tmp = Foo->load(undef, {
253        sort => 'created_on',
254        direction => 'ascend',
255        limit => 1 });
256    is_object($tmp, $foo[0], 'Oldest Foo is Foo #1');
257
258    ## Load using descending sort with limit = 2
259    @tmp = Foo->load(undef, {
260        sort => 'created_on',
261        direction => 'descend',
262        limit => 2 });
263    are_objects(\@tmp, [ reverse @foo ], 'Two Foos newest-first load() finds Foos #2 and #1');
264
265    ## Load using descending sort by created_on, no limit
266    @tmp = Foo->load(undef, {
267        sort => 'created_on',
268        direction => 'descend' });
269    are_objects(\@tmp, [ reverse @foo ], 'All Foos newest-first load() finds Foos #2 and #1');
270
271    ## Load using ascending sort by status, no limit
272    @tmp = Foo->load(undef, { sort => 'status', });
273    are_objects(\@tmp, [ reverse @foo ], 'All Foos lowest-status-first load() finds Foos #2 and #1');
274
275    ## Load using 'last' where status == 2
276    $tmp = Foo->load({ status => 2 }, {
277        sort => 'created_on',
278        direction => 'descend',
279        limit => 1 });
280    is_object($tmp, $foo[0], 'Newest status=2 Foo is Foo #1');
281}
282
283sub ranges : Tests(9) {
284    my $tmp;
285    my @foo = map { Foo->load($_) } (1..2);
286   
287    ## Load using range search, one less than foo[1]->created_on and newer
288    $tmp = Foo->load(
289        { created_on => [ $foo[1]->column('created_on')-1 ] },
290        { range => { created_on => 1 } });
291    is_object($tmp, $foo[1], 'Foo from open-ended date range before Foo #2 is Foo #2');
292
293    ## Load using EXCLUSIVE range search, up through the momment $foo[1] created
294    $tmp = Foo->load(
295        { created_on => [ $foo[1]->column('created_on')-1, 
296                          $foo[1]->column('created_on') ] },
297        { range => { created_on => 1 } });
298    ok(!$tmp, "Exclusive date range load() ending at Foo #1's date found no Foos");
299
300    $tmp = Foo->load(
301        { created_on => [ $foo[1]->column('created_on'), 
302                          $foo[1]->column('created_on')+1 ] },
303        { range => { created_on => 1 } });
304    ok(!$tmp, "Exclusive date range load() starting at Foo #1's date found no Foos");
305
306    ## Load using INCLUSIVE range search, up through the momment $foo[1] created
307    $tmp = Foo->load(
308        { created_on => [ $foo[1]->column('created_on')-1, 
309                          $foo[1]->column('created_on') ] },
310        { range_incl => { created_on => 1 } });
311    ok($tmp, 'Loaded an object based on range_incl (ts-1 to ts)');
312    is_object($tmp, $foo[1], "Foo from inclusive date-range load() ending at Foo #1's date is Foo #2");
313
314    $tmp = Foo->load(
315        { created_on => [ $foo[1]->column('created_on'), 
316                          $foo[1]->column('created_on')+1 ] },
317        { range_incl => { created_on => 1 } });
318    ok($tmp, 'Loaded an object based on range_incl (ts to ts+1)');
319    is_object($tmp, $foo[1], "Foo from inclusive date-range load() starting at Foo #1's date is Foo #2");
320
321    ## Check that range searches return nothing when nothing is in the range.
322    $tmp = Foo->load( { created_on => [ undef, '19690101000000' ] },
323                  { range => { created_on => 1 } });
324    ok(!$tmp, 'Prehistoric date range load() found no Foos');
325
326    ## Range search, all items with created_on less than foo[1]->created_on
327    $tmp = Foo->load(
328        { created_on => [ undef, $foo[1]->column('created_on')-1 ] },
329        { range => { created_on => 1 } });
330    is_object($tmp, $foo[0], "Foo from exclusive open-started date-range load() ending before Foo #1 is Foo #1");
331}
332
333sub unmake_foos : Test(teardown) {
334    MT::Test->reset_table_for('Foo');
335}
336
337
338package main;
339use MT::Test;
340
341Test::Class->runtests('Test::GroupBy', 'Test::Search', +132);
342
343my($foo, @foo, @bar);
344my($tmp, @tmp);
345
346# Test for existing table
347ok(MT::Object->driver->dbd->ddl_class->column_defs('Foo'), "table mt_foo exists after upgrade");
348# Test for non-existent table
349ok(!MT::Object->driver->dbd->ddl_class->column_defs('Zot'), "table mt_zot does not exist after upgrade where undefined");
350
351## Test creating object with new
352##     test column access through column, then through AUTOLOAD
353$foo = Foo->new;
354isa_ok($foo, 'Foo', 'New Foo could be created');
355$foo->column('name', 'foo');
356is($foo->column('name'), 'foo', 'Setting name field with column() persists through access');
357$foo->name('foo');
358is($foo->name, 'foo', 'Setting name field with mutator method persists through access');
359$foo->status(2);
360$foo->text('bar');
361
362## Test saving created object
363ok($foo->save, 'A Foo could be saved');
364is($foo->id, 1, 'First Foo was given an id of 1, says accessor method');
365is($foo->column('id'), 1, 'First Foo was given an id of 1, says column()');
366
367is_object(scalar Foo->load(1), $foo, 'Foo #1 by id is Foo #1');
368
369##     Change column value, save, try to load using old value (fail?),
370##     then load again using new value
371$foo->status(0);
372ok($foo->save, 'Foo #1 saved with new status (0)');
373$tmp = Foo->load({ status => 2 });
374ok(!$tmp, 'Foo #1 no longer loads with old status (2)');
375$tmp = Foo->load({ status => 0 });
376is_object($tmp, $foo, 'Foo #1 by new status (0) is Foo #1');
377
378## Create a new object so we can do range and last/first lookups.
379## Sleep first so that they get different created_on timestamps.
380sleep(3);
381
382## Create new object for iterator testing
383$foo[0] = $foo;
384$foo[1] = Foo->new;
385$foo[1]->name('baz');
386$foo[1]->text('quux');
387$foo[1]->status(1);
388$foo[1]->save;
389
390## TEST LOADING IN VARIOUS WAYS
391
392## Load all objects via iterator
393my $iter = Foo->load_iter(undef, { sort => 'created_on', direction => 'ascend' });
394isa_ok($iter, 'CODE', "Iterator for all Foos");
395ok($tmp = $iter->(), 'Iterator for our two Foos had one object');
396is_object($tmp, $foo[0], "All Foo iterator's first Foo is Foo #1");
397ok($tmp = $iter->(), 'Iterator for our two Foos had two objects');
398is_object($tmp, $foo[1], "All Foo iterator's second Foo is Foo #2");
399ok(!$iter->(), 'Iterator for our two Foos did not have a third object');
400
401## Load all objects with status == 1 via iterator
402$iter = Foo->load_iter({ status => 1 });
403isa_ok($iter, 'CODE', "Iterator for status=1 Foos");
404ok($tmp = $iter->(), 'Iterator for our status=1 Foos had one object');
405is_object($tmp, $foo[1], "Status=1 Foo iterator's first Foo is Foo #2");
406ok(!$iter->(), "Iterator for our status=1 Foos did not have a second object");
407
408## Load using non-existent ID (should fail)
409$tmp = Foo->load(3);
410ok(!$tmp, 'There is no Foo #3');
411
412
413## Get count of objects
414is(Foo->count(), 2, 'Count of all Foos finds both');
415is(Foo->count({ status => 0 }), 1, 'Count of all status=0 Foos finds all one');
416my $ranged_count = Foo->count(
417    { created_on => [ $foo[1]->column('created_on')-1 ] },
418    { range => { created_on => 1 } }
419);
420is($ranged_count, 1, 'Count of all Foos in open-ended date range starting before Foo #1 finds all one');
421
422## Update status for later tests.
423$foo[0]->status(2);
424$foo[0]->save;
425
426## Test start_val loads.
427## Given the first Foo object, should load the "next" one
428## (the one with a larger created_on time)
429$tmp = Foo->load(undef, {
430    limit => 1,
431    sort => 'created_on',
432    direction => 'ascend',
433    start_val => $foo[0]->created_on });
434is_object($tmp, $foo[1], 'Next newer Foo after Foo #1 is Foo #2');
435
436## Given the first Foo object, try to load the "previous" one
437## (the one with a smaller created_on time). This should fail.
438$tmp = Foo->load(undef, {
439    limit => 1,
440    sort => 'created_on',
441    direction => 'descend',
442    start_val => $foo[0]->created_on });
443ok(!$tmp, 'Search for next older Foo before Foo #1 found none');
444
445## Given the second Foo object, try to load the "previous" one
446## (the one with a smaller created_on time). This should work.
447$tmp = Foo->load(undef, {
448    limit => 1,
449    sort => 'created_on',
450    direction => 'descend',
451    start_val => $foo[1]->created_on });
452is_object($tmp, $foo[0], 'Next older Foo before Foo #2 is Foo #1');
453
454## Given the second Foo object, try to load the "next" one
455## (the one with a larger created_on time). This should fail.
456$tmp = Foo->load(undef, {
457    limit => 1,
458    sort => 'created_on',
459    direction => 'ascend',
460    start_val => $foo[1]->created_on });
461ok(!$tmp, 'Search for next newer Foo after Foo #2 found none');
462
463## Now, given the second Foo object's created_on - 1, try to
464## load the "previous" one. This should work.
465$tmp = Foo->load(undef, {
466    limit => 1,
467    sort => 'created_on',
468    direction => 'descend',
469    start_val => $foo[1]->created_on-1 });
470is_object($tmp, $foo[0], 'Next older Foo before just before Foo #2 is Foo #1');
471
472## Now, given the second Foo object's created_on - 1, try to
473## load the "next" one. This should work.
474$tmp = Foo->load(undef, {
475    limit => 1,
476    sort => 'created_on',
477    direction => 'ascend',
478    start_val => $foo[1]->created_on-1 });
479is_object($tmp, $foo[1], 'Next newer Foo after just before Foo #2 is Foo #2');
480
481## Override created_on timestamp, make sure it works
482my $ts = substr($foo[1]->created_on, 0, -4) . '0000';
483$foo[1]->created_on($ts);
484$foo[1]->save;
485
486@tmp = Foo->load(undef, {
487    sort => 'created_on',
488    direction => 'descend',
489    limit => 2 });
490are_objects(\@tmp, \@foo, 'Time-traveled Foos newest-first are Foos #1 and #2');
491
492## Test limit of 2 with direction descend, but without
493## a sort option. This should sort by the most recently-added
494## records, ie. sorted by ID, basically.
495@tmp = Foo->load(undef, {
496    direction => 'descend',
497    limit => 2 });
498are_objects(\@tmp, [ reverse @foo ], 'Foos highest-id-first are Foos #2 and #1');
499
500## Test loading using offset.
501## Should load the second Foo object.
502$tmp = Foo->load(undef, {
503    direction => 'descend',
504    sort => 'created_on',
505    limit => 1,
506    offset => 1 });
507is_object($tmp, $foo[1], 'Second newest Foo is Foo #2');
508
509## We only have 2 Foo objects, so this should load
510## only the second Foo object (because offset is 1).
511@tmp = Foo->load(undef, {
512    direction => 'descend',
513    sort => 'created_on',
514    limit => 2,
515    offset => 1 });
516are_objects(\@tmp, [ $foo[1] ], 'Second and third newest Foos is just Foo #2');
517
518## Should load the first Foo object (ascend with offset of 1).
519$tmp = Foo->load(undef, {
520    direction => 'ascend',
521    sort => 'created_on',
522    limit => 1,
523    offset => 1 });
524is_object($tmp, $foo[0], 'Second oldest Foo is Foo #1');
525
526## Now test join loads.
527## First we need to create a couple of Bar objects.
528$bar[0] = Bar->new;
529$bar[0]->foo_id($foo[1]->id);
530$bar[0]->name('bar0');
531$bar[0]->status(0);
532ok($bar[0]->save, 'saved');
533sleep(2);  ## Sleep to ensure created_on timestamps are unique
534
535$bar[1] = Bar->new;
536$bar[1]->foo_id($foo[1]->id);
537$bar[1]->name('bar1');
538$bar[1]->status(1);
539ok($bar[1]->save, 'saved');
540sleep(2);  ## Sleep to ensure created_on timestamps are unique
541
542$bar[2] = Bar->new;
543$bar[2]->foo_id($foo[0]->id);
544$bar[2]->name('bar2');
545$bar[2]->status(0);
546ok($bar[2]->save, 'saved');
547sleep(2);  ## Sleep to ensure created_on timestamps are unique
548
549## Get a count of all Foo objects in order of most recently
550## created Bar object. No uniqueness requirement. This tests
551## the on_load_complete temporary table stuff with count.
552
553is(Foo->count(undef,
554    { join => [ 'Bar', 'foo_id',
555                undef,
556                { unique => 1,
557                  sort => 'created_on',
558                  direction => 'descend', } ] }), 2, 'There are 2 unique Foos associated with Bars');
559
560## Now load all Foo objects in order of most recently
561## created Bar object. Make sure they are unique.
562@tmp = Foo->load(undef,
563    { join => [ 'Bar', 'foo_id',
564                undef,
565                { sort => 'created_on',
566                  direction => 'descend',
567                  unique => 1 } ] });
568are_objects(\@tmp, \@foo, 'unique Foos associated with Bars, oldest first');
569
570## Load all Foo objects in order of most recently
571## created Bar object. No uniqueness requirement.
572@tmp = Foo->load(undef,
573    { join => [ 'Bar', 'foo_id',
574                undef,
575                { sort => 'created_on',
576                  direction => 'descend', } ] });
577are_objects(\@tmp, [ @foo, $foo[1] ], 'Foos associated with Bars, oldest first');
578
579## Load last 1 Foo object in order of most recently
580## created Bar object.
581@tmp = Foo->load(undef,
582    { join => [ 'Bar', 'foo_id',
583                undef,
584                { sort => 'created_on',
585                  direction => 'descend',
586                  unique => 1,
587                  limit => 1, } ] });
588are_objects(\@tmp, [ $foo[0] ], 'Foos associated with oldest Bar');
589
590## Load all Foo objects where Bar.name = 'bar0'
591@tmp = Foo->load(undef,
592    { join => [ 'Bar', 'foo_id',
593                { name => 'bar0' },
594                { sort => 'created_on',
595                  direction => 'descend',
596                  unique => 1, } ] });
597are_objects(\@tmp, [ $foo[1] ], 'Foos associated with Bars named bar0');
598
599## foo[1] is older than foo[0] because we overrode the timestamp,
600## so this should load foo[0]
601@tmp = Foo->load(undef,
602    { sort => 'created_on', direction => 'descend', limit => 1,
603    join => [ 'Bar', 'foo_id', { status => 0 }, { unique => 1 } ] });
604are_objects(\@tmp, [ $foo[0] ], 'One Foo associated with Bars of status=0');
605
606## This is the same join as the last one, but without the limit--so
607## we should get both Foo objects this time, in descending order.
608@tmp = Foo->load(undef,
609    { sort => 'created_on', direction => 'descend',
610      join => [ 'Bar', 'foo_id', { status => 0 }, { unique => 1 } ] });
611are_objects(\@tmp, \@foo, 'All Foos associated with Bars of status=0');
612
613## Filter join results by providing a value for 'status'; only Foo[0]
614## has a 'status' == 2, so only that record should be returned.
615@tmp = Foo->load({ status => 2 },
616    { sort => 'created_on', direction => 'descend',
617      join => [ 'Bar', 'foo_id', { status => 0 }, { unique => 1 } ] });
618are_objects(\@tmp, [ $foo[0] ], 'Foos of status=2 associated with Bars of status=0');
619
620# Join across a column.
621@tmp = Foo->load({},
622    { sort => 'created_on', direction => 'descend',
623      join => [ 'Bar', undef, { foo_id => \'= foo_id', status => 0 }, { unique => 1 } ] });
624are_objects(\@tmp, \@foo, 'Foos loaded by explicit join across columns');
625
626@tmp = Foo->load({ status => 2 },
627    { sort => 'created_on', direction => 'descend',
628      join => [ 'Bar', undef, { foo_id => \'= foo_id', status => 0 }, { unique => 1 } ] });
629are_objects(\@tmp, [ $foo[0] ], 'Foos of status=2 loaded by explicit join across columns');
630
631## TEST EXISTS METHOD
632ok($foo->exists, 'First Foo long saved exists in db');
633$tmp = Foo->new;
634ok(!$tmp->exists, 'New Foo just created does not exist in db');
635$tmp->id(5);
636ok(!$tmp->exists, 'New Foo just created with fake id does not exist in db');
637
638## Change foo[1]->status so that its value is unique (for index)
639$foo[1]->status(5);
640ok($foo[1]->save, 'saved');
641ok(Foo->load({ status => 5 }), 'loaded' );
642
643## Test remove
644ok($foo[1]->remove, 'removed');
645ok(! Foo->load(2), 'not loaded');
646ok(! Foo->load({ status => 5 }), 'not loaded');
647ok(! Foo->load({ name => $foo[1]->name }), 'not loaded');
648ok(! Foo->load({ created_on => $foo[1]->created_on }), 'not loaded');
649
650## Test methods:
651##     * properties
652my $props1 = Foo->properties;
653is($props1->{audit}, 1, 'audit');
654is(scalar keys %{ $props1->{indexes} }, 3, 'indexes');
655is($props1->{primary_key}, 'id', 'id');
656is(scalar @{ $props1->{columns} }, 9, 'columns');
657my $props2 = $foo->properties;
658is($props1, $props2, "$props1 is $props2");  ## Same address, because same hashref
659
660##     * column_names
661my $cols = $foo->column_names;
662isa_ok($cols, 'ARRAY');
663my %cols = map { $_ => 1 } @$cols;
664for (qw(id name status text data created_on created_by modified_on modified_by)) {
665    ok($cols{$_}, 'cols');
666}
667
668##     * column_values
669my $vals = $foo->column_values;
670isa_ok($vals, 'HASH');
671is($vals->{id}, $foo->id, 'id');
672is($vals->{name}, $foo->name, 'name');
673is($vals->{status}, $foo->status, 'status');
674is($vals->{text}, $foo->text, 'text');
675is($vals->{created_on}, $foo->created_on, 'created_on');
676is($vals->{created_by}, $foo->created_by, 'created_by');
677is($vals->{modified_on}, $foo->modified_on, 'modified_on');
678is($vals->{modified_by}, $foo->modified_by, 'modified_by');
679
680##     * set_values
681$vals = {
682    id => 5,
683    name => 'baz',
684    status => 7,
685    text => 'quux',
686    created_on => 13209,
687    created_by => 'bar',
688    #modified_on => 39023, modified_by auto-set modified_on in our new code.
689    modified_by => 'foo',
690};
691$foo->set_values($vals);
692for my $col (keys %$vals) {
693    is($vals->{$col}, $foo->column($col), $col);
694}
695
696##     * binary data
697
698my $binmonster = Foo->new;
699
700$vals = {
701    funky => "yes",
702    monkey => "no",
703};
704
705require MT::Serialize;
706my $srlzr = MT::Serialize->new('MT');
707$binmonster->data($srlzr->serialize(\$vals));
708my $x = $binmonster->save();
709warn 'Failed binary data test: ' . $binmonster->errstr() unless $x;
710ok($x, 'saved');
711ok($binmonster->id, 'id');
712Foo->driver->clear_cache if Foo->driver->can('clear_cache');
713my $chk = Foo->load($binmonster->id);
714if ($chk) {
715    my $chk_data = $chk->data;
716    my $chk_vals = $srlzr->unserialize($chk_data);
717    foreach (keys %$vals) {
718        is($$chk_vals->{$_}, $vals->{$_}, $_);
719    }
720} else {
721    foreach (keys %$vals) {
722        ok(0, $_);
723    }
724}
725
726##     * datasource
727is($foo->table_name, 'mt_' . $foo->datasource, 'datasource');
728
729##     * clone
730my $clone = $foo->clone_all;
731for my $col (@$cols) {
732    is($clone->column($col), $foo->column($col), $col);
733}
734
735## Sleep first so that they get different created_on timestamps.
736sleep(3);
737
738Foo->set_by_key({name => "this"});
739my $obj = Foo->load({name => "this"});
740isa_ok($obj, 'Foo');
741
742Foo->set_by_key({name => "this"}, {status => 42});
743$obj = Foo->load({name => "this"});
744is($obj && $obj->status, 42, 'status');
745
746Foo->set_by_key({name => "this"}, {status => 47});
747$obj = Foo->load({name => "this"});
748is($obj && $obj->status, 47, 'status');
749
750Foo->set_by_key({name => "this", status => 47}, {text => "spiffy"});
751$obj = Foo->load({name => "this", status => 47});
752is($obj && $obj->text, 'spiffy', 'text');
753
754sleep(3);
755
756Foo->set_by_key({name => "that"}, {text => "Once"});
757$obj = Foo->load({name => "that"});
758is($obj && $obj->text, 'Once', 'text');
759
760Foo->driver->clear_cache if Foo->driver->can('clear_cache');
761## Load use direct set of values for non-PK column
762@tmp = Foo->load({ name => [qw(foo this)] });
763@tmp = sort {$a->name cmp $b->name} @tmp;
764is(@tmp, 2, 'array length 2');
765
766is(Foo->count(), 4, 'check number of Foos');
767
768## check offsets without limits
769## Should load the third and fourth Foo objects.
770my $foo4 = Foo->load({name => "this"});
771my $foo5 = Foo->load({name => "that"});
772my $foo1 = Foo->load(undef, { 'sort' => 'created_on', 'direction' => 'ascend' });
773my @offs = Foo->load(undef, {
774    direction => 'ascend',
775    sort => 'created_on',
776    offset => 2 });
777is(@offs, 2, 'array length 2');
778isa_ok($offs[0], 'Foo');
779is($offs[0]->id, $foo4->id, 'id');
780isa_ok($offs[1], 'Foo');
781is($offs[1]->id, $foo5->id, 'id');
782
783## Should load the third and fourth Foo objects.
784@offs = Foo->load(undef, {
785    direction => 'descend',
786    sort => 'created_on',
787    offset => 1 });
788is(@offs, 3, 'array length 3');
789isa_ok($offs[0], 'Foo');
790is($offs[0]->id, $foo4->id, 'id');
791isa_ok($offs[1], 'Foo');
792is($offs[1]->id, $binmonster->id, 'id');
793isa_ok($offs[2], 'Foo');
794is($offs[2]->id, $foo1->id, 'id');
795
796# TODO: what are these even about?
797SKIP: {
798    skip(1, '$tmp[0] undefined') unless $tmp[0];
799    ok($tmp[0] && ($tmp[0]->name eq 'foo'), 'name')
800}
801SKIP: {
802    skip(1, '$tmp[1] undefined') unless $tmp[1];
803    ok($tmp[1] && ($tmp[1]->name eq 'this'), 'name');
804}
805
806# -or
807my $newdata = Foo->new;
808$newdata->status(11);
809$newdata->name('Apple');
810$newdata->text('MacBook');
811$newdata->save;
812$newdata = Foo->new;
813$newdata->status(12);
814$newdata->name('Linux');
815$newdata->text('Ubuntu');
816$newdata->save;
817$newdata = Foo->new;
818$newdata->status(13);
819$newdata->name('Microsoft');
820$newdata->text('Vista');
821$newdata->save;
822$newdata = Foo->new;
823$newdata->status(10);
824$newdata->name('Microsoft');
825$newdata->text('XP');
826$newdata->save;
827$newdata = Foo->new;
828$newdata->status(10);
829$newdata->name('Apple');
830$newdata->text('iBook');
831$newdata->save;
832
833my $count = Foo->count( [{status => 10}, -or => {name => 'Apple'}] );
834# ==> select count(*) from mt_foo where foo_status = 10 or foo_name = 'Apple'
835is($count, 3, '-or count');
836
837$count = Foo->count( [ { status => { '<=' => 20 }, name => 'Apple' }, -and_not => { status => 11 } ] );
838# ==> select count(*) from mt_foo where (foo_status <= 20 and foo_name = 'Apple') and not (foo_status = 11)
839is($count, 1, '-and_not count');
840
841$count = Foo->count( [
842    { status => 10 },
843    -or => { name => 'Apple' },
844    -or => { name => { like => '%nux' } },
845] );
846# ==> select count(*) from mt_foo where (foo_status = 10) or (foo_name = 'Apple') or (foo_name like '%nux')
847# (selects Apple+MacBook, Apple+iBook, Microsoft+XP, Linux+Ubuntu)
848is($count, 4, '-or count, 3 clauses');
849
850# alias support
851my $vista = Foo->load({name=>'Microsoft', status=>13});
852my $newbar = Bar->new;
853$newbar->foo_id($vista->id);
854$newbar->name('Silverlight');
855$newbar->status(2);
856$newbar->save;
857sleep(3);
858$newbar = Bar->new;
859$newbar->foo_id($vista->id);
860$newbar->name('IronPython');
861$newbar->status(3);
862$newbar->save;
863sleep(3);
864my $mb = Foo->load({name=>'Apple', status=>11});
865$newbar = Bar->new;
866$newbar->foo_id($mb->id);
867$newbar->name('IronRuby');
868$newbar->status(0);
869$newbar->save;
870
871# select * from foo, bar bar1, bar bar2
872# where bar1.bar_foo_id = foo_id
873# and bar2.bar_foo_id = bar1.bar_foo_id
874# and bar1.status = 2
875# and bar2.status = 3
876my @a_foos = Foo->load(
877    undef,
878    { join => [ 'Bar', undef, { foo_id => \'= foo_id', status => 2 },
879        { join => [ 'Bar', undef, { foo_id => \'= bar1.bar_foo_id', status => 3 },
880            { alias => 'bar2' } ],
881          alias => 'bar1'
882        }
883      ],
884      sort => 'created_on', direction => 'descend',
885    }
886);
887is(scalar(@a_foos), 1, 'join the same table using alias 1');
888is($a_foos[0]->id, $vista->id, 'join the same table using alias 2');
889
890@a_foos = Foo->load(
891    undef,
892    { join => [ 'Bar', undef, { foo_id => \'= foo_id', status => 2 },
893        { join => [ 'Bar', undef, { foo_id => \'= bar1.bar_foo_id', status => 0 },
894            { alias => 'bar2' } ],
895          alias => 'bar1'
896        }
897      ],
898      sort => 'created_on', direction => 'descend',
899    }
900);
901is(scalar(@a_foos), 0, 'join the same table using alias 3');
902 
903
9041;
Note: See TracBrowser for help on using the browser.