django-postman / postman / tests.py

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
"""
Test suite.

- Do not put 'mailer' in INSTALLED_APPS, it disturbs the emails counting.
- Make sure these templates are accessible:
    registration/login.html
    base.html
    404.html

To have a fast test session, you can set a minimal configuration as:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': ':memory:',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    # 'pagination', # or use the mock
    # 'ajax_select', # is an option
    # 'notification', # is an option
    'postman',
)

"""
import copy
from datetime import datetime, timedelta
import re
import sys
from time import sleep

from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.models import User, AnonymousUser
from django.core import mail
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse, clear_url_caches, get_resolver, get_urlconf
from django.db.models import Q
from django.http import QueryDict
from django.template import Template, Context, TemplateSyntaxError, TemplateDoesNotExist
from django.test import TestCase

from postman.fields import CommaSeparatedUserField
# because of reload()'s, do "from postman.forms import xxForm" just before needs
from postman.models import ORDER_BY_KEY, ORDER_BY_MAPPER, Message, PendingMessage,\
    STATUS_PENDING, STATUS_ACCEPTED, STATUS_REJECTED
from postman.urls import OPTION_MESSAGES
from postman.utils import format_body, format_subject, notification

if not 'pagination' in settings.INSTALLED_APPS:
    try:
        import postman.templatetags.pagination_tags
    except:
        sys.exit(
            "Some templates need templatetags from the django-pagination application.\n"
            "Add it to the INSTALLED_APPS, or allow a mock by renaming\n"
            "postman/templatetags/pagination_tags_for_tests.py to pagination_tags.py"
        )

class GenericTest(TestCase):
    """
    Usual generic tests.
    """
    def test_version(self):
        self.assertEqual(sys.modules['postman'].__version__, "1.0.0")

class BaseTest(TestCase):
    """
    Common configuration and helper functions for all tests.
    """
    urls = 'postman.test_urls'

    def setUp(self):
        settings.LANGUAGE_CODE = 'en' # do not bother about translation
        for a in (
            'POSTMAN_DISALLOW_ANONYMOUS',
            'POSTMAN_DISALLOW_MULTIRECIPIENTS',
            'POSTMAN_DISALLOW_COPIES_ON_REPLY',
            'POSTMAN_AUTO_MODERATE_AS',
        ):
            if hasattr(settings, a):
                delattr(settings, a)
        settings.POSTMAN_NOTIFIER_APP = None
        settings.POSTMAN_MAILER_APP = None
        settings.POSTMAN_AUTOCOMPLETER_APP = {
            'arg_default': 'postman_single', # no default, mandatory to enable the feature
        }
        self.reload_modules()

        self.user1 = User.objects.create_user('foo', 'foo@domain.com', 'pass')
        self.user2 = User.objects.create_user('bar', 'bar@domain.com', 'pass')
        self.user3 = User.objects.create_user('baz', 'baz@domain.com', 'pass')
        self.email = 'qux@domain.com'

    def check_now(self, dt):
        "Check that a date is now. Well... almost."
        delta = dt - datetime.now()
        seconds = delta.days * (24*60*60) + delta.seconds
        self.assert_(-2 <= seconds <= 2)

    def check_status(self, m, status=STATUS_PENDING, is_new=True, is_replied=False, parent=None, thread=None,
        moderation_date=False, moderation_by=None, moderation_reason='',
        sender_archived=False, recipient_archived=False,
        sender_deleted_at=False, recipient_deleted_at=False):
        "Check a bunch of properties of a message."

        self.assertEqual(m.is_pending(), status==STATUS_PENDING)
        self.assertEqual(m.is_rejected(), status==STATUS_REJECTED)
        self.assertEqual(m.is_accepted(), status==STATUS_ACCEPTED)
        self.assertEqual(m.is_new, is_new)
        self.assertEqual(m.is_replied, is_replied)
        self.check_now(m.sent_at)
        self.assertEqual(m.parent, parent)
        self.assertEqual(m.thread, thread)
        self.assertEqual(m.sender_archived, sender_archived)
        self.assertEqual(m.recipient_archived, recipient_archived)
        if sender_deleted_at:
            if isinstance(sender_deleted_at, datetime):
                self.assertEqual(m.sender_deleted_at, sender_deleted_at)
            else:
                self.assertNotEquals(m.sender_deleted_at, None)
        else:
            self.assertEqual(m.sender_deleted_at, None)
        if recipient_deleted_at:
            if isinstance(recipient_deleted_at, datetime):
                self.assertEqual(m.recipient_deleted_at, recipient_deleted_at)
            else:
                self.assertNotEquals(m.recipient_deleted_at, None)
        else:
            self.assertEqual(m.recipient_deleted_at, None)
        if moderation_date:
            if isinstance(moderation_date, datetime):
                self.assertEqual(m.moderation_date, moderation_date)
            else:
                self.assertNotEquals(m.moderation_date, None)
        else:
            self.assertEqual(m.moderation_date, None)
        self.assertEqual(m.moderation_by, moderation_by)
        self.assertEqual(m.moderation_reason, moderation_reason)

    def create(self, moderation_status=None, *args, **kwargs):
        "Create a message."
        # need to sleep between creations
        # otherwise some sent_at datetimes are equal and ordering predictions are disturbed
        sleep(0.03)
        if moderation_status:
            kwargs.update(moderation_status=moderation_status)
        return Message.objects.create(subject='s', *args, **kwargs)

    def create_accepted(self, moderation_status=STATUS_ACCEPTED, *args, **kwargs):
        "Create a message as 'accepted'."
        return self.create(moderation_status=moderation_status, *args, **kwargs)

    # set of message creations
    def c12(self, *args, **kwargs):
        return self.create_accepted(sender=self.user1, recipient=self.user2, *args, **kwargs)
    def c13(self, *args, **kwargs):
        return self.create_accepted(sender=self.user1, recipient=self.user3, *args, **kwargs)
    def c21(self, *args, **kwargs):
        return self.create_accepted(sender=self.user2, recipient=self.user1, *args, **kwargs)
    def c23(self, *args, **kwargs):
        return self.create_accepted(sender=self.user2, recipient=self.user3, *args, **kwargs)
    def c32(self, *args, **kwargs):
        return self.create_accepted(sender=self.user3, recipient=self.user2, *args, **kwargs)

    def reload_modules(self):
        "Reload some modules after a change in settings."
        clear_url_caches()
        try:
            reload(sys.modules['postman.forms'])
            reload(sys.modules['postman.views'])
            reload(sys.modules['postman.urls'])
        except KeyError: # happens once at the setUp
            pass
        reload(get_resolver(get_urlconf()).urlconf_module)
    
