summaryrefslogtreecommitdiff
path: root/modules/field/tests/field.test
blob: 97510e476f8c194484422ee36714c63b59093b6e (plain)
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
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
<?php

/**
 * @file
 * Tests for field.module.
 */

/**
 * Parent class for Field API tests.
 */
class FieldTestCase extends DrupalWebTestCase {
  var $default_storage = 'field_sql_storage';

  /**
   * Set the default field storage backend for fields created during tests.
   */
  function setUp() {
    // Since this is a base class for many test cases, support the same
    // flexibility that DrupalWebTestCase::setUp() has for the modules to be
    // passed in as either an array or a variable number of string arguments.
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    parent::setUp($modules);
    // Set default storage backend.
    variable_set('field_storage_default', $this->default_storage);
  }

  /**
   * Generate random values for a field_test field.
   *
   * @param $cardinality
   *   Number of values to generate.
   * @return
   *  An array of random values, in the format expected for field values.
   */
  function _generateTestFieldValues($cardinality) {
    $values = array();
    for ($i = 0; $i < $cardinality; $i++) {
      // field_test fields treat 0 as 'empty value'.
      $values[$i]['value'] = mt_rand(1, 127);
    }
    return $values;
  }

  /**
   * Assert that a field has the expected values in an entity.
   *
   * This function only checks a single column in the field values.
   *
   * @param $entity
   *   The entity to test.
   * @param $field_name
   *   The name of the field to test
   * @param $langcode
   *   The language code for the values.
   * @param $expected_values
   *   The array of expected values.
   * @param $column
   *   (Optional) the name of the column to check.
   */
  function assertFieldValues($entity, $field_name, $langcode, $expected_values, $column = 'value') {
    $e = clone $entity;
    field_attach_load('test_entity', array($e->ftid => $e));
    $values = isset($e->{$field_name}[$langcode]) ? $e->{$field_name}[$langcode] : array();
    $this->assertEqual(count($values), count($expected_values), t('Expected number of values were saved.'));
    foreach ($expected_values as $key => $value) {
      $this->assertEqual($values[$key][$column], $value, t('Value @value was saved correctly.', array('@value' => $value)));
    }
  }
}

class FieldAttachTestCase extends FieldTestCase {
  function setUp($modules = array()) {
    // Since this is a base class for many test cases, support the same
    // flexibility that DrupalWebTestCase::setUp() has for the modules to be
    // passed in as either an array or a variable number of string arguments.
    if (!is_array($modules)) {
      $modules = func_get_args();
    }
    if (!in_array('field_test', $modules)) {
      $modules[] = 'field_test';
    }
    parent::setUp($modules);

    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
    $this->field = array('field_name' => $this->field_name, 'type' => 'test_field', 'cardinality' => 4);
    $this->field = field_create_field($this->field);
    $this->field_id = $this->field['id'];
    $this->instance = array(
      'field_name' => $this->field_name,
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
      'label' => $this->randomName() . '_label',
      'description' => $this->randomName() . '_description',
      'weight' => mt_rand(0, 127),
      'settings' => array(
        'test_instance_setting' => $this->randomName(),
      ),
      'widget' => array(
        'type' => 'test_field_widget',
        'label' => 'Test Field',
        'settings' => array(
          'test_widget_setting' => $this->randomName(),
        )
      )
    );
    field_create_instance($this->instance);
  }
}

/**
 * Unit test class for storage-related field_attach_* functions.
 *
 * All field_attach_* test work with all field_storage plugins and
 * all hook_field_attach_pre_{load,insert,update}() hooks.
 */
class FieldAttachStorageTestCase extends FieldAttachTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Field attach tests (storage-related)',
      'description' => 'Test storage-related Field Attach API functions.',
      'group' => 'Field API',
    );
  }

  /**
   * Check field values insert, update and load.
   *
   * Works independently of the underlying field storage backend. Inserts or
   * updates random field data and then loads and verifies the data.
   */
  function testFieldAttachSaveLoad() {
    // Configure the instance so that we test hook_field_load() (see
    // field_test_field_load() in field_test.module).
    $this->instance['settings']['test_hook_field_load'] = TRUE;
    field_update_instance($this->instance);
    $langcode = LANGUAGE_NONE;

    $entity_type = 'test_entity';
    $values = array();

    // TODO : test empty values filtering and "compression" (store consecutive deltas).

    // Preparation: create three revisions and store them in $revision array.
    for ($revision_id = 0; $revision_id < 3; $revision_id++) {
      $revision[$revision_id] = field_test_create_stub_entity(0, $revision_id, $this->instance['bundle']);
      // Note: we try to insert one extra value.
      $values[$revision_id] = $this->_generateTestFieldValues($this->field['cardinality'] + 1);
      $current_revision = $revision_id;
      // If this is the first revision do an insert.
      if (!$revision_id) {
        $revision[$revision_id]->{$this->field_name}[$langcode] = $values[$revision_id];
        field_attach_insert($entity_type, $revision[$revision_id]);
      }
      else {
        // Otherwise do an update.
        $revision[$revision_id]->{$this->field_name}[$langcode] = $values[$revision_id];
        field_attach_update($entity_type, $revision[$revision_id]);
      }
    }

    // Confirm current revision loads the correct data.
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    field_attach_load($entity_type, array(0 => $entity));
    // Number of values per field loaded equals the field cardinality.
    $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], t('Current revision: expected number of values'));
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
      // The field value loaded matches the one inserted or updated.
      $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['value'] , $values[$current_revision][$delta]['value'], t('Current revision: expected value %delta was found.', array('%delta' => $delta)));
      // The value added in hook_field_load() is found.
      $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['additional_key'], 'additional_value', t('Current revision: extra information for value %delta was found', array('%delta' => $delta)));
    }

    // Confirm each revision loads the correct data.
    foreach (array_keys($revision) as $revision_id) {
      $entity = field_test_create_stub_entity(0, $revision_id, $this->instance['bundle']);
      field_attach_load_revision($entity_type, array(0 => $entity));
      // Number of values per field loaded equals the field cardinality.
      $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], t('Revision %revision_id: expected number of values.', array('%revision_id' => $revision_id)));
      for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
        // The field value loaded matches the one inserted or updated.
        $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['value'], $values[$revision_id][$delta]['value'], t('Revision %revision_id: expected value %delta was found.', array('%revision_id' => $revision_id, '%delta' => $delta)));
        // The value added in hook_field_load() is found.
        $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['additional_key'], 'additional_value', t('Revision %revision_id: extra information for value %delta was found', array('%revision_id' => $revision_id, '%delta' => $delta)));
      }
    }
  }

  /**
   * Test the 'multiple' load feature.
   */
  function testFieldAttachLoadMultiple() {
    $entity_type = 'test_entity';
    $langcode = LANGUAGE_NONE;

    // Define 2 bundles.
    $bundles = array(
      1 => 'test_bundle_1',
      2 => 'test_bundle_2',
    );
    field_test_create_bundle($bundles[1]);
    field_test_create_bundle($bundles[2]);
    // Define 3 fields:
    // - field_1 is in bundle_1 and bundle_2,
    // - field_2 is in bundle_1,
    // - field_3 is in bundle_2.
    $field_bundles_map = array(
      1 => array(1, 2),
      2 => array(1),
      3 => array(2),
    );
    for ($i = 1; $i <= 3; $i++) {
      $field_names[$i] = 'field_' . $i;
      $field = array('field_name' => $field_names[$i], 'type' => 'test_field');
      $field = field_create_field($field);
      $field_ids[$i] = $field['id'];
      foreach ($field_bundles_map[$i] as $bundle) {
        $instance = array(
          'field_name' => $field_names[$i],
          'entity_type' => 'test_entity',
          'bundle' => $bundles[$bundle],
          'settings' => array(
            // Configure the instance so that we test hook_field_load()
            // (see field_test_field_load() in field_test.module).
            'test_hook_field_load' => TRUE,
          ),
        );
        field_create_instance($instance);
      }
    }

    // Create one test entity per bundle, with random values.
    foreach ($bundles as $index => $bundle) {
      $entities[$index] = field_test_create_stub_entity($index, $index, $bundle);
      $entity = clone($entities[$index]);
      $instances = field_info_instances('test_entity', $bundle);
      foreach ($instances as $field_name => $instance) {
        $values[$index][$field_name] = mt_rand(1, 127);
        $entity->$field_name = array($langcode => array(array('value' => $values[$index][$field_name])));
      }
      field_attach_insert($entity_type, $entity);
    }

    // Check that a single load correctly loads field values for both entities.
    field_attach_load($entity_type, $entities);
    foreach ($entities as $index => $entity) {
      $instances = field_info_instances($entity_type, $bundles[$index]);
      foreach ($instances as $field_name => $instance) {
        // The field value loaded matches the one inserted.
        $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], $values[$index][$field_name], t('Entity %index: expected value was found.', array('%index' => $index)));
        // The value added in hook_field_load() is found.
        $this->assertEqual($entity->{$field_name}[$langcode][0]['additional_key'], 'additional_value', t('Entity %index: extra information was found', array('%index' => $index)));
      }
    }

    // Check that the single-field load option works.
    $entity = field_test_create_stub_entity(1, 1, $bundles[1]);
    field_attach_load($entity_type, array(1 => $entity), FIELD_LOAD_CURRENT, array('field_id' => $field_ids[1]));
    $this->assertEqual($entity->{$field_names[1]}[$langcode][0]['value'], $values[1][$field_names[1]], t('Entity %index: expected value was found.', array('%index' => 1)));
    $this->assertEqual($entity->{$field_names[1]}[$langcode][0]['additional_key'], 'additional_value', t('Entity %index: extra information was found', array('%index' => 1)));
    $this->assert(!isset($entity->{$field_names[2]}), t('Entity %index: field %field_name is not loaded.', array('%index' => 2, '%field_name' => $field_names[2])));
    $this->assert(!isset($entity->{$field_names[3]}), t('Entity %index: field %field_name is not loaded.', array('%index' => 3, '%field_name' => $field_names[3])));
  }

  /**
   * Test saving and loading fields using different storage backends.
   */
  function testFieldAttachSaveLoadDifferentStorage() {
    $entity_type = 'test_entity';
    $langcode = LANGUAGE_NONE;

    // Create two fields using different storage backends, and their instances.
    $fields = array(
      array(
        'field_name' => 'field_1',
        'type' => 'test_field',
        'cardinality' => 4,
        'storage' => array('type' => 'field_sql_storage')
      ),
      array(
        'field_name' => 'field_2',
        'type' => 'test_field',
        'cardinality' => 4,
        'storage' => array('type' => 'field_test_storage')
      ),
    );
    foreach ($fields as $field) {
      field_create_field($field);
      $instance = array(
        'field_name' => $field['field_name'],
        'entity_type' => 'test_entity',
        'bundle' => 'test_bundle',
      );
      field_create_instance($instance);
    }

    $entity_init = field_test_create_stub_entity();

    // Create entity and insert random values.
    $entity = clone($entity_init);
    $values = array();
    foreach ($fields as $field) {
      $values[$field['field_name']] = $this->_generateTestFieldValues($this->field['cardinality']);
      $entity->{$field['field_name']}[$langcode] = $values[$field['field_name']];
    }
    field_attach_insert($entity_type, $entity);

    // Check that values are loaded as expected.
    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    foreach ($fields as $field) {
      $this->assertEqual($values[$field['field_name']], $entity->{$field['field_name']}[$langcode], t('%storage storage: expected values were found.', array('%storage' => $field['storage']['type'])));
    }
  }

  /**
   * Test storage details alteration.
   *
   * @see field_test_storage_details_alter()
   */
  function testFieldStorageDetailsAlter() {
    $field_name = 'field_test_change_my_details';
    $field = array(
      'field_name' => $field_name,
      'type' => 'test_field',
      'cardinality' => 4,
      'storage' => array('type' => 'field_test_storage'),
    );
    $field = field_create_field($field);
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
    );
    field_create_instance($instance);

    $field = field_info_field($instance['field_name']);
    $instance = field_info_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);

    // The storage details are indexed by a storage engine type.
    $this->assertTrue(array_key_exists('drupal_variables', $field['storage']['details']), t('The storage type is Drupal variables.'));

    $details = $field['storage']['details']['drupal_variables'];

    // The field_test storage details are indexed by variable name. The details
    // are altered, so moon and mars are correct for this test.
    $this->assertTrue(array_key_exists('moon', $details[FIELD_LOAD_CURRENT]), t('Moon is available in the instance array.'));
    $this->assertTrue(array_key_exists('mars', $details[FIELD_LOAD_REVISION]), t('Mars is available in the instance array.'));

    // Test current and revision storage details together because the columns
    // are the same.
    foreach ((array) $field['columns'] as $column_name => $attributes) {
      $this->assertEqual($details[FIELD_LOAD_CURRENT]['moon'][$column_name], $column_name, t('Column name %value matches the definition in %bin.', array('%value' => $column_name, '%bin' => 'moon[FIELD_LOAD_CURRENT]')));
      $this->assertEqual($details[FIELD_LOAD_REVISION]['mars'][$column_name], $column_name, t('Column name %value matches the definition in %bin.', array('%value' => $column_name, '%bin' => 'mars[FIELD_LOAD_REVISION]')));
    }
  }

  /**
   * Tests insert and update with missing or NULL fields.
   */
  function testFieldAttachSaveMissingData() {
    $entity_type = 'test_entity';
    $entity_init = field_test_create_stub_entity();
    $langcode = LANGUAGE_NONE;

    // Insert: Field is missing.
    $entity = clone($entity_init);
    field_attach_insert($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}), t('Insert: missing field results in no value saved'));

    // Insert: Field is NULL.
    field_cache_clear();
    $entity = clone($entity_init);
    $entity->{$this->field_name} = NULL;
    field_attach_insert($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}), t('Insert: NULL field results in no value saved'));

    // Add some real data.
    field_cache_clear();
    $entity = clone($entity_init);
    $values = $this->_generateTestFieldValues(1);
    $entity->{$this->field_name}[$langcode] = $values;
    field_attach_insert($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertEqual($entity->{$this->field_name}[$langcode], $values, t('Field data saved'));

    // Update: Field is missing. Data should survive.
    field_cache_clear();
    $entity = clone($entity_init);
    field_attach_update($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertEqual($entity->{$this->field_name}[$langcode], $values, t('Update: missing field leaves existing values in place'));

    // Update: Field is NULL. Data should be wiped.
    field_cache_clear();
    $entity = clone($entity_init);
    $entity->{$this->field_name} = NULL;
    field_attach_update($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}), t('Update: NULL field removes existing values'));

    // Re-add some data.
    field_cache_clear();
    $entity = clone($entity_init);
    $values = $this->_generateTestFieldValues(1);
    $entity->{$this->field_name}[$langcode] = $values;
    field_attach_update($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertEqual($entity->{$this->field_name}[$langcode], $values, t('Field data saved'));

    // Update: Field is empty array. Data should be wiped.
    field_cache_clear();
    $entity = clone($entity_init);
    $entity->{$this->field_name} = array();
    field_attach_update($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}), t('Update: empty array removes existing values'));
  }

  /**
   * Test insert with missing or NULL fields, with default value.
   */
  function testFieldAttachSaveMissingDataDefaultValue() {
    // Add a default value function.
    $this->instance['default_value_function'] = 'field_test_default_value';
    field_update_instance($this->instance);

    $entity_type = 'test_entity';
    $entity_init = field_test_create_stub_entity();
    $langcode = LANGUAGE_NONE;

    // Insert: Field is NULL.
    $entity = clone($entity_init);
    $entity->{$this->field_name}[$langcode] = NULL;
    field_attach_insert($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}[$langcode]), t('Insert: NULL field results in no value saved'));

    // Insert: Field is missing.
    field_cache_clear();
    $entity = clone($entity_init);
    field_attach_insert($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $values = field_test_default_value($entity_type, $entity, $this->field, $this->instance);
    $this->assertEqual($entity->{$this->field_name}[$langcode], $values, t('Insert: missing field results in default value saved'));
  }

  /**
   * Test field_attach_delete().
   */
  function testFieldAttachDelete() {
    $entity_type = 'test_entity';
    $langcode = LANGUAGE_NONE;
    $rev[0] = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    // Create revision 0
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
    $rev[0]->{$this->field_name}[$langcode] = $values;
    field_attach_insert($entity_type, $rev[0]);

    // Create revision 1
    $rev[1] = field_test_create_stub_entity(0, 1, $this->instance['bundle']);
    $rev[1]->{$this->field_name}[$langcode] = $values;
    field_attach_update($entity_type, $rev[1]);

    // Create revision 2
    $rev[2] = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
    $rev[2]->{$this->field_name}[$langcode] = $values;
    field_attach_update($entity_type, $rev[2]);

    // Confirm each revision loads
    foreach (array_keys($rev) as $vid) {
      $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
      field_attach_load_revision($entity_type, array(0 => $read));
      $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity revision $vid has {$this->field['cardinality']} values.");
    }

    // Delete revision 1, confirm the other two still load.
    field_attach_delete_revision($entity_type, $rev[1]);
    foreach (array(0, 2) as $vid) {
      $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
      field_attach_load_revision($entity_type, array(0 => $read));
      $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity revision $vid has {$this->field['cardinality']} values.");
    }

    // Confirm the current revision still loads
    $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
    field_attach_load($entity_type, array(0 => $read));
    $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity current revision has {$this->field['cardinality']} values.");

    // Delete all field data, confirm nothing loads
    field_attach_delete($entity_type, $rev[2]);
    foreach (array(0, 1, 2) as $vid) {
      $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
      field_attach_load_revision($entity_type, array(0 => $read));
      $this->assertIdentical($read->{$this->field_name}, array(), "The test entity revision $vid is deleted.");
    }
    $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
    field_attach_load($entity_type, array(0 => $read));
    $this->assertIdentical($read->{$this->field_name}, array(), t('The test entity current revision is deleted.'));
  }

  /**
   * Test field_attach_create_bundle() and field_attach_rename_bundle().
   */
  function testFieldAttachCreateRenameBundle() {
    // Create a new bundle. This has to be initiated by the module so that its
    // hook_entity_info() is consistent.
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
    field_test_create_bundle($new_bundle);

    // Add an instance to that bundle.
    $this->instance['bundle'] = $new_bundle;
    field_create_instance($this->instance);

    // Save an entity with data in the field.
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    $langcode = LANGUAGE_NONE;
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
    $entity->{$this->field_name}[$langcode] = $values;
    $entity_type = 'test_entity';
    field_attach_insert($entity_type, $entity);

    // Verify the field data is present on load.
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    field_attach_load($entity_type, array(0 => $entity));
    $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], "Data is retrieved for the new bundle");

    // Rename the bundle. This has to be initiated by the module so that its
    // hook_entity_info() is consistent.
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
    field_test_rename_bundle($this->instance['bundle'], $new_bundle);

    // Check that the instance definition has been updated.
    $this->instance = field_info_instance($entity_type, $this->field_name, $new_bundle);
    $this->assertIdentical($this->instance['bundle'], $new_bundle, "Bundle name has been updated in the instance.");

    // Verify the field data is present on load.
    $entity = field_test_create_stub_entity(0, 0, $new_bundle);
    field_attach_load($entity_type, array(0 => $entity));
    $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], "Bundle name has been updated in the field storage");
  }

  /**
   * Test field_attach_delete_bundle().
   */
  function testFieldAttachDeleteBundle() {
    // Create a new bundle. This has to be initiated by the module so that its
    // hook_entity_info() is consistent.
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
    field_test_create_bundle($new_bundle);

    // Add an instance to that bundle.
    $this->instance['bundle'] = $new_bundle;
    field_create_instance($this->instance);

    // Create a second field for the test bundle
    $field_name = drupal_strtolower($this->randomName() . '_field_name');
    $field = array('field_name' => $field_name, 'type' => 'test_field', 'cardinality' => 1);
    field_create_field($field);
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => 'test_entity',
      'bundle' => $this->instance['bundle'],
      'label' => $this->randomName() . '_label',
      'description' => $this->randomName() . '_description',
      'weight' => mt_rand(0, 127),
      // test_field has no instance settings
      'widget' => array(
        'type' => 'test_field_widget',
        'settings' => array(
          'size' => mt_rand(0, 255))));
    field_create_instance($instance);

    // Save an entity with data for both fields
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    $langcode = LANGUAGE_NONE;
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
    $entity->{$this->field_name}[$langcode] = $values;
    $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues(1);
    field_attach_insert('test_entity', $entity);

    // Verify the fields are present on load
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    field_attach_load('test_entity', array(0 => $entity));
    $this->assertEqual(count($entity->{$this->field_name}[$langcode]), 4, 'First field got loaded');
    $this->assertEqual(count($entity->{$field_name}[$langcode]), 1, 'Second field got loaded');

    // Delete the bundle. This has to be initiated by the module so that its
    // hook_entity_info() is consistent.
    field_test_delete_bundle($this->instance['bundle']);

    // Verify no data gets loaded
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    field_attach_load('test_entity', array(0 => $entity));
    $this->assertFalse(isset($entity->{$this->field_name}[$langcode]), 'No data for first field');
    $this->assertFalse(isset($entity->{$field_name}[$langcode]), 'No data for second field');

    // Verify that the instances are gone
    $this->assertFalse(field_read_instance('test_entity', $this->field_name, $this->instance['bundle']), "First field is deleted");
    $this->assertFalse(field_read_instance('test_entity', $field_name, $instance['bundle']), "Second field is deleted");
  }
}

