~launchpad-pqm/launchpad/devel

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
TALES expressions
=================

There are several kinds of TALES expressions we've implemented in
Launchpad, to help make it easier to create page templates, without the
need to introduce complex Python code in the template itself.

First, let's bring in a small helper function:

    >>> from canonical.launchpad.ftests import test_tales


The count: namespace to get numbers
-----------------------------------

count:len gives you a number which is len(thing).

    >>> test_tales('foo/count:len', foo=[])
    0

    >>> test_tales('foo/count:len', foo=[1, 2, 3])
    3

    >>> test_tales('foo/count:len', foo=object())
    Traceback (most recent call last):
    ...
    TypeError: object of type 'object' has no len()


The image: namespace to get image elements
------------------------------------------

To display the icon for a milestone, use image:icon:

    >>> from lp.registry.model.milestone import MilestoneSet
    >>> milestone = MilestoneSet().get(1)
    >>> test_tales("milestone/image:icon", milestone=milestone)
    '<img ... src="/@@/milestone" />'

The same image:icon, as well as a image:logo and a image:logo is also
available for Person, Product, ProjectGroup, Sprint and Distributions, since
they all implement IHasLogo, IHasMugshot and IHasIcon.

    >>> from lp.registry.interfaces.person import IPersonSet
    >>> mark = getUtility(IPersonSet).getByName('mark')
    >>> test_tales("person/image:sprite_css", person=mark)
    'sprite person'

    >>> test_tales("person/image:logo", person=mark)
    '<img ... src="/@@/person-logo" />'

The Mugshot is presented in an <img> tag.

    >>> test_tales("person/image:mugshot", person=mark)
    '<img...src="/@@/person-mugshot" />'

For people we even have different images in case the person in question
is not an actual launchpad user.

    >>> matsubara = getUtility(IPersonSet).getByName('matsubara')
    >>> matsubara.is_valid_person
    False

    >>> test_tales("person/image:sprite_css", person=matsubara)
    'sprite person-inactive'

    >>> test_tales("person/image:logo", person=matsubara)
    '<img ... src="/@@/person-inactive-logo" />'

    >>> test_tales("person/image:mugshot", person=matsubara)
    '...<img...src="/@@/person-inactive-mugshot" />...'

We also have image:icon for KarmaCategory:

    >>> from lp.registry.model.karma import KarmaCategory
    >>> for category in KarmaCategory.select(orderBy='title'):
    ...     print test_tales("category/image:icon", category=category)
    <img ... title="Answer Tracker" src="/@@/question" />
    <img ... title="Bazaar Branches" src="/@@/branch" />
    <img ... title="Bug Management" src="/@@/bug" />
    <img ... title="Soyuz" src="/@@/package-source" />
    <img ... title="Specification Tracking" src="/@@/blueprint" />
    <img ... title="Translations in Rosetta" src="/@@/translation" />

We also have an icon for bugs.

    >>> from lp.bugs.interfaces.bug import IBugSet
    >>> bug = getUtility(IBugSet).get(1)
    >>> print test_tales("bug/image:sprite_css", bug=bug)
    sprite bug

Icons for each type (purpose) of archive we support. Starting with
personal package archives (PPAs).

    >>> print test_tales("ppa/image:icon", ppa=mark.archive)
    <img ... src="/@@/ppa-icon" />

Then distribution main archives (primary, partner and debug).

    >>> from lp.registry.interfaces.distribution import (
    ...      IDistributionSet)
    >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
    >>> [primary, partner, debug] = ubuntu.all_distro_archives

    >>> print test_tales("archive/image:icon", archive=primary)
    <img ... src="/@@/distribution" />

    >>> print test_tales("archive/image:icon", archive=partner)
    <img ... src="/@@/distribution" />

    >>> print test_tales("archive/image:icon", archive=debug)
    <img ... src="/@@/distribution" />

And finally Copy archives.

    >>> from lp.soyuz.enums import ArchivePurpose
    >>> from lp.soyuz.interfaces.archive import IArchiveSet
    >>> copy = getUtility(IArchiveSet).new(
    ...     owner=mark, purpose=ArchivePurpose.COPY,
    ...     distribution=ubuntu, name='rebuild')

    >>> print test_tales("archive/image:icon", archive=copy)
    <img ... src="/@@/distribution" />

PPAs have a 'link' formatter, which returns the appropriate HTML used
for referring to them in other pages and a 'reference' formatter which
displays the unique ppa reference.

    >>> login('admin@canonical.com')
    >>> owner = factory.makePerson(name="joe", displayname="Joe Smith")
    >>> public_ppa = factory.makeArchive(
    ...     name='ppa', private=False, owner=owner)
    >>> login(ANONYMOUS)
    >>> print test_tales("ppa/fmt:link", ppa=public_ppa)
    <a href="/~joe/+archive/ppa"
       class="sprite ppa-icon">PPA for Joe Smith</a>
    >>> print test_tales("ppa/fmt:reference", ppa=public_ppa)
    ppa:joe/ppa

Disabled PPAs links use a different icon and are only linkified for
users with launchpad.View on them.

    >>> login('admin@canonical.com')
    >>> public_ppa.disable()

    >>> print test_tales("ppa/fmt:link", ppa=public_ppa)
    <a href="/~joe/+archive/ppa" class="sprite ppa-icon-inactive">PPA
    for Joe Smith</a>

    >>> login(ANONYMOUS)

    >>> print test_tales("ppa/fmt:link", ppa=public_ppa)
    <span class="sprite ppa-icon-inactive">PPA for Joe Smith</span>

Private PPAs links are not rendered for users without launchpad.View on
them.

    >>> login('admin@canonical.com')
    >>> private_ppa = factory.makeArchive(
    ...     name='pppa', private=True, owner=owner)

    >>> print test_tales("ppa/fmt:link", ppa=private_ppa)
    <a href="/~joe/+archive/pppa" class="sprite ppa-icon">PPA named pppa
    for Joe Smith</a>

    >>> login(ANONYMOUS)

    >>> print test_tales("ppa/fmt:link", ppa=private_ppa)

Similarly, references to private PPAs are not rendered unless the user has
a subscription to the PPA.

    >>> ppa_user = factory.makePerson(name="jake", displayname="Jake Smith")
    >>> login_person(ppa_user)
    >>> print test_tales("ppa/fmt:reference", ppa=private_ppa)

    >>> login_person(owner)
    >>> ignore = private_ppa.newSubscription(ppa_user, owner)
    >>> login_person(ppa_user)
    >>> print test_tales("ppa/fmt:reference", ppa=private_ppa)
    ppa:joe/pppa

We also have icons for builds which may have different dimensions.

    >>> login('admin@canonical.com')
    >>> from lp.soyuz.tests.test_publishing import SoyuzTestPublisher
    >>> stp = SoyuzTestPublisher()
    >>> stp.prepareBreezyAutotest()
    >>> source = stp.getPubSource()
    >>> build = source.createMissingBuilds()[0]
    >>> login(ANONYMOUS)

The 'Needs building' build is 14x14:

    >>> print test_tales("build/image:icon", build=build)
    <img width="14" height="14"...src="/@@/build-needed" />

