~abompard/mailman/import21

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
# Copyright (C) 2010-2013 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman 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 3 of the License, or (at your option)
# any later version.
#
# GNU Mailman is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# GNU Mailman.  If not, see <http://www.gnu.org/licenses/>.

"""Tests for config.pck imports."""

from __future__ import absolute_import, print_function, unicode_literals

__metaclass__ = type
__all__ = [
    'TestArchiveImport',
    'TestBasicImport',
    ]


import os
import cPickle
import unittest
from datetime import timedelta, datetime
from traceback import format_exc

from mailman.config import config
from mailman.app.lifecycle import create_list, remove_list
from mailman.interfaces.archiver import ArchivePolicy
from mailman.testing.layers import ConfigLayer
from mailman.utilities.importer import import_config_pck, Import21Error
from mailman.interfaces.archiver import ArchivePolicy
from mailman.interfaces.action import Action, FilterAction
from mailman.interfaces.address import ExistingAddressError
from mailman.interfaces.bounce import UnrecognizedBounceDisposition
from mailman.interfaces.bans import IBanManager
from mailman.interfaces.mailinglist import IAcceptableAliasSet
from mailman.interfaces.nntp import NewsgroupModeration
from mailman.interfaces.autorespond import ResponseAction
from mailman.interfaces.templates import ITemplateLoader
from mailman.interfaces.usermanager import IUserManager
from mailman.interfaces.member import DeliveryMode, DeliveryStatus, MemberRole
from mailman.interfaces.languages import ILanguageManager
from mailman.model.address import Address
from mailman.handlers.decorate import decorate
from mailman.utilities.string import expand
from pkg_resources import resource_filename
from enum import Enum
from zope.component import getUtility
from storm.locals import Store



class DummyEnum(Enum):
    # For testing purposes
    val = 42