/**
 * Unit test class for non-storage related field_attach_* functions.
 */
class FieldAttachOtherTestCase extends FieldAttachTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Field attach tests (other)',
      'description' => 'Test other Field Attach API functions.',
      'group' => 'Field API',
    );
  }

  /**
   * Test field_attach_view() and field_attach_prepare_view().
   */
  function testFieldAttachView() {
    $entity_type = 'test_entity';
    $entity_init = field_test_create_stub_entity();
    $langcode = LANGUAGE_NONE;

    // Populate values to be displayed.
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
    $entity_init->{$this->field_name}[$langcode] = $values;

    // Simple formatter, label displayed.
    $entity = clone($entity_init);
    $formatter_setting = $this->randomName();
    $this->instance['display'] = array(
      'full' => array(
        'label' => 'above',
        'type' => 'field_test_default',
        'settings' => array(
          'test_formatter_setting' => $formatter_setting,
        )
      ),
    );
    field_update_instance($this->instance);
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
    $entity->content = field_attach_view($entity_type, $entity, 'full');
    $output = drupal_render($entity->content);
    $this->content = $output;
    $this->assertRaw($this->instance['label'], "Label is displayed.");
    foreach ($values as $delta => $value) {
      $this->content = $output;
      $this->assertRaw("$formatter_setting|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
    }

    // Label hidden.
    $entity = clone($entity_init);
    $this->instance['display']['full']['label'] = 'hidden';
    field_update_instance($this->instance);
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
    $entity->content = field_attach_view($entity_type, $entity, 'full');
    $output = drupal_render($entity->content);
    $this->content = $output;
    $this->assertNoRaw($this->instance['label'], "Hidden label: label is not displayed.");

    // Field hidden.
    $entity = clone($entity_init);
    $this->instance['display'] = array(
      'full' => array(
        'label' => 'above',
        'type' => 'hidden',
      ),
    );
    field_update_instance($this->instance);
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
    $entity->content = field_attach_view($entity_type, $entity, 'full');
    $output = drupal_render($entity->content);
    $this->content = $output;
    $this->assertNoRaw($this->instance['label'], "Hidden field: label is not displayed.");
    foreach ($values as $delta => $value) {
      $this->assertNoRaw($value['value'], "Hidden field: value $delta is not displayed.");
    }

    // Multiple formatter.
    $entity = clone($entity_init);
    $formatter_setting = $this->randomName();
    $this->instance['display'] = array(
      'full' => array(
        'label' => 'above',
        'type' => 'field_test_multiple',
        'settings' => array(
          'test_formatter_setting_multiple' => $formatter_setting,
        )
      ),
    );
    field_update_instance($this->instance);
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
    $entity->content = field_attach_view($entity_type, $entity, 'full');
    $output = drupal_render($entity->content);
    $display = $formatter_setting;
    foreach ($values as $delta => $value) {
      $display .= "|$delta:{$value['value']}";
    }
    $this->content = $output;
    $this->assertRaw($display, "Multiple formatter: all values are displayed, formatter settings are applied.");

    // Test a formatter that uses hook_field_formatter_prepare_view().
    $entity = clone($entity_init);
    $formatter_setting = $this->randomName();
    $this->instance['display'] = array(
      'full' => array(
        'label' => 'above',
        'type' => 'field_test_with_prepare_view',
        'settings' => array(
          'test_formatter_setting_additional' => $formatter_setting,
        )
      ),
    );
    field_update_instance($this->instance);
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
    $entity->content = field_attach_view($entity_type, $entity, 'full');
    $output = drupal_render($entity->content);
    $this->content = $output;
    foreach ($values as $delta => $value) {
      $this->content = $output;
      $expected = $formatter_setting . '|' . $value['value'] . '|' . ($value['value'] + 1);
      $this->assertRaw($expected, "Value $delta is displayed, formatter settings are applied.");
    }

    // TODO:
    // - check display order with several fields

    // Preprocess template.
    $variables = array();
    field_attach_preprocess($entity_type, $entity, $entity->content, $variables);
    $result = TRUE;
    foreach ($values as $delta => $item) {
      if ($variables[$this->field_name][$delta]['value'] !== $item['value']) {
        $result = FALSE;
        break;
      }
    }
    $this->assertTrue($result, t('Variable $@field_name correctly populated.', array('@field_name' => $this->field_name)));
  }

  /**
   * Tests the 'multiple entity' behavior of field_attach_prepare_view().
   */
  function testFieldAttachPrepareViewMultiple() {
    $entity_type = 'test_entity';
    $langcode = LANGUAGE_NONE;

    // Set the instance to be hidden.
    $this->instance['display']['full']['type'] = 'hidden';
    field_update_instance($this->instance);

    // Set up a second instance on another bundle, with a formatter that uses
    // hook_field_formatter_prepare_view().
    field_test_create_bundle('test_bundle_2');
    $formatter_setting = $this->randomName();
    $this->instance2 = $this->instance;
    $this->instance2['bundle'] = 'test_bundle_2';
    $this->instance2['display']['full'] = array(
      'type' => 'field_test_with_prepare_view',
      'settings' => array(
        'test_formatter_setting_additional' => $formatter_setting,
      )
    );
    field_create_instance($this->instance2);

    // Create one entity in each bundle.
    $entity1_init = field_test_create_stub_entity(1, 1, 'test_bundle');
    $values1 = $this->_generateTestFieldValues($this->field['cardinality']);
    $entity1_init->{$this->field_name}[$langcode] = $values1;

    $entity2_init = field_test_create_stub_entity(2, 2, 'test_bundle_2');
    $values2 = $this->_generateTestFieldValues($this->field['cardinality']);
    $entity2_init->{$this->field_name}[$langcode] = $values2;

    // Run prepare_view, and check that the entities come out as expected.
    $entity1 = clone($entity1_init);
    $entity2 = clone($entity2_init);
    field_attach_prepare_view($entity_type, array($entity1->ftid => $entity1, $entity2->ftid => $entity2), 'full');
    $this->assertFalse(isset($entity1->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 1 did not run through the prepare_view hook.');
    $this->assertTrue(isset($entity2->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 2 ran through the prepare_view hook.');

    // Same thing, reversed order.
    $entity1 = clone($entity1_init);
    $entity2 = clone($entity2_init);
    field_attach_prepare_view($entity_type, array($entity2->ftid => $entity2, $entity1->ftid => $entity1), 'full');
    $this->assertFalse(isset($entity1->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 1 did not run through the prepare_view hook.');
    $this->assertTrue(isset($entity2->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 2 ran through the prepare_view hook.');
  }

  /**
   * Test field cache.
   */
  function testFieldAttachCache() {
    // Initialize random values and a test entity.
    $entity_init = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
    $langcode = LANGUAGE_NONE;
    $values = $this->_generateTestFieldValues($this->field['cardinality']);

    // Non-cacheable entity type.
    $entity_type = 'test_entity';
    $cid = "field:$entity_type:{$entity_init->ftid}";

    // Check that no initial cache entry is present.
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no initial cache entry'));

    // Save, and check that no cache entry is present.
    $entity = clone($entity_init);
    $entity->{$this->field_name}[$langcode] = $values;
    field_attach_insert($entity_type, $entity);
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no cache entry on insert'));

    // Load, and check that no cache entry is present.
    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no cache entry on load'));


    // Cacheable entity type.
    $entity_type = 'test_cacheable_entity';
    $cid = "field:$entity_type:{$entity_init->ftid}";
    $instance = $this->instance;
    $instance['entity_type'] = $entity_type;
    field_create_instance($instance);

    // Check that no initial cache entry is present.
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no initial cache entry'));

    // Save, and check that no cache entry is present.
    $entity = clone($entity_init);
    $entity->{$this->field_name}[$langcode] = $values;
    field_attach_insert($entity_type, $entity);
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on insert'));

    // Load a single field, and check that no cache entry is present.
    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity), FIELD_LOAD_CURRENT, array('field_id' => $this->field_id));
    $cache = cache_get($cid, 'cache_field');
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on loading a single field'));

    // Load, and check that a cache entry is present with the expected values.
    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $cache = cache_get($cid, 'cache_field');
    $this->assertEqual($cache->data[$this->field_name][$langcode], $values, t('Cached: correct cache entry on load'));

    // Update with different values, and check that the cache entry is wiped.
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
    $entity = clone($entity_init);
    $entity->{$this->field_name}[$langcode] = $values;
    field_attach_update($entity_type, $entity);
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on update'));

    // Load, and check that a cache entry is present with the expected values.
    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $cache = cache_get($cid, 'cache_field');
    $this->assertEqual($cache->data[$this->field_name][$langcode], $values, t('Cached: correct cache entry on load'));

    // Create a new revision, and check that the cache entry is wiped.
    $entity_init = field_test_create_stub_entity(1, 2, $this->instance['bundle']);
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
    $entity = clone($entity_init);
    $entity->{$this->field_name}[$langcode] = $values;
    field_attach_update($entity_type, $entity);
    $cache = cache_get($cid, 'cache_field');
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on new revision creation'));

    // Load, and check that a cache entry is present with the expected values.
    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $cache = cache_get($cid, 'cache_field');
    $this->assertEqual($cache->data[$this->field_name][$langcode], $values, t('Cached: correct cache entry on load'));

    // Delete, and check that the cache entry is wiped.
    field_attach_delete($entity_type, $entity);
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry after delete'));
  }

  /**
   * Test field_attach_validate().
   *
   * Verify that field_attach_validate() invokes the correct
   * hook_field_validate.
   */
  function testFieldAttachValidate() {
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    $langcode = LANGUAGE_NONE;

    // Set up values to generate errors
    $values = array();
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
      $values[$delta]['value'] = -1;
    }
    // Arrange for item 1 not to generate an error
    $values[1]['value'] = 1;
    $entity->{$this->field_name}[$langcode] = $values;

    try {
      field_attach_validate($entity_type, $entity);
    }
    catch (FieldValidationException $e) {
      $errors = $e->errors;
    }

    foreach ($values as $delta => $value) {
      if ($value['value'] != 1) {
        $this->assertIdentical($errors[$this->field_name][$langcode][$delta][0]['error'], 'field_test_invalid', "Error set on value $delta");
        $this->assertEqual(count($errors[$this->field_name][$langcode][$delta]), 1, "Only one error set on value $delta");
        unset($errors[$this->field_name][$langcode][$delta]);
      }
      else {
        $this->assertFalse(isset($errors[$this->field_name][$langcode][$delta]), "No error set on value $delta");
      }
    }
    $this->assertEqual(count($errors[$this->field_name][$langcode]), 0, 'No extraneous errors set');

    // Check that cardinality is validated.
    $entity->{$this->field_name}[$langcode] = $this->_generateTestFieldValues($this->field['cardinality'] + 1);
    try {
      field_attach_validate($entity_type, $entity);
    }
    catch (FieldValidationException $e) {
      $errors = $e->errors;
    }
    $this->assertEqual($errors[$this->field_name][$langcode][0][0]['error'], 'field_cardinality', t('Cardinality validation failed.'));

  }

  /**
   * Test field_attach_form().
   *
   * This could be much more thorough, but it does verify that the correct
   * widgets show up.
   */
  function testFieldAttachForm() {
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    $form = array();
    $form_state = form_state_defaults();
    field_attach_form($entity_type, $entity, $form, $form_state);

    $langcode = LANGUAGE_NONE;
    $this->assertEqual($form[$this->field_name][$langcode]['#title'], $this->instance['label'], "Form title is {$this->instance['label']}");
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
      // field_test_widget uses 'textfield'
      $this->assertEqual($form[$this->field_name][$langcode][$delta]['value']['#type'], 'textfield', "Form delta $delta widget is textfield");
    }
  }

  /**
   * Test field_attach_submit().
   */
  function testFieldAttachSubmit() {
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    // Build the form.
    $form = array();
    $form_state = form_state_defaults();
    field_attach_form($entity_type, $entity, $form, $form_state);

    // Simulate incoming values.
    $values = array();
    $weights = array();
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
      $values[$delta]['value'] = mt_rand(1, 127);
      // Assign random weight.
      do {
        $weight = mt_rand(0, $this->field['cardinality']);
      } while (in_array($weight, $weights));
      $weights[$delta] = $weight;
      $values[$delta]['_weight'] = $weight;
    }
    // Leave an empty value. 'field_test' fields are empty if empty().
    $values[1]['value'] = 0;

    $langcode = LANGUAGE_NONE;
    // Pretend the form has been built.
    drupal_prepare_form('field_test_entity_form', $form, $form_state);
    drupal_process_form('field_test_entity_form', $form, $form_state);
    $form_state['values'][$this->field_name][$langcode] = $values;
    field_attach_submit($entity_type, $entity, $form, $form_state);

    asort($weights);
    $expected_values = array();
    foreach ($weights as $key => $value) {
      if ($key != 1) {
        $expected_values[] = array('value' => $values[$key]['value']);
      }
    }
    $this->assertIdentical($entity->{$this->field_name}[$langcode], $expected_values, 'Submit filters empty values');
  }
}

class FieldInfoTestCase extends FieldTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Field info tests',
      'description' => 'Get information about existing fields, instances and bundles.',
      'group' => 'Field API',
    );
  }

  function setUp() {
    parent::setUp('field_test');
  }

  /**
   * Test that field types and field definitions are correcly cached.
   */
  function testFieldInfo() {
    // Test that field_test module's fields, widgets, and formatters show up.

    $field_test_info = field_test_field_info();
    // We need to account for the existence of user_field_info_alter().
    foreach (array_keys($field_test_info) as $name) {
      $field_test_info[$name]['instance_settings']['user_register_form'] = FALSE;
    }
    $info = field_info_field_types();
    foreach ($field_test_info as $t_key => $field_type) {
      foreach ($field_type as $key => $val) {
        $this->assertEqual($info[$t_key][$key], $val, t("Field type $t_key key $key is $val"));
      }
      $this->assertEqual($info[$t_key]['module'], 'field_test',  t("Field type field_test module appears"));
    }

    $formatter_info = field_test_field_formatter_info();
    $info = field_info_formatter_types();
    foreach ($formatter_info as $f_key => $formatter) {
      foreach ($formatter as $key => $val) {
        $this->assertEqual($info[$f_key][$key], $val, t("Formatter type $f_key key $key is $val"));
      }
      $this->assertEqual($info[$f_key]['module'], 'field_test',  t("Formatter type field_test module appears"));
    }

    $widget_info = field_test_field_widget_info();
    $info = field_info_widget_types();
    foreach ($widget_info as $w_key => $widget) {
      foreach ($widget as $key => $val) {
        $this->assertEqual($info[$w_key][$key], $val, t("Widget type $w_key key $key is $val"));
      }
      $this->assertEqual($info[$w_key]['module'], 'field_test',  t("Widget type field_test module appears"));
    }

    $storage_info = field_test_field_storage_info();
    $info = field_info_storage_types();
    foreach ($storage_info as $s_key => $storage) {
      foreach ($storage as $key => $val) {
        $this->assertEqual($info[$s_key][$key], $val, t("Storage type $s_key key $key is $val"));
      }
      $this->assertEqual($info[$s_key]['module'], 'field_test',  t("Storage type field_test module appears"));
    }

    // Verify that no unexpected instances exist.
    $core_fields = field_info_fields();
    $instances = field_info_instances('test_entity', 'test_bundle');
    $this->assertTrue(empty($instances), t('With no instances, info bundles is empty.'));

    // Create a field, verify it shows up.
    $field = array(
      'field_name' => drupal_strtolower($this->randomName()),
      'type' => 'test_field',
    );
    field_create_field($field);
    $fields = field_info_fields();
    $this->assertEqual(count($fields), count($core_fields) + 1, t('One new field exists'));
    $this->assertEqual($fields[$field['field_name']]['field_name'], $field['field_name'], t('info fields contains field name'));
    $this->assertEqual($fields[$field['field_name']]['type'], $field['type'], t('info fields contains field type'));
    $this->assertEqual($fields[$field['field_name']]['module'], 'field_test', t('info fields contains field module'));
    $settings = array('test_field_setting' => 'dummy test string');
    foreach ($settings as $key => $val) {
      $this->assertEqual($fields[$field['field_name']]['settings'][$key], $val, t("Field setting $key has correct default value $val"));
    }
    $this->assertEqual($fields[$field['field_name']]['cardinality'], 1, t('info fields contains cardinality 1'));
    $this->assertEqual($fields[$field['field_name']]['active'], 1, t('info fields contains active 1'));

    // Create an instance, verify that it shows up
    $instance = array(
      'field_name' => $field['field_name'],
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
      'label' => $this->randomName(),
      'description' => $this->randomName(),
      'weight' => mt_rand(0, 127),
      // test_field has no instance settings
      'widget' => array(
        'type' => 'test_field_widget',
        'settings' => array(
          'test_setting' => 999)));
    field_create_instance($instance);

    $instances = field_info_instances('test_entity', $instance['bundle']);
    $this->assertEqual(count($instances), 1, t('One instance shows up in info when attached to a bundle.'));
    $this->assertTrue($instance < $instances[$instance['field_name']], t('Instance appears in info correctly'));
  }

  /**
   * Test that cached field definitions are ready for current runtime context.
   */
  function testFieldPrepare() {
    $field_definition = array(
      'field_name' => 'field',
      'type' => 'test_field',
    );
    field_create_field($field_definition);

    // Simulate a stored field definition missing a field setting (e.g. a
    // third-party module adding a new field setting has been enabled, and
    // existing fields do not know the setting yet).
    $data = db_query('SELECT data FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']))->fetchField();
    $data = unserialize($data);
    $data['settings'] = array();
    db_update('field_config')
      ->fields(array('data' => serialize($data)))
      ->condition('field_name', $field_definition['field_name'])
      ->execute();

    field_cache_clear();

    // Read the field back.
    $field = field_info_field($field_definition['field_name']);

    // Check that all expected settings are in place.
    $field_type = field_info_field_types($field_definition['type']);
    $this->assertIdentical($field['settings'], $field_type['settings'], t('All expected default field settings are present.'));
  }

  /**
   * Test that cached instance definitions are ready for current runtime context.
   */
  function testInstancePrepare() {
    $field_definition = array(
      'field_name' => 'field',
      'type' => 'test_field',
    );
    field_create_field($field_definition);
    $instance_definition = array(
      'field_name' => $field_definition['field_name'],
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
    );
    field_create_instance($instance_definition);

    // Simulate a stored instance definition missing various settings (e.g. a
    // third-party module adding instance, widget or display settings has been
    // enabled, but existing instances do not know the new settings).
    $data = db_query('SELECT data FROM {field_config_instance} WHERE field_name = :field_name AND bundle = :bundle', array(':field_name' => $instance_definition['field_name'], ':bundle' => $instance_definition['bundle']))->fetchField();
    $data = unserialize($data);
    $data['settings'] = array();
    $data['widget']['settings'] = 'unavailable_widget';
    $data['widget']['settings'] = array();
    $data['display']['default']['type'] = 'unavailable_formatter';
    $data['display']['default']['settings'] = array();
    db_update('field_config_instance')
      ->fields(array('data' => serialize($data)))
      ->condition('field_name', $instance_definition['field_name'])
      ->condition('bundle', $instance_definition['bundle'])
      ->execute();

    field_cache_clear();

    // Read the instance back.
    $instance = field_info_instance($instance_definition['entity_type'], $instance_definition['field_name'], $instance_definition['bundle']);

    // Check that all expected instance settings are in place.
    $field_type = field_info_field_types($field_definition['type']);
    $this->assertIdentical($instance['settings'], $field_type['instance_settings'] , t('All expected instance settings are present.'));

    // Check that the default widget is used and expected settings are in place.
    $this->assertIdentical($instance['widget']['type'], $field_type['default_widget'], t('Unavailable widget replaced with default widget.'));
    $widget_type = field_info_widget_types($instance['widget']['type']);
    $this->assertIdentical($instance['widget']['settings'], $widget_type['settings'] , t('All expected widget settings are present.'));

    // Check that display settings are set for the 'default' mode.
    $display = $instance['display']['default'];
    $this->assertIdentical($display['type'], $field_type['default_formatter'], t("Formatter is set for the 'default' view mode"));
    $formatter_type = field_info_formatter_types($display['type']);
    $this->assertIdentical($display['settings'], $formatter_type['settings'] , t("Formatter settings are set for the 'default' view mode"));
  }

  /**
   * Test that instances on disabled entity types are filtered out.
   */
  function testInstanceDisabledEntityType() {
    // For this test the field type and the entity type must be exposed by
    // different modules.
    $field_definition = array(
      'field_name' => 'field',
      'type' => 'test_field',
    );
    field_create_field($field_definition);
    $instance_definition = array(
      'field_name' => 'field',
      'entity_type' => 'comment',
      'bundle' => 'comment_node_article',
    );
    field_create_instance($instance_definition);

    // Disable coment module. This clears field_info cache.
    module_disable(array('comment'));
    $this->assertNull(field_info_instance('comment', 'field', 'comment_node_article'), t('No instances are returned on disabled entity types.'));
  }

  /**
   * Test that the field_info settings convenience functions work.
   */
  function testSettingsInfo() {
    $info = field_test_field_info();
    // We need to account for the existence of user_field_info_alter().
    foreach (array_keys($info) as $name) {
      $info[$name]['instance_settings']['user_register_form'] = FALSE;
    }
    foreach ($info as $type => $data) {
      $this->assertIdentical(field_info_field_settings($type), $data['settings'], "field_info_field_settings returns {$type}'s field settings");
      $this->assertIdentical(field_info_instance_settings($type), $data['instance_settings'], "field_info_field_settings returns {$type}'s field instance settings");
    }

    $info = field_test_field_widget_info();
    foreach ($info as $type => $data) {
      $this->assertIdentical(field_info_widget_settings($type), $data['settings'], "field_info_widget_settings returns {$type}'s widget settings");
    }

    $info = field_test_field_formatter_info();
    foreach ($info as $type => $data) {
      $this->assertIdentical(field_info_formatter_settings($type), $data['settings'], "field_info_formatter_settings returns {$type}'s formatter settings");
    }
  }
}