The 'building' build is 14x14:

    >>> from zope.security.proxy import removeSecurityProxy
    >>> from lp.buildmaster.enums import BuildStatus
    >>> removeSecurityProxy(build).status = BuildStatus.BUILDING
    >>> print test_tales("build/image:icon", build=build)
    <img width="14" height="14"...src="/@@/processing" />

But the 'failed to build' build is 16x14:

    >>> removeSecurityProxy(build).status = BuildStatus.FAILEDTOBUILD
    >>> print test_tales("build/image:icon", build=build)
    <img width="16" height="14"...src="/@@/build-failed" />

All objects can be represented as a boolean icon.

    >>> print test_tales("context/image:boolean", context=None)
    <span class="sprite no">&nbsp;<span
      class="invisible-link">no</span></span>

    >>> print test_tales("context/image:boolean", context=False)
    <span class="sprite no">&nbsp;<span
      class="invisible-link">no</span></span>

    >>> print test_tales("context/image:boolean", context=object())
    <span class="sprite yes">&nbsp;<span
      class="invisible-link">yes</span></span>

    >>> print test_tales("context/image:boolean", context=True)
    <span class="sprite yes">&nbsp;<span
      class="invisible-link">yes</span></span>


The fmt: namespace to get strings
---------------------------------

datetimes can be formatted with fmt:date, fmt:time, fmt:datetime and
fmt:rfc822utcdatetime.

    >>> from datetime import datetime
    >>> dt = datetime(2005, 4, 1, 16, 22)
    >>> test_tales('dt/fmt:date', dt=dt)
    '2005-04-01'

    >>> test_tales('dt/fmt:time', dt=dt)
    '16:22:00'

    >>> test_tales('dt/fmt:datetime', dt=dt)
    '2005-04-01 16:22:00'

    >>> test_tales('dt/fmt:rfc822utcdatetime', dt=dt)
    'Fri, 01 Apr 2005 16:22:00 -0000'

To truncate a long string, use fmt:shorten:

    >>> test_tales('foo/fmt:shorten/8', foo='abcdefghij')
    'abcde...'

To ellipsize the middle of a string. use fmt:ellipsize and pass the max
length.

    >>> print test_tales('foo/fmt:ellipsize/25',
    ...     foo='foo-bar-baz-bazoo_22.443.tar.gz')
    foo-bar-baz....443.tar.gz

The string is not ellipsized if it is less than the max length.

    >>> print test_tales('foo/fmt:ellipsize/25',
    ...     foo='firefox_0.9.2.orig.tar.gz')
    firefox_0.9.2.orig.tar.gz

To preserve newlines in text when displaying as HTML, use fmt:nl_to_br:

    >>> test_tales('foo/fmt:nl_to_br',
    ...             foo='icicle\nbicycle\ntricycle & troika')
    'icicle<br />\nbicycle<br />\ntricycle &amp; troika'

To "<pre>" format a string, use fmt:nice_pre:

    >>> import pprint, textwrap
    >>> pprint.pprint(textwrap.wrap(
    ...     test_tales('foo/fmt:nice_pre', foo='hello & goodbye')
    ...    ))
    ['<pre class="wrap">hello &amp; goodbye</pre>']

Add manual word breaks to long words in a string:

    >>> test_tales('foo/fmt:break-long-words', foo='short words')
    'short words'

    >>> test_tales('foo/fmt:break-long-words',
    ...     foo='<http://launchpad.net/products/launchpad>')
    '&lt;http:/<wbr></wbr>/launchpad.<wbr></wbr>...<wbr></wbr>launchpad&gt;'

To get a int with its thousands separated by a comma, use fmt:intcomma.

    >>> test_tales('foo/fmt:intcomma', foo=1234567890)
    '1,234,567,890'

    >>> test_tales('foo/fmt:intcomma', foo=123)
    '123'

    >>> test_tales('foo/fmt:intcomma', foo=1239.45)
    Traceback (most recent call last):
    ...
    AssertionError:...


The fmt: namespace to get URLs
------------------------------

The `fmt:url` is used when you want the canonical URL of a given object.

    >>> print test_tales("bug/fmt:url", bug=bug)
    http://bugs.launchpad.dev/bugs/1