class TestBasicImport(unittest.TestCase):
    layer = ConfigLayer

    def setUp(self):
        self._mlist = create_list('blank@example.com')
        pickle_file = resource_filename('mailman.testing', 'config.pck')
        with open(pickle_file) as fp:
            self._pckdict = cPickle.load(fp)

    def tearDown(self):
        remove_list(self._mlist)

    def _import(self):
        import_config_pck(self._mlist, self._pckdict)

    def test_display_name(self):
        # The mlist.display_name gets set from the old list's real_name.
        self.assertEqual(self._mlist.display_name, 'Blank')
        self._import()
        self.assertEqual(self._mlist.display_name, 'Test')

    def test_mail_host_invariant(self):
        # The mlist.mail_host must not be updated when importing (it will
        # change the list_id property, which is supposed to be read-only)
        self.assertEqual(self._mlist.mail_host, 'example.com')
        self._import()
        self.assertEqual(self._mlist.mail_host, 'example.com')

    def test_rfc2369_headers(self):
        self._mlist.allow_list_posts = False
        self._mlist.include_rfc2369_headers = False
        self._import()
        self.assertTrue(self._mlist.allow_list_posts)
        self.assertTrue(self._mlist.include_rfc2369_headers)

    def test_no_overwrite_rosters(self):
        # The mlist.members and mlist.digest_members rosters must not be
        # overwritten.
        for rname in ("members", "digest_members"):
            roster = getattr(self._mlist, rname)
            self.assertFalse(isinstance(roster, dict))
            self._import()
            self.assertFalse(isinstance(roster, dict),
                "The %s roster has been overwritten by the import" % rname)

    def test_last_post_time(self):
        # last_post_time -> last_post_at
        self._pckdict["last_post_time"] = 1270420800.274485
        self.assertEqual(self._mlist.last_post_at, None)
        self._import()
        # convert 1270420800.2744851 to datetime
        expected = datetime(2010, 4, 4, 22, 40, 0, 274485)
        self.assertEqual(self._mlist.last_post_at, expected)

    def test_autoresponse_grace_period(self):
        # autoresponse_graceperiod -> autoresponse_grace_period
        # must be a timedelta, not an int
        self._mlist.autoresponse_grace_period = timedelta(days=42)
        self._import()
        self.assertTrue(isinstance(
                self._mlist.autoresponse_grace_period, timedelta))
        self.assertEqual(self._mlist.autoresponse_grace_period,
                         timedelta(days=90))

    def test_autoresponse_admin_to_owner(self):
        # admin -> owner
        self._mlist.autorespond_owner = DummyEnum.val
        self._mlist.autoresponse_owner_text = 'DUMMY'
        self._import()
        self.assertEqual(self._mlist.autorespond_owner, ResponseAction.none)
        self.assertEqual(self._mlist.autoresponse_owner_text, '')

    #def test_administrative(self):
    #    # administrivia -> administrative
    #    self._mlist.administrative = None
    #    self._import()
    #    self.assertTrue(self._mlist.administrative)

    def test_filter_pass_renames(self):
        # mime_types -> types
        # filename_extensions -> extensions
        self._mlist.filter_types = ["dummy"]
        self._mlist.pass_types = ["dummy"]
        self._mlist.filter_extensions = ["dummy"]
        self._mlist.pass_extensions = ["dummy"]
        self._import()
        self.assertEqual(list(self._mlist.filter_types), [])
        self.assertEqual(list(self._mlist.filter_extensions),
                         ['exe', 'bat', 'cmd', 'com', 'pif',
                          'scr', 'vbs', 'cpl'])
        self.assertEqual(list(self._mlist.pass_types),
                ['multipart/mixed', 'multipart/alternative', 'text/plain'])
        self.assertEqual(list(self._mlist.pass_extensions), [])

    def test_process_bounces(self):
        # bounce_processing -> process_bounces
        self._mlist.process_bounces = None
        self._import()
        self.assertTrue(self._mlist.process_bounces)

    def test_forward_unrecognized_bounces_to(self):
        # bounce_unrecognized_goes_to_list_owner -> forward_unrecognized_bounces_to
        self._mlist.forward_unrecognized_bounces_to = DummyEnum.val
        self._import()
        self.assertEqual(self._mlist.forward_unrecognized_bounces_to,
                         UnrecognizedBounceDisposition.administrators)

    def test_moderator_password(self):
        # mod_password -> moderator_password
        self._mlist.moderator_password = str("TESTDATA")
        self._import()
        self.assertEqual(self._mlist.moderator_password, None)

    def test_moderator_password_str(self):
        # moderator_password must not be unicode
        self._pckdict[b"mod_password"] = b'TESTVALUE'
        self._import()
        self.assertFalse(isinstance(self._mlist.moderator_password, unicode))
        self.assertEqual(self._mlist.moderator_password, b'TESTVALUE')

    def test_newsgroup_moderation(self):
        # news_moderation -> newsgroup_moderation
        # news_prefix_subject_too -> nntp_prefix_subject_too
        self._mlist.newsgroup_moderation = DummyEnum.val
        self._mlist.nntp_prefix_subject_too = None
        self._import()
        self.assertEqual(self._mlist.newsgroup_moderation,
                         NewsgroupModeration.none)
        self.assertTrue(self._mlist.nntp_prefix_subject_too)

    def test_msg_to_message(self):
        # send_welcome_msg -> send_welcome_message
        # send_goodbye_msg -> send_goodbye_message
        self._mlist.send_welcome_message = None
        self._mlist.send_goodbye_message = None
        self._import()
        self.assertTrue(self._mlist.send_welcome_message)
        self.assertTrue(self._mlist.send_goodbye_message)

    def test_ban_list(self):
        banned = [
            ("anne@example.com", "anne@example.com"),
            ("^.*@example.com", "bob@example.com"),
            ("non-ascii-\xe8@example.com", "non-ascii-\ufffd@example.com"),
            ]
        self._pckdict["ban_list"] = [ b[0].encode("iso-8859-1") for b in banned ]
        try:
            self._import()
        except UnicodeDecodeError, e:
            print(format_exc())
            self.fail(e)
        for _pattern, addr in banned:
            self.assertTrue(IBanManager(self._mlist).is_banned(addr))

    def test_acceptable_aliases(self):
        # it used to be a plain-text field (values are newline-separated)
        aliases = ["alias1@example.com",
                   "alias2@exemple.com",
                   "non-ascii-\xe8@example.com",
                   ]
        self._pckdict[b"acceptable_aliases"] = \
                ("\n".join(aliases)).encode("utf-8")
        self._import()
        alias_set = IAcceptableAliasSet(self._mlist)
        self.assertEqual(sorted(alias_set.aliases), aliases)

    def test_acceptable_aliases_invalid(self):
        # values without an '@' sign used to be matched against the local part,
        # now we need to add the '^' sign
        aliases = ["invalid-value", ]
        self._pckdict[b"acceptable_aliases"] = \
                ("\n".join(aliases)).encode("utf-8")
        try:
            self._import()
        except ValueError, e:
            print(format_exc())
            self.fail("Invalid value '%s' caused a crash" % e)
        alias_set = IAcceptableAliasSet(self._mlist)
        self.assertEqual(sorted(alias_set.aliases),
                         [ ("^" + a) for a in aliases ])

    def test_acceptable_aliases_as_list(self):
        # in some versions of the pickle, it can be a list, not a string
        # (seen in the wild)
        aliases = [b"alias1@example.com", b"alias2@exemple.com" ]
        self._pckdict[b"acceptable_aliases"] = aliases
        try:
            self._import()
        except AttributeError:
            print(format_exc())
            self.fail("Import does not handle acceptable_aliases as list")
        alias_set = IAcceptableAliasSet(self._mlist)
        self.assertEqual(sorted(alias_set.aliases), aliases)

    def test_info_non_ascii(self):
        # info can contain non-ascii chars
        info = 'O idioma aceito \xe9 somente Portugu\xeas do Brasil'
        self._pckdict[b"info"] = info.encode("utf-8")
        self._import()
        self.assertEqual(self._mlist.info, info,
                         "Encoding to UTF-8 is not handled")
        # test fallback to ascii with replace
        self._pckdict[b"info"] = info.encode("iso-8859-1")
        self._import()
        self.assertEqual(self._mlist.info,
                         unicode(self._pckdict[b"info"], "ascii", "replace"),
                         "We don't fall back to replacing non-ascii chars")

    def test_preferred_language(self):
        self._pckdict[b"preferred_language"] = b'ja'
        english = getUtility(ILanguageManager).get('en')
        japanese = getUtility(ILanguageManager).get('ja')
        self.assertEqual(self._mlist.preferred_language, english)
        self._import()
        self.assertEqual(self._mlist.preferred_language, japanese)

    def test_preferred_language_unknown_previous(self):
        # when the previous language is unknown, it should not fail
        self._mlist._preferred_language = 'xx' # non-existant
        self._import()
        english = getUtility(ILanguageManager).get('en')
        self.assertEqual(self._mlist.preferred_language, english)

    def test_new_language(self):
        self._pckdict[b"preferred_language"] = b'xx_XX'
        try:
            self._import()
        except Import21Error, e:
            # check the message
            self.assertTrue("[language.xx_XX]" in str(e))
        else:
            self.fail("Import21Error was not raised")



