Source

Trac / trac / ticket / tests / model.py

Full commit
   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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2013 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.

from __future__ import with_statement

from datetime import datetime, timedelta
from StringIO import StringIO
import tempfile
import shutil
import unittest

from trac import core
from trac.attachment import Attachment
from trac.core import TracError, implements
from trac.resource import ResourceNotFound
from trac.tests import compat
from trac.ticket.model import (
    Ticket, Component, Milestone, Priority, Type, Version
)
from trac.ticket.api import (
    IMilestoneChangeListener, ITicketChangeListener, TicketSystem
)
from trac.test import EnvironmentStub
from trac.util.datefmt import from_utimestamp, to_utimestamp, utc


class TestTicketChangeListener(core.Component):
    implements(ITicketChangeListener)

    def ticket_created(self, ticket):
        self.action = 'created'
        self.ticket = ticket
        self.resource = ticket.resource

    def ticket_changed(self, ticket, comment, author, old_values):
        self.action = 'changed'
        self.ticket = ticket
        self.comment = comment
        self.author = author
        self.old_values = old_values

    def ticket_deleted(self, ticket):
        self.action = 'deleted'
        self.ticket = ticket


class TicketTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True)
        self.env.config.set('ticket-custom', 'foo', 'text')
        self.env.config.set('ticket-custom', 'cbon', 'checkbox')
        self.env.config.set('ticket-custom', 'cboff', 'checkbox')

    def tearDown(self):
        self.env.reset_db()

    def _insert_ticket(self, summary, **kw):
        """Helper for inserting a ticket into the database"""
        ticket = Ticket(self.env)
        for k, v in kw.items():
            ticket[k] = v
        return ticket.insert()

    def _create_a_ticket(self):
        # 1. Creating ticket
        ticket = Ticket(self.env)
        ticket['reporter'] = 'santa'
        ticket['summary'] = 'Foo'
        ticket['foo'] = 'This is a custom field'
        return ticket

    def test_invalid_ticket_id(self):
        self.assertEqual(Ticket.id_is_valid(-1), False)
        self.assertEqual(Ticket.id_is_valid(0), False)
        self.assertEqual(Ticket.id_is_valid(1), True)
        self.assertEqual(Ticket.id_is_valid(1L << 31), True)
        self.assertEqual(Ticket.id_is_valid(1L << 32), False)
        self.assertRaises(ResourceNotFound, Ticket, self.env, -1)
        self.assertRaises(ResourceNotFound, Ticket, self.env, 1L << 32)

    def test_create_ticket_1(self):
        ticket = self._create_a_ticket()
        self.assertEqual('santa', ticket['reporter'])
        self.assertEqual('Foo', ticket['summary'])
        self.assertEqual('This is a custom field', ticket['foo'])
        ticket.insert()

    def test_create_ticket_2(self):
        ticket = self._create_a_ticket()
        ticket.insert()
        self.assertEqual(1, ticket.id)
        # Retrieving ticket
        ticket2 = Ticket(self.env, 1)
        self.assertEqual(1, ticket2.id)
        self.assertEqual('santa', ticket2['reporter'])
        self.assertEqual('Foo', ticket2['summary'])
        self.assertEqual('This is a custom field', ticket2['foo'])

    def _modify_a_ticket(self):
        ticket2 = self._create_a_ticket()
        ticket2.insert()
        ticket2['summary'] = 'Bar'
        ticket2['foo'] = 'New value'
        ticket2.save_changes('santa', 'this is my comment')
        return ticket2

    def test_create_ticket_3(self):
        self._modify_a_ticket()
        # Retrieving ticket
        ticket3 = Ticket(self.env, 1)
        self.assertEqual(1, ticket3.id)
        self.assertEqual(ticket3['reporter'], 'santa')
        self.assertEqual(ticket3['summary'], 'Bar')
        self.assertEqual(ticket3['foo'], 'New value')

    def test_create_ticket_4(self):
        ticket3 = self._modify_a_ticket()
        # Testing get_changelog()
        log = ticket3.get_changelog()
        self.assertEqual(len(log), 3)
        ok_vals = ['foo', 'summary', 'comment']
        self.assertIn(log[0][2], ok_vals)
        self.assertIn(log[1][2], ok_vals)
        self.assertIn(log[2][2], ok_vals)

    def test_create_ticket_5(self):
        ticket3 = self._modify_a_ticket()
        # Testing delete()
        ticket3.delete()
        log = ticket3.get_changelog()
        self.assertEqual(len(log), 0)
        self.assertRaises(TracError, Ticket, self.env, 1)

    def test_ticket_id_is_always_int(self):
        ticket_id = self._insert_ticket('Foo')
        self.assertEqual(ticket_id, int(ticket_id))
        ticket = Ticket(self.env, str(ticket_id))
        self.assertEqual(ticket_id, ticket.id)
        self.assertEqual(ticket.resource.id, ticket_id)

    def test_can_save_ticket_without_explicit_comment(self):
        ticket = Ticket(self.env)
        ticket.insert()

        ticket['summary'] = 'another summary'
        ticket.save_changes('foo')

        changes = ticket.get_changelog()
        comment_change = [c for c in changes if c[2] == 'comment'][0]
        self.assertEqual('1', comment_change[3])
        self.assertEqual('', comment_change[4])

    def test_can_save_ticket_without_explicit_username(self):
        ticket = Ticket(self.env)
        ticket.insert()

        ticket['summary'] = 'another summary'
        ticket.save_changes()

        for change in ticket.get_changelog():
            self.assertIsNone(change[1])

    def test_comment_with_whitespace_only_is_not_saved(self):
        ticket = Ticket(self.env)
        ticket.insert()

        ticket.save_changes(comment='\n \n ')
        self.assertEqual(0, len(ticket.get_changelog()))

    def test_prop_whitespace_change_is_not_saved(self):
        ticket = Ticket(self.env)
        ticket.populate({'summary': 'ticket summary'})
        ticket.insert()

        ticket['summary'] = ' ticket summary '
        ticket.save_changes()
        self.assertEqual(0, len(ticket.get_changelog()))

    def test_ticket_default_values(self):
        """
        Verify that a ticket uses default values specified in the configuration
        when created.
        """
        # Set defaults for some standard fields
        self.env.config.set('ticket', 'default_type', 'defect')
        self.env.config.set('ticket', 'default_component', 'component1')

        # Add a custom field of type 'text' with a default value
        self.env.config.set('ticket-custom', 'foo', 'text')
        self.env.config.set('ticket-custom', 'foo.value', 'Something')

        # Add a custom field of type 'select' with a default value specified as
        # the value itself
        self.env.config.set('ticket-custom', 'bar', 'select')
        self.env.config.set('ticket-custom', 'bar.options', 'one|two|three')
        self.env.config.set('ticket-custom', 'bar.value', 'two')

        # Add a custom field of type 'select' with a default value specified as
        # index into the options list
        self.env.config.set('ticket-custom', 'baz', 'select')
        self.env.config.set('ticket-custom', 'baz.options', 'one|two|three')
        self.env.config.set('ticket-custom', 'baz.value', '2')

        ticket = Ticket(self.env)
        self.assertEqual('defect', ticket['type'])
        self.assertEqual('component1', ticket['component'])
        self.assertEqual('Something', ticket['foo'])
        self.assertEqual('two', ticket['bar'])
        self.assertEqual('three', ticket['baz'])

    def test_set_field_stripped(self):
        """
        Verify that whitespace around ticket fields is stripped, except for
        textarea fields.
        """
        ticket = Ticket(self.env)
        ticket['component'] = '  foo  '
        ticket['description'] = '  bar  '
        self.assertEqual('foo', ticket['component'])
        self.assertEqual('  bar  ', ticket['description'])

    def test_set_field_multi(self):
        """
        Ticket fields can't yet be multi-valued
        """
        ticket = Ticket(self.env)
        def set_multi_valued():
            ticket['component'] = ['  foo  ',  '  bar  ']
        self.assertRaises(TracError, set_multi_valued)

    def test_owner_from_component(self):
        """
        Verify that the owner of a new ticket is set to the owner of the
        component.
        """
        component = Component(self.env)
        component.name = 'test'
        component.owner = 'joe'
        component.insert()

        ticket = Ticket(self.env)
        ticket['reporter'] = 'santa'
        ticket['summary'] = 'Foo'
        ticket['component'] = 'test'
        ticket.insert()
        self.assertEqual('joe', ticket['owner'])

    def test_owner_from_changed_component(self):
        """
        Verify that the owner of a new ticket is updated when the component is
        changed.
        """
        component1 = Component(self.env)
        component1.name = 'test1'
        component1.owner = 'joe'
        component1.insert()

        component2 = Component(self.env)
        component2.name = 'test2'
        component2.owner = 'kate'
        component2.insert()

        ticket = Ticket(self.env)
        ticket['reporter'] = 'santa'
        ticket['summary'] = 'Foo'
        ticket['component'] = 'test1'
        ticket['status'] = 'new'
        tktid = ticket.insert()

        ticket = Ticket(self.env, tktid)
        ticket['component'] = 'test2'
        ticket.save_changes('jane', 'Testing')
        self.assertEqual('kate', ticket['owner'])

    def test_no_disown_from_changed_component(self):
        """
        Verify that a ticket is not disowned when the component is changed to
        a non-assigned component.
        """
        component1 = Component(self.env)
        component1.name = 'test1'
        component1.owner = 'joe'
        component1.insert()

        component2 = Component(self.env)
        component2.name = 'test2'
        component2.owner = ''
        component2.insert()

        ticket = Ticket(self.env)
        ticket['reporter'] = 'santa'
        ticket['summary'] = 'Foo'
        ticket['component'] = 'test1'
        ticket['status'] = 'new'
        tktid = ticket.insert()

        ticket = Ticket(self.env, tktid)
        ticket['component'] = 'test2'
        ticket.save_changes('jane', 'Testing')
        self.assertEqual('joe', ticket['owner'])

    def test_populate_ticket(self):
        data = {'summary': 'Hello world', 'reporter': 'john',
                'foo': 'bar', 'checkbox_cbon': '', 'cbon': 'on',
                'checkbox_cboff': ''}
        ticket = Ticket(self.env)
        ticket.populate(data)

        # Standard fields
        self.assertEqual('Hello world', ticket['summary'])
        self.assertEqual('john', ticket['reporter'])

        # An unknown field
        self.assertIsNone(ticket['bar'])

        # Custom field
        self.assertEqual('bar', ticket['foo'])

        # Custom field of type 'checkbox'
        self.assertEqual('on', ticket['cbon'])
        self.assertEqual('0', ticket['cboff'])

    def test_custom_time(self):
        # Add a custom field of type 'time'
        self.env.config.set('ticket-custom', 'due', 'time')
        ticket = Ticket(self.env)
        self.assertFalse('due' in ticket.std_fields)
        self.assertTrue('due' in ticket.time_fields)
        ticket['reporter'] = 'john'
        ticket['summary'] = 'Task1'
        tktid = ticket.insert()
        ticket = Ticket(self.env, tktid)
        # Empty string is default value, but not a time stamp
        self.assertEqual(None, ticket['due'])
        ts = datetime(2011, 11, 11, 0, 0, 0, 0, utc)
        ticket['due'] = ts
        t1 = datetime(2001, 1, 1, 1, 1, 1, 0, utc)
        ticket.save_changes('joe', when=t1)
        self.assertEqual(ts, ticket['due'])
        ticket['due'] = ''
        t2 = datetime(2001, 1, 1, 1, 1, 2, 0, utc)
        ticket.save_changes('joe', when=t2)
        self.assertEqual('', ticket['due'])

    def test_changelog(self):
        tkt_id = self._insert_ticket('Test', reporter='joe', component='foo',
                                     milestone='bar')
        ticket = Ticket(self.env, tkt_id)
        ticket['component'] = 'bar'
        ticket['milestone'] = 'foo'
        now = datetime(2001, 1, 1, 1, 1, 1, 0, utc)
        ticket.save_changes('jane', 'Testing', now)
        changelog = sorted(ticket.get_changelog())
        self.assertEqual([(now, 'jane', 'comment', '1', 'Testing', True),
                          (now, 'jane', 'component', 'foo', 'bar', True),
                          (now, 'jane', 'milestone', 'bar', 'foo', True)],
                         changelog)

    def test_changelog_with_attachment(self):
        """Verify ordering of attachments and comments in the changelog."""
        tkt_id = self._insert_ticket('Test', reporter='joe', component='foo')
        ticket = Ticket(self.env, tkt_id)
        t1 = datetime(2001, 1, 1, 1, 1, 1, 0, utc)
        ticket.save_changes('jane', 'Testing', t1)
        t2 = datetime(2001, 1, 1, 1, 1, 2, 0, utc)
        self.env.db_transaction("""
            INSERT INTO attachment (type, id, filename, size, time,
                                    description, author, ipnr)
            VALUES ('ticket',%s,'file.txt',1234,%s, 'My file','mark','')
            """, (str(tkt_id), to_utimestamp(t2)))
        t3 = datetime(2001, 1, 1, 1, 1, 3, 0, utc)
        ticket.save_changes('jim', 'Other', t3)
        log = ticket.get_changelog()
        self.assertEqual(4, len(log))
        self.assertEqual((t1, 'jane', 'comment', '1', 'Testing', True), log[0])
        self.assertEqual([(t2, 'mark', 'attachment', '', 'file.txt', False),
                          (t2, 'mark', 'comment', '', 'My file', False)],
                          sorted(log[1:3]))
        self.assertEqual((t3, 'jim', 'comment', '2', 'Other', True), log[3])

    def test_subsecond_change(self):
        """Perform two ticket changes within a second."""
        tkt_id = self._insert_ticket('Test', reporter='joe', component='foo')
        ticket = Ticket(self.env, tkt_id)
        t1 = datetime(2001, 1, 1, 1, 1, 1, 123456, utc)
        ticket.save_changes('jane', 'Testing', t1)
        t2 = datetime(2001, 1, 1, 1, 1, 1, 123789, utc)
        ticket.save_changes('jim', 'Other', t2)
        log = ticket.get_changelog()
        self.assertEqual(2, len(log))
        self.assertEqual((t1, 'jane', 'comment', '1', 'Testing', True), log[0])
        self.assertEqual((t2, 'jim', 'comment', '2', 'Other', True), log[1])

    def test_changelog_with_reverted_change(self):
        tkt_id = self._insert_ticket('Test', reporter='joe', component='foo')
        ticket = Ticket(self.env, tkt_id)
        ticket['component'] = 'bar'
        ticket['component'] = 'foo'
        now = datetime(2001, 1, 1,  1, 1, 1, 0, utc)
        ticket.save_changes('jane', 'Testing', now)
        self.assertEqual([(now, 'jane', 'comment', '1', 'Testing', True)],
                         list(ticket.get_changelog()))

    def test_change_listener_created(self):
        listener = TestTicketChangeListener(self.env)
        ticket = self._create_a_ticket()
        ticket.insert()
        self.assertEqual('created', listener.action)
        self.assertEqual(ticket, listener.ticket)
        self.assertEqual(ticket.id, ticket.resource.id)

    def test_change_listener_changed(self):
        listener = TestTicketChangeListener(self.env)
        data = {'component': 'foo', 'milestone': 'bar'}
        tkt_id = self._insert_ticket('Hello World', reporter='john', **data)

        ticket = Ticket(self.env, tkt_id)
        ticket['component'] = 'new component'
        ticket['milestone'] = 'new milestone'

        comment = 'changing ticket'
        ticket.save_changes('author', comment)

        self.assertEqual('changed', listener.action)
        self.assertEqual(comment, listener.comment)
        self.assertEqual('author', listener.author)
        for key, value in data.iteritems():
            self.assertEqual(value, listener.old_values[key])

    def test_change_listener_deleted(self):
        listener = TestTicketChangeListener(self.env)
        ticket = self._create_a_ticket()
        ticket.insert()
        ticket.delete()
        self.assertEqual('deleted', listener.action)
        self.assertEqual(ticket, listener.ticket)