You can also specify an extra argument (a view's name), if you want the
URL of a given page under that object. For that to work, though, we need
to simulate a browser request -- that's why we login() here.

    >>> from canonical.launchpad.webapp.servers import LaunchpadTestRequest
    >>> login(ANONYMOUS, LaunchpadTestRequest())
    >>> print test_tales("bug/fmt:url/+text", bug=bug)
    http://bugs.launchpad.dev/bugs/1/+text


fmt:url accepts an rootsite extension to make URLs to a specific application.

    >>> login(ANONYMOUS,
    ...     LaunchpadTestRequest(SERVER_URL='http://code.launchpad.net'))

    >>> print test_tales("person/fmt:url:bugs", person=mark)
    http://bugs.launchpad.dev/~mark

    >>> print test_tales("person/fmt:url:feeds", person=mark)
    http://feeds.launchpad.dev/~mark

    >>> print test_tales("pillar/fmt:url:answers", pillar=ubuntu)
    http://answers.launchpad.dev/ubuntu

    >>> print test_tales("bug/fmt:url:mainsite", bug=bug)
    http://launchpad.dev/bugs/1

    >>> login(ANONYMOUS)


The fmt: namespace to get a web service URL
-------------------------------------------

The `fmt:api_url` expression gives you the absolute API path to an object.
This path is everything after the web service version number.

    >>> login(ANONYMOUS,
    ...     LaunchpadTestRequest(SERVER_URL='http://bugs.launchpad.net'))

    >>> bob = factory.makePerson(name='bob')
    >>> print test_tales("person/fmt:api_url", person=bob)
    /~bob

    >>> freewidget = factory.makeProduct(name='freewidget')
    >>> print test_tales("product/fmt:api_url", product=freewidget)
    /freewidget

    >>> debuntu = factory.makeDistribution(name='debuntu')
    >>> print test_tales("distro/fmt:api_url", distro=debuntu)
    /debuntu

    >>> branch = factory.makeProductBranch(
    ...     owner=bob, product=freewidget, name='fix-bug')
    >>> print test_tales("branch/fmt:api_url", branch=branch)
    /~bob/freewidget/fix-bug

    >>> login(ANONYMOUS)


The fmt: namespace to get links
-------------------------------

The `fmt:link` tales expression provides a way to define a standard link
to a content object.  There are currently links defined for:

  * people / teams
  * branches
  * bugs
  * bug subscriptions
  * bug tasks
  * branch merge proposals
  * bug-branch links
  * code imports
  * product release files
  * product series
  * blueprints
  * blueprint-branch links
  * projects
  * questions
  * distributions
  * distroseries


Person entries
..............

For a person or team, fmt:link gives us a link to that person's page,
containing the person name and an icon.

    >>> test_tales("person/fmt:link", person=mark)
    u'<a href=".../~mark" class="sprite person">Mark Shuttleworth</a>'

    >>> test_tales("person/fmt:link", person=matsubara)
    u'<a href=".../~matsubara" class="sprite person-inactive">Diogo ...</a>'

    >>> ubuntu_team = getUtility(IPersonSet).getByName('ubuntu-team')
    >>> test_tales("person/fmt:link", person=ubuntu_team)
    u'<a href=".../~ubuntu-team" class="sprite team">Ubuntu Team</a>'

The link can make the URL go to a specific app.

    >>> login(ANONYMOUS,
    ...     LaunchpadTestRequest(SERVER_URL='http://code.launchpad.net'))

    >>> print test_tales("pillar/fmt:link:translations", pillar=ubuntu)
    <a ...http://translations.launchpad.dev/ubuntu...

    >>> print test_tales("person/fmt:url:feeds", person=mark)
    http://feeds.launchpad.dev/~mark

    >>> print test_tales("bug/fmt:url:mainsite", bug=bug)
    http://launchpad.dev/bugs/1

The default behaviour for pillars, persons, and teams is to link to
the mainsite.

    >>> print test_tales("pillar/fmt:link", pillar=ubuntu)
    <a ...http://launchpad.dev/ubuntu...

    >>> print test_tales("person/fmt:link", person=mark)
    <a ...http://launchpad.dev/~mark...

    >>> print test_tales("person/fmt:name_link", person=mark)
    <a ...http://launchpad.dev/~mark...

    >>> print test_tales("team/fmt:link", team=ubuntu_team)
    <a ...http://launchpad.dev/~ubuntu-team...

    >>> login(ANONYMOUS)

The person's displayname is escaped to prevent markup from being
interpreted by the browser. For example, a script added to Sample
Person's displayname will be escaped; averting a XSS vulnerability.

    >>> login('test@canonical.com')
    >>> sample_person = getUtility(IPersonSet).getByName('name12')
    >>> sample_person.displayname = (
    ...     "Sample Person<br/><script>alert('XSS')</script>")
    >>> test_tales("person/fmt:link", person=sample_person)
    u'<a href=".../~name12"...>Sample
      Person&lt;br/&gt;&lt;script&gt;alert(\'XSS\')&lt;/script&gt;</a>'

The fmt:link formatter takes an additional view_name component to extend
the link:

    >>> login(ANONYMOUS, LaunchpadTestRequest())
    >>> test_tales("person/fmt:link/+edit", person=matsubara)
    u'<a href=".../~matsubara/+edit"...>...'

The fmt:local-time formatter will return the local time for that person.
If the person has no time_zone specified, we use UTC.

    >>> sample_person.time_zone
    u'Australia/Perth'

    >>> test_tales("person/fmt:local-time", person=sample_person)
    '... WST'

    >>> print mark.time_zone
    None

    >>> test_tales("person/fmt:local-time", person=mark)
    '... UTC'


Branches
........

For branches, fmt:link links to the branch page.

    >>> from lp.testing import login_person
    >>> eric = factory.makePerson(name='eric')
    >>> fooix = factory.makeProduct(name='fooix')
    >>> branch = factory.makeProductBranch(
    ...     owner=eric, product=fooix, name='bar', title='The branch title')
    >>> print test_tales("branch/fmt:link", branch=branch)
    <a href=".../~eric/fooix/bar"
      class="sprite branch">lp://dev/~eric/fooix/bar</a>

The bzr-link formatter uses the bzr identity.

    >>> print test_tales("branch/fmt:bzr-link", branch=branch)
    <a href="http://code.launchpad.dev/~eric/fooix/bar"
      class="sprite branch">lp://dev/~eric/fooix/bar</a>

    >>> login_person(fooix.owner, LaunchpadTestRequest())
    >>> fooix.development_focus.branch = branch
    >>> from lp.services.propertycache import clear_property_cache
    >>> clear_property_cache(branch)
    >>> print test_tales("branch/fmt:bzr-link", branch=branch)
    <a href=".../~eric/fooix/bar" class="sprite branch">lp://dev/fooix</a>


Bugs
....

For bugs, fmt:link takes to the bug redirect page.

    >>> bug = getUtility(IBugSet).get(1)
    >>> test_tales("bug/fmt:link", bug=bug)
    u'<a href=".../bugs/1" class="sprite bug">Bug #1:
      Firefox does not support SVG</a>'

For bugtasks, fmt:link shows the severity bug icon, and links to the
appropriate project's bug.

    >>> bugtask = bug.bugtasks[0]
    >>> test_tales("bugtask/fmt:link", bugtask=bugtask)
    u'<a href=".../firefox/+bug/1" class="sprite bug-low"
         title="Low - New">Bug #1: Firefox does not support SVG</a>'

Bug titles may contain markup (when describing issue regarding markup).
Their titles are escaped so that they display correctly. This also
prevents a XSS vulnerability where malicious code injected into the
title might be interpreted by the browser.

    >>> login('test@canonical.com')
    >>> bug.title = "Opps<br/><script>alert('XSS')</script>"
    >>> test_tales("bug/fmt:link", bug=getUtility(IBugSet).get(1))
    u'<a href=".../bugs/1" ...>Bug #1:
      Opps&lt;br/&gt;&lt;script&gt;alert(\'XSS\')&lt;/script&gt;</a>'

    >>> test_tales("bugtask/fmt:link", bugtask=bugtask)
    u'<a href=".../firefox/+bug/1" ...>Bug #1:
      Opps&lt;br/&gt;&lt;script&gt;alert(\'XSS\')&lt;/script&gt;</a>'


Branch subscriptions
....................

Branch subscriptions show the person and branch name.  For users without
adequate permissions, a link is not generated.

    >>> branch = factory.makeProductBranch(
    ...     owner=eric, product=fooix, name='my-branch', title='My Branch')
    >>> michael = factory.makePerson(
    ...     name='michael', displayname='Michael the Viking')
    >>> subscription = factory.makeBranchSubscription(
    ...     branch=branch, person=michael)
    >>> test_tales("subscription/fmt:link", subscription=subscription)
    u'Subscription of Michael the Viking to
      lp://dev/~eric/fooix/my-branch'

But if we log in as the subscriber, a link is presented.

    >>> login_person(subscription.person)
    >>> test_tales("subscription/fmt:link", subscription=subscription)
    u'<a href="http://.../+subscription/michael">Subscription
      of Michael the Viking to lp://dev/~eric/fooix/my-branch</a>'

Merge proposals also have a link formatter, which displays branch
titles:


Merge proposals
...............

    >>> login('admin@canonical.com')
    >>> source = factory.makeProductBranch(
    ...     product=fooix, owner=eric, name="fix")
    >>> target = factory.makeProductBranch(product=fooix)
    >>> fooix.development_focus.branch = target
    >>> proposal = source.addLandingTarget(eric, target)
    >>> test_tales("proposal/fmt:link", proposal=proposal)
    u'<a href="...">[Merge] lp://dev/~eric/fooix/fix into lp://dev/fooix</a>'


Code review comments
....................

    >>> comment = factory.makeCodeReviewComment()
    >>> print test_tales('comment/fmt:url', comment=comment)
    http:.../~person-name.../product-name.../branch.../+merge/.../comments/...

    >>> print test_tales('comment/fmt:link', comment=comment)
    <a href="...">Comment by Person-name...</a>


Bug branches
............

    >>> login('test@canonical.com')
    >>> branch = factory.makeAnyBranch()
    >>> bug = factory.makeBug()
    >>> bugbranch = bug.linkBranch(branch, branch.owner)
    >>> test_tales("bugbranch/fmt:link", bugbranch=bugbranch)
    u'<a href="...+bug...">Bug #...</a>'


Code imports
............

The fmt:link for a code import takes you to the branch that the code
import is associated with.  The primary reason that this is here is to
support the branch deletion code.

    >>> login('foo.bar@canonical.com')
    >>> code_import = factory.makeCodeImport(branch_name="trunk")
    >>> test_tales("code_import/fmt:link", code_import=code_import)
    u'<a href=".../trunk">Import of...</a>'


Product release files
.....................

The fmt:link for a product release file will render a link for the
ProductReleaseFile itself (with a title containing its description and
size), plus extra links for the MD5 hash and signature of that PRF.

    # First we define a helper function for printing the links together
    # with their titles.

    >>> from BeautifulSoup import BeautifulSoup
    >>> def print_hrefs_with_titles(html):
    ...     soup = BeautifulSoup(html)
    ...     for link in soup.findAll('a'):
    ...         attrs = dict(link.attrs)
    ...         print "%s: %s" % (attrs.get('href'), attrs.get('title', ''))

    >>> release_file = factory.makeProductReleaseFile()
    >>> html = test_tales("release_file/fmt:link", release_file=release_file)
    >>> print_hrefs_with_titles(html)
    http://.../+download/test.txt: test file (4 bytes)
    http://.../+download/test.txt/+md5:
    http://.../+download/test.txt.asc:

When the ProductReleaseFile is not signed, the link for the signature is
not included.

    >>> release_file = factory.makeProductReleaseFile(
    ...     signed=False)
    >>> html = test_tales("release_file/fmt:link", release_file=release_file)
    >>> soup = BeautifulSoup(html)
    >>> print_hrefs_with_titles(html)
    http://.../+download/test.txt: test file (4 bytes)
    http://.../+download/test.txt/+md5:

The url for the release file can be retrieved using fmt:url.

    >>> print test_tales("release_file/fmt:url", release_file=release_file)
    http://launchpad.dev/.../+download/test.txt

HTML in the file description is escaped in the fmt:link.

    >>> release_file = factory.makeProductReleaseFile(
    ...     signed=False, description='><script>XSS failed</script>')
    >>> print test_tales("release_file/fmt:link", release_file=release_file)
    <img ...
    <a title="&gt;&lt;script&gt;XSS failed&lt;/script&gt; (4 bytes)"
    href="http://launchpad.dev/.../+download/test.txt">test.txt</a> ...



Product series
..............

    >>> product_series = factory.makeProductSeries()
    >>> test_tales("product_series/fmt:link", product_series=product_series)
    u'... series...'


Blueprints
..........

    >>> from lp.blueprints.interfaces.specification import (
    ...     SpecificationPriority)
    >>> login('test@canonical.com')
    >>> specification = factory.makeSpecification(
    ...     priority=SpecificationPriority.UNDEFINED)
    >>> test_tales("specification/fmt:link", specification=specification)
    u'<a...class="sprite blueprint-undefined">...</a>'


Blueprint branches
..................

    >>> specification = factory.makeSpecification(
    ...     priority=SpecificationPriority.UNDEFINED)
    >>> branch = factory.makeAnyBranch()
    >>> specification_branch = specification.linkBranch(branch, branch.owner)
    >>> test_tales("specification_branch/fmt:link",
    ...     specification_branch=specification_branch)
    u'<a...class="sprite blueprint-undefined">...</a>'


Projects
........

    >>> product = factory.makeProduct()
    >>> test_tales('product/fmt:link', product=product)
    u'<a href=... class="sprite product">...</a>'


Questions
.........

    >>> from lp.answers.interfaces.questioncollection import IQuestionSet
    >>> question = getUtility(IQuestionSet).get(1)
    >>> test_tales("question/fmt:link", question=question)
    u'<a... class="sprite question">1:...</a>'


Distributions
.............

    >>> distribution = factory.makeDistribution()
    >>> test_tales("distribution/fmt:link", distribution=distribution)
    u'<a... class="sprite distribution">...</a>'


Distribution Series
...................

    >>> distroseries = factory.makeDistroArchSeries().distroseries
    >>> test_tales("distroseries/fmt:link", distroseries=distroseries)
    u'<a href="...">...</a>'


The fmt: namespace for specially formatted object info
------------------------------------------------------


Bug Trackers
............

    >>> from lp.bugs.interfaces.bugtracker import IBugTrackerSet
    >>> bugtracker = getUtility(IBugTrackerSet).getByName('email')
    >>> bugtracker.title = 'an@email.address bug tracker'
    >>> bugtracker.aliases = ['mailto:eatme@wundrlnd.com',
    ...                       'http://bugs.vikingsrool.no/']

The "standard" 'url' name is supported:

    >>> test_tales("bugtracker/fmt:url", bugtracker=bugtracker)
    u'http://bugs.launchpad.dev/bugs/bugtrackers/email'

(The url is relative if possible, and our test request claims to be from
launchpad.dev, so the url is relative.)

As are 'link', 'external-link', 'external-title-link' and 'aliases',
which help when hiding email addresses from users who are not logged in.

    >>> def print_formatted_bugtrackers():
    ...     expression = "bugtracker/fmt:%s"
    ...     for format in ['link', 'external-link', 'external-title-link']:
    ...         print '%s -->\n  %r' % (
    ...             format, test_tales(expression % format,
    ...                                bugtracker=bugtracker))
    ...     print 'aliases -->\n  %r' % (
    ...         list(test_tales(expression % 'aliases',
    ...                         bugtracker=bugtracker)),)

    >>> login('test@canonical.com')
    >>> print_formatted_bugtrackers()
    link -->
      u'<a href=".../bugs/bugtrackers/email">an@email.address bug tracker</a>'
    external-link -->
      u'<a class="link-external"
        href="mailto:bugs@example.com">mailto:bugs@example.com</a>'
    external-title-link -->
      u'<a class="link-external"
        href="mailto:bugs@example.com">an@email.address bug tracker</a>'
    aliases -->
      [u'http://bugs.vikingsrool.no/', u'mailto:eatme@wundrlnd.com']

    >>> login(ANONYMOUS)
    >>> print_formatted_bugtrackers()
    link -->
      u'<a href="...ckers/email">&lt;email address hidden&gt; bug tracker</a>'
    external-link -->
      u'mailto:&lt;email address hidden&gt;'
    external-title-link -->
      u'&lt;email address hidden&gt; bug tracker'
    aliases -->
      [u'http://bugs.vikingsrool.no/', u'mailto:&lt;email address hidden&gt;']

    >>> login('test@canonical.com')


Bug Watches
...........

    >>> from lp.bugs.interfaces.bugwatch import IBugWatchSet
    >>> sf_bugwatch = getUtility(IBugWatchSet).createBugWatch(
    ...     getUtility(IBugSet).get(12),
    ...     getUtility(ILaunchBag).user,
    ...     getUtility(IBugTrackerSet).getByName('sf'),
    ...     '1234')
    >>> email_bugwatch = getUtility(IBugWatchSet).createBugWatch(
    ...     getUtility(IBugSet).get(12),                   # bug
    ...     getUtility(ILaunchBag).user,                   # owner
    ...     getUtility(IBugTrackerSet).getByName('email'), # bugtracker
    ...     '')                                            # remotebug

The "standard" 'url' name is supported:

    >>> test_tales("bugwatch/fmt:url", bugwatch=sf_bugwatch)
    u'http://bugs.launchpad.dev/bugs/12/+watch/13'

    >>> test_tales("bugwatch/fmt:url", bugwatch=email_bugwatch)
    u'http://bugs.launchpad.dev/bugs/12/+watch/14'

As are 'external-link' and 'external-link-short', which help when hiding
email addresses from users who are not logged in:

    >>> login('test@canonical.com')

    >>> test_tales("bugwatch/fmt:external-link", bugwatch=sf_bugwatch)
    u'<a class="link-external"
      href="http://sourceforge.net/support/tracker.php?aid=1234">sf #1234</a>'

    >>> test_tales("bugwatch/fmt:external-link-short", bugwatch=sf_bugwatch)
    u'<a class="link-external"
      href="http://sourceforge.net/support/tracker.php?aid=1234">1234</a>'

    >>> test_tales("bugwatch/fmt:external-link", bugwatch=email_bugwatch)
    u'<a class="link-external" href="mailto:bugs@example.com">email</a>'

    >>> test_tales(
    ...     "bugwatch/fmt:external-link-short", bugwatch=email_bugwatch)
    u'<a class="link-external" href="mailto:bugs@example.com">&mdash;</a>'

    >>> login(ANONYMOUS)

    >>> test_tales("bugwatch/fmt:external-link", bugwatch=sf_bugwatch)
    u'<a class="link-external"
      href="http://sourceforge.net/support/tracker.php?aid=1234">sf #1234</a>'

    >>> test_tales("bugwatch/fmt:external-link-short", bugwatch=sf_bugwatch)
    u'<a class="link-external"
      href="http://sourceforge.net/support/tracker.php?aid=1234">1234</a>'

    >>> test_tales("bugwatch/fmt:external-link", bugwatch=email_bugwatch)
    u'email'

    >>> test_tales(
    ...     "bugwatch/fmt:external-link-short", bugwatch=email_bugwatch)
    u'&mdash;'

    >>> login('test@canonical.com')


The fmt: namespace to get strings (hiding)
------------------------------------------

PGP blocks, signatures and full-quoted parts of a message can be wrapped
in markup to hide them:

    >>> pgp_open = ('-----BEGIN PGP SIGNED MESSAGE-----\n'
    ...             'Hash: SHA1\n'
    ...             '\n')
    >>> text = ('Top quoting is simply bad netiquette.\n'
    ...         'The words of the leading text should be displayed\n'
    ...         'normally--no markup to hide it from view.\n'
    ...         'Raise your hand if you can read this.\n'
    ...         '\n')
    >>> signature = ('-- \n'
    ...              '__C U R T I S  C.  H O V E Y_______\n'
    ...              'sinzui.is@example.org\n'
    ...              'Guilty of stealing everything I am.\n'
    ...              '\n')
    >>> pgp_close = ('-----BEGIN PGP SIGNATURE-----\n'
    ...              'Version: GnuPG v1.4.1 (GNU/Linux)\n'
    ...              'Comment: Using GnuPG with Thunderbird\n'
    ...              '\n'
    ...              'iD8DBQFED60Y0F+nu1YWqI0RAqrNAJ9hTww5vqDbxp4xJS8ek58W\n'
    ...              'T2PIWy0CUJsX8RXSt/M51WE=\n'
    ...              '=J2S5\n'
    ...              '-----END PGP SIGNATURE-----\n')

The email-to-html formatter marks up text as html using the text-to-html
formatter, then adds additional markup to identify signatures and quoted
passages. The formatters  wraps the text inside the paragraph in a span
of 'foldable' class. Stylesheets and scripts in the browser can format
or change the behaviour of the text as needed.

When given simple paragraphs it behaves just as the text-to-html
formatter.

    >>> print test_tales('foo/fmt:email-to-html',
    ...                  foo=text)
    <p>Top quoting is simply bad netiquette.<br />
    The words of the leading text should be displayed<br />
    normally--no markup to hide it from view.<br />
    Raise your hand if you can read this.</p>

    >>> print test_tales('foo/fmt:text-to-html',
    ...                  foo=text)
    <p>Top quoting is simply bad netiquette.<br />
    The words of the leading text should be displayed<br />
    normally--no markup to hide it from view.<br />
    Raise your hand if you can read this.</p>


Marking PGP blocks
..................

PGP signed messages have opening and closing blocks that are wrapped in
a foldable span.

    >>> print test_tales('foo/fmt:email-to-html',
    ...                  foo='\n'.join([pgp_open, text, pgp_close]))
    <p><span class="foldable">-----BEGIN PGP SIGNED MESSAGE-----<br />
    Hash: SHA1
    </span></p>
    <p>Top quoting is simply bad netiquette.<br />
    The words of the leading text should be displayed<br />
    normally--no markup to hide it from view.<br />
    Raise your hand if you can read this.</p>
    <p><span class="foldable">-----BEGIN PGP SIGNATURE-----<br />
    Version: GnuPG v1.4.1 (GNU/Linux)<br />
    Comment: Using GnuPG with Thunderbird<br />
    <br />
    iD8DBQFED60Y0F+<wbr></wbr>nu1YWqI0RAqrNAJ<wbr></wbr>...
    T2PIWy0CUJsX8RX<wbr></wbr>St/M51WE=<br />
    =J2S5<br />
    -----END PGP SIGNATURE-----
    </span></p>

In this example, we see the main paragraph and the signature marked up
as HTML. All the text inside the signature is wrapped with the foldable
span.

    >>> print test_tales('foo/fmt:email-to-html',
    ...                  foo='\n'.join([text, signature]))
    <p>Top quoting is simply bad netiquette.<br />
    The words of the leading text should be displayed<br />
    normally--no markup to hide it from view.<br />
    Raise your hand if you can read this.</p>
    <p><span class="foldable"...>--<br />
    __C U R T I S  C.  H O V E Y_______<br />
    sinzui.<wbr></wbr>is@example.<wbr></wbr>org<br />
    Guilty of stealing everything I am.
    </span></p>


Marking quoted passages
.......................

Quoted passages are treated somewhat different from signatures because
they often have a citation line before the quoted text. In this example
of the main paragraph and the quoted paragraph, only the lines that
start with the quote identifier ('> ' in this case) are wrapped with the
foldable-quoted span.

    >>> quoted_text = ('Somebody said sometime ago:\n'
    ...                '> 1. Remove the letters  c, j, q, x, w\n'
    ...                '>    from the English Language.\n'
    ...                '> 2. Remove the penny from US currency.\n'
    ...                '\n')
    >>> quoted_text_all = ('> continuing from a previous thought.\n'
    ...                    '> 3. Get new handwriting.\n'
    ...                    '> 4. Add Year Zero to the calendar.\n'
    ...                    '\n')
    >>> print test_tales('foo/fmt:email-to-html',
    ...                  foo='\n'.join([text, quoted_text, quoted_text_all]))
    <p>Top quoting is simply bad netiquette.<br />
    The words of the leading text should be displayed<br />
    normally--no markup to hide it from view.<br />
    Raise your hand if you can read this.</p>
    <p>Somebody said sometime ago:<br />
    <span class="foldable-quoted">
    &gt; 1. Remove the letters  c, j, q, x, w<br />
    &gt;    from the English Language.<br />
    &gt; 2. Remove the penny from US currency.
    </span></p>
    <p><span class="foldable-quoted">&gt; continuing from a previous thoug...
    &gt; 3. Get new handwriting.<br />
    &gt; 4. Add Year Zero to the calendar.
    </span></p>


Different kinds of content can be marked up in a single call
............................................................

The formatter is indifferent to the number and kinds of paragraphs it
must markup. We can format the three examples at the same time.

    >>> print test_tales('foo/fmt:email-to-html',
    ...     foo='\n'.join(
    ...         [text, quoted_text, text, quoted_text_all, signature]))
    <p>Top quoting is simply bad netiquette.<br />
    The words of the leading text should be displayed<br />
    normally--no markup to hide it from view.<br />
    Raise your hand if you can read this.</p>
    <p>Somebody said sometime ago:<br />
    <span class="foldable-quoted"...>
    &gt; 1. Remove the letters  c, j, q, x, w<br />
    &gt;    from the English Language.<br />
    &gt; 2. Remove the penny from US currency.
    </span></p>
    <p>Top quoting is simply bad netiquette.<br />
    The words of the leading text should be displayed<br />
    normally--no markup to hide it from view.<br />
    Raise your hand if you can read this.</p>
    <p><span class="foldable-quoted">&gt; continuing from a previous thoug...
    &gt; 3. Get new handwriting.<br />
    &gt; 4. Add Year Zero to the calendar.
    </span></p>
    <p><span class="foldable"...>--<br />
    __C U R T I S  C.  H O V E Y_______<br />
    sinzui.<wbr></wbr>is@example.<wbr></wbr>org<br />
    Guilty of stealing everything I am.
    </span></p>


Escaping strings
................

To escape a string you should use fmt:escape.

    >>> test_tales('foo/fmt:escape', foo='some value')
    'some value'

    >>> test_tales('foo/fmt:escape', foo='some <br /> value')
    'some &lt;br /&gt; value'


CSS ids
-------

Strings can be converted to valid CSS ids. The id will start with 'j' if
the start of the string is not a letter.

    >>> test_tales('foo/fmt:css-id', foo='beta2-milestone')
    'beta2-milestone'

    >>> test_tales('foo/fmt:css-id', foo='user name')
    'user-name'

    >>> test_tales('foo/fmt:css-id', foo='1.0.1_series')
    'j1-0-1-series'

An optional prefix for the if can be added to the path. It too will be
escaped.

    >>> test_tales('foo/fmt:css-id/series-', foo='1.0.1_series')
    'series-1-0-1-series'

    >>> test_tales('foo/fmt:css-id/series_', foo='1.0.1_series')
    'series-1-0-1-series'

    >>> test_tales('foo/fmt:css-id/0series-', foo='1.0.1_series')
    'j0series-1-0-1-series'


The fmt: namespace to get strings (obfuscation)
-----------------------------------------------

Email addresses embedded in text can be obfuscated. In cases where
personal information may be in the content, and it will be shown to
unauthenticated users, the email address can be hidden. The address is
replaced with the message '<email address hidden>'.

    >>> logout() # Pretend we're unauthenticated.
    >>> test_tales('foo/fmt:obfuscate-email', foo='name.surname@company.com')
    '<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email', foo='name@organization.org.cc')
    '<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email', foo='name+sub@domain.org')
    '<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email',
    ...     foo='long_name@host.long-network.org.cc')
    '<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email',
    ...     foo='"long/name="@organization.org')
    '"<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email',
    ...     foo='long-name@building.museum')
    '<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email', foo='foo@staticmethod.com')
    '<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email', foo='<foo@bar.com>')
    '<email address hidden>'

    >>> print test_tales('foo/fmt:obfuscate-email/fmt:text-to-html',
    ...     foo=signature)
    <p>--<br />
    __C U R T I S  C.  H O V E Y_______<br />
    &lt;email address hidden&gt;<br />
    Guilty of stealing everything I am.</p>

    >>> test_tales('foo/fmt:obfuscate-email',
    ...     foo='mailto:long-name@very.long.dom.cc')
    'mailto:<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email',
    ...     foo='http://person:password@site.net')
    'http://person:<email address hidden>'

    >>> test_tales('foo/fmt:obfuscate-email', foo='name @ host.school.edu')
    'name @ host.school.edu'

    >>> test_tales('foo/fmt:obfuscate-email', foo='person@host')
    'person@host'

    >>> test_tales('foo/fmt:obfuscate-email', foo='(head, tail)=@array')
    '(head, tail)=@array'

    >>> test_tales('foo/fmt:obfuscate-email', foo='@staticmethod')
    '@staticmethod'

    >>> test_tales('foo/fmt:obfuscate-email', foo='element/@attribute')
    'element/@attribute'

    >>> bad_address = (
    ...     "medicalwei@sara:~$ Spinning................................"
    ...     "...........................................................not")
    >>> test_tales('foo/fmt:obfuscate-email', foo=bad_address)
    'medicalwei@sara:~$ ...'

