/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2006-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
16
17
18
"""Tests for the commit CLI of bzr."""
19
5765.1.3 by John Arbash Meinel
We missed a test case that was asserting the old string.
20
import doctest
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
21
import os
5167.1.1 by Parth Malwankar
commit command can now accept message (-m) same as a unicode filename
22
import re
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
23
import sys
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
24
5765.1.3 by John Arbash Meinel
We missed a test case that was asserting the old string.
25
from testtools.matchers import DocTestMatches
26
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
27
from bzrlib import (
5609.31.1 by mbp at sourcefrog
Blackbox tests for no identity set must disable whoami inference
28
    config,
2846.2.1 by Alexander Belchenko
merge approved chunks
29
    osutils,
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
30
    ignores,
3825.2.2 by Jelmer Vernooij
Add blackbox test for commit hook templates.
31
    msgeditor,
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
32
    )
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
33
from bzrlib.bzrdir import BzrDir
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
34
from bzrlib.tests import (
5777.6.5 by Jelmer Vernooij
Add tests for lossy commit.
35
    test_foreign,
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
36
    features,
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
37
    )
5283.4.5 by Martin Pool
Update remaining subclasses of ExternalBase
38
from bzrlib.tests import TestCaseWithTransport
39
40
41
class TestCommit(TestCaseWithTransport):
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
42
1616.1.3 by Martin Pool
Clean up cut&pasted test for verbose commit
43
    def test_05_empty_commit(self):
44
        """Commit of tree with no versioned files should fail"""
45
        # If forced, it should succeed, but this is not tested here.
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
46
        self.make_branch_and_tree('.')
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
47
        self.build_tree(['hello.txt'])
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
48
        out,err = self.run_bzr('commit -m empty', retcode=3)
2089.1.1 by wang
If a commit fails, the commit message is stored in a file at the root of
49
        self.assertEqual('', out)
5765.1.3 by John Arbash Meinel
We missed a test case that was asserting the old string.
50
        # Two ugly bits here.
51
        # 1) We really don't want 'aborting commit write group' anymore.
52
        # 2) bzr: ERROR: is a really long line, so we wrap it with '\'
53
        self.assertThat(
54
            err,
55
            DocTestMatches("""\
56
Committing to: ...
57
bzr: ERROR: No changes to commit.\
58
 Please 'bzr add' the files you want to commit,\
59
 or use --unchanged to force an empty commit.
60
""", flags=doctest.ELLIPSIS|doctest.REPORT_UDIFF))
2089.1.1 by wang
If a commit fails, the commit message is stored in a file at the root of
61
62
    def test_commit_success(self):
63
        """Successful commit should not leave behind a bzr-commit-* file"""
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
64
        self.make_branch_and_tree('.')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
65
        self.run_bzr('commit --unchanged -m message')
2552.2.2 by Vincent Ladeuil
Enforce run_bzr(string) where possible.
66
        self.assertEqual('', self.run_bzr('unknowns')[0])
2089.1.1 by wang
If a commit fails, the commit message is stored in a file at the root of
67
68
        # same for unicode messages
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
69
        self.run_bzr(["commit", "--unchanged", "-m", u'foo\xb5'])
2552.2.2 by Vincent Ladeuil
Enforce run_bzr(string) where possible.
70
        self.assertEqual('', self.run_bzr('unknowns')[0])
1616.1.3 by Martin Pool
Clean up cut&pasted test for verbose commit
71
5777.6.4 by Jelmer Vernooij
Add test for lossy commit to native branch.
72
    def test_commit_lossy_native(self):
73
        """A --lossy option to commit is supported."""
74
        self.make_branch_and_tree('.')
75
        self.run_bzr('commit --lossy --unchanged -m message')
76
        self.assertEqual('', self.run_bzr('unknowns')[0])
77
5777.6.5 by Jelmer Vernooij
Add tests for lossy commit.
78
    def test_commit_lossy_foreign(self):
5777.6.6 by Jelmer Vernooij
Add lossy tests.
79
        test_foreign.register_dummy_foreign_for_test(self)
80
        self.make_branch_and_tree('.',
81
            format=test_foreign.DummyForeignVcsDirFormat())
5777.6.5 by Jelmer Vernooij
Add tests for lossy commit.
82
        self.run_bzr('commit --lossy --unchanged -m message')
5777.6.6 by Jelmer Vernooij
Add lossy tests.
83
        output = self.run_bzr('revision-info')[0]
84
        self.assertTrue(output.startswith('1 dummy-'))
5777.6.5 by Jelmer Vernooij
Add tests for lossy commit.
85
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
86
    def test_commit_with_path(self):
87
        """Commit tree with path of root specified"""
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
88
        a_tree = self.make_branch_and_tree('a')
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
89
        self.build_tree(['a/a_file'])
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
90
        a_tree.add('a_file')
2552.2.5 by Vincent Ladeuil
Revert the intrusive run_bzr('commit') rewritings.
91
        self.run_bzr(['commit', '-m', 'first commit', 'a'])
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
92
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
93
        b_tree = a_tree.bzrdir.sprout('b').open_workingtree()
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
94
        self.build_tree_contents([('b/a_file', 'changes in b')])
2552.2.5 by Vincent Ladeuil
Revert the intrusive run_bzr('commit') rewritings.
95
        self.run_bzr(['commit', '-m', 'first commit in b', 'b'])
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
96
97
        self.build_tree_contents([('a/a_file', 'new contents')])
2552.2.5 by Vincent Ladeuil
Revert the intrusive run_bzr('commit') rewritings.
98
        self.run_bzr(['commit', '-m', 'change in a', 'a'])
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
99
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
100
        b_tree.merge_from_branch(a_tree.branch)
2738.4.2 by Daniel Watkins
Now test for conflicts where appropriate.
101
        self.assertEqual(len(b_tree.conflicts()), 1)
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
102
        self.run_bzr('resolved b/a_file')
2552.2.5 by Vincent Ladeuil
Revert the intrusive run_bzr('commit') rewritings.
103
        self.run_bzr(['commit', '-m', 'merge into b', 'b'])
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
104
1616.1.3 by Martin Pool
Clean up cut&pasted test for verbose commit
105
    def test_10_verbose_commit(self):
106
        """Add one file and examine verbose commit output"""
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
107
        tree = self.make_branch_and_tree('.')
1616.1.3 by Martin Pool
Clean up cut&pasted test for verbose commit
108
        self.build_tree(['hello.txt'])
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
109
        tree.add("hello.txt")
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
110
        out,err = self.run_bzr('commit -m added')
111
        self.assertEqual('', out)
3052.4.1 by Matt Nordhoff
bzr commit: don't print the revision number twice. (Bug #172612)
112
        self.assertContainsRe(err, '^Committing to: .*\n'
2789.2.11 by Ian Clatworthy
remove more reporting stuff
113
                              'added hello.txt\n'
114
                              'Committed revision 1.\n$',)
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
115
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
116
    def prepare_simple_history(self):
117
        """Prepare and return a working tree with one commit of one file"""
118
        # Commit with modified file should say so