class TestArchiveImport(unittest.TestCase):
    """Test conversion of the archive policies.

    Mailman 2.1 had two variables `archive` and `archive_private`.  Now
    there's just a single `archive_policy` enum.
    """
    layer = ConfigLayer

    def setUp(self):
        self._mlist = create_list('blank@example.com')
        self._mlist.archive_policy = DummyEnum.val

    def tearDown(self):
        remove_list(self._mlist)

    def _do_test(self, pckdict, expected):
        import_config_pck(self._mlist, pckdict)
        self.assertEqual(self._mlist.archive_policy, expected)

    def test_public(self):
        self._do_test(dict(archive=True, archive_private=False),
                      ArchivePolicy.public)

    def test_private(self):
        self._do_test(dict(archive=True, archive_private=True),
                      ArchivePolicy.private)

    def test_no_archive(self):
        self._do_test(dict(archive=False, archive_private=False),
                      ArchivePolicy.never)

    def test_bad_state(self):
        # For some reason, the old list has the invalid archiving state where
        # `archive` is False and `archive_private` is True.  It doesn't matter
        # because this still collapses to the same enum value.
        self._do_test(dict(archive=False, archive_private=True),
                      ArchivePolicy.never)

    def test_missing_archive_key(self):
        # For some reason, the old list didn't have an `archive` key.  We
        # treat this as if no archiving is done.
        self._do_test(dict(archive_private=False), ArchivePolicy.never)

    def test_missing_archive_key_archive_public(self):
        # For some reason, the old list didn't have an `archive` key, and it
        # has weird value for archive_private.  We treat this as if no
        # archiving is done.
        self._do_test(dict(archive_private=True), ArchivePolicy.never)

    def test_missing_archive_private_key(self):
        # For some reason, the old list was missing an `archive_private` key.
        # For maximum safety, we treat this as private archiving.
        self._do_test(dict(archive=True), ArchivePolicy.private)



