~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
# Copyright (C) 2006, 2007, 2008, 2009 Canonical Ltd
# Authors: Aaron Bentley
#
# 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


import sys
from cStringIO import StringIO

from bzrlib import (
    branch,
    bzrdir,
    merge_directive,
    tests,
    )
from bzrlib.bundle import serializer


def load_tests(standard_tests, module, loader):
    """Multiply tests for the send command."""
    result = loader.suiteClass()

    # one for each king of change
    changes_tests, remaining_tests = tests.split_suite_by_condition(
        standard_tests, tests.condition_isinstance((
                TestSendStrictWithChanges,
                )))
    changes_scenarios = [
        ('uncommitted',
         dict(_changes_type='_uncommitted_changes')),
        ('pending_merges',
         dict(_changes_type='_pending_merges')),
        ('out-of-sync-trees',
         dict(_changes_type='_out_of_sync_trees')),
        ]
    tests.multiply_tests(changes_tests, changes_scenarios, result)
    # No parametrization for the remaining tests
    result.addTests(remaining_tests)

    return result


class TestSendMixin(object):

    _default_command = ['send', '-o-']
    _default_wd = 'branch'

    def run_send(self, args, cmd=None, rc=0, wd=None, err_re=None):
        if cmd is None: cmd = self._default_command
        if wd is None: wd = self._default_wd
        if err_re is None: err_re = []
        return self.run_bzr(cmd + args, retcode=rc,
                            working_dir=wd,
                            error_regexes=err_re)

    def get_MD(self, args, cmd=None, wd='branch'):
        out = StringIO(self.run_send(args, cmd=cmd, wd=wd)[0])
        return merge_directive.MergeDirective.from_lines(out.readlines())

    def assertBundleContains(self, revs, args, cmd=None, wd='branch'):
        md = self.get_MD(args, cmd=cmd, wd=wd)
        br = serializer.read_bundle(StringIO(md.get_raw_bundle()))
        self.assertEqual(set(revs), set(r.revision_id for r in br.revisions))