119
        wt = BzrDir.create_standalone_workingtree('.')
120
        self.build_tree(['hello.txt', 'extra.txt'])
121
        wt.add(['hello.txt'])
122
        wt.commit(message='added')
123
        return wt
124
125
    def test_verbose_commit_modified(self):
126
        # Verbose commit of modified file should say so
127
        wt = self.prepare_simple_history()
128
        self.build_tree_contents([('hello.txt', 'new contents')])
2789.2.11 by Ian Clatworthy
remove more reporting stuff
129
        out, err = self.run_bzr('commit -m modified')
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
130
        self.assertEqual('', out)
3052.4.1 by Matt Nordhoff
bzr commit: don't print the revision number twice. (Bug #172612)
131
        self.assertContainsRe(err, '^Committing to: .*\n'
2747.6.7 by Daniel Watkins
Modify tests to reflect change in commit output.
132
                              'modified hello\.txt\n'
2789.2.11 by Ian Clatworthy
remove more reporting stuff
133
                              'Committed revision 2\.\n$')
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
134
5167.1.4 by Parth Malwankar
show_warning now uses 'replace' option for encoding the message.
135
    def test_unicode_commit_message_is_filename(self):
5167.1.1 by Parth Malwankar
commit command can now accept message (-m) same as a unicode filename
136
        """Unicode commit message same as a filename (Bug #563646).
137
        """
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
138
        self.requireFeature(features.UnicodeFilenameFeature)
5167.1.1 by Parth Malwankar
commit command can now accept message (-m) same as a unicode filename
139
        file_name = u'\N{euro sign}'
140
        self.run_bzr(['init'])
141
        open(file_name, 'w').write('hello world')
142
        self.run_bzr(['add'])
143
        out, err = self.run_bzr(['commit', '-m', file_name])
144
        reflags = re.MULTILINE|re.DOTALL|re.UNICODE
5167.1.4 by Parth Malwankar
show_warning now uses 'replace' option for encoding the message.
145
        te = osutils.get_terminal_encoding()
146
        self.assertContainsRe(err.decode(te),
147
            u'The commit message is a file name:',
5167.1.1 by Parth Malwankar
commit command can now accept message (-m) same as a unicode filename
148
            flags=reflags)
149
5167.1.6 by Parth Malwankar
fixed comment.
150
        # Run same test with a filename that causes encode
5167.1.5 by Parth Malwankar
added test to handle case if filename cannot be shown in terminal encoding
151
        # error for the terminal encoding. We do this
152
        # by forcing terminal encoding of ascii for
153
        # osutils.get_terminal_encoding which is used
154
        # by ui.text.show_warning
155
        default_get_terminal_enc = osutils.get_terminal_encoding
156
        try:
5320.2.7 by Robert Collins
Sanity check that new_trace_file in pop_log_file is valid, and also fix a test that monkey patched get_terminal_encoding.
157
            osutils.get_terminal_encoding = lambda trace=None: 'ascii'
5167.1.5 by Parth Malwankar
added test to handle case if filename cannot be shown in terminal encoding
158
            file_name = u'foo\u1234'
159
            open(file_name, 'w').write('hello world')
160
            self.run_bzr(['add'])
161
            out, err = self.run_bzr(['commit', '-m', file_name])
162
            reflags = re.MULTILINE|re.DOTALL|re.UNICODE
163
            te = osutils.get_terminal_encoding()
164
            self.assertContainsRe(err.decode(te, 'replace'),
165
                u'The commit message is a file name:',
166
                flags=reflags)
167
        finally:
168
            osutils.get_terminal_encoding = default_get_terminal_enc
169
6345.1.1 by Martin Packman
Add tests for non-ascii unversioned file error during commit
170
    def test_non_ascii_file_unversioned_utf8(self):
171
        self.requireFeature(features.UnicodeFilenameFeature)
172
        tree = self.make_branch_and_tree(".")
173
        self.build_tree(["f"])
174
        tree.add(["f"])
175
        out, err = self.run_bzr(["commit", "-m", "Wrong filename", u"\xa7"],
176
            encoding="utf-8", retcode=3)
177
        self.assertContainsRe(err, "(?m)not versioned: \"\xc2\xa7\"$")
178
179
    def test_non_ascii_file_unversioned_iso_8859_5(self):
180
        self.requireFeature(features.UnicodeFilenameFeature)
181
        tree = self.make_branch_and_tree(".")
182
        self.build_tree(["f"])
183
        tree.add(["f"])
184
        out, err = self.run_bzr(["commit", "-m", "Wrong filename", u"\xa7"],
185
            encoding="iso-8859-5", retcode=3)
186
        self.expectFailure("Error messages are always written as UTF-8",
187
            self.assertNotContainsString, err, "\xc2\xa7")
188
        self.assertContainsRe(err, "(?m)not versioned: \"\xfd\"$")
189
4795.5.12 by Gioele Barabucci
Non-interactive warning for forgotten -m parameter
190
    def test_warn_about_forgotten_commit_message(self):
4795.5.8 by Gioele Barabucci
Test commit cancellation in presence of a suspect -m parameter
191
        """Test that the lack of -m parameter is caught"""
192
        wt = self.make_branch_and_tree('.')
193
        self.build_tree(['one', 'two'])
194
        wt.add(['two'])
4795.5.12 by Gioele Barabucci
Non-interactive warning for forgotten -m parameter
195
        out, err = self.run_bzr('commit -m one two')
196
        self.assertContainsRe(err, "The commit message is a file name")
4795.5.8 by Gioele Barabucci
Test commit cancellation in presence of a suspect -m parameter
197
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
198
    def test_verbose_commit_renamed(self):
199
        # Verbose commit of renamed file should say so
200
        wt = self.prepare_simple_history()
201
        wt.rename_one('hello.txt', 'gutentag.txt')
2789.2.11 by Ian Clatworthy
remove more reporting stuff
202
        out, err = self.run_bzr('commit -m renamed')
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
203
        self.assertEqual('', out)
3052.4.1 by Matt Nordhoff
bzr commit: don't print the revision number twice. (Bug #172612)
204
        self.assertContainsRe(err, '^Committing to: .*\n'
2747.6.7 by Daniel Watkins
Modify tests to reflect change in commit output.
205
                              'renamed hello\.txt => gutentag\.txt\n'
2789.2.11 by Ian Clatworthy
remove more reporting stuff
206
                              'Committed revision 2\.$\n')
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
207
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
208
    def test_verbose_commit_moved(self):
209
        # Verbose commit of file moved to new directory should say so
210
        wt = self.prepare_simple_history()
211
        os.mkdir('subdir')
212
        wt.add(['subdir'])
213
        wt.rename_one('hello.txt', 'subdir/hello.txt')
2789.2.11 by Ian Clatworthy
remove more reporting stuff
214
        out, err = self.run_bzr('commit -m renamed')
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
215
        self.assertEqual('', out)