class TestFilterActionImport(unittest.TestCase):
    # The mlist.filter_action enum values have changed. In Mailman 2.1 the
    # order was 'Discard', 'Reject', 'Forward to List Owner', 'Preserve'.

    layer = ConfigLayer

    def setUp(self):
        self._mlist = create_list('blank@example.com')
        self._mlist.filter_action = DummyEnum.val

    def tearDown(self):
        remove_list(self._mlist)

    def _do_test(self, original, expected):
        import_config_pck(self._mlist, dict(filter_action=original))
        self.assertEqual(self._mlist.filter_action, expected)

    def test_discard(self):
        self._do_test(0, FilterAction.discard)

    def test_reject(self):
        self._do_test(1, FilterAction.reject)

    def test_forward(self):
        self._do_test(2, FilterAction.forward)

    def test_preserve(self):
        self._do_test(3, FilterAction.preserve)



class TestMemberActionImport(unittest.TestCase):
    # The mlist.default_member_action and mlist.default_nonmember_action enum
    # values are different in Mailman 2.1, they have been merged into a
    # single enum in Mailman 3
    # For default_member_action, which used to be called
    # member_moderation_action, the values were:
    # 0==Hold, 1=Reject, 2==Discard
    # For default_nonmember_action, which used to be called
    # generic_nonmember_action, the values were:
    # 0==Accept, 1==Hold, 2==Reject, 3==Discard

    layer = ConfigLayer

    def setUp(self):
        self._mlist = create_list('blank@example.com')
        self._mlist.default_member_action = DummyEnum.val
        self._mlist.default_nonmember_action = DummyEnum.val
        self._pckdict = dict(
            member_moderation_action=DummyEnum.val,
            generic_nonmember_action=DummyEnum.val,
            )

    def tearDown(self):
        remove_list(self._mlist)

    def _do_test(self, expected):
        import_config_pck(self._mlist, self._pckdict)
        for key, value in expected.iteritems():
            self.assertEqual(getattr(self._mlist, key), value)

    def test_member_hold(self):
        self._pckdict[b"member_moderation_action"] = 0
        self._do_test(dict(default_member_action=Action.hold))

    def test_member_reject(self):
        self._pckdict[b"member_moderation_action"] = 1
        self._do_test(dict(default_member_action=Action.reject))

    def test_member_discard(self):
        self._pckdict[b"member_moderation_action"] = 2
        self._do_test(dict(default_member_action=Action.discard))

    def test_nonmember_accept(self):
        self._pckdict[b"generic_nonmember_action"] = 0
        self._do_test(dict(default_nonmember_action=Action.accept))

    def test_nonmember_hold(self):
        self._pckdict[b"generic_nonmember_action"] = 1
        self._do_test(dict(default_nonmember_action=Action.hold))

    def test_nonmember_reject(self):
        self._pckdict[b"generic_nonmember_action"] = 2
        self._do_test(dict(default_nonmember_action=Action.reject))

    def test_nonmember_discard(self):
        self._pckdict[b"generic_nonmember_action"] = 3
        self._do_test(dict(default_nonmember_action=Action.discard))