class TestSend(tests.TestCaseWithTransport, TestSendMixin):

    def setUp(self):
        super(TestSend, self).setUp()
        grandparent_tree = bzrdir.BzrDir.create_standalone_workingtree(
            'grandparent')
        self.build_tree_contents([('grandparent/file1', 'grandparent')])
        grandparent_tree.add('file1')
        grandparent_tree.commit('initial commit', rev_id='rev1')

        parent_bzrdir = grandparent_tree.bzrdir.sprout('parent')
        parent_tree = parent_bzrdir.open_workingtree()
        parent_tree.commit('next commit', rev_id='rev2')

        branch_tree = parent_tree.bzrdir.sprout('branch').open_workingtree()
        self.build_tree_contents([('branch/file1', 'branch')])
        branch_tree.commit('last commit', rev_id='rev3')

    def assertFormatIs(self, fmt_string, md):
        self.assertEqual(fmt_string, md.get_raw_bundle().splitlines()[0])

    def test_uses_parent(self):
        """Parent location is used as a basis by default"""
        errmsg = self.run_send([], rc=3, wd='grandparent')[1]
        self.assertContainsRe(errmsg, 'No submit branch known or specified')
        stdout, stderr = self.run_send([])
        self.assertEqual(stderr.count('Using saved parent location'), 1)
        self.assertBundleContains(['rev3'], [])

    def test_bundle(self):
        """Bundle works like send, except -o is not required"""
        errmsg = self.run_send([], cmd=['bundle'], rc=3, wd='grandparent')[1]
        self.assertContainsRe(errmsg, 'No submit branch known or specified')
        stdout, stderr = self.run_send([], cmd=['bundle'])
        self.assertEqual(stderr.count('Using saved parent location'), 1)
        self.assertBundleContains(['rev3'], [], cmd=['bundle'])

    def test_uses_submit(self):
        """Submit location can be used and set"""
        self.assertBundleContains(['rev3'], [])
        self.assertBundleContains(['rev3', 'rev2'], ['../grandparent'])
        # submit location should be auto-remembered
        self.assertBundleContains(['rev3', 'rev2'], [])

        self.run_send(['../parent'])
        # We still point to ../grandparent
        self.assertBundleContains(['rev3', 'rev2'], [])
        # Remember parent now
        self.run_send(['../parent', '--remember'])
        # Now we point to parent
        self.assertBundleContains(['rev3'], [])

        err = self.run_send(['--remember'], rc=3)[1]
        self.assertContainsRe(err,
                              '--remember requires a branch to be specified.')

    def test_revision_branch_interaction(self):
        self.assertBundleContains(['rev3', 'rev2'], ['../grandparent'])
        self.assertBundleContains(['rev2'], ['../grandparent', '-r-2'])
        self.assertBundleContains(['rev3', 'rev2'],
                                  ['../grandparent', '-r-2..-1'])
        md = self.get_MD(['-r-2..-1'])
        self.assertEqual('rev2', md.base_revision_id)
        self.assertEqual('rev3', md.revision_id)

    def test_output(self):
        # check output for consistency
        # win32 stdout converts LF to CRLF,
        # which would break patch-based bundles
        self.assertBundleContains(['rev3'], [])

    def test_no_common_ancestor(self):
        foo = self.make_branch_and_tree('foo')
        foo.commit('rev a')
        bar = self.make_branch_and_tree('bar')
        bar.commit('rev b')
        self.run_send(['--from', 'foo', '../bar'], wd='foo')

    def test_content_options(self):
        """--no-patch and --no-bundle should work and be independant"""
        md = self.get_MD([])
        self.assertIsNot(None, md.bundle)
        self.assertIsNot(None, md.patch)

        md = self.get_MD(['--format=0.9'])
        self.assertIsNot(None, md.bundle)
        self.assertIsNot(None, md.patch)

        md = self.get_MD(['--no-patch'])
        self.assertIsNot(None, md.bundle)
        self.assertIs(None, md.patch)
        self.run_bzr_error(['Format 0.9 does not permit bundle with no patch'],
                           ['send', '--no-patch', '--format=0.9', '-o-'],
                           working_dir='branch')
        md = self.get_MD(['--no-bundle', '.', '.'])
        self.assertIs(None, md.bundle)
        self.assertIsNot(None, md.patch)

        md = self.get_MD(['--no-bundle', '--format=0.9', '../parent',
                                  '.'])
        self.assertIs(None, md.bundle)
        self.assertIsNot(None, md.patch)

        md = self.get_MD(['--no-bundle', '--no-patch', '.', '.'])
        self.assertIs(None, md.bundle)
        self.assertIs(None, md.patch)

        md = self.get_MD(['--no-bundle', '--no-patch', '--format=0.9',
                          '../parent', '.'])
        self.assertIs(None, md.bundle)
        self.assertIs(None, md.patch)

    def test_from_option(self):
        self.run_bzr('send', retcode=3)
        md = self.get_MD(['--from', 'branch'])
        self.assertEqual('rev3', md.revision_id)
        md = self.get_MD(['-f', 'branch'])
        self.assertEqual('rev3', md.revision_id)

    def test_output_option(self):
        stdout = self.run_bzr('send -f branch --output file1')[0]
        self.assertEqual('', stdout)
        md_file = open('file1', 'rb')
        self.addCleanup(md_file.close)
        self.assertContainsRe(md_file.read(), 'rev3')
        stdout = self.run_bzr('send -f branch --output -')[0]
        self.assertContainsRe(stdout, 'rev3')

    def test_note_revisions(self):
        stderr = self.run_send([])[1]
        self.assertEndsWith(stderr, '\nBundling 1 revision(s).\n')

    def test_mailto_option(self):
        b = branch.Branch.open('branch')
        b.get_config().set_user_option('mail_client', 'editor')
        self.run_bzr_error(
            ('No mail-to address \\(--mail-to\\) or output \\(-o\\) specified',
            ), 'send -f branch')
        b.get_config().set_user_option('mail_client', 'bogus')
        self.run_send([])
        self.run_bzr_error(('Unknown mail client: bogus',),
                           'send -f branch --mail-to jrandom@example.org')
        b.get_config().set_user_option('submit_to', 'jrandom@example.org')
        self.run_bzr_error(('Unknown mail client: bogus',),
                           'send -f branch')

    def test_mailto_child_option(self):
        """Make sure that child_submit_to is used."""
        b = branch.Branch.open('branch')
        b.get_config().set_user_option('mail_client', 'bogus')
        parent = branch.Branch.open('parent')
        parent.get_config().set_user_option('child_submit_to',
                           'somebody@example.org')
        self.run_bzr_error(('Unknown mail client: bogus',),
                           'send -f branch')

    def test_format(self):
        md = self.get_MD(['--format=4'])
        self.assertIs(merge_directive.MergeDirective2, md.__class__)
        self.assertFormatIs('# Bazaar revision bundle v4', md)

        md = self.get_MD(['--format=0.9'])
        self.assertFormatIs('# Bazaar revision bundle v0.9', md)

        md = self.get_MD(['--format=0.9'], cmd=['bundle'])
        self.assertFormatIs('# Bazaar revision bundle v0.9', md)
        self.assertIs(merge_directive.MergeDirective, md.__class__)

        self.run_bzr_error(['Bad value .* for option .format.'],
                            'send -f branch -o- --format=0.999')[0]

    def test_format_child_option(self):
        parent_config = branch.Branch.open('parent').get_config()
        parent_config.set_user_option('child_submit_format', '4')
        md = self.get_MD([])
        self.assertIs(merge_directive.MergeDirective2, md.__class__)

        parent_config.set_user_option('child_submit_format', '0.9')
        md = self.get_MD([])
        self.assertFormatIs('# Bazaar revision bundle v0.9', md)

        md = self.get_MD([], cmd=['bundle'])
        self.assertFormatIs('# Bazaar revision bundle v0.9', md)
        self.assertIs(merge_directive.MergeDirective, md.__class__)

        parent_config.set_user_option('child_submit_format', '0.999')
        self.run_bzr_error(["No such send format '0.999'"],
                            'send -f branch -o-')[0]

    def test_message_option(self):
        self.run_bzr('send', retcode=3)
        md = self.get_MD([])
        self.assertIs(None, md.message)
        md = self.get_MD(['-m', 'my message'])
        self.assertEqual('my message', md.message)

    def test_omitted_revision(self):
        md = self.get_MD(['-r-2..'])
        self.assertEqual('rev2', md.base_revision_id)
        self.assertEqual('rev3', md.revision_id)
        md = self.get_MD(['-r..3', '--from', 'branch', 'grandparent'], wd='.')
        self.assertEqual('rev1', md.base_revision_id)
        self.assertEqual('rev3', md.revision_id)

    def test_nonexistant_branch(self):
        if sys.platform == "win32":
            location = "C:/i/do/not/exist/"
        else:
            location = "/i/do/not/exist/"
        out, err = self.run_bzr(["send", "--from", location], retcode=3)
        self.assertEqual(out, '')
        self.assertEqual(err, 'bzr: ERROR: Not a branch: "%s".\n' % location)