class TicketCommentTestCase(unittest.TestCase):

    def _insert_ticket(self, summary, when, **kwargs):
        ticket = Ticket(self.env)
        for k, v in kwargs.iteritems():
            ticket[k] = v
        self.id = ticket.insert(when)

    def _modify_ticket(self, author, comment, when, cnum, **kwargs):
        ticket = Ticket(self.env, self.id)
        for k, v in kwargs.iteritems():
            ticket[k] = v
        ticket.save_changes(author, comment, when, cnum=cnum)

    def _find_change(self, ticket, cnum):
        (ts, author, comment) = ticket._find_change(cnum)
        return from_utimestamp(ts)

    def assertChange(self, ticket, cnum, date, author, **fields):
        change = ticket.get_change(cnum=cnum)
        self.assertEqual(dict(date=date, author=author, fields=fields), change)


class TicketCommentEditTestCase(TicketCommentTestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True)
        self.created = datetime(2001, 1, 1, 1, 0, 0, 0, utc)
        self._insert_ticket('Test ticket', self.created,
                            owner='john', keywords='a, b, c')
        self.t1 = self.created + timedelta(seconds=1)
        self._modify_ticket('jack', 'Comment 1', self.t1, '1')
        self.t2 = self.created + timedelta(seconds=2)
        self._modify_ticket('john', 'Comment 2', self.t2, '1.2',
                            owner='jack')
        self.t3 = self.created + timedelta(seconds=3)
        self._modify_ticket('jim', 'Comment 3', self.t3, '3',
                            keywords='a, b')

    def tearDown(self):
        self.env.reset_db()

    def test_modify_comment(self):
        """Check modification of a "standalone" comment"""
        ticket = Ticket(self.env, self.id)
        self.assertChange(ticket, 1, self.t1, 'jack',
            comment=dict(author='jack', old='1', new='Comment 1'))
        self.assertChange(ticket, 2, self.t2, 'john',
            owner=dict(author='john', old='john', new='jack'),
            comment=dict(author='john', old='1.2', new='Comment 2'))
        self.assertChange(ticket, 3, self.t3, 'jim',
            keywords=dict(author='jim', old='a, b, c', new='a, b'),
            comment=dict(author='jim', old='3', new='Comment 3'))

        t = self.created + timedelta(seconds=10)
        ticket.modify_comment(self._find_change(ticket, 1),
                              'joe', 'New comment 1', t)
        self.assertChange(ticket, 1, self.t1, 'jack',
            comment=dict(author='jack', old='1', new='New comment 1'),
            _comment0=dict(author='joe', old='Comment 1',
                           new=str(to_utimestamp(t))))
        self.assertEqual(t, Ticket(self.env, self.id)['changetime'])

    def test_threading(self):
        """Check modification of a "threaded" comment"""
        ticket = Ticket(self.env, self.id)
        t = self.created + timedelta(seconds=20)
        ticket.modify_comment(self._find_change(ticket, 2),
                              'joe', 'New comment 2', t)
        self.assertChange(ticket, 2, self.t2, 'john',
            owner=dict(author='john', old='john', new='jack'),
            comment=dict(author='john', old='1.2', new='New comment 2'),
            _comment0=dict(author='joe', old='Comment 2',
                           new=str(to_utimestamp(t))))

    def test_modify_missing_cnum(self):
        """Editing a comment with no cnum in oldvalue"""
        self.env.db_transaction(
            "UPDATE ticket_change SET oldvalue='' WHERE oldvalue='3'")
        ticket = Ticket(self.env, self.id)
        t = self.created + timedelta(seconds=30)
        ticket.modify_comment(self._find_change(ticket, 3),
                              'joe', 'New comment 3', t)
        self.assertChange(ticket, 3, self.t3, 'jim',
            keywords=dict(author='jim', old='a, b, c', new='a, b'),
            comment=dict(author='jim', old='', new='New comment 3'),
            _comment0=dict(author='joe', old='Comment 3',
                           new=str(to_utimestamp(t))))

    def test_modify_missing_comment(self):
        """Editing a comment where the comment field is missing"""
        self.env.db_transaction("""
            DELETE FROM ticket_change WHERE field='comment' AND oldvalue='1.2'
            """)
        ticket = Ticket(self.env, self.id)
        t = self.created + timedelta(seconds=40)
        ticket.modify_comment(self._find_change(ticket, 2),
                              'joe', 'New comment 2', t)
        self.assertChange(ticket, 2, self.t2, 'john',
            owner=dict(author='john', old='john', new='jack'),
            comment=dict(author='john', old='', new='New comment 2'),
            _comment0=dict(author='joe', old='',
                           new=str(to_utimestamp(t))))

    def test_modify_missing_cnums_and_comment(self):
        """Editing a comment when all cnums are missing and one comment
        field is missing
        """
        with self.env.db_transaction as db:
            db("UPDATE ticket_change SET oldvalue='' WHERE oldvalue='1'")
            db("""DELETE FROM ticket_change
                  WHERE field='comment' AND oldvalue='1.2'""")
            db("UPDATE ticket_change SET oldvalue='' WHERE oldvalue='3'")

        # Modify after missing comment
        ticket = Ticket(self.env, self.id)
        t = self.created + timedelta(seconds=50)
        ticket.modify_comment(self._find_change(ticket, 3),
                              'joe', 'New comment 3', t)
        self.assertChange(ticket, 3, self.t3, 'jim',
            keywords=dict(author='jim', old='a, b, c', new='a, b'),
            comment=dict(author='jim', old='', new='New comment 3'),
            _comment0=dict(author='joe', old='Comment 3',
                           new=str(to_utimestamp(t))))

        # Modify missing comment
        t = self.created + timedelta(seconds=60)
        ticket.modify_comment(self._find_change(ticket, 2),
                              'joe', 'New comment 2', t)
        self.assertChange(ticket, 2, self.t2, 'john',
            owner=dict(author='john', old='john', new='jack'),
            comment=dict(author='john', old='', new='New comment 2'),
            _comment0=dict(author='joe', old='',
                           new=str(to_utimestamp(t))))

    def test_missing_comment_edit(self):
        """Modify a comment where one edit is missing"""
        ticket = Ticket(self.env, self.id)
        t1 = self.created + timedelta(seconds=70)
        ticket.modify_comment(self._find_change(ticket, 1),
                              'joe', 'New comment 1', t1)
        t2 = self.created + timedelta(seconds=80)
        ticket.modify_comment(self._find_change(ticket, 1),
                              'joe', 'Other comment 1', t2)

        self.assertChange(ticket, 1, self.t1, 'jack',
            comment=dict(author='jack', old='1', new='Other comment 1'),
            _comment0=dict(author='joe', old='Comment 1',
                           new=str(to_utimestamp(t1))),
            _comment1=dict(author='joe', old='New comment 1',
                           new=str(to_utimestamp(t2))))

        self.env.db_transaction(
            "DELETE FROM ticket_change WHERE field='_comment0'")

        t3 = self.created + timedelta(seconds=90)
        ticket.modify_comment(self._find_change(ticket, 1),
                              'joe', 'Newest comment 1', t3)

        self.assertChange(ticket, 1, self.t1, 'jack',
            comment=dict(author='jack', old='1', new='Newest comment 1'),
            _comment1=dict(author='joe', old='New comment 1',
                           new=str(to_utimestamp(t2))),
            _comment2=dict(author='joe', old='Other comment 1',
                           new=str(to_utimestamp(t3))))

    def test_comment_history(self):
        """Check the generation of the comment history"""
        ticket = Ticket(self.env, self.id)
        t = [self.t1]
        for i in range(1, 32):
            t.append(self.created + timedelta(minutes=i))
            ticket.modify_comment(self._find_change(ticket, 1),
                                  'joe (%d)' % i,
                                  'Comment 1 (%d)' % i, t[-1])
        history = ticket.get_comment_history(cnum=1)
        self.assertEqual((0, t[0], 'jack', 'Comment 1'), history[0])
        for i in range(1, len(history)):
            self.assertEqual((i, t[i], 'joe (%d)' % i,
                             'Comment 1 (%d)' % i), history[i])
        history = ticket.get_comment_history(cdate=self.t1)
        self.assertEqual((0, t[0], 'jack', 'Comment 1'), history[0])
        for i in range(1, len(history)):
            self.assertEqual((i, t[i], 'joe (%d)' % i,
                             'Comment 1 (%d)' % i), history[i])