However, if the user is authenticated, the email address is not
obfuscated.

    >>> login('no-priv@canonical.com')
    >>> test_tales('foo/fmt:obfuscate-email', foo='user@site.net')
    'user@site.net'


Linkification of email addresses
--------------------------------

fmt:linkify-email will recognise email addresses that are registered in
Launchpad and linkify them to point at the profile page for that person.
The resulting HTML includes a person icon next to the linked text to
emphasise the linkage.

    >>> test_tales('foo/fmt:linkify-email',
    ...    foo='I am the mighty foo.bar@canonical.com hear me roar.')
    u'...<a href="http://launchpad.dev/~name16"
      class="sprite person">foo.bar@canonical.com</a>...'

Multiple addresses may be linkified at once:

    >>> test_tales('foo/fmt:linkify-email',
    ...     foo='foo.bar@canonical.com and cprov@ubuntu.com')
    u'<a href="http://launchpad.dev/~name16"
      class="sprite person">foo.bar@canonical.com</a>
      and <a href="http://launchpad.dev/~cprov"
        class="sprite person">cprov@ubuntu.com</a>'

Team addresses are linkified with a team icon:

    >>> test_tales('foo/fmt:linkify-email', foo='support@ubuntu.com')
    u'<a href="http://launchpad.dev/~ubuntu-team"
      class="sprite team">support@ubuntu.com</a>'