class FieldFormTestCase extends FieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Field form tests',
      'description' => 'Test Field form handling.',
      'group' => 'Field API',
    );
  }

  function setUp() {
    parent::setUp('field_test');

    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
    $this->drupalLogin($web_user);

    $this->field_single = array('field_name' => 'field_single', 'type' => 'test_field');
    $this->field_multiple = array('field_name' => 'field_multiple', 'type' => 'test_field', 'cardinality' => 4);
    $this->field_unlimited = array('field_name' => 'field_unlimited', 'type' => 'test_field', 'cardinality' => FIELD_CARDINALITY_UNLIMITED);

    $this->instance = array(
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
      'label' => $this->randomName() . '_label',
      'description' => $this->randomName() . '_description',
      'weight' => mt_rand(0, 127),
      'settings' => array(
        'test_instance_setting' => $this->randomName(),
      ),
      'widget' => array(
        'type' => 'test_field_widget',
        'label' => 'Test Field',
        'settings' => array(
          'test_widget_setting' => $this->randomName(),
        )
      )
    );
  }

  function testFieldFormSingle() {
    $this->field = $this->field_single;
    $this->field_name = $this->field['field_name'];
    $this->instance['field_name'] = $this->field_name;
    field_create_field($this->field);
    field_create_instance($this->instance);
    $langcode = LANGUAGE_NONE;

    // Display creation form.
    $this->drupalGet('test-entity/add/test-bundle');
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget is displayed');
    $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
    // TODO : check that the widget is populated with default value ?

    // Submit with invalid value (field-level validation).
    $edit = array("{$this->field_name}[$langcode][0][value]" => -1);
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $this->instance['label'])), 'Field validation fails with invalid input.');
    // TODO : check that the correct field is flagged for error.

    // Create an entity
    $value = mt_rand(1, 127);
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
    $this->drupalPost(NULL, $edit, t('Save'));
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
    $id = $match[1];
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
    $entity = field_test_entity_test_load($id);
    $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');

    // Display edit form.
    $this->drupalGet('test-entity/manage/' . $id . '/edit');
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", $value, 'Widget is displayed with the correct default value');
    $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');

    // Update the entity.
    $value = mt_rand(1, 127);
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
    $entity = field_test_entity_test_load($id);
    $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was updated');

    // Empty the field.
    $value = '';
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
    $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
    $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
    $entity = field_test_entity_test_load($id);
    $this->assertIdentical($entity->{$this->field_name}, array(), 'Field was emptied');

  }

  function testFieldFormSingleRequired() {
    $this->field = $this->field_single;
    $this->field_name = $this->field['field_name'];
    $this->instance['field_name'] = $this->field_name;
    $this->instance['required'] = TRUE;
    field_create_field($this->field);
    field_create_instance($this->instance);
    $langcode = LANGUAGE_NONE;

    // Submit with missing required value.
    $edit = array();
    $this->drupalPost('test-entity/add/test-bundle', $edit, t('Save'));
    $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');

    // Create an entity
    $value = mt_rand(1, 127);
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
    $this->drupalPost(NULL, $edit, t('Save'));
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
    $id = $match[1];
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
    $entity = field_test_entity_test_load($id);
    $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');

    // Edit with missing required value.
    $value = '';
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
    $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
    $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
  }