4183.5.5 by Robert Collins
Enable record_iter_changes for cases where it can work.
216
        self.assertEqual(set([
217
            'Committing to: %s/' % osutils.getcwd(),
218
            'added subdir',
219
            'renamed hello.txt => subdir/hello.txt',
220
            'Committed revision 2.',
221
            '',
222
            ]), set(err.split('\n')))
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
223
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
224
    def test_verbose_commit_with_unknown(self):
1616.1.3 by Martin Pool
Clean up cut&pasted test for verbose commit
225
        """Unknown files should not be listed by default in verbose output"""
226
        # Is that really the best policy?
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
227
        wt = BzrDir.create_standalone_workingtree('.')
1616.1.3 by Martin Pool
Clean up cut&pasted test for verbose commit
228
        self.build_tree(['hello.txt', 'extra.txt'])
1669.2.1 by Martin Pool
verbose commit now specifically identifies modified/renamed/reparented files
229
        wt.add(['hello.txt'])
2789.2.11 by Ian Clatworthy
remove more reporting stuff
230
        out,err = self.run_bzr('commit -m added')
1616.1.3 by Martin Pool
Clean up cut&pasted test for verbose commit
231
        self.assertEqual('', out)
3052.4.1 by Matt Nordhoff
bzr commit: don't print the revision number twice. (Bug #172612)
232
        self.assertContainsRe(err, '^Committing to: .*\n'
2747.6.7 by Daniel Watkins
Modify tests to reflect change in commit output.
233
                              'added hello\.txt\n'
2789.2.11 by Ian Clatworthy
remove more reporting stuff
234
                              'Committed revision 1\.\n$')
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
235
1668.1.5 by Martin Pool
[broken] fix up display of files changed by a commit
236
    def test_verbose_commit_with_unchanged(self):
1616.1.4 by Martin Pool
Verbose commit shouldn't talk about every unchanged file.
237
        """Unchanged files should not be listed by default in verbose output"""
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
238
        tree = self.make_branch_and_tree('.')
1616.1.4 by Martin Pool
Verbose commit shouldn't talk about every unchanged file.
239
        self.build_tree(['hello.txt', 'unchanged.txt'])
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
240
        tree.add('unchanged.txt')
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
241
        self.run_bzr('commit -m unchanged unchanged.txt')
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
242
        tree.add("hello.txt")
2789.2.11 by Ian Clatworthy
remove more reporting stuff
243
        out,err = self.run_bzr('commit -m added')
1616.1.4 by Martin Pool
Verbose commit shouldn't talk about every unchanged file.
244
        self.assertEqual('', out)
3052.4.1 by Matt Nordhoff
bzr commit: don't print the revision number twice. (Bug #172612)
245
        self.assertContainsRe(err, '^Committing to: .*\n'
2747.6.7 by Daniel Watkins
Modify tests to reflect change in commit output.
246
                              'added hello\.txt\n'
2789.2.11 by Ian Clatworthy
remove more reporting stuff
247
                              'Committed revision 2\.$\n')
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
248
2747.6.13 by Daniel Watkins
Renamed test to reflect what it is actually doing.
249
    def test_verbose_commit_includes_master_location(self):
2747.6.4 by Daniel Watkins
Modified test as suggested on-list.
250
        """Location of master is displayed when committing to bound branch"""
2747.6.2 by Daniel Watkins
Added test for behaviour.
251
        a_tree = self.make_branch_and_tree('a')
252
        self.build_tree(['a/b'])
253
        a_tree.add('b')
254
        a_tree.commit(message='Initial message')
255
256
        b_tree = a_tree.branch.create_checkout('b')
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
257
        expected = "%s/" % (osutils.abspath('a'), )
2747.6.4 by Daniel Watkins
Modified test as suggested on-list.
258
        out, err = self.run_bzr('commit -m blah --unchanged', working_dir='b')
3052.4.1 by Matt Nordhoff
bzr commit: don't print the revision number twice. (Bug #172612)
259
        self.assertEqual(err, 'Committing to: %s\n'
2747.6.7 by Daniel Watkins
Modify tests to reflect change in commit output.
260
                         'Committed revision 2.\n' % expected)
2747.6.2 by Daniel Watkins
Added test for behaviour.
261
4634.94.4 by John Arbash Meinel
Fix bug #433779, sanitize '\r' characters in commit.
262
    def test_commit_sanitizes_CR_in_message(self):
263
        # See bug #433779, basically Emacs likes to pass '\r\n' style line
264
        # endings to 'bzr commit -m ""' which breaks because we don't allow
265
        # '\r' in commit messages. (Mostly because of issues where XML style
266
        # formats arbitrarily strip it out of the data while parsing.)
267
        # To make life easier for users, we just always translate '\r\n' =>
268
        # '\n'. And '\r' => '\n'.
269
        a_tree = self.make_branch_and_tree('a')
270
        self.build_tree(['a/b'])
271
        a_tree.add('b')
272
        self.run_bzr(['commit',
273
                      '-m', 'a string\r\n\r\nwith mixed\r\rendings\n'],
274
                     working_dir='a')
275
        rev_id = a_tree.branch.last_revision()
276
        rev = a_tree.branch.repository.get_revision(rev_id)
277
        self.assertEqualDiff('a string\n\nwith mixed\n\nendings\n',
278
                             rev.message)
279
1668.1.5 by Martin Pool
[broken] fix up display of files changed by a commit
280
    def test_commit_merge_reports_all_modified_files(self):
281
        # the commit command should show all the files that are shown by
282
        # bzr diff or bzr status when committing, even when they were not
283
        # changed by the user but rather through doing a merge.
284
        this_tree = self.make_branch_and_tree('this')
285
        # we need a bunch of files and dirs, to perform one action on each.
286
        self.build_tree([
287
            'this/dirtorename/',
288
            'this/dirtoreparent/',
289
            'this/dirtoleave/',
290
            'this/dirtoremove/',
291
            'this/filetoreparent',
292
            'this/filetorename',
293
            'this/filetomodify',
294
            'this/filetoremove',
295
            'this/filetoleave']
296
            )
297
        this_tree.add([
298
            'dirtorename',
299
            'dirtoreparent',
300
            'dirtoleave',
301
            'dirtoremove',
302
            'filetoreparent',
303
            'filetorename',
304
            'filetomodify',
305
            'filetoremove',
306
            'filetoleave']
307
            )
308
        this_tree.commit('create_files')
309
        other_dir = this_tree.bzrdir.sprout('other')
310
        other_tree = other_dir.open_workingtree()
311
        other_tree.lock_write()
312
        # perform the needed actions on the files and dirs.
313
        try:
314
            other_tree.rename_one('dirtorename', 'renameddir')
315
            other_tree.rename_one('dirtoreparent', 'renameddir/reparenteddir')
316
            other_tree.rename_one('filetorename', 'renamedfile')
2738.4.6 by Daniel Watkins
Rewrapped lines longer than 79 characters.
317
            other_tree.rename_one('filetoreparent',
318
                                  'renameddir/reparentedfile')
1668.1.5 by Martin Pool
[broken] fix up display of files changed by a commit
319
            other_tree.remove(['dirtoremove', 'filetoremove'])
