This file is indexed.

/usr/share/pyshared/apport/crashdb_impl/launchpad.py is in python-apport 2.0.1-0ubuntu5.

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
# vim: set fileencoding=UTF-8 :
'''Crash database implementation for Launchpad.'''

# Copyright (C) 2007 - 2009 Canonical Ltd.
# Authors: Martin Pitt <martin.pitt@ubuntu.com> and Markus Korn <thekorn@gmx.de>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.

import urllib, tempfile, os.path, re, gzip, sys
import email
try:
    from cStringIO import StringIO
except ImportError:
    from io import StringIO

from launchpadlib.errors import HTTPError
from launchpadlib.launchpad import Launchpad

import apport.crashdb
import apport

default_credentials_path = os.path.expanduser('~/.cache/apport/launchpad.credentials')

def filter_filename(attachments):
    for attachment in attachments:
        try:
            f = attachment.data.open()
        except HTTPError:
            apport.error('Broken attachment on bug, ignoring')
            continue
        name = f.filename
        if name.endswith('.txt') or name.endswith('.gz'):
            yield f

def id_set(tasks):
    # same as set(int(i.bug.id) for i in tasks) but faster
    return set(int(i.self_link.split('/').pop()) for i in tasks)


class CrashDatabase(apport.crashdb.CrashDatabase):
    '''Launchpad implementation of crash database interface.'''

    def __init__(self, auth, options):
        '''Initialize Launchpad crash database.

        You need to specify a launchpadlib-style credentials file to
        access launchpad. If you supply None, it will use
        default_credentials_path (~/.cache/apport/launchpad.credentials).

        Recognized options are:
        - distro: Name of the distribution in Launchpad
        - project: Name of the project in Launchpad
        (Note that exactly one of "distro" or "project" must be given.)
        - launchpad_instance: If set, this uses the given launchpad instance
          instead of production (optional). This can be overriden or set by
          $APPORT_LAUNCHPAD_INSTANCE environment.
        - cache_dir: Path to a permanent cache directory; by default it uses a
          temporary one. (optional). This can be overridden or set by
          $APPORT_LAUNCHPAD_CACHE environment.
        - escalation_subscription: This subscribes the given person or team to
          a bug once it gets the 10th duplicate.
        - escalation_tag: This adds the given tag to a bug once it gets more
          than 10 duplicates.
        '''
        if os.getenv('APPORT_LAUNCHPAD_INSTANCE'):
            options['launchpad_instance'] = os.getenv(
                'APPORT_LAUNCHPAD_INSTANCE')
        if not auth:
            lp_instance = options.get('launchpad_instance')
            if lp_instance:
                auth = default_credentials_path + '.' + lp_instance.split('://', 1)[-1]
            else:
                auth = default_credentials_path
        apport.crashdb.CrashDatabase.__init__(self, auth, options)

        self.distro = options.get('distro')
        if self.distro:
            assert 'project' not in options, 'Must not set both "project" and "distro" option'
        else:
            assert 'project' in options, 'Need to have either "project" or "distro" option'

        self.arch_tag = 'need-%s-retrace' % apport.packaging.get_system_architecture()
        self.options = options
        self.auth = auth
        assert self.auth

        self.__launchpad = None
        self.__lp_distro = None
        self.__lpcache = os.getenv('APPORT_LAUNCHPAD_CACHE', options.get('cache_dir'))

    @property
    def launchpad(self):
        '''Return Launchpad instance.'''

        if self.__launchpad:
            return self.__launchpad

        if self.options.get('launchpad_instance'):
            launchpad_instance = self.options.get('launchpad_instance')
        else:
            launchpad_instance = 'production'

        auth_dir = os.path.dirname(self.auth)
        if auth_dir and not os.path.isdir(auth_dir):
            os.makedirs(auth_dir)

        try:
            self.__launchpad = Launchpad.login_with('apport-collect',
                    launchpad_instance, launchpadlib_dir=self.__lpcache,
                    allow_access_levels=['WRITE_PRIVATE'],
                    credentials_file = self.auth,
                    version='1.0')
        except Exception as e:
            if hasattr(e, 'content'):
                msg = e.content
            else:
                msg = str(e)
            apport.error('connecting to Launchpad failed: %s\nYou can reset the credentials by removing the file "%s"', msg, self.auth)
            sys.exit(99) # transient error

        return self.__launchpad

    def _get_distro_tasks(self, tasks):
        if not self.distro:
            raise StopIteration

        for t in tasks:
            if t.bug_target_name.lower() == self.distro or \
                    re.match('^.+\(%s.*\)$' % self.distro, t.bug_target_name.lower()):
                yield t

    @property
    def lp_distro(self):
        if not self.distro:
            return None
        if self.__lp_distro is None:
            self.__lp_distro = self.launchpad.distributions[self.distro]
        return self.__lp_distro

    def upload(self, report, progress_callback = None):
        '''Upload given problem report return a handle for it.

        This should happen noninteractively.

        If the implementation supports it, and a function progress_callback is
        passed, that is called repeatedly with two arguments: the number of
        bytes already sent, and the total number of bytes to send. This can be
        used to provide a proper upload progress indication on frontends.
        '''
        assert self.accepts(report)

        # set reprocessing tags
        hdr = {}
        hdr['Tags'] = 'apport-%s' % report['ProblemType'].lower()
        a = report.get('PackageArchitecture')
        if not a or a == 'all':
            a = report.get('Architecture')
        if a:
            hdr['Tags'] += ' ' + a
        if 'Tags' in report:
            hdr['Tags'] += ' ' + report['Tags'].lower()

        # privacy/retracing for distro reports
        # FIXME: ugly hack until LP has a real crash db
        if 'DistroRelease' in report:
            if a and ('VmCore' in report or 'CoreDump' in report):
                hdr['Private'] = 'yes'
                hdr['Subscribers'] = 'apport'
                hdr['Tags'] += ' need-%s-retrace' % a
            elif 'Traceback' in report:
                hdr['Private'] = 'yes'
                hdr['Subscribers'] = 'apport'
                hdr['Tags'] += ' need-duplicate-check'
        if 'DuplicateSignature' in report and 'need-duplicate-check' not in hdr['Tags']:
                hdr['Tags'] += ' need-duplicate-check'

        # if we have checkbox submission key, link it to the bug; keep text
        # reference until the link is shown in Launchpad's UI
        if 'CheckboxSubmission' in report:
            hdr['HWDB-Submission'] = report['CheckboxSubmission']

        # order in which keys should appear in the temporary file
        order = [ 'ProblemType', 'DistroRelease', 'Package', 'Regression', 'Reproducible',
        'TestedUpstream', 'ProcVersionSignature', 'Uname', 'NonfreeKernelModules' ]

        # write MIME/Multipart version into temporary file
        mime = tempfile.TemporaryFile()
        report.write_mime(mime, extra_headers=hdr, skip_keys=['Tags'], priority_fields=order)
        mime.flush()
        mime.seek(0)

        ticket = upload_blob(mime, progress_callback,
                hostname=self.get_hostname())
        assert ticket
        return ticket

    def get_hostname(self):
        '''Return the hostname for the Launchpad instance.'''

        launchpad_instance = self.options.get('launchpad_instance')
        if launchpad_instance:
            if launchpad_instance == 'staging':
                hostname = 'staging.launchpad.net'
            else:
                hostname = 'launchpad.dev'
        else:
            hostname = 'launchpad.net'
        return hostname

    def get_comment_url(self, report, handle):
        '''Return an URL that should be opened after report has been uploaded
        and upload() returned handle.

        Should return None if no URL should be opened (anonymous filing without
        user comments); in that case this function should do whichever
        interactive steps it wants to perform.'''

        args = {}
        title = report.get('Title', report.standard_title())
        if title:
            # always use UTF-8 encoding, urlencode() blows up otherwise in
            # python 2.7
            if type(title) != type(b''):
                title = title.encode('UTF-8')
            args['field.title'] = title

        hostname = self.get_hostname()

        project = self.options.get('project')

        if not project:
            if 'SourcePackage' in report:
                return 'https://bugs.%s/%s/+source/%s/+filebug/%s?%s' % (
                    hostname, self.distro, report['SourcePackage'], handle, urllib.urlencode(args))
            else:
                return 'https://bugs.%s/%s/+filebug/%s?%s' % (
                    hostname, self.distro, handle, urllib.urlencode(args))
        else:
            return 'https://bugs.%s/%s/+filebug/%s?%s' % (
                hostname, project, handle, urllib.urlencode(args))

    def get_id_url(self, report, id):
        '''Return URL for a given report ID.

        The report is passed in case building the URL needs additional
        information from it, such as the SourcePackage name.

        Return None if URL is not available or cannot be determined.
        '''
        return 'https://bugs.launchpad.net/bugs/' + str(id)

    def download(self, id):
        '''Download the problem report from given ID and return a Report.'''

        report = apport.Report()
        b = self.launchpad.bugs[id]

        # parse out fields from summary
        m = re.search(r'(ProblemType:.*)$', b.description, re.S)
        if not m:
            m = re.search(r'^--- \r?$[\r\n]*(.*)', b.description, re.M | re.S)
        assert m, 'bug description must contain standard apport format data'

        description = m.group(1).encode('UTF-8').replace('\xc2\xa0', ' ').replace('\r\n', '\n')

        if '\n\n' in description:
            # this often happens, remove all empty lines between top and
            # 'Uname'
            if 'Uname:' in description:
                # this will take care of bugs like LP #315728 where stuff
                # is added after the apport data
                (part1, part2) = description.split('Uname:', 1)
                description = part1.replace('\n\n', '\n') + 'Uname:' \
                    + part2.split('\n\n', 1)[0]
            else:
                # just parse out the Apport block; e. g. LP #269539
                description = description.split('\n\n', 1)[0]

        report.load(StringIO(description))

        if 'Date' not in report:
            # We had not submitted this field for a while, claiming it
            # redundant. But it is indeed required for up-to-the-minute
            # comparison with log files, etc. For backwards compatibility with
            # those reported bugs, read the creation date
            try:
                report['Date'] = b.date_created.ctime()
            except AttributeError:
                # support older wadllib API which returned strings
                report['Date'] = b.date_created
        if 'ProblemType' not in report:
            if 'apport-bug' in b.tags:
                report['ProblemType'] = 'Bug'
            elif 'apport-crash' in b.tags:
                report['ProblemType'] = 'Crash'
            elif 'apport-kernelcrash' in b.tags:
                report['ProblemType'] = 'KernelCrash'
            elif 'apport-package' in b.tags:
                report['ProblemType'] = 'Package'
            else:
                raise ValueError('cannot determine ProblemType from tags: ' + str(b.tags))

        report['Tags'] = ' '.join(b.tags)

        if 'Title' in report:
            report['OriginalTitle'] = report['Title']

        report['Title'] = b.title

        for attachment in filter_filename(b.attachments):
            key, ext = os.path.splitext(attachment.filename)
            # ignore attachments with invalid keys
            try:
                report[key] = ''
            except:
                continue
            if ext == '.txt':
                report[key] = attachment.read()
            elif ext == '.gz':
                try:
                    report[key] = gzip.GzipFile(fileobj=attachment).read()
                except IOError as e:
                    # some attachments are only called .gz, but are
                    # uncompressed (LP #574360)
                    if 'Not a gzip' not in str(e):
                        raise
                    attachment.seek(0)
                    report[key] = attachment.read()
            else:
                raise Exception('Unknown attachment type: ' + attachment.filename)
        return report

    def update(self, id, report, comment, change_description=False,
            attachment_comment=None, key_filter=None):
        '''Update the given report ID with all data from report.

        This creates a text comment with the "short" data (see
        ProblemReport.write_mime()), and creates attachments for all the
        bulk/binary data.

        If change_description is True, and the crash db implementation supports
        it, the short data will be put into the description instead (like in a
        new bug).

        comment will be added to the "short" data. If attachment_comment is
        given, it will be added to the attachment uploads.

        If key_filter is a list or set, then only those keys will be added.
        '''
        bug = self.launchpad.bugs[id]

        if key_filter:
            skip_keys = set(report.keys()) - set(key_filter)
        else:
            skip_keys = None

        # we want to reuse the knowledge of write_mime() with all its different input
        # types and output formatting; however, we have to dissect the mime ourselves,
        # since we can't just upload it as a blob
        mime = tempfile.TemporaryFile()
        report.write_mime(mime, skip_keys=skip_keys)
        mime.flush()
        mime.seek(0)
        msg = email.message_from_file(mime)
        msg_iter = msg.walk()

        # first part is the multipart container
        part = msg_iter.next()
        assert part.is_multipart()

        # second part should be an inline text/plain attachments with all short
        # fields
        part = msg_iter.next()
        assert not part.is_multipart()
        assert part.get_content_type() == 'text/plain'

        if not key_filter:
            # when we update a complete report, we are updating an existing bug
            # with apport-collect
            x = bug.tags[:] # LP#254901 workaround
            x.append('apport-collected')
            # add any tags (like the release) to the bug
            if 'Tags' in report:
                x += report['Tags'].lower().split()
            bug.tags = x
            bug.lp_save()
            bug = self.launchpad.bugs[id] # fresh bug object, LP#336866 workaround

        # short text data
        if change_description:
            bug.description = bug.description + '\n--- \n' + part.get_payload(decode=True).decode('UTF-8', 'replace')
            bug.lp_save()
        else:
            bug.newMessage(content=part.get_payload(decode=True),
                subject=comment)

        # other parts are the attachments:
        for part in msg_iter:
            # print '   attachment: %s...' % part.get_filename()
            bug.addAttachment(comment=attachment_comment or '',
                description=part.get_filename(),
                content_type=None,
                data=part.get_payload(decode=True),
                filename=part.get_filename(), is_patch=False)

    def update_traces(self, id, report, comment=''):
        '''Update the given report ID for retracing results.

        This updates Stacktrace, ThreadStacktrace, StacktraceTop,
        and StacktraceSource. You can also supply an additional comment.
        '''
        apport.crashdb.CrashDatabase.update_traces(self, id, report, comment)

        bug = self.launchpad.bugs[id]
        # ensure it's assigned to a package
        if 'SourcePackage' in report:
            for task in bug.bug_tasks:
                if task.target.resource_type_link.endswith('#distribution'):
                    task.target = self.lp_distro.getSourcePackage(name=report['SourcePackage'])
                    task.lp_save()
                    bug = self.launchpad.bugs[id]
                    break

        # remove core dump if stack trace is usable
        if report.has_useful_stacktrace():
            for a in bug.attachments:
                if a.title == 'CoreDump.gz':
                    try:
                        a.removeFromBug()
                    except HTTPError:
                        pass # LP#249950 workaround
            try:
                task = self._get_distro_tasks(bug.bug_tasks).next()
                if task.importance == 'Undecided':
                    task.importance = 'Medium'
                    task.lp_save()
            except StopIteration:
                pass # no distro tasks

            # update bug title with retraced function name
            fn = report.stacktrace_top_function()
            if fn:
                m = re.match('^(.*crashed with SIG.* in )([^( ]+)(\(\).*$)', bug.title)
                if m and m.group(2) != fn:
                    bug.title = m.group(1) + fn + m.group(3)
                    try:
                        bug.lp_save()
                    except HTTPError:
                        pass # LP#336866 workaround
                    bug = self.launchpad.bugs[id]

        self._subscribe_triaging_team(bug, report)

    def get_distro_release(self, id):
        '''Get 'DistroRelease: <release>' from the given report ID and return
        it.'''
        bug = self.launchpad.bugs[id]
        m = re.search('DistroRelease: ([-a-zA-Z0-9.+/ ]+)', bug.description)
        if m:
            return m.group(1)
        raise ValueError('URL does not contain DistroRelease: field')

    def get_affected_packages(self, id):
        '''Return list of affected source packages for given ID.'''

        bug_target_re = re.compile(
                    r'/%s/(?:(?P<suite>[^/]+)/)?\+source/(?P<source>[^/]+)$' %
                    self.distro)

        bug = self.launchpad.bugs[id]
        result = []

        for task in bug.bug_tasks:
            match = bug_target_re.search(task.target.self_link)
            if not match:
                continue
            if task.status in ('Invalid', "Won't Fix", 'Fix Released'):
                continue
            result.append(match.group('source'))
        return result

    def is_reporter(self, id):
        '''Check whether the user is the reporter of given ID.'''

        bug = self.launchpad.bugs[id]
        return bug.owner.name == self.launchpad.me.name

    def can_update(self, id):
        '''Check whether the user is eligible to update a report.

        A user should add additional information to an existing ID if (s)he is
        the reporter or subscribed, the bug is open, not a duplicate, etc. The
        exact policy and checks should be done according to  the particular
        implementation.
        '''
        bug = self.launchpad.bugs[id]
        if bug.duplicate_of:
            return False

        if bug.owner.name == self.launchpad.me.name:
            return True

        # check subscription
        me = self.launchpad.me.self_link
        for sub in bug.subscriptions.entries:
            if sub['person_link'] == me:
                return True

        return False

    def get_unretraced(self):
        '''Return an ID set of all crashes which have not been retraced yet and
        which happened on the current host architecture.'''
        try:
            bugs = self.lp_distro.searchTasks(tags=self.arch_tag, created_since='2011-08-01')
            return id_set(bugs)
        except Exception as e:
            apport.error('connecting to Launchpad failed: %s', str(e))
            sys.exit(99) # transient error

    def get_dup_unchecked(self):
        '''Return an ID set of all crashes which have not been checked for
        being a duplicate.

        This is mainly useful for crashes of scripting languages such as
        Python, since they do not need to be retraced. It should not return
        bugs that are covered by get_unretraced().'''

        try:
            bugs = self.lp_distro.searchTasks(tags='need-duplicate-check', created_since='2011-08-01')
            return id_set(bugs)
        except Exception as e:
            apport.error('connecting to Launchpad failed: %s', str(e))
            sys.exit(99) # transient error

    def get_unfixed(self):
        '''Return an ID set of all crashes which are not yet fixed.

        The list must not contain bugs which were rejected or duplicate.

        This function should make sure that the returned list is correct. If
        there are any errors with connecting to the crash database, it should
        raise an exception (preferably IOError).'''

        bugs = self.lp_distro.searchTasks(tags='apport-crash')
        return id_set(bugs)

    def _get_source_version(self, package):
        '''Return the version of given source package in the latest release of
        given distribution.

        If 'distro' is None, we will look for a launchpad project .
        '''
        sources = self.lp_distro.main_archive.getPublishedSources(
            exact_match=True,
            source_name=package,
            distro_series=self.lp_distro.current_series
        )
        # first element is the latest one
        return sources[0].source_package_version

    def get_fixed_version(self, id):
        '''Return the package version that fixes a given crash.

        Return None if the crash is not yet fixed, or an empty string if the
        crash is fixed, but it cannot be determined by which version. Return
        'invalid' if the crash report got invalidated, such as closed a
        duplicate or rejected.

        This function should make sure that the returned result is correct. If
        there are any errors with connecting to the crash database, it should
        raise an exception (preferably IOError).
        '''
        # do not do version tracking yet; for that, we need to get the current
        # distrorelease and the current package version in that distrorelease
        # (or, of course, proper version tracking in Launchpad itself)

        try:
            b = self.launchpad.bugs[id]
        except KeyError:
            return 'invalid'

        if b.duplicate_of:
            return 'invalid'

        tasks = list(b.bug_tasks) # just fetch it once

        if self.distro:
            distro_identifier = '(%s)' %self.distro.lower()
            fixed_tasks = filter(lambda task: task.status == 'Fix Released' and \
                    distro_identifier in task.bug_target_display_name.lower(), tasks)

            if not fixed_tasks:
                fixed_distro = filter(lambda task: task.status == 'Fix Released' and \
                        task.bug_target_name.lower() == self.distro.lower(), tasks)
                if fixed_distro:
                    # fixed in distro inself (without source package)
                    return ''

            if len(fixed_tasks) > 1:
                apport.warning('There is more than one task fixed in %s %s, using first one to determine fixed version', self.distro, id)
                return ''

            if fixed_tasks:
                task = fixed_tasks.pop()
                try:
                    return self._get_source_version(task.bug_target_display_name.split()[0])
                except IndexError:
                    # source does not exist any more
                    return 'invalid'
            else:
                # check if there only invalid ones
                invalid_tasks = filter(lambda task: task.status in ('Invalid', "Won't Fix", 'Expired') and \
                        distro_identifier in task.bug_target_display_name.lower(), tasks)
                if invalid_tasks:
                    non_invalid_tasks = filter(lambda task: task.status not in ('Invalid', "Won't Fix", 'Expired') and \
                        distro_identifier in task.bug_target_display_name.lower(), tasks)
                    if not non_invalid_tasks:
                        return 'invalid'
        else:
            fixed_tasks = filter(lambda task: task.status == 'Fix Released',
                    tasks)
            if fixed_tasks:
                # TODO: look for current series
                return ''
            # check if there any invalid ones
            if filter(lambda task: task.status == 'Invalid', tasks):
                return 'invalid'

        return None

    def duplicate_of(self, id):
        '''Return master ID for a duplicate bug.

        If the bug is not a duplicate, return None.
        '''
        b = self.launchpad.bugs[id].duplicate_of
        if b:
            return b.id
        else:
            return None

    def close_duplicate(self, report, id, master_id):
        '''Mark a crash id as duplicate of given master ID.

        If master is None, id gets un-duplicated.
        '''
        bug = self.launchpad.bugs[id]

        if master_id:
            assert id != master_id, 'cannot mark bug %s as a duplicate of itself' % str(id)

            # check whether the master itself is a dup
            master = self.launchpad.bugs[master_id]
            if master.duplicate_of:
                master = master.duplicate_of
                master_id = master.id
                if master.id == id:
                    # this happens if the bug was manually duped to a newer one
                    apport.warning('Bug %i was manually marked as a dupe of newer bug %i, not closing as duplicate',
                            id, master_id)
                    return

            for a in bug.attachments:
                if a.title in ('CoreDump.gz', 'Stacktrace.txt',
                    'ThreadStacktrace.txt', 'ProcMaps.txt', 'ProcStatus.txt',
                    'Registers.txt', 'Disassembly.txt'):
                    try:
                        a.removeFromBug()
                    except HTTPError:
                        pass # LP#249950 workaround

            bug = self.launchpad.bugs[id] # fresh bug object, LP#336866 workaround
            bug.newMessage(content='Thank you for taking the time to report this crash and helping \
to make this software better.  This particular crash has already been reported and \
is a duplicate of bug #%i, so is being marked as such.  Please look at the \
other bug report to see if there is any missing information that you can \
provide, or to see if there is a workaround for the bug.  Additionally, any \
further discussion regarding the bug should occur in the other report.  \
Please continue to report any other bugs you may find.' % master_id,
                subject='This bug is a duplicate')

            bug = self.launchpad.bugs[id] # refresh, LP#336866 workaround
            if bug.private:
                bug.private = False

            # set duplicate last, since we cannot modify already dup'ed bugs
            if not bug.duplicate_of:
                bug.duplicate_of = master

            if len(master.duplicates) == 10:
                if 'escalation_tag' in self.options and \
                    self.options['escalation_tag'] not in master.tags and \
                    self.options.get('escalated_tag', ' invalid ') not in master.tags:
                        master.tags = master.tags + [self.options['escalation_tag']] # LP#254901 workaround
                        master.lp_save()

                if 'escalation_subscription' in self.options and \
                    self.options.get('escalated_tag', ' invalid ') not in master.tags:
                    p = self.launchpad.people[self.options['escalation_subscription']]
                    master.subscribe(person=p)

            # requesting updated stack trace?
            if report.has_useful_stacktrace() and ('apport-request-retrace' in master.tags
                    or 'apport-failed-retrace' in master.tags):
                self.update(master_id, report, 'Updated stack trace from duplicate bug %i' % id,
                        key_filter=['Stacktrace', 'ThreadStacktrace',
                            'Package', 'Dependencies', 'ProcMaps', 'ProcCmdline'])

                master = self.launchpad.bugs[master_id]
                x = master.tags[:] # LP#254901 workaround
                try:
                    x.remove('apport-failed-retrace')
                except ValueError:
                    pass
                try:
                    x.remove('apport-request-retrace')
                except ValueError:
                    pass
                master.tags = x
                try:
                    master.lp_save()
                except HTTPError:
                    pass # LP#336866 workaround

        else:
            if bug.duplicate_of:
                bug.duplicate_of = None

        if bug._dirty_attributes: # LP#336866 workaround
            bug.lp_save()

    def mark_regression(self, id, master):
        '''Mark a crash id as reintroducing an earlier crash which is
        already marked as fixed (having ID 'master').'''

        bug = self.launchpad.bugs[id]
        bug.newMessage(content='This crash has the same stack trace characteristics as bug #%i. \
However, the latter was already fixed in an earlier package version than the \
one in this report. This might be a regression or because the problem is \
in a dependent package.' % master,
            subject='Possible regression detected')
        bug = self.launchpad.bugs[id] # fresh bug object, LP#336866 workaround
        bug.tags = bug.tags + ['regression-retracer'] # LP#254901 workaround
        bug.lp_save()

    def mark_retraced(self, id):
        '''Mark crash id as retraced.'''

        bug = self.launchpad.bugs[id]
        if self.arch_tag in bug.tags:
            x = bug.tags[:] # LP#254901 workaround
            x.remove(self.arch_tag)
            bug.tags = x
            try:
                bug.lp_save()
            except HTTPError:
                pass # LP#336866 workaround

    def mark_retrace_failed(self, id, invalid_msg=None):
        '''Mark crash id as 'failed to retrace'.'''

        bug = self.launchpad.bugs[id]
        if invalid_msg:
            try:
                task = self._get_distro_tasks(bug.bug_tasks).next()
            except StopIteration:
                # no distro task, just use the first one
                task = bug.bug_tasks[0]
            task.status = 'Invalid'
            task.lp_save()
            bug.newMessage(content=invalid_msg,
                    subject='Crash report cannot be processed')

            for a in bug.attachments:
                if a.title == 'CoreDump.gz':
                    try:
                        a.removeFromBug()
                    except HTTPError:
                        pass # LP#249950 workaround
        else:
            if 'apport-failed-retrace' not in bug.tags:
                bug.tags = bug.tags + ['apport-failed-retrace'] # LP#254901 workaround
                bug.lp_save()

    def _mark_dup_checked(self, id, report):
        '''Mark crash id as checked for being a duplicate.'''

        bug = self.launchpad.bugs[id]

        # if we have a distro task without a package, fix it
        if 'SourcePackage' in report:
            for task in bug.bug_tasks:
                if task.target.resource_type_link.endswith('#distribution'):
                    task.target = self.lp_distro.getSourcePackage(
                        name=report['SourcePackage'])
                    task.lp_save()
                    bug = self.launchpad.bugs[id]
                    break

        if 'need-duplicate-check' in bug.tags:
            x = bug.tags[:] # LP#254901 workaround
            x.remove('need-duplicate-check')
            bug.tags = x
            bug.lp_save()
        self._subscribe_triaging_team(bug, report)

    def known(self, report):
        '''Check if the crash db already knows about the crash signature.

        Check if the report has a DuplicateSignature, crash_signature(), or
        StacktraceAddressSignature, and ask the database whether the problem is
        already known. If so, return an URL where the user can check the status
        or subscribe (if available), or just return True if the report is known
        but there is no public URL. In that case the report will not be
        uploaded (i. e. upload() will not be called).

        Return None if the report does not have any signature or the crash
        database does not support checking for duplicates on the client side.

        The default implementation uses a text file format generated by
        duplicate_db_publish() at an URL specified by the "dupdb_url" option.
        Subclasses are free to override this with a custom implementation, such
        as a real database lookup.
        '''
        # we override the method here to check if the user actually has access
        # to the bug, and if the bug requests more retraces; in either case we
        # should file it.
        url = apport.crashdb.CrashDatabase.known(self, report)

        if not url:
            return url

        # record the fact that it is a duplicate, for triagers
        report['DuplicateOf'] = url

        try:
            f = urllib.urlopen(url + '/+text')
        except IOError:
            # if we are offline, or LP is down, upload will fail anyway, so we
            # can just as well avoid the upload
            return url

        line = f.readline()
        if not line.startswith('bug:'):
            # presumably a 404 etc. page, which happens for private bugs
            return True

        # check tags
        for line in f:
            if line.startswith('tags:'):
                if 'apport-failed-retrace' in line or 'apport-request-retrace' in line:
                    return None
                else:
                    break

            # stop at the first task, tags are in the first block
            if not line.strip():
                break

        return url

    def _subscribe_triaging_team(self, bug, report):
        '''Subscribe the right triaging team to the bug.'''

        #FIXME: this entire function is an ugly Ubuntu specific hack until LP
        #gets a real crash db; see https://wiki.ubuntu.com/CrashReporting

        if 'DistroRelease' in report and report['DistroRelease'].split()[0] != 'Ubuntu':
            return # only Ubuntu bugs are filed private

        #use a url hack here, it is faster
        person = '%s~ubuntu-crashes-universe' %self.launchpad._root_uri
        bug.subscribe(person=person)

