This file is indexed.

/usr/share/pyshared/lazr/restful/docs/webservice-declarations.txt is in python-lazr.restful 0.19.3-0ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
Web Service API Declarations
****************************

You can easily create a web service by tagging your content interfaces
with some decorators. From this tagging the web service API will be
created automatically.

Exporting the data model
========================

The LAZR Web Service data model consists of entries and collection (see
webservice.txt for all the details). Entries support the IEntry
interface and are basically a single resource exported. Think something
like a bug, a person, an article, etc. Collections are a set of
resources of the same types, think something like the set of bugs,
persons, teams, articles, etc.

Exporting entries
=================

Only entries are exported as data. You can mark that one of your content
interface is exported on the web service as an entry, by using the
export_as_webservice_entry() declaration.

You can mark the fields that should be part of the entry data model by
using the exported() wrapper. It takes an optional 'exported_as' parameter
that can be used to change the name under which the field will be
exported.

For example, here we declare that the IBook interface is exported as an
entry on the  web service. It exports the title, author, and base_price
field, but not the inventory_number field.

    >>> from zope.interface import Interface
    >>> from zope.schema import Text, TextLine, Float, List
    >>> from lazr.restful.declarations import (
    ...     export_as_webservice_entry, exported)
    >>> class IBook(Interface):
    ...     """A simple book data model."""
    ...     export_as_webservice_entry()
    ...
    ...     title = exported(TextLine(title=u'The book title'))
    ...
    ...     author = exported(TextLine(title=u"The book's author."))
    ...
    ...     base_price = exported(Float(
    ...         title=u"The regular price of the book."),
    ...         exported_as='price')
    ...
    ...     inventory_number = TextLine(title=u'The inventory part number.')

These declarations add tagged values to the original interface elements.
The tags are in the lazr.restful namespace and are dictionaries of
elements.

    >>> from pprint import pformat
    >>> def print_export_tag(element):
    ...     """Print the content of the 'lazr.restful.exported' tag."""
    ...     def format_value(value):
    ...         if isinstance(value, dict):
    ...             return pformat(value, width=40)
    ...         else:
    ...             return repr(value)
    ...     tag = element.queryTaggedValue('lazr.restful.exported')
    ...     if tag is None:
    ...         print "tag 'lazr.restful.exported' is not present"
    ...     else:
    ...         print "\n".join(
    ...             "%s: %s" %(key, format_value(value))
    ...             for key, value in sorted(tag.items()))
    >>> print_export_tag(IBook)
    _as_of_was_used: False
    contributes_to: None
    exported: True
    plural_name: 'books'
    publish_web_link: True
    singular_name: 'book'
    type: 'entry'
    >>> print_export_tag(IBook['title'])
    as: 'title'
    original_name: 'title'
    type: 'field'
    >>> print_export_tag(IBook['author'])
    as: 'author'
    original_name: 'author'
    type: 'field'
    >>> print_export_tag(IBook['base_price'])
    as: 'price'
    original_name: 'base_price'
    type: 'field'
    >>> print_export_tag(IBook['inventory_number'])
    tag 'lazr.restful.exported' is not present

Only IField can be exported as entry fields.

    >>> from zope.interface import Attribute
    >>> class Foo(Interface):
    ...     export_as_webservice_entry()
    ...     not_a_field = exported(Attribute('A standard attribute'))
    Traceback (most recent call last):
      ...
    TypeError: exported() can only be used on IFields.

Object fields cannot be exported because they cause validation problems.

    >>> from zope.schema import Object
    >>> class UsesIObject(Interface):
    ...     export_as_webservice_entry()
    ...     object = exported(Object(schema=Interface))
    Traceback (most recent call last):
    TypeError: Object exported; use Reference instead.

Instead you should use Reference, a subclass of Object designed to
avoid the validation problems.

    >>> from lazr.restful.fields import Reference
    >>> class UsesIReference(Interface):
    ...     export_as_webservice_entry()
    ...     object = exported(Reference(schema=Interface))

In the same vein, export_as_webservice_entry() can only be used on
Interface.

    >>> class NotAnInterface(object):
    ...     export_as_webservice_entry()
    Traceback (most recent call last):
      ...
    TypeError: export_as_webservice_entry() can only be used on an
    interface.

And from within a class declaration.

    >>> export_as_webservice_entry()
    Traceback (most recent call last):
      ...
    TypeError: export_as_webservice_entry() can only be used from within
    an interface definition.

publish_web_link
-------------

If each webservice entry corresponds to some page on a website,
lazr.restful will publish a web_link for each entry, pointing to the
corresponding website page. For a given entry type, you can suppress
this by passing in False for the `publish_web_link` argument to
`export_as_webservice_entry`.

    >>> from zope.interface import Attribute
    >>> class INotOnTheWebsite(Interface):
    ...     export_as_webservice_entry(publish_web_link=False)
    ...     field = exported(TextLine(title=u"A field."))
    >>> print_export_tag(INotOnTheWebsite)
    _as_of_was_used: False
    contributes_to: None
    ...
    publish_web_link: False
    ...

Exporting a collection
======================

Collections scoped to an entry are exported simply by using
exported() on the CollectionField containing the scoped collection
items:

    >>> class ISimpleComment(Interface):
    ...     """A simple comment."""
    ...     comment = TextLine(title=u'Comment')

    >>> from zope.schema import Object
    >>> from lazr.restful.fields import CollectionField
    >>> class IBookWithComments(IBook):
    ...     """A book with some comments."""
    ...     export_as_webservice_entry()
    ...
    ...     comments = exported(CollectionField(
    ...         value_type=Object(schema=ISimpleComment)))

Top-level collections are different though, they are exported by using the
export_as_webservice_collection() in the ``Set`` class. The method that returns
all of the collection items must be tagged with @collection_default_content
decorator.

    >>> from lazr.restful.declarations import (
    ...     export_as_webservice_collection, collection_default_content,
    ...     REQUEST_USER)
    >>> class IBookSet(Interface):
    ...     """Set of all the books in the system."""
    ...     export_as_webservice_collection(IBook)
    ...
    ...     @collection_default_content()
    ...     def getAllBooks():
    ...         """Return an iterator over all the books."""

In case the method to call requires parameters, the value to use can be
specified using parameters to the decorator constructor. There is a
special REQUEST_USER marker that can be used to specify that this
parameter should contain the logged in user.

    >>> class ICheckedOutBookSet(Interface):
    ...     """Give access to the checked out books."""
    ...     export_as_webservice_collection(IBook)
    ...
    ...     @collection_default_content(user=REQUEST_USER, title='')
    ...     def getByTitle(title, user):
    ...         """Return checked out books.
    ...         :param title: String to match against the book title.
    ...             The empty string matches everything.
    ...         :param user: The user who should have checked the book out.
    ...         """

Like for entries, this adds keys in the 'lazr.restful.exported'
tagged value.

    >>> print_export_tag(IBookSet)
    collection_default_content: {None: ('getAllBooks', {})}
    collection_entry_schema: <InterfaceClass __builtin__.IBook>
    type: 'collection'

    >>> print_export_tag(ICheckedOutBookSet)
    collection_default_content: {None: ('getByTitle',
            {'title': '',
             'user': <class '...REQUEST_USER'>})}
    collection_entry_schema: <InterfaceClass __builtin__.IBook>
    type: 'collection'

The entry schema for a collection must be provided and must be an
interface:

    >>> class MissingEntrySchema(Interface):
    ...     export_as_webservice_collection()
    Traceback (most recent call last):
      ...
    TypeError: export_as_webservice_collection() takes exactly 1
    argument (0 given)

    >>> class InvalidEntrySchema(Interface):
    ...     export_as_webservice_collection("not an interface")
    Traceback (most recent call last):
      ...
    TypeError: entry_schema must be an interface.

It's an error to try to export a collection without marking a method as
exporting the default content.

    >>> class IDummyInterface(Interface):
    ...     pass

    >>> class MissingDefaultContent(Interface):
    ...     export_as_webservice_collection(IDummyInterface)
    Traceback (most recent call last):
      ...
    TypeError: export_as_webservice_collection() is missing a method
    tagged with @collection_default_content.

As it is an error, to mark more than one method:

    >>> class TwoDefaultContent(Interface):
    ...     export_as_webservice_collection(IDummyInterface)
    ...     @collection_default_content()
    ...     def getAll1():
    ...         """A first getAll()."""
    ...     @collection_default_content()
    ...     def getAll2():
    ...         """Another getAll()."""
    Traceback (most recent call last):
      ...
    TypeError: Only one method can be marked with
    @collection_default_content for version '(earliest version)'.

export_as_webservice_collection() can only be used on Interface.

    >>> class NotAnInterface(object):
    ...     export_as_webservice_collection(IDummyInterface)
    Traceback (most recent call last):
      ...
    TypeError: export_as_webservice_collection() can only be used on an
    interface.

And from within a class declaration.

    >>> export_as_webservice_collection(IDummyInterface)
    Traceback (most recent call last):
      ...
    TypeError: export_as_webservice_collection() can only be used from
    within an interface definition.

collection_default_content() can only be used from within an Interface
declaration:

    >>> @collection_default_content()
    ... def a_function(): pass
    Traceback (most recent call last):
      ...
    TypeError: @collection_default_content can only be used from within
    an interface definition.

And the interface must have been exported as a collection:

    >>> class NotExported(Interface):
    ...     export_as_webservice_entry()
    ...     @collection_default_content()
    ...     def a_function(): pass
    Traceback (most recent call last):
      ...
    TypeError: @collection_default_content can only be used from within an
    interface exported as a collection.

Exporting methods
=================

Entries and collections can publish named operations on the
webservice. Every named operation corresponds to some method defined
on the content interface. To publish a method as a named operation,
you tag it with special decorators.

Four different decorators are used based on the kind of method
exported.

1. @export_read_operation

    This will mark the method as available as a GET operation on the
    exported resource.

2. @export_write_operation

    This will mark the method as available as a POST operation on the
    exported resource.

3. @export_factory_operation(schema, fields)

    Like the @export_write_operation decorator, this will mark the
    method as available as a POST operation on the exported resource,
    with the addition that the result of the method is a new object and
    the HTTP status code will be set appropriately.

    This decorator takes as parameters the schema of the object it is
    creating and the name of the fields in the schema that are passed as
    parameters.

4. @export_destructor_operation

    This will mark the method as available as a DELETE operation on the
    exported resource.

The specification of the web service's acceptable method parameters
should be described using the @operation_parameters decorator, which
takes normal IField instances.

When an operation returns an object that's exposed as a resource, you
should describe its return value with the
@operation_returns_collection_of and @operation_returns_entry
decorators. Both decorators take an interface that has been exposed as
an entry. @operation_returns_entry is used when the operation returns
a single entry; @operation_returns_collection_of is used when the
operation returns a collection of entries.

    >>> from lazr.restful.declarations import (
    ...     export_operation_as, export_factory_operation,
    ...     export_read_operation, operation_parameters,
    ...     operation_returns_entry, operation_returns_collection_of,
    ...     rename_parameters_as)
    >>> from lazr.restful.interface import copy_field
    >>> class IBookSetOnSteroids(IBookSet):
    ...     """IBookSet supporting some methods."""
    ...     export_as_webservice_collection(IBook)
    ...
    ...     @collection_default_content()
    ...     @operation_parameters(
    ...         text=copy_field(IBook['title'], title=u'Text to search for.'))
    ...     @operation_returns_collection_of(IBook)
    ...     @export_read_operation()
    ...     def searchBookTitles(text):
    ...         """Return list of books whose titles contain 'text'."""
    ...
    ...     @operation_parameters(
    ...         text=copy_field(IBook['title'], title=u'Text to search for.'))
    ...     @operation_returns_entry(IBook)
    ...     @export_read_operation()
    ...     def bestMatch(text):
    ...         """Return the best match for books containing 'text'."""
    ...
    ...     @export_operation_as('create_book')
    ...     @rename_parameters_as(base_price='price')
    ...     @export_factory_operation(
    ...         IBook, ['author', 'base_price', 'title'])
    ...     def new(author, base_price, title):
    ...         """Create a new book."""