320
            self.build_tree_contents([
2738.4.5 by Daniel Watkins
Fixed whitespace issues.
321
                ('other/newdir/',),
1668.1.5 by Martin Pool
[broken] fix up display of files changed by a commit
322
                ('other/filetomodify', 'new content'),
323
                ('other/newfile', 'new file content')])
324
            other_tree.add('newfile')
325
            other_tree.add('newdir/')
326
            other_tree.commit('modify all sample files and dirs.')
327
        finally:
328
            other_tree.unlock()
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
329
        this_tree.merge_from_branch(other_tree.branch)
1668.1.5 by Martin Pool
[broken] fix up display of files changed by a commit
330
        os.chdir('this')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
331
        out,err = self.run_bzr('commit -m added')
1668.1.5 by Martin Pool
[broken] fix up display of files changed by a commit
332
        self.assertEqual('', out)
4183.5.5 by Robert Collins
Enable record_iter_changes for cases where it can work.
333
        self.assertEqual(set([
334
            'Committing to: %s/' % osutils.getcwd(),
335
            'modified filetomodify',
336
            'added newdir',
337
            'added newfile',
338
            'renamed dirtorename => renameddir',
339
            'renamed filetorename => renamedfile',
340
            'renamed dirtoreparent => renameddir/reparenteddir',
341
            'renamed filetoreparent => renameddir/reparentedfile',
342
            'deleted dirtoremove',
343
            'deleted filetoremove',
344
            'Committed revision 2.',
345
            ''
346
            ]), set(err.split('\n')))
1668.1.5 by Martin Pool
[broken] fix up display of files changed by a commit
347
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
348
    def test_empty_commit_message(self):
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
349
        tree = self.make_branch_and_tree('.')
350
        self.build_tree_contents([('foo.c', 'int main() {}')])
351
        tree.add('foo.c')
6064.1.1 by Jelmer Vernooij
Allow committing with an explicit empty commit message.
352
        self.run_bzr('commit -m ""')
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
353
354
    def test_other_branch_commit(self):
355
        # this branch is to ensure consistent behaviour, whether we're run
356
        # inside a branch, or not.
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
357
        outer_tree = self.make_branch_and_tree('.')
358
        inner_tree = self.make_branch_and_tree('branch')
359
        self.build_tree_contents([
360
            ('branch/foo.c', 'int main() {}'),
361
            ('branch/bar.c', 'int main() {}')])
4570.4.3 by Robert Collins
Fix a couple of small bugs in the patch - use specific files with record_iter_changs, and the CLI shouldn't generate a filter of [] for commit.
362
        inner_tree.add(['foo.c', 'bar.c'])
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
363
        # can't commit files in different trees; sane error
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
364
        self.run_bzr('commit -m newstuff branch/foo.c .', retcode=3)
4570.4.3 by Robert Collins
Fix a couple of small bugs in the patch - use specific files with record_iter_changs, and the CLI shouldn't generate a filter of [] for commit.
365
        # can commit to branch - records foo.c only
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
366
        self.run_bzr('commit -m newstuff branch/foo.c')
4570.4.3 by Robert Collins
Fix a couple of small bugs in the patch - use specific files with record_iter_changs, and the CLI shouldn't generate a filter of [] for commit.
367
        # can commit to branch - records bar.c
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
368
        self.run_bzr('commit -m newstuff branch')
4570.4.3 by Robert Collins
Fix a couple of small bugs in the patch - use specific files with record_iter_changs, and the CLI shouldn't generate a filter of [] for commit.
369
        # No changes left
370
        self.run_bzr_error(["No changes to commit"], 'commit -m newstuff branch')
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
371
372
    def test_out_of_date_tree_commit(self):
373
        # check we get an error code and a clear message committing with an out
374
        # of date checkout
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
375
        tree = self.make_branch_and_tree('branch')
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
376
        # make a checkout
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
377
        checkout = tree.branch.create_checkout('checkout', lightweight=True)
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
378
        # commit to the original branch to make the checkout out of date
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
379
        tree.commit('message branch', allow_pointless=True)
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
380
        # now commit to the checkout should emit
381
        # ERROR: Out of date with the branch, 'bzr update' is suggested
2530.3.1 by Martin Pool
Cleanup old variations on run_bzr in the test suite
382
        output = self.run_bzr('commit --unchanged -m checkout_message '
1508.1.22 by Robert Collins
implement out of date working tree checks in commit.
383
                             'checkout', retcode=3)
384
        self.assertEqual(output,
385
                         ('',
2738.4.6 by Daniel Watkins
Rewrapped lines longer than 79 characters.
386
                          "bzr: ERROR: Working tree is out of date, please "
387
                          "run 'bzr update'.\n"))
1587.1.8 by Robert Collins
Local commits on unbound branches fail.
388
389
    def test_local_commit_unbound(self):
390
        # a --local commit on an unbound branch is an error
391
        self.make_branch_and_tree('.')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
392
        out, err = self.run_bzr('commit --local', retcode=3)
1587.1.8 by Robert Collins
Local commits on unbound branches fail.
393
        self.assertEqualDiff('', out)
394
        self.assertEqualDiff('bzr: ERROR: Cannot perform local-only commits '
395
                             'on unbound branches.\n', err)
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
396
397
    def test_commit_a_text_merge_in_a_checkout(self):
398
        # checkouts perform multiple actions in a transaction across bond
399
        # branches and their master, and have been observed to fail in the
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
400
        # past. This is a user story reported to fail in bug #43959 where
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
401
        # a merge done in a checkout (using the update command) failed to
402
        # commit correctly.
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
403
        trunk = self.make_branch_and_tree('trunk')
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
404
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
405
        u1 = trunk.branch.create_checkout('u1')
4985.3.17 by Vincent Ladeuil
Some cleanup.
406
        self.build_tree_contents([('u1/hosts', 'initial contents\n')])
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
407
        u1.add('hosts')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
408
        self.run_bzr('commit -m add-hosts u1')
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
409
2664.13.2 by Daniel Watkins
tests.blackbox.test_commit now uses internals where appropriate.
410
        u2 = trunk.branch.create_checkout('u2')
4985.3.17 by Vincent Ladeuil
Some cleanup.
411
        self.build_tree_contents([('u2/hosts', 'altered in u2\n')])
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
412
        self.run_bzr('commit -m checkin-from-u2 u2')
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
413
414
        # make an offline commits
4985.3.17 by Vincent Ladeuil
Some cleanup.
415
        self.build_tree_contents([('u1/hosts', 'first offline change in u1\n')])
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
416
        self.run_bzr('commit -m checkin-offline --local u1')
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
417
418
        # now try to pull in online work from u2, and then commit our offline
419
        # work as a merge
420
        # retcode 1 as we expect a text conflict
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
421
        self.run_bzr('update u1', retcode=1)
4985.3.17 by Vincent Ladeuil
Some cleanup.
422
        self.assertFileEqual('''\
423
<<<<<<< TREE
424
first offline change in u1
425
=======
426
altered in u2
427
>>>>>>> MERGE-SOURCE
428
''',
4985.3.10 by Gerard Krol
Reformat long lines
429
                             'u1/hosts')
