~brian-murray/apport/add-apport-version

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
# vim: set encoding=UTF-8 fileencoding=UTF-8 :

'''Store, load, and handle problem reports.'''

# Copyright (C) 2006 - 2009 Canonical Ltd.
# Author: Martin Pitt <martin.pitt@ubuntu.com>
# 
# 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 zlib, base64, time, sys, gzip, struct
from email.encoders import encode_base64
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
try:
    from cStringIO import StringIO
except ImportError:
    from io import StringIO

try:
    from collections import UserDict
except ImportError:
    # Python 2
    from UserDict import IterableUserDict as UserDict

class CompressedValue:
    '''Represent a ProblemReport value which is gzip compressed.'''

    def __init__(self, value=None, name=None):
        '''Initialize an empty CompressedValue object with an optional name.'''
        
        self.gzipvalue = None
        self.name = name
        # By default, compressed values are in gzip format. Earlier versions of
        # problem_report used zlib format (without gzip header). If you have such
        # a case, set legacy_zlib to True.
        self.legacy_zlib = False

        if value:
            self.set_value(value)

    def set_value(self, value):
        '''Set uncompressed value.'''

        out = StringIO()
        gzip.GzipFile(self.name, mode='wb', fileobj=out).write(value)
        self.gzipvalue = out.getvalue()
        self.legacy_zlib = False

    def get_value(self):
        '''Return uncompressed value.'''

        if not self.gzipvalue:
            return None

        if self.legacy_zlib:
            return zlib.decompress(self.gzipvalue)
        return gzip.GzipFile(fileobj=StringIO(self.gzipvalue)).read()

    def write(self, file):
        '''Write uncompressed value into given file-like object.'''

        assert self.gzipvalue

        if self.legacy_zlib:
            file.write(zlib.decompress(self.gzipvalue))
            return

        gz = gzip.GzipFile(fileobj=StringIO(self.gzipvalue))
        while True:
            block = gz.read(1048576)
            if not block:
                break
            file.write(block)

    def __len__(self):
        '''Return length of uncompressed value.'''

        assert self.gzipvalue
        if self.legacy_zlib:
            return len(self.get_value())
        return int(struct.unpack("<L", self.gzipvalue[-4:])[0])

    def splitlines(self):
        '''Behaves like splitlines() for a normal string.'''

        return self.get_value().splitlines()