Unknown email addresses are not altered in any way:

    >>> test_tales('foo/fmt:linkify-email', foo='nobody@example.com')
    'nobody@example.com'

Users who specify that their email addresses must be hidden also do not
get linkified.  test@canonical.com is hidden:

    >>> person_set = getUtility(IPersonSet)
    >>> discreet_user = person_set.getByEmail('test@canonical.com')
    >>> discreet_user.hide_email_addresses
    True

    >>> test_tales('foo/fmt:linkify-email', foo='test@canonical.com')
    'test@canonical.com'


Test the 'fmt:' namespace where the context is a dict.
------------------------------------------------------

Test the 'fmt:url' namespace for canonical urls.

    >>> from zope.interface import implements
    >>> from canonical.launchpad.webapp.interfaces import ICanonicalUrlData
    >>> class ObjectThatHasUrl:
    ...     implements(ICanonicalUrlData)
    ...     path = 'bonobo/saki'
    ...     inside = None
    ...     rootsite = None

    >>> object_having_url = ObjectThatHasUrl()
    >>> test_tales('foo/fmt:url', foo=object_having_url)
    u'/bonobo/saki'

Now, we need to test that it gets the correct application URL from the
request.

Make a mock-up IBrowserRequest, and use this as the interaction.

    >>> from zope.interface import implements
    >>> from canonical.launchpad.webapp.interfaces import (
    ...     ILaunchpadBrowserApplicationRequest)
    >>> class MockBrowserRequest:
    ...     implements(ILaunchpadBrowserApplicationRequest,)
    ...
    ...     interaction = None
    ...     principal = None
    ...
    ...     def __init__(self):
    ...         self.annotations = {}
    ...
    ...     def getRootURL(self, rootsite):
    ...         return self.getApplicationURL() + '/'
    ...
    ...     def getApplicationURL(self):
    ...         return 'https://mandrill.example.org:23'
    ...
    ...     def setPrincipal(self, principal):
    ...         self.principal = principal

    >>> participation = MockBrowserRequest()

    >>> login(ANONYMOUS, participation)