4985.3.1 by Gerard Krol
Werkt wel ok
430
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
431
        self.run_bzr('resolved u1/hosts')
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
432
        # add a text change here to represent resolving the merge conflicts in
433
        # favour of a new version of the file not identical to either the u1
434
        # version or the u2 version.
435
        self.build_tree_contents([('u1/hosts', 'merge resolution\n')])
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
436
        self.run_bzr('commit -m checkin-merge-of-the-offline-work-from-u1 u1')
1551.7.24 by Aaron Bentley
Ensure commit respects file spec when committing removals
437
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
438
    def test_commit_exclude_excludes_modified_files(self):
439
        """Commit -x foo should ignore changes to foo."""
440
        tree = self.make_branch_and_tree('.')
441
        self.build_tree(['a', 'b', 'c'])
442
        tree.smart_add(['.'])
443
        out, err = self.run_bzr(['commit', '-m', 'test', '-x', 'b'])
444
        self.assertFalse('added b' in out)
445
        self.assertFalse('added b' in err)
3602.1.4 by Robert Collins
Andrew's review feedback.
446
        # If b was excluded it will still be 'added' in status.
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
447
        out, err = self.run_bzr(['added'])
448
        self.assertEqual('b\n', out)
449
        self.assertEqual('', err)
450
451
    def test_commit_exclude_twice_uses_both_rules(self):
452
        """Commit -x foo -x bar should ignore changes to foo and bar."""
453
        tree = self.make_branch_and_tree('.')
454
        self.build_tree(['a', 'b', 'c'])
455
        tree.smart_add(['.'])
456
        out, err = self.run_bzr(['commit', '-m', 'test', '-x', 'b', '-x', 'c'])
457
        self.assertFalse('added b' in out)
458
        self.assertFalse('added c' in out)
459
        self.assertFalse('added b' in err)
460
        self.assertFalse('added c' in err)
3602.1.4 by Robert Collins
Andrew's review feedback.
461
        # If b was excluded it will still be 'added' in status.
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
462
        out, err = self.run_bzr(['added'])
3602.1.4 by Robert Collins
Andrew's review feedback.
463
        self.assertTrue('b\n' in out)
464
        self.assertTrue('c\n' in out)
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
465
        self.assertEqual('', err)
466
1551.7.24 by Aaron Bentley
Ensure commit respects file spec when committing removals
467
    def test_commit_respects_spec_for_removals(self):
468
        """Commit with a file spec should only commit removals that match"""
469
        t = self.make_branch_and_tree('.')
470
        self.build_tree(['file-a', 'dir-a/', 'dir-a/file-b'])
471
        t.add(['file-a', 'dir-a', 'dir-a/file-b'])
472
        t.commit('Create')
473
        t.remove(['file-a', 'dir-a/file-b'])
474
        os.chdir('dir-a')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
475
        result = self.run_bzr('commit . -m removed-file-b')[1]
1551.7.24 by Aaron Bentley
Ensure commit respects file spec when committing removals
476
        self.assertNotContainsRe(result, 'file-a')
477
        result = self.run_bzr('status')[0]
478
        self.assertContainsRe(result, 'removed:\n  file-a')
2116.2.1 by John Arbash Meinel
Add commit --strict tests, and add a default ignore so that commit --strict works again
479
480
    def test_strict_commit(self):
481
        """Commit with --strict works if everything is known"""
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
482
        ignores._set_user_ignores([])
2116.2.1 by John Arbash Meinel
Add commit --strict tests, and add a default ignore so that commit --strict works again
483
        tree = self.make_branch_and_tree('tree')
484
        self.build_tree(['tree/a'])
485
        tree.add('a')
486
        # A simple change should just work
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
487
        self.run_bzr('commit --strict -m adding-a',
2116.2.1 by John Arbash Meinel
Add commit --strict tests, and add a default ignore so that commit --strict works again
488
                     working_dir='tree')
489
490
    def test_strict_commit_no_changes(self):
491
        """commit --strict gives "no changes" if there is nothing to commit"""
492
        tree = self.make_branch_and_tree('tree')
493
        self.build_tree(['tree/a'])
494
        tree.add('a')
495
        tree.commit('adding a')
496
497
        # With no changes, it should just be 'no changes'
498
        # Make sure that commit is failing because there is nothing to do
4351.1.2 by Ian Clatworthy
tweak grammar in error message
499
        self.run_bzr_error(['No changes to commit'],
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
500
                           'commit --strict -m no-changes',
2116.2.1 by John Arbash Meinel
Add commit --strict tests, and add a default ignore so that commit --strict works again
501
                           working_dir='tree')
502
503
        # But --strict doesn't care if you supply --unchanged
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
504
        self.run_bzr('commit --strict --unchanged -m no-changes',
2116.2.1 by John Arbash Meinel
Add commit --strict tests, and add a default ignore so that commit --strict works again
505
                     working_dir='tree')
506
507
    def test_strict_commit_unknown(self):
508
        """commit --strict fails if a file is unknown"""
509
        tree = self.make_branch_and_tree('tree')
510
        self.build_tree(['tree/a'])
511
        tree.add('a')
512
        tree.commit('adding a')
513
514
        # Add one file so there is a change, but forget the other
515
        self.build_tree(['tree/b', 'tree/c'])
516
        tree.add('b')
517
        self.run_bzr_error(['Commit refused because there are unknown files'],
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
518
                           'commit --strict -m add-b',
2116.2.1 by John Arbash Meinel
Add commit --strict tests, and add a default ignore so that commit --strict works again
519
                           working_dir='tree')
520
521
        # --no-strict overrides --strict
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
522
        self.run_bzr('commit --strict -m add-b --no-strict',
2116.2.1 by John Arbash Meinel
Add commit --strict tests, and add a default ignore so that commit --strict works again
523
                     working_dir='tree')
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
524
525
    def test_fixes_bug_output(self):
526
        """commit --fixes=lp:23452 succeeds without output."""
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
527
        tree = self.make_branch_and_tree('tree')
528
        self.build_tree(['tree/hello.txt'])
529
        tree.add('hello.txt')
2376.4.12 by Jonathan Lange
Update NEWS file.
530
        output, err = self.run_bzr(
2789.2.11 by Ian Clatworthy
remove more reporting stuff
531
            'commit -m hello --fixes=lp:23452 tree/hello.txt')
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
532
        self.assertEqual('', output)
3052.4.1 by Matt Nordhoff
bzr commit: don't print the revision number twice. (Bug #172612)
533
        self.assertContainsRe(err, 'Committing to: .*\n'
2747.6.7 by Daniel Watkins
Modify tests to reflect change in commit output.
534
                              'added hello\.txt\n'
2789.2.11 by Ian Clatworthy
remove more reporting stuff
535
                              'Committed revision 1\.\n')
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
536
2453.2.1 by Martin Pool
Don't set the bugs property unless bugs are actually set
537
    def test_no_bugs_no_properties(self):