class ProblemReport(UserDict):
    def __init__(self, type = 'Crash', date = None):
        '''Initialize a fresh problem report.

        type can be 'Crash', 'Packaging', 'KernelCrash' or 'KernelOops'.
        date is the desired date/time string; if None (default), the
        current local time is used.
        '''
        if date == None:
            date = time.asctime()
        self.data = {'ProblemType': type, 'Date': date}

        # keeps track of keys which were added since the last ctor or load()
        self.old_keys = set()

    def load(self, file, binary=True):
        '''Initialize problem report from a file-like object.
        
        If binary is False, binary data is not loaded; the dictionary key is
        created, but its value will be an empty string. If it is true, it is
        transparently uncompressed and available as dictionary string values.
        If binary is 'compressed', the compressed value is retained, and the
        dictionary value will be a CompressedValue object. This is useful if
        the compressed value is still useful (to avoid recompression if the
        file needs to be written back).

        Files are in RFC822 format.
        '''
        self.data.clear()
        key = None
        value = None
        b64_block = False
        bd = None
        for line in file:
            # continuation line
            if line.startswith(' '):
                if b64_block and not binary:
                    continue
                assert (key != None and value != None)
                if b64_block:
                    l = base64.b64decode(line)
                    if bd:
                        value += bd.decompress(l)
                    else:
                        if binary == 'compressed':
                            # check gzip header; if absent, we have legacy zlib
                            # data
                            if value.gzipvalue == '' and not l.startswith('\037\213\010'): 
                                value.legacy_zlib = True
                            value.gzipvalue += l
                        else:
                            # lazy initialization of bd
                            # skip gzip header, if present
                            if l.startswith('\037\213\010'): 
                                bd = zlib.decompressobj(-zlib.MAX_WBITS)
                                value = bd.decompress(self._strip_gzip_header(l))
                            else:
                                # legacy zlib-only format used default block
                                # size
                                bd = zlib.decompressobj()
                                value += bd.decompress(l)
                else:
                    if len(value) > 0:
                        value += '\n'
                    value += line[1:-1]
            else:
                if b64_block:
                    if bd:
                        value += bd.flush()
                    b64_block = False
                    bd = None
                if key:
                    assert value != None
                    self.data[key] = value
                (key, value) = line.split(':', 1)
                value = value.strip()
                if value == 'base64':
                    if binary == 'compressed':
                        value = CompressedValue(key)
                        value.gzipvalue = ''
                    else:
                        value = ''
                    b64_block = True

        if key != None:
            self.data[key] = value

        self.old_keys = set(self.data.keys())

    def has_removed_fields(self):
        '''Check if the report has any keys which were not loaded.
        
        This could happen when using binary=False in load().
        '''
        return ('' in self.itervalues())

    def _is_binary(self, string):
        '''Check if the given strings contains binary data.'''

        for c in string:
            if c < ' ' and not c.isspace():
                return True
        return False

    def write(self, file, only_new = False):
        '''Write information into the given file-like object.

        If only_new is True, only keys which have been added since the last
        load() are written (i. e. those returned by new_keys()).

        If a value is a string, it is written directly. Otherwise it must be a
        tuple of the form (file, encode=True, limit=None, fail_on_empty=False).
        The first argument can be a file name or a file-like object,
        which will be read and its content will become the value of this key.
        'encode' specifies whether the contents will be
        gzip compressed and base64-encoded (this defaults to True). If limit is
        set to a positive integer, the file is not attached if it's larger
        than the given limit, and the entire key will be removed. If
        fail_on_empty is True, reading zero bytes will cause an IOError.

        Files are written in RFC822 format.
        '''
        # sort keys into ASCII non-ASCII/binary attachment ones, so that
        # the base64 ones appear last in the report
        asckeys = []
        binkeys = []
        for k in self.data.keys():
            if only_new and k in self.old_keys:
                continue
            v = self.data[k]
            if hasattr(v, 'find'):
                if self._is_binary(v):
                    binkeys.append(k)
                else:
                    asckeys.append(k)
            else:
                if not isinstance(v, CompressedValue) and len(v) >= 2 and not v[1]: # force uncompressed
                    asckeys.append(k)
                else:
                    binkeys.append(k)

        asckeys.sort()
        if 'ProblemType' in asckeys:
            asckeys.remove('ProblemType')
            asckeys.insert(0, 'ProblemType')
        binkeys.sort()

        # write the ASCII keys first
        for k in asckeys:
            v = self.data[k]

            # if it's a tuple, we have a file reference; read the contents
            if not hasattr(v, 'find'):
                if len(v) >= 3 and v[2] != None:
                    limit = v[2]
                else:
                    limit = None

                fail_on_empty = len(v) >= 4 and v[3]

                if hasattr(v[0], 'read'):
                    v = v[0].read() # file-like object
                else:
                    v = open(v[0]).read() # file name

                if fail_on_empty and len(v) == 0:
                    raise IOError('did not get any data for field ' + k)

                if limit != None and len(v) > limit:
                    del self.data[k]
                    continue

            if sys.version.startswith('2'):
                if isinstance(v, unicode):
                    # unicode → str
                    v = v.encode('UTF-8')

            if '\n' in v:
                # multiline value
                file.write('%s:\n' % k)
                file.write(' %s\n' % v.replace('\n', '\n '))
            else:
                # single line value
                file.write('%s: %s\n' % (k, v))

        # now write the binary keys with gzip compression and base64 encoding
        for k in binkeys:
            v = self.data[k]
            limit = None
            size = 0

            curr_pos = file.tell()
            file.write (k + ': base64\n ')

            # CompressedValue
            if isinstance(v, CompressedValue):
                file.write(base64.b64encode(v.gzipvalue))
                file.write('\n')
                continue

            # write gzip header
            gzip_header = '\037\213\010\010\000\000\000\000\002\377' + k + '\000'
            file.write(base64.b64encode(gzip_header))
            file.write('\n ')
            crc = zlib.crc32('')

            bc = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
                zlib.DEF_MEM_LEVEL, 0)
            # direct value
            if hasattr(v, 'find'):
                size += len(v)
                crc = zlib.crc32(v, crc)
                outblock = bc.compress(v)
                if outblock:
                    file.write(base64.b64encode(outblock))
                    file.write('\n ')
            # file reference
            else:
                if len(v) >= 3 and v[2] != None:
                    limit = v[2]

                if hasattr(v[0], 'read'):
                    f = v[0] # file-like object
                else:
                    f = open(v[0]) # file name
                while True:
                    block = f.read(1048576)
                    size += len(block)
                    crc = zlib.crc32(block, crc)
                    if limit != None:
                        if size > limit:
                            # roll back
                            file.seek(curr_pos)
                            file.truncate(curr_pos)
                            del self.data[k]
                            crc = None
                            break
                    if block:
                        outblock = bc.compress(block)
                        if outblock:
                            file.write(base64.b64encode(outblock))
                            file.write('\n ')
                    else:
                        break

                if len(v) >= 4 and v[3]:
                    if size == 0:
                        raise IOError('did not get any data for field %s from %s' % (k, str(v[0])))

            # flush compressor and write the rest
            if not limit or size <= limit:
                block = bc.flush()
                # append gzip trailer: crc (32 bit) and size (32 bit)
                if crc:
                    block += struct.pack("<L", crc & 0xFFFFFFFF)
                    block += struct.pack("<L", size & 0xFFFFFFFF)

                file.write(base64.b64encode(block))
                file.write('\n')

    def add_to_existing(self, reportfile, keep_times=False):
        '''Add this report's data to an already existing report file.

        The file will be temporarily chmod'ed to 000 to prevent frontends
        from picking up a hal-updated report file. If keep_times
        is True, then the file's atime and mtime restored after updating.
        '''
        st = os.stat(reportfile)
        try:
            f = open(reportfile, 'a')
            os.chmod(reportfile, 0)
            self.write(f)
            f.close()
        finally:
            if keep_times:
                os.utime(reportfile, (st.st_atime, st.st_mtime))
            os.chmod(reportfile, st.st_mode)

    def write_mime(self, file, attach_treshold = 5, extra_headers={},
        skip_keys=None, priority_fields=None):
        '''Write MIME/Multipart RFC 2822 formatted data into file.

        file must be a file-like object, not a path.

        If a value is a string or a CompressedValue, it is written directly.
        Otherwise it must be a tuple containing the source file and an optional
        boolean value (in that order); the first argument can be a file name or
        a file-like object, which will be read and its content will become the
        value of this key.  The file will be gzip compressed, unless the key
        already ends in .gz.

        attach_treshold specifies the maximum number of lines for a value to be
        included into the first inline text part. All bigger values (as well as
        all non-ASCII ones) will become an attachment.

        Extra MIME preamble headers can be specified, too, as a dictionary.

        skip_keys is a set/list specifying keys which are filtered out and not
        written to the destination file.

        priority_fields is a set/list specifying the order in which keys should
        appear in the destination file.
        '''
        keys = sorted(self.data.keys())

        text = ''
        attachments = []

        if 'ProblemType' in keys:
            keys.remove('ProblemType')
            keys.insert(0, 'ProblemType')

        if priority_fields:
            counter = 0
            for priority_field in priority_fields:
                if priority_field in keys:
                    keys.remove(priority_field)
                    keys.insert(counter, priority_field)
                    counter += 1

        for k in keys:
            if skip_keys and k in skip_keys:
                continue
            v = self.data[k]
            attach_value = None

            # compressed values are ready for attaching in gzip form
            if isinstance(v, CompressedValue):
                attach_value = v.gzipvalue

            # if it's a tuple, we have a file reference; read the contents
            # and gzip it
            elif not hasattr(v, 'find'):
                attach_value = ''
                if hasattr(v[0], 'read'):
                    f = v[0] # file-like object
                else:
                    f = open(v[0]) # file name
                if k.endswith('.gz'):
                    attach_value = f.read()
                else:
                    io = StringIO()
                    gf = gzip.GzipFile(k, mode='wb', fileobj=io)
                    while True:
                        block = f.read(1048576)
                        if block:
                            gf.write(block)
                        else:
                            gf.close()
                            break
                    attach_value = io.getvalue()
                f.close()

            # binary value
            elif self._is_binary(v):
                if k.endswith('.gz'):
                    attach_value = v
                else:
                    attach_value = CompressedValue(v, k).gzipvalue

            # if we have an attachment value, create an attachment
            if attach_value:
                att = MIMEBase('application', 'x-gzip')
                if k.endswith('.gz'):
                    att.add_header('Content-Disposition', 'attachment', filename=k)
                else:
                    att.add_header('Content-Disposition', 'attachment', filename=k+'.gz')
                att.set_payload(attach_value)
                encode_base64(att)
                attachments.append(att)
            else:
                # plain text value

                # ensure that byte arrays are valid UTF-8
                if type(v) == type(''):
                    v = v.decode('UTF-8', 'replace')
                # convert unicode to UTF-8 str
                assert isinstance(v, unicode)
                v = v.encode('UTF-8')

                lines = len(v.splitlines())
                if lines == 1:
                    v = v.rstrip()
                    text += '%s: %s\n' % (k, v)
                elif lines <= attach_treshold:
                    text += '%s:\n ' % k
                    if not v.endswith('\n'):
                        v += '\n'
                    text += v.strip().replace('\n', '\n ') + '\n'
                else:
                    # too large, separate attachment
                    att = MIMEText(v, _charset='UTF-8')
                    att.add_header('Content-Disposition', 'attachment', filename=k+'.txt')
                    attachments.append(att)

        # create initial text attachment
        att = MIMEText(text, _charset='UTF-8')
        att.add_header('Content-Disposition', 'inline')
        attachments.insert(0, att)

        msg = MIMEMultipart()
        for k, v in extra_headers.items():
            msg.add_header(k, v)
        for a in attachments:
            msg.attach(a)

        file.write(msg.as_string())
        file.write('\n')

    def __setitem__(self, k, v):
        assert hasattr(k, 'isalnum')
        assert k.replace('.', '').replace('-', '').replace('_', '').isalnum()
        # value must be a string or a CompressedValue or a file reference
        # (tuple (string|file [, bool]))
        assert (isinstance(v, CompressedValue) or hasattr(v, 'isalnum') or
            (hasattr(v, '__getitem__') and (
            len(v) == 1 or (len(v) >= 2 and v[1] in (True, False)))
            and (hasattr(v[0], 'isalnum') or hasattr(v[0], 'read'))))

        return self.data.__setitem__(k, v)

    def new_keys(self):
        '''Return newly added keys.

        Return the set of keys which have been added to the report since it
        was constructed or loaded.
        '''
        return set(self.data.keys()) - self.old_keys

    @classmethod
    def _strip_gzip_header(klass, line):
        '''Strip gzip header from line and return the rest.'''

        flags = ord(line[3])
        offset = 10
        if flags & 4: # FLG.FEXTRA
            offset += line[offset] + 1
        if flags & 8: # FLG.FNAME
            while ord(line[offset]) != 0:
                offset += 1
            offset += 1
        if flags & 16: # FLG.FCOMMENT
            while ord(line[offset]) != 0:
                offset += 1
            offset += 1
        if flags & 2: # FLG.FHCRC
            offset += 2

        return line[offset:]