#
# Launchpad storeblob API (should go into launchpadlib, see LP #315358)
#

import multipartpost_handler, urllib2, time, httplib

_https_upload_callback = None

#
# This progress code is based on KodakLoader by Jason Hildebrand
# <jason@opensky.ca>. See http://www.opensky.ca/~jdhildeb/software/kodakloader/
# for details.
class HTTPSProgressConnection(httplib.HTTPSConnection):
    '''Implement a HTTPSConnection with an optional callback function for
    upload progress.'''

    def send(self, data):
        global _https_upload_callback

        # if callback has not been set, call the old method
        if not _https_upload_callback:
            httplib.HTTPSConnection.send(self, data)
            return

        sent = 0
        total = len(data)
        chunksize = 1024
        while sent < total:
            _https_upload_callback(sent, total)
            t1 = time.time()
            httplib.HTTPSConnection.send(self, data[sent:sent+chunksize])
            sent += chunksize
            t2 = time.time()

            # adjust chunksize so that it takes between .5 and 2
            # seconds to send a chunk
            if t2 - t1 < .5:
                chunksize *= 2
            elif t2 - t1 > 2:
                chunksize /= 2

class HTTPSProgressHandler(urllib2.HTTPSHandler):

    def https_open(self, req):
        return self.do_open(HTTPSProgressConnection, req)