538
        """If no bugs are fixed, the bugs property is not set.
539
540
        see https://beta.launchpad.net/bzr/+bug/109613
541
        """
542
        tree = self.make_branch_and_tree('tree')
543
        self.build_tree(['tree/hello.txt'])
544
        tree.add('hello.txt')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
545
        self.run_bzr( 'commit -m hello tree/hello.txt')
2453.2.1 by Martin Pool
Don't set the bugs property unless bugs are actually set
546
        # Get the revision properties, ignoring the branch-nick property, which
547
        # we don't care about for this test.
548
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
549
        properties = dict(last_rev.properties)
550
        del properties['branch-nick']
551
        self.assertFalse('bugs' in properties)
552
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
553
    def test_fixes_bug_sets_property(self):
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
554
        """commit --fixes=lp:234 sets the lp:234 revprop to 'fixed'."""
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
555
        tree = self.make_branch_and_tree('tree')
556
        self.build_tree(['tree/hello.txt'])
557
        tree.add('hello.txt')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
558
        self.run_bzr('commit -m hello --fixes=lp:234 tree/hello.txt')
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
559
560
        # Get the revision properties, ignoring the branch-nick property, which
561
        # we don't care about for this test.
562
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
563
        properties = dict(last_rev.properties)
564
        del properties['branch-nick']
565
2376.4.18 by Jonathan Lange
Store all bug fix URLs in a single property.
566
        self.assertEqual({'bugs': 'https://launchpad.net/bugs/234 fixed'},
2376.4.7 by jml at canonical
- Add docstrings to tests.
567
                         properties)
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
568
569
    def test_fixes_multiple_bugs_sets_properties(self):
570
        """--fixes can be used more than once to show that bugs are fixed."""
571
        tree = self.make_branch_and_tree('tree')
572
        self.build_tree(['tree/hello.txt'])
573
        tree.add('hello.txt')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
574
        self.run_bzr('commit -m hello --fixes=lp:123 --fixes=lp:235'
575
                     ' tree/hello.txt')
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
576
577
        # Get the revision properties, ignoring the branch-nick property, which
578
        # we don't care about for this test.
579
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
580
        properties = dict(last_rev.properties)
581
        del properties['branch-nick']
582
2376.4.18 by Jonathan Lange
Store all bug fix URLs in a single property.
583
        self.assertEqual(
2376.4.21 by Jonathan Lange
Change the bugs separator to \n from ,
584
            {'bugs': 'https://launchpad.net/bugs/123 fixed\n'
2376.4.18 by Jonathan Lange
Store all bug fix URLs in a single property.
585
                     'https://launchpad.net/bugs/235 fixed'},
586
            properties)
2376.4.7 by jml at canonical
- Add docstrings to tests.
587
588
    def test_fixes_bug_with_alternate_trackers(self):
589
        """--fixes can be used on a properly configured branch to mark bug
590
        fixes on multiple trackers.
591
        """
592
        tree = self.make_branch_and_tree('tree')
593
        tree.branch.get_config().set_user_option(
594
            'trac_twisted_url', 'http://twistedmatrix.com/trac')
595
        self.build_tree(['tree/hello.txt'])
596
        tree.add('hello.txt')
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
597
        self.run_bzr('commit -m hello --fixes=lp:123 --fixes=twisted:235 tree/')
2376.4.7 by jml at canonical
- Add docstrings to tests.
598
599
        # Get the revision properties, ignoring the branch-nick property, which
600
        # we don't care about for this test.
601
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
602
        properties = dict(last_rev.properties)
603
        del properties['branch-nick']
604
2376.4.18 by Jonathan Lange
Store all bug fix URLs in a single property.
605
        self.assertEqual(
2376.4.21 by Jonathan Lange
Change the bugs separator to \n from ,
606
            {'bugs': 'https://launchpad.net/bugs/123 fixed\n'
2376.4.18 by Jonathan Lange
Store all bug fix URLs in a single property.
607
                     'http://twistedmatrix.com/trac/ticket/235 fixed'},
608
            properties)
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
609
610
    def test_fixes_unknown_bug_prefix(self):
611
        tree = self.make_branch_and_tree('tree')
612
        self.build_tree(['tree/hello.txt'])
613
        tree.add('hello.txt')
614
        self.run_bzr_error(
615
            ["Unrecognized bug %s. Commit refused." % 'xxx:123'],
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
616
            'commit -m add-b --fixes=xxx:123',
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
617
            working_dir='tree')
618
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
619
    def test_fixes_bug_with_default_tracker(self):
620
        """commit --fixes=234 uses the default bug tracker."""
621
        tree = self.make_branch_and_tree('tree')
622
        self.build_tree(['tree/hello.txt'])
623
        tree.add('hello.txt')
624
        self.run_bzr_error(
625
            ["bzr: ERROR: No tracker specified for bug 123. Use the form "
626
            "'tracker:id' or specify a default bug tracker using the "
6120.1.2 by Jelmer Vernooij
Doc doc doc.
627
            "`bugtracker` option.\n"
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
628
            "See \"bzr help bugs\" for more information on this feature. "
629
            "Commit refused."],
630
            'commit -m add-b --fixes=123',
631
            working_dir='tree')
6120.1.2 by Jelmer Vernooij
Doc doc doc.
632
        tree.branch.get_config().set_user_option("bugtracker", "lp")
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
633
        self.run_bzr('commit -m hello --fixes=234 tree/hello.txt')
634
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
6120.1.3 by Jelmer Vernooij
Review feedback from vila
635
        self.assertEqual('https://launchpad.net/bugs/234 fixed',
636
                         last_rev.properties['bugs'])
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
637
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
638
    def test_fixes_invalid_bug_number(self):
639
        tree = self.make_branch_and_tree('tree')
640
        self.build_tree(['tree/hello.txt'])
641
        tree.add('hello.txt')
642
        self.run_bzr_error(
3535.10.9 by James Westby
Make the improved messages show up in the UI.
643
            ["Did not understand bug identifier orange: Must be an integer. "
644
             "See \"bzr help bugs\" for more information on this feature.\n"
645
             "Commit refused."],
2552.2.3 by Vincent Ladeuil
Deprecate the varargs syntax and fix the tests.
646
            'commit -m add-b --fixes=lp:orange',
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
647
            working_dir='tree')
2376.4.7 by jml at canonical
- Add docstrings to tests.
648
649
    def test_fixes_invalid_argument(self):
650
        """Raise an appropriate error when the fixes argument isn't tag:id."""
651
        tree = self.make_branch_and_tree('tree')
652
        self.build_tree(['tree/hello.txt'])
653
        tree.add('hello.txt')
654
        self.run_bzr_error(
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
655
            [r"Invalid bug orange:apples:bananas. Must be in the form of "
656
             r"'tracker:id'\. See \"bzr help bugs\" for more information on "
657
             r"this feature.\nCommit refused\."],
658
            'commit -m add-b --fixes=orange:apples:bananas',
2376.4.7 by jml at canonical
- Add docstrings to tests.
659
            working_dir='tree')
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
660
661
    def test_no_author(self):