class TestConvertToURI(unittest.TestCase):
    # The following values were plain text, and are now URIs in Mailman 3:
    # - welcome_message_uri
    # - goodbye_message_uri
    # - header_uri
    # - footer_uri
    # - digest_header_uri
    # - digest_footer_uri
    #
    # The templates contain variables that must be replaced:
    # - %(real_name)s -> %(display_name)s
    # - %(real_name)s@%(host_name)s -> %(fqdn_listname)s
    # - %(web_page_url)slistinfo%(cgiext)s/%(_internal_name)s -> %(listinfo_uri)s

    layer = ConfigLayer

    def setUp(self):
        self._mlist = create_list('blank@example.com')
        self._conf_mapping = dict(
            welcome_msg="welcome_message_uri",
            goodbye_msg="goodbye_message_uri",
            msg_header="header_uri",
            msg_footer="footer_uri",
            digest_header="digest_header_uri",
            digest_footer="digest_footer_uri",
        )
        self._pckdict = dict()
        #self._pckdict = {
        #    "preferred_language": "XX", # templates are lang-specific
        #}

    def tearDown(self):
        remove_list(self._mlist)

    def test_text_to_uri(self):
        for oldvar, newvar in self._conf_mapping.iteritems():
            self._pckdict[str(oldvar)] = b"TEST VALUE"
            import_config_pck(self._mlist, self._pckdict)
            newattr = getattr(self._mlist, newvar)
            text = decorate(self._mlist, newattr)
            self.assertEqual(text, "TEST VALUE",
                    "Old variable %s was not properly imported to %s"
                    % (oldvar, newvar))

    def test_substitutions(self):
        test_text = ("UNIT TESTING %(real_name)s mailing list\n"
                     "%(real_name)s@%(host_name)s\n"
                     "%(web_page_url)slistinfo%(cgiext)s/%(_internal_name)s")
        expected_text = ("UNIT TESTING $display_name mailing list\n"
                         "$fqdn_listname\n"
                         "$listinfo_uri")
        for oldvar, newvar in self._conf_mapping.iteritems():
            self._pckdict[str(oldvar)] = str(test_text)
            import_config_pck(self._mlist, self._pckdict)
            newattr = getattr(self._mlist, newvar)
            template_uri = expand(newattr, dict(
                listname=self._mlist.fqdn_listname,
                language=self._mlist.preferred_language.code,
                ))
            loader = getUtility(ITemplateLoader)
            text = loader.get(template_uri)
            self.assertEqual(text, expected_text,
                    "Old variables were not converted for %s" % newvar)

    def test_keep_default(self):
        # If the value was not changed from MM2.1's default, don't import it
        default_msg_footer = (
            "_______________________________________________\n"
            "%(real_name)s mailing list\n"
            "%(real_name)s@%(host_name)s\n"
            "%(web_page_url)slistinfo%(cgiext)s/%(_internal_name)s"
            )
        for oldvar in ("msg_footer", "digest_footer"):
            newvar = self._conf_mapping[oldvar]
            self._pckdict[str(oldvar)] = str(default_msg_footer)
            old_value = getattr(self._mlist, newvar)
            import_config_pck(self._mlist, self._pckdict)
            new_value = getattr(self._mlist, newvar)
            self.assertEqual(old_value, new_value,
                    "Default value was not preserved for %s" % newvar)

    def test_keep_default_if_fqdn_changed(self):
        # Use case: importing the old a@ex.com into b@ex.com
        # We can't check if it changed from the default
        # -> don't import, we may do more harm than good and it's easy to
        # change if needed
        test_value = b"TEST-VALUE"
        for oldvar, newvar in self._conf_mapping.iteritems():
            self._mlist.mail_host = "example.com"
            self._pckdict[b"mail_host"] = b"test.example.com"
            self._pckdict[str(oldvar)] = test_value
            old_value = getattr(self._mlist, newvar)
            import_config_pck(self._mlist, self._pckdict)
            new_value = getattr(self._mlist, newvar)
            self.assertEqual(old_value, new_value,
                    "Default value was not preserved for %s" % newvar)

    def test_unicode(self):
        # non-ascii templates
        for oldvar in self._conf_mapping:
            self._pckdict[str(oldvar)] = b"Ol\xe1!"
        try:
            import_config_pck(self._mlist, self._pckdict)
        except UnicodeDecodeError, e:
            print(format_exc())
            self.fail(e)
        for oldvar, newvar in self._conf_mapping.iteritems():
            newattr = getattr(self._mlist, newvar)
            text = decorate(self._mlist, newattr)
            expected = u'Ol\ufffd!'
            self.assertEqual(text, expected)

    def test_unicode_in_default(self):
        # What if the default template is already in UTF-8? (like if you import twice)
        footer = b'\xe4\xb8\xad $listinfo_uri'
        footer_path = os.path.join(config.VAR_DIR, "templates", "lists",
                                   "blank@example.com", "en", "footer-generic.txt")
        try:
            os.makedirs(os.path.dirname(footer_path))
        except OSError:
            pass
        with open(footer_path, "w") as footer_file:
            footer_file.write(footer)
        self._pckdict[b"msg_footer"] = b"NEW-VALUE"
        import_config_pck(self._mlist, self._pckdict)
        text = decorate(self._mlist, self._mlist.footer_uri)
        self.assertEqual(text, 'NEW-VALUE')