class ViewTest(BaseTest):
    """
    Test the views.
    """
    def test_home(self):
        response = self.client.get('/messages/')
        self.assertRedirects(response, reverse('postman_inbox'), status_code=301, target_status_code=302)

    def check_folder(self, folder):
        url = reverse('postman_' + folder, args=[OPTION_MESSAGES])
        template = "postman/{0}.html".format(folder)
        # anonymous
        response = self.client.get(url)
        self.assertRedirects(response, "{0}?{1}={2}".format(settings.LOGIN_URL, REDIRECT_FIELD_NAME, url))
        # authenticated
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)
        url = reverse('postman_' + folder)
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)

    def test_inbox(self):
        self.check_folder('inbox')

    def test_sent(self):
        self.check_folder('sent')

    def test_archives(self):
        self.check_folder('archives')

    def test_trash(self):
        self.check_folder('trash')

    def check_template(self, action, args):
        # don't want to bother with additional templates; test only the parameter passing
        url = reverse('postman_' + action + '_template', args=args)
        self.assertRaises(TemplateDoesNotExist, self.client.get, url)

    def test_template(self):
        "Test the 'template_name' parameter."
        m1 = self.c12()
        m1.read_at, m1.thread = datetime.now(), m1
        m2 = self.c21(parent=m1, thread=m1.thread)
        m1.replied_at = m2.sent_at; m1.save()
        self.assert_(self.client.login(username='foo', password='pass'))
        for actions, args in [
            (('inbox', 'sent', 'archives', 'trash', 'write'), []),
            (('view', 'view_conversation'), [1]),
            (('reply',), [2]),
        ]:
            for action in actions:
                self.check_template(action, args)

    def test_write_authentication(self):
        "Test permission and what template & form are used."
        url = reverse('postman_write')
        template = "postman/write.html"
        # anonymous is allowed
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)
        from postman.forms import AnonymousWriteForm
        self.assert_(isinstance(response.context['form'], AnonymousWriteForm))
        # anonymous is not allowed
        settings.POSTMAN_DISALLOW_ANONYMOUS = True
        self.reload_modules()
        response = self.client.get(url)
        self.assertRedirects(response, "{0}?{1}={2}".format(settings.LOGIN_URL, REDIRECT_FIELD_NAME, url))
        # authenticated
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)
        from postman.forms import WriteForm
        self.assert_(isinstance(response.context['form'], WriteForm))

    def test_write_recipient(self):
        "Test the passing of recipient names in URL."
        template = "postman/write.html"

        url = reverse('postman_write', args=['foo'])
        response = self.client.get(url)
        self.assertContains(response, 'value="foo"')

        url = reverse('postman_write', args=['foo:bar'])
        response = self.client.get(url)
        self.assertContains(response, 'value="bar, foo"')

        url = reverse('postman_write', args=[':foo::intruder:bar:a-b+c@d.com:foo:'])
        response = self.client.get(url)
        self.assertContains(response, 'value="bar, foo"')

    def test_write_auto_complete(self):
        "Test the 'autocomplete_channels' parameter."
        url = reverse('postman_write_auto_complete')
        # anonymous
        response = self.client.get(url)
        f = response.context['form'].fields['recipients']
        if hasattr(f, 'channel'): # app may not be in INSTALLED_APPS
            self.assertEqual(f.channel, 'postman_single')
        # authenticated
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        f = response.context['form'].fields['recipients']
        if hasattr(f, 'channel'):
            self.assertEqual(f.channel, 'postman_multiple')

    def check_init_by_query_string(self, action, args=[]):
        template = "postman/{0}.html".format(action)
        url = reverse('postman_' + action, args=args)
        response = self.client.get(url + '?subject=that%20is%20the%20subject')
        self.assertContains(response, 'value="that is the subject"')
        response = self.client.get(url + '?body=this%20is%20my%20body')
        self.assertContains(response, 'name="body">this is my body')

    def test_write_querystring(self):
        "Test the prefilling by query string."
        self.check_init_by_query_string('write')

    def check_message(self, m, is_anonymous=False, subject='s', body='b', recipient_username='bar'):
        "Check some message properties, status, and that no mail is sent."
        self.assertEqual(m.subject, subject)
        self.assertEqual(m.body, body)
        self.assertEqual(m.email, 'a@b.com' if is_anonymous else '')
        self.assertEqual(m.sender, self.user1 if not is_anonymous else None)
        self.assertEqual(m.recipient.username, recipient_username)
        if is_anonymous:
            self.check_status(m, sender_deleted_at=True)
        self.assertEqual(len(mail.outbox), 0)

    def check_write_post(self, extra={}, is_anonymous=False):
        "Check message generation, redirection, and mandatory fields."
        url = reverse('postman_write')
        url_with_success_url = reverse('postman_write_with_success_url_to_sent')
        data = {'recipients': self.user2.username, 'subject': 's', 'body': 'b'}
        data.update(extra)
        # default redirect is to the requestor page
        response = self.client.post(url, data, HTTP_REFERER=url)
        self.assertRedirects(response, url)
        self.check_message(Message.objects.get(pk=1), is_anonymous)
        # fallback redirect is to inbox. So redirect again when login is required
        response = self.client.post(url, data)
        self.assertRedirects(response, reverse('postman_inbox'), target_status_code=302 if is_anonymous else 200)
        self.check_message(Message.objects.get(pk=2), is_anonymous)
        # redirect url may be superseded
        response = self.client.post(url_with_success_url, data, HTTP_REFERER=url)
        self.assertRedirects(response, reverse('postman_sent'), target_status_code=302 if is_anonymous else 200)
        self.check_message(Message.objects.get(pk=3), is_anonymous)
        # query string has highest precedence
        response = self.client.post(url_with_success_url + '?next=' + url, data, HTTP_REFERER='does not matter')
        self.assertRedirects(response, url)
        self.check_message(Message.objects.get(pk=4), is_anonymous)

        for f in data.keys():
            if f in ('body',): continue
            d = data.copy()
            del d[f]
            response = self.client.post(url, d, HTTP_REFERER=url)
            self.assertFormError(response, 'form', f, 'This field is required.')

    def test_write_post_anonymous(self):
        self.check_write_post({'email': 'a@b.com'}, is_anonymous=True)

    def test_write_post_authenticated(self):
        self.assert_(self.client.login(username='foo', password='pass'))
        self.check_write_post()

    def test_write_post_multirecipient(self):
        "Test number of recipients constraint."
        url = reverse('postman_write')
        data = {
            'email': 'a@b.com', 'subject': 's', 'body': 'b',
            'recipients': '{0}, {1}'.format(self.user2.username, self.user3.username)}
        # anonymous
        response = self.client.post(url, data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', CommaSeparatedUserField.default_error_messages['max'].format(limit_value=1, show_value=2))
        # authenticated
        self.assert_(self.client.login(username='foo', password='pass'))
        del data['email']
        response = self.client.post(url, data, HTTP_REFERER=url)
        self.assertRedirects(response, url)
        self.check_message(Message.objects.get(pk=1))
        self.check_message(Message.objects.get(pk=2), recipient_username='baz')

        url_with_max = reverse('postman_write_with_max')
        response = self.client.post(url_with_max, data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', CommaSeparatedUserField.default_error_messages['max'].format(limit_value=1, show_value=2))

        settings.POSTMAN_DISALLOW_MULTIRECIPIENTS = True
        response = self.client.post(url, data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', CommaSeparatedUserField.default_error_messages['max'].format(limit_value=1, show_value=2))

    def test_write_post_filters(self):
        "Test user- and exchange- filters."
        url = reverse('postman_write')
        data = {
            'subject': 's', 'body': 'b',
            'recipients': '{0}, {1}'.format(self.user2.username, self.user3.username)}
        self.assert_(self.client.login(username='foo', password='pass'))

        response = self.client.post(reverse('postman_write_with_user_filter_reason'), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Some usernames are rejected: bar (some reason).")

        response = self.client.post(reverse('postman_write_with_user_filter_no_reason'), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Some usernames are rejected: bar, baz.")

        response = self.client.post(reverse('postman_write_with_user_filter_false'), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Some usernames are rejected: bar, baz.")

        response = self.client.post(reverse('postman_write_with_user_filter_exception'), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', ['first good reason',"anyway, I don't like bar"])

        response = self.client.post(reverse('postman_write_with_exch_filter_reason'), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Writing to some users is not possible: bar (some reason).")

        response = self.client.post(reverse('postman_write_with_exch_filter_no_reason'), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Writing to some users is not possible: bar, baz.")

        response = self.client.post(reverse('postman_write_with_exch_filter_false'), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Writing to some users is not possible: bar, baz.")

        response = self.client.post(reverse('postman_write_with_exch_filter_exception'), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', ['first good reason',"anyway, I don't like bar"])

    def test_write_post_moderate(self):
        "Test 'auto_moderators' parameter."
        url = reverse('postman_write')
        data = {'subject': 's', 'body': 'b', 'recipients': self.user2.username}
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.post(reverse('postman_write_moderate'), data, HTTP_REFERER=url)
        self.assertRedirects(response, url)
        self.check_status(Message.objects.get(pk=1), status=STATUS_REJECTED, recipient_deleted_at=True,
            moderation_date=True, moderation_reason="some reason")

    def test_reply_authentication(self):
        "Test permission and what template & form are used."
        template = "postman/reply.html"
        self.c21(body="this is my body")
        url = reverse('postman_reply', args=[1])
        # anonymous
        response = self.client.get(url)
        self.assertRedirects(response, "{0}?{1}={2}".format(settings.LOGIN_URL, REDIRECT_FIELD_NAME, url))
        # authenticated
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)
        from postman.forms import FullReplyForm
        self.assert_(isinstance(response.context['form'], FullReplyForm))
        self.assertContains(response, 'value="Re: s"')
        self.assertContains(response, 'name="body">\n\nbar wrote:\n&gt; this is my body')
        self.assertEqual(response.context['recipient'], 'bar')

    def test_reply_formatters(self):
        "Test the 'formatters' parameter."
        template = "postman/reply.html"
        self.c21(body="this is my body")
        url = reverse('postman_reply_formatters', args=[1])
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)
        self.assertContains(response, 'value="Re_ s"')
        self.assertContains(response, 'name="body">bar _ this is my body')

    def test_reply_auto_complete(self):
        "Test the 'autocomplete_channel' parameter."
        self.c21()
        url = reverse('postman_reply_auto_complete', args=[1])
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        f = response.context['form'].fields['recipients']
        if hasattr(f, 'channel'):
            self.assertEqual(f.channel, 'postman_multiple')

    def check_404(self, view_name, pk):
        "Return is a 404 page."
        url = reverse(view_name, args=[pk])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

    def check_reply_404(self, pk):
        self.check_404('postman_reply', pk)

    def test_reply_id(self):
        "Test all sort of failures."
        self.assert_(self.client.login(username='foo', password='pass'))
        # invalid message id
        self.check_reply_404(1000)
        # existent message but you are the sender, not the recipient
        self.check_reply_404(Message.objects.get(pk=self.c12().pk).pk) # create & verify really there
        # existent message but not yours at all
        self.check_reply_404(Message.objects.get(pk=self.c23().pk).pk)
        # existent message but not yet visible to you
        self.check_reply_404(Message.objects.get(pk=self.create(sender=self.user2, recipient=self.user1).pk).pk)
        # cannot reply to a deleted message
        self.check_reply_404(Message.objects.get(pk=self.c21(recipient_deleted_at=datetime.now()).pk).pk)

    def test_reply_querystring(self):
        "Test the prefilling by query string."
        self.assert_(self.client.login(username='foo', password='pass'))
        self.c21()
        self.check_init_by_query_string('reply', [1])

    def test_reply_post(self):
        "Test message generation and redirection."
        self.c21()
        url = reverse('postman_reply', args=[1])
        url_with_success_url = reverse('postman_reply_with_success_url_to_sent', args=[1])
        data = {'subject': 's', 'body': 'b'}
        self.assert_(self.client.login(username='foo', password='pass'))
        # default redirect is to the requestor page
        response = self.client.post(url, data, HTTP_REFERER=url)
        self.assertRedirects(response, url)
        self.check_message(Message.objects.get(pk=2))
        # fallback redirect is to inbox
        response = self.client.post(url, data)
        self.assertRedirects(response, reverse('postman_inbox'))
        self.check_message(Message.objects.get(pk=3))
        # redirect url may be superseded
        response = self.client.post(url_with_success_url, data, HTTP_REFERER=url)
        self.assertRedirects(response, reverse('postman_sent'))
        self.check_message(Message.objects.get(pk=4))
        # query string has highest precedence
        response = self.client.post(url_with_success_url + '?next=' + url, data, HTTP_REFERER='does not matter')
        self.assertRedirects(response, url)
        self.check_message(Message.objects.get(pk=5))
        # missing subject is valid, as in quick reply
        response = self.client.post(url, {}, HTTP_REFERER=url)
        self.assertRedirects(response, url)
        self.check_message(Message.objects.get(pk=6), subject='Re: s', body='')

    def test_reply_post_copies(self):
        "Test number of recipients constraint."
        self.c21()
        url = reverse('postman_reply', args=[1])
        data = {'subject': 's', 'body': 'b', 'recipients': self.user3.username}
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.post(url, data, HTTP_REFERER=url)
        self.assertRedirects(response, url)
        self.check_message(Message.objects.get(pk=2))
        self.check_message(Message.objects.get(pk=3), recipient_username='baz')

        url_with_max = reverse('postman_reply_with_max', args=[1])
        data.update(recipients='{0}, {1}'.format(self.user2.username, self.user3.username))
        response = self.client.post(url_with_max, data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', CommaSeparatedUserField.default_error_messages['max'].format(limit_value=1, show_value=2))

        settings.POSTMAN_DISALLOW_COPIES_ON_REPLY = True
        self.reload_modules()
        response = self.client.post(url, data, HTTP_REFERER=url)
        self.assertRedirects(response, url)
        self.check_message(Message.objects.get(pk=4))
        self.assertRaises(Message.DoesNotExist, Message.objects.get, pk=5)

    def test_reply_post_filters(self):
        "Test user- and exchange- filters."
        self.c21()
        url = reverse('postman_reply', args=[1])
        data = {'subject': 's', 'body': 'b', 'recipients': '{0}, {1}'.format(self.user2.username, self.user3.username)}
        self.assert_(self.client.login(username='foo', password='pass'))

        response = self.client.post(reverse('postman_reply_with_user_filter_reason', args=[1]), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Some usernames are rejected: bar (some reason).")

        response = self.client.post(reverse('postman_reply_with_user_filter_no_reason', args=[1]), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Some usernames are rejected: bar, baz.")

        response = self.client.post(reverse('postman_reply_with_user_filter_false', args=[1]), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Some usernames are rejected: bar, baz.")

        response = self.client.post(reverse('postman_reply_with_user_filter_exception', args=[1]), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', ['first good reason',"anyway, I don't like bar"])

        response = self.client.post(reverse('postman_reply_with_exch_filter_reason', args=[1]), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Writing to some users is not possible: bar (some reason).")

        response = self.client.post(reverse('postman_reply_with_exch_filter_no_reason', args=[1]), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Writing to some users is not possible: bar, baz.")

        response = self.client.post(reverse('postman_reply_with_exch_filter_false', args=[1]), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', "Writing to some users is not possible: bar, baz.")

        response = self.client.post(reverse('postman_reply_with_exch_filter_exception', args=[1]), data, HTTP_REFERER=url)
        self.assertFormError(response, 'form', 'recipients', ['first good reason',"anyway, I don't like bar"])

    def test_reply_post_moderate(self):
        "Test 'auto_moderators' parameter."
        m = self.c21()
        url = reverse('postman_reply', args=[1])
        data = {'subject': 's', 'body': 'b'}
        self.assert_(self.client.login(username='foo', password='pass'))

        response = self.client.post(reverse('postman_reply_moderate', args=[1]), data, HTTP_REFERER=url)
        self.assertRedirects(response, url)
        self.check_status(Message.objects.get(pk=2), status=STATUS_REJECTED, recipient_deleted_at=True,
            parent=m, thread=m,
            moderation_date=True, moderation_reason="some reason")

    def test_view_authentication(self):
        "Test permission, what template and form are used, set-as-read."
        template = "postman/view.html"
        self.c12()
        self.c21()
        url = reverse('postman_view', args=[1])
        # anonymous
        response = self.client.get(url)
        self.assertRedirects(response, "{0}?{1}={2}".format(settings.LOGIN_URL, REDIRECT_FIELD_NAME, url))
        # authenticated
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)
        self.assertFalse(response.context['archived'])
        self.assert_(response.context['reply_to_pk'] is None)
        self.assert_(response.context['form'] is None)
        self.check_status(Message.objects.get(pk=1), status=STATUS_ACCEPTED)

        url = reverse('postman_view', args=[2])
        response = self.client.get(url)
        self.assertFalse(response.context['archived'])
        self.assertEqual(response.context['reply_to_pk'], 2)
        from postman.forms import QuickReplyForm
        self.assert_(isinstance(response.context['form'], QuickReplyForm))
        self.check_status(Message.objects.get(pk=2), status=STATUS_ACCEPTED, is_new=False)

    def test_view_formatters(self):
        "Test the 'formatters' parameter."
        template = "postman/view.html"
        self.c21(body="this is my body")
        url = reverse('postman_view_formatters', args=[1])
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)
        self.assertNotContains(response, 'value="Re_ s"')
        self.assertContains(response, 'name="body">bar _ this is my body')

    def check_view_404(self, pk):
        self.check_404('postman_view', pk)

    def test_view_id(self):
        "Test all sort of failures."
        self.assert_(self.client.login(username='foo', password='pass'))
        # invalid message id
        self.check_view_404(1000)
        # existent message but not yours
        self.check_view_404(Message.objects.get(pk=self.c23().pk).pk) # create & verify really there
        # existent message but not yet visible to you
        self.check_view_404(Message.objects.get(pk=self.create(sender=self.user2, recipient=self.user1).pk).pk)

    def test_view_conversation_authentication(self):
        "Test permission, what template and form are used, number of messages in the conversation, set-as-read."
        template = "postman/view.html"
        m1 = self.c12()
        m1.read_at, m1.thread = datetime.now(), m1
        m2 = self.c21(parent=m1, thread=m1.thread)
        m1.replied_at = m2.sent_at; m1.save()
        url = reverse('postman_view_conversation', args=[1])
        self.check_status(Message.objects.get(pk=1), status=STATUS_ACCEPTED, is_new=False, is_replied=True, thread=m1)
        # anonymous
        response = self.client.get(url)
        self.assertRedirects(response, "{0}?{1}={2}".format(settings.LOGIN_URL, REDIRECT_FIELD_NAME, url))
        # authenticated
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        self.assertTemplateUsed(response, template)
        self.assertFalse(response.context['archived'])
        self.assertEqual(response.context['reply_to_pk'], 2)
        from postman.forms import QuickReplyForm
        self.assert_(isinstance(response.context['form'], QuickReplyForm))
        self.assertEqual(len(response.context['pm_messages']), 2)
        self.check_status(Message.objects.get(pk=2), status=STATUS_ACCEPTED, is_new=False, parent=m1, thread=m1)

    def check_view_conversation_404(self, thread_id):
        self.check_404('postman_view_conversation', thread_id)

    def test_view_conversation_id(self):
        "Test all sort of failures."
        self.assert_(self.client.login(username='foo', password='pass'))
        # invalid conversation id
        self.check_view_conversation_404(1000)
        # existent conversation but not yours
        m1 = self.c23()
        m1.read_at, m1.thread = datetime.now(), m1
        m2 = self.c32(parent=m1, thread=m1.thread)
        m1.replied_at = m2.sent_at; m1.save()
        self.check_view_conversation_404(m1.thread_id)

    def test_view_conversation(self):
        "Test message visibility."
        m1 = self.c12()
        m1.read_at, m1.thread = datetime.now(), m1
        m1.save()
        m2 = self.create(sender=self.user2, recipient=self.user1, parent=m1, thread=m1.thread)
        url = reverse('postman_view_conversation', args=[1])
        self.check_status(Message.objects.get(pk=1), status=STATUS_ACCEPTED, is_new=False, thread=m1)
        # existent response but not yet visible to you
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.get(url)
        self.assertEqual(len(response.context['pm_messages']), 1)
        self.check_status(Message.objects.get(pk=2), parent=m1, thread=m1)
        # complete view on the other side
        self.assert_(self.client.login(username='bar', password='pass'))
        response = self.client.get(url)
        self.assertEqual(len(response.context['pm_messages']), 2)

    def check_update(self, view_name, field_bit, field_value=None):
        "Check permission, redirection, field updates, invalid cases."
        url = reverse(view_name)
        url_with_success_url = reverse(view_name + '_with_success_url_to_archives')
        data = {'pks': ('1', '2', '3')}
        # anonymous
        response = self.client.post(url, data)
        self.assertRedirects(response, "{0}?{1}={2}".format(settings.LOGIN_URL, REDIRECT_FIELD_NAME, url))
        # authenticated
        self.assert_(self.client.login(username='foo', password='pass'))
        # default redirect is to the requestor page
        redirect_url = reverse('postman_sent')
        response = self.client.post(url, data, HTTP_REFERER=redirect_url)
        self.assertRedirects(response, redirect_url)
        sender_kw = 'sender_{0}'.format(field_bit)
        recipient_kw = 'recipient_{0}'.format(field_bit)
        self.check_status(Message.objects.get(pk=1), status=STATUS_ACCEPTED, **{sender_kw: field_value})
        self.check_status(Message.objects.get(pk=2), status=STATUS_ACCEPTED, **{recipient_kw: field_value})
        self.check_status(Message.objects.get(pk=3), status=STATUS_ACCEPTED, **{sender_kw: field_value})
        self.check_status(Message.objects.get(pk=4), status=STATUS_ACCEPTED)
        # fallback redirect is to inbox
        response = self.client.post(url, data) # doesn't hurt if already archived|deleted|undeleted
        self.assertRedirects(response, reverse('postman_inbox'))
        # redirect url may be superseded
        response = self.client.post(url_with_success_url, data, HTTP_REFERER=redirect_url)
        self.assertRedirects(response, reverse('postman_archives'))
        # query string has highest precedence
        response = self.client.post(url_with_success_url + '?next=' + redirect_url, data, HTTP_REFERER='does not matter')
        self.assertRedirects(response, redirect_url)
        # missing payload
        response = self.client.post(url)
        self.assertRedirects(response, reverse('postman_inbox'))

        # not a POST
        response = self.client.get(url, data)
        self.assertEqual(response.status_code, 404)
        # not yours
        self.assert_(self.client.login(username='baz', password='pass'))
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, 404)

    def check_update_conversation(self, view_name, root_msg, field_bit, field_value=None):
        "Check redirection, field updates, invalid cases."
        url = reverse(view_name)
        data = {'tpks': '1'}
        self.assert_(self.client.login(username='foo', password='pass'))
        response = self.client.post(url, data)
        self.assertRedirects(response, reverse('postman_inbox'))
        sender_kw = 'sender_{0}'.format(field_bit)
        recipient_kw = 'recipient_{0}'.format(field_bit)
        self.check_status(Message.objects.get(pk=1), status=STATUS_ACCEPTED, is_new=False, is_replied=True, thread=root_msg, **{sender_kw: field_value})
        self.check_status(Message.objects.get(pk=2), status=STATUS_ACCEPTED, parent=root_msg, thread=root_msg, **{recipient_kw: field_value})
        # missing payload
        response = self.client.post(url)
        self.assertRedirects(response, reverse('postman_inbox'))

        # not a POST
        response = self.client.get(url, data)
        self.assertEqual(response.status_code, 404)
        # not yours
        self.assert_(self.client.login(username='baz', password='pass'))
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, 404)

    def test_archive(self):
        "Test archive action on messages."
        self.c12()
        self.c21()
        self.c12()
        self.c13()
        self.check_update('postman_archive', 'archived', True)

    def test_archive_conversation(self):
        "Test archive action on conversations."
        m1 = self.c12()
        m1.read_at, m1.thread = datetime.now(), m1
        m2 = self.c21(parent=m1, thread=m1.thread)
        m1.replied_at = m2.sent_at; m1.save()
        self.check_update_conversation('postman_archive', m1, 'archived', True)

    def test_delete(self):
        "Test delete action on messages."
        self.c12()
        self.c21()
        self.c12()
        self.c13()
        self.check_update('postman_delete', 'deleted_at', True)

    def test_delete_conversation(self):
        "Test delete action on conversations."
        m1 = self.c12()
        m1.read_at, m1.thread = datetime.now(), m1
        m2 = self.c21(parent=m1, thread=m1.thread)
        m1.replied_at = m2.sent_at; m1.save()
        self.check_update_conversation('postman_delete', m1, 'deleted_at', True)

    def test_undelete(self):
        "Test undelete action on messages."
        self.c12(sender_deleted_at=datetime.now())
        self.c21(recipient_deleted_at=datetime.now())
        self.c12(sender_deleted_at=datetime.now())
        self.c13()
        self.check_update('postman_undelete', 'deleted_at')

    def test_undelete_conversation(self):
        "Test undelete action on conversations."
        m1 = self.c12(sender_deleted_at=datetime.now())
        m1.read_at, m1.thread = datetime.now(), m1
        m2 = self.c21(parent=m1, thread=m1.thread, recipient_deleted_at=datetime.now())
        m1.replied_at = m2.sent_at; m1.save()
        self.check_update_conversation('postman_undelete', m1, 'deleted_at')

class FieldTest(BaseTest):
    """
    Test the CommaSeparatedUserField.
    """
    def test_label(self):
        "Test the plural/singular of the label."
        f = CommaSeparatedUserField(label=('plural','singular'))
        self.assertEqual(f.label, 'plural')
        f.set_max(1)
        self.assertEqual(f.label, 'singular')

        f = CommaSeparatedUserField(label=('plural','singular'), max=1)
        self.assertEqual(f.label, 'singular')
        f.set_max(2)
        self.assertEqual(f.label, 'plural')

        f = CommaSeparatedUserField(label=('plural','singular'), max=2)
        self.assertEqual(f.label, 'plural')
        f.set_max(1)
        self.assertEqual(f.label, 'singular')

    def test_to_python(self):
        "Test the conversion to a python list."
        f = CommaSeparatedUserField()
        self.assertEqual(f.to_python(''), [])
        self.assertEqual(f.to_python('foo'), ['foo'])
        self.assertEqual(frozenset(f.to_python('foo, bar')), frozenset(['foo', 'bar']))
        self.assertEqual(frozenset(f.to_python('foo, bar,baz')), frozenset(['foo', 'bar', 'baz']))
        self.assertEqual(f.to_python(' foo , foo '), ['foo'])
        self.assertEqual(frozenset(f.to_python('foo,, bar,')), frozenset(['foo', 'bar']))
        self.assertEqual(frozenset(f.to_python(',foo, \t , bar')), frozenset(['foo', 'bar']))

    def test_clean(self):
        "Test the 'clean' validation."
        f = CommaSeparatedUserField(required=False)
        self.assertEqual(f.clean(''), [])
        self.assertEqual(f.clean('foo'), [self.user1])
        self.assertEqual(frozenset(f.clean('foo, bar')), frozenset([self.user1, self.user2]))
        # 'intruder' is not a username
        self.assertRaises(ValidationError, f.clean, 'foo, intruder, bar')
        # only active users are considered
        self.user1.is_active = False
        self.user1.save()
        self.assertRaises(ValidationError, f.clean, 'foo, bar')

    def test_user_filter(self):
        "Test the 'user_filter' argument."
        f = CommaSeparatedUserField(user_filter=lambda u: None)
        self.assertEqual(frozenset(f.clean('foo, bar')), frozenset([self.user1, self.user2]))
        # no reason
        f = CommaSeparatedUserField(user_filter=lambda u: '' if u == self.user1 else None)
        self.assertRaises(ValidationError, f.clean, 'foo, bar')
        # with reason
        f = CommaSeparatedUserField(user_filter=lambda u: 'some reason' if u == self.user1 else None)
        self.assertRaises(ValidationError, f.clean, 'foo, bar')

    def test_min(self):
        "Test the 'min' argument."
        f = CommaSeparatedUserField(required=False, min=1)
        self.assertEqual(f.clean(''), [])

        f = CommaSeparatedUserField(min=1)
        self.assertEqual(f.clean('foo'), [self.user1])

        f = CommaSeparatedUserField(min=2)
        self.assertEqual(frozenset(f.clean('foo, bar')), frozenset([self.user1, self.user2]))
        self.assertRaises(ValidationError, f.clean, 'foo')

    def test_max(self):
        "Test the 'max' argument."
        f = CommaSeparatedUserField(max=1)
        self.assertEqual(f.clean('foo'), [self.user1])
        self.assertRaises(ValidationError, f.clean, 'foo, bar')

class MessageManagerTest(BaseTest):
    """
    Test the Message manager.
    """
    def test_num_queries(self):
        "Test the number of queries."
        # not available in django v1.2.3
        if not hasattr(self, 'assertNumQueries'):
            return
        self.c12()
        self.c21()
        self.c12(sender_archived=True, recipient_deleted_at=datetime.now())
        self.c21(sender_archived=True, recipient_deleted_at=datetime.now())
        for u in (self.user1, self.user2):
            with self.assertNumQueries(1):
                msgs = list(Message.objects.sent(u, option=OPTION_MESSAGES))
                user = msgs[0].recipient
            with self.assertNumQueries(1):
                msgs = list(Message.objects.inbox(u, option=OPTION_MESSAGES))
                user = msgs[0].sender
            with self.assertNumQueries(1):
                msgs = list(Message.objects.archives(u, option=OPTION_MESSAGES))
                user = msgs[0].sender
                user = msgs[0].recipient
            with self.assertNumQueries(1):
                msgs = list(Message.objects.trash(u, option=OPTION_MESSAGES))
                user = msgs[0].sender
                user = msgs[0].recipient
            with self.assertNumQueries(1):
                msgs = list(Message.objects.thread(u, Q(pk=1)))
                user = msgs[0].sender
                user = msgs[0].recipient

    def test(self):
        """
              user1       user2
        -----------       -----------  read repl
        arch del             arch del
                   ---...
                   ---X            x
                   ------>|             x    x
                  |<------|             x    x
                  |------>
                   ------>
                   ------>              x    
                   <------              
                    ...---
              x       X---
        """

        m1 = self.c12(moderation_status=STATUS_PENDING); 
        m2 = self.c12(moderation_status=STATUS_REJECTED, recipient_deleted_at=datetime.now())
        m3 = self.c12()
        m3.read_at, m3.thread = datetime.now(), m3
        m4 = self.c21(parent=m3, thread=m3.thread)
        m3.replied_at = m4.sent_at; m3.save()
        m4.read_at = datetime.now()
        m5 = self.c12(parent=m4, thread=m4.thread)
        m4.replied_at = m5.sent_at; m4.save()
        m6 = self.c12()
        m7 = self.c12()
        m7.read_at = datetime.now(); m7.save()
        m8 = self.c21()
        m9 = self.c21(moderation_status=STATUS_PENDING)
        m10 = self.c21(moderation_status=STATUS_REJECTED, recipient_deleted_at=datetime.now())

        def pk(x): return x.pk
        def pk_cnt(x): return (x.pk, x.count)
        self.assertEqual(Message.objects.count(), 10)
        self.assertEqual(Message.objects.inbox_unread_count(self.user1), 1)
        self.assertEqual(Message.objects.inbox_unread_count(self.user2), 2)
        self.assertEqual(self.user1.sent_messages.count(), 6)
        self.assertEqual(self.user1.received_messages.count(), 4)
        self.assertEqual(self.user2.sent_messages.count(), 4)
        self.assertEqual(self.user2.received_messages.count(), 6)
        self.assertEqual(set(m3.child_messages.all()), set([m3,m4,m5]))
        self.assertEqual(list(m3.next_messages.all()), [m4])
        self.assertEqual(m3.get_replies_count(), 1)
        self.assertEqual(list(m4.next_messages.all()), [m5])
        self.assertEqual(m4.get_replies_count(), 1)
        self.assertEqual(m5.get_replies_count(), 0)
        # by messages
        self.assertQuerysetEqual(Message.objects.sent(self.user1, option=OPTION_MESSAGES), [7,6,5,3,2,1], transform=pk)
        self.assertQuerysetEqual(Message.objects.sent(self.user2, option=OPTION_MESSAGES), [10,9,8,4], transform=pk)
        self.assertQuerysetEqual(Message.objects.inbox(self.user1, option=OPTION_MESSAGES), [8,4], transform=pk)
        self.assertQuerysetEqual(Message.objects.inbox(self.user2, option=OPTION_MESSAGES), [7,6,5,3], transform=pk)
        self.assertQuerysetEqual(Message.objects.archives(self.user1, option=OPTION_MESSAGES), [], transform=pk)
        self.assertQuerysetEqual(Message.objects.archives(self.user2, option=OPTION_MESSAGES), [], transform=pk)
        self.assertQuerysetEqual(Message.objects.trash(self.user1, option=OPTION_MESSAGES), [], transform=pk)
        self.assertQuerysetEqual(Message.objects.trash(self.user2, option=OPTION_MESSAGES), [], transform=pk)
        # by conversations
        self.assertQuerysetEqual(Message.objects.sent(self.user1), [(7,0),(6,0),(5,3),(2,0),(1,0)], transform=pk_cnt)
        self.assertQuerysetEqual(Message.objects.sent(self.user2), [(10,0),(9,0),(8,0),(4,3)], transform=pk_cnt)
        self.assertQuerysetEqual(Message.objects.inbox(self.user1), [(8,0),(4,3)], transform=pk_cnt)
        self.assertQuerysetEqual(Message.objects.inbox(self.user2), [(7,0),(6,0),(5,3)], transform=pk_cnt)

        self.assertQuerysetEqual(Message.objects.thread(self.user1, Q(thread=3)), [3,4,5], transform=pk)
        self.assertQuerysetEqual(Message.objects.thread(self.user1, Q(pk=4)), [4], transform=pk)
        self.assertQuerysetEqual(Message.objects.thread(self.user2, Q(thread=3)), [3,4,5], transform=pk)
        self.assertQuerysetEqual(Message.objects.thread(self.user2, Q(pk=4)), [4], transform=pk)
        # mark as archived and deleted
        """
              user1       user2
        -----------       -----------  read repl
        arch del             arch del
         X         ---...
              X    ---X            x
         X    X    ------>|             x    x
                  |<------|   X    X    x    x
                  |------>
         X         ------>    X
                   ------>         X    x    
              X    <------              
                    ...---         X
              x       X---    X
        """
        m1.sender_archived = True; m1.save()
        m2.sender_deleted_at = datetime.now(); m2.save()
        m3.sender_archived, m3.sender_deleted_at = True, datetime.now(); m3.save()
        m4.sender_archived, m4.sender_deleted_at = True, datetime.now(); m4.save()
        m6.sender_archived, m6.recipient_archived = True, True; m6.save()
        m7.recipient_deleted_at = datetime.now(); m7.save()
        m8.recipient_deleted_at = datetime.now(); m8.save()
        m9.sender_deleted_at = datetime.now(); m9.save()
        m10.sender_archived = True; m10.save()
        self.assertEqual(Message.objects.inbox_unread_count(self.user1), 0)
        self.assertEqual(Message.objects.inbox_unread_count(self.user2), 1)
        # by messages
        self.assertQuerysetEqual(Message.objects.archives(self.user1, option=OPTION_MESSAGES), [6,1], transform=pk)
        self.assertQuerysetEqual(Message.objects.archives(self.user2, option=OPTION_MESSAGES), [10,6], transform=pk)
        self.assertQuerysetEqual(Message.objects.trash(self.user1, option=OPTION_MESSAGES), [8,3,2], transform=pk)
        self.assertQuerysetEqual(Message.objects.trash(self.user2, option=OPTION_MESSAGES), [9,7,4], transform=pk)
        self.assertQuerysetEqual(Message.objects.sent(self.user1, option=OPTION_MESSAGES), [7,5], transform=pk)
        self.assertQuerysetEqual(Message.objects.sent(self.user2, option=OPTION_MESSAGES), [8], transform=pk)
        self.assertQuerysetEqual(Message.objects.inbox(self.user1, option=OPTION_MESSAGES), [4], transform=pk)
        self.assertQuerysetEqual(Message.objects.inbox(self.user2, option=OPTION_MESSAGES), [5,3], transform=pk)
        # by conversations
        self.assertQuerysetEqual(Message.objects.sent(self.user1), [(7,0),(5,3)], transform=pk_cnt)
        self.assertQuerysetEqual(Message.objects.sent(self.user2), [(8,0)], transform=pk_cnt)
        self.assertQuerysetEqual(Message.objects.inbox(self.user1), [(4,3)], transform=pk_cnt)
        self.assertQuerysetEqual(Message.objects.inbox(self.user2), [(5,3)], transform=pk_cnt)

        self.assertQuerysetEqual(Message.objects.thread(self.user1, Q(thread=3)), [3,4,5], transform=pk)
        self.assertQuerysetEqual(Message.objects.thread(self.user1, Q(pk=4)), [4], transform=pk)
        self.assertQuerysetEqual(Message.objects.thread(self.user2, Q(thread=3)), [3,4,5], transform=pk)
        self.assertQuerysetEqual(Message.objects.thread(self.user2, Q(pk=4)), [4], transform=pk)
        # mark as read
        self.assertEqual(Message.objects.set_read(self.user2, Q(thread=3)), 1)
        m = Message.objects.get(pk=5)
        self.check_status(m, status=STATUS_ACCEPTED, is_new=False, parent=m4, thread=m3)
        self.check_now(m.read_at)
        self.assertEqual(Message.objects.set_read(self.user2, Q(pk=6)), 1)
        m = Message.objects.get(pk=6)
        self.check_status(m, status=STATUS_ACCEPTED, is_new=False, sender_archived=True, recipient_archived=True)
        self.check_now(m.read_at)
        self.assertEqual(Message.objects.set_read(self.user1, Q(pk=8)), 1)
        m = Message.objects.get(pk=8)
        self.check_status(m, status=STATUS_ACCEPTED, is_new=False, recipient_deleted_at=True)
        self.check_now(m.read_at)

class MessageTest(BaseTest):
    """
    Test the Message model.
    """
    def check_parties(self, m, s=None, r=None, email=''):
        "Check party related properties."
        obfuscated_email_re = re.compile('^[0-9a-f]{4}..[0-9a-f]{4}@domain$')
        m.sender, m.recipient, m.email = s, r, email
        if s or email:
            m.clean()
        else:
            self.assertRaises(ValidationError, m.clean)
        self.assertEqual(m.admin_sender(), s.username if s else '<'+email+'>')
        self.assertEqual(m.clear_sender, m.admin_sender())
        if s:
            self.assertEqual(m.obfuscated_sender, s.username)
        elif email:
            self.assert_(obfuscated_email_re.match(m.obfuscated_sender))
        else:
            self.assertEqual(m.obfuscated_sender, '')
        self.assertEqual(m.admin_recipient(), r.username if r else '<'+email+'>')
        self.assertEqual(m.clear_recipient, m.admin_recipient())
        if r:
            self.assertEqual(m.obfuscated_recipient, r.username)
        elif email:
            self.assert_(obfuscated_email_re.match(m.obfuscated_recipient))
        else:
            self.assertEqual(m.obfuscated_recipient, '')

    def test_parties(self):
        "Test sender/recipient/email."
        m = Message()
        self.check_parties(m)
        self.check_parties(m, s=self.user1)
        self.check_parties(m, r=self.user2)
        self.check_parties(m, s=self.user1,                   r=self.user2)
        self.check_parties(m, s=self.user1, email=self.email              )
        self.check_parties(m,               email=self.email, r=self.user2)

    def test_status(self):
        "Test status."
        m = Message.objects.create(subject='s')
        self.check_status(m)
        m = Message.objects.create(subject='s', moderation_status=STATUS_REJECTED)
        self.check_status(m, status=STATUS_REJECTED)
        m = Message.objects.create(subject='s', moderation_status=STATUS_ACCEPTED)
        self.check_status(m, status=STATUS_ACCEPTED)
        m = Message.objects.create(subject='s', read_at=datetime.now())
        self.check_status(m, is_new=False)
        m = Message.objects.create(subject='s', replied_at=datetime.now())
        self.check_status(m, is_replied=True)

    def test_moderated_count(self):
        "Test 'moderated_messages' count."
        msg = Message.objects.create(subject='s', moderation_status=STATUS_ACCEPTED,
            moderation_date=datetime.now(), moderation_by=self.user1)
        msg.save()
        self.assertEqual(list(self.user1.moderated_messages.all()), [msg])

    def test_moderation_from_pending(self):
        "Test moderation management when leaving 'pending' status."
        msg = Message.objects.create(subject='s')
        # pending -> pending: nothing changes
        m = copy.copy(msg)
        m.clean_moderation(STATUS_PENDING, self.user1)
        self.check_status(m)
        # pending -> rejected
        m = copy.copy(msg)
        m.moderation_status = STATUS_REJECTED
        m.clean_moderation(STATUS_PENDING, self.user1) # one try with moderator
        self.check_status(m, status=STATUS_REJECTED,
            moderation_date=True, moderation_by=self.user1, recipient_deleted_at=True)
        self.check_now(m.moderation_date)
        self.check_now(m.recipient_deleted_at)
        # pending -> accepted
        m = copy.copy(msg)
        m.moderation_status = STATUS_ACCEPTED
        m.clean_moderation(STATUS_PENDING) # one try without moderator
        self.check_status(m, status=STATUS_ACCEPTED, moderation_date=True)
        self.check_now(m.moderation_date)

    def test_moderation_from_rejected(self):
        "Test moderation management when leaving 'rejected' status."
        date_in_past = datetime.now() - timedelta(days=2) # any value, just to avoid now()
        reason = 'some good reason'
        msg = Message.objects.create(subject='s', moderation_status=STATUS_REJECTED,
            moderation_date=date_in_past, moderation_by=self.user1, moderation_reason=reason,
            recipient_deleted_at=date_in_past)
        # rejected -> rejected: nothing changes
        m = copy.copy(msg)
        m.clean_moderation(STATUS_REJECTED, self.user2)
        self.check_status(m, status=STATUS_REJECTED,
            moderation_date=date_in_past, moderation_by=self.user1, moderation_reason=reason,
            recipient_deleted_at=date_in_past)
        # rejected -> pending
        m = copy.copy(msg)
        m.moderation_status = STATUS_PENDING
        m.clean_moderation(STATUS_REJECTED) # one try without moderator
        self.check_status(m, status=STATUS_PENDING,
            moderation_date=True, moderation_reason=reason, recipient_deleted_at=False)
        self.check_now(m.moderation_date)
        # rejected -> accepted
        m = copy.copy(msg)
        m.moderation_status = STATUS_ACCEPTED
        m.clean_moderation(STATUS_REJECTED, self.user2) # one try with moderator
        self.check_status(m, status=STATUS_ACCEPTED,
            moderation_date=True, moderation_by=self.user2, moderation_reason=reason,
            recipient_deleted_at=False)
        self.check_now(m.moderation_date)

    def test_moderation_from_accepted(self):
        "Test moderation management when leaving 'accepted' status."
        date_in_past = datetime.now() - timedelta(days=2) # any value, just to avoid now()
        msg = Message.objects.create(subject='s', moderation_status=STATUS_ACCEPTED,
            moderation_date=date_in_past, moderation_by=self.user1, recipient_deleted_at=date_in_past)
        # accepted -> accepted: nothing changes
        m = copy.copy(msg)
        m.clean_moderation(STATUS_ACCEPTED, self.user2)
        self.check_status(m, status=STATUS_ACCEPTED,
            moderation_date=date_in_past, moderation_by=self.user1, recipient_deleted_at=date_in_past)
        # accepted -> pending
        m = copy.copy(msg)
        m.moderation_status = STATUS_PENDING
        m.clean_moderation(STATUS_ACCEPTED, self.user2) # one try with moderator
        self.check_status(m, status=STATUS_PENDING,
            moderation_date=True, moderation_by=self.user2, recipient_deleted_at=date_in_past)
        self.check_now(m.moderation_date)
        # accepted -> rejected
        m = copy.copy(msg)
        m.moderation_status = STATUS_REJECTED
        m.clean_moderation(STATUS_ACCEPTED) # one try without moderator
        self.check_status(m, status=STATUS_REJECTED, moderation_date=True, recipient_deleted_at=True)
        self.check_now(m.moderation_date)
        self.check_now(m.recipient_deleted_at)

    def test_visitor(self):
        "Test clean_for_visitor()."
        date_in_past = datetime.now() - timedelta(days=2) # any value, just to avoid now()
        # as the sender
        m = Message.objects.create(subject='s', recipient=self.user1)
        m.clean_for_visitor()
        self.check_status(m, sender_deleted_at=True)
        self.check_now(m.sender_deleted_at)
        # as the recipient
        msg = Message.objects.create(subject='s', sender=self.user1)
        # pending
        m = copy.copy(msg)
        m.read_at=date_in_past
        m.recipient_deleted_at=date_in_past
        m.clean_for_visitor()
        self.check_status(m, recipient_deleted_at=False)
        # rejected
        m = copy.copy(msg)
        m.moderation_status = STATUS_REJECTED
        m.read_at=date_in_past
        m.recipient_deleted_at=date_in_past
        m.clean_for_visitor()
        self.check_status(m, status=STATUS_REJECTED, recipient_deleted_at=date_in_past)
        # accepted
        m = copy.copy(msg)
        m.moderation_status = STATUS_ACCEPTED
        m.clean_for_visitor()
        self.check_status(m, status=STATUS_ACCEPTED, is_new=False, recipient_deleted_at=True)
        self.check_now(m.read_at)
        self.check_now(m.recipient_deleted_at)

    def test_update_parent(self):
        "Test update_parent()."
        parent = Message.objects.create(subject='s', sender=self.user1, recipient=self.user2,
            moderation_status=STATUS_ACCEPTED)
        parent.thread = parent
        parent.save()
        # any previous rejected reply should not interfere
        rejected_reply = Message.objects.create(subject='s', sender=self.user2, recipient=self.user1,
            parent=parent, thread=parent.thread, moderation_status=STATUS_REJECTED)
        # any previous pending reply should not interfere
        pending_reply = Message.objects.create(subject='s', sender=self.user2, recipient=self.user1,
            parent=parent, thread=parent.thread, moderation_status=STATUS_PENDING)
        reply = Message.objects.create(subject='s', sender=self.user2, recipient=self.user1,
            parent=parent, thread=parent.thread)

        # the reply is accepted
        r = copy.deepcopy(reply)
        r.moderation_status = STATUS_ACCEPTED
        # accepted -> accepted: no change
        r.update_parent(STATUS_ACCEPTED)
        self.check_status(r.parent, status=STATUS_ACCEPTED, thread=parent)
        # pending -> accepted: parent is replied
        r.update_parent(STATUS_PENDING)
        p = Message.objects.get(pk=parent.pk) # better to ask the DB to check the save()
        self.check_status(p, status=STATUS_ACCEPTED, thread=parent, is_replied=True)
        self.assertEqual(p.replied_at, r.sent_at)
        # rejected -> accepted: same as pending -> accepted
        # so check here the acceptance of an anterior date
        # note: use again the some object for convenience but another reply is more realistic
        r.sent_at = r.sent_at - timedelta(days=1)
        r.update_parent(STATUS_REJECTED)
        p = Message.objects.get(pk=parent.pk)
        self.check_status(p, status=STATUS_ACCEPTED, thread=parent, is_replied=True)
        self.assertEqual(p.replied_at, r.sent_at)

        # a reply is withdrawn and no other reply
        r = copy.deepcopy(reply)
        r.parent.replied_at = r.sent_at
        r.moderation_status = STATUS_REJECTED # could be STATUS_PENDING
        # rejected -> rejected: no change. In real case, parent.replied_at would be already empty
        r.update_parent(STATUS_REJECTED)
        self.check_status(r.parent, status=STATUS_ACCEPTED, thread=parent, is_replied=True)
        # pending -> rejected: no change. In real case, parent.replied_at would be already empty
        r.update_parent(STATUS_PENDING)
        self.check_status(r.parent, status=STATUS_ACCEPTED, thread=parent, is_replied=True)
        # accepted -> rejected: parent is no more replied
        r.update_parent(STATUS_ACCEPTED)
        p = Message.objects.get(pk=parent.pk) 
        self.check_status(p, status=STATUS_ACCEPTED, thread=parent)
        # note: accepted -> rejected, with the existence of another suitable reply
        # is covered in the accepted -> pending case

        # a reply is withdrawn but there is another suitable reply
        other_reply = Message.objects.create(subject='s', sender=self.user2, recipient=self.user1,
            parent=parent, thread=parent.thread, moderation_status=STATUS_ACCEPTED)
        r = copy.deepcopy(reply)
        r.parent.replied_at = r.sent_at
        r.moderation_status = STATUS_PENDING # could be STATUS_REJECTED
        # pending -> pending: no change. In real case, parent.replied_at would be from another reply object
        r.update_parent(STATUS_PENDING)
        self.check_status(r.parent, status=STATUS_ACCEPTED, thread=parent, is_replied=True)
        # rejected -> pending: no change. In real case, parent.replied_at would be from another reply object 
        r.update_parent(STATUS_REJECTED)
        self.check_status(r.parent, status=STATUS_ACCEPTED, thread=parent, is_replied=True)
        # accepted -> pending: parent is still replied but by another object
        r.update_parent(STATUS_ACCEPTED)
        p = Message.objects.get(pk=parent.pk)
        self.check_status(p, status=STATUS_ACCEPTED, thread=parent, is_replied=True)
        self.assertEqual(p.replied_at, other_reply.sent_at)
        # note: accepted -> pending, with no other suitable reply
        # is covered in the accepted -> rejected case

    def check_notification(self, m, mail_number, email=None, notice_label=None):
        "Check number of mails, recipient, and notice creation."
        m.notify_users(STATUS_PENDING)
        self.assertEqual(len(mail.outbox), mail_number)
        if mail_number:
            self.assertEqual(mail.outbox[0].to, [email])
        if notification and notice_label:
            notice = notification.Notice.objects.get(pk=1)
            self.assertEqual(notice.notice_type.label, notice_label)

    def test_notification_rejection_visitor(self):
        "Test notify_users() for rejection, from a visitor."
        m = Message.objects.create(subject='s', moderation_status=STATUS_REJECTED, email=self.email, recipient=self.user2)
        self.check_notification(m, 1, self.email)

    def test_notification_rejection_user(self):
        "Test notify_users() for rejection, from a User."
        m = Message.objects.create(subject='s', moderation_status=STATUS_REJECTED, sender = self.user1, recipient=self.user2)
        self.check_notification(m, 1, self.user1.email, notice_label='postman_rejection')

    def test_notification_rejection_user_inactive(self):
        "Test notify_users() for rejection, from a User, but must be active."
        m = Message.objects.create(subject='s', moderation_status=STATUS_REJECTED, sender = self.user1, recipient=self.user2)
        self.user1.is_active = False
        self.check_notification(m, 0, notice_label='postman_rejection')

    def test_notification_acceptance_visitor(self):
        "Test notify_users() for acceptance, to a visitor."
        m = Message.objects.create(subject='s', moderation_status=STATUS_ACCEPTED, sender=self.user1, email=self.email)
        self.check_notification(m, 1, self.email)

    def test_notification_acceptance_user(self):
        "Test notify_users() for acceptance, to a User."
        m = Message.objects.create(subject='s', moderation_status=STATUS_ACCEPTED, sender=self.user1, recipient = self.user2)
        self.check_notification(m, 1, self.user2.email, notice_label='postman_message')

    def test_notification_acceptance_user_inactive(self):
        "Test notify_users() for acceptance, to a User, but must be active."
        m = Message.objects.create(subject='s', moderation_status=STATUS_ACCEPTED, sender=self.user1, recipient = self.user2)
        self.user2.is_active = False
        self.check_notification(m, 0, notice_label='postman_message')

    def test_notification_acceptance_reply(self):
        "Test notify_users() for acceptance, for a reply, to a User."
        p = Message.objects.create(subject='s', moderation_status=STATUS_ACCEPTED, sender=self.user2, recipient=self.user1)
        m = Message.objects.create(subject='s', moderation_status=STATUS_ACCEPTED, sender=self.user1, recipient=self.user2,
            parent=p, thread=p)
        self.check_notification(m, 1, self.user2.email, notice_label='postman_reply')

    def test_dates(self):
        "Test set_dates(), get_dates()."
        m = Message()
        set = datetime.now(), datetime.now(), datetime.now()
        m.set_dates(*set)
        get = m.get_dates()
        self.assertEqual(get, set)

    def test_moderation(self):
        "Test set_moderation(), get_moderation()."
        m = Message()
        set = STATUS_ACCEPTED, self.user1.pk, datetime.now(), 'some reason'
        m.set_moderation(*set)
        get = m.get_moderation()
        self.assertEqual(get, set)

    def check_auto_moderation(self, msg, seq, default):
        "Check auto-moderation results."
        for mod, result in seq:
            m = copy.copy(msg)
            m.auto_moderate(mod)
            changes = {}
            if result is True:
                changes['status'] = STATUS_ACCEPTED
            elif result is None:
                changes['status'] = default
            else:
                changes['status'] = STATUS_REJECTED
                changes['moderation_reason'] = result
            m.sent_at = datetime.now() # refresh, as we recycle the same base message
            self.check_status(m, **changes)

    def test_auto_moderation(self):
        "Test auto-moderation function combination."
        msg = Message.objects.create(subject='s')

        def moderate_as_none(m):              return None
        def moderate_as_true(m):              return True
        def moderate_as_false(m):             return False
        def moderate_as_0(m):                 return 0
        def moderate_as_100(m):               return 100
        def moderate_as_50(m):                return 50
        def moderate_as_49_default_reason(m): return 49
        moderate_as_49_default_reason.default_reason = 'moderate_as_49 default_reason'
        def moderate_as_49_with_reason(m):    return (49, 'moderate_as_49 with_reason')
        moderate_as_49_with_reason.default_reason = 'is not used'
        def moderate_as_1(m):                 return (1, 'moderate_as_1')
        def moderate_as_1_no_reason(m):       return (1, ' ')
        def moderate_as_2(m):                 return (2, 'moderate_as_2')
        def moderate_as_98(m):                return 98
        moderate_as_98.default_reason = 'useless; never used'
        def moderate_badly_as_negative(m):    return -1
        def moderate_badly_as_too_high(m):    return 101
        def moderate_as_0_with_reason(m):     return (0, 'moderate_as_0 with_reason')
        def invalid_moderator_1(m):           return (0, )
        def invalid_moderator_2(m):           return (0, 'reason', 'extra')

        for mod in [invalid_moderator_1, invalid_moderator_2]:
            m = copy.copy(msg)
            self.assertRaises(ValueError, m.auto_moderate, mod)

        seq = (
            # no moderator, no valid rating, or moderator is unable to state, default applies
            ([], None),
            (moderate_badly_as_negative, None),
            (moderate_badly_as_too_high, None),
            (moderate_as_none, None),
            # firm decision
            (moderate_as_false, ''),  (moderate_as_0, ''),
            (moderate_as_true, True), (moderate_as_100, True),
            # round to up
            (moderate_as_50, True),
            # reasons
            (moderate_as_49_default_reason, moderate_as_49_default_reason.default_reason),
            (moderate_as_49_with_reason, 'moderate_as_49 with_reason'),
            # priority is left to right
            ([moderate_as_none, moderate_as_false, moderate_as_true], ''),
            ([moderate_as_none, moderate_as_true, moderate_as_false], True),
            # keep only reasons for ratings below 50, non empty or whitespace
            ([moderate_as_1, moderate_as_98], 'moderate_as_1'),
            ([moderate_as_1, moderate_as_2, moderate_as_50], 'moderate_as_1, moderate_as_2'),
            ([moderate_as_1, moderate_as_1_no_reason, moderate_as_2], 'moderate_as_1, moderate_as_2'),
            # a firm reject imposes its reason
            ([moderate_as_1, moderate_as_2, moderate_as_50, moderate_as_0_with_reason], 'moderate_as_0 with_reason'),
            # neutral or invalid moderators do not count in the average
            ([moderate_as_50, moderate_as_none, moderate_badly_as_negative, moderate_badly_as_too_high], True),
        )
        # no default auto moderation
        # settings.POSTMAN_AUTO_MODERATE_AS = None
        self.check_auto_moderation(msg, seq, STATUS_PENDING)
        # default is: accepted
        settings.POSTMAN_AUTO_MODERATE_AS = True
        self.check_auto_moderation(msg, seq, STATUS_ACCEPTED)
        # default is: rejected
        settings.POSTMAN_AUTO_MODERATE_AS = False
        self.check_auto_moderation(msg, seq, STATUS_REJECTED)

class PendingMessageManagerTest(BaseTest):
    """
    Test the PendingMessage manager.
    """
    def test(self):
        msg1 = self.create()
        msg2 = self.create(moderation_status=STATUS_REJECTED)
        msg3 = self.create(moderation_status=STATUS_ACCEPTED)
        msg4 = self.create()
        self.assertQuerysetEqual(PendingMessage.objects.all(), [msg4.pk, msg1.pk], transform=lambda x: x.pk)

class PendingMessageTest(BaseTest):
    """
    Test the PendingMessage model.
    """
    def test(self):
        m = PendingMessage()
        self.assert_(m.is_pending())
        m.set_accepted()
        self.assert_(m.is_accepted())
        m.set_rejected()
        self.assert_(m.is_rejected())

from django.utils.encoding import force_unicode
from django.utils.formats import localize
class FiltersTest(BaseTest):
    """
    Test the filters.
    """
    def check_sub(self, x, y, value):
        t = Template("{% load postman_tags %}{% with "+x+"|sub:"+y+" as var %}{{ var }}{% endwith %}")
        self.assertEqual(t.render(Context({})), value)

    def test_sub(self):
        "Test '|sub'."
        self.check_sub('6', '2', '4')
        self.check_sub('6', "'X'", '6')
        self.check_sub("'X'", '2', 'X')

    def check_or_me(self, x, value, user=None):
        t = Template("{% load postman_tags %}{{ "+x+"|or_me:user }}") # do not load i18n to be able to check the untranslated pattern
        self.assertEqual(t.render(Context({'user': user or AnonymousUser()})), value)

    def test_or_me(self):
        "Test '|or_me'."
        self.check_or_me("'foo'", 'foo')
        self.check_or_me("'foo'", '&lt;me&gt;', self.user1)
        self.check_or_me("'bar'", 'bar', self.user1)

    def check_compact_date(self, date, value, format='H:i,d b,d/m/y'):
        # use 'H', 'd', 'm' instead of 'G', 'j', 'n' because no strftime equivalents
        t = Template('{% load postman_tags %}{{ date|compact_date:"'+format+'" }}')
        self.assertEqual(t.render(Context({'date': date})), value)
    
    def test_compact_date(self):
        "Test '|compact_date'."
        dt = datetime.now()
        default = force_unicode(localize(dt)) # as in template/__init__.py/_render_value_in_context()
        self.check_compact_date(dt, default, format='')
        self.check_compact_date(dt, default, format='one')
        self.check_compact_date(dt, default, format='one,two')
        self.check_compact_date(dt, dt.strftime('%H:%M'))
        dt = datetime.now() - timedelta(days=1) # little fail: do not work on Jan, 1st, because the year changes as well
        self.check_compact_date(dt, dt.strftime('%d %b').lower()) # filter's 'b' is lowercase
        dt = datetime.now() - timedelta(days=365)
        self.check_compact_date(dt, dt.strftime('%d/%m/%y'))

class TagsTest(BaseTest):
    """
    Test the template tags.
    """
    def check_postman_unread(self, value, user=None, asvar=''):
        t = Template("{% load postman_tags %}{% postman_unread " + asvar +" %}")
        ctx = Context({'user': user} if user else {})
        self.assertEqual(t.render(ctx), value)
        return ctx

    def test_postman_unread(self):
        "Test 'postman_unread'."
        self.check_postman_unread('')
        self.check_postman_unread('', AnonymousUser())
        self.check_postman_unread('0', self.user1)
        Message.objects.create(subject='s', recipient=self.user1)
        self.check_postman_unread('0', self.user1)
        Message.objects.create(subject='s', recipient=self.user1, moderation_status=STATUS_ACCEPTED)
        self.check_postman_unread('1', self.user1)
        ctx = self.check_postman_unread('', self.user1, 'as var')
        self.assertEqual(ctx['var'], 1)
        self.assertRaises(TemplateSyntaxError, self.check_postman_unread, '', self.user1, 'as var extra')
        self.assertRaises(TemplateSyntaxError, self.check_postman_unread, '', self.user1, 'As var')
    
    def check_order_by(self, keyword, value_list, context=None):
        t = Template("{% load postman_tags %}{% postman_order_by " + keyword +" %}")
        r = t.render(Context({'gets': QueryDict(context)} if context else {}))
        self.assertEqual(r[0], '?')
        self.assertEqual(set(r[1:].split('&')), set([k+'='+v for k,v in value_list]))

    def test_order_by(self):
        "Test 'postman_order_by'."
        for k,v in ORDER_BY_MAPPER.items():
            self.check_order_by(k, [(ORDER_BY_KEY, v)])
        self.check_order_by('subject', [(ORDER_BY_KEY, 's')], ORDER_BY_KEY+'=foo')
        self.check_order_by('subject', [(ORDER_BY_KEY, 'S')], ORDER_BY_KEY+'=s')
        self.check_order_by('subject', [(ORDER_BY_KEY, 's'), ('page', '12')], 'page=12')
        self.check_order_by('subject', [('foo', 'bar'), (ORDER_BY_KEY, 's'), ('baz', 'qux')], 'foo=bar&'+ORDER_BY_KEY+'=S&baz=qux')
        self.assertRaises(TemplateSyntaxError, self.check_order_by, '', None)
        self.assertRaises(TemplateSyntaxError, self.check_order_by, 'subject extra', None)
        self.assertRaises(TemplateSyntaxError, self.check_order_by, 'unknown', None)

class UtilsTest(BaseTest):
    """
    Test helper functions.
    """
    def test_format_body(self):
        "Test format_body()."
        header = "\n\nfoo wrote:\n"
        footer = "\n"
        self.assertEqual(format_body(self.user1, "foo bar"), header+"> foo bar"+footer)
        self.assertEqual(format_body(self.user1, "foo bar", indent='|_'), header+"|_foo bar"+footer)
        self.assertEqual(format_body(self.user1, width=10, body="34 67 90"), header+"> 34 67 90"+footer)
        self.assertEqual(format_body(self.user1, width=10, body="34 67 901"), header+"> 34 67\n> 901"+footer)
        self.assertEqual(format_body(self.user1, width=10, body="> 34 67 901"), header+"> > 34 67 901"+footer)
        self.assertEqual(format_body(self.user1, width=10,
            body=    "34 67\n"   "\n" "  \n"   "  .\n"   "End"),
            header+"> 34 67\n" "> \n" "> \n" ">   .\n" "> End"+footer)

    def test_format_subject(self):
        "Test format_subject()."
        self.assertEqual(format_subject("foo bar"), "Re: foo bar")
        self.assertEqual(format_subject("Re: foo bar"), "Re: foo bar")
        self.assertEqual(format_subject("rE: foo bar"), "rE: foo bar")
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.