In the above example, the exported new() method demonstrates two
features to support having different names on the web service than in
the internal API.  It is possible to export a method under a different
name by using the @export_operation_as decorator which takes the name
under which the method should be exported.

The @rename_parameters_as decorator can be used to rename the method
parameters on the web service.  In the example, the 'base_price' parameter
will be called 'price' when exported on the web service.

When some required parameters of the method should not be provided by
the webservice client, it is possible to use the @call_with decorator to
specify the value to use. The special REQUEST_USER marker can be used to
specify that this parameter should contain the logged in user.

    >>> from lazr.restful.declarations import (
    ...     call_with, export_destructor_operation, export_write_operation,
    ...     REQUEST_USER)
    >>> class IBookOnSteroids(IBook):
    ...     """IBook with some methods."""
    ...     export_as_webservice_entry()
    ...
    ...     @call_with(who=REQUEST_USER, kind='normal')
    ...     @export_write_operation()
    ...     def checkout(who, kind):
    ...         """Check this book out."""
    ...
    ...     @export_destructor_operation()
    ...     def destroy():
    ...         """Destroy the book."""

Like other declarations, these will add tagged values to the interface
method. We didn't have to specify the return type for the factory
operation, because a factory operation always returns the
newly-created object.

    >>> print_export_tag(IBookSetOnSteroids['new'])
    as: 'create_book'
    call_with: {}
    creates: <...IBook...>
    params: {'author': <...TextLine...>,
        'base_price': <...Float...>,
        'title': <...TextLine...>}
    return_type: <lazr.restful._operation.ObjectLink object...>
    type: 'factory'

We did specify the return type for the 'searchBookTitles' method: it
returns a collection.

    >>> print_export_tag(IBookSetOnSteroids['searchBookTitles'])
    as: 'searchBookTitles'
    call_with: {}
    params: {'text': <...TextLine...>}
    return_type: <lazr.restful.fields.CollectionField object...>
    type: 'read_operation'

The 'bestMatch' method returns an entry.

    >>> print_export_tag(IBookSetOnSteroids['bestMatch'])
    as: 'bestMatch'
    call_with: {}
    params: {'text': <...TextLine...>}
    return_type: <lazr.restful.fields.Reference object...>
    type: 'read_operation'

The 'checkout' method doesn't return anything.

    >>> print_export_tag(IBookOnSteroids['checkout'])
    as: 'checkout'
    call_with: {'kind': 'normal', 'who': <class '...REQUEST_USER'>}
    params: {}
    return_type: None
    type: 'write_operation'

Parameters that are not renamed are exported under the same name:

    >>> for name, param in sorted(IBookSetOnSteroids['new'].getTaggedValue(
    ...     'lazr.restful.exported')['params'].items()):
    ...     print "%s: %s" % (name, param.__name__)
    author: author
    base_price: price
    title: title

