1
# Copyright (C) 2005 Canonical Ltd
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.
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.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Test commit message editor.
31
from bzrlib.branch import Branch
32
from bzrlib.config import ensure_config_dir_exists, config_filename
33
from bzrlib.msgeditor import (
34
make_commit_message_template_encoded,
35
edit_commit_message_encoded
37
from bzrlib.tests import (
41
TestCaseWithTransport,
45
from bzrlib.tests.EncodingAdapter import EncodingTestAdapter
46
from bzrlib.trace import mutter
49
def load_tests(standard_tests, module, loader):
50
"""Parameterize the test for tempfile creation with different encodings."""
51
to_adapt, result = split_suite_by_re(standard_tests,
52
"test__create_temp_file_with_commit_template_in_unicode_dir")
53
for test in iter_suite_tests(to_adapt):
54
result.addTests(EncodingTestAdapter().adapt(test))
58
class MsgEditorTest(TestCaseWithTransport):
60
def make_uncommitted_tree(self):
61
"""Build a branch with uncommitted unicode named changes in the cwd."""
62
working_tree = self.make_branch_and_tree('.')
63
b = working_tree.branch
64
filename = u'hell\u00d8'
66
self.build_tree_contents([(filename, 'contents of hello')])
67
except UnicodeEncodeError:
68
raise TestSkipped("can't build unicode working tree in "
69
"filesystem encoding %s" % sys.getfilesystemencoding())
70
working_tree.add(filename)
73
def test_commit_template(self):
74
"""Test building a commit message template"""
75
working_tree = self.make_uncommitted_tree()
76
template = msgeditor.make_commit_message_template(working_tree,
78
self.assertEqualDiff(template,
84
def test_commit_template_encoded(self):
85
"""Test building a commit message template"""
86
working_tree = self.make_uncommitted_tree()
87
template = make_commit_message_template_encoded(working_tree,
89
output_encoding='utf8')
90
self.assertEqualDiff(template,
97
def test_commit_template_and_diff(self):
98
"""Test building a commit message template"""
99
working_tree = self.make_uncommitted_tree()
100
template = make_commit_message_template_encoded(working_tree,
103
output_encoding='utf8')
109
self.assertTrue(u"""\
112
""".encode('utf8') in template)
114
def make_do_nothing_editor(self):
115
if sys.platform == "win32":
116
f = file('fed.bat', 'w')
117
f.write('@rem dummy fed')
121
f = file('fed.sh', 'wb')
122
f.write('#!/bin/sh\n')
124
os.chmod('fed.sh', 0755)
127
def test_run_editor(self):
128
os.environ['BZR_EDITOR'] = self.make_do_nothing_editor()
129
self.assertEqual(True, msgeditor._run_editor(''),
130
'Unable to run dummy fake editor')
132
def make_fake_editor(self, message='test message from fed\\n'):
133
"""Set up environment so that an editor will be a known script.
135
Sets up BZR_EDITOR so that if an editor is spawned it will run a
136
script that just adds a known message to the start of the file.
138
f = file('fed.py', 'wb')
139
f.write('#!%s\n' % sys.executable)
143
if len(sys.argv) == 2:
154
if sys.platform == "win32":
155
# [win32] make batch file and set BZR_EDITOR
156
f = file('fed.bat', 'w')
160
""" % sys.executable)
162
os.environ['BZR_EDITOR'] = 'fed.bat'
164
# [non-win32] make python script executable and set BZR_EDITOR
165
os.chmod('fed.py', 0755)
166
os.environ['BZR_EDITOR'] = './fed.py'
168
def test_edit_commit_message(self):
169
working_tree = self.make_uncommitted_tree()
170
self.make_fake_editor()
172
mutter('edit_commit_message without infotext')
173
self.assertEqual('test message from fed\n',
174
msgeditor.edit_commit_message(''))
176
mutter('edit_commit_message with ascii string infotext')
177
self.assertEqual('test message from fed\n',
178
msgeditor.edit_commit_message('spam'))
180
mutter('edit_commit_message with unicode infotext')
181
self.assertEqual('test message from fed\n',
182
msgeditor.edit_commit_message(u'\u1234'))
184
tmpl = edit_commit_message_encoded(u'\u1234'.encode("utf8"))
185
self.assertEqual('test message from fed\n', tmpl)
187
def test_start_message(self):
188
self.make_uncommitted_tree()
189
self.make_fake_editor()
190
self.assertEqual('test message from fed\nstart message\n',
191
msgeditor.edit_commit_message('',
192
start_message='start message\n'))
193
self.assertEqual('test message from fed\n',
194
msgeditor.edit_commit_message('',
197
def test_deleted_commit_message(self):
198
working_tree = self.make_uncommitted_tree()
200
if sys.platform == 'win32':
201
os.environ['BZR_EDITOR'] = 'cmd.exe /c del'
203
os.environ['BZR_EDITOR'] = 'rm'
205
self.assertRaises((IOError, OSError), msgeditor.edit_commit_message, '')
207
def test__get_editor(self):
208
# Test that _get_editor can return a decent list of items
209
bzr_editor = os.environ.get('BZR_EDITOR')
210
visual = os.environ.get('VISUAL')
211
editor = os.environ.get('EDITOR')
213
os.environ['BZR_EDITOR'] = 'bzr_editor'
214
os.environ['VISUAL'] = 'visual'
215
os.environ['EDITOR'] = 'editor'
217
ensure_config_dir_exists()
218
f = open(config_filename(), 'wb')
219
f.write('editor = config_editor\n')
222
editors = list(msgeditor._get_editor())
223
editors = [editor for (editor, cfg_src) in editors]
225
self.assertEqual(['bzr_editor', 'config_editor', 'visual',
226
'editor'], editors[:4])
228
if sys.platform == 'win32':
229
self.assertEqual(['wordpad.exe', 'notepad.exe'], editors[4:])
231
self.assertEqual(['/usr/bin/editor', 'vi', 'pico', 'nano',
235
# Restore the environment
236
if bzr_editor is None:
237
del os.environ['BZR_EDITOR']
239
os.environ['BZR_EDITOR'] = bzr_editor
241
del os.environ['VISUAL']
243
os.environ['VISUAL'] = visual
245
del os.environ['EDITOR']
247
os.environ['EDITOR'] = editor
249
def test__run_editor_EACCES(self):
250
"""If running a configured editor raises EACESS, the user is warned."""
251
os.environ['BZR_EDITOR'] = 'eacces.py'
252
f = file('eacces.py', 'wb')
253
f.write('# Not a real editor')
255
# Make the fake editor unreadable (and unexecutable)
256
os.chmod('eacces.py', 0)
257
# Set $EDITOR so that _run_editor will terminate before trying real
259
os.environ['EDITOR'] = self.make_do_nothing_editor()
260
# Call _run_editor, capturing mutter.warning calls.
263
warnings.append(args[0] % args[1:])
264
_warning = trace.warning
265
trace.warning = warning
267
msgeditor._run_editor('')
269
trace.warning = _warning
270
self.assertStartsWith(warnings[0], 'Could not start editor "eacces.py"')
272
def test__create_temp_file_with_commit_template(self):
273
# check that commit template written properly
274
# and has platform native line-endings (CRLF on win32)
275
create_file = msgeditor._create_temp_file_with_commit_template
276
msgfilename, hasinfo = create_file('infotext','----','start message')
277
self.assertNotEqual(None, msgfilename)
278
self.assertTrue(hasinfo)
279
expected = os.linesep.join(['start message',
285
self.assertFileEqual(expected, msgfilename)
287
def test__create_temp_file_with_commit_template_in_unicode_dir(self):
288
self.requireFeature(tests.UnicodeFilenameFeature)
289
if hasattr(self, 'info'):
290
os.mkdir(self.info['directory'])
291
os.chdir(self.info['directory'])
292
msgeditor._create_temp_file_with_commit_template('infotext')
294
raise TestNotApplicable('Test run elsewhere with non-ascii data.')
296
def test__create_temp_file_with_empty_commit_template(self):
298
create_file = msgeditor._create_temp_file_with_commit_template
299
msgfilename, hasinfo = create_file('')
300
self.assertNotEqual(None, msgfilename)
301
self.assertFalse(hasinfo)
302
self.assertFileEqual('', msgfilename)
304
def test_unsupported_encoding_commit_message(self):
305
old_env = osutils.set_or_unset_env('LANG', 'C')
307
# LANG env variable has no effect on Windows
308
# but some characters anyway cannot be represented
309
# in default user encoding
310
char = probe_bad_non_ascii(osutils.get_user_encoding())
312
raise TestSkipped('Cannot find suitable non-ascii character '
313
'for user_encoding (%s)' % osutils.get_user_encoding())
315
self.make_fake_editor(message=char)
317
working_tree = self.make_uncommitted_tree()
318
self.assertRaises(errors.BadCommitMessageEncoding,
319
msgeditor.edit_commit_message, '')
321
osutils.set_or_unset_env('LANG', old_env)
323
def test_generate_commit_message_template_no_hooks(self):
324
commit_obj = commit.Commit()
326
msgeditor.generate_commit_message_template(commit_obj))
328
def test_generate_commit_message_template_hook(self):
329
def restoreDefaults():
330
msgeditor.hooks['commit_message_template'] = []
331
self.addCleanup(restoreDefaults)
332
msgeditor.hooks.install_named_hook("commit_message_template",
333
lambda commit_obj, msg: "save me some typing\n", None)
334
commit_obj = commit.Commit()
335
self.assertEquals("save me some typing\n",
336
msgeditor.generate_commit_message_template(commit_obj))