~bzr-pqm/bzr/bzr.dev

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
# Copyright (C) 2008 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Tests for pack repositories.

These tests are repeated for all pack-based repository formats.
"""

from cStringIO import StringIO
from stat import S_ISDIR

from bzrlib.btree_index import BTreeGraphIndex
from bzrlib.index import GraphIndex
from bzrlib import (
    bzrdir,
    errors,
    inventory,
    osutils,
    progress,
    repository,
    revision as _mod_revision,
    symbol_versioning,
    tests,
    ui,
    upgrade,
    workingtree,
    )
from bzrlib.repofmt.groupcompress_repo import RepositoryFormatCHK1
from bzrlib.smart import (
    client,
    server,
    )
from bzrlib.tests import (
    TestCase,
    TestCaseWithTransport,
    TestNotApplicable,
    TestSkipped,
    )
from bzrlib.transport import (
    fakenfs,
    memory,
    get_transport,
    )
from bzrlib.tests.per_repository import TestCaseWithRepository


class TestPackRepository(TestCaseWithTransport):
    """Tests to be repeated across all pack-based formats.

    The following are populated from the test scenario:

    :ivar format_name: Registered name fo the format to test.
    :ivar format_string: On-disk format marker.
    :ivar format_supports_external_lookups: Boolean.
    """

    def get_format(self):
        return bzrdir.format_registry.make_bzrdir(self.format_name)

    def test_attribute__fetch_order(self):
        """Packs do not need ordered data retrieval."""
        format = self.get_format()
        repo = self.make_repository('.', format=format)
        self.assertEqual('unordered', repo._format._fetch_order)

    def test_attribute__fetch_uses_deltas(self):
        """Packs reuse deltas."""
        format = self.get_format()
        repo = self.make_repository('.', format=format)
        if isinstance(format.repository_format, RepositoryFormatCHK1):
            # TODO: This is currently a workaround. CHK format repositories
            #       ignore the 'deltas' flag, but during conversions, we can't
            #       do unordered delta fetches. Remove this clause once we
            #       improve the inter-format fetching.
            self.assertEqual(False, repo._format._fetch_uses_deltas)
        else:
            self.assertEqual(True, repo._format._fetch_uses_deltas)

    def test_disk_layout(self):
        format = self.get_format()
        repo = self.make_repository('.', format=format)
        # in case of side effects of locking.
        repo.lock_write()
        repo.unlock()
        t = repo.bzrdir.get_repository_transport(None)
        self.check_format(t)
        # XXX: no locks left when unlocked at the moment
        # self.assertEqualDiff('', t.get('lock').read())
        self.check_databases(t)

    def check_format(self, t):
        self.assertEqualDiff(
            self.format_string, # from scenario
            t.get('format').read())

    def assertHasNoKndx(self, t, knit_name):
        """Assert that knit_name has no index on t."""
        self.assertFalse(t.has(knit_name + '.kndx'))

    def assertHasNoKnit(self, t, knit_name):
        """Assert that knit_name exists on t."""
        # no default content
        self.assertFalse(t.has(knit_name + '.knit'))

    def check_databases(self, t):
        """check knit content for a repository."""
        # check conversion worked
        self.assertHasNoKndx(t, 'inventory')
        self.assertHasNoKnit(t, 'inventory')
        self.assertHasNoKndx(t, 'revisions')
        self.assertHasNoKnit(t, 'revisions')
        self.assertHasNoKndx(t, 'signatures')
        self.assertHasNoKnit(t, 'signatures')
        self.assertFalse(t.has('knits'))
        # revision-indexes file-container directory
        self.assertEqual([],
            list(self.index_class(t, 'pack-names', None).iter_all_entries()))
        self.assertTrue(S_ISDIR(t.stat('packs').st_mode))
        self.assertTrue(S_ISDIR(t.stat('upload').st_mode))
        self.assertTrue(S_ISDIR(t.stat('indices').st_mode))
        self.assertTrue(S_ISDIR(t.stat('obsolete_packs').st_mode))

    def test_shared_disk_layout(self):
        format = self.get_format()
        repo = self.make_repository('.', shared=True, format=format)
        # we want:
        t = repo.bzrdir.get_repository_transport(None)
        self.check_format(t)
        # XXX: no locks left when unlocked at the moment
        # self.assertEqualDiff('', t.get('lock').read())
        # We should have a 'shared-storage' marker file.
        self.assertEqualDiff('', t.get('shared-storage').read())
        self.check_databases(t)

    def test_shared_no_tree_disk_layout(self):
        format = self.get_format()
        repo = self.make_repository('.', shared=True, format=format)
        repo.set_make_working_trees(False)
        # we want:
        t = repo.bzrdir.get_repository_transport(None)
        self.check_format(t)
        # XXX: no locks left when unlocked at the moment
        # self.assertEqualDiff('', t.get('lock').read())
        # We should have a 'shared-storage' marker file.
        self.assertEqualDiff('', t.get('shared-storage').read())
        # We should have a marker for the no-working-trees flag.
        self.assertEqualDiff('', t.get('no-working-trees').read())
        # The marker should go when we toggle the setting.
        repo.set_make_working_trees(True)
        self.assertFalse(t.has('no-working-trees'))
        self.check_databases(t)

    def test_adding_revision_creates_pack_indices(self):
        format = self.get_format()
        tree = self.make_branch_and_tree('.', format=format)
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
        self.assertEqual([],
            list(self.index_class(trans, 'pack-names', None).iter_all_entries()))
        tree.commit('foobarbaz')
        index = self.index_class(trans, 'pack-names', None)
        index_nodes = list(index.iter_all_entries())
        self.assertEqual(1, len(index_nodes))
        node = index_nodes[0]
        name = node[1][0]
        # the pack sizes should be listed in the index
        pack_value = node[2]
        sizes = [int(digits) for digits in pack_value.split(' ')]
        for size, suffix in zip(sizes, ['.rix', '.iix', '.tix', '.six']):
            stat = trans.stat('indices/%s%s' % (name, suffix))
            self.assertEqual(size, stat.st_size)

    def test_pulling_nothing_leads_to_no_new_names(self):
        format = self.get_format()
        tree1 = self.make_branch_and_tree('1', format=format)
        tree2 = self.make_branch_and_tree('2', format=format)
        tree1.branch.repository.fetch(tree2.branch.repository)
        trans = tree1.branch.repository.bzrdir.get_repository_transport(None)
        self.assertEqual([],
            list(self.index_class(trans, 'pack-names', None).iter_all_entries()))

    def test_commit_across_pack_shape_boundary_autopacks(self):
        format = self.get_format()
        tree = self.make_branch_and_tree('.', format=format)
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
        # This test could be a little cheaper by replacing the packs
        # attribute on the repository to allow a different pack distribution
        # and max packs policy - so we are checking the policy is honoured
        # in the test. But for now 11 commits is not a big deal in a single
        # test.
        for x in range(9):
            tree.commit('commit %s' % x)
        # there should be 9 packs:
        index = self.index_class(trans, 'pack-names', None)
        self.assertEqual(9, len(list(index.iter_all_entries())))
        # insert some files in obsolete_packs which should be removed by pack.
        trans.put_bytes('obsolete_packs/foo', '123')
        trans.put_bytes('obsolete_packs/bar', '321')
        # committing one more should coalesce to 1 of 10.
        tree.commit('commit triggering pack')
        index = self.index_class(trans, 'pack-names', None)
        self.assertEqual(1, len(list(index.iter_all_entries())))
        # packing should not damage data
        tree = tree.bzrdir.open_workingtree()
        check_result = tree.branch.repository.check(
            [tree.branch.last_revision()])
        nb_files = 5 # .pack, .rix, .iix, .tix, .six
        if tree.branch.repository._format.supports_chks:
            nb_files += 1 # .cix
        # We should have 10 x nb_files files in the obsolete_packs directory.
        obsolete_files = list(trans.list_dir('obsolete_packs'))
        self.assertFalse('foo' in obsolete_files)
        self.assertFalse('bar' in obsolete_files)
        self.assertEqual(10 * nb_files, len(obsolete_files))
        # XXX: Todo check packs obsoleted correctly - old packs and indices
        # in the obsolete_packs directory.
        large_pack_name = list(index.iter_all_entries())[0][1][0]
        # finally, committing again should not touch the large pack.
        tree.commit('commit not triggering pack')
        index = self.index_class(trans, 'pack-names', None)
        self.assertEqual(2, len(list(index.iter_all_entries())))
        pack_names = [node[1][0] for node in index.iter_all_entries()]
        self.assertTrue(large_pack_name in pack_names)

    def test_fail_obsolete_deletion(self):
        # failing to delete obsolete packs is not fatal
        format = self.get_format()
        server = fakenfs.FakeNFSServer()
        server.setUp()
        self.addCleanup(server.tearDown)
        transport = get_transport(server.get_url())
        bzrdir = self.get_format().initialize_on_transport(transport)
        repo = bzrdir.create_repository()
        repo_transport = bzrdir.get_repository_transport(None)
        self.assertTrue(repo_transport.has('obsolete_packs'))
        # these files are in use by another client and typically can't be deleted
        repo_transport.put_bytes('obsolete_packs/.nfsblahblah', 'contents')
        repo._pack_collection._clear_obsolete_packs()
        self.assertTrue(repo_transport.has('obsolete_packs/.nfsblahblah'))

    def test_pack_after_two_commits_packs_everything(self):
        format = self.get_format()
        tree = self.make_branch_and_tree('.', format=format)
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
        tree.commit('start')
        tree.commit('more work')
        tree.branch.repository.pack()
        # there should be 1 pack:
        index = self.index_class(trans, 'pack-names', None)
        self.assertEqual(1, len(list(index.iter_all_entries())))
        self.assertEqual(2, len(tree.branch.repository.all_revision_ids()))

    def test_pack_layout(self):
        # Test that the ordering of revisions in pack repositories is
        # tip->ancestor
        format = self.get_format()
        if type(format.repository_format) is RepositoryFormatCHK1:
            raise TestSkipped("Not updated for GroupCompress internals")
        tree = self.make_branch_and_tree('.', format=format)
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
        tree.commit('start', rev_id='1')
        tree.commit('more work', rev_id='2')
        tree.branch.repository.pack()
        tree.lock_read()
        self.addCleanup(tree.unlock)
        pack = tree.branch.repository._pack_collection.get_pack_by_name(
            tree.branch.repository._pack_collection.names()[0])
        # revision access tends to be tip->ancestor, so ordering that way on
        # disk is a good idea.
        for _1, key, val, refs in pack.revision_index.iter_all_entries():
            if key == ('1',):
                pos_1 = int(val[1:].split()[0])
            else:
                pos_2 = int(val[1:].split()[0])
        self.assertTrue(pos_2 < pos_1)

    def test_pack_repositories_support_multiple_write_locks(self):
        format = self.get_format()
        self.make_repository('.', shared=True, format=format)
        r1 = repository.Repository.open('.')
        r2 = repository.Repository.open('.')
        r1.lock_write()
        self.addCleanup(r1.unlock)
        r2.lock_write()
        r2.unlock()

    def _add_text(self, repo, fileid):
        """Add a text to the repository within a write group."""
        repo.texts.add_lines((fileid, 'samplerev+'+fileid), [],
            ['smaplerev+'+fileid])

    def test_concurrent_writers_merge_new_packs(self):
        format = self.get_format()
        self.make_repository('.', shared=True, format=format)
        r1 = repository.Repository.open('.')
        r2 = repository.Repository.open('.')
        r1.lock_write()
        try:
            # access enough data to load the names list
            list(r1.all_revision_ids())
            r2.lock_write()
            try:
                # access enough data to load the names list
                list(r2.all_revision_ids())
                r1.start_write_group()
                try:
                    r2.start_write_group()
                    try:
                        self._add_text(r1, 'fileidr1')
                        self._add_text(r2, 'fileidr2')
                    except:
                        r2.abort_write_group()
                        raise
                except:
                    r1.abort_write_group()
                    raise
                # both r1 and r2 have open write groups with data in them
                # created while the other's write group was open.
                # Commit both which requires a merge to the pack-names.
                try:
                    r1.commit_write_group()
                except:
                    r1.abort_write_group()
                    r2.abort_write_group()
                    raise
                r2.commit_write_group()
                # tell r1 to reload from disk
                r1._pack_collection.reset()
                # Now both repositories should know about both names
                r1._pack_collection.ensure_loaded()
                r2._pack_collection.ensure_loaded()
                self.assertEqual(r1._pack_collection.names(), r2._pack_collection.names())
                self.assertEqual(2, len(r1._pack_collection.names()))
            finally:
                r2.unlock()
        finally:
            r1.unlock()

    def test_concurrent_writer_second_preserves_dropping_a_pack(self):
        format = self.get_format()
        self.make_repository('.', shared=True, format=format)
        r1 = repository.Repository.open('.')
        r2 = repository.Repository.open('.')
        # add a pack to drop
        r1.lock_write()
        try:
            r1.start_write_group()
            try:
                self._add_text(r1, 'fileidr1')
            except:
                r1.abort_write_group()
                raise
            else:
                r1.commit_write_group()
            r1._pack_collection.ensure_loaded()
            name_to_drop = r1._pack_collection.all_packs()[0].name
        finally:
            r1.unlock()
        r1.lock_write()
        try:
            # access enough data to load the names list
            list(r1.all_revision_ids())
            r2.lock_write()
            try:
                # access enough data to load the names list
                list(r2.all_revision_ids())
                r1._pack_collection.ensure_loaded()
                try:
                    r2.start_write_group()
                    try:
                        # in r1, drop the pack
                        r1._pack_collection._remove_pack_from_memory(
                            r1._pack_collection.get_pack_by_name(name_to_drop))
                        # in r2, add a pack
                        self._add_text(r2, 'fileidr2')
                    except:
                        r2.abort_write_group()
                        raise
                except:
                    r1._pack_collection.reset()
                    raise
                # r1 has a changed names list, and r2 an open write groups with
                # changes.
                # save r1, and then commit the r2 write group, which requires a
                # merge to the pack-names, which should not reinstate
                # name_to_drop
                try:
                    r1._pack_collection._save_pack_names()
                    r1._pack_collection.reset()
                except:
                    r2.abort_write_group()
                    raise
                try:
                    r2.commit_write_group()
                except:
                    r2.abort_write_group()
                    raise
                # Now both repositories should now about just one name.
                r1._pack_collection.ensure_loaded()
                r2._pack_collection.ensure_loaded()
                self.assertEqual(r1._pack_collection.names(), r2._pack_collection.names())
                self.assertEqual(1, len(r1._pack_collection.names()))
                self.assertFalse(name_to_drop in r1._pack_collection.names())
            finally:
                r2.unlock()
        finally:
            r1.unlock()

    def test_concurrent_pack_triggers_reload(self):
        # create 2 packs, which we will then collapse
        tree = self.make_branch_and_tree('tree')
        tree.lock_write()
        try:
            rev1 = tree.commit('one')
            rev2 = tree.commit('two')
            r2 = repository.Repository.open('tree')
            r2.lock_read()
            try:
                # Now r2 has read the pack-names file, but will need to reload
                # it after r1 has repacked
                tree.branch.repository.pack()
                self.assertEqual({rev2:(rev1,)}, r2.get_parent_map([rev2]))
            finally:
                r2.unlock()
        finally:
            tree.unlock()

    def test_concurrent_pack_during_get_record_reloads(self):
        tree = self.make_branch_and_tree('tree')
        tree.lock_write()
        try:
            rev1 = tree.commit('one')
            rev2 = tree.commit('two')
            keys = [(rev1,), (rev2,)]
            r2 = repository.Repository.open('tree')
            r2.lock_read()
            try:
                # At this point, we will start grabbing a record stream, and
                # trigger a repack mid-way
                packed = False
                result = {}
                record_stream = r2.revisions.get_record_stream(keys,
                                    'unordered', False)
                for record in record_stream:
                    result[record.key] = record
                    if not packed:
                        tree.branch.repository.pack()
                        packed = True
                # The first record will be found in the original location, but
                # after the pack, we have to reload to find the next record
                self.assertEqual(sorted(keys), sorted(result.keys()))
            finally:
                r2.unlock()
        finally:
            tree.unlock()

    def test_lock_write_does_not_physically_lock(self):
        repo = self.make_repository('.', format=self.get_format())
        repo.lock_write()
        self.addCleanup(repo.unlock)
        self.assertFalse(repo.get_physical_lock_status())

    def prepare_for_break_lock(self):
        # Setup the global ui factory state so that a break-lock method call
        # will find usable input in the input stream.
        old_factory = ui.ui_factory
        def restoreFactory():
            ui.ui_factory = old_factory
        self.addCleanup(restoreFactory)
        ui.ui_factory = ui.SilentUIFactory()
        ui.ui_factory.stdin = StringIO("y\n")

    def test_break_lock_breaks_physical_lock(self):
        repo = self.make_repository('.', format=self.get_format())
        repo._pack_collection.lock_names()
        repo.control_files.leave_in_place()
        repo.unlock()
        repo2 = repository.Repository.open('.')
        self.assertTrue(repo.get_physical_lock_status())
        self.prepare_for_break_lock()
        repo2.break_lock()
        self.assertFalse(repo.get_physical_lock_status())

    def test_broken_physical_locks_error_on__unlock_names_lock(self):
        repo = self.make_repository('.', format=self.get_format())
        repo._pack_collection.lock_names()
        self.assertTrue(repo.get_physical_lock_status())
        repo2 = repository.Repository.open('.')
        self.prepare_for_break_lock()
        repo2.break_lock()
        self.assertRaises(errors.LockBroken, repo._pack_collection._unlock_names)

    def test_fetch_without_find_ghosts_ignores_ghosts(self):
        # we want two repositories at this point:
        # one with a revision that is a ghost in the other
        # repository.
        # 'ghost' is present in has_ghost, 'ghost' is absent in 'missing_ghost'.
        # 'references' is present in both repositories, and 'tip' is present
        # just in has_ghost.
        # has_ghost       missing_ghost
        #------------------------------
        # 'ghost'             -
        # 'references'    'references'
        # 'tip'               -
        # In this test we fetch 'tip' which should not fetch 'ghost'
        has_ghost = self.make_repository('has_ghost', format=self.get_format())
        missing_ghost = self.make_repository('missing_ghost',
            format=self.get_format())

        def add_commit(repo, revision_id, parent_ids):
            repo.lock_write()
            repo.start_write_group()
            inv = inventory.Inventory(revision_id=revision_id)
            inv.root.revision = revision_id
            root_id = inv.root.file_id
            sha1 = repo.add_inventory(revision_id, inv, [])
            repo.texts.add_lines((root_id, revision_id), [], [])
            rev = _mod_revision.Revision(timestamp=0,
                                         timezone=None,
                                         committer="Foo Bar <foo@example.com>",
                                         message="Message",
                                         inventory_sha1=sha1,
                                         revision_id=revision_id)
            rev.parent_ids = parent_ids
            repo.add_revision(revision_id, rev)
            repo.commit_write_group()
            repo.unlock()
        add_commit(has_ghost, 'ghost', [])
        add_commit(has_ghost, 'references', ['ghost'])
        add_commit(missing_ghost, 'references', ['ghost'])
        add_commit(has_ghost, 'tip', ['references'])
        missing_ghost.fetch(has_ghost, 'tip')
        # missing ghost now has tip and not ghost.
        rev = missing_ghost.get_revision('tip')
        inv = missing_ghost.get_inventory('tip')
        self.assertRaises(errors.NoSuchRevision,
            missing_ghost.get_revision, 'ghost')
        self.assertRaises(errors.NoSuchRevision,
            missing_ghost.get_inventory, 'ghost')

    def make_write_ready_repo(self):
        repo = self.make_repository('.', format=self.get_format())
        repo.lock_write()
        repo.start_write_group()
        return repo

    def test_missing_inventories_compression_parent_prevents_commit(self):
        repo = self.make_write_ready_repo()
        key = ('junk',)
        if not getattr(repo.inventories._index, '_missing_compression_parents',
            None):
            raise TestSkipped("No missing compression parents")
        repo.inventories._index._missing_compression_parents.add(key)
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
        repo.abort_write_group()
        repo.unlock()

    def test_missing_revisions_compression_parent_prevents_commit(self):
        repo = self.make_write_ready_repo()
        key = ('junk',)
        if not getattr(repo.inventories._index, '_missing_compression_parents',
            None):
            raise TestSkipped("No missing compression parents")
        repo.revisions._index._missing_compression_parents.add(key)
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
        repo.abort_write_group()
        repo.unlock()

    def test_missing_signatures_compression_parent_prevents_commit(self):
        repo = self.make_write_ready_repo()
        key = ('junk',)
        if not getattr(repo.inventories._index, '_missing_compression_parents',
            None):
            raise TestSkipped("No missing compression parents")
        repo.signatures._index._missing_compression_parents.add(key)
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
        repo.abort_write_group()
        repo.unlock()

    def test_missing_text_compression_parent_prevents_commit(self):
        repo = self.make_write_ready_repo()
        key = ('some', 'junk')
        if not getattr(repo.inventories._index, '_missing_compression_parents',
            None):
            raise TestSkipped("No missing compression parents")
        repo.texts._index._missing_compression_parents.add(key)
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
        e = self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
        repo.abort_write_group()
        repo.unlock()

    def test_supports_external_lookups(self):
        repo = self.make_repository('.', format=self.get_format())
        self.assertEqual(self.format_supports_external_lookups,
            repo._format.supports_external_lookups)

    def test_abort_write_group_does_not_raise_when_suppressed(self):
        """Similar to per_repository.test_write_group's test of the same name.

        Also requires that the exception is logged.
        """
        self.vfs_transport_factory = memory.MemoryServer
        repo = self.make_repository('repo')
        token = repo.lock_write()
        self.addCleanup(repo.unlock)
        repo.start_write_group()
        # Damage the repository on the filesystem
        self.get_transport('').rename('repo', 'foo')
        # abort_write_group will not raise an error
        self.assertEqual(None, repo.abort_write_group(suppress_errors=True))
        # But it does log an error
        log_file = self._get_log(keep_log_file=True)
        self.assertContainsRe(log_file, 'abort_write_group failed')
        self.assertContainsRe(log_file, r'INFO  bzr: ERROR \(ignored\):')
        if token is not None:
            repo.leave_lock_in_place()

    def test_abort_write_group_does_raise_when_not_suppressed(self):
        self.vfs_transport_factory = memory.MemoryServer
        repo = self.make_repository('repo')
        token = repo.lock_write()
        self.addCleanup(repo.unlock)
        repo.start_write_group()
        # Damage the repository on the filesystem
        self.get_transport('').rename('repo', 'foo')
        # abort_write_group will not raise an error
        self.assertRaises(Exception, repo.abort_write_group)
        if token is not None:
            repo.leave_lock_in_place()

    def test_suspend_write_group(self):
        self.vfs_transport_factory = memory.MemoryServer
        repo = self.make_repository('repo')
        token = repo.lock_write()
        self.addCleanup(repo.unlock)
        repo.start_write_group()
        repo.texts.add_lines(('file-id', 'revid'), (), ['lines'])
        wg_tokens = repo.suspend_write_group()
        expected_pack_name = wg_tokens[0] + '.pack'
        upload_transport = repo._pack_collection._upload_transport
        limbo_files = upload_transport.list_dir('')
        self.assertTrue(expected_pack_name in limbo_files, limbo_files)
        md5 = osutils.md5(upload_transport.get_bytes(expected_pack_name))
        self.assertEqual(wg_tokens[0], md5.hexdigest())

    def test_resume_write_group_then_abort(self):
        # Create a repo, start a write group, insert some data, suspend.
        self.vfs_transport_factory = memory.MemoryServer
        repo = self.make_repository('repo')
        token = repo.lock_write()
        self.addCleanup(repo.unlock)
        repo.start_write_group()
        text_key = ('file-id', 'revid')
        repo.texts.add_lines(text_key, (), ['lines'])
        wg_tokens = repo.suspend_write_group()
        # Get a fresh repository object for the repo on the filesystem.
        same_repo = repo.bzrdir.open_repository()
        # Resume
        same_repo.lock_write()
        self.addCleanup(same_repo.unlock)
        same_repo.resume_write_group(wg_tokens)
        same_repo.abort_write_group()
        self.assertEqual(
            [], same_repo._pack_collection._upload_transport.list_dir(''))
        self.assertEqual(
            [], same_repo._pack_collection._pack_transport.list_dir(''))

    def test_resume_malformed_token(self):
        self.vfs_transport_factory = memory.MemoryServer
        # Make a repository with a suspended write group
        repo = self.make_repository('repo')
        token = repo.lock_write()
        self.addCleanup(repo.unlock)
        repo.start_write_group()
        text_key = ('file-id', 'revid')
        repo.texts.add_lines(text_key, (), ['lines'])
        wg_tokens = repo.suspend_write_group()
        # Make a new repository
        new_repo = self.make_repository('new_repo')
        token = new_repo.lock_write()
        self.addCleanup(new_repo.unlock)
        hacked_wg_token = (
            '../../../../repo/.bzr/repository/upload/' + wg_tokens[0])
        self.assertRaises(
            errors.UnresumableWriteGroup,
            new_repo.resume_write_group, [hacked_wg_token])


class TestPackRepositoryStacking(TestCaseWithTransport):

    """Tests for stacking pack repositories"""

    def setUp(self):
        if not self.format_supports_external_lookups:
            raise TestNotApplicable("%r doesn't support stacking"
                % (self.format_name,))
        super(TestPackRepositoryStacking, self).setUp()

    def get_format(self):
        return bzrdir.format_registry.make_bzrdir(self.format_name)

    def test_stack_checks_rich_root_compatibility(self):
        # early versions of the packing code relied on pack internals to
        # stack, but the current version should be able to stack on any
        # format.
        #
        # TODO: Possibly this should be run per-repository-format and raise
        # TestNotApplicable on formats that don't support stacking. -- mbp
        # 20080729
        repo = self.make_repository('repo', format=self.get_format())
        if repo.supports_rich_root():
            # can only stack on repositories that have compatible internal
            # metadata
            if getattr(repo._format, 'supports_tree_reference', False):
                if repo._format.supports_chks:
                    matching_format_name = 'development6-rich-root'
                else:
                    matching_format_name = 'pack-0.92-subtree'
            else:
                matching_format_name = 'rich-root-pack'
            mismatching_format_name = 'pack-0.92'
        else:
            # We don't have a non-rich-root CHK format.
            if repo._format.supports_chks:
                raise AssertionError("no non-rich-root CHK formats known")
            else:
                matching_format_name = 'pack-0.92'
            mismatching_format_name = 'pack-0.92-subtree'
        base = self.make_repository('base', format=matching_format_name)
        repo.add_fallback_repository(base)
        # you can't stack on something with incompatible data
        bad_repo = self.make_repository('mismatch',
            format=mismatching_format_name)
        e = self.assertRaises(errors.IncompatibleRepositories,
            repo.add_fallback_repository, bad_repo)
        self.assertContainsRe(str(e),
            r'(?m)KnitPackRepository.*/mismatch/.*\nis not compatible with\n'
            r'.*Repository.*/repo/.*\n'
            r'different rich-root support')

    def test_stack_checks_serializers_compatibility(self):
        repo = self.make_repository('repo', format=self.get_format())
        if getattr(repo._format, 'supports_tree_reference', False):
            # can only stack on repositories that have compatible internal
            # metadata
            if repo._format.supports_chks:
                # No CHK subtree formats in bzr.dev, so this doesn't execute.
                matching_format_name = 'development6-subtree'
            else:
                matching_format_name = 'pack-0.92-subtree'
            mismatching_format_name = 'rich-root-pack'
        else:
            if repo.supports_rich_root():
                matching_format_name = 'rich-root-pack'
                mismatching_format_name = 'pack-0.92-subtree'
            else:
                raise TestNotApplicable('No formats use non-v5 serializer'
                    ' without having rich-root also set')
        base = self.make_repository('base', format=matching_format_name)
        repo.add_fallback_repository(base)
        # you can't stack on something with incompatible data
        bad_repo = self.make_repository('mismatch',
            format=mismatching_format_name)
        e = self.assertRaises(errors.IncompatibleRepositories,
            repo.add_fallback_repository, bad_repo)
        self.assertContainsRe(str(e),
            r'(?m)KnitPackRepository.*/mismatch/.*\nis not compatible with\n'
            r'.*Repository.*/repo/.*\n'
            r'different serializers')

    def test_adding_pack_does_not_record_pack_names_from_other_repositories(self):
        base = self.make_branch_and_tree('base', format=self.get_format())
        base.commit('foo')
        referencing = self.make_branch_and_tree('repo', format=self.get_format())
        referencing.branch.repository.add_fallback_repository(base.branch.repository)
        referencing.commit('bar')
        new_instance = referencing.bzrdir.open_repository()
        new_instance.lock_read()
        self.addCleanup(new_instance.unlock)
        new_instance._pack_collection.ensure_loaded()
        self.assertEqual(1, len(new_instance._pack_collection.all_packs()))

    def test_autopack_only_considers_main_repo_packs(self):
        format = self.get_format()
        base = self.make_branch_and_tree('base', format=format)
        base.commit('foo')
        tree = self.make_branch_and_tree('repo', format=format)
        tree.branch.repository.add_fallback_repository(base.branch.repository)
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
        # This test could be a little cheaper by replacing the packs
        # attribute on the repository to allow a different pack distribution
        # and max packs policy - so we are checking the policy is honoured
        # in the test. But for now 11 commits is not a big deal in a single
        # test.
        for x in range(9):
            tree.commit('commit %s' % x)
        # there should be 9 packs:
        index = self.index_class(trans, 'pack-names', None)
        self.assertEqual(9, len(list(index.iter_all_entries())))
        # committing one more should coalesce to 1 of 10.
        tree.commit('commit triggering pack')
        index = self.index_class(trans, 'pack-names', None)
        self.assertEqual(1, len(list(index.iter_all_entries())))
        # packing should not damage data
        tree = tree.bzrdir.open_workingtree()
        check_result = tree.branch.repository.check(
            [tree.branch.last_revision()])
        nb_files = 5 # .pack, .rix, .iix, .tix, .six
        if tree.branch.repository._format.supports_chks:
            nb_files += 1 # .cix
        # We should have 10 x nb_files files in the obsolete_packs directory.
        obsolete_files = list(trans.list_dir('obsolete_packs'))
        self.assertFalse('foo' in obsolete_files)
        self.assertFalse('bar' in obsolete_files)
        self.assertEqual(10 * nb_files, len(obsolete_files))
        # XXX: Todo check packs obsoleted correctly - old packs and indices
        # in the obsolete_packs directory.
        large_pack_name = list(index.iter_all_entries())[0][1][0]
        # finally, committing again should not touch the large pack.
        tree.commit('commit not triggering pack')
        index = self.index_class(trans, 'pack-names', None)
        self.assertEqual(2, len(list(index.iter_all_entries())))
        pack_names = [node[1][0] for node in index.iter_all_entries()]
        self.assertTrue(large_pack_name in pack_names)


class TestSmartServerAutopack(TestCaseWithTransport):

    def setUp(self):
        super(TestSmartServerAutopack, self).setUp()
        # Create a smart server that publishes whatever the backing VFS server
        # does.
        self.smart_server = server.SmartTCPServer_for_testing()
        self.smart_server.setUp(self.get_server())
        self.addCleanup(self.smart_server.tearDown)
        # Log all HPSS calls into self.hpss_calls.
        client._SmartClient.hooks.install_named_hook(
            'call', self.capture_hpss_call, None)
        self.hpss_calls = []

    def capture_hpss_call(self, params):
        self.hpss_calls.append(params.method)

    def get_format(self):
        return bzrdir.format_registry.make_bzrdir(self.format_name)

    def test_autopack_or_streaming_rpc_is_used_when_using_hpss(self):
        # Make local and remote repos
        format = self.get_format()
        tree = self.make_branch_and_tree('local', format=format)
        self.make_branch_and_tree('remote', format=format)
        remote_branch_url = self.smart_server.get_url() + 'remote'
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
        # Make 9 local revisions, and push them one at a time to the remote
        # repo to produce 9 pack files.
        for x in range(9):
            tree.commit('commit %s' % x)
            tree.branch.push(remote_branch)
        # Make one more push to trigger an autopack
        self.hpss_calls = []
        tree.commit('commit triggering pack')
        tree.branch.push(remote_branch)
        autopack_calls = len([call for call in self.hpss_calls if call ==
            'PackRepository.autopack'])
        streaming_calls = len([call for call in self.hpss_calls if call ==
            'Repository.insert_stream'])
        if autopack_calls:
            # Non streaming server
            self.assertEqual(1, autopack_calls)
            self.assertEqual(0, streaming_calls)
        else:
            # Streaming was used, which autopacks on the remote end.
            self.assertEqual(0, autopack_calls)
            # NB: The 2 calls are because of the sanity check that the server
            # supports the verb (see remote.py:RemoteSink.insert_stream for
            # details).
            self.assertEqual(2, streaming_calls)


def load_tests(basic_tests, module, loader):
    # these give the bzrdir canned format name, and the repository on-disk
    # format string
    scenarios_params = [
         dict(format_name='pack-0.92',
              format_string="Bazaar pack repository format 1 (needs bzr 0.92)\n",
              format_supports_external_lookups=False,
              index_class=GraphIndex),
         dict(format_name='pack-0.92-subtree',
              format_string="Bazaar pack repository format 1 "
              "with subtree support (needs bzr 0.92)\n",
              format_supports_external_lookups=False,
              index_class=GraphIndex),
         dict(format_name='1.6',
              format_string="Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n",
              format_supports_external_lookups=True,
              index_class=GraphIndex),
         dict(format_name='1.6.1-rich-root',
              format_string="Bazaar RepositoryFormatKnitPack5RichRoot "
                  "(bzr 1.6.1)\n",
              format_supports_external_lookups=True,
              index_class=GraphIndex),
         dict(format_name='1.9',
              format_string="Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n",
              format_supports_external_lookups=True,
              index_class=BTreeGraphIndex),
         dict(format_name='1.9-rich-root',
              format_string="Bazaar RepositoryFormatKnitPack6RichRoot "
                  "(bzr 1.9)\n",
              format_supports_external_lookups=True,
              index_class=BTreeGraphIndex),
         dict(format_name='development6-rich-root',
              format_string='Bazaar development format - group compression '
                  'and chk inventory (needs bzr.dev from 1.14)\n',
              format_supports_external_lookups=False,
              index_class=BTreeGraphIndex),
         ]
    # name of the scenario is the format name
    scenarios = [(s['format_name'], s) for s in scenarios_params]
    return tests.multiply_tests(basic_tests, scenarios, loader.suiteClass())