It is possible to use @operation_parameters with
@export_factory_operation to specify parameters that are not part of the
schema.

    >>> class ComplexBookFactory(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     @operation_parameters(collection=TextLine())
    ...     @export_factory_operation(IBook, ['author', 'title'])
    ...     def create_book(author, title, collection):
    ...         """Create a book in a collection."""

    >>> print_export_tag(ComplexBookFactory['create_book'])
    as: 'create_book'
    call_with: {}
    creates: <...IBook...>
    params: {'author': <...TextLine...>,
        'collection': <...TextLine...>,
        'title': <...TextLine...>}
    return_type: <lazr.restful._operation.ObjectLink object...>
    type: 'factory'

Default values and required parameters
--------------------------------------

Parameters default and required attributes are set automatically based
on the method signature.

    >>> class ComplexParameterDefinition(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     @operation_parameters(
    ...         required1=TextLine(),
    ...         required2=TextLine(default=u'Not required'),
    ...         optional1=TextLine(required=True),
    ...         optional2=TextLine(),
    ...         )
    ...     @export_read_operation()
    ...     def a_method(required1, required2, optional1='Default',
    ...                  optional2='Default2'):
    ...         """Method demonstrating how required/default are set."""

In this example, the required1 definition will be automatically
considered required.

    >>> param_defs = ComplexParameterDefinition['a_method'].getTaggedValue(
    ...     'lazr.restful.exported')['params']
    >>> param_defs['required1'].required
    True

But required2 will not be considered required because a default value
was provided.

    >>> param_defs['required2'].required
    False

NOTE: It's not possible to make an optional parameter required on the
webservice. In the above case, required=True was specified on
"optional1", but that will be overridden. The reason for that is that by
default required is always True, so it's not possible to distinguish
between the case where required was set to True, and required is True
because it's the default value.

    >>> param_defs['optional1'].required
    False
    >>> param_defs['optional1'].default
    u'Default'

And optional2 was exported with the same default than the method:

    >>> param_defs['optional2'].required
    False
    >>> param_defs['optional2'].default
    u'Default2'

Error handling
--------------

All these decorators can only be used from within an interface
definition:

    >>> @export_operation_as('test')
    ... def a_method1(self): pass
    Traceback (most recent call last):
      ...
    TypeError: export_operation_as() can only be used from within an interface
    definition.

    >>> @export_read_operation()
    ... def another_method(self): pass
    Traceback (most recent call last):
      ...
    TypeError: export_read_operation() can only be used from within an
    interface definition.

An error is also reported if not enough parameters are defined as
exported:

    >>> class MissingParameter(Interface):
    ...     export_as_webservice_entry()
    ...     @call_with(param1=1)
    ...     @operation_parameters(
    ...         param2=TextLine())
    ...     @export_read_operation()
    ...     def a_method(param1, param2, param3, param4): pass
    Traceback (most recent call last):
      ...
    TypeError: method "a_method" is missing definitions for parameter(s)
    exported in version "(earliest version)": param3, param4

Defining a parameter not available on the method also results in an
error:

    >>> class BadParameter(Interface):
    ...     export_as_webservice_entry()
    ...     @operation_parameters(
    ...         no_such_param=TextLine())
    ...     @export_read_operation()
    ...     def a_method(): pass
    Traceback (most recent call last):
      ...
    TypeError: method "a_method" doesn't have the following exported parameters
    in version "(earliest version)": no_such_param.

But that's not a problem if the exported method actually takes arbitrary
keyword parameters:

    >>> class AnyParameter(Interface):
    ...     export_as_webservice_entry()
    ...     @operation_parameters(
    ...         param1=TextLine())
    ...     @export_read_operation()
    ...     def a_method(**kwargs): pass

When using @export_factory_operation, TypeError will also be raised if
one of the field doesn't exists in the schema:

    >>> class MissingParameter(Interface):
    ...     export_as_webservice_entry()
    ...     @export_factory_operation(IBook, ['no_such_field'])
    ...     def a_method(): pass
    Traceback (most recent call last):
      ...
    TypeError: IBook doesn't define 'no_such_field'.

Or if the field name doesn't represent a field:

    >>> class NotAField(Interface):
    ...     export_as_webservice_entry()
    ...     @export_factory_operation(IBookOnSteroids, ['checkout'])
    ...     def a_method(): pass
    Traceback (most recent call last):
      ...
    TypeError: IBookOnSteroids.checkout doesn't provide IField.

Or if @operation_parameters redefine a field specified in the factory:

    >>> class Redefinition(Interface):
    ...     export_as_webservice_entry()
    ...     @operation_parameters(title=TextLine())
    ...     @export_factory_operation(IBookOnSteroids, ['title'])
    ...     def create_book(title): pass
    Traceback (most recent call last):
      ...
    TypeError: 'title' parameter is already defined.

All parameters definitions must be schema fields:

    >>> class BadParameterDefinition(Interface):
    ...     export_as_webservice_entry()
    ...     @operation_parameters(a_param=object())
    ...     @export_read_operation()
    ...     def a_method(): pass
    Traceback (most recent call last):
      ...
    TypeError: export definition of "a_param" in method "a_method" must
    provide IField: <object...>

Renaming a parameter that wasn't defined results in an error:

    >>> class NonExistentParameter(Interface):
    ...     @rename_parameters_as(param1='name', param2='name2')
    ...     @operation_parameters(param1=TextLine())
    ...     @export_read_operation()
    ...     def a_method(param1): pass
    Traceback (most recent call last):
      ...
    TypeError: rename_parameters_as(): no "param2" parameter is exported.

Trying to use @rename_parameters_as without exporting the method also
results in an error.

    >>> class MissingMethodExport(Interface):
    ...     @rename_parameters_as(a_param='name')
    ...     def a_method(): pass
    Traceback (most recent call last):
      ...
    TypeError: "a_method" isn't exported on the webservice.

The decorators @operation_returns_entry and
@operation_returns_collection_of will only accept an IInterface as
argument.

    >>> class ReturnOtherThanInterface(Interface):
    ...     export_as_webservice_entry()
    ...     @operation_returns_entry("not-an-interface")
    ...     @export_read_operation()
    ...     def a_method(**kwargs): pass
    Traceback (most recent call last):
    ...
    TypeError: Entry type not-an-interface does not provide IInterface.

    >>> class ReturnOtherThanInterface(Interface):
    ...     export_as_webservice_entry()
    ...     @operation_returns_collection_of("not-an-interface")
    ...     @export_read_operation()
    ...     def a_method(**kwargs): pass
    Traceback (most recent call last):
    ...
    TypeError: Collection value type not-an-interface does not
    provide IInterface.

Exporting exceptions
====================

When a method raises an exception, the default is to report the error as
'500 Internal Server Error'. In many cases, that's not the case and one
of the 4XX error would be better.

For Python 2.6 or higher, or for annotating an already existing exception,
you can use error_status.

In Python 2.6, you would spell this as follows::

    from lazr.restful.declarations import error_status
    @error_status(400)
    class InvalidDemo(Exception):
        """An example exception"""

In earlier Pythons it is still usable.

    >>> from lazr.restful.declarations import error_status
    >>> class InvalidDemo(Exception):
    ...     """An example exception"""
    ...
    >>> ignore = error_status(400)(InvalidDemo)

The function sets the __lazr_webservice_error__ attribute on the
exception, which will be used by the view handling the exception.

    >>> InvalidDemo.__lazr_webservice_error__
    400

The function raises an exception if it is used for something that already has
a conflicting __lazr_webservice_error__ attribute.

    >>> ignore = error_status(400)(InvalidDemo) # OK
    >>> InvalidDemo.__lazr_webservice_error__
    400
    >>> error_status(401)(InvalidDemo) # Not OK
    Traceback (most recent call last):
    ...
    ValueError: ('Exception already has an error status', 400)

It also raises an exception if it is used on something that is not an
Exception.

    >>> error_status(400)(object)
    Traceback (most recent call last):
    ...
    TypeError: Annotated value must be an exception class.

Exceptions can be also be tagged internally to the class definition with the
webservice_error() declaration to state the proper HTTP status code to use for
that kind of error.

    >>> from lazr.restful.declarations import webservice_error
    >>> class InvalidEmail(Exception):
    ...     """Error happening when the email is not valid."""
    ...     webservice_error(400)

As with error_status, the directive sets the __lazr_webservice_error__
attribute on the exception, which will be used by the view handling the
exception.

    >>> InvalidEmail.__lazr_webservice_error__
    400

Using that directive outside of a class declaration is an error:

    >>> webservice_error(402)
    Traceback (most recent call last):
      ...
    TypeError: webservice_error() can only be used from within an
    exception definition.

Export and inheritance
======================

A child interface inherits the markup of its ancestors, even when the
base interface isn't exported itself.

    >>> class IHasName(Interface):
    ...     name = exported(TextLine())
    ...
    ...     @operation_parameters(new_name=TextLine())
    ...     @export_write_operation()
    ...     def rename(new_name):
    ...         """Rename the object."""

    >>> class IUser(IHasName):
    ...     export_as_webservice_entry()
    ...
    ...     nickname = exported(TextLine())
    ...
    ...     @operation_parameters(to=Object(IHasName), msg=TextLine())
    ...     @export_write_operation()
    ...     def talk_to(to, msg):
    ...         """Sends a message to another named object."""

    >>> for name in sorted(IUser.names(True)):
    ...     print '== %s ==' % name
    ...     print_export_tag(IUser[name])
    == name ==
    as: 'name'
    original_name: 'name'
    type: 'field'
    == nickname ==
    as: 'nickname'
    original_name: 'nickname'
    type: 'field'
    == rename ==
    as: 'rename'
    call_with: {}
    params: {'new_name': <...TextLine...>}
    return_type: None
    type: 'write_operation'
    == talk_to ==
    as: 'talk_to'
    call_with: {}
    params: {'msg': <...TextLine...>,
        'to': <...Object...>}
    return_type: None
    type: 'write_operation'


Contributing interfaces
=======================

It is possible to mix multiple interfaces into a single exported entry. This
is specially useful when you want to export fields/methods that belong to
adapters for your entry's class instead of to the class itself. For example,
we can have an IDeveloper interface contributing to IUser.

    >>> class IDeveloper(Interface):
    ...     export_as_webservice_entry(contributes_to=[IUser])
    ...
    ...     programming_languages = exported(List(
    ...         title=u'Programming Languages spoken by this developer'))

This will cause all the fields/methods of IDeveloper to be exported as part of
the IBook entry instead of exporting a new entry for IDeveloper. For this to
work you just need to ensure an object of the exported entry type can be
adapted into the contributing interface (e.g. an IUser object can be adapted
into IDeveloper).

    >>> print_export_tag(IDeveloper)
    _as_of_was_used: False
    contributes_to: [<InterfaceClass __builtin__.IUser>]
    exported: True
    plural_name: 'developers'
    publish_web_link: True
    singular_name: 'developer'
    type: 'entry'

To learn how this works, see ContributingInterfacesTestCase in
tests/test_declarations.py.


Generating the webservice
=========================

Setup
-----

Before we can continue, we must define a web service configuration
object. Each web service needs to have one of these registered
utilities providing basic information about the web service. This one
is just a dummy.

    >>> from lazr.restful.testing.helpers import TestWebServiceConfiguration
    >>> from zope.component import provideUtility
    >>> from lazr.restful.interfaces import IWebServiceConfiguration
    >>> class MyWebServiceConfiguration(TestWebServiceConfiguration):
    ...     active_versions = ["beta", "1.0", "2.0", "3.0"]
    ...     last_version_with_mutator_named_operations = "1.0"
    ...     first_version_with_total_size_link = "2.0"
    ...     code_revision = "1.0b"
    ...     default_batch_size = 50
    >>> provideUtility(MyWebServiceConfiguration(), IWebServiceConfiguration)

We must also set up the ability to create versioned requests. This web
service has four versions: 'beta', '1.0', '2.0', and '3.0'.  We'll
need a marker interface for every version, registered as a utility
under the name of the version.

Each version interface subclasses the previous version's
interface. This lets a request use a resource definition for the
previous version if it hasn't changed since then.

    >>> from zope.component import getSiteManager
    >>> from lazr.restful.interfaces import IWebServiceVersion
    >>> class ITestServiceRequestBeta(IWebServiceVersion):
    ...     pass
    >>> class ITestServiceRequest10(ITestServiceRequestBeta):
    ...     pass
    >>> class ITestServiceRequest20(ITestServiceRequest10):
    ...     pass
    >>> class ITestServiceRequest30(ITestServiceRequest20):
    ...     pass
    >>> sm = getSiteManager()
    >>> for marker, name in [(ITestServiceRequestBeta, 'beta'),
    ...                      (ITestServiceRequest10, '1.0'),
    ...                      (ITestServiceRequest20, '2.0'),
    ...                      (ITestServiceRequest30, '3.0')]:
    ...     sm.registerUtility(marker, IWebServiceVersion, name=name)

    >>> from lazr.restful.testing.webservice import FakeRequest
    >>> request = FakeRequest(version='beta')


Entry
-----

The webservice can be generated from tagged interfaces.  For every
version in the web service, generate_entry_interfaces() will create a
subinterface of IEntry containing a copy of those IField definitions
from the original interface that were tagged for export.

    >>> from lazr.restful.declarations import generate_entry_interfaces
    >>> [[version, entry_interface]] = generate_entry_interfaces(
    ...     IBook, [], 'beta')

The created interface is named with 'Entry' appended to the original
name, and is in the same module

    >>> entry_interface.__module__
    '__builtin__'
    >>> entry_interface.__name__
    'IBookEntry_beta'

The original interface docstring is copied over to the new interface:

    >>> entry_interface.__doc__
    'A simple book data model.'

It extends IEntry.

    >>> from lazr.restful.interfaces import IEntry
    >>> entry_interface.extends(IEntry)
    True

All fields tagged were copied to the new interface:

    >>> def dump_entry_interface(entry_interface):
    ...     for name, field in sorted(
    ...         entry_interface.namesAndDescriptions()):
    ...         print "%s: %s" % (name, field.__class__.__name__)
    >>> dump_entry_interface(entry_interface)
    author: TextLine
    price: Float
    title: TextLine

The field __name__ attribute contains the exported name:

    >>> print entry_interface['price'].__name__
    price

Associated with the interface through tags are automatically-generated
'singular' and 'plural' names for the interface.

    >>> from lazr.restful.interfaces import LAZR_WEBSERVICE_NAME
    >>> tags = entry_interface.queryTaggedValue(LAZR_WEBSERVICE_NAME)
    >>> print tags['singular']
    book
    >>> print tags['plural']
    books

It's an error to use generate_entry_interfaces() on an interface that
wasn't marked for export:

    >>> class SimpleNotExported(Interface):
    ...     """Interface not exported."""
    >>> generate_entry_interfaces(SimpleNotExported, [], 'beta')
    Traceback (most recent call last):
      ...
    TypeError: 'SimpleNotExported' isn't tagged for webservice export.

The interface must also be exported as an entry:

    >>> generate_entry_interfaces(IBookSet, [], 'beta')
    Traceback (most recent call last):
      ...
    TypeError: 'IBookSet' isn't exported as an entry.

The adapter can be generated using the generate_entry_adapters()
function, which takes the tagged content interface and the IEntry
subinterface as parameters.

    >>> from lazr.restful.declarations import generate_entry_adapters
    >>> entry_adapter_factories = generate_entry_adapters(
    ...     IBook, [], [('beta', entry_interface)])

generate_entry_adapters() generates an adapter for every version of
the web service (see a test for it below, in "Versioned
Services"). This web service only has one version, so there's only one
adapter.

    >>> [factory] = entry_adapter_factories
    >>> print factory.version
    beta
    >>> entry_adapter_factory = factory.object

The generated adapter provides the webservice interface:

    >>> entry_interface.implementedBy(entry_adapter_factory)
    True

The resulting class is named based on the interface:

    >>> print entry_adapter_factory.__name__
    BookEntry_betaAdapter

Its docstring is also copied over from the original interface:

    >>> entry_adapter_factory.__doc__
    'A simple book data model.'

The resulting adapter has its schema attribute set to the exported
interface, and proxies all attributes to the underlying object.

    >>> from zope.interface.verify import verifyObject
    >>> from zope.interface import implements
    >>> class Book(object):
    ...     """Simple IBook implementation."""
    ...     implements(IBook)
    ...     def __init__(self, author, title, base_price,
    ...                  inventory_number):
    ...         self.author = author
    ...         self.title = title
    ...         self.base_price = base_price
    ...         self.inventory_number = inventory_number

Now we can turn a Book object into something that implements
IBookEntry.

    >>> entry_adapter = entry_adapter_factory(
    ...     Book(u'Aldous Huxley', u'Island', 10.0, '12345'),
    ...     request)

    >>> entry_adapter.schema is entry_interface
    True
    >>> verifyObject(entry_interface, entry_adapter)
    True
    >>> entry_adapter.author
    u'Aldous Huxley'
    >>> entry_adapter.price
    10.0
    >>> entry_adapter.title
    u'Island'

It's an error to call this function on an interface not exported on the
web service:

    >>> generate_entry_adapters(
    ...     SimpleNotExported, [], ('beta', entry_interface))
    Traceback (most recent call last):
      ...
    TypeError: 'SimpleNotExported' isn't tagged for webservice export.

Or exported as a collection:

    >>> generate_entry_adapters(IBookSet, [], ('beta', entry_interface))
    Traceback (most recent call last):
      ...
    TypeError: 'IBookSet' isn't exported as an entry.


Collection
----------

An ICollection adapter for content interface tagged as being exported as
collections on the webservice can be generated by using the
generate_collection_adapter() function.

    >>> from lazr.restful.interfaces import ICollection
    >>> from lazr.restful.declarations import (
    ...     generate_collection_adapter)

    >>> collection_adapter_factory = generate_collection_adapter(IBookSet)
    >>> ICollection.implementedBy(collection_adapter_factory)
    True

The find() method will return the result of calling the method tagged
with the @collection_default_content decorator.

    >>> class BookSet(object):
    ...     """Simple IBookSet implementation."""
    ...     implements(IBookSet)
    ...
    ...     def __init__(self, books=()):
    ...         self.books = books
    ...
    ...     def getAllBooks(self):
    ...         return self.books

    >>> collection_adapter = collection_adapter_factory(
    ...     BookSet(['A book', 'Another book']), request)

    >>> verifyObject(ICollection, collection_adapter)
    True

    >>> collection_adapter.find()
    ['A book', 'Another book']

The adapter's docstring is taken from the original interface.

    >>> collection_adapter.__doc__
    'Set of all the books in the system.'

If parameters were specified, they'll be passed in to the method by
find(). The REQUEST_USER marker value will be replaced by the logged in
user.

    >>> class CheckedOutBookSet(object):
    ...     """Simple ICheckedOutBookSet implementation."""
    ...     implements(ICheckedOutBookSet)
    ...
    ...     def getByTitle(self, title, user):
    ...         print '%s searched for checked out book matching "%s".' % (
    ...             user, title)

    >>> checked_out_adapter = generate_collection_adapter(
    ...     ICheckedOutBookSet)(CheckedOutBookSet(), request)

    >>> checked_out_adapter.find()
    A user searched for checked out book matching "".

It's an error to call this function on an interface not exported on the
web service:

    >>> generate_collection_adapter(SimpleNotExported)
    Traceback (most recent call last):
      ...
    TypeError: 'SimpleNotExported' isn't tagged for webservice export.

Or exported as an entry.

    >>> generate_collection_adapter(IBook)
    Traceback (most recent call last):
      ...
    TypeError: 'IBook' isn't exported as a collection.

Methods
-------

IResourceOperation adapters can be generated for exported methods by
using the generate_operation_adapter() function. Using it on a method
exported as a read operation will generate an IResourceGETOperation.

    >>> from lazr.restful.interfaces import IResourceGETOperation
    >>> from lazr.restful.declarations import (
    ...     generate_operation_adapter)

    >>> read_method_adapter_factory = generate_operation_adapter(
    ...     IBookSetOnSteroids['searchBookTitles'])
    >>> IResourceGETOperation.implementedBy(read_method_adapter_factory)
    True

The defined adapter is named GET_<interface>_<exported_name>_beta
and uses the ResourceOperation base class. The "_beta" indicates
that the adapter will be used in the earliest version of the web
service, and any subsequent versions, until a newer implementation
supercedes it.

    >>> from lazr.restful import ResourceOperation
    >>> read_method_adapter_factory.__name__
    'GET_IBookSetOnSteroids_searchBookTitles_beta'
    >>> issubclass(read_method_adapter_factory, ResourceOperation)
    True

The adapter's docstring is taken from the decorated method docstring.

    >>> read_method_adapter_factory.__doc__
    "Return list of books whose titles contain 'text'."

The adapter's params attribute contains the specification of the
parameters accepted by the operation.

    >>> from operator import attrgetter
    >>> def print_params(params):
    ...     """Print the name and type of the defined parameters."""
    ...     for param in sorted(params, key=attrgetter('__name__')):
    ...         print "%s: %s" % (param.__name__, param.__class__.__name__)
    >>> print_params(read_method_adapter_factory.params)
    text: TextLine

The call() method calls the underlying method and returns its result.

    >>> class BookSetOnSteroids(BookSet):
    ...     implements(IBookSetOnSteroids)
    ...
    ...     result = None
    ...
    ...     def searchBookTitles(self, text):
    ...         return self.result
    ...
    ...     def new(self, author, base_price, title):
    ...         return Book(author, title, base_price, "unknown")

Now we can create a fake request that invokes the named operation.

    >>> request = FakeRequest(version='beta')
    >>> read_method_adapter = read_method_adapter_factory(
    ...     BookSetOnSteroids(), request)
    >>> verifyObject(IResourceGETOperation, read_method_adapter)
    True
    >>> read_method_adapter.send_modification_event
    False

    >>> read_method_adapter.context.result = []

Since the method is declared as returning a list of objects, the
return value is a dictionary containing a batched list.

    >>> print read_method_adapter.call(text='')
    {"total_size": 0, "start": 0, "entries": []}

Methods exported as a write operations generates an adapter providing
IResourcePOSTOperation.

    >>> from lazr.restful.interfaces import IResourcePOSTOperation

    >>> write_method_adapter_factory = generate_operation_adapter(
    ...     IBookOnSteroids['checkout'])
    >>> IResourcePOSTOperation.implementedBy(write_method_adapter_factory)
    True

The generated adapter class name is POST_<interface>_<operation>_beta.

    >>> print write_method_adapter_factory.__name__
    POST_IBookOnSteroids_checkout_beta

The adapter's params property also contains the available parameters
(for which there are none in this case.)

    >>> print_params(write_method_adapter_factory.params)

    >>> class BookOnSteroids(Book):
    ...     implements(IBookOnSteroids)
    ...     def checkout(self, who, kind):
    ...         print "%s did a %s check out of '%s'." % (
    ...             who, kind, self.title)

    >>> write_method_adapter = write_method_adapter_factory(
    ...     BookOnSteroids(
    ...         'Aldous Huxley', 'The Doors of Perception', 8, 'unknown'),
    ...     FakeRequest())

    >>> verifyObject(IResourcePOSTOperation, write_method_adapter)
    True
    >>> write_method_adapter.send_modification_event
    True

The call() method invokes the exported method on the context object. In
this case, the underlying parameters were set using call_with. The
REQUEST_USER specification is replaced by the current user.

    >>> write_method_adapter.call()
    A user did a normal check out of 'The Doors of Perception'.
    'null'

Methods exported as a factory also generate an adapter providing
IResourcePOSTOperation.

    >>> factory_method_adapter_factory = generate_operation_adapter(
    ...     IBookSetOnSteroids['new'])
    >>> IResourcePOSTOperation.implementedBy(factory_method_adapter_factory)
    True

    >>> factory_method_adapter = factory_method_adapter_factory(
    ...     BookSetOnSteroids(), FakeRequest())
    >>> verifyObject(IResourcePOSTOperation, factory_method_adapter)
    True
    >>> factory_method_adapter.send_modification_event
    False

The generated adapter class name is also
POST_<interface>_<operation>_beta.

    >>> print write_method_adapter_factory.__name__
    POST_IBookOnSteroids_checkout_beta

The adapter's params property also contains the available parameters.

    >>> print_params(factory_method_adapter_factory.params)
    author: TextLine
    price: Float
    title: TextLine

Factory operations set the 201 Created status code and return the
URL to the newly created object. The body of the response will be empty.

(For the URL generation to work, we need to register an IAbsoluteURL
adapter and set the request as the current interaction.)

    >>> from urllib import quote
    >>> from zope.component import provideAdapter
    >>> from zope.traversing.browser.interfaces import IAbsoluteURL
    >>> from zope.publisher.interfaces.http import IHTTPApplicationRequest
    >>> class BookAbsoluteURL(object):
    ...     """Returns a believable absolute URL for a book."""
    ...     implements(IAbsoluteURL)
    ...
    ...     def __init__(self, context, request):
    ...         self.context = context
    ...         self.request = request
    ...
    ...     def __str__(self):
    ...         return ("http://api.example.org/books/" +
    ...                 quote(self.context.title))
    ...
    ...     __call__ = __str__
    >>> provideAdapter(BookAbsoluteURL,
    ...     [IBook, IHTTPApplicationRequest], IAbsoluteURL)

    >>> from zope.security.management import endInteraction, newInteraction
    >>> endInteraction()
    >>> newInteraction(factory_method_adapter.request)

    >>> factory_method_adapter.call(
    ...     author='Aldous Huxley', title="Eyeless in Gaza", price=10.5)
    u''
    >>> response = factory_method_adapter.request.response
    >>> response.status
    201
    >>> print response.headers['Location']
    http://api.example.org/books/Eyeless%20in%20Gaza

The generate_operation_adapter() function can only be called on an
IMethod marked for export:

    >>> generate_operation_adapter(IBook)
    Traceback (most recent call last):
      ...
    TypeError: <...IBook...> doesn't provide IMethod.

    >>> generate_operation_adapter(IBookSet['getAllBooks'])
    Traceback (most recent call last):
      ...
    TypeError: 'getAllBooks' isn't tagged for webservice export.

Methods exported as a destructor operations generates an adapter providing
IResourceDELETEOperation.

    >>> from lazr.restful.interfaces import IResourceDELETEOperation
    >>> destructor_method_adapter_factory = generate_operation_adapter(
    ...     IBookOnSteroids['destroy'])
    >>> IResourceDELETEOperation.implementedBy(
    ...     destructor_method_adapter_factory)
    True

The generated adapter class name is
DELETE_<interface>_<operation>_beta.

    >>> print destructor_method_adapter_factory.__name__
    DELETE_IBookOnSteroids_destroy_beta

Destructor
----------

A method can be designated as a destructor for the entry. Here, the
destroy() method is designated as the destructor for IHasText.

    >>> class IHasText(Interface):
    ...     export_as_webservice_entry()
    ...     text = exported(TextLine(readonly=True))
    ...
    ...     @export_destructor_operation()
    ...     def destroy():
    ...         pass
    >>> ignored = generate_entry_interfaces(IHasText, [], 'beta')

A destructor method cannot take any free arguments.

    >>> class IHasText(Interface):
    ...     export_as_webservice_entry()
    ...     text = exported(TextLine(readonly=True))
    ...
    ...     @export_destructor_operation()
    ...     @operation_parameters(argument=TextLine())
    ...     def destroy(argument):
    ...         pass
    Traceback (most recent call last):
    ...
    TypeError: A destructor method must take no non-fixed arguments.
    In version (earliest version), the "destroy" method takes 1:
    "argument".

    >>> class IHasText(Interface):
    ...     export_as_webservice_entry()
    ...     text = exported(TextLine(readonly=True))
    ...
    ...     @export_destructor_operation()
    ...     @call_with(argument="fixed value")
    ...     def destroy(argument):
    ...         pass
    >>> ignored = generate_entry_interfaces(IHasText, [], 'beta')

An entry cannot have more than one destructor.

    >>> from lazr.restful.declarations import export_destructor_operation
    >>> class IHasText(Interface):
    ...     export_as_webservice_entry()
    ...     text = exported(TextLine(readonly=True))
    ...
    ...     @export_destructor_operation()
    ...     def destroy():
    ...         pass
    ...
    ...     @export_destructor_operation()
    ...     def destroy2():
    ...         pass
    >>> generate_entry_interfaces(IHasText, [], 'beta')
    Traceback (most recent call last):
    ...
    TypeError: An entry can only have one destructor method for
    version (earliest version); destroy and destroy2 make two.

Mutators
--------

A method can be designated as a mutator for some field. Here, the
set_text() method is designated as the mutator for the 'text' field.

    >>> from lazr.restful.declarations import mutator_for
    >>> class IHasText(Interface):
    ...     export_as_webservice_entry()
    ...     text = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(text)
    ...     @operation_parameters(text=TextLine())
    ...     @export_write_operation()
    ...     def set_text(text):
    ...         pass

The implementation of set_text() applies a standardized transform to the
incoming text.

    >>> from zope.interface import implements
    >>> class HasText(object):
    ...     implements(IHasText);
    ...
    ...     def __init__(self):
    ...         self.text = ''
    ...
    ...     def set_text(self, text):
    ...         self.text = "!" + text + "!"

Generate the entry interface and adapter...

    >>> [hastext_entry_interface] = generate_entry_interfaces(
    ...     IHasText, [], 'beta')
    >>> [hastext_entry_adapter_factory] = generate_entry_adapters(
    ...     IHasText, [], [hastext_entry_interface])

    >>> obj = HasText()
    >>> print hastext_entry_adapter_factory.version
    beta
    >>> hastext_entry_adapter = hastext_entry_adapter_factory.object(
    ...     obj, request)

...and you'll have an object that invokes set_text() when you set the
'text' attribute.

    >>> hastext_entry_adapter.text
    ''
    >>> hastext_entry_adapter.text = 'foo'
    >>> hastext_entry_adapter.text
    '!foo!'

The original interface defines 'text' as read-only, but the
generated interface does not.

    >>> hastext_entry_interface.object.get('text').readonly
    False

It's not necessary to expose the mutator method as a write operation.

    >>> class IHasText(Interface):
    ...     export_as_webservice_entry()
    ...     text = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(text)
    ...     def set_text(text):
    ...         pass


A mutator method must take only one argument: the new value for the
field. Taking no arguments is obviously an error.

    >>> class ZeroArgumentMutator(Interface):
    ...     export_as_webservice_entry()
    ...     value = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(value)
    ...     def set_value():
    ...         pass
    Traceback (most recent call last):
    ...
    TypeError: A mutator method must take one and only one non-fixed
    argument. set_value takes 0.

Taking more than one argument is also an error...

    >>> class TwoArgumentMutator(Interface):
    ...     export_as_webservice_entry()
    ...     value = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(value)
    ...     def set_value(arg1, arg2):
    ...         pass
    Traceback (most recent call last):
    ...
    TypeError: A mutator method must take one and only one non-fixed
    argument. set_value takes 2.

...unless all but one of the arguments are spoken for by a call_with()
annotation. This definition does not result in a TypeError.

    >>> class OneFixedArgumentMutator(Interface):
    ...     export_as_webservice_entry()
    ...     value = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(value)
    ...     @call_with(arg1=REQUEST_USER, arg3='fixed')
    ...     @operation_parameters(arg2=TextLine())
    ...     @export_write_operation()
    ...     def set_value(arg1, arg2, arg3):
    ...         pass

A field can only have a mutator if it's read-only (not settable
directly).

    >>> class WritableMutator(Interface):
    ...     export_as_webservice_entry()
    ...     value = exported(TextLine(readonly=False))
    ...
    ...     @mutator_for(value)
    ...     @export_write_operation()
    ...     def set_value(new_value):
    ...         pass
    Traceback (most recent call last):
    ...
    TypeError: Only a read-only field can have a mutator method.

A field can only have one mutator.

    >>> class FieldWithTwoMutators(Interface):
    ...     export_as_webservice_entry()
    ...     value = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(value)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value(new_value):
    ...         pass
    ...
    ...     @mutator_for(value)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value_2(new_value):
    ...         pass
    Traceback (most recent call last):
    ...
    TypeError: A field can only have one mutator method for version
    (earliest version); set_value_2 makes two.

Read-only fields
----------------

A read-write field can be published as read-only in the web service.

    >>> class ExternallyReadOnlyField(Interface):
    ...     export_as_webservice_entry()
    ...     value = exported(TextLine(readonly=False), readonly=True)

    >>> interfaces = generate_entry_interfaces(
    ...     ExternallyReadOnlyField, [], 'beta')
    >>> [(beta, beta_interface)] = interfaces

    >>> ExternallyReadOnlyField['value'].readonly
    False
    >>> beta_interface['value'].readonly
    True

A read-only field cannot be published as read-write in the web service
just by declaring it read-write. You have to provide a
mutator.

    >>> class InternallyReadOnlyField(Interface):
    ...     export_as_webservice_entry()
    ...     value = exported(TextLine(readonly=True), readonly=False)

    >>> generate_entry_interfaces(InternallyReadOnlyField, [], 'beta')
    Traceback (most recent call last):
    ...
    TypeError: InternallyReadOnlyField.value is defined as a read-only
    field, so you can't just declare it to be read-write in the web
    service: you must define a mutator.

Caching
-------

It is possible to cache a server response in the browser cache using
the @cache_for decorator:

    >>> from lazr.restful.declarations import cache_for
    >>>
    >>> class ICachedBookSet(IBookSet):
    ...     """IBookSet supporting caching."""
    ...     export_as_webservice_collection(IBook)
    ...
    ...     @collection_default_content()
    ...     @export_read_operation()
    ...     @cache_for(60)
    ...     def getAllBooks():
    ...         """Return all books."""
    ...
    ...
    >>> class CachedBookSet(BookSet):
    ...     """Simple ICachedBookSet implementation."""
    ...     implements(ICachedBookSet)
    ...
    ...     def getAllBooks(self):
    ...         return self.books

    >>> read_method_adapter_factory = generate_operation_adapter(
    ...     ICachedBookSet['getAllBooks'])
    >>> read_method_adapter = read_method_adapter_factory(
    ...     CachedBookSet(['Cool book']), request)
    >>> print read_method_adapter.call()
    ['Cool book']
    >>> print request.response.headers
    {'Content-Type': 'application/json', 'Cache-control': 'max-age=60'}

Only positive int or long objects should be passed to @cache_for:

    >>> class ICachedBookSet(IBookSet):
    ...     @cache_for('60')
    ...     def getAllBooks():
    ...         """Return all books."""
    ...
    Traceback (most recent call last):
    ...
    TypeError: Caching duration should be int or long, not str
    >>>
    >>> class ICachedBookSet(IBookSet):
    ...     @cache_for(-15)
    ...     def getAllBooks():
    ...         """Return all books."""
    ...
    Traceback (most recent call last):
    ...
    ValueError: Caching duration should be a positive number: -15

Versioned services
==================

Different versions of the webservice can publish the same data model
object in totally different ways.

Collections
-----------

A collection's contents are determined by calling one of its
methods. Which method is called, and with which arguments, can vary
across versions.

    >>> from lazr.restful.declarations import generate_operation_adapter

    >>> class IMultiVersionCollection(Interface):
    ...     export_as_webservice_collection(Interface)
    ...
    ...     @collection_default_content('2.0')
    ...     def content_20():
    ...         """The content method for version 2.0."""
    ...
    ...     @collection_default_content('1.0', argument='1.0 value')
    ...     @collection_default_content(argument='pre-1.0 value')
    ...     def content_pre_20(argument):
    ...         """The content method for versions before 2.0"""

Here's a simple implementation of IMultiVersionCollection. It'll
illustrate how the different versions of the web service invoke
different methods to find the collection contents.

    >>> class MultiVersionCollection():
    ...     """Simple IMultiVersionCollection implementation."""
    ...     implements(IMultiVersionCollection)
    ...
    ...     def content_20(self):
    ...         return ["contents", "for", "version", "2.0"]
    ...
    ...     def content_pre_20(self, argument):
    ...         return ["you", "passed", "in", argument]

By passing a version string into generate_collection_adapter(), we can
get different adapter classes for different versions of the web
service. We'll be invoking each version against the same data model
object. Here it is:

    >>> data_object = MultiVersionCollection()

Passing in None to generate_collection_adapter gets us the collection
as it appears in the earliest version of the web service. The
content_pre_20() method is invoked with the 'argument' parameter equal
to "pre-1.0 value".

    >>> interface = IMultiVersionCollection
    >>> adapter_earliest_factory = generate_collection_adapter(
    ...     interface, None)
    >>> print adapter_earliest_factory.__name__
    MultiVersionCollectionCollectionAdapter___Earliest

    >>> collection_earliest = adapter_earliest_factory(data_object, request)
    >>> print collection_earliest.find()
    ['you', 'passed', 'in', 'pre-1.0 value']

Passing in '1.0' gets us the collection as it appears in the 1.0
version of the web service. Note that the argument passed in to
content_pre_20() is different, and so the returned contents are
slightly different.

    >>> adapter_10_factory = generate_collection_adapter(interface, '1.0')
    >>> print adapter_10_factory.__name__
    MultiVersionCollectionCollectionAdapter_1_0

    >>> collection_10 = adapter_10_factory(data_object, request)
    >>> print collection_10.find()
    ['you', 'passed', 'in', '1.0 value']

Passing in '2.0' gets us a collection with totally different contents,
because a totally different method is being called.

    >>> adapter_20_factory = generate_collection_adapter(interface, '2.0')
    >>> print adapter_20_factory.__name__
    MultiVersionCollectionCollectionAdapter_2_0

    >>> collection_20 = adapter_20_factory(data_object, request)
    >>> print collection_20.find()
    ['contents', 'for', 'version', '2.0']

An error occurs when we try to generate an adapter for a version
that's not mentioned in the annotations.

    >>> generate_collection_adapter(interface, 'NoSuchVersion')
    Traceback (most recent call last):
    ...
    AssertionError: 'IMultiVersionCollection' isn't tagged for export
    to web service version 'NoSuchVersion'.

Entries
-------

The singular and plural name of an entry never changes between
versions, because the names are a property of the original
interface. But the published fields can change or be renamed from
version to version.

Here's a data model interface defining four fields which are published
in some versions and not others, and which may have different names in
different versions.

1. A TextLine called 'field', published in all versions.
2. A Text called 'unchanging_name', published in all versions.
3. A TextLine called 'field3' in the earliest version, removed in '1.0',
   published as '20_name' in '2.0', and renamed to '30_name' in '3.0'.
4. A Float not published in the earliest version, introduced as
   'new_in_10' in '1.0', and renamed to 'renamed_in_30' in '3.0'.

    >>> from zope.schema import Text, Float
    >>> class IMultiVersionEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine())
    ...
    ...     field2 = exported(Text(), exported_as='unchanging_name')
    ...
    ...     field3 = exported(TextLine(),
    ...         ('3.0', dict(exported_as='30_name')),
    ...         ('2.0', dict(exported=True, exported_as='20_name')),
    ...         ('1.0', dict(exported=False)))
    ...
    ...     field4 = exported(Float(),
    ...         ('3.0', dict(exported_as='renamed_in_30')),
    ...         ('1.0', dict(exported=True, exported_as='new_in_10')),
    ...         exported=False)

Let's take a look at the entry interfaces generated for each version.

    >>> versions = ['beta', '1.0', '2.0', '3.0']
    >>> versions_and_interfaces = generate_entry_interfaces(
    ...     IMultiVersionEntry, [], *versions)

    >>> for version, interface in versions_and_interfaces:
    ...     print version
    beta
    1.0
    2.0
    3.0

    >>> interface_beta, interface_10, interface_20, interface_30 = (
    ...     [interface for version, interface in versions_and_interfaces])

    >>> dump_entry_interface(interface_beta)
    field: TextLine
    field3: TextLine
    unchanging_name: Text

    >>> dump_entry_interface(interface_10)
    field: TextLine
    new_in_10: Float
    unchanging_name: Text

    >>> dump_entry_interface(interface_20)
    20_name: TextLine
    field: TextLine
    new_in_10: Float
    unchanging_name: Text

    >>> dump_entry_interface(interface_30)
    30_name: TextLine
    field: TextLine
    renamed_in_30: Float
    unchanging_name: Text


Here's a simple implementation of the entry.

    >>> class MultiVersionEntry():
    ...     """Simple IMultiVersionEntry implementation."""
    ...     implements(IMultiVersionEntry)
    ...     field = "field value"
    ...     field2 = "unchanging value"
    ...     field3 = "field 3 value"
    ...     field4 = 1.0


When we call generate_entry_adapters(), we'll get an adapter
classes for each version of the web service. We'll be invoking
each version against the same data model object. Here it is:

    >>> data_object = MultiVersionEntry()


generate_entry_adapters() generates adaptor factories that mediate
between this data model object and the many-faceted interface
classes.

    >>> entry_adapters = generate_entry_adapters(
    ...     IMultiVersionEntry, [], versions_and_interfaces)

    >>> for version, adapter in entry_adapters:
    ...     print version
    beta
    1.0
    2.0
    3.0

    >>> adapter_beta, adapter_10, adapter_20, adapter_30 = (
    ...     [interface for version, interface in entry_adapters])

Here's the 'beta' version of the object:

    >>> object_beta = adapter_beta(data_object, request)
    >>> print object_beta.field
    field value
    >>> print object_beta.field3
    field 3 value
    >>> print object_beta.unchanging_name
    unchanging value

The 'field4' field is not available in the 'beta' version under any name.

    >>> print object_beta.field4
    Traceback (most recent call last):
    ...
    AttributeError: 'MultiVersionEntryEntry_betaAdapter' object has no
    attribute 'field4'

    >>> print object_beta.new_in_10
    Traceback (most recent call last):
    ...
    AttributeError: 'MultiVersionEntryEntry_betaAdapter' object has no
    attribute 'new_in_10'

Here's the '1.0' version. 'field3' is gone and the 'field4' field is
now available as 'new_in_10'.

    >>> object_10 = adapter_10(data_object, request)
    >>> print object_10.field
    field value
    >>> print object_10.unchanging_name
    unchanging value
    >>> print object_10.new_in_10
    1.0

    >>> object_10.field3
    Traceback (most recent call last):
    ...
    AttributeError: 'MultiVersionEntryEntry_1_0Adapter' object has no
    attribute 'field3'

Here's the '2.0' version. 'field3' is back, but now it's called '20_name'.

    >>> object_20 = adapter_20(data_object, request)
    >>> print object_20.field
    field value
    >>> print object_20.unchanging_name
    unchanging value
    >>> print getattr(object_20, '20_name')
    field 3 value
    >>> print object_20.new_in_10
    1.0

Here's the '3.0' version. 'field3' has been renamed to '30_name' and
'field4' has been renamed to 'renamed_in_30'

    >>> object_30 = adapter_30(data_object, request)
    >>> print object_30.field
    field value
    >>> print object_30.unchanging_name
    unchanging value
    >>> print getattr(object_30, '30_name')
    field 3 value
    >>> print object_30.renamed_in_30
    1.0

    >>> getattr(object_30, '20_name')
    Traceback (most recent call last):
    ...
    AttributeError: 'MultiVersionEntryEntry_3_0Adapter' object has no
    attribute '20_name'

    >>> object_30.new_in_10
    Traceback (most recent call last):
    ...
    AttributeError: 'MultiVersionEntryEntry_3_0Adapter' object has no
    attribute 'new_in_10'

Why the list of version strings?
********************************

Why does generate_entry_interfaces need a list of version strings?
This example should make it clear.

    >>> class IAmbiguousMultiVersion(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field1 = exported(TextLine(),
    ...         ('foo', dict(exported_as='foo_name')))
    ...     field2 = exported(TextLine(),
    ...         ('bar', dict(exported_as='bar_name')))

This web service clearly has two versions, 'foo', and 'bar', but which
is the earlier version and which the later? If 'foo' is the earlier
version, then 'bar' inherits behavior from 'foo'.

    >>> foo, bar = generate_entry_interfaces(
    ...     IAmbiguousMultiVersion, [], 'foo', 'bar')

    >>> print foo.version
    foo
    >>> dump_entry_interface(foo.object)
    field2: TextLine
    foo_name: TextLine

    >>> print bar.version
    bar
    >>> dump_entry_interface(bar.object)
    bar_name: TextLine
    foo_name: TextLine

But if 'bar' is the earlier version, then 'foo' inherits behavior from
'bar'. (We need to redefine the class because our previous call to
generate_entry_interfaces() modified the class to reflect the original
list of versions.)

    >>> class IAmbiguousMultiVersion(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field1 = exported(TextLine(),
    ...         ('foo', dict(exported_as='foo_name')))
    ...     field2 = exported(TextLine(),
    ...         ('bar', dict(exported_as='bar_name')))

    >>> bar, foo = generate_entry_interfaces(
    ...     IAmbiguousMultiVersion, [], 'bar', 'foo')

    >>> print bar.version
    bar
    >>> dump_entry_interface(bar.object)
    bar_name: TextLine
    field1: TextLine

    >>> print foo.version
    foo
    >>> dump_entry_interface(foo.object)
    bar_name: TextLine
    foo_name: TextLine

If a web service definition is complex enough, it's possible to derive
an ordered list of all the versions just from looking at the field
annotations. But it's not possible in general, and that's why
generate_entry_interfaces takes a list of versions.

Error handling
**************

You'll get an error if you annotate a field with a version that turns
out not to be included in the version list.

    >>> class INonexistentVersionEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(),
    ...         ('2.0', dict(exported_as='foo')),
    ...         ('1.0', dict(exported_as='bar')))

    >>> generate_entry_interfaces(
    ...     INonexistentVersionEntry, [], 'beta', '1.0')
    Traceback (most recent call last):
    ...
    ValueError: Field "field" in interface "INonexistentVersionEntry":
    Unrecognized version "2.0".

You'll get an error if you put an earlier version's annotations on top
of a later version.

    >>> class IWrongOrderEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(),
    ...         ('1.0', dict(exported_as='bar')),
    ...         ('2.0', dict(exported_as='foo')))

    >>> generate_entry_interfaces(IWrongOrderEntry, [], '1.0', '2.0')
    Traceback (most recent call last):
    ...
    ValueError: Field "..." in interface "IWrongOrderEntry":
    Version "1.0" defined after the later version "2.0".

You'll get an error if you define annotations twice for the same
version. This can happen because you repeated the version annotations:

    >>> class IDuplicateEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(),
    ...         ('beta', dict(exported_as='another_beta_name')),
    ...         ('beta', dict(exported_as='beta_name')))

    >>> generate_entry_interfaces(IDuplicateEntry, [], 'beta', '1.0')
    Traceback (most recent call last):
    ...
    ValueError: Field "field" in interface "IDuplicateEntry":
    Duplicate definitions for version "beta".

