DataObjectTest.php
53.1 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
<?php
/**
* @package framework
* @subpackage tests
*/
class DataObjectTest extends SapphireTest {
protected static $fixture_file = 'DataObjectTest.yml';
protected $extraDataObjects = array(
'DataObjectTest_Team',
'DataObjectTest_Fixture',
'DataObjectTest_SubTeam',
'OtherSubclassWithSameField',
'DataObjectTest_FieldlessTable',
'DataObjectTest_FieldlessSubTable',
'DataObjectTest_ValidatedObject',
'DataObjectTest_Player',
'DataObjectTest_TeamComment',
'DataObjectTest_ExtendedTeamComment'
);
public function testDb() {
$obj = new DataObjectTest_TeamComment();
$dbFields = $obj->db();
// Assert fields are included
$this->assertArrayHasKey('Name', $dbFields);
// Assert the base fields are excluded
$this->assertArrayNotHasKey('Created', $dbFields);
$this->assertArrayNotHasKey('LastEdited', $dbFields);
$this->assertArrayNotHasKey('ClassName', $dbFields);
$this->assertArrayNotHasKey('ID', $dbFields);
// Assert that the correct field type is returned when passing a field
$this->assertEquals('Varchar', $obj->db('Name'));
$this->assertEquals('Text', $obj->db('Comment'));
$obj = new DataObjectTest_ExtendedTeamComment();
$dbFields = $obj->db();
// Assert overloaded fields have correct data type
$this->assertEquals('HTMLText', $obj->db('Comment'));
$this->assertEquals('HTMLText', $dbFields['Comment'],
'Calls to DataObject::db without a field specified return correct data types');
// assertEquals doesn't verify the order of array elements, so access keys manually to check order:
// expected: array('Name' => 'Varchar', 'Comment' => 'HTMLText')
reset($dbFields);
$this->assertEquals('Name', key($dbFields), 'DataObject::db returns fields in correct order');
next($dbFields);
$this->assertEquals('Comment', key($dbFields), 'DataObject::db returns fields in correct order');
}
public function testValidObjectsForBaseFields() {
$obj = new DataObjectTest_ValidatedObject();
foreach (array('Created', 'LastEdited', 'ClassName', 'ID') as $field) {
$helper = $obj->dbObject($field);
$this->assertTrue(
($helper instanceof DBField),
"for {$field} expected helper to be DBField, but was " .
(is_object($helper) ? get_class($helper) : "null")
);
}
}
public function testDataIntegrityWhenTwoSubclassesHaveSameField() {
// Save data into DataObjectTest_SubTeam.SubclassDatabaseField
$obj = new DataObjectTest_SubTeam();
$obj->SubclassDatabaseField = "obj-SubTeam";
$obj->write();
// Change the class
$obj->ClassName = 'OtherSubclassWithSameField';
$obj->write();
$obj->flushCache();
// Re-fetch from the database and confirm that the data is sourced from
// OtherSubclassWithSameField.SubclassDatabaseField
$obj = DataObject::get_by_id('DataObjectTest_Team', $obj->ID);
$this->assertNull($obj->SubclassDatabaseField);
// Confirm that save the object in the other direction.
$obj->SubclassDatabaseField = 'obj-Other';
$obj->write();
$obj->ClassName = 'DataObjectTest_SubTeam';
$obj->write();
$obj->flushCache();
// If we restore the class, the old value has been lying dormant and will be available again.
// NOTE: This behaviour is volatile; we may change this in the future to clear fields that
// are no longer relevant when changing ClassName
$obj = DataObject::get_by_id('DataObjectTest_Team', $obj->ID);
$this->assertEquals('obj-SubTeam', $obj->SubclassDatabaseField);
}
/**
* Test deletion of DataObjects
* - Deleting using delete() on the DataObject
* - Deleting using DataObject::delete_by_id()
*/
public function testDelete() {
// Test deleting using delete() on the DataObject
// Get the first page
$obj = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$objID = $obj->ID;
// Check the page exists before deleting
$this->assertTrue(is_object($obj) && $obj->exists());
// Delete the page
$obj->delete();
// Check that page does not exist after deleting
$obj = DataObject::get_by_id('DataObjectTest_Player', $objID);
$this->assertTrue(!$obj || !$obj->exists());
// Test deleting using DataObject::delete_by_id()
// Get the second page
$obj = $this->objFromFixture('DataObjectTest_Player', 'captain2');
$objID = $obj->ID;
// Check the page exists before deleting
$this->assertTrue(is_object($obj) && $obj->exists());
// Delete the page
DataObject::delete_by_id('DataObjectTest_Player', $obj->ID);
// Check that page does not exist after deleting
$obj = DataObject::get_by_id('DataObjectTest_Player', $objID);
$this->assertTrue(!$obj || !$obj->exists());
}
/**
* Test methods that get DataObjects
* - DataObject::get()
* - All records of a DataObject
* - Filtering
* - Sorting
* - Joins
* - Limit
* - Container class
* - DataObject::get_by_id()
* - DataObject::get_one()
* - With and without caching
* - With and without ordering
*/
public function testGet() {
// Test getting all records of a DataObject
$comments = DataObject::get('DataObjectTest_TeamComment');
$this->assertEquals(3, $comments->Count());
// Test WHERE clause
$comments = DataObject::get('DataObjectTest_TeamComment', "\"Name\"='Bob'");
$this->assertEquals(1, $comments->Count());
foreach($comments as $comment) {
$this->assertEquals('Bob', $comment->Name);
}
// Test sorting
$comments = DataObject::get('DataObjectTest_TeamComment', '', "\"Name\" ASC");
$this->assertEquals(3, $comments->Count());
$this->assertEquals('Bob', $comments->First()->Name);
$comments = DataObject::get('DataObjectTest_TeamComment', '', "\"Name\" DESC");
$this->assertEquals(3, $comments->Count());
$this->assertEquals('Phil', $comments->First()->Name);
// Test limit
$comments = DataObject::get('DataObjectTest_TeamComment', '', "\"Name\" ASC", '', '1,2');
$this->assertEquals(2, $comments->Count());
$this->assertEquals('Joe', $comments->First()->Name);
$this->assertEquals('Phil', $comments->Last()->Name);
// Test get_by_id()
$captain1ID = $this->idFromFixture('DataObjectTest_Player', 'captain1');
$captain1 = DataObject::get_by_id('DataObjectTest_Player', $captain1ID);
$this->assertEquals('Captain', $captain1->FirstName);
// Test get_one() without caching
$comment1 = DataObject::get_one('DataObjectTest_TeamComment', "\"Name\" = 'Joe'", false);
$comment1->Comment = "Something Else";
$comment2 = DataObject::get_one('DataObjectTest_TeamComment', "\"Name\" = 'Joe'", false);
$this->assertNotEquals($comment1->Comment, $comment2->Comment);
// Test get_one() with caching
$comment1 = DataObject::get_one('DataObjectTest_TeamComment', "\"Name\" = 'Bob'", true);
$comment1->Comment = "Something Else";
$comment2 = DataObject::get_one('DataObjectTest_TeamComment', "\"Name\" = 'Bob'", true);
$this->assertEquals((string)$comment1->Comment, (string)$comment2->Comment);
// Test get_one() with order by without caching
$comment = DataObject::get_one('DataObjectTest_TeamComment', '', false, "\"Name\" ASC");
$this->assertEquals('Bob', $comment->Name);
$comment = DataObject::get_one('DataObjectTest_TeamComment', '', false, "\"Name\" DESC");
$this->assertEquals('Phil', $comment->Name);
// Test get_one() with order by with caching
$comment = DataObject::get_one('DataObjectTest_TeamComment', '', true, '"Name" ASC');
$this->assertEquals('Bob', $comment->Name);
$comment = DataObject::get_one('DataObjectTest_TeamComment', '', true, '"Name" DESC');
$this->assertEquals('Phil', $comment->Name);
// Test get_one() with bad case on the classname
$subteam1 = DataObject::get_one('dataobjecttest_subteam', "\"Title\" = 'Subteam 1'", true);
$this->assertEquals($subteam1->Title, "Subteam 1");
}
public function testGetSubclassFields() {
/* Test that fields / has_one relations from the parent table and the subclass tables are extracted */
$captain1 = $this->objFromFixture("DataObjectTest_Player", "captain1");
// Base field
$this->assertEquals('Captain', $captain1->FirstName);
// Subclass field
$this->assertEquals('007', $captain1->ShirtNumber);
// Subclass has_one relation
$this->assertEquals($this->idFromFixture('DataObjectTest_Team', 'team1'), $captain1->FavouriteTeamID);
}
public function testGetRelationClass() {
$obj = new DataObjectTest_Player();
$this->assertEquals(singleton('DataObjectTest_Player')->getRelationClass('FavouriteTeam'),
'DataObjectTest_Team', 'has_one is properly inspected');
$this->assertEquals(singleton('DataObjectTest_Company')->getRelationClass('CurrentStaff'),
'DataObjectTest_Staff', 'has_many is properly inspected');
$this->assertEquals(singleton('DataObjectTest_Team')->getRelationClass('Players'), 'DataObjectTest_Player',
'many_many is properly inspected');
$this->assertEquals(singleton('DataObjectTest_Player')->getRelationClass('Teams'), 'DataObjectTest_Team',
'belongs_many_many is properly inspected');
$this->assertEquals(singleton('DataObjectTest_CEO')->getRelationClass('Company'), 'DataObjectTest_Company',
'belongs_to is properly inspected');
}
public function testGetHasOneRelations() {
$captain1 = $this->objFromFixture("DataObjectTest_Player", "captain1");
/* There will be a field called (relname)ID that contains the ID of the object linked to via the
* has_one relation */
$this->assertEquals($this->idFromFixture('DataObjectTest_Team', 'team1'), $captain1->FavouriteTeamID);
/* There will be a method called $obj->relname() that returns the object itself */
$this->assertEquals($this->idFromFixture('DataObjectTest_Team', 'team1'), $captain1->FavouriteTeam()->ID);
}
public function testLimitAndCount() {
$players = DataObject::get("DataObjectTest_Player");
// There's 4 records in total
$this->assertEquals(4, $players->count());
// Testing "##, ##" syntax
$this->assertEquals(4, $players->limit(20)->count());
$this->assertEquals(4, $players->limit(20, 0)->count());
$this->assertEquals(0, $players->limit(20, 20)->count());
$this->assertEquals(2, $players->limit(2, 0)->count());
$this->assertEquals(1, $players->limit(5, 3)->count());
}
/**
* Test writing of database columns which don't correlate to a DBField,
* e.g. all relation fields on has_one/has_many like "ParentID".
*
*/
public function testWritePropertyWithoutDBField() {
$obj = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$obj->FavouriteTeamID = 99;
$obj->write();
// reload the page from the database
$savedObj = DataObject::get_by_id('DataObjectTest_Player', $obj->ID);
$this->assertTrue($savedObj->FavouriteTeamID == 99);
}
/**
* Test has many relationships
* - Test getComponents() gets the ComponentSet of the other side of the relation
* - Test the IDs on the DataObjects are set correctly
*/
public function testHasManyRelationships() {
$team1 = $this->objFromFixture('DataObjectTest_Team', 'team1');
// Test getComponents() gets the ComponentSet of the other side of the relation
$this->assertTrue($team1->Comments()->Count() == 2);
// Test the IDs on the DataObjects are set correctly
foreach($team1->Comments() as $comment) {
$this->assertEquals($team1->ID, $comment->TeamID);
}
// Test that we can add and remove items that already exist in the database
$newComment = new DataObjectTest_TeamComment();
$newComment->Name = "Automated commenter";
$newComment->Comment = "This is a new comment";
$newComment->write();
$team1->Comments()->add($newComment);
$this->assertEquals($team1->ID, $newComment->TeamID);
$comment1 = $this->objFromFixture('DataObjectTest_TeamComment', 'comment1');
$comment2 = $this->objFromFixture('DataObjectTest_TeamComment', 'comment2');
$team1->Comments()->remove($comment2);
$team1CommentIDs = $team1->Comments()->sort('ID')->column('ID');
$this->assertEquals(array($comment1->ID, $newComment->ID), $team1CommentIDs);
// Test that removing an item from a list doesn't remove it from the same
// relation belonging to a different object
$team1 = $this->objFromFixture('DataObjectTest_Team', 'team1');
$team2 = $this->objFromFixture('DataObjectTest_Team', 'team2');
$team2->Comments()->remove($comment1);
$team1CommentIDs = $team1->Comments()->sort('ID')->column('ID');
$this->assertEquals(array($comment1->ID, $newComment->ID), $team1CommentIDs);
}
public function testHasOneRelationship() {
$team1 = $this->objFromFixture('DataObjectTest_Team', 'team1');
$player1 = $this->objFromFixture('DataObjectTest_Player', 'player1');
// Add a captain to team 1
$team1->setField('CaptainID', $player1->ID);
$team1->write();
$this->assertEquals($player1->ID, $team1->Captain()->ID,
'The captain exists for team 1');
$this->assertEquals($player1->ID, $team1->getComponent('Captain')->ID,
'The captain exists through the component getter');
$this->assertEquals($team1->Captain()->FirstName, 'Player 1',
'Player 1 is the captain');
$this->assertEquals($team1->getComponent('Captain')->FirstName, 'Player 1',
'Player 1 is the captain');
}
/**
* @todo Extend type change tests (e.g. '0'==NULL)
*/
public function testChangedFields() {
$obj = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$obj->FirstName = 'Captain-changed';
$obj->IsRetired = true;
$this->assertEquals(
$obj->getChangedFields(false, 1),
array(
'FirstName' => array(
'before' => 'Captain',
'after' => 'Captain-changed',
'level' => 2
),
'IsRetired' => array(
'before' => 1,
'after' => true,
'level' => 1
)
),
'Changed fields are correctly detected with strict type changes (level=1)'
);
$this->assertEquals(
$obj->getChangedFields(false, 2),
array(
'FirstName' => array(
'before'=>'Captain',
'after'=>'Captain-changed',
'level' => 2
)
),
'Changed fields are correctly detected while ignoring type changes (level=2)'
);
$newObj = new DataObjectTest_Player();
$newObj->FirstName = "New Player";
$this->assertEquals(
$newObj->getChangedFields(false, 2),
array(
'FirstName' => array(
'before' => null,
'after' => 'New Player',
'level' => 2
)
),
'Initialised fields are correctly detected as full changes'
);
}
public function testIsChanged() {
$obj = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$obj->FirstName = 'Captain-changed';
$obj->IsRetired = true; // type change only, database stores "1"
$this->assertTrue($obj->isChanged('FirstName', 1));
$this->assertTrue($obj->isChanged('FirstName', 2));
$this->assertTrue($obj->isChanged('IsRetired', 1));
$this->assertFalse($obj->isChanged('IsRetired', 2));
$this->assertFalse($obj->isChanged('Email', 1), 'Doesnt change mark unchanged property');
$this->assertFalse($obj->isChanged('Email', 2), 'Doesnt change mark unchanged property');
$newObj = new DataObjectTest_Player();
$newObj->FirstName = "New Player";
$this->assertTrue($newObj->isChanged('FirstName', 1));
$this->assertTrue($newObj->isChanged('FirstName', 2));
$this->assertFalse($newObj->isChanged('Email', 1));
$this->assertFalse($newObj->isChanged('Email', 2));
$newObj->write();
$this->assertFalse($newObj->isChanged('FirstName', 1));
$this->assertFalse($newObj->isChanged('FirstName', 2));
$this->assertFalse($newObj->isChanged('Email', 1));
$this->assertFalse($newObj->isChanged('Email', 2));
$obj = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$obj->FirstName = null;
$this->assertTrue($obj->isChanged('FirstName', 1));
$this->assertTrue($obj->isChanged('FirstName', 2));
/* Test when there's not field provided */
$obj = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$obj->FirstName = "New Player";
$this->assertTrue($obj->isChanged());
$obj->write();
$this->assertFalse($obj->isChanged());
}
public function testRandomSort() {
/* If we perform the same regularly sorted query twice, it should return the same results */
$itemsA = DataObject::get("DataObjectTest_TeamComment", "", "ID");
foreach($itemsA as $item) $keysA[] = $item->ID;
$itemsB = DataObject::get("DataObjectTest_TeamComment", "", "ID");
foreach($itemsB as $item) $keysB[] = $item->ID;
/* Test when there's not field provided */
$obj = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$obj->FirstName = "New Player";
$this->assertTrue($obj->isChanged());
$obj->write();
$this->assertFalse($obj->isChanged());
/* If we perform the same random query twice, it shouldn't return the same results */
$itemsA = DataObject::get("DataObjectTest_TeamComment", "", DB::getConn()->random());
$itemsB = DataObject::get("DataObjectTest_TeamComment", "", DB::getConn()->random());
$itemsC = DataObject::get("DataObjectTest_TeamComment", "", DB::getConn()->random());
$itemsD = DataObject::get("DataObjectTest_TeamComment", "", DB::getConn()->random());
foreach($itemsA as $item) $keysA[] = $item->ID;
foreach($itemsB as $item) $keysB[] = $item->ID;
foreach($itemsC as $item) $keysC[] = $item->ID;
foreach($itemsD as $item) $keysD[] = $item->ID;
// These shouldn't all be the same (run it 4 times to minimise chance of an accidental collision)
// There's about a 1 in a billion chance of an accidental collision
$this->assertTrue($keysA != $keysB || $keysB != $keysC || $keysC != $keysD);
}
public function testWriteSavesToHasOneRelations() {
/* DataObject::write() should save to a has_one relationship if you set a field called (relname)ID */
$team = new DataObjectTest_Team();
$captainID = $this->idFromFixture('DataObjectTest_Player', 'player1');
$team->CaptainID = $captainID;
$team->write();
$this->assertEquals($captainID,
DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value());
/* After giving it a value, you should also be able to set it back to null */
$team->CaptainID = '';
$team->write();
$this->assertEquals(0,
DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value());
/* You should also be able to save a blank to it when it's first created */
$team = new DataObjectTest_Team();
$team->CaptainID = '';
$team->write();
$this->assertEquals(0,
DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value());
/* Ditto for existing records without a value */
$existingTeam = $this->objFromFixture('DataObjectTest_Team', 'team1');
$existingTeam->CaptainID = '';
$existingTeam->write();
$this->assertEquals(0,
DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $existingTeam->ID")->value());
}
public function testCanAccessHasOneObjectsAsMethods() {
/* If you have a has_one relation 'Captain' on $obj, and you set the $obj->CaptainID = (ID), then the
* object itself should be accessible as $obj->Captain() */
$team = $this->objFromFixture('DataObjectTest_Team', 'team1');
$captainID = $this->idFromFixture('DataObjectTest_Player', 'captain1');
$team->CaptainID = $captainID;
$this->assertNotNull($team->Captain());
$this->assertEquals($captainID, $team->Captain()->ID);
}
public function testFieldNamesThatMatchMethodNamesWork() {
/* Check that a field name that corresponds to a method on DataObject will still work */
$obj = new DataObjectTest_Fixture();
$obj->Data = "value1";
$obj->DbObject = "value2";
$obj->Duplicate = "value3";
$obj->write();
$this->assertNotNull($obj->ID);
$this->assertEquals('value1',
DB::query("SELECT \"Data\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value());
$this->assertEquals('value2',
DB::query("SELECT \"DbObject\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value());
$this->assertEquals('value3',
DB::query("SELECT \"Duplicate\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value());
}
/**
* @todo Re-enable all test cases for field existence after behaviour has been fixed
*/
public function testFieldExistence() {
$teamInstance = $this->objFromFixture('DataObjectTest_Team', 'team1');
$teamSingleton = singleton('DataObjectTest_Team');
$subteamInstance = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1');
$subteamSingleton = singleton('DataObjectTest_SubTeam');
/* hasField() singleton checks */
$this->assertTrue($teamSingleton->hasField('ID'),
'hasField() finds built-in fields in singletons');
$this->assertTrue($teamSingleton->hasField('Title'),
'hasField() finds custom fields in singletons');
/* hasField() instance checks */
$this->assertFalse($teamInstance->hasField('NonExistingField'),
'hasField() doesnt find non-existing fields in instances');
$this->assertTrue($teamInstance->hasField('ID'),
'hasField() finds built-in fields in instances');
$this->assertTrue($teamInstance->hasField('Created'),
'hasField() finds built-in fields in instances');
$this->assertTrue($teamInstance->hasField('DatabaseField'),
'hasField() finds custom fields in instances');
//$this->assertFalse($teamInstance->hasField('SubclassDatabaseField'),
//'hasField() doesnt find subclass fields in parentclass instances');
$this->assertTrue($teamInstance->hasField('DynamicField'),
'hasField() finds dynamic getters in instances');
$this->assertTrue($teamInstance->hasField('HasOneRelationshipID'),
'hasField() finds foreign keys in instances');
$this->assertTrue($teamInstance->hasField('ExtendedDatabaseField'),
'hasField() finds extended fields in instances');
$this->assertTrue($teamInstance->hasField('ExtendedHasOneRelationshipID'),
'hasField() finds extended foreign keys in instances');
//$this->assertTrue($teamInstance->hasField('ExtendedDynamicField'),
//'hasField() includes extended dynamic getters in instances');
/* hasField() subclass checks */
$this->assertTrue($subteamInstance->hasField('ID'),
'hasField() finds built-in fields in subclass instances');
$this->assertTrue($subteamInstance->hasField('Created'),
'hasField() finds built-in fields in subclass instances');
$this->assertTrue($subteamInstance->hasField('DatabaseField'),
'hasField() finds custom fields in subclass instances');
$this->assertTrue($subteamInstance->hasField('SubclassDatabaseField'),
'hasField() finds custom fields in subclass instances');
$this->assertTrue($subteamInstance->hasField('DynamicField'),
'hasField() finds dynamic getters in subclass instances');
$this->assertTrue($subteamInstance->hasField('HasOneRelationshipID'),
'hasField() finds foreign keys in subclass instances');
$this->assertTrue($subteamInstance->hasField('ExtendedDatabaseField'),
'hasField() finds extended fields in subclass instances');
$this->assertTrue($subteamInstance->hasField('ExtendedHasOneRelationshipID'),
'hasField() finds extended foreign keys in subclass instances');
/* hasDatabaseField() singleton checks */
//$this->assertTrue($teamSingleton->hasDatabaseField('ID'),
//'hasDatabaseField() finds built-in fields in singletons');
$this->assertTrue($teamSingleton->hasDatabaseField('Title'),
'hasDatabaseField() finds custom fields in singletons');
/* hasDatabaseField() instance checks */
$this->assertFalse($teamInstance->hasDatabaseField('NonExistingField'),
'hasDatabaseField() doesnt find non-existing fields in instances');
//$this->assertTrue($teamInstance->hasDatabaseField('ID'),
//'hasDatabaseField() finds built-in fields in instances');
$this->assertTrue($teamInstance->hasDatabaseField('Created'),
'hasDatabaseField() finds built-in fields in instances');
$this->assertTrue($teamInstance->hasDatabaseField('DatabaseField'),
'hasDatabaseField() finds custom fields in instances');
$this->assertFalse($teamInstance->hasDatabaseField('SubclassDatabaseField'),
'hasDatabaseField() doesnt find subclass fields in parentclass instances');
//$this->assertFalse($teamInstance->hasDatabaseField('DynamicField'),
//'hasDatabaseField() doesnt dynamic getters in instances');
$this->assertTrue($teamInstance->hasDatabaseField('HasOneRelationshipID'),
'hasDatabaseField() finds foreign keys in instances');
$this->assertTrue($teamInstance->hasDatabaseField('ExtendedDatabaseField'),
'hasDatabaseField() finds extended fields in instances');
$this->assertTrue($teamInstance->hasDatabaseField('ExtendedHasOneRelationshipID'),
'hasDatabaseField() finds extended foreign keys in instances');
$this->assertFalse($teamInstance->hasDatabaseField('ExtendedDynamicField'),
'hasDatabaseField() doesnt include extended dynamic getters in instances');
/* hasDatabaseField() subclass checks */
$this->assertTrue($subteamInstance->hasField('DatabaseField'),
'hasField() finds custom fields in subclass instances');
$this->assertTrue($subteamInstance->hasField('SubclassDatabaseField'),
'hasField() finds custom fields in subclass instances');
}
/**
* @todo Re-enable all test cases for field inheritance aggregation after behaviour has been fixed
*/
public function testFieldInheritance() {
$teamInstance = $this->objFromFixture('DataObjectTest_Team', 'team1');
$subteamInstance = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1');
$this->assertEquals(
array_keys($teamInstance->inheritedDatabaseFields()),
array(
//'ID',
//'ClassName',
//'Created',
//'LastEdited',
'Title',
'DatabaseField',
'ExtendedDatabaseField',
'CaptainID',
'HasOneRelationshipID',
'ExtendedHasOneRelationshipID'
),
'inheritedDatabaseFields() contains all fields defined on instance: base, extended and foreign keys'
);
$this->assertEquals(
array_keys(DataObject::database_fields('DataObjectTest_Team')),
array(
//'ID',
'ClassName',
'Created',
'LastEdited',
'Title',
'DatabaseField',
'ExtendedDatabaseField',
'CaptainID',
'HasOneRelationshipID',
'ExtendedHasOneRelationshipID'
),
'databaseFields() contains only fields defined on instance, including base, extended and foreign keys'
);
$this->assertEquals(
array_keys($subteamInstance->inheritedDatabaseFields()),
array(
//'ID',
//'ClassName',
//'Created',
//'LastEdited',
'SubclassDatabaseField',
'ParentTeamID',
'Title',
'DatabaseField',
'ExtendedDatabaseField',
'CaptainID',
'HasOneRelationshipID',
'ExtendedHasOneRelationshipID',
),
'inheritedDatabaseFields() on subclass contains all fields, including base, extended and foreign keys'
);
$this->assertEquals(
array_keys(DataObject::database_fields('DataObjectTest_SubTeam')),
array(
'SubclassDatabaseField',
'ParentTeamID',
),
'databaseFields() on subclass contains only fields defined on instance'
);
}
public function testSearchableFields() {
$player = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$fields = $player->searchableFields();
$this->assertArrayHasKey(
'IsRetired',
$fields,
'Fields defined by $searchable_fields static are correctly detected'
);
$this->assertArrayHasKey(
'ShirtNumber',
$fields,
'Fields defined by $searchable_fields static are correctly detected'
);
$team = $this->objFromFixture('DataObjectTest_Team', 'team1');
$fields = $team->searchableFields();
$this->assertArrayHasKey(
'Title',
$fields,
'Fields can be inherited from the $summary_fields static, including methods called on fields'
);
$this->assertArrayHasKey(
'Captain.ShirtNumber',
$fields,
'Fields on related objects can be inherited from the $summary_fields static'
);
$this->assertArrayHasKey(
'Captain.FavouriteTeam.Title',
$fields,
'Fields on related objects can be inherited from the $summary_fields static'
);
$testObj = new DataObjectTest_Fixture();
$fields = $testObj->searchableFields();
$this->assertEmpty($fields);
}
public function testSummaryFieldsCustomLabels() {
$team = $this->objFromFixture('DataObjectTest_Team', 'team1');
$summaryFields = $team->summaryFields();
$this->assertEquals(
'Custom Title',
$summaryFields['Title'],
'Custom title is preserved'
);
$this->assertEquals(
'Captain\'s shirt number',
$summaryFields['Captain.ShirtNumber'],
'Custom title on relation is preserved'
);
}
public function testDataObjectUpdate() {
/* update() calls can use the dot syntax to reference has_one relations and other methods that return
* objects */
$team1 = $this->objFromFixture('DataObjectTest_Team', 'team1');
$team1->CaptainID = $this->idFromFixture('DataObjectTest_Player', 'captain1');
$team1->update(array(
'DatabaseField' => 'Something',
'Captain.FirstName' => 'Jim',
'Captain.Email' => 'jim@example.com',
'Captain.FavouriteTeam.Title' => 'New and improved team 1',
));
/* Test the simple case of updating fields on the object itself */
$this->assertEquals('Something', $team1->DatabaseField);
/* Setting Captain.Email and Captain.FirstName will have updated DataObjectTest_Captain.captain1 in
* the database. Although update() doesn't usually write, it does write related records automatically. */
$captain1 = $this->objFromFixture('DataObjectTest_Player', 'captain1');
$this->assertEquals('Jim', $captain1->FirstName);
$this->assertEquals('jim@example.com', $captain1->Email);
/* Jim's favourite team is team 1; we need to reload the object to the the change that setting Captain.
* FavouriteTeam.Title made */
$reloadedTeam1 = $this->objFromFixture('DataObjectTest_Team', 'team1');
$this->assertEquals('New and improved team 1', $reloadedTeam1->Title);
}
public function testDataObjectUpdateNew() {
/* update() calls can use the dot syntax to reference has_one relations and other methods that return
* objects */
$team1 = $this->objFromFixture('DataObjectTest_Team', 'team1');
$team1->CaptainID = 0;
$team1->update(array(
'Captain.FirstName' => 'Jim',
'Captain.FavouriteTeam.Title' => 'New and improved team 1',
));
/* Test that the captain ID has been updated */
$this->assertGreaterThan(0, $team1->CaptainID);
/* Fetch the newly created captain */
$captain1 = DataObjectTest_Player::get()->byID($team1->CaptainID);
$this->assertEquals('Jim', $captain1->FirstName);
/* Grab the favourite team and make sure it has the correct values */
$reloadedTeam1 = $captain1->FavouriteTeam();
$this->assertEquals($reloadedTeam1->ID, $captain1->FavouriteTeamID);
$this->assertEquals('New and improved team 1', $reloadedTeam1->Title);
}
public function testWritingInvalidDataObjectThrowsException() {
$validatedObject = new DataObjectTest_ValidatedObject();
$this->setExpectedException('ValidationException');
$validatedObject->write();
}
public function testWritingValidDataObjectDoesntThrowException() {
$validatedObject = new DataObjectTest_ValidatedObject();
$validatedObject->Name = "Mr. Jones";
$validatedObject->write();
$this->assertTrue($validatedObject->isInDB(), "Validated object was not saved to database");
}
public function testSubclassCreation() {
/* Creating a new object of a subclass should set the ClassName field correctly */
$obj = new DataObjectTest_SubTeam();
$obj->write();
$this->assertEquals("DataObjectTest_SubTeam",
DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value());
}
public function testForceInsert() {
/* If you set an ID on an object and pass forceInsert = true, then the object should be correctly created */
$conn = DB::getConn();
if(method_exists($conn, 'allowPrimaryKeyEditing')) $conn->allowPrimaryKeyEditing('DataObjectTest_Team', true);
$obj = new DataObjectTest_SubTeam();
$obj->ID = 1001;
$obj->Title = 'asdfasdf';
$obj->SubclassDatabaseField = 'asdfasdf';
$obj->write(false, true);
if(method_exists($conn, 'allowPrimaryKeyEditing')) $conn->allowPrimaryKeyEditing('DataObjectTest_Team', false);
$this->assertEquals("DataObjectTest_SubTeam",
DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value());
/* Check that it actually saves to the database with the correct ID */
$this->assertEquals("1001", DB::query(
"SELECT \"ID\" FROM \"DataObjectTest_SubTeam\" WHERE \"SubclassDatabaseField\" = 'asdfasdf'")->value());
$this->assertEquals("1001",
DB::query("SELECT \"ID\" FROM \"DataObjectTest_Team\" WHERE \"Title\" = 'asdfasdf'")->value());
}
public function TestHasOwnTable() {
/* Test DataObject::has_own_table() returns true if the object has $has_one or $db values */
$this->assertTrue(DataObject::has_own_table("DataObjectTest_Player"));
$this->assertTrue(DataObject::has_own_table("DataObjectTest_Team"));
$this->assertTrue(DataObject::has_own_table("DataObjectTest_Fixture"));
/* Root DataObject that always have a table, even if they lack both $db and $has_one */
$this->assertTrue(DataObject::has_own_table("DataObjectTest_FieldlessTable"));
/* Subclasses without $db or $has_one don't have a table */
$this->assertFalse(DataObject::has_own_table("DataObjectTest_FieldlessSubTable"));
/* Return false if you don't pass it a subclass of DataObject */
$this->assertFalse(DataObject::has_own_table("DataObject"));
$this->assertFalse(DataObject::has_own_table("ViewableData"));
$this->assertFalse(DataObject::has_own_table("ThisIsntADataObject"));
}
public function testMerge() {
// test right merge of subclasses
$left = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1');
$right = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam2_with_player_relation');
$leftOrigID = $left->ID;
$left->merge($right, 'right', false, false);
$this->assertEquals(
$left->Title,
'Subteam 2',
'merge() with "right" priority overwrites fields with existing values on subclasses'
);
$this->assertEquals(
$left->ID,
$leftOrigID,
'merge() with "right" priority doesnt overwrite database ID'
);
// test overwriteWithEmpty flag on existing left values
$left = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam2_with_player_relation');
$right = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam3_with_empty_fields');
$left->merge($right, 'right', false, true);
$this->assertEquals(
$left->Title,
'Subteam 3',
'merge() with $overwriteWithEmpty overwrites non-empty fields on left object'
);
// test overwriteWithEmpty flag on empty left values
$left = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1');
// $SubclassDatabaseField is empty on here
$right = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam2_with_player_relation');
$left->merge($right, 'right', false, true);
$this->assertEquals(
$left->SubclassDatabaseField,
NULL,
'merge() with $overwriteWithEmpty overwrites empty fields on left object'
);
// @todo test "left" priority flag
// @todo test includeRelations flag
// @todo test includeRelations in combination with overwriteWithEmpty
// @todo test has_one relations
// @todo test has_many and many_many relations
}
public function testPopulateDefaults() {
$obj = new DataObjectTest_Fixture();
$this->assertEquals(
$obj->MyFieldWithDefault,
'Default Value',
'Defaults are populated for in-memory object from $defaults array'
);
$this->assertEquals(
$obj->MyFieldWithAltDefault,
'Default Value',
'Defaults are populated from overloaded populateDefaults() method'
);
}
public function testNewClassInstance() {
$dataObject = $this->objFromFixture('DataObjectTest_Team', 'team1');
$changedDO = $dataObject->newClassInstance('DataObjectTest_SubTeam');
$changedFields = $changedDO->getChangedFields();
// Don't write the record, it will reset changed fields
$this->assertInstanceOf('DataObjectTest_SubTeam', $changedDO);
$this->assertEquals($changedDO->ClassName, 'DataObjectTest_SubTeam');
$this->assertContains('ClassName', array_keys($changedFields));
$this->assertEquals($changedFields['ClassName']['before'], 'DataObjectTest_Team');
$this->assertEquals($changedFields['ClassName']['after'], 'DataObjectTest_SubTeam');
$changedDO->write();
$this->assertInstanceOf('DataObjectTest_SubTeam', $changedDO);
$this->assertEquals($changedDO->ClassName, 'DataObjectTest_SubTeam');
}
public function testManyManyExtraFields() {
$player = $this->objFromFixture('DataObjectTest_Player', 'player1');
$team = $this->objFromFixture('DataObjectTest_Team', 'team1');
// Get all extra fields
$teamExtraFields = $team->many_many_extraFields();
$this->assertEquals(array(
'Players' => array('Position' => 'Varchar(100)')
), $teamExtraFields);
// Ensure fields from parent classes are included
$subTeam = singleton('DataObjectTest_SubTeam');
$teamExtraFields = $subTeam->many_many_extraFields();
$this->assertEquals(array(
'Players' => array('Position' => 'Varchar(100)'),
'FormerPlayers' => array('Position' => 'Varchar(100)')
), $teamExtraFields);
// Extra fields are immediately available on the Team class (defined in $many_many_extraFields)
$teamExtraFields = $team->many_many_extraFields('Players');
$this->assertEquals($teamExtraFields, array(
'Position' => 'Varchar(100)'
));
// We'll have to go through the relation to get the extra fields on Player
$playerExtraFields = $player->many_many_extraFields('Teams');
$this->assertEquals($playerExtraFields, array(
'Position' => 'Varchar(100)'
));
// Iterate through a many-many relationship and confirm that extra fields are included
$newTeam = new DataObjectTest_Team();
$newTeam->Title = "New team";
$newTeam->write();
$newTeamID = $newTeam->ID;
$newPlayer = new DataObjectTest_Player();
$newPlayer->FirstName = "Sam";
$newPlayer->Surname = "Minnee";
$newPlayer->write();
// The idea of Sam as a prop is essentially humourous.
$newTeam->Players()->add($newPlayer, array("Position" => "Prop"));
// Requery and uncache everything
$newTeam->flushCache();
$newTeam = DataObject::get_by_id('DataObjectTest_Team', $newTeamID);
// Check that the Position many_many_extraField is extracted.
$player = $newTeam->Players()->First();
$this->assertEquals('Sam', $player->FirstName);
$this->assertEquals("Prop", $player->Position);
// Check that ordering a many-many relation by an aggregate column doesn't fail
$player = $this->objFromFixture('DataObjectTest_Player', 'player2');
$player->Teams("", "count(DISTINCT \"DataObjectTest_Team_Players\".\"DataObjectTest_PlayerID\") DESC");
}
/**
* Check that the queries generated for many-many relation queries can have unlimitedRowCount
* called on them.
*/
public function testManyManyUnlimitedRowCount() {
$player = $this->objFromFixture('DataObjectTest_Player', 'player2');
// TODO: What's going on here?
$this->assertEquals(2, $player->Teams()->dataQuery()->query()->unlimitedRowCount());
}
/**
* Tests that singular_name() generates sensible defaults.
*/
public function testSingularName() {
$assertions = array(
'DataObjectTest_Player' => 'Data Object Test Player',
'DataObjectTest_Team' => 'Data Object Test Team',
'DataObjectTest_Fixture' => 'Data Object Test Fixture'
);
foreach($assertions as $class => $expectedSingularName) {
$this->assertEquals(
$expectedSingularName,
singleton($class)->singular_name(),
"Assert that the singular_name for '$class' is correct."
);
}
}
/**
* Tests that plural_name() generates sensible defaults.
*/
public function testPluralName() {
$assertions = array(
'DataObjectTest_Player' => 'Data Object Test Players',
'DataObjectTest_Team' => 'Data Object Test Teams',
'DataObjectTest_Fixture' => 'Data Object Test Fixtures'
);
foreach($assertions as $class => $expectedPluralName) {
$this->assertEquals(
$expectedPluralName,
singleton($class)->plural_name(),
"Assert that the plural_name for '$class' is correct."
);
}
}
public function testHasDatabaseField() {
$team = singleton('DataObjectTest_Team');
$subteam = singleton('DataObjectTest_SubTeam');
$this->assertTrue(
$team->hasDatabaseField('Title'),
"hasOwnDatabaseField() works with \$db fields"
);
$this->assertTrue(
$team->hasDatabaseField('CaptainID'),
"hasOwnDatabaseField() works with \$has_one fields"
);
$this->assertFalse(
$team->hasDatabaseField('NonExistentField'),
"hasOwnDatabaseField() doesn't detect non-existend fields"
);
$this->assertTrue(
$team->hasDatabaseField('ExtendedDatabaseField'),
"hasOwnDatabaseField() works with extended fields"
);
$this->assertFalse(
$team->hasDatabaseField('SubclassDatabaseField'),
"hasOwnDatabaseField() doesn't pick up fields in subclasses on parent class"
);
$this->assertTrue(
$subteam->hasDatabaseField('SubclassDatabaseField'),
"hasOwnDatabaseField() picks up fields in subclasses"
);
}
public function testFieldTypes() {
$obj = new DataObjectTest_Fixture();
$obj->DateField = '1988-01-02';
$obj->DatetimeField = '1988-03-04 06:30';
$obj->write();
$obj->flushCache();
$obj = DataObject::get_by_id('DataObjectTest_Fixture', $obj->ID);
$this->assertEquals('1988-01-02', $obj->DateField);
$this->assertEquals('1988-03-04 06:30:00', $obj->DatetimeField);
}
public function testTwoSubclassesWithTheSameFieldNameWork() {
// Create two objects of different subclasses, setting the values of fields that are
// defined separately in each subclass
$obj1 = new DataObjectTest_SubTeam();
$obj1->SubclassDatabaseField = "obj1";
$obj2 = new OtherSubclassWithSameField();
$obj2->SubclassDatabaseField = "obj2";
// Write them to the database
$obj1->write();
$obj2->write();
// Check that the values of those fields are properly read from the database
$values = DataObject::get("DataObjectTest_Team", "\"DataObjectTest_Team\".\"ID\" IN
($obj1->ID, $obj2->ID)")->column("SubclassDatabaseField");
$this->assertEquals(array_intersect($values, array('obj1', 'obj2')), $values);
}
public function testClassNameSetForNewObjects() {
$d = new DataObjectTest_Player();
$this->assertEquals('DataObjectTest_Player', $d->ClassName);
}
public function testHasValue() {
$team = new DataObjectTest_Team();
$this->assertFalse($team->hasValue('Title', null, false));
$this->assertFalse($team->hasValue('DatabaseField', null, false));
$team->Title = 'hasValue';
$this->assertTrue($team->hasValue('Title', null, false));
$this->assertFalse($team->hasValue('DatabaseField', null, false));
$team->DatabaseField = '<p></p>';
$this->assertTrue($team->hasValue('Title', null, false));
$this->assertFalse (
$team->hasValue('DatabaseField', null, false),
'Test that a blank paragraph on a HTML field is not a valid value.'
);
$team->Title = '<p></p>';
$this->assertTrue (
$team->hasValue('Title', null, false),
'Test that an empty paragraph is a value for non-HTML fields.'
);
$team->DatabaseField = 'hasValue';
$this->assertTrue($team->hasValue('Title', null, false));
$this->assertTrue($team->hasValue('DatabaseField', null, false));
}
public function testHasMany() {
$company = new DataObjectTest_Company();
$this->assertEquals (
array (
'CurrentStaff' => 'DataObjectTest_Staff',
'PreviousStaff' => 'DataObjectTest_Staff'
),
$company->has_many(),
'has_many strips field name data by default.'
);
$this->assertEquals (
'DataObjectTest_Staff',
$company->has_many('CurrentStaff'),
'has_many strips field name data by default on single relationships.'
);
$this->assertEquals (
array (
'CurrentStaff' => 'DataObjectTest_Staff.CurrentCompany',
'PreviousStaff' => 'DataObjectTest_Staff.PreviousCompany'
),
$company->has_many(null, false),
'has_many returns field name data when $classOnly is false.'
);
$this->assertEquals (
'DataObjectTest_Staff.CurrentCompany',
$company->has_many('CurrentStaff', false),
'has_many returns field name data on single records when $classOnly is false.'
);
}
public function testGetRemoteJoinField() {
$company = new DataObjectTest_Company();
$this->assertEquals('CurrentCompanyID', $company->getRemoteJoinField('CurrentStaff'));
$this->assertEquals('PreviousCompanyID', $company->getRemoteJoinField('PreviousStaff'));
$ceo = new DataObjectTest_CEO();
$this->assertEquals('CEOID', $ceo->getRemoteJoinField('Company', 'belongs_to'));
$this->assertEquals('PreviousCEOID', $ceo->getRemoteJoinField('PreviousCompany', 'belongs_to'));
}
public function testBelongsTo() {
$company = new DataObjectTest_Company();
$ceo = new DataObjectTest_CEO();
$company->write();
$ceo->write();
$company->CEOID = $ceo->ID;
$company->write();
$this->assertEquals($company->ID, $ceo->Company()->ID, 'belongs_to returns the right results.');
$ceo = new DataObjectTest_CEO();
$ceo->write();
$this->assertTrue (
$ceo->Company() instanceof DataObjectTest_Company,
'DataObjects across belongs_to relations are automatically created.'
);
$this->assertEquals($ceo->ID, $ceo->Company()->CEOID, 'Remote IDs are automatically set.');
$ceo->write(false, false, false, true);
$this->assertTrue($ceo->Company()->isInDB(), 'write() writes belongs_to components to the database.');
$newCEO = DataObject::get_by_id('DataObjectTest_CEO', $ceo->ID);
$this->assertEquals (
$ceo->Company()->ID, $newCEO->Company()->ID, 'belongs_to can be retrieved from the database.'
);
}
/**
* @expectedException LogicException
*/
public function testInvalidate() {
$do = new DataObjectTest_Fixture();
$do->write();
$do->delete();
$do->delete(); // Prohibit invalid object manipulation
$do->write();
$do->duplicate();
}
public function testToMap() {
$obj = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1');
$map = $obj->toMap();
$this->assertArrayHasKey('ID', $map, 'Contains base fields');
$this->assertArrayHasKey('Title', $map, 'Contains fields from parent class');
$this->assertArrayHasKey('SubclassDatabaseField', $map, 'Contains fields from concrete class');
$this->assertEquals($obj->ID, $map['ID'],
'Contains values from base fields');
$this->assertEquals($obj->Title, $map['Title'],
'Contains values from parent class fields');
$this->assertEquals($obj->SubclassDatabaseField, $map['SubclassDatabaseField'],
'Contains values from concrete class fields');
$newObj = new DataObjectTest_SubTeam();
$this->assertArrayHasKey('Title', $map, 'Contains null fields');
}
public function testIsEmpty() {
$objEmpty = new DataObjectTest_Team();
$this->assertTrue($objEmpty->isEmpty(), 'New instance without populated defaults is empty');
$objEmpty->Title = '0'; //
$this->assertFalse($objEmpty->isEmpty(), 'Zero value in attribute considered non-empty');
}
public function testRelField() {
$captain = $this->objFromFixture('DataObjectTest_Player', 'captain1');
// Test traversal of a single has_one
$this->assertEquals("Team 1", $captain->relField('FavouriteTeam.Title'));
// Test direct field access
$this->assertEquals("Captain", $captain->relField('FirstName'));
$player = $this->objFromFixture('DataObjectTest_Player', 'player2');
// Test that we can traverse more than once, and that arbitrary methods are okay
$this->assertEquals("Team 1", $player->relField('Teams.First.Title'));
$newPlayer = new DataObjectTest_Player();
$this->assertNull($newPlayer->relField('Teams.First.Title'));
// Test that relField works on db field manipulations
$comment = $this->objFromFixture('DataObjectTest_TeamComment', 'comment3');
$this->assertEquals("PHIL IS A UNIQUE GUY, AND COMMENTS ON TEAM2" , $comment->relField('Comment.UpperCase'));
}
public function testRelObject() {
$captain = $this->objFromFixture('DataObjectTest_Player', 'captain1');
// Test traversal of a single has_one
$this->assertInstanceOf("Varchar", $captain->relObject('FavouriteTeam.Title'));
$this->assertEquals("Team 1", $captain->relObject('FavouriteTeam.Title')->getValue());
// Test direct field access
$this->assertInstanceOf("Boolean", $captain->relObject('IsRetired'));
$this->assertEquals(1, $captain->relObject('IsRetired')->getValue());
$player = $this->objFromFixture('DataObjectTest_Player', 'player2');
// Test that we can traverse more than once, and that arbitrary methods are okay
$this->assertInstanceOf("Varchar", $player->relObject('Teams.First.Title'));
$this->assertEquals("Team 1", $player->relObject('Teams.First.Title')->getValue());
}
public function testLateStaticBindingStyle() {
// Confirm that DataObjectTest_Player::get() operates as excepted
$this->assertEquals(4, DataObjectTest_Player::get()->Count());
$this->assertInstanceOf('DataObjectTest_Player', DataObjectTest_Player::get()->First());
// You can't pass arguments to LSB syntax - use the DataList methods instead.
$this->setExpectedException('InvalidArgumentException');
DataObjectTest_Player::get(null, "\"ID\" = 1");
}
public function testBrokenLateStaticBindingStyle() {
// If you call DataObject::get() you have to pass a first argument
$this->setExpectedException('InvalidArgumentException');
DataObject::get();
}
}
class DataObjectTest_Player extends Member implements TestOnly {
private static $db = array(
'IsRetired' => 'Boolean',
'ShirtNumber' => 'Varchar',
);
private static $has_one = array(
'FavouriteTeam' => 'DataObjectTest_Team',
);
private static $belongs_many_many = array(
'Teams' => 'DataObjectTest_Team'
);
private static $searchable_fields = array(
'IsRetired',
'ShirtNumber'
);
}
class DataObjectTest_Team extends DataObject implements TestOnly {
private static $db = array(
'Title' => 'Varchar',
'DatabaseField' => 'HTMLVarchar'
);
private static $has_one = array(
"Captain" => 'DataObjectTest_Player',
'HasOneRelationship' => 'DataObjectTest_Player',
);
private static $has_many = array(
'SubTeams' => 'DataObjectTest_SubTeam',
'Comments' => 'DataObjectTest_TeamComment'
);
private static $many_many = array(
'Players' => 'DataObjectTest_Player'
);
private static $many_many_extraFields = array(
'Players' => array(
'Position' => 'Varchar(100)'
)
);
private static $summary_fields = array(
'Title' => 'Custom Title',
'Title.UpperCase' => 'Title',
'Captain.ShirtNumber' => 'Captain\'s shirt number',
'Captain.FavouriteTeam.Title' => 'Captain\'s favourite team'
);
private static $default_sort = '"Title"';
public function MyTitle() {
return 'Team ' . $this->Title;
}
public function getDynamicField() {
return 'dynamicfield';
}
}
class DataObjectTest_Fixture extends DataObject implements TestOnly {
private static $db = array(
// Funny field names
'Data' => 'Varchar',
'Duplicate' => 'Varchar',
'DbObject' => 'Varchar',
// Field types
'DateField' => 'Date',
'DatetimeField' => 'Datetime',
'MyFieldWithDefault' => 'Varchar',
'MyFieldWithAltDefault' => 'Varchar'
);
private static $defaults = array(
'MyFieldWithDefault' => 'Default Value',
);
private static $summary_fields = array(
'Data' => 'Data',
'DateField.Nice' => 'Date'
);
private static $searchable_fields = array();
public function populateDefaults() {
parent::populateDefaults();
$this->MyFieldWithAltDefault = 'Default Value';
}
}
class DataObjectTest_SubTeam extends DataObjectTest_Team implements TestOnly {
private static $db = array(
'SubclassDatabaseField' => 'Varchar'
);
private static $has_one = array(
"ParentTeam" => 'DataObjectTest_Team',
);
private static $many_many = array(
'FormerPlayers' => 'DataObjectTest_Player'
);
private static $many_many_extraFields = array(
'FormerPlayers' => array(
'Position' => 'Varchar(100)'
)
);
}
class OtherSubclassWithSameField extends DataObjectTest_Team implements TestOnly {
private static $db = array(
'SubclassDatabaseField' => 'Varchar',
);
}
class DataObjectTest_FieldlessTable extends DataObject implements TestOnly {
}
class DataObjectTest_FieldlessSubTable extends DataObjectTest_Team implements TestOnly {
}
class DataObjectTest_Team_Extension extends DataExtension implements TestOnly {
private static $db = array(
'ExtendedDatabaseField' => 'Varchar'
);
private static $has_one = array(
'ExtendedHasOneRelationship' => 'DataObjectTest_Player'
);
public function getExtendedDynamicField() {
return "extended dynamic field";
}
}
class DataObjectTest_ValidatedObject extends DataObject implements TestOnly {
private static $db = array(
'Name' => 'Varchar(50)'
);
protected function validate() {
if(!empty($this->Name)) {
return new ValidationResult();
} else {
return new ValidationResult(false, "This object needs a name. Otherwise it will have an identity crisis!");
}
}
}
class DataObjectTest_Company extends DataObject {
private static $has_one = array (
'CEO' => 'DataObjectTest_CEO',
'PreviousCEO' => 'DataObjectTest_CEO'
);
private static $has_many = array (
'CurrentStaff' => 'DataObjectTest_Staff.CurrentCompany',
'PreviousStaff' => 'DataObjectTest_Staff.PreviousCompany'
);
}
class DataObjectTest_Staff extends DataObject {
private static $has_one = array (
'CurrentCompany' => 'DataObjectTest_Company',
'PreviousCompany' => 'DataObjectTest_Company'
);
}
class DataObjectTest_CEO extends DataObjectTest_Staff {
private static $belongs_to = array (
'Company' => 'DataObjectTest_Company.CEO',
'PreviousCompany' => 'DataObjectTest_Company.PreviousCEO'
);
}
class DataObjectTest_TeamComment extends DataObject {
private static $db = array(
'Name' => 'Varchar',
'Comment' => 'Text'
);
private static $has_one = array(
'Team' => 'DataObjectTest_Team'
);
}
class DataObjectTest_ExtendedTeamComment extends DataObjectTest_TeamComment {
private static $db = array(
'Comment' => 'HTMLText'
);
}
DataObjectTest_Team::add_extension('DataObjectTest_Team_Extension');