662
        """If the author is not specified, the author property is not set."""
663
        tree = self.make_branch_and_tree('tree')
664
        self.build_tree(['tree/hello.txt'])
665
        tree.add('hello.txt')
666
        self.run_bzr( 'commit -m hello tree/hello.txt')
667
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
668
        properties = last_rev.properties
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
669
        self.assertFalse('author' in properties)
670
671
    def test_author_sets_property(self):
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
672
        """commit --author='John Doe <jdoe@example.com>' sets the author
673
           revprop.
674
        """
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
675
        tree = self.make_branch_and_tree('tree')
676
        self.build_tree(['tree/hello.txt'])
677
        tree.add('hello.txt')
3099.2.1 by John Arbash Meinel
Allow 'bzr commit --author' to take a unicode string.
678
        self.run_bzr(["commit", '-m', 'hello',
679
                      '--author', u'John D\xf6 <jdoe@example.com>',
680
                     "tree/hello.txt"])
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
681
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
682
        properties = last_rev.properties
4056.2.3 by James Westby
Use a new "authors" revision property to allow multiple authors
683
        self.assertEqual(u'John D\xf6 <jdoe@example.com>', properties['authors'])
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
684
685
    def test_author_no_email(self):
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
686
        """Author's name without an email address is allowed, too."""
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
687
        tree = self.make_branch_and_tree('tree')
688
        self.build_tree(['tree/hello.txt'])
689
        tree.add('hello.txt')
2671.2.4 by Lukáš Lalinský
Fixed broken test_author_* blackbox tests.
690
        out, err = self.run_bzr("commit -m hello --author='John Doe' "
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
691
                                "tree/hello.txt")
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
692
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
693
        properties = last_rev.properties
4056.2.3 by James Westby
Use a new "authors" revision property to allow multiple authors
694
        self.assertEqual('John Doe', properties['authors'])
2833.2.1 by Alexander Belchenko
XFAIL test for bug #140419
695
4056.2.1 by James Westby
Allow specifying multiple authors for a revision.
696
    def test_multiple_authors(self):
697
        """Multiple authors can be specyfied, and all are stored."""
698
        tree = self.make_branch_and_tree('tree')
699
        self.build_tree(['tree/hello.txt'])
700
        tree.add('hello.txt')
701
        out, err = self.run_bzr("commit -m hello --author='John Doe' "
702
                                "--author='Jane Rey' tree/hello.txt")
703
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
704
        properties = last_rev.properties
4056.2.3 by James Westby
Use a new "authors" revision property to allow multiple authors
705
        self.assertEqual('John Doe\nJane Rey', properties['authors'])
4056.2.1 by James Westby
Allow specifying multiple authors for a revision.
706
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
707
    def test_commit_time(self):
708
        tree = self.make_branch_and_tree('tree')
709
        self.build_tree(['tree/hello.txt'])
710
        tree.add('hello.txt')
711
        out, err = self.run_bzr("commit -m hello "
712
            "--commit-time='2009-10-10 08:00:00 +0100' tree/hello.txt")
713
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
714
        self.assertEqual(
715
            'Sat 2009-10-10 08:00:00 +0100',
716
            osutils.format_date(last_rev.timestamp, last_rev.timezone))
717
        
718
    def test_commit_time_bad_time(self):
719
        tree = self.make_branch_and_tree('tree')
720
        self.build_tree(['tree/hello.txt'])
721
        tree.add('hello.txt')
722
        out, err = self.run_bzr("commit -m hello "
723
            "--commit-time='NOT A TIME' tree/hello.txt", retcode=3)
724
        self.assertStartsWith(
725
            err, "bzr: ERROR: Could not parse --commit-time:")