Or it can happen because you defined the earliest version implicitly
using keyword arguments, and then explicitly defined conflicting
values.

    >>> class IDuplicateEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(),
    ...         ('beta', dict(exported_as='beta_name')),
    ...         exported_as='earliest_name')

    >>> generate_entry_interfaces(IDuplicateEntry, [], 'beta', '1.0')
    Traceback (most recent call last):
    ...
    ValueError: Field "field" in interface "IDuplicateEntry":
    Annotation "as" has conflicting values for the earliest version:
    "earliest_name" (from keyword arguments) and "beta_name" (defined
    explicitly).

You'll get an error if you include an unrecognized key in a field's
version definition.

    >>> class InvalidMultiVersionEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(),
    ...         ('3.0', dict(not_recognized='this will error')))
    Traceback (most recent call last):
    ...
    ValueError: Unrecognized annotation for version "3.0": "not_recognized"

    >>> class InvalidMultiVersionEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(), not_recognized='this will error')
    Traceback (most recent call last):
    ...
    TypeError: exported got an unexpected keyword argument 'not_recognized'

generate_entry_interfaces() generates an interface class for
every version, even when an interface does not change at all between
versions. (This could be optimized away.)

    >>> class IUnchangingEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(),
    ...         ('3.0', dict(exported_as='30_name')),
    ...         ('beta', dict(exported_as='unchanging_name')))

    >>> [interface.version for interface in
    ...      generate_entry_interfaces(IUnchangingEntry, [], *versions)]
    ['beta', '1.0', '2.0', '3.0']