Note how the URL has only a path part, because it is for the same site
as the current request.

    >>> test_tales('foo/fmt:url', foo=object_having_url)
    u'/bonobo/saki'


The some_string/fmt:something helper
------------------------------------

Test the 'fmt:' namespace where the context is None. In general, these
will return an empty string.  They are provided for ease of handling
NULL values from the database, which become None values for attributes
in content classes.

Everything you can do with 'something/fmt:foo', you should be able to do
with 'None/fmt:foo'.

    >>> test_tales('foo/fmt:shorten', foo=None)
    Traceback (most recent call last):
    ...
    LocationError: 'you need to traverse a number after fmt:shorten'

    >>> test_tales('foo/fmt:shorten/8', foo=None)
    ''

    >>> test_tales('foo/fmt:nl_to_br', foo=None)
    ''

    >>> test_tales('foo/fmt:nice_pre', foo=None)
    ''

    >>> test_tales('foo/fmt:break-long-words', foo=None)
    ''

    >>> test_tales('foo/fmt:date', foo=None)
    ''

    >>> test_tales('foo/fmt:time', foo=None)
    ''

    >>> test_tales('foo/fmt:datetime', foo=None)
    ''

    >>> test_tales('foo/fmt:rfc822utcdatetime', foo=None)
    ''

    >>> test_tales('foo/fmt:pagetitle', foo=None)
    ''

    >>> test_tales('foo/fmt:text-to-html', foo=None)
    ''

    >>> test_tales('foo/fmt:email-to-html', foo=None)
    ''

    >>> test_tales('foo/fmt:url', foo=None)
    ''

    >>> test_tales('foo/fmt:exactduration', foo=None)
    ''