def upload_blob(blob, progress_callback = None, hostname='launchpad.net'):
    '''Upload blob (file-like object) to Launchpad.

    progress_callback can be set to a function(sent, total) which is regularly
    called with the number of bytes already sent and total number of bytes to
    send. It is called every 0.5 to 2 seconds (dynamically adapted to upload
    bandwidth).

    Return None on error, or the ticket number on success.

    By default this uses the production Launchpad hostname. Set
    hostname to 'launchpad.dev' or 'staging.launchpad.net' to use another
    instance for testing.
    '''
    ticket = None

    global _https_upload_callback
    _https_upload_callback = progress_callback

    opener = urllib2.build_opener(HTTPSProgressHandler, multipartpost_handler.MultipartPostHandler)
    url = 'https://%s/+storeblob' % hostname
    result = opener.open(url,
        { 'FORM_SUBMIT': '1', 'field.blob': blob })
    ticket = result.info().get('X-Launchpad-Blob-Token')

    return ticket

#
# Unit tests
#

if __name__ == '__main__':
    import unittest, urllib2, atexit, shutil, subprocess

    crashdb = None
    segv_report = None
    python_report = None

    class _T(unittest.TestCase):
        # this assumes that a source package 'coreutils' exists and builds a
        # binary package 'coreutils'
        test_package = 'coreutils'
        test_srcpackage = 'coreutils'

        #
        # Generic tests, should work for all CrashDB implementations
        #

        def setUp(self):
            global crashdb
            if not crashdb:
                crashdb = self._get_instance()
            self.crashdb = crashdb

            # create a local reference report so that we can compare
            # DistroRelease, Architecture, etc.
            self.ref_report = apport.Report()
            self.ref_report.add_os_info()
            self.ref_report.add_user_info()
            self.ref_report['SourcePackage'] = 'coreutils'

            # Objects tests rely on.
            self.uncommon_description_bug = self._file_uncommon_description_bug()
            self._create_project('langpack-o-matic')

            # XXX Should create new bug reports, not reuse those.
            self.known_test_id = self.uncommon_description_bug.id
            self.known_test_id2 = self._file_uncommon_description_bug().id

        def _create_project(self, name):
            '''Create a project using launchpadlib to be used by tests.'''

            project = self.crashdb.launchpad.projects[name]
            if not project:
                self.crashdb.launchpad.projects.new_project(
                    description=name + 'description',
                    display_name=name,
                    name=name,
                    summary=name + 'summary',
                    title=name + 'title')

        def _file_uncommon_description_bug(self):
            '''File a bug report with an uncommon description.

            Example taken from real LP bug 269539. It contains only
            ProblemType/Architecture/DistroRelease in the description, and has
            free-form description text after the Apport data.
            '''
            desc = '''problem

ProblemType: Package
Architecture: amd64
DistroRelease: Ubuntu 8.10

more text

and more
'''
            return self.crashdb.launchpad.bugs.createBug(
                title=b'mixed description bug'.encode(),
                description=desc,
                target=self.crashdb.lp_distro)

        @property
        def hostname(self):
            '''Get the Launchpad hostname for the given crashdb.'''

            return self.crashdb.get_hostname()

        def _file_segv_report(self):
            '''File a SEGV crash report.

            Return (crash ID, report).
            '''
            r = self._generate_sigsegv_report()
            r.add_package_info(self.test_package)
            r.add_os_info()
            r.add_gdb_info()
            r.add_user_info()
            self.assertEqual(r.standard_title(), 'crash crashed with SIGSEGV in f()')

            # add some binary gibberish which isn't UTF-8
            r['ShortGibberish'] = ' "]\xb6"\n'
            r['LongGibberish'] = 'a\nb\nc\nd\ne\n\xff\xff\xff\n\f'

            handle = self.crashdb.upload(r)
            self.assertTrue(handle)
            bug_target = self._get_bug_target(self.crashdb, r)
            self.assertTrue(bug_target)

            id = self._file_bug(bug_target, r, handle)
            self.assertTrue(id > 0)
            return (id, r)

        def test_1_report_segv(self):
            '''upload() and get_comment_url() for SEGV crash

            This needs to run first, since it sets segv_report.
            '''
            global segv_report
            (id, report) = self._file_segv_report()
            segv_report = id
            url = self.crashdb.get_comment_url(report, id)

            sys.stderr.write('(https://%s/bugs/%i) ' % (self.hostname, id))

            #TODO: check this programatically
            sys.stderr.write('[%s] ' % url)

        def test_1_report_python(self):
            '''upload() and get_comment_url() for Python crash

            This needs to run early, since it sets python_report.
            '''
            r = apport.Report('Crash')
            r['ExecutablePath'] = '/bin/foo'
            r['Traceback'] = '''Traceback (most recent call last):
  File "/bin/foo", line 67, in fuzz
    print(weird)
NameError: global name 'weird' is not defined'''
            r['Tags'] = 'boogus pybogus'
            r.add_package_info(self.test_package)
            r.add_os_info()
            r.add_user_info()
            self.assertEqual(r.standard_title(),
                "foo crashed with NameError in fuzz(): global name 'weird' is not defined")

            handle = self.crashdb.upload(r)
            self.assertTrue(handle)
            bug_target = self._get_bug_target(self.crashdb, r)
            self.assertTrue(bug_target)

            id = self._file_bug(bug_target, r, handle)
            self.assertTrue(id > 0)
            global python_report
            python_report = id
            sys.stderr.write('(https://%s/bugs/%i) ' % (self.hostname, id))

        def test_2_download(self):
            '''download()'''

            r = self.crashdb.download(segv_report)
            self.assertEqual(r['ProblemType'], 'Crash')
            self.assertEqual(r['Title'], 'crash crashed with SIGSEGV in f()')
            self.assertEqual(r['DistroRelease'], self.ref_report['DistroRelease'])
            self.assertEqual(r['Architecture'], self.ref_report['Architecture'])
            self.assertEqual(r['Uname'], self.ref_report['Uname'])
            self.assertEqual(r.get('NonfreeKernelModules'),
                self.ref_report.get('NonfreeKernelModules'))
            self.assertEqual(r.get('UserGroups'), self.ref_report.get('UserGroups'))
            tags = set(r['Tags'].split())
            self.assertEqual(tags, set([self.crashdb.arch_tag, 'apport-crash',
                apport.packaging.get_system_architecture()]))

            self.assertEqual(r['Signal'], '11')
            self.assertTrue(r['ExecutablePath'].endswith('/crash'))
            self.assertEqual(r['SourcePackage'], self.test_srcpackage)
            self.assertTrue(r['Package'].startswith(self.test_package + ' '))
            self.assertTrue('f (x=42)' in r['Stacktrace'])
            self.assertTrue('f (x=42)' in r['StacktraceTop'])
            self.assertTrue('f (x=42)' in r['ThreadStacktrace'])
            self.assertTrue(len(r['CoreDump']) > 1000)
            self.assertTrue('Dependencies' in r)
            self.assertTrue('Disassembly' in r)
            self.assertTrue('Registers' in r)

            # check tags
            r = self.crashdb.download(python_report)
            tags = set(r['Tags'].split())
            self.assertEqual(tags, set(['apport-crash', 'boogus', 'pybogus',
                'need-duplicate-check', apport.packaging.get_system_architecture()]))

        def test_3_update_traces(self):
            '''update_traces()'''

            r = self.crashdb.download(segv_report)
            self.assertTrue('CoreDump' in r)
            self.assertTrue('Dependencies' in r)
            self.assertTrue('Disassembly' in r)
            self.assertTrue('Registers' in r)
            self.assertTrue('Stacktrace' in r)
            self.assertTrue('ThreadStacktrace' in r)
            self.assertEqual(r['Title'], 'crash crashed with SIGSEGV in f()')

            # updating with a useless stack trace retains core dump
            r['StacktraceTop'] = '?? ()'
            r['Stacktrace'] = 'long\ntrace'
            r['ThreadStacktrace'] = 'thread\neven longer\ntrace'
            r['FooBar'] = 'bogus'
            self.crashdb.update_traces(segv_report, r, 'I can has a better retrace?')
            r = self.crashdb.download(segv_report)
            self.assertTrue('CoreDump' in r)
            self.assertTrue('Dependencies' in r)
            self.assertTrue('Disassembly' in r)
            self.assertTrue('Registers' in r)
            self.assertTrue('Stacktrace' in r) # TODO: ascertain that it's the updated one
            self.assertTrue('ThreadStacktrace' in r)
            self.assertFalse('FooBar' in r)
            self.assertEqual(r['Title'], 'crash crashed with SIGSEGV in f()')

            tags = self.crashdb.launchpad.bugs[segv_report].tags
            self.assertTrue('apport-crash' in tags)
            self.assertFalse('apport-collected' in tags)

            # updating with a useful stack trace removes core dump
            r['StacktraceTop'] = 'read () from /lib/libc.6.so\nfoo (i=1) from /usr/lib/libfoo.so'
            r['Stacktrace'] = 'long\ntrace'
            r['ThreadStacktrace'] = 'thread\neven longer\ntrace'
            self.crashdb.update_traces(segv_report, r, 'good retrace!')
            r = self.crashdb.download(segv_report)
            self.assertFalse('CoreDump' in r)
            self.assertTrue('Dependencies' in r)
            self.assertTrue('Disassembly' in r)
            self.assertTrue('Registers' in r)
            self.assertTrue('Stacktrace' in r)
            self.assertTrue('ThreadStacktrace' in r)
            self.assertFalse('FooBar' in r)

            # as previous title had standard form, the top function gets
            # updated
            self.assertEqual(r['Title'], 'crash crashed with SIGSEGV in read()')

            # respects title amendments
            bug = self.crashdb.launchpad.bugs[segv_report]
            bug.title = 'crash crashed with SIGSEGV in f() on exit'
            try:
                bug.lp_save()
            except HTTPError:
                pass # LP#336866 workaround
            r['StacktraceTop'] = 'read () from /lib/libc.6.so\nfoo (i=1) from /usr/lib/libfoo.so'
            self.crashdb.update_traces(segv_report, r, 'good retrace with title amendment')
            r = self.crashdb.download(segv_report)
            self.assertEqual(r['Title'], 'crash crashed with SIGSEGV in read() on exit')

            # does not destroy custom titles
            bug = self.crashdb.launchpad.bugs[segv_report]
            bug.title = 'crash is crashy'
            try:
                bug.lp_save()
            except HTTPError:
                pass # LP#336866 workaround

            r['StacktraceTop'] = 'read () from /lib/libc.6.so\nfoo (i=1) from /usr/lib/libfoo.so'
            self.crashdb.update_traces(segv_report, r, 'good retrace with custom title')
            r = self.crashdb.download(segv_report)
            self.assertEqual(r['Title'], 'crash is crashy')

            # test various situations which caused crashes
            r['Stacktrace'] = '' # empty file
            r['ThreadStacktrace'] = '"]\xb6"\n' # not interpretable as UTF-8, LP #353805
            r['StacktraceSource'] = 'a\nb\nc\nd\ne\n\xff\xff\xff\n\f'
            self.crashdb.update_traces(segv_report, r, 'tests')

        def test_get_comment_url(self):
            '''get_comment_url() for non-ASCII titles'''

            # UTF-8 bytestring, works in both python 2.7 and 3
            title = b'1\xc3\xa4\xe2\x99\xa52'

            # distro, UTF-8 bytestring
            r = apport.Report('Bug')
            r['Title'] = title
            url = self.crashdb.get_comment_url(r, 42)
            self.assertTrue(url.endswith('/ubuntu/+filebug/42?field.title=1%C3%A4%E2%99%A52'))

            # distro, unicode
            r['Title'] = title.decode('UTF-8')
            url = self.crashdb.get_comment_url(r, 42)
            self.assertTrue(url.endswith('/ubuntu/+filebug/42?field.title=1%C3%A4%E2%99%A52'))

            # package, unicode
            r['SourcePackage'] = 'coreutils'
            url = self.crashdb.get_comment_url(r, 42)
            self.assertTrue(url.endswith('/ubuntu/+source/coreutils/+filebug/42?field.title=1%C3%A4%E2%99%A52'))

        def test_update_description(self):
            '''update() with changing description'''

            bug_target = self.crashdb.lp_distro.getSourcePackage(name='bash')
            bug = self.crashdb.launchpad.bugs.createBug(
                description='test description for test bug.',
                target=bug_target,
                title='testbug')
            id = bug.id
            self.assertTrue(id > 0)
            sys.stderr.write('(https://%s/bugs/%i) ' % (self.hostname, id))

            r = apport.Report('Bug')

            r['OneLiner'] = 'bogus→'
            r['StacktraceTop'] = 'f()\ng()\nh(1)'
            r['ShortGoo'] = 'lineone\nlinetwo'
            r['DpkgTerminalLog'] = 'one\ntwo\nthree\nfour\nfive\nsix'
            r['VarLogDistupgradeBinGoo'] = '\x01' * 1024

            self.crashdb.update(id, r, 'NotMe', change_description=True)

            r = self.crashdb.download(id)

            self.assertEqual(r['OneLiner'], 'bogus→')
            self.assertEqual(r['ShortGoo'], 'lineone\nlinetwo')
            self.assertEqual(r['DpkgTerminalLog'], 'one\ntwo\nthree\nfour\nfive\nsix')
            self.assertEqual(r['VarLogDistupgradeBinGoo'], '\x01' * 1024)

            self.assertEqual(self.crashdb.launchpad.bugs[id].tags,
                ['apport-collected'])

        def test_update_comment(self):
            '''update() with appending comment'''

            bug_target = self.crashdb.lp_distro.getSourcePackage(name='bash')
            # we need to fake an apport description separator here, since we
            # want to be lazy and use download() for checking the result
            bug = self.crashdb.launchpad.bugs.createBug(
                description='Pr0blem\n\n--- \nProblemType: Bug',
                target=bug_target,
                title='testbug')
            id = bug.id
            self.assertTrue(id > 0)
            sys.stderr.write('(https://%s/bugs/%i) ' % (self.hostname, id))

            r = apport.Report('Bug')

            r['OneLiner'] = 'bogus→'
            r['StacktraceTop'] = 'f()\ng()\nh(1)'
            r['ShortGoo'] = 'lineone\nlinetwo'
            r['DpkgTerminalLog'] = 'one\ntwo\nthree\nfour\nfive\nsix'
            r['VarLogDistupgradeBinGoo'] = '\x01' * 1024

            self.crashdb.update(id, r, 'meow', change_description=False)

            r = self.crashdb.download(id)

            self.assertFalse('OneLiner' in r)
            self.assertFalse('ShortGoo' in r)
            self.assertEqual(r['ProblemType'], 'Bug')
            self.assertEqual(r['DpkgTerminalLog'], 'one\ntwo\nthree\nfour\nfive\nsix')
            self.assertEqual(r['VarLogDistupgradeBinGoo'], '\x01' * 1024)

            self.assertEqual(self.crashdb.launchpad.bugs[id].tags,
                ['apport-collected'])

        def test_update_filter(self):
            '''update() with a key filter'''

            bug_target = self.crashdb.lp_distro.getSourcePackage(name='bash')
            bug = self.crashdb.launchpad.bugs.createBug(
                description='test description for test bug',
                target=bug_target,
                title='testbug')
            id = bug.id
            self.assertTrue(id > 0)
            sys.stderr.write('(https://%s/bugs/%i) ' % (self.hostname, id))

            r = apport.Report('Bug')

            r['OneLiner'] = 'bogus→'
            r['StacktraceTop'] = 'f()\ng()\nh(1)'
            r['ShortGoo'] = 'lineone\nlinetwo'
            r['DpkgTerminalLog'] = 'one\ntwo\nthree\nfour\nfive\nsix'
            r['VarLogDistupgradeBinGoo'] = '\x01' * 1024

            self.crashdb.update(id, r, 'NotMe', change_description=True,
                    key_filter=['ProblemType', 'ShortGoo', 'DpkgTerminalLog'])

            r = self.crashdb.download(id)

            self.assertFalse('OneLiner' in r)
            self.assertEqual(r['ShortGoo'], 'lineone\nlinetwo')
            self.assertEqual(r['ProblemType'], 'Bug')
            self.assertEqual(r['DpkgTerminalLog'], 'one\ntwo\nthree\nfour\nfive\nsix')
            self.assertFalse('VarLogDistupgradeBinGoo' in r)

            self.assertEqual(self.crashdb.launchpad.bugs[id].tags, [])

        def test_get_distro_release(self):
            '''get_distro_release()'''

            self.assertEqual(self.crashdb.get_distro_release(segv_report),
                    self.ref_report['DistroRelease'])

        def test_get_affected_packages(self):
            '''get_affected_packages()'''

            self.assertEqual(self.crashdb.get_affected_packages(segv_report),
                    [self.ref_report['SourcePackage']])

        def test_is_reporter(self):
            '''is_reporter()'''

            self.assertTrue(self.crashdb.is_reporter(segv_report))
            self.assertFalse(self.crashdb.is_reporter(1))

        def test_can_update(self):
            '''can_update()'''

            self.assertTrue(self.crashdb.can_update(segv_report))
            self.assertFalse(self.crashdb.can_update(1))

        def test_duplicates(self):
            '''duplicate handling'''

            # initially we have no dups
            self.assertEqual(self.crashdb.duplicate_of(segv_report), None)
            self.assertEqual(self.crashdb.get_fixed_version(segv_report), None)

            # dupe our segv_report and check that it worked; then undupe it
            r = self.crashdb.download(segv_report)
            self.crashdb.close_duplicate(r, segv_report, self.known_test_id)
            self.assertEqual(self.crashdb.duplicate_of(segv_report), self.known_test_id)

            # this should be a no-op
            self.crashdb.close_duplicate(r, segv_report, self.known_test_id)
            self.assertEqual(self.crashdb.duplicate_of(segv_report), self.known_test_id)

            self.assertEqual(self.crashdb.get_fixed_version(segv_report), 'invalid')
            self.crashdb.close_duplicate(r, segv_report, None)
            self.assertEqual(self.crashdb.duplicate_of(segv_report), None)
            self.assertEqual(self.crashdb.get_fixed_version(segv_report), None)

            # this should have removed attachments; note that Stacktrace is
            # short, and thus inline
            r = self.crashdb.download(segv_report)
            self.assertFalse('CoreDump' in r)
            self.assertFalse('Disassembly' in r)
            self.assertFalse('ProcMaps' in r)
            self.assertFalse('ProcStatus' in r)
            self.assertFalse('Registers' in r)
            self.assertFalse('Stacktrace' in r)
            self.assertFalse('ThreadStacktrace' in r)

            # now try duplicating to a duplicate bug; this should automatically
            # transition to the master bug
            self.crashdb.close_duplicate(apport.Report(), self.known_test_id,
                    self.known_test_id2)
            self.crashdb.close_duplicate(r, segv_report, self.known_test_id)
            self.assertEqual(self.crashdb.duplicate_of(segv_report),
                    self.known_test_id2)

            self.crashdb.close_duplicate(apport.Report(), self.known_test_id, None)
            self.crashdb.close_duplicate(apport.Report(), self.known_test_id2, None)
            self.crashdb.close_duplicate(r, segv_report, None)

            # this should be a no-op
            self.crashdb.close_duplicate(apport.Report(), self.known_test_id, None)
            self.assertEqual(self.crashdb.duplicate_of(self.known_test_id), None)

            self.crashdb.mark_regression(segv_report, self.known_test_id)
            self._verify_marked_regression(segv_report)

        def test_marking_segv(self):
            '''processing status markings for signal crashes'''

            # mark_retraced()
            unretraced_before = self.crashdb.get_unretraced()
            self.assertTrue(segv_report in unretraced_before)
            self.assertFalse(python_report in unretraced_before)
            self.crashdb.mark_retraced(segv_report)
            unretraced_after = self.crashdb.get_unretraced()
            self.assertFalse(segv_report in unretraced_after)
            self.assertEqual(unretraced_before,
                    unretraced_after.union(set([segv_report])))
            self.assertEqual(self.crashdb.get_fixed_version(segv_report), None)

            # mark_retrace_failed()
            self._mark_needs_retrace(segv_report)
            self.crashdb.mark_retraced(segv_report)
            self.crashdb.mark_retrace_failed(segv_report)
            unretraced_after = self.crashdb.get_unretraced()
            self.assertFalse(segv_report in unretraced_after)
            self.assertEqual(unretraced_before,
                    unretraced_after.union(set([segv_report])))
            self.assertEqual(self.crashdb.get_fixed_version(segv_report), None)

            # mark_retrace_failed() of invalid bug
            self._mark_needs_retrace(segv_report)
            self.crashdb.mark_retraced(segv_report)
            self.crashdb.mark_retrace_failed(segv_report, "I don't like you")
            unretraced_after = self.crashdb.get_unretraced()
            self.assertFalse(segv_report in unretraced_after)
            self.assertEqual(unretraced_before,
                    unretraced_after.union(set([segv_report])))
            self.assertEqual(self.crashdb.get_fixed_version(segv_report),
                    'invalid')

        def test_marking_python(self):
            '''processing status markings for interpreter crashes'''

            unchecked_before = self.crashdb.get_dup_unchecked()
            self.assertTrue(python_report in unchecked_before)
            self.assertFalse(segv_report in unchecked_before)
            self.crashdb._mark_dup_checked(python_report, self.ref_report)
            unchecked_after = self.crashdb.get_dup_unchecked()
            self.assertFalse(python_report in unchecked_after)
            self.assertEqual(unchecked_before,
                    unchecked_after.union(set([python_report])))
            self.assertEqual(self.crashdb.get_fixed_version(python_report),
                    None)

        def test_update_traces_invalid(self):
            '''updating an invalid crash

            This simulates a race condition where a crash being processed gets
            invalidated by marking it as a duplicate.
            '''
            id = self._file_segv_report()[0]
            sys.stderr.write('(https://%s/bugs/%i) ' % (self.hostname, id))

            r = self.crashdb.download(id)

            self.crashdb.close_duplicate(r, id, segv_report)

            # updating with a useful stack trace removes core dump
            r['StacktraceTop'] = 'read () from /lib/libc.6.so\nfoo (i=1) from /usr/lib/libfoo.so'
            r['Stacktrace'] = 'long\ntrace'
            r['ThreadStacktrace'] = 'thread\neven longer\ntrace'
            self.crashdb.update_traces(id, r, 'good retrace!')

            r = self.crashdb.download(id)
            self.assertFalse('CoreDump' in r)

        def test_get_fixed_version(self):
            '''get_fixed_version() for fixed bugs

            Other cases are already checked in test_marking_segv() (invalid
            bugs) and test_duplicates (duplicate bugs) for efficiency.
            '''
            self._mark_report_fixed(segv_report)
            fixed_ver = self.crashdb.get_fixed_version(segv_report)
            self.assertNotEqual(fixed_ver, None)
            self.assertTrue(fixed_ver[0].isdigit())
            self._mark_report_new(segv_report)
            self.assertEqual(self.crashdb.get_fixed_version(segv_report), None)

        #
        # Launchpad specific implementation and tests
        #

        @classmethod
        def _get_instance(klass):
            '''Create a CrashDB instance'''

            launchpad_instance = os.environ.get('APPORT_LAUNCHPAD_INSTANCE') or 'staging'

            return CrashDatabase(os.environ.get('LP_CREDENTIALS'),
                    {'distro': 'ubuntu',
                     'launchpad_instance': launchpad_instance})

        def _get_bug_target(self, db, report):
            '''Return the bug_target for this report.'''

            project = db.options.get('project')
            if 'SourcePackage' in report:
                return db.lp_distro.getSourcePackage(name=report['SourcePackage'])
            elif project:
                return db.launchpad.projects[project]
            else:
                return self.lp_distro

        def _get_librarian_hostname(self):
            '''Return the librarian hostname according to the LP hostname used.'''

            hostname = self.crashdb.get_hostname()
            if 'staging' in hostname:
                return 'staging.launchpadlibrarian.net'
            else:
                return 'launchpad.dev:58080'

        def _file_bug(self, bug_target, report, handle, comment=None):
            '''File a bug report.'''

            bug_title = report.get('Title', report.standard_title())

            blob_info = self.crashdb.launchpad.temporary_blobs.fetch(
                token=handle)
            # XXX 2010-08-03 matsubara bug=612990:
            #     Can't fetch the blob directly, so let's load it from the
            #     representation.
            blob = self.crashdb.launchpad.load(blob_info['self_link'])
            #XXX Need to find a way to trigger the job that process the blob
            # rather polling like this. This makes the test suite take forever
            # to run.
            while not blob.hasBeenProcessed():
                time.sleep(1)

            # processed_blob contains info about privacy, additional comments
            # and attachments.
            processed_blob = blob.getProcessedData()

            bug = self.crashdb.launchpad.bugs.createBug(
                description=processed_blob['extra_description'],
                private=processed_blob['private'],
                tags=processed_blob['initial_tags'],
                target=bug_target,
                title=bug_title)

            for comment in processed_blob['comments']:
                bug.newMessage(content=comment)

            # Ideally, one would be able to retrieve the attachment content
            # from the ProblemReport object or from the processed_blob.
            # Unfortunately the processed_blob only give us the Launchpad
            # librarian file_alias_id, so that's why we need to
            # download it again and upload to the bug report. It'd be even
            # better if addAttachment could work like linkAttachment, the LP
            # api used in the +filebug web UI, but there are security concerns
            # about the way linkAttachment works.
            librarian_url = 'http://%s' % self._get_librarian_hostname()
            for attachment in processed_blob['attachments']:
                filename = description = attachment['description']
                # Download the attachment data.
                data = urllib.urlopen(urllib.basejoin(librarian_url,
                    str(attachment['file_alias_id']) + '/' + filename)).read()
                # Add the attachment to the newly created bug report.
                bug.addAttachment(
                    comment=filename,
                    data=data,
                    filename=filename,
                    description=description)

            for subscriber in processed_blob['subscribers']:
                sub = self.crashdb.launchpad.people[subscriber]
                if sub:
                    bug.subscribe(person=sub)

            for submission_key in processed_blob['hwdb_submission_keys']:
                # XXX 2010-08-04 matsubara bug=628889:
                #     Can't fetch the submission directly, so let's load it
                #     from the representation.
                submission = self.crashdb.launchpad.load(
                    'https://api.%s/beta/+hwdb/+submission/%s'
                    % (self.crashdb.get_hostname(), submission_key))
                bug.linkHWSubmission(submission=submission)
            return int(bug.id)

        def _mark_needs_retrace(self, id):
            '''Mark a report ID as needing retrace.'''

            bug = self.crashdb.launchpad.bugs[id]
            if self.crashdb.arch_tag not in bug.tags:
                bug.tags = bug.tags + [self.crashdb.arch_tag]
                bug.lp_save()

        def _mark_needs_dupcheck(self, id):
            '''Mark a report ID as needing duplicate check.'''

            bug = self.crashdb.launchpad.bugs[id]
            if 'need-duplicate-check' not in bug.tags:
                bug.tags = bug.tags + ['need-duplicate-check']
                bug.lp_save()

        def _mark_report_fixed(self, id):
            '''Close a report ID as "fixed".'''

            bug = self.crashdb.launchpad.bugs[id]
            tasks = list(bug.bug_tasks)
            assert len(tasks) == 1
            t = tasks[0]
            t.status = 'Fix Released'
            t.lp_save()

        def _mark_report_new(self, id):
            '''Reopen a report ID as "new".'''

            bug = self.crashdb.launchpad.bugs[id]
            tasks = list(bug.bug_tasks)
            assert len(tasks) == 1
            t = tasks[0]
            t.status = 'New'
            t.lp_save()

        def _verify_marked_regression(self, id):
            '''Verify that report ID is marked as regression.'''

            bug = self.crashdb.launchpad.bugs[id]
            self.assertTrue('regression-retracer' in bug.tags)

        def test_project(self):
            '''reporting crashes against a project instead of a distro'''

            launchpad_instance = os.environ.get('APPORT_LAUNCHPAD_INSTANCE') or 'staging'
            # crash database for langpack-o-matic project (this does not have
            # packages in any distro)
            crashdb = CrashDatabase(os.environ.get('LP_CREDENTIALS'),
                {'project': 'langpack-o-matic',
                 'launchpad_instance': launchpad_instance})
            self.assertEqual(crashdb.distro, None)

            # create Python crash report
            r = apport.Report('Crash')
            r['ExecutablePath'] = '/bin/foo'
            r['Traceback'] = '''Traceback (most recent call last):
  File "/bin/foo", line 67, in fuzz
    print(weird)
NameError: global name 'weird' is not defined'''
            r.add_os_info()
            r.add_user_info()
            self.assertEqual(r.standard_title(),
                    "foo crashed with NameError in fuzz(): global name 'weird' is not defined")

            # file it
            handle = crashdb.upload(r)
            self.assertTrue(handle)
            bug_target = self._get_bug_target(crashdb, r)
            self.assertEqual(bug_target.name, 'langpack-o-matic')

            id = self._file_bug(bug_target, r, handle)
            self.assertTrue(id > 0)
            sys.stderr.write('(https://%s/bugs/%i) ' % (self.hostname, id))

            # update
            r = crashdb.download(id)
            r['StacktraceTop'] = 'read () from /lib/libc.6.so\nfoo (i=1) from /usr/lib/libfoo.so'
            r['Stacktrace'] = 'long\ntrace'
            r['ThreadStacktrace'] = 'thread\neven longer\ntrace'
            crashdb.update_traces(id, r, 'good retrace!')
            r = crashdb.download(id)

            # test fixed version
            self.assertEqual(crashdb.get_fixed_version(id), None)
            crashdb.close_duplicate(r, id, self.known_test_id)
            self.assertEqual(crashdb.duplicate_of(id), self.known_test_id)
            self.assertEqual(crashdb.get_fixed_version(id), 'invalid')
            crashdb.close_duplicate(r, id, None)
            self.assertEqual(crashdb.duplicate_of(id), None)
            self.assertEqual(crashdb.get_fixed_version(id), None)

        def test_download_robustness(self):
            '''download() of uncommon description formats'''

            # only ProblemType/Architecture/DistroRelease in description
            r = self.crashdb.download(self.uncommon_description_bug.id)
            self.assertEqual(r['ProblemType'], 'Package')
            self.assertEqual(r['Architecture'], 'amd64')
            self.assertTrue(r['DistroRelease'].startswith('Ubuntu '))

        def test_escalation(self):
            '''Escalating bugs with more than 10 duplicates'''

            assert segv_report, 'you need to run test_1_report_segv() first'

            launchpad_instance = os.environ.get('APPORT_LAUNCHPAD_INSTANCE') or 'staging'
            db = CrashDatabase(os.environ.get('LP_CREDENTIALS'),
                    {'distro': 'ubuntu',
                     'launchpad_instance': launchpad_instance,
                     'escalation_tag': 'omgkittens',
                     'escalation_subscription': 'apport-hackers'})

            count = 0
            p = db.launchpad.people[db.options['escalation_subscription']].self_link
            first_dup = 59
            try:
                for b in range(first_dup, first_dup+13):
                    count += 1
                    sys.stderr.write('%i ' % b)
                    db.close_duplicate(apport.Report(), b, segv_report)
                    b = db.launchpad.bugs[segv_report]
                    has_escalation_tag = db.options['escalation_tag'] in b.tags
                    has_escalation_subscription = any([s.person_link == p for s in b.subscriptions])
                    if count <= 10:
                        self.assertFalse(has_escalation_tag)
                        self.assertFalse(has_escalation_subscription)
                    else:
                        self.assertTrue(has_escalation_tag)
                        self.assertTrue(has_escalation_subscription)
            finally:
                for b in range(first_dup, first_dup+count):
                    sys.stderr.write('R%i ' % b)
                    db.close_duplicate(apport.Report(), b, None)
            sys.stderr.write('\n')

        def test_marking_python_task_mangle(self):
            '''source package task fixup for marking interpreter crashes'''

            self._mark_needs_dupcheck(python_report)
            unchecked_before = self.crashdb.get_dup_unchecked()
            self.assertTrue(python_report in unchecked_before)

            # add an upstream task, and remove the package name from the
            # package task; _mark_dup_checked is supposed to restore the
            # package name
            b = self.crashdb.launchpad.bugs[python_report]
            if b.private:
                b.private = False
                b.lp_save()
            t = b.bug_tasks[0]
            t.target = self.crashdb.launchpad.distributions['ubuntu']
            t.lp_save()
            b.addTask(target=self.crashdb.launchpad.projects['coreutils'])

            self.crashdb._mark_dup_checked(python_report, self.ref_report)

            unchecked_after = self.crashdb.get_dup_unchecked()
            self.assertFalse(python_report in unchecked_after)
            self.assertEqual(unchecked_before,
                    unchecked_after.union(set([python_report])))

            # upstream task should be unmodified
            b = self.crashdb.launchpad.bugs[python_report]
            self.assertEqual(b.bug_tasks[0].bug_target_name, 'coreutils')
            self.assertEqual(b.bug_tasks[0].status, 'New')

            # package-less distro task should have package name fixed
            self.assertEqual(b.bug_tasks[1].bug_target_name, 'coreutils (Ubuntu)')
            self.assertEqual(b.bug_tasks[1].status, 'New')

            # should not confuse get_fixed_version()
            self.assertEqual(self.crashdb.get_fixed_version(python_report),
                    None)

        @classmethod
        def _generate_sigsegv_report(klass, signal='11'):
            '''Create a test executable which will die with a SIGSEGV, generate a
            core dump for it, create a problem report with those two arguments
            (ExecutablePath and CoreDump) and call add_gdb_info().

            Return the apport.report.Report.
            '''
            workdir = None
            orig_cwd = os.getcwd()
            pr = apport.report.Report()
            try:
                workdir = tempfile.mkdtemp()
                atexit.register(shutil.rmtree, workdir)
                os.chdir(workdir)

                # create a test executable
                with open('crash.c', 'w') as fd:
                    fd.write('''
int f(x) {
    int* p = 0; *p = x;
    return x+1;
}
int main() { return f(42); }
''')
                assert subprocess.call(['gcc', '-g', 'crash.c', '-o', 'crash']) == 0
                assert os.path.exists('crash')

                # call it through gdb and dump core
                subprocess.call(['gdb', '--batch', '--ex', 'run', '--ex',
                    'generate-core-file core', './crash'], stdout=subprocess.PIPE)
                assert os.path.exists('core')
                assert subprocess.call(['readelf', '-n', 'core'],
                    stdout=subprocess.PIPE) == 0

                pr['ExecutablePath'] = os.path.join(workdir, 'crash')
                pr['CoreDump'] = (os.path.join(workdir, 'core'),)
                pr['Signal'] = signal

                pr.add_gdb_info()
            finally:
                os.chdir(orig_cwd)

            return pr

    unittest.main()