Named operations
----------------

It's easy to reflect the most common changes between versions:
operations and arguments being renamed, changes in fixed values, etc.
This method appears differently in three versions of the web service:
2.0, 1.0, and in an unnamed pre-1.0 version.

    >>> from lazr.restful.declarations import operation_for_version
    >>> class IMultiVersionMethod(Interface):
    ...     export_as_webservice_entry()
    ...
    ...
    ...     @cache_for(300)
    ...     @operation_for_version('3.0')
    ...
    ...     @call_with(fixed='2.0 value', user=REQUEST_USER)
    ...     @operation_for_version('2.0')
    ...
    ...     @call_with(fixed='1.0 value', user=REQUEST_USER)
    ...     @export_operation_as('new_name')
    ...     @rename_parameters_as(required="required_argument")
    ...     @operation_for_version('1.0')
    ...
    ...     @call_with(fixed='pre-1.0 value', user=REQUEST_USER)
    ...     @cache_for(100)
    ...     @operation_parameters(
    ...         required=TextLine(),
    ...         fixed=TextLine()
    ...         )
    ...     @export_read_operation()
    ...     def a_method(required, fixed, user):
    ...         """Method demonstrating multiversion publication."""

Here's a simple implementation of IMultiVersionMethod. It'll
illustrate how the different versions of the web service invoke
`a_method` with different hard-coded values for the `fixed` argument.

    >>> class MultiVersionMethod():
    ...     """Simple IMultiVersionMethod implementation."""
    ...     implements(IMultiVersionMethod)
    ...
    ...     def a_method(self, required, fixed, user):
    ...         return "Required value: %s. Fixed value: %s. User: %s." % (
    ...             required, fixed, user)