726
6280.2.1 by Matt Giuca
bzrlib.timestamp: More robust handling of time stamp string. (LP: #892657)
727
    def test_commit_time_missing_tz(self):
728
        tree = self.make_branch_and_tree('tree')
729
        self.build_tree(['tree/hello.txt'])
730
        tree.add('hello.txt')
731
        out, err = self.run_bzr("commit -m hello "
732
            "--commit-time='2009-10-10 08:00:00' tree/hello.txt", retcode=3)
733
        self.assertStartsWith(
734
            err, "bzr: ERROR: Could not parse --commit-time:")
735
        # Test that it is actually checking and does not simply crash with
736
        # some other exception
6280.2.3 by Matt Giuca
bzrlib.timestamp: Better error message if the string is missing a timezone offset.
737
        self.assertContainsString(err, "missing a timezone offset")
6280.2.1 by Matt Giuca
bzrlib.timestamp: More robust handling of time stamp string. (LP: #892657)
738
2833.2.1 by Alexander Belchenko
XFAIL test for bug #140419
739
    def test_partial_commit_with_renames_in_tree(self):
2833.2.2 by Alexander Belchenko
Bug #140419 fixed by Robert Collins
740
        # this test illustrates bug #140419
2833.2.1 by Alexander Belchenko
XFAIL test for bug #140419
741
        t = self.make_branch_and_tree('.')
742
        self.build_tree(['dir/', 'dir/a', 'test'])
743
        t.add(['dir/', 'dir/a', 'test'])
744
        t.commit('initial commit')
745
        # important part: file dir/a should change parent
746
        # and should appear before old parent
747
        # then during partial commit we have error
748
        # parent_id {dir-XXX} not in inventory
749
        t.rename_one('dir/a', 'a')
750
        self.build_tree_contents([('test', 'changes in test')])
2833.2.2 by Alexander Belchenko
Bug #140419 fixed by Robert Collins
751
        # partial commit
752
        out, err = self.run_bzr('commit test -m "partial commit"')
753
        self.assertEquals('', out)
754
        self.assertContainsRe(err, r'modified test\nCommitted revision 2.')
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
755
756
    def test_commit_readonly_checkout(self):
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
757
        # https://bugs.launchpad.net/bzr/+bug/129701
2872.5.1 by Martin Pool
Avoid internal error tracebacks on failure to lock on readonly transport (#129701).
758
        # "UnlockableTransport error trying to commit in checkout of readonly
759
        # branch"
760
        self.make_branch('master')
761
        master = BzrDir.open_from_transport(
762
            self.get_readonly_transport('master')).open_branch()
763
        master.create_checkout('checkout')
764
        out, err = self.run_bzr(['commit', '--unchanged', '-mfoo', 'checkout'],
765
            retcode=3)
766
        self.assertContainsRe(err,
2872.5.3 by Martin Pool
Pass back LockFailed from smart server lock methods
767
            r'^bzr: ERROR: Cannot lock.*readonly transport')
3825.2.2 by Jelmer Vernooij
Add blackbox test for commit hook templates.
768
5137.1.2 by Robert Collins
Review feedback: add comment about return value and an additional test.
769
    def setup_editor(self):
3825.2.2 by Jelmer Vernooij
Add blackbox test for commit hook templates.
770
        # Test that commit template hooks work
771
        if sys.platform == "win32":
772
            f = file('fed.bat', 'w')
773
            f.write('@rem dummy fed')
774
            f.close()
5570.3.12 by Vincent Ladeuil
Replace osutils.set_or_unset_env calls with self.overrideEnv.
775
            self.overrideEnv('BZR_EDITOR', "fed.bat")
3825.2.2 by Jelmer Vernooij
Add blackbox test for commit hook templates.
776
        else:
777
            f = file('fed.sh', 'wb')
778
            f.write('#!/bin/sh\n')
779
            f.close()
780
            os.chmod('fed.sh', 0755)
5570.3.12 by Vincent Ladeuil
Replace osutils.set_or_unset_env calls with self.overrideEnv.
781
            self.overrideEnv('BZR_EDITOR', "./fed.sh")
5137.1.2 by Robert Collins
Review feedback: add comment about return value and an additional test.
782
783
    def setup_commit_with_template(self):
784
        self.setup_editor()
3825.2.2 by Jelmer Vernooij
Add blackbox test for commit hook templates.
785
        msgeditor.hooks.install_named_hook("commit_message_template",
786
                lambda commit_obj, msg: "save me some typing\n", None)
787
        tree = self.make_branch_and_tree('tree')
788
        self.build_tree(['tree/hello.txt'])
789
        tree.add('hello.txt')
5137.1.2 by Robert Collins
Review feedback: add comment about return value and an additional test.
790
        return tree
791
6064.1.1 by Jelmer Vernooij
Allow committing with an explicit empty commit message.
792
    def test_edit_empty_message(self):
793
        tree = self.make_branch_and_tree('tree')
794
        self.setup_editor()
795
        self.build_tree(['tree/hello.txt'])
796
        tree.add('hello.txt')
797
        out, err = self.run_bzr("commit tree/hello.txt", retcode=3,
798
            stdin="y\n")
799
        self.assertContainsRe(err,
6064.1.4 by Jelmer Vernooij
Fix capitalization.
800
            "bzr: ERROR: Empty commit message specified")
6064.1.1 by Jelmer Vernooij
Allow committing with an explicit empty commit message.
801
5137.1.2 by Robert Collins
Review feedback: add comment about return value and an additional test.
802
    def test_commit_hook_template_accepted(self):
803
        tree = self.setup_commit_with_template()
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
804
        out, err = self.run_bzr("commit tree/hello.txt", stdin="y\n")
3825.2.2 by Jelmer Vernooij
Add blackbox test for commit hook templates.
805
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
806
        self.assertEqual('save me some typing\n', last_rev.message)
5137.1.2 by Robert Collins
Review feedback: add comment about return value and an additional test.
807
808
    def test_commit_hook_template_rejected(self):
809
        tree = self.setup_commit_with_template()
810
        expected = tree.last_revision()
6045.1.6 by paulbrianstewart at gmail
Added punctuation to the commit message
811
        out, err = self.run_bzr_error(["Empty commit message specified."
6045.1.1 by Paul Stewart
Changed the empty commit message to ask the user either enter a commit message or use --message ' ' to leave a blank commit message
812
                  " Please specify a commit message with either"
813
                  " --message or --file or leave a blank message"
6045.1.6 by paulbrianstewart at gmail
Added punctuation to the commit message
814
                  " with --message \"\"."],
5137.1.2 by Robert Collins
Review feedback: add comment about return value and an additional test.
815
            "commit tree/hello.txt", stdin="n\n")
816
        self.assertEqual(expected, tree.last_revision())
5187.2.4 by Parth Malwankar
added tests.
817
5912.4.10 by Jonathan Riddell
add test for set_commit_message hook
818
    def test_set_commit_message(self):
819
        msgeditor.hooks.install_named_hook("set_commit_message",
820
                lambda commit_obj, msg: "save me some typing\n", None)
821
        tree = self.make_branch_and_tree('tree')
822
        self.build_tree(['tree/hello.txt'])
823
        tree.add('hello.txt')
824
        out, err = self.run_bzr("commit tree/hello.txt")
825
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
826
        self.assertEqual('save me some typing\n', last_rev.message)
827
5187.2.4 by Parth Malwankar
added tests.
828
    def test_commit_without_username(self):
829
        """Ensure commit error if username is not set.
830
        """
831
        self.run_bzr(['init', 'foo'])
832
        os.chdir('foo')
833
        open('foo.txt', 'w').write('hello')
834
        self.run_bzr(['add'])
5570.3.12 by Vincent Ladeuil
Replace osutils.set_or_unset_env calls with self.overrideEnv.
835
        self.overrideEnv('EMAIL', None)
836
        self.overrideEnv('BZR_EMAIL', None)
5609.31.1 by mbp at sourcefrog
Blackbox tests for no identity set must disable whoami inference
837
        # Also, make sure that it's not inferred from mailname.
838
        self.overrideAttr(config, '_auto_user_id',
839
            lambda: (None, None))
5187.2.4 by Parth Malwankar
added tests.
840
        out, err = self.run_bzr(['commit', '-m', 'initial'], 3)
841
        self.assertContainsRe(err, 'Unable to determine your name')
5050.7.1 by Parth Malwankar
added test case for recursion error
842
843
    def test_commit_recursive_checkout(self):
844
        """Ensure that a commit to a recursive checkout fails cleanly.
845
        """
846
        self.run_bzr(['init', 'test_branch'])
847
        self.run_bzr(['checkout', 'test_branch', 'test_checkout'])
848
        os.chdir('test_checkout')
849
        self.run_bzr(['bind', '.']) # bind to self
850
        open('foo.txt', 'w').write('hello')
851
        self.run_bzr(['add'])
5050.7.2 by Parth Malwankar
recursive binding now shows a clear error
852
        out, err = self.run_bzr(['commit', '-m', 'addedfoo'], 3)
5050.7.1 by Parth Malwankar
added test case for recursion error
853
        self.assertEqual(out, '')
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
854
        self.assertContainsRe(err,
855
            'Branch.*test_checkout.*appears to be bound to itself')
6323.2.2 by Jelmer Vernooij
Add hpss call count for committing to a lightweight checkout.
856
857
858
class TestSmartServerCommit(TestCaseWithTransport):
859
860
    def test_commit_to_lightweight(self):
861
        self.setup_smart_server_with_call_log()
862
        t = self.make_branch_and_tree('from')
863
        for count in range(9):
864
            t.commit(message='commit %d' % count)
865
        out, err = self.run_bzr(['checkout', '--lightweight', self.get_url('from'),
866
            'target'])
867
        self.reset_smart_call_log()
868
        self.build_tree(['target/afile'])
869
        self.run_bzr(['add', 'target/afile'])
870
        out, err = self.run_bzr(['commit', '-m', 'do something', 'target'])
871
        # This figure represent the amount of work to perform this use case. It
872
        # is entirely ok to reduce this number if a test fails due to rpc_count
873
        # being too low. If rpc_count increases, more network roundtrips have
874
        # become necessary for this use case. Please do not adjust this number
875
        # upwards without agreement from bzr's network support maintainers.
876
        self.assertLength(220, self.hpss_calls)