The lp: namespace for presenting DBSchema items
-----------------------------------------------

This is deprecated, and should raise a deprecation warning in the
future, and eventually be removed.  It is no longer needed, now that we
have an EnumCol for sqlobject.

Test the 'lp:' namespace for presenting DBSchema items.

    >>> from lp.soyuz.enums import BinaryPackageFormat
    >>> deb = BinaryPackageFormat.DEB.value
    >>> test_tales('deb/lp:BinaryPackageFormat', deb=deb)
    'Ubuntu Package'


The someobject/required:some.Permission helper
----------------------------------------------

Test the 'required:' namespace.  We're already logged in as the
anonymous user, and anonymous users can't edit any person:

    >>> test_tales('person/required:launchpad.Edit', person=mark)
    False

Anonymous users can do anything with the zope.Public permission.

    >>> test_tales('person/required:zope.Public', person=mark)
    True

Queries about permissions that don't exist will raise an exception:

    >>> test_tales('person/required:mushroom.Badger', person=mark)
    Traceback (most recent call last):
    ...
    ValueError: ('Undefined permission id', 'mushroom.Badger')


The somevalue/enumvalue:ENUMVALUE helper
----------------------------------------

You can test whether a particular value that you have in your page
template matches a particular valid value for that DBSchema enum.

This was going to be called 'enum-value', but Zope doesn't allow this.
To be fixed upstream.

    >>> deb = BinaryPackageFormat.DEB
    >>> udeb = BinaryPackageFormat.UDEB
    >>> test_tales('deb/enumvalue:DEB', deb=deb)
    True

    >>> test_tales('deb/enumvalue:DEB', deb=udeb)
    False

We don't get a ValueError when we use a value that doesn't appear in the
DBSchema the item comes from.

    >>> test_tales('deb/enumvalue:CHEESEFISH', deb=udeb)
    Traceback (most recent call last):
    ...
    LocationError: 'The enumerated type BinaryPackageFormat does not have a
                     value CHEESEFISH.'

It is possible for dbschemas to have a 'None' value.  This is a bit
awkward, because when the value is None, we can't do any checking
whether a new value is from the correct schema.  In any case, this case
is not currently handled.

The enumvalue tales expression is designed to work with security wrapped
dbschema items too:

    >>> from zope.security.proxy import ProxyFactory
    >>> wrapped_deb = ProxyFactory(BinaryPackageFormat.DEB)
    >>> test_tales('deb/enumvalue:DEB', deb=wrapped_deb)
    True

    >>> test_tales('deb/enumvalue:UDEB', deb=wrapped_deb)
    False

    >>> test_tales('deb/enumvalue:CHEESEFISH', deb=wrapped_deb)
    Traceback (most recent call last):
    ...
    LocationError: 'The enumerated type BinaryPackageFormat does not have a
                     value CHEESEFISH.'


Formatting timedelta objects
----------------------------

Representing timedetla objects can be done using either exact or
approximate durations.

    >>> from datetime import timedelta
    >>> delta = timedelta(days=2)
    >>> test_tales('delta/fmt:exactduration', delta=delta)
    '2 days, 0 hours, 0 minutes, 0.0 seconds'

    >>> test_tales('delta/fmt:approximateduration', delta=delta)
    'two days'

    >>> test_tales('delta/fmt:approximateduration/use-digits', delta=delta)
    '2 days'

    >>> delta = timedelta(days=12, hours=6, minutes=30)
    >>> test_tales('delta/fmt:exactduration', delta=delta)
    '12 days, 6 hours, 30 minutes, 0.0 seconds'

    >>> test_tales('delta/fmt:approximateduration', delta=delta)
    '12 days'

    >>> test_tales('delta/fmt:approximateduration/use-digits', delta=delta)
    '12 days'

    >>> delta = timedelta(days=0, minutes=62)
    >>> test_tales('delta/fmt:exactduration', delta=delta)
    '1 hour, 2 minutes, 0.0 seconds'

    >>> test_tales('delta/fmt:approximateduration', delta=delta)
    'an hour'

    >>> test_tales('delta/fmt:approximateduration/use-digits', delta=delta)
    '1 hour'

    >>> delta = timedelta(days=0, minutes=82)
    >>> test_tales('delta/fmt:exactduration', delta=delta)
    '1 hour, 22 minutes, 0.0 seconds'

    >>> test_tales('delta/fmt:approximateduration', delta=delta)
    '1 hour 20 minutes'

    >>> test_tales('delta/fmt:approximateduration/use-digits', delta=delta)
    '1 hour 20 minutes'

    >>> delta = timedelta(days=0, seconds=62)
    >>> test_tales('delta/fmt:exactduration', delta=delta)
    '1 minute, 2.0 seconds'

    >>> test_tales('delta/fmt:approximateduration', delta=delta)
    'a minute'

    >>> test_tales('delta/fmt:approximateduration/use-digits', delta=delta)
    '1 minute'

    >>> delta = timedelta(days=0, seconds=90)
    >>> test_tales('delta/fmt:exactduration', delta=delta)
    '1 minute, 30.0 seconds'

    >>> test_tales('delta/fmt:approximateduration', delta=delta)
    'two minutes'

    >>> test_tales('delta/fmt:approximateduration/use-digits', delta=delta)
    '2 minutes'