By passing a version string into generate_operation_adapter(), we can
get different adapter classes for different versions of the web
service. We'll be invoking each version against the same data model
object. Here it is:

    >>> data_object = MultiVersionMethod()

Passing in None to generate_operation_adapter gets us the method as it
appears in the earliest version of the web service.

    >>> method = IMultiVersionMethod['a_method']
    >>> adapter_earliest_factory = generate_operation_adapter(method, None)
    >>> print adapter_earliest_factory.__name__
    GET_IMultiVersionMethod_a_method_beta

    >>> method_earliest = adapter_earliest_factory(data_object, request)
    >>> print method_earliest.call(required="foo")
    Required value: foo. Fixed value: pre-1.0 value. User: A user.

Passing in '1.0' or '2.0' gets us the method as it appears in the
appropriate version of the web service. Note that the name of the
adapter factory changes to reflect the fact that the method's name in
1.0 is 'new_name', not 'a_method'.

    >>> adapter_10_factory = generate_operation_adapter(method, '1.0')
    >>> print adapter_10_factory.__name__
    GET_IMultiVersionMethod_new_name_1_0

    >>> method_10 = adapter_10_factory(data_object, request)
    >>> print method_10.call(required="bar")
    Required value: bar. Fixed value: 1.0 value. User: A user.

    >>> adapter_20_factory = generate_operation_adapter(method, '2.0')
    >>> print adapter_20_factory.__name__
    GET_IMultiVersionMethod_new_name_2_0

    >>> method_20 = adapter_20_factory(data_object, request)
    >>> print method_20.call(required="baz")
    Required value: baz. Fixed value: 2.0 value. User: A user.

    >>> adapter_30_factory = generate_operation_adapter(method, '3.0')
    >>> print adapter_30_factory.__name__
    GET_IMultiVersionMethod_new_name_3_0
    >>> method_30 = adapter_30_factory(data_object, request)
    >>> print method_30.call(required="baz")
    Required value: baz. Fixed value: 2.0 value. User: A user.

An error occurs when we try to generate an adapter for a version
that's not mentioned in the annotations.

    >>> generate_operation_adapter(method, 'NoSuchVersion')
    Traceback (most recent call last):
    ...
    AssertionError: 'a_method' isn't tagged for export to web service
    version 'NoSuchVersion'

Now that we've seen how lazr.restful uses the annotations to create
classes, let's take a closer look at how the 'a_method' method object
is annotated.

    >>> dictionary = method.getTaggedValue('lazr.restful.exported')

The tagged value containing the annotations looks like a dictionary,
but it's actually a stack of dictionaries named after the versions.

    >>> dictionary.dict_names
    [None, '1.0', '2.0', '3.0']

The dictionary on top of the stack is for the 3.0 version of the web
service. This version inherits its name ('new_name') and its fixed
arguments ('2.0 value' and REQUEST_USER) from the 2.0 version, but it
also sets a new value for 'cache_for'.

    >>> print dictionary['as']
    new_name
    >>> print pformat(dictionary['call_with'])
    {'fixed': '2.0 value',
     'user': <class '...REQUEST_USER'>}
    >>> dictionary['cache_for']
    300

Let's pop the 3.0 version off the stack. Now we can see how the method
looks in 2.0. In 2.0, the method is published as 'new_name' and its
'fixed' argument is fixed to the string '2.0 value'. It inherits its
value for 'cache_for' from version 1.0.

    >>> ignored = dictionary.pop()
    >>> print dictionary['as']
    new_name
    >>> print pformat(dictionary['call_with'])
    {'fixed': '2.0 value',
     'user': <class '...REQUEST_USER'>}
    >>> dictionary['cache_for']
    100

The published name of the 'required' argument is 'required_argument',
not 'required'.

    >>> print dictionary['params']['required'].__name__
    required_argument

Let's pop the 2.0 version off the stack. Now we can see how the method
looks in 1.0. It's still called 'new_name', and its 'required'
argument is still called 'required_argument', but its 'fixed' argument
is fixed to the string '1.0 value'.

    >>> ignored = dictionary.pop()
    >>> print dictionary['as']
    new_name
    >>> print pformat(dictionary['call_with'])
    {'fixed': '1.0 value',
     'user': <class '...REQUEST_USER'>}
    >>> print dictionary['params']['required'].__name__
    required_argument
    >>> dictionary['cache_for']
    100