#
# Unit test
#

import unittest, tempfile, os, email

class _T(unittest.TestCase):
    def test_basic_operations(self):
        '''basic creation and operation.'''

        pr = ProblemReport()
        pr['foo'] = 'bar'
        pr['bar'] = ' foo   bar\nbaz\n   blip  '
        pr['dash-key'] = '1'
        pr['dot.key'] = '1'
        pr['underscore_key'] = '1'
        self.assertEqual(pr['foo'], 'bar')
        self.assertEqual(pr['bar'], ' foo   bar\nbaz\n   blip  ')
        self.assertEqual(pr['ProblemType'], 'Crash')
        self.assertTrue(time.strptime(pr['Date']))
        self.assertEqual(pr['dash-key'], '1')
        self.assertEqual(pr['dot.key'], '1')
        self.assertEqual(pr['underscore_key'], '1')

    def test_ctor_arguments(self):
        '''non-default constructor arguments.'''

        pr = ProblemReport('KernelCrash')
        self.assertEqual(pr['ProblemType'], 'KernelCrash')
        pr = ProblemReport(date = '19801224 12:34')
        self.assertEqual(pr['Date'], '19801224 12:34')

    def test_sanity_checks(self):
        '''various error conditions.'''

        pr = ProblemReport()
        self.assertRaises(AssertionError, pr.__setitem__, 'a b', '1')
        self.assertRaises(AssertionError, pr.__setitem__, 'a', 1)
        self.assertRaises(AssertionError, pr.__setitem__, 'a', 1)
        self.assertRaises(AssertionError, pr.__setitem__, 'a', (1,))
        self.assertRaises(AssertionError, pr.__setitem__, 'a', ('/tmp/nonexistant', ''))
        self.assertRaises(KeyError, pr.__getitem__, 'Nonexistant')

    def test_compressed_values(self):
        '''handling of CompressedValue values.'''

        large_val = 'A' * 5000000

        pr = ProblemReport()
        pr['Foo'] = CompressedValue('FooFoo!')
        pr['Bin'] = CompressedValue()
        pr['Bin'].set_value('AB' * 10 + '\0' * 10 + 'Z')
        pr['Large'] = CompressedValue(large_val)

        self.assertTrue(isinstance(pr['Foo'], CompressedValue))
        self.assertTrue(isinstance(pr['Bin'], CompressedValue))
        self.assertEqual(pr['Foo'].get_value(), 'FooFoo!')
        self.assertEqual(pr['Bin'].get_value(), 'AB' * 10 + '\0' * 10 + 'Z')
        self.assertEqual(pr['Large'].get_value(), large_val)
        self.assertEqual(len(pr['Foo']), 7)
        self.assertEqual(len(pr['Bin']), 31)
        self.assertEqual(len(pr['Large']), len(large_val))

        io = StringIO()
        pr['Bin'].write(io)
        self.assertEqual(io.getvalue(), 'AB' * 10 + '\0' * 10 + 'Z')
        io = StringIO()
        pr['Large'].write(io)
        self.assertEqual(io.getvalue(), large_val)

        pr['Multiline'] = CompressedValue('\1\1\1\n\2\2\n\3\3\3')
        self.assertEqual(pr['Multiline'].splitlines(), 
            ['\1\1\1', '\2\2', '\3\3\3'])

        # test writing of reports with CompressedValues
        io = StringIO()
        pr.write(io)
        io.seek(0)
        pr = ProblemReport()
        pr.load(io)
        self.assertEqual(pr['Foo'], 'FooFoo!')
        self.assertEqual(pr['Bin'], 'AB' * 10 + '\0' * 10 + 'Z')
        self.assertEqual(pr['Large'], large_val)

    def test_write(self):
        '''write() and proper formatting.'''

        pr = ProblemReport(date = 'now!')
        pr['Simple'] = 'bar'
        if sys.version.startswith('2'):
            pr['SimpleUTF8'] = '1äö2Φ3'
            pr['SimpleUnicode'] = '1äö2Φ3'.decode('UTF-8')
            pr['TwoLineUnicode'] = 'pi-π\nnu-η'.decode('UTF-8')
            pr['TwoLineUTF8'] = 'pi-π\nnu-η'.decode('UTF-8')
        else:
            pr['SimpleUTF8'] = '1äö2Φ3'.encode('UTF-8')
            pr['SimpleUnicode'] = '1äö2Φ3'
            pr['TwoLineUnicode'] = 'pi-π\nnu-η'
            pr['TwoLineUTF8'] = 'pi-π\nnu-η'
        pr['WhiteSpace'] = ' foo   bar\nbaz\n  blip  \n\nafteremptyline'
        io = StringIO()
        pr.write(io)
        self.assertEqual(io.getvalue(),
'''ProblemType: Crash
Date: now!
Simple: bar
SimpleUTF8: 1äö2Φ3
SimpleUnicode: 1äö2Φ3
TwoLineUTF8:
 pi-π
 nu-η
TwoLineUnicode:
 pi-π
 nu-η
WhiteSpace:
  foo   bar
 baz
   blip  
 
 afteremptyline
''')

    def test_write_append(self):
        '''write() with appending to an existing file.'''

        pr = ProblemReport(date = 'now!')
        pr['Simple'] = 'bar'
        pr['WhiteSpace'] = ' foo   bar\nbaz\n  blip  '
        io = StringIO()
        pr.write(io)

        pr.clear()
        pr['Extra'] = 'appended'
        pr.write(io)

        self.assertEqual(io.getvalue(), 
'''ProblemType: Crash
Date: now!
Simple: bar
WhiteSpace:
  foo   bar
 baz
   blip  
Extra: appended
''')

        temp = tempfile.NamedTemporaryFile()
        temp.write('AB' * 10 + '\0' * 10 + 'Z')
        temp.flush()

        pr = ProblemReport(date = 'now!')
        pr['File'] = (temp.name,)
        io = StringIO()
        pr.write(io)
        temp.close()

        pr.clear()
        pr['Extra'] = 'appended'
        pr.write(io)

        io.seek(0)
        pr = ProblemReport()
        pr.load(io)

        self.assertEqual(pr['Date'], 'now!')
        self.assertEqual(pr['File'], 'AB' * 10 + '\0' * 10 + 'Z')
        self.assertEqual(pr['Extra'], 'appended')

    def test_load(self):
        '''load() with various formatting.'''

        pr = ProblemReport()
        pr.load(StringIO(
'''ProblemType: Crash
Date: now!
Simple: bar
WhiteSpace:
  foo   bar
 baz
   blip  
'''))
        self.assertEqual(pr['ProblemType'], 'Crash')
        self.assertEqual(pr['Date'], 'now!')
        self.assertEqual(pr['Simple'], 'bar')
        self.assertEqual(pr['WhiteSpace'], ' foo   bar\nbaz\n  blip  ')

        # test last field a bit more
        pr.load(StringIO(
'''ProblemType: Crash
Date: now!
Simple: bar
WhiteSpace:
  foo   bar
 baz
   blip  
 
'''))
        self.assertEqual(pr['ProblemType'], 'Crash')
        self.assertEqual(pr['Date'], 'now!')
        self.assertEqual(pr['Simple'], 'bar')
        self.assertEqual(pr['WhiteSpace'], ' foo   bar\nbaz\n  blip  \n')

        pr = ProblemReport()
        pr.load(StringIO(
'''ProblemType: Crash
WhiteSpace:
  foo   bar
 baz
 
   blip  
Last: foo
'''))
        self.assertEqual(pr['WhiteSpace'], ' foo   bar\nbaz\n\n  blip  ')
        self.assertEqual(pr['Last'], 'foo')

        pr.load(StringIO(
'''ProblemType: Crash
WhiteSpace:
  foo   bar
 baz
   blip  
Last: foo
 
'''))
        self.assertEqual(pr['WhiteSpace'], ' foo   bar\nbaz\n  blip  ')
        self.assertEqual(pr['Last'], 'foo\n')

        # empty lines in values must have a leading space in coding
        invalid_spacing = StringIO('''WhiteSpace:
 first

 second
''')
        pr = ProblemReport()
        self.assertRaises(ValueError, pr.load, invalid_spacing)

        # test that load() cleans up properly
        pr.load(StringIO('ProblemType: Crash'))
        self.assertEqual(list(pr.keys()), ['ProblemType'])

    def test_write_file(self):
        '''writing a report with binary file data.'''

        temp = tempfile.NamedTemporaryFile()
        temp.write('AB' * 10 + '\0' * 10 + 'Z')
        temp.flush()

        pr = ProblemReport(date = 'now!')
        pr['File'] = (temp.name,)
        pr['Afile'] = (temp.name,)
        io = StringIO()
        pr.write(io)
        temp.close()

        self.assertEqual(io.getvalue(),
'''ProblemType: Crash
Date: now!
Afile: base64
 H4sICAAAAAAC/0FmaWxlAA==
 c3RyxIAMcBAFAK/2p9MfAAAA
File: base64
 H4sICAAAAAAC/0ZpbGUA
 c3RyxIAMcBAFAK/2p9MfAAAA
''')

        # force compression/encoding bool
        temp = tempfile.NamedTemporaryFile()
        temp.write('foo\0bar')
        temp.flush()
        pr = ProblemReport(date = 'now!')
        pr['File'] = (temp.name, False)
        io = StringIO()
        pr.write(io)

        self.assertEqual(io.getvalue(),
'''ProblemType: Crash
Date: now!
File: foo\0bar
''')

        pr['File'] = (temp.name, True)
        io = StringIO()
        pr.write(io)

        self.assertEqual(io.getvalue(),
'''ProblemType: Crash
Date: now!
File: base64
 H4sICAAAAAAC/0ZpbGUA
 S8vPZ0hKLAIACq50HgcAAAA=
''')
        temp.close()

    def test_write_fileobj(self):
        '''writing a report with a pointer to a file-like object.'''

        tempbin = StringIO('AB' * 10 + '\0' * 10 + 'Z')
        tempasc = StringIO('Hello World')

        pr = ProblemReport(date = 'now!')
        pr['BinFile'] = (tempbin,)
        pr['AscFile'] = (tempasc, False)
        io = StringIO()
        pr.write(io)
        io.seek(0)

        pr = ProblemReport()
        pr.load(io)
        self.assertEqual(pr['BinFile'], tempbin.getvalue())
        self.assertEqual(pr['AscFile'], tempasc.getvalue())

    def test_write_empty_fileobj(self):
        '''writing a report with a pointer to a file-like object with enforcing non-emptyness.'''

        tempbin = StringIO('')
        tempasc = StringIO('')

        pr = ProblemReport(date = 'now!')
        pr['BinFile'] = (tempbin, True, None, True)
        io = StringIO()
        self.assertRaises(IOError, pr.write, io)

        pr = ProblemReport(date = 'now!')
        pr['AscFile'] = (tempasc, False, None, True)
        io = StringIO()
        self.assertRaises(IOError, pr.write, io)

    def test_write_delayed_fileobj(self):
        '''writing a report with file pointers and delayed data.'''

        (fout, fin) = os.pipe()

        if os.fork() == 0:
            os.close(fout)
            time.sleep(0.3)
            os.write(fin, 'ab' * 512*1024)
            time.sleep(0.3)
            os.write(fin, 'hello')
            time.sleep(0.3)
            os.write(fin, ' world')
            os.close(fin)
            os._exit(0)

        os.close(fin)

        pr = ProblemReport(date = 'now!')
        pr['BinFile'] = (os.fdopen(fout),)
        io = StringIO()
        pr.write(io)
        assert os.wait()[1] == 0

        io.seek(0)

        pr2 = ProblemReport()
        pr2.load(io)
        self.assertTrue(pr2['BinFile'].endswith('abhello world'))
        self.assertEqual(len(pr2['BinFile']), 1048576 + len('hello world'))

    def test_read_file(self):
        '''reading a report with binary data.'''

        bin_report = '''ProblemType: Crash
Date: now!
File: base64
 H4sICAAAAAAC/0ZpbGUA
 c3RyxIAMcBAFAK/2p9MfAAAA
Foo: Bar
'''

        # test with reading everything
        pr = ProblemReport()
        pr.load(StringIO(bin_report))
        self.assertEqual(pr['File'], 'AB' * 10 + '\0' * 10 + 'Z')
        self.assertEqual(pr.has_removed_fields(), False)

        # test with skipping binary data
        pr.load(StringIO(bin_report), binary=False)
        self.assertEqual(pr['File'], '')
        self.assertEqual(pr.has_removed_fields(), True)

        # test with keeping compressed binary data
        pr.load(StringIO(bin_report), binary='compressed')
        self.assertEqual(pr['Foo'], 'Bar')
        self.assertEqual(pr.has_removed_fields(), False)
        self.assertTrue(isinstance(pr['File'], CompressedValue))

        self.assertEqual(pr['File'].get_value(), 'AB' * 10 + '\0' * 10 + 'Z')

    def test_read_file_legacy(self):
        '''reading a report with binary data in legacy format without gzip
        header.'''

        bin_report = '''ProblemType: Crash
Date: now!
File: base64
 eJw=
 c3RyxIAMcBAFAG55BXk=
Foo: Bar
'''

        data = 'AB' * 10 + '\0' * 10 + 'Z'

        # test with reading everything
        pr = ProblemReport()
        pr.load(StringIO(bin_report))
        self.assertEqual(pr['File'], data)
        self.assertEqual(pr.has_removed_fields(), False)

        # test with skipping binary data
        pr.load(StringIO(bin_report), binary=False)
        self.assertEqual(pr['File'], '')
        self.assertEqual(pr.has_removed_fields(), True)

        # test with keeping CompressedValues
        pr.load(StringIO(bin_report), binary='compressed')
        self.assertEqual(pr.has_removed_fields(), False)
        self.assertEqual(len(pr['File']), len(data))
        self.assertEqual(pr['File'].get_value(), data)
        io = StringIO()
        pr['File'].write(io)
        io.seek(0)
        self.assertEqual(io.read(), data)

    def test_big_file(self):
        '''writing and re-decoding a big random file.'''

        # create 1 MB random file
        temp = tempfile.NamedTemporaryFile()
        data = os.urandom(1048576)
        temp.write(data)
        temp.flush()

        # write it into problem report
        pr = ProblemReport()
        pr['File'] = (temp.name,)
        pr['Before'] = 'xtestx'
        pr['ZAfter'] = 'ytesty'
        io = StringIO()
        pr.write(io)
        temp.close()

        # read it again
        io.seek(0)
        pr = ProblemReport()
        pr.load(io)

        self.assertTrue(pr['File'] == data)
        self.assertEqual(pr['Before'], 'xtestx')
        self.assertEqual(pr['ZAfter'], 'ytesty')

        # write it again
        io2 = StringIO()
        pr.write(io2)
        self.assertTrue(io.getvalue() == io2.getvalue())

        # check gzip compatibility
        io.seek(0)
        pr = ProblemReport()
        pr.load(io, binary='compressed')
        self.assertEqual(pr['File'].get_value(), data)

    def test_size_limit(self):
        '''writing and a big random file with a size limit key.'''

        # create 1 MB random file
        temp = tempfile.NamedTemporaryFile()
        data = os.urandom(1048576)
        temp.write(data)
        temp.flush()

        # write it into problem report
        pr = ProblemReport()
        pr['FileSmallLimit'] = (temp.name, True, 100)
        pr['FileLimitMinus1'] = (temp.name, True, 1048575)
        pr['FileExactLimit'] = (temp.name, True, 1048576)
        pr['FileLimitPlus1'] = (temp.name, True, 1048577)
        pr['FileLimitNone'] = (temp.name, True, None)
        pr['Before'] = 'xtestx'
        pr['ZAfter'] = 'ytesty'
        io = StringIO()
        pr.write(io)
        temp.close()

        # read it again
        io.seek(0)
        pr = ProblemReport()
        pr.load(io)

        self.assertFalse(pr.has_key('FileSmallLimit'))
        self.assertFalse(pr.has_key('FileLimitMinus1'))
        self.assertTrue(pr['FileExactLimit'] == data)
        self.assertTrue(pr['FileLimitPlus1'] == data)
        self.assertTrue(pr['FileLimitNone'] == data)
        self.assertEqual(pr['Before'], 'xtestx')
        self.assertEqual(pr['ZAfter'], 'ytesty')

    def test_iter(self):
        '''ProblemReport iteration.'''

        pr = ProblemReport()
        pr['foo'] = 'bar'

        keys = []
        for k in pr:
            keys.append(k)
        keys.sort()
        self.assertEqual(' '.join(keys), 'Date ProblemType foo')

        self.assertEqual(len([k for k in pr if k != 'foo']), 2)

    def test_modify(self):
        '''reading, modifying fields, and writing back.'''

        report = '''ProblemType: Crash
Date: now!
Long:
 xxx
 .
 yyy
Short: Bar
File: base64
 H4sICAAAAAAC/0ZpbGUA
 c3RyxIAMcBAFAK/2p9MfAAAA
'''

        pr = ProblemReport()
        pr.load(StringIO(report))

        self.assertEqual(pr['Long'], 'xxx\n.\nyyy')

        # write back unmodified
        io = StringIO()
        pr.write(io)
        self.assertEqual(io.getvalue(), report)

        pr['Short'] = 'aaa\nbbb'
        pr['Long'] = '123'
        io = StringIO()
        pr.write(io)
        self.assertEqual(io.getvalue(),
'''ProblemType: Crash
Date: now!
Long: 123
Short:
 aaa
 bbb
File: base64
 H4sICAAAAAAC/0ZpbGUA
 c3RyxIAMcBAFAK/2p9MfAAAA
''')

    def test_add_to_existing(self):
        '''adding information to an existing report.'''

        # original report
        pr = ProblemReport()
        pr['old1'] = '11'
        pr['old2'] = '22'

        (fd, rep) = tempfile.mkstemp()
        os.close(fd)
        pr.write(open(rep, 'w'))

        origstat = os.stat(rep)

        # create a new one and add it
        pr = ProblemReport()
        pr.clear()
        pr['new1'] = '33'

        pr.add_to_existing(rep, keep_times=True)

        # check keep_times
        newstat = os.stat(rep)
        self.assertEqual(origstat.st_mode, newstat.st_mode)
        self.assertAlmostEqual(origstat.st_atime, newstat.st_atime, 1)
        self.assertAlmostEqual(origstat.st_mtime, newstat.st_mtime, 1)

        # check report contents
        newpr = ProblemReport()
        newpr.load(open(rep))
        self.assertEqual(newpr['old1'], '11')
        self.assertEqual(newpr['old2'], '22')
        self.assertEqual(newpr['new1'], '33')

        # create a another new one and add it, but make sure mtime must be
        # different
        time.sleep(1)
        open(rep).read() # bump atime
        time.sleep(1)

        pr = ProblemReport()
        pr.clear()
        pr['new2'] = '44'

        pr.add_to_existing(rep)

        # check that timestamps have been updates
        newstat = os.stat(rep)
        self.assertEqual(origstat.st_mode, newstat.st_mode)
        self.assertNotEqual(origstat.st_mtime, newstat.st_mtime)
        # skip atime check if filesystem is mounted noatime
        skip_atime = False
        dir = rep
        while len(dir)>1:
            dir, filename = os.path.split(dir)
            if os.path.ismount(dir):
                for line in open('/proc/mounts'):
                    mount, fs, options = line.split(' ')[1:4]
                    if mount == dir and 'noatime' in options.split(','):
                        skip_atime = True
                        break
                break
        if not skip_atime:
            self.assertNotEqual(origstat.st_atime, newstat.st_atime)

        # check report contents
        newpr = ProblemReport()
        newpr.load(open(rep))
        self.assertEqual(newpr['old1'], '11')
        self.assertEqual(newpr['old2'], '22')
        self.assertEqual(newpr['new1'], '33')
        self.assertEqual(newpr['new2'], '44')

        os.unlink(rep)

    def test_write_mime_text(self):
        '''write_mime() for text values.'''

        pr = ProblemReport(date = 'now!')
        pr['Simple'] = 'bar'
        if sys.version.startswith('2'):
            pr['SimpleUTF8'] = '1äö2Φ3'
            pr['SimpleUnicode'] = '1äö2Φ3'.decode('UTF-8')
            pr['TwoLineUnicode'] = 'pi-π\nnu-η\n'.decode('UTF-8')
            pr['TwoLineUTF8'] = 'pi-π\nnu-η\n'.decode('UTF-8')
        else:
            pr['SimpleUTF8'] = '1äö2Φ3'.encode('UTF-8')
            pr['SimpleUnicode'] = '1äö2Φ3'
            pr['TwoLineUnicode'] = 'pi-π\nnu-η\n'
            pr['TwoLineUTF8'] = 'pi-π\nnu-η\n'
        pr['SimpleLineEnd'] = 'bar\n'
        pr['TwoLine'] = 'first\nsecond\n'
        pr['InlineMargin'] = 'first\nsecond\nthird\nfourth\nfifth\n'
        pr['Multiline'] = ' foo   bar\nbaz\n  blip  \nline4\nline♥5!!\nłıµ€ ⅝\n'
        io = StringIO()
        pr.write_mime(io)
        io.seek(0)

        msg = email.message_from_file(io)
        parts = [p for p in msg.walk()]
        self.assertEqual(len(parts), 3)

        # first part is the multipart container
        self.assertTrue(parts[0].is_multipart())

        # second part should be an inline text/plain attachments with all short
        # fields
        self.assertTrue(not parts[1].is_multipart())
        self.assertEqual(parts[1].get_content_type(), 'text/plain')
        self.assertEqual(parts[1].get_content_charset(), 'utf-8')
        self.assertEqual(parts[1].get_filename(), None)
        self.assertEqual(parts[1].get_payload(decode=True), '''ProblemType: Crash
Date: now!
InlineMargin:
 first
 second
 third
 fourth
 fifth
Simple: bar
SimpleLineEnd: bar
SimpleUTF8: 1äö2Φ3
SimpleUnicode: 1äö2Φ3
TwoLine:
 first
 second
TwoLineUTF8:
 pi-π
 nu-η
TwoLineUnicode:
 pi-π
 nu-η
''')

        # third part should be the Multiline: field as attachment
        self.assertTrue(not parts[2].is_multipart())
        self.assertEqual(parts[2].get_content_type(), 'text/plain')
        self.assertEqual(parts[2].get_content_charset(), 'utf-8')
        self.assertEqual(parts[2].get_filename(), 'Multiline.txt')
        self.assertEqual(parts[2].get_payload(decode=True), ''' foo   bar
baz
  blip  
line4
line♥5!!
łıµ€ ⅝
''')

    def test_write_mime_binary(self):
        '''write_mime() for binary values and file references.'''

        bin_value = 'AB' * 10 + '\0' * 10 + 'Z'

        temp = tempfile.NamedTemporaryFile()
        temp.write(bin_value)
        temp.flush()

        tempgz = tempfile.NamedTemporaryFile()
        gz = gzip.GzipFile('File1', 'w', fileobj=tempgz)
        gz.write(bin_value)
        gz.close()
        tempgz.flush()

        pr = ProblemReport(date = 'now!')
        pr['Context'] = 'Test suite'
        pr['File1'] = (temp.name,)
        pr['File1.gz'] = (tempgz.name,)
        pr['Value1'] = bin_value
        pr['Value1.gz'] = open(tempgz.name).read()
        pr['ZValue'] = CompressedValue(bin_value)
        io = StringIO()
        pr.write_mime(io)
        io.seek(0)

        msg = email.message_from_file(io)
        parts = [p for p in msg.walk()]
        self.assertEqual(len(parts), 7)

        # first part is the multipart container
        self.assertTrue(parts[0].is_multipart())

        # second part should be an inline text/plain attachments with all short
        # fields
        self.assertTrue(not parts[1].is_multipart())
        self.assertEqual(parts[1].get_content_type(), 'text/plain')
        self.assertEqual(parts[1].get_content_charset(), 'utf-8')
        self.assertEqual(parts[1].get_filename(), None)
        self.assertEqual(parts[1].get_payload(decode=True),
            'ProblemType: Crash\nContext: Test suite\nDate: now!\n')

        # third part should be the File1: file contents as gzip'ed attachment
        self.assertTrue(not parts[2].is_multipart())
        self.assertEqual(parts[2].get_content_type(), 'application/x-gzip')
        self.assertEqual(parts[2].get_filename(), 'File1.gz')
        f = tempfile.TemporaryFile()
        f.write(parts[2].get_payload(decode=True))
        f.seek(0)
        self.assertEqual(gzip.GzipFile(mode='rb', fileobj=f).read(), bin_value)

        # fourth part should be the File1.gz: file contents as gzip'ed
        # attachment; write_mime() should not compress it again
        self.assertTrue(not parts[3].is_multipart())
        self.assertEqual(parts[3].get_content_type(), 'application/x-gzip')
        self.assertEqual(parts[3].get_filename(), 'File1.gz')
        f = tempfile.TemporaryFile()
        f.write(parts[3].get_payload(decode=True))
        f.seek(0)
        self.assertEqual(gzip.GzipFile(mode='rb', fileobj=f).read(), bin_value)

        # fifth part should be the Value1: value as gzip'ed attachment
        self.assertTrue(not parts[4].is_multipart())
        self.assertEqual(parts[4].get_content_type(), 'application/x-gzip')
        self.assertEqual(parts[4].get_filename(), 'Value1.gz')
        f = tempfile.TemporaryFile()
        f.write(parts[4].get_payload(decode=True))
        f.seek(0)
        self.assertEqual(gzip.GzipFile(mode='rb', fileobj=f).read(), bin_value)

        # sixth part should be the Value1: value as gzip'ed attachment;
        # write_mime should not compress it again
        self.assertTrue(not parts[5].is_multipart())
        self.assertEqual(parts[5].get_content_type(), 'application/x-gzip')
        self.assertEqual(parts[5].get_filename(), 'Value1.gz')
        f = tempfile.TemporaryFile()
        f.write(parts[5].get_payload(decode=True))
        f.seek(0)
        self.assertEqual(gzip.GzipFile(mode='rb', fileobj=f).read(), bin_value)

        # seventh part should be the ZValue: value as gzip'ed attachment;
        # write_mime should not compress it again
        self.assertTrue(not parts[6].is_multipart())
        self.assertEqual(parts[6].get_content_type(), 'application/x-gzip')
        self.assertEqual(parts[6].get_filename(), 'ZValue.gz')
        f = tempfile.TemporaryFile()
        f.write(parts[6].get_payload(decode=True))
        f.seek(0)
        self.assertEqual(gzip.GzipFile(mode='rb', fileobj=f).read(), bin_value)

    def test_write_mime_extra_headers(self):
        '''write_mime() with extra headers.'''

        pr = ProblemReport(date = 'now!')
        pr['Simple'] = 'bar'
        pr['TwoLine'] = 'first\nsecond\n'
        io = StringIO()
        pr.write_mime(io, extra_headers={'Greeting': 'hello world', 
            'Foo': 'Bar'})
        io.seek(0)

        msg = email.message_from_file(io)
        self.assertEqual(msg['Greeting'], 'hello world')
        self.assertEqual(msg['Foo'], 'Bar')
        parts = [p for p in msg.walk()]
        self.assertEqual(len(parts), 2)

        # first part is the multipart container
        self.assertTrue(parts[0].is_multipart())

        # second part should be an inline text/plain attachments with all short
        # fields
        self.assertTrue(not parts[1].is_multipart())
        self.assertEqual(parts[1].get_content_type(), 'text/plain')
        self.assertTrue('Simple: bar' in parts[1].get_payload(decode=True))

    def test_write_mime_filter(self):
        '''write_mime() with key filters.'''

        bin_value = 'AB' * 10 + '\0' * 10 + 'Z'

        pr = ProblemReport(date = 'now!')
        pr['GoodText'] = 'Hi'
        pr['BadText'] = 'YouDontSeeMe'
        pr['GoodBin'] = bin_value
        pr['BadBin'] = 'Y' + '\x05' * 10 + '-'
        io = StringIO()
        pr.write_mime(io, skip_keys=['BadText', 'BadBin'])
        io.seek(0)

        msg = email.message_from_file(io)
        parts = [p for p in msg.walk()]
        self.assertEqual(len(parts), 3)

        # first part is the multipart container
        self.assertTrue(parts[0].is_multipart())

        # second part should be an inline text/plain attachments with all short
        # fields
        self.assertTrue(not parts[1].is_multipart())
        self.assertEqual(parts[1].get_content_type(), 'text/plain')
        self.assertEqual(parts[1].get_content_charset(), 'utf-8')
        self.assertEqual(parts[1].get_filename(), None)
        self.assertEqual(parts[1].get_payload(decode=True), '''ProblemType: Crash
Date: now!
GoodText: Hi
''')

        # third part should be the GoodBin: field as attachment
        self.assertTrue(not parts[2].is_multipart())
        f = tempfile.TemporaryFile()
        f.write(parts[2].get_payload(decode=True))
        f.seek(0)
        self.assertEqual(gzip.GzipFile(mode='rb', fileobj=f).read(), bin_value)

    def test_write_mime_order(self):
        '''write_mime() with keys ordered.'''

        bin_value = 'AB' * 10 + '\0' * 10 + 'Z'

        pr = ProblemReport(date = 'now!')
        pr['SecondText'] = 'What'
        pr['FirstText'] = 'Who'
        pr['FourthText'] = 'Today'
        pr['ThirdText'] = "I Don't Know"
        io = StringIO()
        pr.write_mime(io, priority_fields=['FirstText', 'SecondText',
            'ThirdText', 'Unknown', 'FourthText'])
        io.seek(0)

        msg = email.message_from_file(io)
        parts = [p for p in msg.walk()]
        self.assertEqual(len(parts), 2)

        # first part is the multipart container
        self.assertTrue(parts[0].is_multipart())

        # second part should be an inline text/plain attachments with all short
        # fields
        self.assertTrue(not parts[1].is_multipart())
        self.assertEqual(parts[1].get_content_type(), 'text/plain')
        self.assertEqual(parts[1].get_content_charset(), 'utf-8')
        self.assertEqual(parts[1].get_filename(), None)
        self.assertEqual(parts[1].get_payload(decode=True), '''FirstText: Who
SecondText: What
ThirdText: I Don't Know
FourthText: Today
ProblemType: Crash
Date: now!
''')

    def test_updating(self):
        '''new_keys() and write() with only_new=True.'''

        pr = ProblemReport()
        self.assertEqual(pr.new_keys(), set(['ProblemType', 'Date']))
        pr.load(StringIO(
'''ProblemType: Crash
Date: now!
Foo: bar
Baz: blob
'''))

        self.assertEqual(pr.new_keys(), set())

        pr['Foo'] = 'changed'
        pr['NewKey'] = 'new new'
        self.assertEqual(pr.new_keys(), set(['NewKey']))

        out = StringIO()
        pr.write(out, only_new=True)
        self.assertEqual(out.getvalue(), 'NewKey: new new\n')

    def test_import_dict(self):
        '''importing a dictionary with update().'''

        pr = ProblemReport()
        pr['oldtext'] = 'Hello world'
        pr['oldbin'] = 'AB' * 10 + '\0' * 10 + 'Z'
        pr['overwrite'] = 'I am crap'

        d = {}
        d['newtext'] = 'Goodbye world'
        d['newbin'] = '11\000\001\002\xFFZZ'
        d['overwrite'] = 'I am good' 

        pr.update(d)
        self.assertEqual(pr['oldtext'], 'Hello world')
        self.assertEqual(pr['oldbin'], 'AB' * 10 + '\0' * 10 + 'Z')
        self.assertEqual(pr['newtext'], 'Goodbye world')
        self.assertEqual(pr['newbin'], '11\000\001\002\xFFZZ')
        self.assertEqual(pr['overwrite'], 'I am good')

if __name__ == '__main__':
    unittest.main()