-
Notifications
You must be signed in to change notification settings - Fork 28
/
EActiveRecordRelationBehaviorTest.php
1324 lines (1151 loc) · 35.1 KB
/
EActiveRecordRelationBehaviorTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* EActiveRecordRelationBehavior unit tests
*
* @author Carsten Brandt <mail@cebe.cc>
* @link http://yiiext.github.com/extensions/activerecord-relation-behavior/index.html
* @copyright Copyright © 2012 Carsten Brandt
* @license https://github.com/yiiext/activerecord-relation-behavior/blob/master/LICENSE#L1
*
* How to run this test
* --------------------
*
* 1. make sure yii framework is available under ./yii/framework
* you can do this by
* - cloning the yii git repo with `git clone https://github.com/yiisoft/yii.git yii`
* - or linking existing yii directory here with `ln -s ../../path/to/yii yii`
*
* 2. make sure you have phpunit installed and available in PATH (http://www.phpunit.de/manual/3.6/en/installation.html)
*
* 3. run `phpunit --colors EActiveRecordRelationBehaviorTest.php` or if you want coverage information in html,
* run `phpunit --coverage-html tmp/coverage --colors EActiveRecordRelationBehaviorTest.php`
*/
namespace yiiext\behaviors\activeRecordRelation\tests;
define('TEST_NAMESPACE', 'yiiext\behaviors\activeRecordRelation\tests');
if (!defined('YII_PATH')) {
$yii = dirname(__FILE__).'/vendor/yiisoft/yii/framework/yiit.php';
require_once($yii);
}
require_once(dirname(__FILE__).'/EActiveRecordRelationBehavior.php');
\PHP_CodeCoverage_Filter::$blacklistClassNames = array();
/**
* unit test class for EActiveRecordRelationBehavior
*
* these things are not covered and should be kept in mind while developing:
*
* - make sure it works with any custom db connection
* therefor only use $this->owner->dbConnection
* - make sure it works with any possible configuration that works for yii
*
* these things should be added in test
* @todo make sure it works with and without table prefix
* @todo make sure it works with and without defined primary keys
* @todo make sure 'through' relations are not touched until they are supported
*
* @author Carsten Brandt <mail@cebe.cc>
* @package yiiext.behaviors.activeRecordRelation.tests
*/
class EActiveRecordRelationBehaviorTest extends \CTestCase
{
public $dbFile;
/** @var EActiveRecordRelationBehaviorTestMigration */
protected $migration;
/**
* set up environment with yii application and migrate up db
*/
public function setUp()
{
$basePath=dirname(__FILE__).'/tmp';
if (!file_exists($basePath))
mkdir($basePath, 0777, true);
if (!file_exists($basePath.'/runtime'))
mkdir($basePath.'/runtime', 0777, true);
// create webapp
if (\Yii::app()===null) {
\Yii::createWebApplication(array(
'basePath'=>$basePath,
));
}
\CActiveRecord::$db=null;
if (!isset($_ENV['DB']) || $_ENV['DB'] == 'sqlite')
{
if (!$this->dbFile)
$this->dbFile = $basePath.'/test.'.uniqid(time()).'.db';
\Yii::app()->setComponent('db', new \CDbConnection('sqlite:'.$this->dbFile));
}
elseif ($_ENV['DB'] == 'mysql')
\Yii::app()->setComponent('db', new \CDbConnection('mysql:dbname=test;host=localhost', 'root'));
elseif ($_ENV['DB'] == 'pgsql')
\Yii::app()->setComponent('db', new \CDbConnection('pqsql:dbname=test;host=localhost', 'postgres'));
else
throw new \Exception('Unknown db. Only sqlite, mysql and pgsql are valid.');
// create db
$this->migration = new EActiveRecordRelationBehaviorTestMigration();
$this->migration->dbConnection = \Yii::app()->db;
$this->migration->up();
}
/**
* migrate down db when test succeeds
*/
public function tearDown()
{
if (!$this->hasFailed() && $this->migration && $this->dbFile) {
$this->migration->down();
unlink($this->dbFile);
}
}
/**
* dataprovider that lists possible configuration options for foreign keys, so
* we make sure to have our models configured in many ways and it still works
* @return array (configType, transactional)
*/
public function fkConfigurationProvider()
{
$configOptions = array(
'normal', // all fks configured as string
// 'fkarray', // will be supported when support for composite pks is added
// 'fkcomma', // will be used when composite pks are supported
);
// @todo mix them!
$configs = array();
foreach($configOptions as $option) {
$configs[] = array(array('Profile'=>$option, 'User'=>$option, 'Post'=>$option, 'Category'=>$option), true);
$configs[] = array(array('Profile'=>$option, 'User'=>$option, 'Post'=>$option, 'Category'=>$option), false);
}
return $configs;
}
protected function setConfig($config)
{
Profile::$configurationType = $config['Profile'];
User::$configurationType = $config['User'];
Post::$configurationType = $config['Post'];
Category::$configurationType = $config['Category'];
}
protected function startTransaction($t)
{
$this->assertNull(\Yii::app()->db->currentTransaction, 'there shouldn\'t be a transaction at start');
if ($t) {
\Yii::app()->db->beginTransaction();
$this->assertNotNull(\Yii::app()->db->currentTransaction, 'there should be a transaction after beginTransaction');
}
}
protected function endTransaction($t)
{
if ($t) {
$this->assertNotNull(\Yii::app()->db->currentTransaction, 'there should be a transaction, we created one at start');
\Yii::app()->db->currentTransaction->commit();
$this->assertNull(\Yii::app()->db->currentTransaction, 'there shouldn\'t be a transaction after commit');
} else {
$this->assertNull(\Yii::app()->db->currentTransaction, 'there shouldn\'t be a transaction anymore, behavior should have committed or rolledBack');
}
}
/**
* test creation of AR and assigning a relation with BELONGS_TO
*
* @dataProvider fkConfigurationProvider
*/
public function testBelongsTo($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
$john = $this->getJohn();
$p = new Post();
$p->title = 'hi testing!';
$p->author = $john;
// saving with a related record that is new should fail
$exception=false;
try {
$p->save();
} catch (\CDbException $e) {
$exception=true;
}
$this->assertTrue($exception, 'Expected CDbException on saving with a non saved record.');
$this->assertSaveSuccess($p->author); // saved john
$this->assertSaveSuccess($p);
$this->assertEquals($p->author_id, $john->id);
$p->refresh();
$this->assertEquals($p->author_id, $john->id);
$this->assertNotNull($p->author);
$this->assertEquals($p->author->id, $john->id);
$jane = $this->getJane(10, true);
$p = new Post();
$p->title = 'hi testing2!';
$p->author = $jane->id;
$this->assertSaveSuccess($p);
$this->assertEquals($p->author_id, $jane->id);
$p->refresh();
$this->assertEquals($p->author_id, $jane->id);
$this->assertNotNull($p->author);
$this->assertEquals($p->author->id, $jane->id);
$this->endTransaction($transactional);
}
/**
* test creation of AR and assigning a relation with HAS_ONE
* this also tests the HAS_ONE oposite BELONGS_TO
*
* @dataProvider fkConfigurationProvider
*/
public function testHasOne($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
// check if the normal thing works
$john = $this->getJohn();
$this->assertSaveSuccess($john);
// create a jane to make sure her relation does not change
$jane = $this->getJane();
$this->assertSaveSuccess($jane);
$this->assertNull($john->profile);
$this->assertEquals(array(), $john->posts);
$this->assertEquals($this->getJohn(1)->attributes, $john->attributes);
$john->refresh();
$this->assertNull($john->profile);
$this->assertEquals(array(), $john->posts);
$this->assertEquals($this->getJohn(1)->attributes, $john->attributes);
$john->profile = new Profile();
$this->assertNotNull($john->profile);
$this->assertEquals(array(), $john->posts);
$this->assertEquals($this->getJohn(1)->attributes, $john->attributes);
$john->profile->website = 'http://www.example.com/';
$this->assertEquals('http://www.example.com/', $john->profile->website);
// saving with a related record that is new should fail
$exception=false;
try {
$john->save();
} catch (\CDbException $e) {
$exception=true;
}
$this->assertTrue($exception, 'Expected CDbException on saving with a non saved record.');
$this->assertSaveFailure($john->profile, array('owner_id')); // owner_id is required and not set by EActiveRecordRelationBehavior
$john->profile->owner = $john;
$this->assertSaveSuccess($john->profile);
// after profile is saved, john should be saved
$this->assertSaveSuccess($john);
$this->assertNotNull($john->profile);
/** @var Profile $profile */
$this->assertNotNull($profile=Profile::model()->findByPk($john->profile->owner_id));
/** @var User $user */
$this->assertNotNull($user=User::model()->findByPk($john->id));
$this->assertEquals($profile, $user->profile);
$this->assertEquals($user, $profile->owner);
$this->assertNull($jane->profile);
$jane->refresh();
$this->assertNull($jane->profile);
// this can not work since pk of profile can not be null
// @todo should be supported
/*$p = $john->profile;
$this->assertNotNull($john->profile);
$john->profile = null;
$this->assertNull($john->profile);
$this->assertSaveSuccess($john);
$this->assertNull($john->profile);
$john->refresh();
$this->assertNull($john->profile);
$p->refresh();*/
$this->endTransaction($transactional);
}
/**
* test creation of AR and assigning a relation with HAS_MANY as pk values
* one record is added as object later
*
* @dataProvider fkConfigurationProvider
*/
public function testHasManyPk($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
$author = $this->getJohn();
$this->assertSaveSuccess($author);
$this->assertEquals(array(), $author->posts);
$posts = $this->getPosts(10);
for($n=1;$n<10;$n++) {
$posts[$n] = $posts[$n]->id;
}
$author->posts = $posts;
$this->assertEquals(9, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(9, count($author->posts));
$author->refresh();
$this->assertEquals(9, count($author->posts));
// remove some records
unset($posts[1]);
unset($posts[3]);
$author->posts = $posts;
$this->assertEquals(7, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(7, count($author->posts));
$author->refresh();
$this->assertEquals(7, count($author->posts));
// remove some, add some records
unset($posts[4]);
unset($posts[5]);
$p = new Post();
$p->title = 'testtitle';
$this->assertSaveSuccess($p);
$posts[] = $p; // this one is mixed
$author->posts = $posts;
$this->assertEquals(6, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(6, count($author->posts));
$author->refresh();
$this->assertEquals(6, count($author->posts));
// remove all records
$author->posts = array();
$this->assertEquals(0, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(0, count($author->posts));
$author->refresh();
$this->assertEquals(0, count($author->posts));
$this->endTransaction($transactional);
}
/**
* test creation of AR and assigning a relation with HAS_MANY as objects values
* one record is added as pk later
*
* @dataProvider fkConfigurationProvider
*/
public function testHasManyObject($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
$author = $this->getJohn();
$this->assertSaveSuccess($author);
$this->assertEquals(array(), $author->posts);
$posts = $this->getPosts();
$author->posts = $posts;
$this->assertEquals(9, count($author->posts));
// saving with a related record that is new should fail
$exception=false;
try {
$author->save();
} catch (\CDbException $e) {
$exception=true;
}
$this->assertTrue($exception, 'Expected CDbException on saving with a non saved record.');
// saving last record
$this->assertSaveSuccess(end($posts));
$this->assertEquals(9, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(9, count($author->posts));
$author->refresh();
$this->assertEquals(9, count($author->posts));
// remove some records
unset($posts[1]);
unset($posts[3]);
$author->posts = $posts;
$this->assertEquals(7, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(7, count($author->posts));
$author->refresh();
$this->assertEquals(7, count($author->posts));
// remove some, add some records
unset($posts[4]);
unset($posts[5]);
$p = new Post();
$p->title = 'testtitle';
$this->assertSaveSuccess($p);
$posts[] = $p->id; // this one is mixed
$author->posts = $posts;
$this->assertEquals(6, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(6, count($author->posts));
$author->refresh();
$this->assertEquals(6, count($author->posts));
// remove all records
$author->posts = array();
$this->assertEquals(0, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(0, count($author->posts));
$author->refresh();
$this->assertEquals(0, count($author->posts));
$this->endTransaction($transactional);
}
/**
* test adding null values to HAS_MANY pk values
*
* @dataProvider fkConfigurationProvider
*/
public function testHasManyNulls($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
$author = $this->getJohn();
$this->assertSaveSuccess($author);
$this->assertEquals(array(), $author->posts);
$posts = $this->getPosts(10);
$posts[2] = null;
$posts[5] = null;
for($n=1;$n<10;$n++) {
$posts[$n] = $posts[$n] !== null ? $posts[$n]->id : null;
}
$author->posts = $posts;
$this->assertEquals(9, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(9, count($author->posts));
$author->refresh();
$this->assertEquals(7, count($author->posts));
$posts = $author->posts;
// set some records to null
$posts[1] = null;
$posts[3] = null;
$author->posts = $posts;
$this->assertEquals(7, count($author->posts));
$this->assertSaveSuccess($author);
$this->assertEquals(7, count($author->posts));
$author->refresh();
$this->assertEquals(5, count($author->posts));
$this->endTransaction($transactional);
}
/**
* @return array
*/
protected function beforeManyMany()
{
$untouchedCategory1 = new Category();
$untouchedCategory1->name = 'untouched1';
$this->assertEquals(0, count($untouchedCategory1->posts));
$this->assertSaveSuccess($untouchedCategory1);
$this->assertEquals(0, count($untouchedCategory1->posts));
$untouchedCategory2 = new Category();
$untouchedCategory2->name = 'untouched2';
$untouchedCategory2->posts = $this->getPosts(10, true);
$this->assertEquals(9, count($untouchedCategory2->posts));
$this->assertSaveSuccess($untouchedCategory2);
$this->assertEquals(9, count($untouchedCategory2->posts));
return array($untouchedCategory1, $untouchedCategory2);
}
/**
* @param Category $untouchedCategory1
* @param Category $untouchedCategory2
*/
protected function afterManyMany($untouchedCategory1, $untouchedCategory2)
{
$this->assertEquals('untouched1', $untouchedCategory1->name);
$this->assertEquals(0, count($untouchedCategory1->posts));
$untouchedCategory1->refresh();
$this->assertEquals('untouched1', $untouchedCategory1->name);
$this->assertEquals(0, count($untouchedCategory1->posts));
$this->assertEquals('untouched2', $untouchedCategory2->name);
$this->assertEquals(9, count($untouchedCategory2->posts));
$untouchedCategory2->refresh();
$this->assertEquals('untouched2', $untouchedCategory2->name);
$this->assertEquals(9, count($untouchedCategory2->posts));
}
public function manymanyData()
{
$data = array(
array(true, 1), // only pks
array(true, 2), // mixed
array(false, 1), // only model objects
);
// mix in data from @dataProvider fkConfigurationProvider
$return = array();
foreach($this->fkConfigurationProvider() as $row) {
foreach($data as $dataRow) {
$return[] = array_merge($dataRow, $row);
}
}
return $return;
}
/**
* test creation of AR and assigning a relation with MANY_MANY as pk values
*
* @dataProvider manymanyData
*/
public function testManyMany($postsAsPk, $modulo, $config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
if ($postsAsPk) { // first with pk data
$posts=$this->getPosts(10, true);
for($n=1;$n<10;$n++) {
if ($n % $modulo == 0) {
$posts[$n] = $posts[$n]->id;
}
}
} else {
$posts = $this->getPosts(10, true); // second with object data
}
list($un1, $un2) = $this->beforeManyMany();
// begin real test
$category = new Category();
$category->name = 'my new cat';
$this->assertEquals(array(), $category->posts);
$category->save();
$this->assertEquals(array(), $category->posts);
$category->save();
$this->assertEquals(0, count($category->posts));
$category->posts = $posts;
$this->assertEquals(9, count($category->posts));
$category->save();
$this->assertEquals(9, count($category->posts));
// remove some records
unset($posts[1]);
unset($posts[3]);
$this->assertEquals(9, count($category->posts));
$category->posts = $posts;
$this->assertEquals(7, count($category->posts));
$category->save();
$this->assertEquals(7, count($category->posts));
// remove some, add some records
unset($posts[4]);
unset($posts[5]);
$p = new Post();
$p->title = 'testtitle';
$this->assertSaveSuccess($p);
$posts[] = $p->id; // this one is mixed
$this->assertEquals(7, count($category->posts));
$category->posts = $posts;
$this->assertEquals(6, count($category->posts));
$category->save();
$this->assertEquals(6, count($category->posts));
// @todo test if additional relation data is touched
// end real test, checking untouched
$this->afterManyMany($un1, $un2);
$this->endTransaction($transactional);
}
/**
* test adding null values to MANY_MANY pk values
*
* @dataProvider manymanyData
*/
public function testManyManyNulls($postsAsPk, $modulo, $config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
if ($postsAsPk) { // first with pk data
$posts=$this->getPosts(10, true);
for($n=1;$n<10;$n++) {
if ($n % $modulo == 0) {
$posts[$n] = $posts[$n]->id;
}
}
} else {
$posts = $this->getPosts(10, true); // second with object data
}
$posts[2] = null;
$posts[5] = null;
list($un1, $un2) = $this->beforeManyMany();
// begin real test
$category = new Category();
$category->name = 'my new cat';
$this->assertEquals(array(), $category->posts);
$category->save();
$this->assertEquals(array(), $category->posts);
$category->save();
$this->assertEquals(0, count($category->posts));
$category->posts = $posts;
$this->assertEquals(9, count($category->posts));
$category->save();
$this->assertEquals(9, count($category->posts));
$category->refresh();
$this->assertEquals(7, count($category->posts));
$posts = $category->posts;
// set some records to null
$posts[1] = null;
$posts[3] = null;
$this->assertEquals(7, count($category->posts));
$category->posts = $posts;
$this->assertEquals(7, count($category->posts));
$category->save();
$this->assertEquals(7, count($category->posts));
$category->refresh();
$this->assertEquals(5, count($category->posts));
// end real test, checking untouched
$this->afterManyMany($un1, $un2);
$this->endTransaction($transactional);
}
/**
* @expectedException CDbException
* @dataProvider fkConfigurationProvider
*/
public function testManyManyException($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
$cat = new Category();
$cat->posts = 1;
$cat->save();
$this->endTransaction($transactional);
}
/**
* @expectedException CDbException
* @dataProvider fkConfigurationProvider
*/
public function testYiiException1($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
$cat = new Category();
$cat->broken = true;
$cat->posts = array();
$cat->save();
$this->endTransaction($transactional);
}
/**
* @expectedException CDbException
* @dataProvider fkConfigurationProvider
*/
public function testYiiException2($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
$cat = new Category();
$this->migration->dropRelationTable();
$cat->posts = array();
$cat->save();
$this->endTransaction($transactional);
}
public function testValidationBeforeSave()
{
$model = new Profile();
$model->disableOwnerRule = true;
$model->owner = new User();
$this->assertTrue($model->validate());
}
public function testValidationBeforeSaveFail()
{
$model = new Profile();
$model->owner = new User();
$this->assertFalse($model->validate());
}
/**
* Tests the transaction getter and setter
*/
public function testGetSetTransaction()
{
$behavior = new \EActiveRecordRelationBehavior();
$behavior->setTransaction($transaction=\Yii::app()->db->beginTransaction());
$this->assertInstanceOf('CDbTransaction', $transaction);
$this->assertSame($transaction, $behavior->getTransaction());
}
/**
* tests if withRelations() words correctly
*
* @dataProvider fkConfigurationProvider
*/
public function testSaveWithRelations($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
// create test data
// -- user
$jane = $this->getJane(10, true);
// -- profile
$profile = new Profile();
$profile->disableOwnerRule = true;
$profile->photo = "Jane's Photo";
$profile->website = "jane.doe.com";
$profile->save();
// -- posts
$posts = $this->getPosts(10);
// set profile and posts for jane
$jane->profile = $profile;
$jane->posts = $posts;
// save posts only
$jane->withRelations('posts')->save();
$jane->refresh();
$this->assertNull($jane->profile);
$this->assertEquals(9, count($jane->posts));
// set profile and posts for jane again
$jane->profile = $profile;
$jane->posts = $posts;
// save posts and profile
$jane->withRelations('posts', 'profile')->save();
$jane->refresh();
$this->assertEquals(9, count($jane->posts));
$this->assertEquals("jane.doe.com", $jane->profile->website);
$this->endTransaction($transactional);
}
/**
* tests if withoutRelations() words correctly
*
* @dataProvider fkConfigurationProvider
*/
public function testSaveWithoutRelations($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
// create test data
// -- user
$jane = $this->getJane(10, true);
// -- profile#1
$profile1 = new Profile();
$profile1->disableOwnerRule = true;
$profile1->photo = "Jane's Photo";
$profile1->website = "jane.doe.com";
$profile1->save();
// -- profile#2
$profile2 = new Profile();
$profile2->disableOwnerRule = true;
$profile2->photo = "Jane's Photo";
$profile2->website = "jane.doe.io";
$profile2->save();
// -- posts
$posts = $this->getPosts(10);
// set profile and posts for jane
$jane->profile = $profile1;
$jane->posts = $posts;
// save profile only
$jane->withoutRelations('posts')->save();
$jane->refresh();
$this->assertEquals(0, count($jane->posts));
$this->assertEquals("jane.doe.com", $jane->profile->website);
// set profile and posts for jane again
$jane->profile = $profile2;
$jane->posts = $posts;
// save posts only
$jane->withoutRelations('profile')->save();
$jane->refresh();
$this->assertEquals(9, count($jane->posts));
$this->assertEquals("jane.doe.com", $jane->profile->website);
$this->endTransaction($transactional);
}
/**
* tests if setting ignoreRelations works as expected
*
* @dataProvider fkConfigurationProvider
*/
public function testIgnoreRelations($config, $transactional)
{
$this->setConfig($config);
$this->startTransaction($transactional);
// set ignore relations for user
User::$testIgnoreRelations = array('profile');
// create test data
// -- user
$jane = $this->getJane(10, true);
// -- profile
$profile = new Profile();
$profile->disableOwnerRule = true;
$profile->photo = "Jane's Photo";
$profile->website = "jane.doe.com";
$profile->save();
// -- posts
$posts = $this->getPosts(10);
// set profile and posts for jane
$jane->profile = $profile;
$jane->posts = $posts;
// save profile only
$jane->save();
$jane->refresh();
$this->assertEquals(9, count($jane->posts));
$this->assertNull($jane->profile);
$this->endTransaction($transactional);
}
/**
* @param \CActiveRecord $ar
*/
public function assertSaveSuccess($ar)
{
$this->assertTrue($ar->save(), 'Expected saving of AR '.get_class($ar).' without errors: '.print_r($ar->getErrors(),true));
}
/**
* @param \CActiveRecord $ar
*/
public function assertSaveFailure($ar, $failedAttributes=null)
{
$this->assertFalse($ar->save(), 'Expected saving of AR '.get_class($ar).' to fail.');
if ($failedAttributes!==null)
$this->assertEquals($failedAttributes, array_keys($ar->getErrors()));
}
public static function assertEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
if ($expected instanceof \CActiveRecord) {
/** @var \CActiveRecord $expected */
self::assertNotNull($actual, 'Failed asserting that two ActiveRecords are equal. Second is null. '.$message);
self::assertTrue($expected->equals($actual), 'Failed asserting that two ActiveRecords are equal. '.$message);
} elseif ($actual instanceof \CActiveRecord) {
/** @var \CActiveRecord $actual */
self::assertNotNull($expected, 'Failed asserting that two ActiveRecords are equal. First is null. '.$message);
self::assertTrue($actual->equals($expected), 'Failed asserting that two ActiveRecords are equal. '.$message);
} else {
parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
}
}
/**
* @return User
*/
protected function getJohn($id=null, $save=false)
{
$john = new User();
if ($id)
$john->id = $id;
$john->username = 'John';
$john->password = '123456';
$john->email = 'john@doe.com';
if ($save)
$this->assertSaveSuccess($john);
return $john;
}
/**
* @return User
*/
protected function getJane($id=null, $save=false)
{
$jane = new User();
if ($id)
$jane->id = $id;
$jane->username = 'Jane';
$jane->password = '654321';
$jane->email = 'jane@doe.com';
if ($save)
$this->assertSaveSuccess($jane);
return $jane;
}
protected function getPosts($saveUntil=9, $addAuthor=false)
{
$posts = array();
for($n=1;$n<10;$n++) {
$p = new Post();
$p->title = 'title'.$n;
$p->content = 'content'.$n;
if ($n < $saveUntil) {
if ($addAuthor) {
$p->author = ($n % 2 == 0) ? $this->getJane(null, true) : $this->getJohn(null, true);
}
$this->assertSaveSuccess($p);
}
$posts[$n] = $p;
}
return $posts;
}
}
class EActiveRecordRelationBehaviorTestMigration extends \CDbMigration
{
private $relationTableDropped=true;
public function up()
{
ob_start();
// these are the tables from yii definitive guide
// http://www.yiiframework.com/doc/guide/1.1/en/database.arr
$this->createTable('tbl_user', array(
'id'=>'pk',
'username'=>'string',
'password'=>'string',
'email'=>'string',
));
$this->createTable('tbl_profile', array(
'owner_id'=>'pk',
'photo'=>'binary',
'website'=>'string',
'FOREIGN KEY (owner_id) REFERENCES tbl_user(id)',
));
$this->createTable('tbl_post', array(
'id'=>'pk',
'title'=>'string',
'content'=>'text',
'create_time'=>'timestamp',
'author_id'=>'integer',
'FOREIGN KEY (author_id) REFERENCES tbl_user(id)',
));
$this->createTable('tbl_post_category', array(
'post_id'=>'integer',
'category_id'=>'integer',
'post_order'=>'integer', // added this row to test additional attributes added to a relation
'PRIMARY KEY(post_id, category_id)',
'FOREIGN KEY (post_id) REFERENCES tbl_post(id)',
'FOREIGN KEY (category_id) REFERENCES tbl_category(id)',
));
$this->relationTableDropped=false;