Formatting Link objects
-----------------------

MenuLinks (ILink) can be formatted anchored text and icons.

    # Build a link like the MenuAPI does.

    >>> from canonical.launchpad.webapp.menu import Link, MenuLink
    >>> from canonical.launchpad.webapp.servers import LaunchpadTestRequest

    >>> request = LaunchpadTestRequest()
    >>> login(ANONYMOUS, request)
    >>> link = Link('+place', 'text', 'summary', icon='icon', enabled=True)
    >>> menu_link = MenuLink(link)
    >>> menu_link.url = "http://launchpad.dev/+place"
    >>> menu_link.name = 'test_link'

The link can be rendered as an anchored icon.

    >>> print test_tales('menu_link/fmt:icon', menu_link=menu_link)
    <a href="http://launchpad.dev/+place"
       class="menu-link-test_link sprite icon" title="summary"><span
       class="invisible-link">text</span></a>

The default rendering can be explicitly called too, text with an icon to
the left.

    >>> print test_tales('menu_link/fmt:link', menu_link=menu_link)
    <a href="http://launchpad.dev/+place"
       class="menu-link-test_link sprite icon" title="summary">text</a>

The 'edit', 'remove' and 'trash-icon' links are rendered icons followed
by text. They have both the sprite and modify CSS classes.

    >>> menu_link.icon = 'edit'
    >>> print test_tales('menu_link/fmt:link', menu_link=menu_link)
    <a href="http://launchpad.dev/+place"
       class="menu-link-test_link sprite modify edit" title="summary">text</a>

    >>> menu_link.icon = 'remove'
    >>> print test_tales('menu_link/fmt:link', menu_link=menu_link)
    <a href="http://launchpad.dev/+place"
       class="menu-link-test_link sprite modify remove"
         title="summary">text</a>

    >>> menu_link.icon = 'trash-icon'
    >>> print test_tales('menu_link/fmt:link', menu_link=menu_link)
    <a href="http://launchpad.dev/+place"
       class="menu-link-test_link sprite modify trash-icon"
         title="summary">text</a>

fmt:icon-link and fmt:link-icon are deprecated. They are an alias for
fmt:link. They do not control formatting as they once did; fmt:link
controls the format based on the icon name.

    >>> menu_link.icon = 'icon'
    >>> print test_tales('menu_link/fmt:icon-link', menu_link=menu_link)
    <a href="http://launchpad.dev/+place"
       class="menu-link-test_link sprite icon" title="summary">text</a>

    >>> print test_tales('menu_link/fmt:link-icon', menu_link=menu_link)
    <a href="http://launchpad.dev/+place"
       class="menu-link-test_link sprite icon" title="summary">text</a>

And the url format is also available.

    >>> print test_tales('menu_link/fmt:url', menu_link=menu_link)
    http://launchpad.dev/+place

If the link is disabled, no markup is rendered.

    >>> menu_link.enabled = False
    >>> test_tales('menu_link/fmt:icon', menu_link=menu_link)
    u''

    >>> test_tales('menu_link/fmt:link-icon', menu_link=menu_link)
    u''

    >>> test_tales('menu_link/fmt:link', menu_link=menu_link)
    u''

    >>> test_tales('menu_link/fmt:url', menu_link=menu_link)
    u''


CSS classes for public and private objects
------------------------------------------

Users need to recognise private information as they are viewing it. This
is accomplished with a CSS class.

Any object can be converted to the 'public' CSS class. The object does
not need to implement IPrivacy.

    >>> thing = object()
    >>> print test_tales('context/fmt:public-private-css', context=thing)
    public

The CSS class honors the state of the object's privacy if the object
supports the private attribute. If the object is not private, the class
is 'public'.

    >>> bug = factory.makeBug(title='public-and-private')
    >>> print bug.private
    False

    >>> print test_tales('context/fmt:public-private-css', context=bug)
    public

If the private attribute is True, the class is 'private'.

    >>> owner = bug.bugtasks[0].target.owner
    >>> login_person(owner)
    >>> bug.setPrivate(True, owner)
    True

    >>> print test_tales('context/fmt:public-private-css', context=bug)
    private

    >>> login(ANONYMOUS)


Formatting of private attributes on Teams
-----------------------------------------

To protect privacy of teams, the formatter for teams will only show the
data for link, displayname, and unique_displayname if the current user
has the appropriate privileges.

The team 'myteam' is a private team so only the team members
and Launchpad admins can see the details.

Foo Bar is an administrator so he can see all.

    >>> login('foo.bar@canonical.com')
    >>> myteam = getUtility(IPersonSet).getByName('myteam')
    >>> test_tales("team/fmt:link", team=myteam)
    u'<a ...class="sprite team"...>My Team</a>'

    >>> test_tales("team/fmt:displayname", team=myteam)
    u'My Team'

    >>> test_tales("team/fmt:unique_displayname", team=myteam)
    u'My Team (myteam)'

Owner is a member of myteam so he can see all.

    >>> login('owner@canonical.com')
    >>> test_tales("team/fmt:link", team=myteam)
    u'<a ...class="sprite team"...>My Team</a>'

    >>> test_tales("team/fmt:displayname", team=myteam)
    u'My Team'

    >>> test_tales("team/fmt:unique_displayname", team=myteam)
    u'My Team (myteam)'

No Priv is neither a member of myteam nor an administrator, so the
information about myteam is hidden.

    >>> login('no-priv@canonical.com')
    >>> test_tales("team/fmt:link", team=myteam)
    u'<span ...class="sprite team"...>&lt;hidden&gt;</span>'

    >>> test_tales("team/fmt:displayname", team=myteam)
    u'<hidden>'

    >>> test_tales("team/fmt:unique_displayname", team=myteam)
    u'<hidden>'

The anonymous user is not allowed to see private team details.

    >>> login(ANONYMOUS)
    >>> test_tales("team/fmt:link", team=myteam)
    u'<span ...class="sprite team"...>&lt;hidden&gt;</span>'

    >>> test_tales("team/fmt:displayname", team=myteam)
    u'<hidden>'

    >>> test_tales("team/fmt:unique_displayname", team=myteam)
    u'<hidden>'