//  function testFieldFormMultiple() {
//    $this->field = $this->field_multiple;
//    $this->field_name = $this->field['field_name'];
//    $this->instance['field_name'] = $this->field_name;
//    field_create_field($this->field);
//    field_create_instance($this->instance);
//  }

  function testFieldFormUnlimited() {
    $this->field = $this->field_unlimited;
    $this->field_name = $this->field['field_name'];
    $this->instance['field_name'] = $this->field_name;
    field_create_field($this->field);
    field_create_instance($this->instance);
    $langcode = LANGUAGE_NONE;

    // Display creation form -> 1 widget.
    $this->drupalGet('test-entity/add/test-bundle');
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
    $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');

    // Press 'add more' button -> 2 widgets.
    $this->drupalPost(NULL, array(), t('Add another item'));
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
    $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
    $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
    // TODO : check that non-field inpurs are preserved ('title')...

    // Yet another time so that we can play with more values -> 3 widgets.
    $this->drupalPost(NULL, array(), t('Add another item'));

    // Prepare values and weights.
    $count = 3;
    $delta_range = $count - 1;
    $values = $weights = $pattern = $expected_values = $edit = array();
    for ($delta = 0; $delta <= $delta_range; $delta++) {
      // Assign unique random values and weights.
      do {
        $value = mt_rand(1, 127);
      } while (in_array($value, $values));
      do {
        $weight = mt_rand(-$delta_range, $delta_range);
      } while (in_array($weight, $weights));
      $edit["$this->field_name[$langcode][$delta][value]"] = $value;
      $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
      // We'll need three slightly different formats to check the values.
      $values[$delta] = $value;
      $weights[$delta] = $weight;
      $field_values[$weight]['value'] = (string) $value;
      $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
    }

    // Press 'add more' button -> 4 widgets
    $this->drupalPost(NULL, $edit, t('Add another item'));
    for ($delta = 0; $delta <= $delta_range; $delta++) {
      $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
      $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
    }
    ksort($pattern);
    $pattern = implode('.*', array_values($pattern));
    $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
    $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
    $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
    $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');

    // Submit the form and create the entity.
    $this->drupalPost(NULL, $edit, t('Save'));
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
    $id = $match[1];
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
    $entity = field_test_entity_test_load($id);
    ksort($field_values);
    $field_values = array_values($field_values);
    $this->assertIdentical($entity->{$this->field_name}[$langcode], $field_values, 'Field values were saved in the correct order');

    // Display edit form: check that the expected number of widgets is
    // displayed, with correct values change values, reorder, leave an empty
    // value in the middle.
    // Submit: check that the entity is updated with correct values
    // Re-submit: check that the field can be emptied.

    // Test with several multiple fields in a form
  }

  function testFieldFormJSAddMore() {
    $this->field = $this->field_unlimited;
    $this->field_name = $this->field['field_name'];
    $this->instance['field_name'] = $this->field_name;
    field_create_field($this->field);
    field_create_instance($this->instance);
    $langcode = LANGUAGE_NONE;

    // Display creation form -> 1 widget.
    $this->drupalGet('test-entity/add/test-bundle');

    // Press 'add more' button a couple times -> 3 widgets.
    // drupalPostAJAX() will not work iteratively, so we add those through
    // non-JS submission.
    $this->drupalPost(NULL, array(), t('Add another item'));
    $this->drupalPost(NULL, array(), t('Add another item'));

    // Prepare values and weights.
    $count = 3;
    $delta_range = $count - 1;
    $values = $weights = $pattern = $expected_values = $edit = array();
    for ($delta = 0; $delta <= $delta_range; $delta++) {
      // Assign unique random values and weights.
      do {
        $value = mt_rand(1, 127);
      } while (in_array($value, $values));
      do {
        $weight = mt_rand(-$delta_range, $delta_range);
      } while (in_array($weight, $weights));
      $edit["$this->field_name[$langcode][$delta][value]"] = $value;
      $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
      // We'll need three slightly different formats to check the values.
      $values[$delta] = $value;
      $weights[$delta] = $weight;
      $field_values[$weight]['value'] = (string) $value;
      $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
    }
    // Press 'add more' button through Ajax, and place the expected HTML result
    // as the tested content.
    $commands = $this->drupalPostAJAX(NULL, $edit, $this->field_name . '_add_more');
    $this->content = $commands[1]['data'];

    for ($delta = 0; $delta <= $delta_range; $delta++) {
      $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
      $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
    }
    ksort($pattern);
    $pattern = implode('.*', array_values($pattern));
    $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
    $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
    $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
    $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
  }

  /**
   * Tests widgets handling multiple values.
   */
  function testFieldFormMultipleWidget() {
    // Create a field with fixed cardinality and an instance using a multiple
    // widget.
    $this->field = $this->field_multiple;
    $this->field_name = $this->field['field_name'];
    $this->instance['field_name'] = $this->field_name;
    $this->instance['widget']['type'] = 'test_field_widget_multiple';
    field_create_field($this->field);
    field_create_instance($this->instance);
    $langcode = LANGUAGE_NONE;

    // Display creation form.
    $this->drupalGet('test-entity/add/test-bundle');
    $this->assertFieldByName("{$this->field_name}[$langcode]", '', t('Widget is displayed.'));

    // Create entity with three values.
    $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3');
    $this->drupalPost(NULL, $edit, t('Save'));
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
    $id = $match[1];

    // Check that the values were saved.
    $entity_init = field_test_create_stub_entity($id);
    $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));

    // Display the form, check that the values are correctly filled in.
    $this->drupalGet('test-entity/manage/' . $id . '/edit');
    $this->assertFieldByName("{$this->field_name}[$langcode]", '1, 2, 3', t('Widget is displayed.'));

    // Submit the form with more values than the field accepts.
    $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3, 4, 5');
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertRaw('this field cannot hold more than 4 values', t('Form validation failed.'));
    // Check that the field values were not submitted.
    $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
  }

  /**
   * Tests fields with no 'edit' access.
   */
  function testFieldFormAccess() {
    // Create a "regular" field.
    $field = $this->field_single;
    $field_name = $field['field_name'];
    $instance = $this->instance;
    $instance['field_name'] = $field_name;
    field_create_field($field);
    field_create_instance($instance);

    // Create a field with no edit access - see field_test_field_access().
    $field_no_access = array(
      'field_name' => 'field_no_edit_access',
      'type' => 'test_field',
    );
    $field_name_no_access = $field_no_access['field_name'];
    $instance_no_access = array(
      'field_name' => $field_name_no_access,
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
      'default_value' => array(0 => array('value' => 99)),
    );
    field_create_field($field_no_access);
    field_create_instance($instance_no_access);

    $langcode = LANGUAGE_NONE;

    // Display creation form.
    $this->drupalGet('test-entity/add/test-bundle');
    $this->assertNoFieldByName("{$field_name_no_access}[$langcode][0][value]", '', t('Widget is not displayed if field access is denied.'));

    // Create entity.
    $edit = array("{$field_name}[$langcode][0][value]" => 1);
    $this->drupalPost(NULL, $edit, t('Save'));
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
    $id = $match[1];

    // Check that the default value was saved.
    $entity = field_test_entity_test_load($id);
    $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, t('Default value was saved for the field with no edit access.'));
    $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 1, t('Entered value vas saved for the field with edit access.'));

    // Create a new revision.
    $edit = array("{$field_name}[$langcode][0][value]" => 2, 'revision' => TRUE);
    $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));

    // Check that the new revision has the expected values.
    $entity = field_test_entity_test_load($id);
    $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, t('New revision has the expected value for the field with no edit access.'));
    $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, t('New revision has the expected value for the field with edit access.'));

    // Check that the revision is also saved in the revisions table.
    $entity = field_test_entity_test_load($id, $entity->ftvid);
    $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, t('New revision has the expected value for the field with no edit access.'));
    $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, t('New revision has the expected value for the field with edit access.'));
  }

  /**
   * Tests Field API form integration within a subform.
   */
  function testNestedFieldForm() {
    // Add two instances on the 'test_bundle'
    field_create_field($this->field_single);
    field_create_field($this->field_unlimited);
    $this->instance['field_name'] = 'field_single';
    $this->instance['label'] = 'Single field';
    field_create_instance($this->instance);
    $this->instance['field_name'] = 'field_unlimited';
    $this->instance['label'] = 'Unlimited field';
    field_create_instance($this->instance);

    // Create two entities.
    $entity_1 = field_test_create_stub_entity(1, 1);
    $entity_1->is_new = TRUE;
    $entity_1->field_single[LANGUAGE_NONE][] = array('value' => 0);
    $entity_1->field_unlimited[LANGUAGE_NONE][] = array('value' => 1);
    field_test_entity_save($entity_1);

    $entity_2 = field_test_create_stub_entity(2, 2);
    $entity_2->is_new = TRUE;
    $entity_2->field_single[LANGUAGE_NONE][] = array('value' => 10);
    $entity_2->field_unlimited[LANGUAGE_NONE][] = array('value' => 11);
    field_test_entity_save($entity_2);

    // Display the 'combined form'.
    $this->drupalGet('test-entity/nested/1/2');
    $this->assertFieldByName('field_single[und][0][value]', 0, t('Entity 1: field_single value appears correctly is the form.'));
    $this->assertFieldByName('field_unlimited[und][0][value]', 1, t('Entity 1: field_unlimited value 0 appears correctly is the form.'));
    $this->assertFieldByName('entity_2[field_single][und][0][value]', 10, t('Entity 2: field_single value appears correctly is the form.'));
    $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 11, t('Entity 2: field_unlimited value 0 appears correctly is the form.'));

    // Submit the form and check that the entities are updated accordingly.
    $edit = array(
      'field_single[und][0][value]' => 1,
      'field_unlimited[und][0][value]' => 2,
      'field_unlimited[und][1][value]' => 3,
      'entity_2[field_single][und][0][value]' => 11,
      'entity_2[field_unlimited][und][0][value]' => 12,
      'entity_2[field_unlimited][und][1][value]' => 13,
    );
    $this->drupalPost(NULL, $edit, t('Save'));
    field_cache_clear();
    $entity_1 = field_test_create_stub_entity(1);
    $entity_2 = field_test_create_stub_entity(2);
    $this->assertFieldValues($entity_1, 'field_single', LANGUAGE_NONE, array(1));
    $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(2, 3));
    $this->assertFieldValues($entity_2, 'field_single', LANGUAGE_NONE, array(11));
    $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(12, 13));

    // Submit invalid values and check that errors are reported on the
    // correct widgets.
    $edit = array(
      'field_unlimited[und][1][value]' => -1,
    );
    $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
    $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), t('Entity 1: the field validation error was reported.'));
    $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-field-unlimited-und-1-value'));
    $this->assertTrue($error_field, t('Entity 1: the error was flagged on the correct element.'));
    $edit = array(
      'entity_2[field_unlimited][und][1][value]' => -1,
    );
    $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
    $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), t('Entity 2: the field validation error was reported.'));
    $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-entity-2-field-unlimited-und-1-value'));
    $this->assertTrue($error_field, t('Entity 2: the error was flagged on the correct element.'));

    // Test that reordering works on both entities.
    $edit = array(
      'field_unlimited[und][0][_weight]' => 0,
      'field_unlimited[und][1][_weight]' => -1,
      'entity_2[field_unlimited][und][0][_weight]' => 0,
      'entity_2[field_unlimited][und][1][_weight]' => -1,
    );
    $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
    field_cache_clear();
    $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
    $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 12));

    // Test the 'add more' buttons. Only Ajax submission is tested, because
    // the two 'add more' buttons present in the form have the same #value,
    // which confuses drupalPost().
    // 'Add more' button in the first entity:
    $this->drupalGet('test-entity/nested/1/2');
    $this->drupalPostAJAX(NULL, array(), 'field_unlimited_add_more');
    $this->assertFieldByName('field_unlimited[und][0][value]', 3, t('Entity 1: field_unlimited value 0 appears correctly is the form.'));
    $this->assertFieldByName('field_unlimited[und][1][value]', 2, t('Entity 1: field_unlimited value 1 appears correctly is the form.'));
    $this->assertFieldByName('field_unlimited[und][2][value]', '', t('Entity 1: field_unlimited value 2 appears correctly is the form.'));
    $this->assertFieldByName('field_unlimited[und][3][value]', '', t('Entity 1: an empty widget was added for field_unlimited value 3.'));
    // 'Add more' button in the first entity (changing field values):
    $edit = array(
      'entity_2[field_unlimited][und][0][value]' => 13,
      'entity_2[field_unlimited][und][1][value]' => 14,
      'entity_2[field_unlimited][und][2][value]' => 15,
    );
    $this->drupalPostAJAX(NULL, $edit, 'entity_2_field_unlimited_add_more');
    $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 13, t('Entity 2: field_unlimited value 0 appears correctly is the form.'));
    $this->assertFieldByName('entity_2[field_unlimited][und][1][value]', 14, t('Entity 2: field_unlimited value 1 appears correctly is the form.'));
    $this->assertFieldByName('entity_2[field_unlimited][und][2][value]', 15, t('Entity 2: field_unlimited value 2 appears correctly is the form.'));
    $this->assertFieldByName('entity_2[field_unlimited][und][3][value]', '', t('Entity 2: an empty widget was added for field_unlimited value 3.'));
    // Save the form and check values are saved correclty.
    $this->drupalPost(NULL, array(), t('Save'));
    field_cache_clear();
    $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
    $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 14, 15));
  }
}