class TestRosterImport(unittest.TestCase):

    layer = ConfigLayer

    def setUp(self):
        self._mlist = create_list('blank@example.com')
        self._pckdict = {
            "members": {
                "anne@example.com": 0,
                "bob@example.com": b"bob@ExampLe.Com",
            },
            "digest_members": {
                "cindy@example.com": 0,
                "dave@example.com": b"dave@ExampLe.Com",
            },
            "passwords": {
                "anne@example.com" : b"annepass",
                "bob@example.com"  : b"bobpass",
                "cindy@example.com": b"cindypass",
                "dave@example.com" : b"davepass",
            },
            "language": {
                "anne@example.com" : b"fr",
                "bob@example.com"  : b"de",
                "cindy@example.com": b"es",
                "dave@example.com" : b"it",
            },
            "usernames": { # Usernames are unicode strings in the pickle
                "anne@example.com" : "Anne",
                "bob@example.com"  : "Bob",
                "cindy@example.com": "Cindy",
                "dave@example.com" : "Dave",
            },
            "owner": [
                "anne@example.com",
                "emily@example.com",
            ],
            "moderator": [
                "bob@example.com",
                "fred@example.com",
            ],
        }
        self._usermanager = getUtility(IUserManager)
        language_manager = getUtility(ILanguageManager)
        for code in self._pckdict["language"].values():
            if code not in language_manager.codes:
                language_manager.add(code, 'utf-8', code)

    def tearDown(self):
        remove_list(self._mlist)

    def test_member(self):
        import_config_pck(self._mlist, self._pckdict)
        for name in ("anne", "bob", "cindy", "dave"):
            addr = "%s@example.com" % name
            self.assertTrue(
                    addr in [ a.email for a in self._mlist.members.addresses],
                    "Address %s was not imported" % addr)
        self.assertTrue("anne@example.com" in [ a.email
                        for a in self._mlist.regular_members.addresses])
        self.assertTrue("bob@example.com" in [ a.email
                        for a in self._mlist.regular_members.addresses])
        self.assertTrue("cindy@example.com" in [ a.email
                        for a in self._mlist.digest_members.addresses])
        self.assertTrue("dave@example.com" in [ a.email
                        for a in self._mlist.digest_members.addresses])

    def test_original_email(self):
        import_config_pck(self._mlist, self._pckdict)
        bob = self._usermanager.get_address("bob@example.com")
        self.assertEqual(bob.original_email, "bob@ExampLe.Com")
        dave = self._usermanager.get_address("dave@example.com")
        self.assertEqual(dave.original_email, "dave@ExampLe.Com")

    def test_language(self):
        import_config_pck(self._mlist, self._pckdict)
        for name in ("anne", "bob", "cindy", "dave"):
            addr = "%s@example.com" % name
            member = self._mlist.members.get_member(addr)
            self.assertTrue(member is not None,
                            "Address %s was not imported" % addr)
            print(self._pckdict["language"])
            print(member.preferred_language, member.preferred_language.code)
            self.assertEqual(member.preferred_language.code,
                             self._pckdict["language"][addr])

    def test_new_language(self):
        self._pckdict[b"language"]["anne@example.com"] = b'xx_XX'
        try:
            import_config_pck(self._mlist, self._pckdict)
        except Import21Error, e:
            # check the message
            self.assertTrue("[language.xx_XX]" in str(e))
        else:
            self.fail("Import21Error was not raised")

    def test_username(self):
        import_config_pck(self._mlist, self._pckdict)
        for name in ("anne", "bob", "cindy", "dave"):
            addr = "%s@example.com" % name
            user = self._usermanager.get_user(addr)
            address = self._usermanager.get_address(addr)
            self.assertTrue(user is not None,
                    "User %s was not imported" % addr)
            self.assertTrue(address is not None,
                    "Address %s was not imported" % addr)
            display_name = self._pckdict["usernames"][addr]
            self.assertEqual(user.display_name, display_name,
                    "The display name was not set for User %s" % addr)
            self.assertEqual(address.display_name, display_name,
                    "The display name was not set for Address %s" % addr)

    def test_owner(self):
        import_config_pck(self._mlist, self._pckdict)
        for name in ("anne", "emily"):
            addr = "%s@example.com" % name
            self.assertTrue(
                    addr in [ a.email for a in self._mlist.owners.addresses ],
                    "Address %s was not imported as owner" % addr)
        self.assertFalse("emily@example.com" in
                [ a.email for a in self._mlist.members.addresses ],
                "Address emily@ was wrongly added to the members list")

    def test_moderator(self):
        import_config_pck(self._mlist, self._pckdict)
        for name in ("bob", "fred"):
            addr = "%s@example.com" % name
            self.assertTrue(
                    addr in [ a.email for a in self._mlist.moderators.addresses ],
                    "Address %s was not imported as moderator" % addr)
        self.assertFalse("fred@example.com" in
                [ a.email for a in self._mlist.members.addresses ],
                "Address fred@ was wrongly added to the members list")

    def test_password(self):
        #self.anne.password = config.password_context.encrypt('abc123')
        import_config_pck(self._mlist, self._pckdict)
        for name in ("anne", "bob", "cindy", "dave"):
            addr = "%s@example.com" % name
            user = self._usermanager.get_user(addr)
            self.assertTrue(user is not None,
                    "Address %s was not imported" % addr)
            self.assertEqual(user.password, b'{plaintext}%spass' % name,
                    "Password for %s was not imported" % addr)

    def test_same_user(self):
        # Adding the address of an existing User must not create another user
        user = self._usermanager.create_user('anne@example.com', 'Anne')
        user.register("bob@example.com") # secondary email
        import_config_pck(self._mlist, self._pckdict)
        member = self._mlist.members.get_member('bob@example.com')
        self.assertEqual(member.user, user)

    def test_owner_and_moderator_not_lowercase(self):
        # In the v2.1 pickled dict, the owner and moderator lists are not
        # necessarily lowercased already
        self._pckdict["owner"] = [b"Anne@example.com"]
        self._pckdict["moderator"] = [b"Anne@example.com"]
        try:
            import_config_pck(self._mlist, self._pckdict)
        except AssertionError:
            print(format_exc())
            self.fail("The address was not lowercased")
        self.assertTrue("anne@example.com" in
                [ a.email for a in self._mlist.owners.addresses ])
        self.assertTrue("anne@example.com" in
                [ a.email for a in self._mlist.moderators.addresses])

    def test_address_already_exists_but_no_user(self):
        # An address already exists, but it is not linked to a user nor
        # subscribed
        anne_addr = Address("anne@example.com", "Anne")
        Store.of(self._mlist).add(anne_addr)
        try:
            import_config_pck(self._mlist, self._pckdict)
        except ExistingAddressError:
            print(format_exc())
            self.fail("existing address was not checked")
        anne = self._usermanager.get_user("anne@example.com")
        self.assertTrue(anne.controls("anne@example.com"))
        self.assertTrue(anne_addr in self._mlist.regular_members.addresses)

    def test_address_already_subscribed_but_no_user(self):
        # An address is already subscribed, but it is not linked to a user
        anne_addr = Address("anne@example.com", "Anne")
        self._mlist.subscribe(anne_addr)
        try:
            import_config_pck(self._mlist, self._pckdict)
        except ExistingAddressError:
            print(format_exc())
            self.fail("existing address was not checked")
        anne = self._usermanager.get_user("anne@example.com")
        self.assertTrue(anne.controls("anne@example.com"))