class TicketCommentDeleteTestCase(TicketCommentTestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True)
        self.env.config.set('ticket-custom', 'foo', 'text')
        self.created = datetime(2001, 1, 1, 1, 0, 0, 0, utc)
        self._insert_ticket('Test ticket', self.created,
                            owner='john', keywords='a, b, c', foo='initial')
        self.t1 = self.created + timedelta(seconds=1)
        self._modify_ticket('jack', 'Comment 1', self.t1, '1',
                            foo='change 1')
        self.t2 = self.created + timedelta(seconds=2)
        self._modify_ticket('john', 'Comment 2', self.t2, '1.2',
                            owner='jack', foo='change2')
        self.t3 = self.created + timedelta(seconds=3)
        self._modify_ticket('jim', 'Comment 3', self.t3, '3',
                            keywords='a, b', foo='change3')
        self.t4 = self.created + timedelta(seconds=4)
        self._modify_ticket('joe', 'Comment 4', self.t4, '4',
                            keywords='a', foo='change4')

    def tearDown(self):
        self.env.reset_db()

    def test_delete_last_comment(self):
        ticket = Ticket(self.env, self.id)
        self.assertEqual('a', ticket['keywords'])
        self.assertEqual('change4', ticket['foo'])
        t = datetime.now(utc)
        ticket.delete_change(cnum=4, when=t)
        self.assertEqual('a, b', ticket['keywords'])
        self.assertEqual('change3', ticket['foo'])
        self.assertIsNone(ticket.get_change(cnum=4))
        self.assertIsNotNone(ticket.get_change(cnum=3))
        self.assertEqual(t, ticket.time_changed)

    def test_delete_last_comment_when_custom_field_gone(self):
        """Regression test for http://trac.edgewall.org/ticket/10858"""
        ticket = Ticket(self.env, self.id)
        self.assertEqual('a', ticket['keywords'])
        self.assertEqual('change4', ticket['foo'])
        # we simulate the removal of the definition of the 'foo' custom field
        self.env.config.remove('ticket-custom', 'foo')
        del TicketSystem(self.env).fields
        del TicketSystem(self.env).custom_fields
        ticket = Ticket(self.env, self.id)
        #
        t = datetime.now(utc)
        ticket.delete_change(cnum=4, when=t)
        self.assertEqual('a, b', ticket['keywords'])
        # 'foo' is no longer defined for the ticket
        self.assertIsNone(ticket['foo'])
        # however, 'foo=change3' is still in the database
        self.assertEqual([('change3',)], self.env.db_query("""
            SELECT value FROM ticket_custom WHERE ticket=%s AND name='foo'
            """, (self.id,)))
        self.assertIsNone(ticket.get_change(cnum=4))
        self.assertIsNotNone(ticket.get_change(cnum=3))
        self.assertEqual(t, ticket.time_changed)

    def test_delete_last_comment_by_date(self):
        ticket = Ticket(self.env, self.id)
        self.assertEqual('a', ticket['keywords'])
        self.assertEqual('change4', ticket['foo'])
        t = datetime.now(utc)
        ticket.delete_change(cdate=self.t4, when=t)
        self.assertEqual('a, b', ticket['keywords'])
        self.assertEqual('change3', ticket['foo'])
        self.assertIsNone(ticket.get_change(cdate=self.t4))
        self.assertIsNotNone(ticket.get_change(cdate=self.t3))
        self.assertEqual(t, ticket.time_changed)

    def test_delete_mid_comment(self):
        ticket = Ticket(self.env, self.id)
        self.assertChange(ticket, 4, self.t4, 'joe',
            comment=dict(author='joe', old='4', new='Comment 4'),
            keywords=dict(author='joe', old='a, b', new='a'),
            foo=dict(author='joe', old='change3', new='change4'))
        t = datetime.now(utc)
        ticket.delete_change(cnum=3, when=t)
        self.assertIsNone(ticket.get_change(cnum=3))
        self.assertEqual('a', ticket['keywords'])
        self.assertChange(ticket, 4, self.t4, 'joe',
            comment=dict(author='joe', old='4', new='Comment 4'),
            keywords=dict(author='joe', old='a, b, c', new='a'),
            foo=dict(author='joe', old='change2', new='change4'))
        self.assertEqual(t, ticket.time_changed)

    def test_delete_mid_comment_by_date(self):
        ticket = Ticket(self.env, self.id)
        self.assertChange(ticket, 4, self.t4, 'joe',
            comment=dict(author='joe', old='4', new='Comment 4'),
            keywords=dict(author='joe', old='a, b', new='a'),
            foo=dict(author='joe', old='change3', new='change4'))
        t = datetime.now(utc)
        ticket.delete_change(cdate=self.t3, when=t)
        self.assertIsNone(ticket.get_change(cdate=self.t3))
        self.assertEqual('a', ticket['keywords'])
        self.assertChange(ticket, 4, self.t4, 'joe',
            comment=dict(author='joe', old='4', new='Comment 4'),
            keywords=dict(author='joe', old='a, b, c', new='a'),
            foo=dict(author='joe', old='change2', new='change4'))
        self.assertEqual(t, ticket.time_changed)

    def test_delete_mid_comment_inconsistent(self):
        # Make oldvalue on keywords for change 4 inconsistent. This should
        # result in no change in oldvalue when deleting change 3. The
        # oldvalue of foo should change normally.
        self.env.db_transaction("""
            UPDATE ticket_change SET oldvalue='1, 2'
            WHERE field='keywords' AND oldvalue='a, b'
            """)
        ticket = Ticket(self.env, self.id)
        self.assertChange(ticket, 4, self.t4, 'joe',
            comment=dict(author='joe', old='4', new='Comment 4'),
            keywords=dict(author='joe', old='1, 2', new='a'),
            foo=dict(author='joe', old='change3', new='change4'))
        ticket.delete_change(3)
        self.assertIsNone(ticket.get_change(3))
        self.assertEqual('a', ticket['keywords'])
        self.assertChange(ticket, 4, self.t4, 'joe',
            comment=dict(author='joe', old='4', new='Comment 4'),
            keywords=dict(author='joe', old='1, 2', new='a'),
            foo=dict(author='joe', old='change2', new='change4'))

    def test_delete_all_comments(self):
        ticket = Ticket(self.env, self.id)
        ticket.delete_change(4)
        ticket.delete_change(3)
        ticket.delete_change(2)
        t = datetime.now(utc)
        ticket.delete_change(1, when=t)
        self.assertEqual(t, ticket.time_changed)


class EnumTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True)

    def tearDown(self):
        self.env.reset_db()

    def test_priority_fetch(self):
        prio = Priority(self.env, 'major')
        self.assertEqual(prio.name, 'major')
        self.assertEqual(prio.value, '3')

    def test_priority_insert(self):
        prio = Priority(self.env)
        prio.name = 'foo'
        prio.insert()
        self.assertTrue(prio.exists)

    def test_priority_insert_with_value(self):
        prio = Priority(self.env)
        prio.name = 'bar'
        prio.value = 100
        prio.insert()
        self.assertTrue(prio.exists)

    def test_priority_update(self):
        prio = Priority(self.env, 'major')
        prio.name = 'foo'
        prio.update()
        Priority(self.env, 'foo')
        self.assertRaises(TracError, Priority, self.env, 'major')

    def test_priority_delete(self):
        prio = Priority(self.env, 'major')
        self.assertEqual('3', prio.value)
        prio.delete()
        self.assertFalse(prio.exists)
        self.assertRaises(TracError, Priority, self.env, 'major')
        prio = Priority(self.env, 'minor')
        self.assertEqual('3', prio.value)

    def test_ticket_type_update(self):
        tkttype = Type(self.env, 'task')
        self.assertEqual(tkttype.name, 'task')
        self.assertEqual(tkttype.value, '3')
        tkttype.name = 'foo'
        tkttype.update()
        Type(self.env, 'foo')