class FieldDisplayAPITestCase extends FieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Field Display API tests',
      'description' => 'Test the display API.',
      'group' => 'Field API',
    );
  }

  function setUp() {
    parent::setUp('field_test');

    // Create a field and instance.
    $this->field_name = 'test_field';
    $this->label = $this->randomName();
    $this->cardinality = 4;

    $this->field = array(
      'field_name' => $this->field_name,
      'type' => 'test_field',
      'cardinality' => $this->cardinality,
    );
    $this->instance = array(
      'field_name' => $this->field_name,
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
      'label' => $this->label,
      'display' => array(
        'default' => array(
          'type' => 'field_test_default',
          'settings' => array(
            'test_formatter_setting' => $this->randomName(),
          ),
        ),
        'teaser' => array(
          'type' => 'field_test_default',
          'settings' => array(
            'test_formatter_setting' => $this->randomName(),
          ),
        ),
      ),
    );
    field_create_field($this->field);
    field_create_instance($this->instance);

    // Create an entity with values.
    $this->values = $this->_generateTestFieldValues($this->cardinality);
    $this->entity = field_test_create_stub_entity();
    $this->is_new = TRUE;
    $this->entity->{$this->field_name}[LANGUAGE_NONE] = $this->values;
    field_test_entity_save($this->entity);
  }

  /**
   * Test the field_view_field() function.
   */
  function testFieldViewField() {
    // No display settings: check that default display settings are used.
    $output = field_view_field('test_entity', $this->entity, $this->field_name);
    $this->drupalSetContent(drupal_render($output));
    $settings = field_info_formatter_settings('field_test_default');
    $setting = $settings['test_formatter_setting'];
    $this->assertText($this->label, t('Label was displayed.'));
    foreach ($this->values as $delta => $value) {
      $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }

    // Check that explicit display settings are used.
    $display = array(
      'label' => 'hidden',
      'type' => 'field_test_multiple',
      'settings' => array(
        'test_formatter_setting_multiple' => $this->randomName(),
        'alter' => TRUE,
      ),
    );
    $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
    $this->drupalSetContent(drupal_render($output));
    $setting = $display['settings']['test_formatter_setting_multiple'];
    $this->assertNoText($this->label, t('Label was not displayed.'));
    $this->assertText('field_test_field_attach_view_alter', t('Alter fired, display passed.'));
    $array = array();
    foreach ($this->values as $delta => $value) {
      $array[] = $delta . ':' . $value['value'];
    }
    $this->assertText($setting . '|' . implode('|', $array), t('Values were displayed with expected setting.'));

    // Check the prepare_view steps are invoked.
    $display = array(
      'label' => 'hidden',
      'type' => 'field_test_with_prepare_view',
      'settings' => array(
        'test_formatter_setting_additional' => $this->randomName(),
      ),
    );
    $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
    $view = drupal_render($output);
    $this->drupalSetContent($view);
    $setting = $display['settings']['test_formatter_setting_additional'];
    $this->assertNoText($this->label, t('Label was not displayed.'));
    $this->assertNoText('field_test_field_attach_view_alter', t('Alter not fired.'));
    foreach ($this->values as $delta => $value) {
      $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }

    // View mode: check that display settings specified in the instance are
    // used.
    $output = field_view_field('test_entity', $this->entity, $this->field_name, 'teaser');
    $this->drupalSetContent(drupal_render($output));
    $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
    $this->assertText($this->label, t('Label was displayed.'));
    foreach ($this->values as $delta => $value) {
      $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }

    // Unknown view mode: check that display settings for 'default' view mode
    // are used.
    $output = field_view_field('test_entity', $this->entity, $this->field_name, 'unknown_view_mode');
    $this->drupalSetContent(drupal_render($output));
    $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
    $this->assertText($this->label, t('Label was displayed.'));
    foreach ($this->values as $delta => $value) {
      $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }
  }

  /**
   * Test the field_view_value() function.
   */
  function testFieldViewValue() {
    // No display settings: check that default display settings are used.
    $settings = field_info_formatter_settings('field_test_default');
    $setting = $settings['test_formatter_setting'];
    foreach ($this->values as $delta => $value) {
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item);
      $this->drupalSetContent(drupal_render($output));
      $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }

    // Check that explicit display settings are used.
    $display = array(
      'type' => 'field_test_multiple',
      'settings' => array(
        'test_formatter_setting_multiple' => $this->randomName(),
      ),
    );
    $setting = $display['settings']['test_formatter_setting_multiple'];
    $array = array();
    foreach ($this->values as $delta => $value) {
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
      $this->drupalSetContent(drupal_render($output));
      $this->assertText($setting . '|0:' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }

    // Check that prepare_view steps are invoked.
    $display = array(
      'type' => 'field_test_with_prepare_view',
      'settings' => array(
        'test_formatter_setting_additional' => $this->randomName(),
      ),
    );
    $setting = $display['settings']['test_formatter_setting_additional'];
    $array = array();
    foreach ($this->values as $delta => $value) {
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
      $this->drupalSetContent(drupal_render($output));
      $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }

    // View mode: check that display settings specified in the instance are
    // used.
    $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
    foreach ($this->values as $delta => $value) {
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'teaser');
      $this->drupalSetContent(drupal_render($output));
      $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }

    // Unknown view mode: check that display settings for 'default' view mode
    // are used.
    $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
    foreach ($this->values as $delta => $value) {
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'unknown_view_mode');
      $this->drupalSetContent(drupal_render($output));
      $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
    }
  }
}