class TestPreferencesImport(unittest.TestCase):

    layer = ConfigLayer

    def setUp(self):
        self._mlist = create_list('blank@example.com')
        self._pckdict = dict(
            members={ "anne@example.com": 0 },
            user_options=dict(),
            delivery_status=dict(),
        )
        self._usermanager = getUtility(IUserManager)

    def tearDown(self):
        remove_list(self._mlist)

    def _do_test(self, oldvalue, expected):
        self._pckdict["user_options"]["anne@example.com"] = oldvalue
        import_config_pck(self._mlist, self._pckdict)
        user = self._usermanager.get_user("anne@example.com")
        self.assertTrue(user is not None, "User was not imported")
        member = self._mlist.members.get_member("anne@example.com")
        self.assertTrue(member is not None, "Address was not subscribed")
        for exp_name, exp_val in expected.iteritems():
            try:
                currentval = getattr(member, exp_name)
            except AttributeError:
                # hide_address has no direct getter
                currentval = getattr(member.preferences, exp_name)
            self.assertEqual(currentval, exp_val,
                    "Preference %s was not imported" % exp_name)
        # XXX: should I check that other params are still equal to
        # mailman.core.constants.system_preferences ?

    def test_acknowledge_posts(self):
        # AcknowledgePosts
        self._do_test(4, dict(acknowledge_posts=True))

    def test_hide_address(self):
        # ConcealSubscription
        self._do_test(16, dict(hide_address=True))

    def test_receive_own_postings(self):
        # DontReceiveOwnPosts
        self._do_test(2, dict(receive_own_postings=False))

    def test_receive_list_copy(self):
        # DontReceiveDuplicates
        self._do_test(256, dict(receive_list_copy=False))

    def test_digest_plain(self):
        # Digests & DisableMime
        self._pckdict["digest_members"] = self._pckdict["members"].copy()
        self._pckdict["members"] = dict()
        self._do_test(8, dict(delivery_mode=DeliveryMode.plaintext_digests))

    def test_digest_mime(self):
        # Digests & not DisableMime
        self._pckdict["digest_members"] = self._pckdict["members"].copy()
        self._pckdict["members"] = dict()
        self._do_test(0, dict(delivery_mode=DeliveryMode.mime_digests))

    def test_delivery_status(self):
        # look for the pckdict["delivery_status"] key which will look like
        # (status, time) where status is among the following:
        # ENABLED  = 0 # enabled
        # UNKNOWN  = 1 # legacy disabled
        # BYUSER   = 2 # disabled by user choice
        # BYADMIN  = 3 # disabled by admin choice
        # BYBOUNCE = 4 # disabled by bounces
        for oldval, expected in enumerate((DeliveryStatus.enabled,
                DeliveryStatus.unknown, DeliveryStatus.by_user,
                DeliveryStatus.by_moderator, DeliveryStatus.by_bounces)):
            self._pckdict["delivery_status"]["anne@example.com"] = (oldval, 0)
            import_config_pck(self._mlist, self._pckdict)
            member = self._mlist.members.get_member("anne@example.com")
            self.assertTrue(member is not None, "Address was not subscribed")
            self.assertEqual(member.delivery_status, expected)
            member.unsubscribe()

    def test_moderate(self):
        # Option flag Moderate is translated to
        # member.moderation_action = Action.hold
        self._do_test(128, dict(moderation_action=Action.hold))

    def test_multiple_options(self):
        # DontReceiveDuplicates & DisableMime & SuppressPasswordReminder
        self._pckdict[b"digest_members"] = self._pckdict[b"members"].copy()
        self._pckdict[b"members"] = dict()
        self._do_test(296, dict(
                receive_list_copy=False,
                delivery_mode=DeliveryMode.plaintext_digests,
                ))