Let's pop one more time to see how the method looks in the pre-1.0
version. It hasn't yet been renamed to 'new_name', its 'required'
argument hasn't yet been renamed to 'required_argument', and its
'fixed' argument is fixed to the string 'pre-1.0 value'.

    >>> ignored = dictionary.pop()
    >>> print dictionary['as']
    a_method
    >>> print dictionary['params']['required'].__name__
    required
    >>> print pformat(dictionary['call_with'])
    {'fixed': 'pre-1.0 value',
     'user': <class '...REQUEST_USER'>}
    >>> dictionary['cache_for']
    100

@operation_removed_in_version
*****************************

Sometimes you want version n+1 to remove a named operation that was
present in version n. The @operation_removed_in_version declaration
does just this.

Let's define an operation that's introduced in 1.0 and removed in 2.0.

    >>> from lazr.restful.declarations import operation_removed_in_version
    >>> class DisappearingMultiversionMethod(Interface):
    ...     export_as_webservice_entry()
    ...     @operation_removed_in_version(2.0)
    ...     @operation_parameters(arg=Float())
    ...     @export_read_operation()
    ...     @operation_for_version(1.0)
    ...     def method(arg):
    ...         """A doomed method."""

    >>> dictionary = DisappearingMultiversionMethod[
    ...     'method'].getTaggedValue('lazr.restful.exported')

The method is not present in 2.0:

    >>> version, attrs = dictionary.pop()
    >>> print version
    2.0
    >>> sorted(attrs.items())
    [('type', 'removed_operation')]

It is present in 1.0:

    >>> version, attrs = dictionary.pop()
    >>> print version
    1.0
    >>> print attrs['type']
    read_operation
    >>> print attrs['params']['arg']
    <zope.schema._field.Float object...>

But it's not present in the unnamed pre-1.0 version, since it hadn't
been defined yet:

    >>> pre_10 = dictionary.pop()
    >>> print pre_10.version
    None
    >>> print pre_10.object
    {'type': 'removed_operation'}

The @operation_removed_in_version declaration can also be used to
reset a named operation's definition if you need to completely re-do
it.

For instance, ordinarily you can't change the type of an operation, or
totally redefine its parameters--and you shouldn't really need
to. It's usually easier to publish two different operations that have
the same name in different versions. But you can do it with a single
operation, by removing the operation with
@operation_removed_in_version and defining it again--either in the
same version or in some later version.