class FieldCrudTestCase extends FieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Field CRUD tests',
      'description' => 'Test field create, read, update, and delete.',
      'group' => 'Field API',
    );
  }

  function setUp() {
    // field_update_field() tests use number.module
    parent::setUp('field_test', 'number');
  }

  // TODO : test creation with
  // - a full fledged $field structure, check that all the values are there
  // - a minimal $field structure, check all default values are set
  // defer actual $field comparison to a helper function, used for the two cases above

  /**
   * Test the creation of a field.
   */
  function testCreateField() {
    $field_definition = array(
      'field_name' => 'field_2',
      'type' => 'test_field',
    );
    field_test_memorize();
    $field_definition = field_create_field($field_definition);
    $mem = field_test_memorize();
    $this->assertIdentical($mem['field_test_field_create_field'][0][0], $field_definition, 'hook_field_create_field() called with correct arguments.');

    // Read the raw record from the {field_config_instance} table.
    $result = db_query('SELECT * FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']));
    $record = $result->fetchAssoc();
    $record['data'] = unserialize($record['data']);

    // Ensure that basic properties are preserved.
    $this->assertEqual($record['field_name'], $field_definition['field_name'], t('The field name is properly saved.'));
    $this->assertEqual($record['type'], $field_definition['type'], t('The field type is properly saved.'));

    // Ensure that cardinality defaults to 1.
    $this->assertEqual($record['cardinality'], 1, t('Cardinality defaults to 1.'));

    // Ensure that default settings are present.
    $field_type = field_info_field_types($field_definition['type']);
    $this->assertIdentical($record['data']['settings'], $field_type['settings'], t('Default field settings have been written.'));

    // Ensure that default storage was set.
    $this->assertEqual($record['storage_type'], variable_get('field_storage_default'), t('The field type is properly saved.'));

    // Guarantee that the name is unique.
    try {
      field_create_field($field_definition);
      $this->fail(t('Cannot create two fields with the same name.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create two fields with the same name.'));
    }

    // Check that field type is required.
    try {
      $field_definition = array(
        'field_name' => 'field_1',
      );
      field_create_field($field_definition);
      $this->fail(t('Cannot create a field with no type.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create a field with no type.'));
    }

    // Check that field name is required.
    try {
      $field_definition = array(
        'type' => 'test_field'
      );
      field_create_field($field_definition);
      $this->fail(t('Cannot create an unnamed field.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create an unnamed field.'));
    }

    // Check that field name must start with a letter or _.
    try {
      $field_definition = array(
        'field_name' => '2field_2',
        'type' => 'test_field',
      );
      field_create_field($field_definition);
      $this->fail(t('Cannot create a field with a name starting with a digit.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create a field with a name starting with a digit.'));
    }

    // Check that field name must only contain lowercase alphanumeric or _.
    try {
      $field_definition = array(
        'field_name' => 'field#_3',
        'type' => 'test_field',
      );
      field_create_field($field_definition);
      $this->fail(t('Cannot create a field with a name containing an illegal character.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create a field with a name containing an illegal character.'));
    }

    // Check that field name cannot be longer than 32 characters long.
    try {
      $field_definition = array(
        'field_name' => '_12345678901234567890123456789012',
        'type' => 'test_field',
      );
      field_create_field($field_definition);
      $this->fail(t('Cannot create a field with a name longer than 32 characters.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create a field with a name longer than 32 characters.'));
    }

    // Check that field name can not be an entity key.
    // "ftvid" is known as an entity key from the "test_entity" type.
    try {
      $field_definition = array(
        'type' => 'test_field',
        'field_name' => 'ftvid',
      );
      $field = field_create_field($field_definition);
      $this->fail(t('Cannot create a field bearing the name of an entity key.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create a field bearing the name of an entity key.'));
    }
  }

  /**
   * Test failure to create a field.
   */
  function testCreateFieldFail() {
    $field_name = 'duplicate';
    $field_definition = array('field_name' => $field_name, 'type' => 'test_field', 'storage' => array('type' => 'field_test_storage_failure'));
    $query = db_select('field_config')->condition('field_name', $field_name)->countQuery();

    // The field does not appear in field_config.
    $count = $query->execute()->fetchField();
    $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');

    // Try to create the field.
    try {
      $field = field_create_field($field_definition);
      $this->assertTrue(FALSE, 'Field creation (correctly) fails.');
    }
    catch (Exception $e) {
      $this->assertTrue(TRUE, 'Field creation (correctly) fails.');
    }

    // The field does not appear in field_config.
    $count = $query->execute()->fetchField();
    $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
  }

  /**
   * Test reading back a field definition.
   */
  function testReadField() {
    $field_definition = array(
      'field_name' => 'field_1',
      'type' => 'test_field',
    );
    field_create_field($field_definition);

    // Read the field back.
    $field = field_read_field($field_definition['field_name']);
    $this->assertTrue($field_definition < $field, t('The field was properly read.'));
  }

  /**
   * Test creation of indexes on data column.
   */
  function testFieldIndexes() {
    // Check that indexes specified by the field type are used by default.
    $field_definition = array(
      'field_name' => 'field_1',
      'type' => 'test_field',
    );
    field_create_field($field_definition);
    $field = field_read_field($field_definition['field_name']);
    $expected_indexes = array('value' => array('value'));
    $this->assertEqual($field['indexes'], $expected_indexes, t('Field type indexes saved by default'));

    // Check that indexes specified by the field definition override the field
    // type indexes.
    $field_definition = array(
      'field_name' => 'field_2',
      'type' => 'test_field',
      'indexes' => array(
        'value' => array(),
      ),
    );
    field_create_field($field_definition);
    $field = field_read_field($field_definition['field_name']);
    $expected_indexes = array('value' => array());
    $this->assertEqual($field['indexes'], $expected_indexes, t('Field definition indexes override field type indexes'));

    // Check that indexes specified by the field definition add to the field
    // type indexes.
    $field_definition = array(
      'field_name' => 'field_3',
      'type' => 'test_field',
      'indexes' => array(
        'value_2' => array('value'),
      ),
    );
    field_create_field($field_definition);
    $field = field_read_field($field_definition['field_name']);
    $expected_indexes = array('value' => array('value'), 'value_2' => array('value'));
    $this->assertEqual($field['indexes'], $expected_indexes, t('Field definition indexes are merged with field type indexes'));
  }

  /**
   * Test the deletion of a field.
   */
  function testDeleteField() {
    // TODO: Also test deletion of the data stored in the field ?

    // Create two fields (so we can test that only one is deleted).
    $this->field = array('field_name' => 'field_1', 'type' => 'test_field');
    field_create_field($this->field);
    $this->another_field = array('field_name' => 'field_2', 'type' => 'test_field');
    field_create_field($this->another_field);

    // Create instances for each.
    $this->instance_definition = array(
      'field_name' => $this->field['field_name'],
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
      'widget' => array(
        'type' => 'test_field_widget',
      ),
    );
    field_create_instance($this->instance_definition);
    $this->another_instance_definition = $this->instance_definition;
    $this->another_instance_definition['field_name'] = $this->another_field['field_name'];
    field_create_instance($this->another_instance_definition);

    // Test that the first field is not deleted, and then delete it.
    $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
    $this->assertTrue(!empty($field) && empty($field['deleted']), t('A new field is not marked for deletion.'));
    field_delete_field($this->field['field_name']);

    // Make sure that the field is marked as deleted when it is specifically
    // loaded.
    $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
    $this->assertTrue(!empty($field['deleted']), t('A deleted field is marked for deletion.'));

    // Make sure that this field's instance is marked as deleted when it is
    // specifically loaded.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
    $this->assertTrue(!empty($instance['deleted']), t('An instance for a deleted field is marked for deletion.'));

    // Try to load the field normally and make sure it does not show up.
    $field = field_read_field($this->field['field_name']);
    $this->assertTrue(empty($field), t('A deleted field is not loaded by default.'));

    // Try to load the instance normally and make sure it does not show up.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $this->assertTrue(empty($instance), t('An instance for a deleted field is not loaded by default.'));

    // Make sure the other field (and its field instance) are not deleted.
    $another_field = field_read_field($this->another_field['field_name']);
    $this->assertTrue(!empty($another_field) && empty($another_field['deleted']), t('A non-deleted field is not marked for deletion.'));
    $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
    $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), t('An instance of a non-deleted field is not marked for deletion.'));

    // Try to create a new field the same name as a deleted field and
    // write data into it.
    field_create_field($this->field);
    field_create_instance($this->instance_definition);
    $field = field_read_field($this->field['field_name']);
    $this->assertTrue(!empty($field) && empty($field['deleted']), t('A new field with a previously used name is created.'));
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $this->assertTrue(!empty($instance) && empty($instance['deleted']), t('A new instance for a previously used field name is created.'));

    // Save an entity with data for the field
    $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
    $langcode = LANGUAGE_NONE;
    $values[0]['value'] = mt_rand(1, 127);
    $entity->{$field['field_name']}[$langcode] = $values;
    $entity_type = 'test_entity';
    field_attach_insert('test_entity', $entity);

    // Verify the field is present on load
    $entity = field_test_create_stub_entity(0, 0, $this->instance_definition['bundle']);
    field_attach_load($entity_type, array(0 => $entity));
    $this->assertIdentical(count($entity->{$field['field_name']}[$langcode]), count($values), "Data in previously deleted field saves and loads correctly");
    foreach ($values as $delta => $value) {
      $this->assertEqual($entity->{$field['field_name']}[$langcode][$delta]['value'], $values[$delta]['value'], "Data in previously deleted field saves and loads correctly");
    }
  }

  function testUpdateNonExistentField() {
    $test_field = array('field_name' => 'does_not_exist', 'type' => 'number_decimal');
    try {
      field_update_field($test_field);
      $this->fail(t('Cannot update a field that does not exist.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot update a field that does not exist.'));
    }
  }

  function testUpdateFieldType() {
    $field = array('field_name' => 'field_type', 'type' => 'number_decimal');
    $field = field_create_field($field);

    $test_field = array('field_name' => 'field_type', 'type' => 'number_integer');
    try {
      field_update_field($test_field);
      $this->fail(t('Cannot update a field to a different type.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot update a field to a different type.'));
    }
  }

  /**
   * Test updating a field.
   */
  function testUpdateField() {
    // Create a field with a defined cardinality, so that we can ensure it's
    // respected. Since cardinality enforcement is consistent across database
    // systems, it makes a good test case.
    $cardinality = 4;
    $field_definition = array(
      'field_name' => 'field_update',
      'type' => 'test_field',
      'cardinality' => $cardinality,
    );
    $field_definition = field_create_field($field_definition);
    $instance = array(
      'field_name' => 'field_update',
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
    );
    $instance = field_create_instance($instance);

    do {
      // We need a unique ID for our entity. $cardinality will do.
      $id = $cardinality;
      $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
      // Fill in the entity with more values than $cardinality.
      for ($i = 0; $i < 20; $i++) {
        $entity->field_update[LANGUAGE_NONE][$i]['value'] = $i;
      }
      // Save the entity.
      field_attach_insert('test_entity', $entity);
      // Load back and assert there are $cardinality number of values.
      $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
      field_attach_load('test_entity', array($id => $entity));
      $this->assertEqual(count($entity->field_update[LANGUAGE_NONE]), $field_definition['cardinality'], 'Cardinality is kept');
      // Now check the values themselves.
      for ($delta = 0; $delta < $cardinality; $delta++) {
        $this->assertEqual($entity->field_update[LANGUAGE_NONE][$delta]['value'], $delta, 'Value is kept');
      }
      // Increase $cardinality and set the field cardinality to the new value.
      $field_definition['cardinality'] = ++$cardinality;
      field_update_field($field_definition);
    } while ($cardinality < 6);
  }

  /**
   * Test field type modules forbidding an update.
   */
  function testUpdateFieldForbid() {
    $field = array('field_name' => 'forbidden', 'type' => 'test_field', 'settings' => array('changeable' => 0, 'unchangeable' => 0));
    $field = field_create_field($field);
    $field['settings']['changeable']++;
    try {
      field_update_field($field);
      $this->pass(t("A changeable setting can be updated."));
    }
    catch (FieldException $e) {
      $this->fail(t("An unchangeable setting cannot be updated."));
    }
    $field['settings']['unchangeable']++;
    try {
      field_update_field($field);
      $this->fail(t("An unchangeable setting can be updated."));
    }
    catch (FieldException $e) {
      $this->pass(t("An unchangeable setting cannot be updated."));
    }
  }

  /**
   * Test that fields are properly marked active or inactive.
   */
  function testActive() {
    $field_definition = array(
      'field_name' => 'field_1',
      'type' => 'test_field',
      // For this test, we need a storage backend provided by a different
      // module than field_test.module.
      'storage' => array(
        'type' => 'field_sql_storage',
      ),
    );
    field_create_field($field_definition);

    // Test disabling and enabling:
    // - the field type module,
    // - the storage module,
    // - both.
    $this->_testActiveHelper($field_definition, array('field_test'));
    $this->_testActiveHelper($field_definition, array('field_sql_storage'));
    $this->_testActiveHelper($field_definition, array('field_test', 'field_sql_storage'));
  }

  /**
   * Helper function for testActive().
   *
   * Test dependency between a field and a set of modules.
   *
   * @param $field_definition
   *   A field definition.
   * @param $modules
   *   An aray of module names. The field will be tested to be inactive as long
   *   as any of those modules is disabled.
   */
  function _testActiveHelper($field_definition, $modules) {
    $field_name = $field_definition['field_name'];

    // Read the field.
    $field = field_read_field($field_name);
    $this->assertTrue($field_definition <= $field, t('The field was properly read.'));

    module_disable($modules, FALSE);

    $fields = field_read_fields(array('field_name' => $field_name), array('include_inactive' => TRUE));
    $this->assertTrue(isset($fields[$field_name]) && $field_definition < $field, t('The field is properly read when explicitly fetching inactive fields.'));

    // Re-enable modules one by one, and check that the field is still inactive
    // while some modules remain disabled.
    while ($modules) {
      $field = field_read_field($field_name);
      $this->assertTrue(empty($field), t('%modules disabled. The field is marked inactive.', array('%modules' => implode(', ', $modules))));

      $module = array_shift($modules);
      module_enable(array($module), FALSE);
    }

    // Check that the field is active again after all modules have been
    // enabled.
    $field = field_read_field($field_name);
    $this->assertTrue($field_definition <= $field, t('The field was was marked active.'));
  }
}

class FieldInstanceCrudTestCase extends FieldTestCase {
  protected $field;

  public static function getInfo() {
    return array(
      'name' => 'Field instance CRUD tests',
      'description' => 'Create field entities by attaching fields to entities.',
      'group' => 'Field API',
    );
  }

  function setUp() {
    parent::setUp('field_test');

    $this->field = array(
      'field_name' => drupal_strtolower($this->randomName()),
      'type' => 'test_field',
    );
    field_create_field($this->field);
    $this->instance_definition = array(
      'field_name' => $this->field['field_name'],
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
    );
  }

  // TODO : test creation with
  // - a full fledged $instance structure, check that all the values are there
  // - a minimal $instance structure, check all default values are set
  // defer actual $instance comparison to a helper function, used for the two cases above,
  // and for testUpdateFieldInstance

  /**
   * Test the creation of a field instance.
   */
  function testCreateFieldInstance() {
    field_create_instance($this->instance_definition);

    // Read the raw record from the {field_config_instance} table.
    $result = db_query('SELECT * FROM {field_config_instance} WHERE field_name = :field_name AND bundle = :bundle', array(':field_name' => $this->instance_definition['field_name'], ':bundle' => $this->instance_definition['bundle']));
    $record = $result->fetchAssoc();
    $record['data'] = unserialize($record['data']);

    $field_type = field_info_field_types($this->field['type']);
    $widget_type = field_info_widget_types($field_type['default_widget']);
    $formatter_type = field_info_formatter_types($field_type['default_formatter']);

    // Check that default values are set.
    $this->assertIdentical($record['data']['required'], FALSE, t('Required defaults to false.'));
    $this->assertIdentical($record['data']['label'], $this->instance_definition['field_name'], t('Label defaults to field name.'));
    $this->assertIdentical($record['data']['description'], '', t('Description defaults to empty string.'));
    $this->assertIdentical($record['data']['widget']['type'], $field_type['default_widget'], t('Default widget has been written.'));
    $this->assertTrue(isset($record['data']['display']['default']), t('Display for "full" view_mode has been written.'));
    $this->assertIdentical($record['data']['display']['default']['type'], $field_type['default_formatter'], t('Default formatter for "full" view_mode has been written.'));

    // Check that default settings are set.
    $this->assertIdentical($record['data']['settings'], $field_type['instance_settings'] , t('Default instance settings have been written.'));
    $this->assertIdentical($record['data']['widget']['settings'], $widget_type['settings'] , t('Default widget settings have been written.'));
    $this->assertIdentical($record['data']['display']['default']['settings'], $formatter_type['settings'], t('Default formatter settings for "full" view_mode have been written.'));

    // Guarantee that the field/bundle combination is unique.
    try {
      field_create_instance($this->instance_definition);
      $this->fail(t('Cannot create two instances with the same field / bundle combination.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create two instances with the same field / bundle combination.'));
    }

    // Check that the specified field exists.
    try {
      $this->instance_definition['field_name'] = $this->randomName();
      field_create_instance($this->instance_definition);
      $this->fail(t('Cannot create an instance of a non-existing field.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create an instance of a non-existing field.'));
    }

    // Create a field restricted to a specific entity type.
    $field_restricted = array(
      'field_name' => drupal_strtolower($this->randomName()),
      'type' => 'test_field',
      'entity_types' => array('test_cacheable_entity'),
    );
    field_create_field($field_restricted);

    // Check that an instance can be added to an entity type allowed
    // by the field.
    try {
      $instance = $this->instance_definition;
      $instance['field_name'] = $field_restricted['field_name'];
      $instance['entity_type'] = 'test_cacheable_entity';
      field_create_instance($instance);
      $this->pass(t('Can create an instance on an entity type allowed by the field.'));
    }
    catch (FieldException $e) {
      $this->fail(t('Can create an instance on an entity type allowed by the field.'));
    }

    // Check that an instance cannot be added to an entity type
    // forbidden by the field.
    try {
      $instance = $this->instance_definition;
      $instance['field_name'] = $field_restricted['field_name'];
      field_create_instance($instance);
      $this->fail(t('Cannot create an instance on an entity type forbidden by the field.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create an instance on an entity type forbidden by the field.'));
    }

    // TODO: test other failures.
  }