class TestSendStrictMixin(TestSendMixin):

    def make_parent_and_local_branches(self):
        # Create a 'parent' branch as the base
        self.parent_tree = bzrdir.BzrDir.create_standalone_workingtree('parent')
        self.build_tree_contents([('parent/file', 'parent')])
        self.parent_tree.add('file')
        self.parent_tree.commit('first commit', rev_id='parent')
        # Branch 'local' from parent and do a change
        local_bzrdir = self.parent_tree.bzrdir.sprout('local')
        self.local_tree = local_bzrdir.open_workingtree()
        self.build_tree_contents([('local/file', 'local')])
        self.local_tree.commit('second commit', rev_id='local')

    _default_command = ['send', '-o-', '../parent']
    _default_wd = 'local'
    _default_sent_revs = ['local']
    _default_errors = ['Working tree ".*/local/" has uncommitted '
                       'changes \(See bzr status\)\.',]

    def set_config_send_strict(self, value):
        # set config var (any of bazaar.conf, locations.conf, branch.conf
        # should do)
        conf = self.local_tree.branch.get_config()
        conf.set_user_option('send_strict', value)

    def assertSendFails(self, args):
        self.run_send(args, rc=3, err_re=self._default_errors)

    def assertSendSucceeds(self, args, revs=None):
        if revs is None:
            revs = self._default_sent_revs
        out, err = self.run_send(args)
        self.assertEquals(
            'Bundling %d revision(s).\n' % len(revs), err)
        md = merge_directive.MergeDirective.from_lines(
                StringIO(out).readlines())
        self.assertEqual('parent', md.base_revision_id)
        br = serializer.read_bundle(StringIO(md.get_raw_bundle()))
        self.assertEqual(set(revs), set(r.revision_id for r in br.revisions))