class TestMilestoneChangeListener(core.Component):
    implements(IMilestoneChangeListener)

    def milestone_created(self, milestone):
        self.action = 'created'
        self.milestone = milestone

    def milestone_changed(self, milestone, old_values):
        self.action = 'changed'
        self.milestone = milestone
        self.old_values = old_values

    def milestone_deleted(self, milestone):
        self.action = 'deleted'
        self.milestone = milestone


class MilestoneTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True)
        self.env.path = tempfile.mkdtemp(prefix='trac-tempenv-')
        self.created_at = datetime(2001, 1, 1, tzinfo=utc)
        self.updated_at = self.created_at + timedelta(seconds=1)

    def tearDown(self):
        shutil.rmtree(self.env.path)
        self.env.reset_db()

    def _create_milestone(self, **values):
        milestone = Milestone(self.env)
        for k, v in values.iteritems():
            setattr(milestone, k, v)
        return milestone

    def _insert_ticket(self, when=None, **kwargs):
        ticket = Ticket(self.env)
        for name, value in kwargs.iteritems():
            ticket[name] = value
        ticket.insert(when or self.created_at)
        return ticket

    def _update_ticket(self, ticket, author=None, comment=None, when=None,
                       **kwargs):
        for name, value in kwargs.iteritems():
            ticket[name] = value
        ticket.save_changes(author, comment, when or self.updated_at)

    def test_new_milestone(self):
        milestone = Milestone(self.env)
        self.assertFalse(milestone.exists)
        self.assertIsNone(milestone.name)
        self.assertIsNone(milestone.due)
        self.assertIsNone(milestone.completed)
        self.assertEqual('', milestone.description)

    def test_new_milestone_empty_name(self):
        """
        Verifies that specifying an empty milestone name results in the
        milestone being correctly detected as non-existent.
        """
        milestone = Milestone(self.env, '')
        self.assertFalse(milestone.exists)
        self.assertIsNone(milestone.name)
        self.assertIsNone(milestone.due)
        self.assertIsNone(milestone.completed)
        self.assertEqual('', milestone.description)

    def test_existing_milestone(self):
        self.env.db_transaction("INSERT INTO milestone (name) VALUES ('Test')")

        milestone = Milestone(self.env, 'Test')
        self.assertTrue(milestone.exists)
        self.assertEqual('Test', milestone.name)
        self.assertIsNone(milestone.due)
        self.assertIsNone(milestone.completed)
        self.assertEqual('', milestone.description)

    def test_create_and_update_milestone(self):
        milestone = Milestone(self.env)
        milestone.name = 'Test'
        milestone.insert()

        self.assertEqual([('Test', 0, 0, '')], self.env.db_query("""
            SELECT name, due, completed, description FROM milestone
            WHERE name='Test'
            """))

        # Use the same model object to update the milestone
        milestone.description = 'Some text'
        milestone.update()
        self.assertEqual([('Test', 0, 0, 'Some text')], self.env.db_query("""
            SELECT name, due, completed, description FROM milestone
            WHERE name='Test'
            """))

    def test_move_tickets(self):
        self.env.db_transaction.executemany(
            "INSERT INTO milestone (name) VALUES (%s)",
            [('Test',), ('Testing',)])
        tkt1 = self._insert_ticket(status='new', summary='Foo',
                                   milestone='Test')
        tkt2 = self._insert_ticket(status='new', summary='Bar',
                                   milestone='Test')
        self._update_ticket(tkt2, status='closed', resolution='fixed')
        milestone = Milestone(self.env, 'Test')
        milestone.move_tickets('Testing', 'anonymous', 'Move tickets')

        tkt1 = Ticket(self.env, tkt1.id)
        tkt2 = Ticket(self.env, tkt2.id)
        self.assertEqual('Testing', tkt1['milestone'])
        self.assertEqual('Testing', tkt2['milestone'])
        self.assertEqual(tkt1['changetime'], tkt2['changetime'])
        self.assertNotEqual(self.updated_at, tkt1['changetime'])

    def test_move_tickets_exclude_closed(self):
        self.env.db_transaction.executemany(
            "INSERT INTO milestone (name) VALUES (%s)",
            [('Test',), ('Testing',)])
        tkt1 = self._insert_ticket(status='new', summary='Foo',
                                   milestone='Test')
        tkt2 = self._insert_ticket(status='new', summary='Bar',
                                   milestone='Test')
        self._update_ticket(tkt2, status='closed', resolution='fixed')
        milestone = Milestone(self.env, 'Test')
        milestone.move_tickets('Testing', 'anonymous', 'Move tickets',
                               exclude_closed=True)

        tkt1 = Ticket(self.env, tkt1.id)
        tkt2 = Ticket(self.env, tkt2.id)
        self.assertEqual('Testing', tkt1['milestone'])
        self.assertEqual('Test', tkt2['milestone'])
        self.assertNotEqual(self.updated_at, tkt1['changetime'])
        self.assertEqual(self.updated_at, tkt2['changetime'])

    def test_move_tickets_target_doesnt_exist(self):
        self.env.db_transaction("INSERT INTO milestone (name) VALUES ('Test')")
        tkt1 = self._insert_ticket(status='new', summary='Foo',
                                   milestone='Test')
        tkt2 = self._insert_ticket(status='new', summary='Bar',
                                   milestone='Test')
        milestone = Milestone(self.env, 'Test')
        self.assertRaises(ResourceNotFound, milestone.move_tickets,
                          'Testing', 'anonymous')

        tkt1 = Ticket(self.env, tkt1.id)
        tkt2 = Ticket(self.env, tkt2.id)
        self.assertEqual('Test', tkt1['milestone'])
        self.assertEqual('Test', tkt2['milestone'])
        self.assertNotEqual(self.updated_at, tkt1['changetime'])
        self.assertNotEqual(self.updated_at, tkt2['changetime'])

    def test_create_milestone_without_name(self):
        milestone = Milestone(self.env)
        self.assertRaises(TracError, milestone.insert)

    def test_delete_milestone(self):
        self.env.db_transaction("INSERT INTO milestone (name) VALUES ('Test')")
        tkt1 = self._insert_ticket(status='new', summary='Foo',
                                   milestone='Test')
        tkt2 = self._insert_ticket(status='new', summary='Bar',
                                   milestone='Test')
        self._update_ticket(tkt2, status='closed', resolution='fixed')
        milestone = Milestone(self.env, 'Test')
        milestone.delete()
        self.assertFalse(milestone.exists)
        self.assertEqual([],
            self.env.db_query("SELECT * FROM milestone WHERE name='Test'"))

        tkt1 = Ticket(self.env, tkt1.id)
        tkt2 = Ticket(self.env, tkt2.id)
        self.assertEqual('', tkt1['milestone'])
        self.assertEqual('', tkt2['milestone'])
        self.assertEqual(tkt1['changetime'], tkt2['changetime'])
        self.assertNotEqual(self.updated_at, tkt1['changetime'])

    def test_delete_milestone_retarget_tickets(self):
        self.env.db_transaction.executemany(
            "INSERT INTO milestone (name) VALUES (%s)",
            [('Test',), ('Other',)])
        tkt1 = self._insert_ticket(status='new', summary='Foo',
                                   milestone='Test')
        tkt2 = self._insert_ticket(status='new', summary='Bar',
                                   milestone='Test')
        self._update_ticket(tkt2, status='closed', resolution='fixed')
        milestone = Milestone(self.env, 'Test')
        milestone.delete(retarget_to='Other')
        self.assertFalse(milestone.exists)

        tkt1 = Ticket(self.env, tkt1.id)
        tkt2 = Ticket(self.env, tkt2.id)
        self.assertEqual('Other', tkt1['milestone'])
        self.assertEqual('Other', tkt2['milestone'])
        self.assertEqual(tkt1['changetime'], tkt2['changetime'])
        self.assertNotEqual(self.updated_at, tkt1['changetime'])

    def test_update_milestone(self):
        self.env.db_transaction("INSERT INTO milestone (name) VALUES ('Test')")

        milestone = Milestone(self.env, 'Test')
        t1 = datetime(2001, 01, 01, tzinfo=utc)
        t2 = datetime(2002, 02, 02, tzinfo=utc)
        milestone.due = t1
        milestone.completed = t2
        milestone.description = 'Foo bar'
        milestone.update()

        self.assertEqual(
            [('Test', to_utimestamp(t1), to_utimestamp(t2), 'Foo bar')],
            self.env.db_query("SELECT * FROM milestone WHERE name='Test'"))

    def test_update_milestone_without_name(self):
        self.env.db_transaction("INSERT INTO milestone (name) VALUES ('Test')")

        milestone = Milestone(self.env, 'Test')
        milestone.name = None
        self.assertRaises(TracError, milestone.update)

    def test_rename_milestone(self):
        milestone = Milestone(self.env)
        milestone.name = 'OldName'
        milestone.insert()

        attachment = Attachment(self.env, 'milestone', 'OldName')
        attachment.insert('foo.txt', StringIO(), 0, 1)

        milestone = Milestone(self.env, 'OldName')
        milestone.name = 'NewName'
        milestone.update()

        self.assertRaises(ResourceNotFound, Milestone, self.env, 'OldName')
        self.assertEqual('NewName', Milestone(self.env, 'NewName').name)

        attachments = Attachment.select(self.env, 'milestone', 'OldName')
        self.assertRaises(StopIteration, attachments.next)
        attachments = Attachment.select(self.env, 'milestone', 'NewName')
        self.assertEqual('foo.txt', attachments.next().filename)
        self.assertRaises(StopIteration, attachments.next)

    def test_rename_milestone_retarget_tickets(self):
        self.env.db_transaction("INSERT INTO milestone (name) VALUES ('Test')")
        tkt1 = self._insert_ticket(status='new', summary='Foo',
                                   milestone='Test')
        tkt2 = self._insert_ticket(status='new', summary='Bar',
                                   milestone='Test')
        self._update_ticket(tkt2, status='closed', resolution='fixed')
        milestone = Milestone(self.env, 'Test')
        milestone.name = 'Testing'
        milestone.update()

        tkt1 = Ticket(self.env, tkt1.id)
        tkt2 = Ticket(self.env, tkt2.id)
        self.assertEqual('Testing', tkt1['milestone'])
        self.assertEqual('Testing', tkt2['milestone'])
        self.assertEqual(tkt1['changetime'], tkt2['changetime'])
        self.assertNotEqual(self.updated_at, tkt1['changetime'])

    def test_select_milestones(self):
        self.env.db_transaction.executemany(
            "INSERT INTO milestone (name) VALUES (%s)",
            [('1.0',), ('2.0',)])

        milestones = list(Milestone.select(self.env))
        self.assertEqual('1.0', milestones[0].name)
        self.assertTrue(milestones[0].exists)
        self.assertEqual('2.0', milestones[1].name)
        self.assertTrue(milestones[1].exists)

    def test_change_listener_created(self):
        listener = TestMilestoneChangeListener(self.env)
        milestone = self._create_milestone(name='Milestone 1')
        milestone.insert()
        self.assertEqual('created', listener.action)
        self.assertEqual(milestone, listener.milestone)

    def test_change_listener_changed(self):
        listener = TestMilestoneChangeListener(self.env)
        milestone = self._create_milestone(
            name='Milestone 1',
            due=datetime(2001, 01, 01, tzinfo=utc),
            description='The milestone description')
        milestone.insert()

        milestone.name = 'Milestone 2'
        milestone.completed = datetime(2001, 02, 03, tzinfo=utc)
        milestone.description = 'The changed description'
        milestone.update()

        self.assertEqual('changed', listener.action)
        self.assertEqual(milestone, listener.milestone)
        self.assertEqual({'name': 'Milestone 1', 'completed': None,
                          'description': 'The milestone description'},
                         listener.old_values)

    def test_change_listener_deleted(self):
        listener = TestMilestoneChangeListener(self.env)
        milestone = self._create_milestone(name='Milestone 1')
        milestone.insert()
        self.assertTrue(milestone.exists)
        milestone.delete()
        self.assertEqual('Milestone 1', milestone.name)
        self.assertFalse(milestone.exists)
        self.assertEqual('deleted', listener.action)
        self.assertEqual(milestone, listener.milestone)


class ComponentTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True)

    def tearDown(self):
        self.env.reset_db()

    def test_exists_negative(self):
        def get_fake_component():
            return Component(self.env, "Shrubbery")
        self.assertRaises(TracError, get_fake_component)

    def test_exists(self):
        """
        http://trac.edgewall.org/ticket/4247
        """
        for c in Component.select(self.env):
            self.assertEqual(c.exists, True)

    def test_create_and_update(self):
        component = Component(self.env)
        component.name = 'Test'
        component.insert()

        self.assertEqual([('Test', None, None)], self.env.db_query("""
            SELECT name, owner, description FROM component
            WHERE name='Test'"""))

        # Use the same model object to update the component
        component.owner = 'joe'
        component.update()
        self.assertEqual([('Test', 'joe', None)], self.env.db_query(
            "SELECT name, owner, description FROM component WHERE name='Test'"))

class VersionTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True)

    def tearDown(self):
        self.env.reset_db()

    def test_exists_negative(self):
        def get_fake_version():
            return Version(self.env, "-1")
        self.assertRaises(TracError, get_fake_version)

    def test_exists(self):
        """
        http://trac.edgewall.org/ticket/4247
        """
        for v in Version.select(self.env):
            self.assertEqual(v.exists, True)

    def test_create_and_update(self):
        version = Version(self.env)
        version.name = 'Test'
        version.insert()

        self.assertEqual([('Test', 0, None)], self.env.db_query(
            "SELECT name, time, description FROM version WHERE name='Test'"))

        # Use the same model object to update the version
        version.description = 'Some text'
        version.update()
        self.assertEqual([('Test', 0, 'Some text')], self.env.db_query(
            "SELECT name, time, description FROM version WHERE name='Test'"))


def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TicketTestCase))
    suite.addTest(unittest.makeSuite(TicketCommentEditTestCase))
    suite.addTest(unittest.makeSuite(TicketCommentDeleteTestCase))
    suite.addTest(unittest.makeSuite(EnumTestCase))
    suite.addTest(unittest.makeSuite(MilestoneTestCase))
    suite.addTest(unittest.makeSuite(ComponentTestCase))
    suite.addTest(unittest.makeSuite(VersionTestCase))
    return suite

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