  /**
   * Test reading back an instance definition.
   */
  function testReadFieldInstance() {
    field_create_instance($this->instance_definition);

    // Read the instance back.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $this->assertTrue($this->instance_definition < $instance, t('The field was properly read.'));
  }

  /**
   * Test the update of a field instance.
   */
  function testUpdateFieldInstance() {
    field_create_instance($this->instance_definition);
    $field_type = field_info_field_types($this->field['type']);

    // Check that basic changes are saved.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $instance['required'] = !$instance['required'];
    $instance['label'] = $this->randomName();
    $instance['description'] = $this->randomName();
    $instance['settings']['test_instance_setting'] = $this->randomName();
    $instance['widget']['settings']['test_widget_setting'] =$this->randomName();
    $instance['widget']['weight']++;
    $instance['display']['default']['settings']['test_formatter_setting'] = $this->randomName();
    $instance['display']['default']['weight']++;
    field_update_instance($instance);

    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $this->assertEqual($instance['required'], $instance_new['required'], t('"required" change is saved'));
    $this->assertEqual($instance['label'], $instance_new['label'], t('"label" change is saved'));
    $this->assertEqual($instance['description'], $instance_new['description'], t('"description" change is saved'));
    $this->assertEqual($instance['widget']['settings']['test_widget_setting'], $instance_new['widget']['settings']['test_widget_setting'], t('Widget setting change is saved'));
    $this->assertEqual($instance['widget']['weight'], $instance_new['widget']['weight'], t('Widget weight change is saved'));
    $this->assertEqual($instance['display']['default']['settings']['test_formatter_setting'], $instance_new['display']['default']['settings']['test_formatter_setting'], t('Formatter setting change is saved'));
    $this->assertEqual($instance['display']['default']['weight'], $instance_new['display']['default']['weight'], t('Widget weight change is saved'));

    // Check that changing widget and formatter types updates the default settings.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $instance['widget']['type'] = 'test_field_widget_multiple';
    $instance['display']['default']['type'] = 'field_test_multiple';
    field_update_instance($instance);

    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $this->assertEqual($instance['widget']['type'], $instance_new['widget']['type'] , t('Widget type change is saved.'));
    $settings = field_info_widget_settings($instance_new['widget']['type']);
    $this->assertIdentical($settings, array_intersect_key($instance_new['widget']['settings'], $settings) , t('Widget type change updates default settings.'));
    $this->assertEqual($instance['display']['default']['type'], $instance_new['display']['default']['type'] , t('Formatter type change is saved.'));
    $info = field_info_formatter_types($instance_new['display']['default']['type']);
    $settings = $info['settings'];
    $this->assertIdentical($settings, array_intersect_key($instance_new['display']['default']['settings'], $settings) , t('Changing formatter type updates default settings.'));

    // Check that adding a new view mode is saved and gets default settings.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $instance['display']['teaser'] = array();
    field_update_instance($instance);

    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $this->assertTrue(isset($instance_new['display']['teaser']), t('Display for the new view_mode has been written.'));
    $this->assertIdentical($instance_new['display']['teaser']['type'], $field_type['default_formatter'], t('Default formatter for the new view_mode has been written.'));
    $info = field_info_formatter_types($instance_new['display']['teaser']['type']);
    $settings = $info['settings'];
    $this->assertIdentical($settings, $instance_new['display']['teaser']['settings'] , t('Default formatter settings for the new view_mode have been written.'));

    // TODO: test failures.
  }

  /**
   * Test the deletion of a field instance.
   */
  function testDeleteFieldInstance() {
    // TODO: Test deletion of the data stored in the field also.
    // Need to check that data for a 'deleted' field / instance doesn't get loaded
    // Need to check data marked deleted is cleaned on cron (not implemented yet...)

    // Create two instances for the same field so we can test that only one
    // is deleted.
    field_create_instance($this->instance_definition);
    $this->another_instance_definition = $this->instance_definition;
    $this->another_instance_definition['bundle'] .= '_another_bundle';
    $instance = field_create_instance($this->another_instance_definition);

    // Test that the first instance is not deleted, and then delete it.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
    $this->assertTrue(!empty($instance) && empty($instance['deleted']), t('A new field instance is not marked for deletion.'));
    field_delete_instance($instance);

    // Make sure the instance is marked as deleted when the instance is
    // specifically loaded.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
    $this->assertTrue(!empty($instance['deleted']), t('A deleted field instance is marked for deletion.'));

    // Try to load the instance normally and make sure it does not show up.
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
    $this->assertTrue(empty($instance), t('A deleted field instance is not loaded by default.'));

    // Make sure the other field instance is not deleted.
    $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
    $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), t('A non-deleted field instance is not marked for deletion.'));

    // Make sure the field is deleted when its last instance is deleted.
    field_delete_instance($another_instance);
    $field = field_read_field($another_instance['field_name'], array('include_deleted' => TRUE));
    $this->assertTrue(!empty($field['deleted']), t('A deleted field is marked for deletion after all its instances have been marked for deletion.'));
  }
}

/**
 * Unit test class for the multilanguage fields logic.
 *
 * The following tests will check the multilanguage logic of _field_invoke() and
 * that only the correct values are returned by field_available_languages().
 */
class FieldTranslationsTestCase extends FieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Field translations tests',
      'description' => 'Test multilanguage fields logic.',
      'group' => 'Field API',
    );
  }

  function setUp() {
    parent::setUp('locale', 'field_test');

    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');

    $this->entity_type = 'test_entity';

    $field = array(
      'field_name' => $this->field_name,
      'type' => 'test_field',
      'cardinality' => 4,
      'translatable' => TRUE,
    );
    field_create_field($field);
    $this->field = field_read_field($this->field_name);

    $instance = array(
      'field_name' => $this->field_name,
      'entity_type' => $this->entity_type,
      'bundle' => 'test_bundle',
    );
    field_create_instance($instance);
    $this->instance = field_read_instance('test_entity', $this->field_name, 'test_bundle');

    require_once DRUPAL_ROOT . '/includes/locale.inc';
    for ($i = 0; $i < 3; ++$i) {
      locale_add_language('l' . $i, $this->randomString(), $this->randomString());
    }
  }

  /**
   * Ensures that only valid values are returned by field_available_languages().
   */
  function testFieldAvailableLanguages() {
    // Test 'translatable' fieldable info.
    field_test_entity_info_translatable('test_entity', FALSE);
    $field = $this->field;
    $field['field_name'] .= '_untranslatable';

    // Enable field translations for the entity.
    field_test_entity_info_translatable('test_entity', TRUE);

    // Test hook_field_languages() invocation on a translatable field.
    variable_set('field_test_field_available_languages_alter', TRUE);
    $enabled_languages = field_content_languages();
    $available_languages = field_available_languages($this->entity_type, $this->field);
    foreach ($available_languages as $delta => $langcode) {
      if ($langcode != 'xx' && $langcode != 'en') {
        $this->assertTrue(in_array($langcode, $enabled_languages), t('%language is an enabled language.', array('%language' => $langcode)));
      }
    }
    $this->assertTrue(in_array('xx', $available_languages), t('%language was made available.', array('%language' => 'xx')));
    $this->assertFalse(in_array('en', $available_languages), t('%language was made unavailable.', array('%language' => 'en')));

    // Test field_available_languages() behavior for untranslatable fields.
    $this->field['translatable'] = FALSE;
    $this->field_name = $this->field['field_name'] = $this->instance['field_name'] = drupal_strtolower($this->randomName() . '_field_name');
    $available_languages = field_available_languages($this->entity_type, $this->field);
    $this->assertTrue(count($available_languages) == 1 && $available_languages[0] === LANGUAGE_NONE, t('For untranslatable fields only LANGUAGE_NONE is available.'));
  }

  /**
   * Test the multilanguage logic of _field_invoke().
   */
  function testFieldInvoke() {
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    // Populate some extra languages to check if _field_invoke() correctly uses
    // the result of field_available_languages().
    $values = array();
    $extra_languages = mt_rand(1, 4);
    $languages = $available_languages = field_available_languages($this->entity_type, $this->field);
    for ($i = 0; $i < $extra_languages; ++$i) {
      $languages[] = $this->randomString(2);
    }

    // For each given language provide some random values.
    foreach ($languages as $langcode) {
      for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
        $values[$langcode][$delta]['value'] = mt_rand(1, 127);
      }
    }
    $entity->{$this->field_name} = $values;

    $results = _field_invoke('test_op', $entity_type, $entity);
    foreach ($results as $langcode => $result) {
      $hash = hash('sha256', serialize(array($entity_type, $entity, $this->field_name, $langcode, $values[$langcode])));
      // Check whether the parameters passed to _field_invoke() were correctly
      // forwarded to the callback function.
      $this->assertEqual($hash, $result, t('The result for %language is correctly stored.', array('%language' => $langcode)));
    }
    $this->assertEqual(count($results), count($available_languages), t('No unavailable language has been processed.'));
  }

  /**
   * Test the multilanguage logic of _field_invoke_multiple().
   */
  function testFieldInvokeMultiple() {
    $values = array();
    $entities = array();
    $entity_type = 'test_entity';
    $entity_count = mt_rand(1, 5);
    $available_languages = field_available_languages($this->entity_type, $this->field);

    for ($id = 1; $id <= $entity_count; ++$id) {
      $entity = field_test_create_stub_entity($id, $id, $this->instance['bundle']);
      $languages = $available_languages;

      // Populate some extra languages to check whether _field_invoke()
      // correctly uses the result of field_available_languages().
      $extra_languages = mt_rand(1, 4);
      for ($i = 0; $i < $extra_languages; ++$i) {
        $languages[] = $this->randomString(2);
      }

      // For each given language provide some random values.
      foreach ($languages as $langcode) {
        for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
          $values[$id][$langcode][$delta]['value'] = mt_rand(1, 127);
        }
      }
      $entity->{$this->field_name} = $values[$id];
      $entities[$id] = $entity;
    }

    $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities);
    foreach ($grouped_results as $id => $results) {
      foreach ($results as $langcode => $result) {
        $hash = hash('sha256', serialize(array($entity_type, $entities[$id], $this->field_name, $langcode, $values[$id][$langcode])));
        // Check whether the parameters passed to _field_invoke() were correctly
        // forwarded to the callback function.
        $this->assertEqual($hash, $result, t('The result for entity %id/%language is correctly stored.', array('%id' => $id, '%language' => $langcode)));
      }
      $this->assertEqual(count($results), count($available_languages), t('No unavailable language has been processed for entity %id.', array('%id' => $id)));
    }
  }

  /**
   * Test translatable fields storage/retrieval.
   */
  function testTranslatableFieldSaveLoad() {
    // Enable field translations for nodes.
    field_test_entity_info_translatable('node', TRUE);
    $entity_info = entity_get_info('node');
    $this->assertTrue(count($entity_info['translation']), t('Nodes are translatable.'));

    // Prepare the field translations.
    field_test_entity_info_translatable('test_entity', TRUE);
    $eid = $evid = 1;
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
    $field_translations = array();
    $available_languages = field_available_languages($entity_type, $this->field);
    $this->assertTrue(count($available_languages) > 1, t('Field is translatable.'));
    foreach ($available_languages as $langcode) {
      $field_translations[$langcode] = $this->_generateTestFieldValues($this->field['cardinality']);
    }

    // Save and reload the field translations.
    $entity->{$this->field_name} = $field_translations;
    field_attach_insert($entity_type, $entity);
    unset($entity->{$this->field_name});
    field_attach_load($entity_type, array($eid => $entity));

    // Check if the correct values were saved/loaded.
    foreach ($field_translations as $langcode => $items) {
      $result = TRUE;
      foreach ($items as $delta => $item) {
        $result = $result && $item['value'] == $entity->{$this->field_name}[$langcode][$delta]['value'];
      }
      $this->assertTrue($result, t('%language translation correctly handled.', array('%language' => $langcode)));
    }
  }

  /**
   * Tests display language logic for translatable fields.
   */
  function testFieldDisplayLanguage() {
    $field_name = drupal_strtolower($this->randomName() . '_field_name');
    $entity_type = 'test_entity';

    // We need an additional field here to properly test display language
    // suggestions.
    $field = array(
      'field_name' => $field_name,
      'type' => 'test_field',
      'cardinality' => 2,
      'translatable' => TRUE,
    );
    field_create_field($field);

    $instance = array(
      'field_name' => $field['field_name'],
      'entity_type' => $entity_type,
      'bundle' => 'test_bundle',
    );
    field_create_instance($instance);

    $entity = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
    $instances = field_info_instances($entity_type, $this->instance['bundle']);

    $enabled_languages = field_content_languages();
    $languages = array();

    // Generate field translations for languages different from the first
    // enabled.
    foreach ($instances as $instance) {
      $field_name = $instance['field_name'];
      $field = field_info_field($field_name);
      do {
        // Index 0 is reserved for the requested language, this way we ensure
        // that no field is actually populated with it.
        $langcode = $enabled_languages[mt_rand(1, count($enabled_languages) - 1)];
      }
      while (isset($languages[$langcode]));
      $languages[$langcode] = TRUE;
      $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues($field['cardinality']);
    }

    // Test multiple-fields display languages for untranslatable entities.
    field_test_entity_info_translatable($entity_type, FALSE);
    drupal_static_reset('field_language');
    $requested_language = $enabled_languages[0];
    $display_language = field_language($entity_type, $entity, NULL, $requested_language);
    foreach ($instances as $instance) {
      $field_name = $instance['field_name'];
      $this->assertTrue($display_language[$field_name] == LANGUAGE_NONE, t('The display language for field %field_name is %language.', array('%field_name' => $field_name, '%language' => LANGUAGE_NONE)));
    }

    // Test multiple-fields display languages for translatable entities.
    field_test_entity_info_translatable($entity_type, TRUE);
    drupal_static_reset('field_language');
    $display_language = field_language($entity_type, $entity, NULL, $requested_language);

    foreach ($instances as $instance) {
      $field_name = $instance['field_name'];
      $langcode = $display_language[$field_name];
      // As the requested language was not assinged to any field, if the
      // returned language is defined for the current field, core fallback rules
      // were successfully applied.
      $this->assertTrue(isset($entity->{$field_name}[$langcode]) && $langcode != $requested_language, t('The display language for the field %field_name is %language.', array('%field_name' => $field_name, '%language' => $langcode)));
    }

    // Test single-field display language.
    drupal_static_reset('field_language');
    $langcode = field_language($entity_type, $entity, $this->field_name, $requested_language);
    $this->assertTrue(isset($entity->{$this->field_name}[$langcode]) && $langcode != $requested_language, t('The display language for the (single) field %field_name is %language.', array('%field_name' => $field_name, '%language' => $langcode)));

    // Test field_language() basic behavior without language fallback.
    variable_set('field_test_language_fallback', FALSE);
    $entity->{$this->field_name}[$requested_language] = mt_rand(1, 127);
    drupal_static_reset('field_language');
    $display_language = field_language($entity_type, $entity, $this->field_name, $requested_language);
    $this->assertEqual($display_language, $requested_language, t('Display language behave correctly when language fallback is disabled'));
  }

  /**
   * Tests field translations when creating a new revision.
   */
  function testFieldFormTranslationRevisions() {
    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
    $this->drupalLogin($web_user);

    // Prepare the field translations.
    field_test_entity_info_translatable($this->entity_type, TRUE);
    $eid = 1;
    $entity = field_test_create_stub_entity($eid, $eid, $this->instance['bundle']);
    $available_languages = array_flip(field_available_languages($this->entity_type, $this->field));
    unset($available_languages[LANGUAGE_NONE]);
    $field_name = $this->field['field_name'];

    // Store the field translations.
    $entity->is_new = TRUE;
    foreach ($available_languages as $langcode => $value) {
      $entity->{$field_name}[$langcode][0]['value'] = $value + 1;
    }
    field_test_entity_save($entity);

    // Create a new revision.
    $langcode = field_valid_language(NULL);
    $edit = array("{$field_name}[$langcode][0][value]" => $entity->{$field_name}[$langcode][0]['value'], 'revision' => TRUE);
    $this->drupalPost('test-entity/manage/' . $eid . '/edit', $edit, t('Save'));

    // Check translation revisions.
    $this->checkTranslationRevisions($eid, $eid, $available_languages);
    $this->checkTranslationRevisions($eid, $eid + 1, $available_languages);
  }

  /**
   * Check if the field translation attached to the entity revision identified
   * by the passed arguments were correctly stored.
   */
  private function checkTranslationRevisions($eid, $evid, $available_languages) {
    $field_name = $this->field['field_name'];
    $entity = field_test_entity_test_load($eid, $evid);
    foreach ($available_languages as $langcode => $value) {
      $passed = isset($entity->{$field_name}[$langcode]) && $entity->{$field_name}[$langcode][0]['value'] == $value + 1;
      $this->assertTrue($passed, t('The @language translation for revision @revision was correctly stored', array('@language' => $langcode, '@revision' => $entity->ftvid)));
    }
  }
}