class TestSendStrictWithoutChanges(tests.TestCaseWithTransport,
                                   TestSendStrictMixin):

    def setUp(self):
        super(TestSendStrictWithoutChanges, self).setUp()
        self.make_parent_and_local_branches()

    def test_send_default(self):
        self.assertSendSucceeds([])

    def test_send_strict(self):
        self.assertSendSucceeds(['--strict'])

    def test_send_no_strict(self):
        self.assertSendSucceeds(['--no-strict'])

    def test_send_config_var_strict(self):
        self.set_config_send_strict('true')
        self.assertSendSucceeds([])

    def test_send_config_var_no_strict(self):
        self.set_config_send_strict('false')
        self.assertSendSucceeds([])


class TestSendStrictWithChanges(tests.TestCaseWithTransport,
                                   TestSendStrictMixin):

    _changes_type = None # Set by load_tests

    def setUp(self):
        super(TestSendStrictWithChanges, self).setUp()
        # load tests set _changes_types to the name of the method we want to
        # call now
        do_changes_func = getattr(self, self._changes_type)
        do_changes_func()

    def _uncommitted_changes(self):
        self.make_parent_and_local_branches()
        # Make a change without committing it
        self.build_tree_contents([('local/file', 'modified')])

    def _pending_merges(self):
        self.make_parent_and_local_branches()
        # Create 'other' branch containing a new file
        other_bzrdir = self.parent_tree.bzrdir.sprout('other')
        other_tree = other_bzrdir.open_workingtree()
        self.build_tree_contents([('other/other-file', 'other')])
        other_tree.add('other-file')
        other_tree.commit('other commit', rev_id='other')
        # Merge and revert, leaving a pending merge
        self.local_tree.merge_from_branch(other_tree.branch)
        self.local_tree.revert(filenames=['other-file'], backups=False)

    def _out_of_sync_trees(self):
        self.make_parent_and_local_branches()
        self.run_bzr(['checkout', '--lightweight', 'local', 'checkout'])
        # Make a change and commit it
        self.build_tree_contents([('local/file', 'modified in local')])
        self.local_tree.commit('modify file', rev_id='modified-in-local')
        # Exercise commands from the checkout directory
        self._default_wd = 'checkout'
        self._default_errors = ["Working tree is out of date, please run"
                                " 'bzr update'\.",]
        self._default_sent_revs = ['modified-in-local', 'local']

    def test_send_default(self):
        self.assertSendFails([])

    def test_send_with_revision(self):
        self.assertSendSucceeds(['-r', 'revid:local'], revs=['local'])

    def test_send_no_strict(self):
        self.assertSendSucceeds(['--no-strict'])

    def test_send_strict_with_changes(self):
        self.assertSendFails(['--strict'])

    def test_send_respect_config_var_strict(self):
        self.set_config_send_strict('true')
        self.assertSendFails([])
        self.assertSendSucceeds(['--no-strict'])


    def test_send_bogus_config_var_ignored(self):
        self.set_config_send_strict("I'm unsure")
        self.assertSendFails([])


    def test_send_no_strict_command_line_override_config(self):
        self.set_config_send_strict('true')
        self.assertSendFails([])
        self.assertSendSucceeds(['--no-strict'])

    def test_push_strict_command_line_override_config(self):
        self.set_config_send_strict('false')
        self.assertSendSucceeds([])
        self.assertSendFails(['--strict'])


class TestBundleStrictWithoutChanges(TestSendStrictWithoutChanges):

    _default_command = ['bundle-revisions', '../parent']