In this example, the type of the operation, the type and number of the
arguments, and the return value change in version 1.0.

    >>> class ReadOrWriteMethod(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     @operation_parameters(arg=TextLine(), arg2=TextLine())
    ...     @export_write_operation()
    ...     @operation_removed_in_version(1.0)
    ...
    ...     @operation_parameters(arg=Float())
    ...     @operation_returns_collection_of(Interface)
    ...     @export_read_operation()
    ...     def method(arg, arg2='default'):
    ...         """A read *or* a write operation, depending on version."""

    >>> dictionary = ReadOrWriteMethod[
    ...     'method'].getTaggedValue('lazr.restful.exported')

In version 1.0, the 'method' named operation is a write operation that
takes two TextLine arguments and has no special return value.

    >>> version, attrs = dictionary.pop()
    >>> print version
    1.0
    >>> print attrs['type']
    write_operation
    >>> attrs['params']['arg']
    <zope.schema._bootstrapfields.TextLine object...>
    >>> attrs['params']['arg2']
    <zope.schema._bootstrapfields.TextLine object...>
    >>> print attrs.get('return_type')
    None

In the unnamed pre-1.0 version, the 'method' operation is a read
operation that takes a single Float argument and returns a collection.

    >>> version, attrs = dictionary.pop()
    >>> print attrs['type']
    read_operation

    >>> attrs['params']['arg']
    <zope.schema._field.Float object...>
    >>> attrs['params'].keys()
    ['arg']

    >>> attrs['return_type']
    <lazr.restful.fields.CollectionField object...>

Mutators
********

Different versions can define different mutator methods for the same field.

    >>> class IDifferentMutators(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_for_version('beta')
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value(new_value):
    ...         pass
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_for_version('1.0')
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value_2(new_value):
    ...         pass

    >>> ignored = generate_entry_interfaces(
    ...     IDifferentMutators, [], 'beta', '1.0')

But you can't define two mutators for the same field in the same version.

    >>> class IDuplicateMutator(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_for_version('1.0')
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value(new_value):
    ...         pass
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_for_version('1.0')
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value_2(new_value):
    ...         pass
    Traceback (most recent call last):
    ...
    TypeError: A field can only have one mutator method for version
    1.0; set_value_2 makes two.

Here's a case that's a little trickier. You'll also get an error if
you implicitly define a mutator for the earliest version (without
giving its name), and then define another one explicitly (giving the
name of the earliest version.)

    >>> class IImplicitAndExplicitMutator(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_for_version('beta')
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value_2(new_value):
    ...         pass
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value_2(new_value):
    ...         pass

    >>> generate_entry_interfaces(
    ...     IImplicitAndExplicitMutator, [], 'beta', '1.0')
    Traceback (most recent call last):
    ...
    ValueError: Field "field" in interface
    "IImplicitAndExplicitMutator": Both implicit and explicit mutator
    definitions found for earliest version beta.

This error isn't detected until you try to generate the entry
interfaces, because until that point lazr.restful doesn't know that
'beta' is the earliest version. If the earliest version was 'alpha',
the IImplicitAndExplicitMutator class would be valid.

(Again, to test this hypothesis, we need to re-define the class,
because the generate_entry_interfaces call modified the original
class's annotations in place.)

    >>> class IImplicitAndExplicitMutator(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_for_version('beta')
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value_2(new_value):
    ...         pass
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value_2(new_value):
    ...         pass

    >>> ignored = generate_entry_interfaces(
    ...     IImplicitAndExplicitMutator, [], 'alpha', 'beta', '1.0')

Destructor operations
*********************

A destructor can be published in different ways in different versions,
but the restrictions on destructor arguments are enforced separately
for each version.

Here, the destructor fixes a value for the 'fixed2' argument in the
earliest version, but not in '1.0'. This is fine: the 1.0 value for
'fixed2' will be inherited from the previous version.

    >>> class IGoodDestructorEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     @call_with(fixed1="value3")
    ...     @operation_for_version('1.0')
    ...     @export_destructor_operation()
    ...     @call_with(fixed1="value1", fixed2="value")
    ...     @operation_parameters(fixed1=TextLine(), fixed2=TextLine())
    ...     def destructor(fixed1, fixed2):
    ...         """Another destructor method."""

    >>> ignore = generate_entry_interfaces(
    ...     IGoodDestructorEntry, [], 'beta', '1.0')

In this next example, the destructor is removed in 1.0 and
added back in 2.0. The 2.0 version does not inherit any values from
its prior incarnation, so the fact that it does not fix any value for
'fixed2' is a problem. The fact that 'fixed2' is fixed in 3.0 doesn't
help; the method is incompletely specified in 2.0.

    >>> class IBadDestructorEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     @call_with(fixed2="value4")
    ...     @operation_for_version('2.0')
    ...     @export_destructor_operation()
    ...     @operation_parameters(fixed1=TextLine(), fixed2=TextLine())
    ...     @call_with(fixed1="value3")
    ...     @operation_for_version('2.0')
    ...     @operation_removed_in_version('1.0')
    ...     @export_destructor_operation()
    ...     @call_with(fixed1="value1", fixed2="value")
    ...     @operation_parameters(fixed1=TextLine(), fixed2=TextLine())
    ...     def destructor(fixed1, fixed2):
    ...         """Another destructor method."""
    Traceback (most recent call last):
    ...
    TypeError: A destructor method must take no non-fixed
    arguments. In version 2.0, the "destructor" method takes 1:
    "fixed2".


Security
========

The adapters have checkers defined for them that grant access to all
attributes in the interface. (There is no reason to protect them since
the underlying content security checker will still apply.)

::

    >>> from lazr.restful.debug import debug_proxy
    >>> from zope.security.checker import ProxyFactory

    # ProxyFactory wraps the content using the defined checker.
    >>> print debug_proxy(ProxyFactory(entry_adapter))
    zope.security._proxy._Proxy (using zope.security.checker.Checker)
        public: author, price, schema, title
        public (set): author, price, schema, title

    >>> print debug_proxy(ProxyFactory(collection_adapter))
    zope.security._proxy._Proxy (using zope.security.checker.Checker)
        public: entry_schema, find

    >>> print debug_proxy(ProxyFactory(read_method_adapter))
    zope.security._proxy._Proxy (using zope.security.checker.Checker)
        public: __call__, return_type, send_modification_event

    >>> print debug_proxy(ProxyFactory(write_method_adapter))
    zope.security._proxy._Proxy (using zope.security.checker.Checker)
        public: __call__, send_modification_event

    >>> print debug_proxy(ProxyFactory(factory_method_adapter))
    zope.security._proxy._Proxy (using zope.security.checker.Checker)
        public: __call__, send_modification_event

ZCML Registration
=================

There is a ZCML directive available that will inspect a given module and
generate and register all the interfaces and adapters for all interfaces
marked for export.

(Put the interface in a module where it will be possible for the ZCML
handler to inspect.)

    >>> from lazr.restful.testing.helpers import register_test_module
    >>> bookexample = register_test_module(
    ...     'bookexample', IBook, IBookSet, IBookOnSteroids,
    ...     IBookSetOnSteroids, ISimpleComment, InvalidEmail)

After the registration, adapters from IBook to IEntry, and IBookSet to
ICollection are available:

    >>> from zope.component import getMultiAdapter
    >>> book = Book(u'George Orwell', u'1984', 10.0, u'12345-1984')
    >>> bookset = BookSet([book])

    >>> entry_adapter = getMultiAdapter((book, request), IEntry)
    >>> verifyObject(IEntry, entry_adapter)
    True

    >>> print entry_adapter.schema.__name__
    IBookEntry_beta
    >>> verifyObject(entry_adapter.schema, entry_adapter)
    True

    >>> collection_adapter = getMultiAdapter((bookset, request), ICollection)
    >>> verifyObject(ICollection, collection_adapter)
    True

IResourceOperation adapters named under the exported method names
are also available for IBookSetOnSteroids and IBookOnSteroids.

    >>> from zope.component import getGlobalSiteManager, getUtility
    >>> adapter_registry = getGlobalSiteManager().adapters

    >>> from lazr.restful.interfaces import IWebServiceClientRequest
    >>> request_interface = IWebServiceClientRequest
    >>> adapter_registry.lookup(
    ...     (IBookSetOnSteroids, request_interface),
    ...     IResourceGETOperation, 'searchBookTitles')
    <class '...GET_IBookSetOnSteroids_searchBookTitles_beta'>
    >>> adapter_registry.lookup(
    ...     (IBookSetOnSteroids, request_interface),
    ...     IResourcePOSTOperation, 'create_book')
    <class '...POST_IBookSetOnSteroids_create_book_beta'>
    >>> adapter_registry.lookup(
    ...     (IBookOnSteroids, request_interface),
    ...     IResourcePOSTOperation, 'checkout')
    <class '...POST_IBookOnSteroids_checkout_beta'>

There is also a 'index.html' view on the IWebServiceClientRequest
registered for the InvalidEmail exception.

    >>> from zope.interface import implementedBy
    >>> adapter_registry.lookup(
    ...     (implementedBy(InvalidEmail), IWebServiceClientRequest),
    ...     Interface, 'index.html')
    <class '...WebServiceExceptionView'>

(Clean-up.)

    >>> import sys
    >>> del bookexample
    >>> del sys.modules['lazr.restful.bookexample']

Error handling
--------------

Some error handling happens in the ZCML registration phase. At this
point, all the annotations have been processed, and the
IWebServiceConfiguration utility (with its canonical list of versions)
has become available. This lets us run checks on the versioning
annotations that couldn't be run before.

Here's a class annotated by someone who believes that version 1.0 of
the web service is a later version than version 2.0. (Or who believes
that named operation annotations proceed from the top down rather than
the bottom up.)

    >>> class WrongOrderVersions(Interface):
    ...     export_as_webservice_entry()
    ...     @export_operation_as('10_name')
    ...     @operation_for_version("1.0")
    ...     @operation_parameters(arg=Float())
    ...     @export_read_operation()
    ...     @operation_for_version("2.0")
    ...     def method(arg):
    ...         """A method."""

An attempt to register this module with ZCML results in an error
explaining the problem.

    >>> register_test_module('wrongorder', WrongOrderVersions)
    Traceback (most recent call last):
    ...
    ConfigurationExecutionError: <type 'exceptions.AssertionError'>:
    Annotations on "WrongOrderVersions.method" put an earlier version
    on top of a later version: "beta", "2.0", "1.0". The correct order
    is: "beta", "1.0", "2.0".  ...

Here's a class in which a named operation is removed in version 1.0
and then annotated without being reinstated.

    >>> class AnnotatingARemovedMethod(Interface):
    ...     export_as_webservice_entry()
    ...     @operation_parameters(arg=TextLine())
    ...     @export_operation_as('already_been_removed')
    ...     @operation_removed_in_version("2.0")
    ...     @operation_parameters(arg=Float())
    ...     @export_read_operation()
    ...     @operation_for_version("1.0")
    ...     def method(arg):
    ...         """A method."""

    >>> register_test_module('annotatingremoved', AnnotatingARemovedMethod)
    Traceback (most recent call last):
    ...
    ConfigurationExecutionError: ... Method "method" contains
    annotations for version "2.0", even though it's not published in
    that version. The bad annotations are: "params", "as".
    ...

Mutators as named operations
----------------------------

In earlier versions of lazr.restful, mutator methods were published as
named operations. This behavior is now deprecated and will eventually
be removed. But to maintain backwards compatibility, mutator methods
are still published as named operations up to a certain point. The
MyWebServiceConfiguration class (above) defines
last_version_with_mutator_named_operations as '1.0', meaning that in
'beta' and '1.0', mutator methods will be published as named
operations, and in '2.0' and '3.0' they will not.

Let's consider an entry that defines a mutator in the very first
version of the web service and never removes it.

    >>> class IBetaMutatorEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value(new_value):
    ...         pass

    >>> class BetaMutator:
    ...     implements(IBetaMutatorEntry)

    >>> module = register_test_module(
    ...     'betamutator', IBetaMutatorEntry, BetaMutator)

Here's a helper method that will create a request for a given version.

    >>> from zope.interface import alsoProvides
    >>> def request_for(version):
    ...     request = FakeRequest(version=version)
    ...     marker = getUtility(IWebServiceVersion, name=version)
    ...     alsoProvides(request, marker)
    ...     return request

Here's a helper method that will look up named operation for a given
version.

    >>> from lazr.restful.interfaces import IResourcePOSTOperation
    >>> def operation_for(context, version, name):
    ...     request = request_for(version)
    ...     return getMultiAdapter(
    ...         (context, request), IResourcePOSTOperation, name)

In the 'beta' and '1.0' versions, the lookup succeeds and returns the
generated adapter class defined for 'beta'. These two versions publish
"set_value" as a named POST operation.

    >>> context = BetaMutator()
    >>> operation_for(context, 'beta', 'set_value')
    <lazr.restful.declarations.POST_IBetaMutatorEntry_set_value_beta ...>
    >>> operation_for(context, '1.0', 'set_value')
    <lazr.restful.declarations.POST_IBetaMutatorEntry_set_value_beta ...>

In '2.0', the lookup fails, not because of anything in the definition
of IBetaMutatorEntry, but because the web service configuration
defines 1.0 as the last version in which mutators are published as
named operations.

    >>> operation_for(context, '2.0', 'set_value')
    Traceback (most recent call last):
    ...
    ComponentLookupError: ...

Here's an entry that defines a mutator method in version 2.0, after
the cutoff point.

    >>> class I20MutatorEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     @operation_for_version('2.0')
    ...     def set_value(new_value):
    ...         pass

    >>> class Mutator20:
    ...     implements(I20MutatorEntry)

    >>> module = register_test_module(
    ...     'mutator20', I20MutatorEntry, Mutator20)

The named operation lookup never succeeds. In '1.0' it fails because
the mutator hasn't been published yet. In '2.0' it fails because that
version comes after the last one to publish mutators as named
operations ('1.0').

    >>> context = Mutator20()
    >>> operation_for(context, '1.0', 'set_value')
    Traceback (most recent call last):
    ...
    ComponentLookupError: ...

    >>> operation_for(context, '2.0', 'set_value')
    Traceback (most recent call last):
    ...
    ComponentLookupError: ...

Edge cases
**********

You can promote a named operation to a mutator operation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here's a named operation that was defined in '1.0' and promoted to a
mutator in '3.0'.

    >>> class IOperationPromotedToMutator(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @operation_for_version('3.0')
    ...     @operation_parameters(text=TextLine())
    ...     @export_write_operation()
    ...     @operation_for_version('1.0')
    ...     def set_value(text):
    ...         pass

    >>> class OperationPromotedToMutator:
    ...     implements(IOperationPromotedToMutator)
    ...
    ...     def __init__(self):
    ...         self.field = None
    ...
    ...     def set_value(self, value):
    ...         self.field = "!" + value + "!"

    >>> module = register_test_module(
    ...     'mutatorpromotion', IOperationPromotedToMutator,
    ...     OperationPromotedToMutator)

    >>> context = OperationPromotedToMutator()

The operation is not available in 'beta', because it hasn't been
defined yet.

    >>> print operation_for(context, 'beta', 'set_value').__class__.__name__
    Traceback (most recent call last):
    ...
    ComponentLookupError: ...

The operation is available in both '1.0', and '2.0', even though
mutator operations aren't published as named operations after
1.0. This is because the operation doesn't become a mutator operation
until 3.0.

    >>> print operation_for(context, '1.0', 'set_value').__class__.__name__
    POST_IOperationPromotedToMutator_set_value_1_0

    >>> print operation_for(context, '2.0', 'set_value').__class__.__name__
    POST_IOperationPromotedToMutator_set_value_1_0

The operation is not available in 3.0, the version in which it becomes
a mutator.

    >>> operation_for(context, '3.0', 'set_value')
    Traceback (most recent call last):
    ...
    ComponentLookupError: ...

But the mutator is active, as you can see by modifying the entry's field:

    >>> context = OperationPromotedToMutator()
    >>> request_30 = request_for('3.0')
    >>> entry = getMultiAdapter((context, request_30), IEntry)
    >>> entry.field = 'foo'
    >>> print entry.field
    !foo!

You can't immediately reinstate a mutator operation as a named operation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here's one that shows a limitation of the software. This method
defines a mutator 'set_value' for version 1.0, which will be removed
in version 2.0. It *also* defines a named operation to be published
as 'set_value' in version 2.0, and a third operation to be published
as 'set_value' in version 3.0.

    >>> class IMutatorPlusNamedOperationEntry(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     @operation_for_version('1.0')
    ...     def set_value(new_value):
    ...         pass
    ...
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     @export_operation_as('set_value')
    ...     @operation_for_version('2.0')
    ...     def not_a_mutator(new_value):
    ...         pass
    ...
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     @export_operation_as('set_value')
    ...     @operation_for_version('3.0')
    ...     def also_not_a_mutator(new_value):
    ...         pass

    >>> class MutatorPlusNamedOperation:
    ...     implements(IMutatorPlusNamedOperationEntry)

    >>> module = register_test_module(
    ...     'multimutator', IMutatorPlusNamedOperationEntry,
    ...     MutatorPlusNamedOperation)

The mutator is accessible for version 1.0, as you'd expect.

    >>> context = MutatorPlusNamedOperation()
    >>> print operation_for(context, '1.0', 'set_value').__class__.__name__
    POST_IMutatorPlusNamedOperationEntry_set_value_1_0

But the named operation that replaces the mutator in version 1.0 is
not accessible.

    >>> operation_for(context, '2.0', 'set_value')
    Traceback (most recent call last):
    ...
    ComponentLookupError: ...

The named operation of the same name defined in version 3.0 _is_
accessible.

    >>> print operation_for(context, '3.0', 'set_value').__class__.__name__
    POST_IMutatorPlusNamedOperationEntry_set_value_3_0

So, in the version that gets rid of named operations for mutator
methods, you can't define a named operation with the same name as one
of the outgoing mutator methods.

Removing mutator named operations altogether
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You can remove this behavior altogether (such that mutators are never
named operations) by setting the value of the configuration variable
'last_version_with_mutator_named_operations' to None.

    >>> config = getUtility(IWebServiceConfiguration)
    >>> config.last_version_with_mutator_named_operations = None

Here's a class identical to IBetaMutatorEntry: it defines a mutator in
the 'beta' version of the web service. (We have to redefine the class
to avoid conflicting registrations.)

    >>> class IBetaMutatorEntry2(IBetaMutatorEntry):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value(new_value):
    ...         pass

    >>> class BetaMutator2:
    ...     implements(IBetaMutatorEntry2)

    >>> module = register_test_module(
    ...     'betamutator2', IBetaMutatorEntry2, BetaMutator2)

    >>> module = register_test_module(
    ...     'betamutator', IBetaMutatorEntry, BetaMutator)

Back when last_version_with_mutator_named_operations was '1.0', the
'set_value' named operation on IBetaMutatorEntry was accessible in
'beta' but not in '1.0' or later versions. Now, IBetaMutatorEntry2's
'set_value' mutator is not even accessible in 'beta'.

    >>> context = BetaMutator2()
    >>> operation_for(context, 'beta', 'set_value')
    Traceback (most recent call last):
    ...
    ComponentLookupError: ...

Getting the old behavior back
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You can bring back the old behavior (in which mutators are always
named operations) by setting 'last_version_with_mutator_named_operations'
to the last active version.

    >>> config.last_version_with_mutator_named_operations = (
    ...     config.active_versions[-1])

Again, we have to publish a new entry class, to avoid conflicting
registrations.

    >>> class IBetaMutatorEntry3(Interface):
    ...     export_as_webservice_entry()
    ...
    ...     field = exported(TextLine(readonly=True))
    ...
    ...     @mutator_for(field)
    ...     @export_write_operation()
    ...     @operation_parameters(new_value=TextLine())
    ...     def set_value(new_value):
    ...         pass

    >>> class BetaMutator3:
    ...     implements(IBetaMutatorEntry3)

    >>> module = register_test_module(
    ...     'betamutator3', IBetaMutatorEntry3, BetaMutator3)

Back when last_version_with_mutator_named_operations was '1.0', the
'set_value' mutator on IBetaMutatorEntry was not accessible in any
version past '1.0'. Now, the corresponding IBetaMutatorEntry3 mutator
is accessible in every version.

    >>> context = BetaMutator3()
    >>> operation_for(context, 'beta', 'set_value')
    <...POST_IBetaMutatorEntry3_set_value_beta...>
    >>> operation_for(context, '1.0', 'set_value')
    <...POST_IBetaMutatorEntry3_set_value_beta...>
    >>> operation_for(context, '2.0', 'set_value')
    <...POST_IBetaMutatorEntry3_set_value_beta...>
    >>> operation_for(context, '3.0', 'set_value')
    <...POST_IBetaMutatorEntry3_set_value_beta...>