/**
 * Unit test class for field bulk delete and batch purge functionality.
 */
class FieldBulkDeleteTestCase extends FieldTestCase {
  protected $field;

  public static function getInfo() {
    return array(
      'name' => 'Field bulk delete tests',
      'description' => 'Bulk delete fields and instances, and clean up afterwards.',
      'group' => 'Field API',
    );
  }

  /**
   * Convenience function for Field API tests.
   *
   * Given an array of potentially fully-populated entities and an
   * optional field name, generate an array of stub entities of the
   * same fieldable type which contains the data for the field name
   * (if given).
   *
   * @param $entity_type
   *   The entity type of $entities.
   * @param $entities
   *   An array of entities of type $entity_type.
   * @param $field_name
   *   Optional; a field name whose data should be copied from
   *   $entities into the returned stub entities.
   * @return
   *   An array of stub entities corresponding to $entities.
   */
  function _generateStubEntities($entity_type, $entities, $field_name = NULL) {
    $stubs = array();
    foreach ($entities as $entity) {
      $stub = entity_create_stub_entity($entity_type, entity_extract_ids($entity_type, $entity));
      if (isset($field_name)) {
        $stub->{$field_name} = $entity->{$field_name};
      }
      $stubs[] = $stub;
    }
    return $stubs;
  }

  function setUp() {
    parent::setUp('field_test');

    // Clean up data from previous test cases.
    $this->fields = array();
    $this->instances = array();

    // Create two bundles.
    $this->bundles = array('bb_1' => 'bb_1', 'bb_2' => 'bb_2');
    foreach ($this->bundles as $name => $desc) {
      field_test_create_bundle($name, $desc);
    }

    // Create two fields.
    $field = array('field_name' => 'bf_1', 'type' => 'test_field', 'cardinality' => 1);
    $this->fields[] = field_create_field($field);
    $field = array('field_name' => 'bf_2', 'type' => 'test_field', 'cardinality' => 4);
    $this->fields[] = field_create_field($field);

    // For each bundle, create an instance of each field, and 10
    // entities with values for each field.
    $id = 0;
    $this->entity_type = 'test_entity';
    foreach ($this->bundles as $bundle) {
      foreach ($this->fields as $field) {
        $instance = array(
          'field_name' => $field['field_name'],
          'entity_type' => $this->entity_type,
          'bundle' => $bundle,
          'widget' => array(
            'type' => 'test_field_widget',
          )
        );
        $this->instances[] = field_create_instance($instance);
      }

      for ($i = 0; $i < 10; $i++) {
        $entity = field_test_create_stub_entity($id, $id, $bundle);
        foreach ($this->fields as $field) {
          $entity->{$field['field_name']}[LANGUAGE_NONE] = $this->_generateTestFieldValues($field['cardinality']);
        }
        $this->entities[$id] = $entity;
        field_attach_insert($this->entity_type, $entity);
        $id++;
      }
    }
  }

  /**
   * Verify that deleting an instance leaves the field data items in
   * the database and that the appropriate Field API functions can
   * operate on the deleted data and instance.
   *
   * This tests how EntityFieldQuery interacts with
   * field_delete_instance() and could be moved to FieldCrudTestCase,
   * but depends on this class's setUp().
   */
  function testDeleteFieldInstance() {
    $bundle = reset($this->bundles);
    $field = reset($this->fields);

    // There are 10 entities of this bundle.
    $query = new EntityFieldQuery();
    $found = $query
      ->fieldCondition($field)
      ->entityCondition('bundle', $bundle)
      ->execute();
    $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found before deleting');

    // Delete the instance.
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
    field_delete_instance($instance);

    // The instance still exists, deleted.
    $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
    $this->assertEqual(count($instances), 1, 'There is one deleted instance');
    $this->assertEqual($instances[0]['bundle'], $bundle, 'The deleted instance is for the correct bundle');

    // There are 0 entities of this bundle with non-deleted data.
    $query = new EntityFieldQuery();
    $found = $query
      ->fieldCondition($field)
      ->entityCondition('bundle', $bundle)
      ->execute();
    $this->assertTrue(!isset($found['test_entity']), 'No entities found after deleting');

    // There are 10 entities of this bundle when deleted fields are allowed, and
    // their values are correct.
    $query = new EntityFieldQuery();
    $found = $query
      ->fieldCondition($field)
      ->entityCondition('bundle', $bundle)
      ->deleted(TRUE)
      ->execute();
    field_attach_load($this->entity_type, $found[$this->entity_type], FIELD_LOAD_CURRENT, array('field_id' => $field['id'], 'deleted' => 1));
    $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found after deleting');
    foreach ($found['test_entity'] as $id => $entity) {
      $this->assertEqual($this->entities[$id]->{$field['field_name']}, $entity->{$field['field_name']}, "Entity $id with deleted data loaded correctly");
    }
  }

  /**
   * Verify that field data items and instances are purged when an
   * instance is deleted.
   */
  function testPurgeInstance() {
    field_test_memorize();

    $bundle = reset($this->bundles);
    $field = reset($this->fields);

    // Delete the instance.
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
    field_delete_instance($instance);

    // No field hooks were called.
    $mem = field_test_memorize();
    $this->assertEqual(count($mem), 0, 'No field hooks were called');

    $batch_size = 2;
    for ($count = 8; $count >= 0; $count -= 2) {
      // Purge two entities.
      field_purge_batch($batch_size);

      // There are $count deleted entities left.
      $query = new EntityFieldQuery();
      $found = $query
        ->fieldCondition($field)
        ->entityCondition('bundle', $bundle)
        ->deleted(TRUE)
        ->execute();
      $this->assertEqual($count ? count($found['test_entity']) : count($found), $count, 'Correct number of entities found after purging 2');
    }

    // hook_field_delete() was called on a pseudo-entity for each entity. Each
    // pseudo entity has a $field property that matches the original entity,
    // but no others.
    $mem = field_test_memorize();
    $this->assertEqual(count($mem['field_test_field_delete']), 10, 'hook_field_delete was called for the right number of entities');
    $stubs = $this->_generateStubEntities($this->entity_type, $this->entities, $field['field_name']);
    $count = count($stubs);
    foreach ($mem['field_test_field_delete'] as $args) {
      $entity = $args[1];
      $this->assertEqual($stubs[$entity->ftid], $entity, 'hook_field_delete() called with the correct stub');
      unset($stubs[$entity->ftid]);
    }
    $this->assertEqual(count($stubs), $count-10, 'hook_field_delete was called with each entity once');

    // The instance still exists, deleted.
    $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
    $this->assertEqual(count($instances), 1, 'There is one deleted instance');

    // Purge the instance.
    field_purge_batch($batch_size);

    // The instance is gone.
    $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
    $this->assertEqual(count($instances), 0, 'The instance is gone');

    // The field still exists, not deleted, because it has a second instance.
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
    $this->assertTrue(isset($fields[$field['id']]), 'The field exists and is not deleted');
  }

  /**
   * Verify that fields are preserved and purged correctly as multiple
   * instances are deleted and purged.
   */
  function testPurgeField() {
    $field = reset($this->fields);

    // Delete the first instance.
    $instance = field_info_instance($this->entity_type, $field['field_name'], 'bb_1');
    field_delete_instance($instance);

    // Purge the data.
    field_purge_batch(10);

    // Purge again to purge the instance.
    field_purge_batch(0);

    // The field still exists, not deleted.
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
    $this->assertTrue(isset($fields[$field['id']]) && !$fields[$field['id']]['deleted'], 'The field exists and is not deleted');

    // Delete the second instance.
    $instance = field_info_instance($this->entity_type, $field['field_name'], 'bb_2');
    field_delete_instance($instance);

    // Purge the data.
    field_purge_batch(10);

    // The field still exists, deleted.
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
    $this->assertTrue(isset($fields[$field['id']]) && $fields[$field['id']]['deleted'], 'The field exists and is deleted');

    // Purge again to purge the instance and the field.
    field_purge_batch(0);

    // The field is gone.
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
    $this->assertEqual(count($fields), 0, 'The field is purged.');
  }
}

/**
 * Tests entity properties.
 */
class EntityPropertiesTestCase extends FieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Entity properties',
      'description' => 'Tests entity properties.',
      'group' => 'Entity API',
    );
  }

  function setUp() {
    parent::setUp('field_test');
  }

  /**
   * Tests label key and label callback of an entity.
   */
  function testEntityLabel() {
    $entity_types = array(
      'test_entity_no_label',
      'test_entity_label',
      'test_entity_label_callback',
    );

    $entity = field_test_create_stub_entity();

    foreach ($entity_types as $entity_type) {
      $label = entity_label($entity_type, $entity);

      switch ($entity_type) {
        case 'test_entity_no_label':
          $this->assertFalse($label, 'Entity with no label property or callback returned FALSE.');
          break;

        case 'test_entity_label':
          $this->assertEqual($label, $entity->ftlabel, 'Entity with label key returned correct label.');
          break;

        case 'test_entity_label_callback':
          $this->assertEqual($label, 'label callback ' . $entity->ftlabel, 'Entity with label callback returned correct label.');
          break;
      }
    }
  }
}