~bzr-pqm/bzr/bzr.dev

2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2005 Canonical Ltd
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
2
#
3
# This program is free software; you can redistribute it and/or modify
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
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.
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
7
#
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.
12
#
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
16
17
"""Test commit message editor.
18
"""
19
20
import os
21
import sys
22
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
23
import bzrlib
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
24
from bzrlib import (
25
    errors,
26
    msgeditor,
27
    osutils,
28
    )
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
29
from bzrlib.branch import Branch
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
30
from bzrlib.config import ensure_config_dir_exists, config_filename
2598.6.24 by ghigo
update on the basis of Aaron suggestions
31
from bzrlib.msgeditor import (
32
    make_commit_message_template_encoded,
2598.6.27 by ghigo
small cleanup (line lenght)
33
    edit_commit_message_encoded
2598.6.24 by ghigo
update on the basis of Aaron suggestions
34
)
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
35
from bzrlib.tests import (
2921.6.14 by Robert Collins
Push the message editor test parameterisation down into the message editor
36
    iter_suite_tests,
2839.6.2 by Alexander Belchenko
changes after Martin's review
37
    probe_bad_non_ascii,
2921.6.14 by Robert Collins
Push the message editor test parameterisation down into the message editor
38
    split_suite_by_re,
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
39
    TestCaseWithTransport,
3004.1.8 by Daniel Watkins
Changed TestSkipped to TestNotApplicable as suggested by Aaron.
40
    TestNotApplicable,
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
41
    TestSkipped,
42
    )
2921.6.14 by Robert Collins
Push the message editor test parameterisation down into the message editor
43
from bzrlib.tests.EncodingAdapter import EncodingTestAdapter
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
44
from bzrlib.trace import mutter
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
45
2592.3.164 by Robert Collins
Reduce spurious differences to bzr.dev from merge mishaps.
46
2921.6.14 by Robert Collins
Push the message editor test parameterisation down into the message editor
47
def load_tests(standard_tests, module, loader):
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
48
    """Parameterize the test for tempfile creation with different encodings."""
2921.6.14 by Robert Collins
Push the message editor test parameterisation down into the message editor
49
    to_adapt, result = split_suite_by_re(standard_tests,
50
        "test__create_temp_file_with_commit_template_in_unicode_dir")
51
    for test in iter_suite_tests(to_adapt):
52
        result.addTests(EncodingTestAdapter().adapt(test))
53
    return result
54
55
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
56
class MsgEditorTest(TestCaseWithTransport):
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
57
1526.1.4 by Robert Collins
forgot my self.
58
    def make_uncommitted_tree(self):
1526.1.1 by Robert Collins
Run the test suite with no locale as well as the default locale. Also add a test for build_tree_shape to selftest.
59
        """Build a branch with uncommitted unicode named changes in the cwd."""
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
60
        working_tree = self.make_branch_and_tree('.')
61
        b = working_tree.branch
1526.1.1 by Robert Collins
Run the test suite with no locale as well as the default locale. Also add a test for build_tree_shape to selftest.
62
        filename = u'hell\u00d8'
1526.1.3 by Robert Collins
Merge from upstream.
63
        try:
64
            self.build_tree_contents([(filename, 'contents of hello')])
65
        except UnicodeEncodeError:
66
            raise TestSkipped("can't build unicode working tree in "
1185.33.97 by Martin Pool
MsgEditor tests should be skipped on platforms without unicode fs.
67
                "filesystem encoding %s" % sys.getfilesystemencoding())
1526.1.1 by Robert Collins
Run the test suite with no locale as well as the default locale. Also add a test for build_tree_shape to selftest.
68
        working_tree.add(filename)
69
        return working_tree
70
    
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
71
    def test_commit_template(self):
72
        """Test building a commit message template"""
1526.1.2 by Robert Collins
Fix typo in my msgeditor test changes.
73
        working_tree = self.make_uncommitted_tree()
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
74
        template = msgeditor.make_commit_message_template(working_tree,
2598.6.24 by ghigo
update on the basis of Aaron suggestions
75
                                                                 None)
2598.6.18 by ghigo
Update the tests to the new *_encoded() functions
76
        self.assertEqualDiff(template,
77
u"""\
78
added:
79
  hell\u00d8
80
""")
81
82
    def test_commit_template_encoded(self):
83
        """Test building a commit message template"""
84
        working_tree = self.make_uncommitted_tree()
2598.6.24 by ghigo
update on the basis of Aaron suggestions
85
        template = make_commit_message_template_encoded(working_tree,
86
                                                        None,
87
                                                        output_encoding='utf8')
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
88
        self.assertEqualDiff(template,
89
u"""\
90
added:
91
  hell\u00d8
2598.6.14 by ghigo
Update the test
92
""".encode("utf8"))
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
93
2598.6.18 by ghigo
Update the tests to the new *_encoded() functions
94
2598.6.2 by ghigo
Add testcase
95
    def test_commit_template_and_diff(self):
96
        """Test building a commit message template"""
97
        working_tree = self.make_uncommitted_tree()
2598.6.24 by ghigo
update on the basis of Aaron suggestions
98
        template = make_commit_message_template_encoded(working_tree,
99
                                                        None,
100
                                                        diff=True,
101
                                                        output_encoding='utf8')
2598.6.2 by ghigo
Add testcase
102
2598.6.10 by ghigo
In the commit dialog, the diff is stored as 8-bit raw data
103
        self.assertTrue("""\
2598.6.2 by ghigo
Add testcase
104
@@ -0,0 +1,1 @@
105
+contents of hello
2598.6.14 by ghigo
Update the test
106
""" in template)
2598.6.3 by ghigo
Add test case
107
        self.assertTrue(u"""\
108
added:
109
  hell\u00d8
2598.6.14 by ghigo
Update the test
110
""".encode('utf8') in template)
2598.6.2 by ghigo
Add testcase
111
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
112
    def test_run_editor(self):
113
        if sys.platform == "win32":
114
            f = file('fed.bat', 'w')
115
            f.write('@rem dummy fed')
116
            f.close()
117
            os.environ['BZR_EDITOR'] = 'fed.bat'
118
        else:
119
            f = file('fed.sh', 'wb')
120
            f.write('#!/bin/sh\n')
121
            f.close()
122
            os.chmod('fed.sh', 0755)
123
            os.environ['BZR_EDITOR'] = './fed.sh'
124
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
125
        self.assertEqual(True, msgeditor._run_editor(''),
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
126
                         'Unable to run dummy fake editor')
127
2625.9.5 by Daniel Watkins
Modified test_msgeditor.make_fake_editor to allow a custom message to be inserted.
128
    def make_fake_editor(self, message='test message from fed\\n'):
2258.3.2 by James Westby
Allow an empty start message.
129
        """Set up environment so that an editor will be a known script.
130
131
        Sets up BZR_EDITOR so that if an editor is spawned it will run a
132
        script that just adds a known message to the start of the file.
133
        """
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
134
        f = file('fed.py', 'wb')
135
        f.write('#!%s\n' % sys.executable)
136
        f.write("""\
2625.9.5 by Daniel Watkins
Modified test_msgeditor.make_fake_editor to allow a custom message to be inserted.
137
# coding=utf-8
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
138
import sys
139
if len(sys.argv) == 2:
140
    fn = sys.argv[1]
141
    f = file(fn, 'rb')
142
    s = f.read()
143
    f.close()
144
    f = file(fn, 'wb')
2625.9.9 by Daniel Watkins
Used format string as suggested by abentley.
145
    f.write('%s')
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
146
    f.write(s)
147
    f.close()
2625.9.9 by Daniel Watkins
Used format string as suggested by abentley.
148
""" % (message, ))
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
149
        f.close()
150
        if sys.platform == "win32":
151
            # [win32] make batch file and set BZR_EDITOR
152
            f = file('fed.bat', 'w')
153
            f.write("""\
154
@echo off
1711.4.2 by jfmeinel
current python may be running in a path that has a space, so properly quote the python exe name. for test_msgeditor
155
"%s" fed.py %%1
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
156
""" % sys.executable)
157
            f.close()
158
            os.environ['BZR_EDITOR'] = 'fed.bat'
159
        else:
160
            # [non-win32] make python script executable and set BZR_EDITOR
161
            os.chmod('fed.py', 0755)
162
            os.environ['BZR_EDITOR'] = './fed.py'
163
2258.3.2 by James Westby
Allow an empty start message.
164
    def test_edit_commit_message(self):
165
        working_tree = self.make_uncommitted_tree()
166
        self.make_fake_editor()
167
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
168
        mutter('edit_commit_message without infotext')
169
        self.assertEqual('test message from fed\n',
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
170
                         msgeditor.edit_commit_message(''))
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
171
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
172
        mutter('edit_commit_message with ascii string infotext')
173
        self.assertEqual('test message from fed\n',
174
                         msgeditor.edit_commit_message('spam'))
175
1185.85.9 by John Arbash Meinel
[patch] Alexander Belchenko: test spawning a msg editor
176
        mutter('edit_commit_message with unicode infotext')
177
        self.assertEqual('test message from fed\n',
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
178
                         msgeditor.edit_commit_message(u'\u1234'))
2598.6.18 by ghigo
Update the tests to the new *_encoded() functions
179
2598.6.27 by ghigo
small cleanup (line lenght)
180
        tmpl = edit_commit_message_encoded(u'\u1234'.encode("utf8"))
181
        self.assertEqual('test message from fed\n', tmpl)
1185.85.14 by John Arbash Meinel
Change exception handling for msgeditor.py to only catch specific exceptions.
182
2258.3.2 by James Westby
Allow an empty start message.
183
    def test_start_message(self):
184
        self.make_uncommitted_tree()
185
        self.make_fake_editor()
2258.3.1 by James Westby
Add a way to specify a template commit message.
186
        self.assertEqual('test message from fed\nstart message\n',
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
187
                         msgeditor.edit_commit_message('',
2258.3.1 by James Westby
Add a way to specify a template commit message.
188
                                              start_message='start message\n'))
2258.3.2 by James Westby
Allow an empty start message.
189
        self.assertEqual('test message from fed\n',
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
190
                         msgeditor.edit_commit_message('',
2258.3.2 by James Westby
Allow an empty start message.
191
                                              start_message=''))
2258.3.1 by James Westby
Add a way to specify a template commit message.
192
1185.85.14 by John Arbash Meinel
Change exception handling for msgeditor.py to only catch specific exceptions.
193
    def test_deleted_commit_message(self):
194
        working_tree = self.make_uncommitted_tree()
195
196
        if sys.platform == 'win32':
1711.4.1 by John Arbash Meinel
del is not an executable program on win32, you must use cmd /c del
197
            os.environ['BZR_EDITOR'] = 'cmd.exe /c del'
1185.85.14 by John Arbash Meinel
Change exception handling for msgeditor.py to only catch specific exceptions.
198
        else:
199
            os.environ['BZR_EDITOR'] = 'rm'
200
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
201
        self.assertRaises((IOError, OSError), msgeditor.edit_commit_message, '')
1185.85.14 by John Arbash Meinel
Change exception handling for msgeditor.py to only catch specific exceptions.
202
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
203
    def test__get_editor(self):
204
        # Test that _get_editor can return a decent list of items
205
        bzr_editor = os.environ.get('BZR_EDITOR')
1668.4.1 by Olaf Conradi
Make msgeditor invocation comply with Debian Policy.
206
        visual = os.environ.get('VISUAL')
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
207
        editor = os.environ.get('EDITOR')
208
        try:
209
            os.environ['BZR_EDITOR'] = 'bzr_editor'
1668.4.1 by Olaf Conradi
Make msgeditor invocation comply with Debian Policy.
210
            os.environ['VISUAL'] = 'visual'
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
211
            os.environ['EDITOR'] = 'editor'
212
213
            ensure_config_dir_exists()
214
            f = open(config_filename(), 'wb')
215
            f.write('editor = config_editor\n')
216
            f.close()
217
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
218
            editors = list(msgeditor._get_editor())
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
219
1668.4.1 by Olaf Conradi
Make msgeditor invocation comply with Debian Policy.
220
            self.assertEqual(['bzr_editor', 'config_editor', 'visual',
221
                              'editor'], editors[:4])
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
222
223
            if sys.platform == 'win32':
1668.4.1 by Olaf Conradi
Make msgeditor invocation comply with Debian Policy.
224
                self.assertEqual(['wordpad.exe', 'notepad.exe'], editors[4:])
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
225
            else:
1668.4.1 by Olaf Conradi
Make msgeditor invocation comply with Debian Policy.
226
                self.assertEqual(['/usr/bin/editor', 'vi', 'pico', 'nano',
227
                                  'joe'], editors[4:])
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
228
229
        finally:
230
            # Restore the environment
231
            if bzr_editor is None:
232
                del os.environ['BZR_EDITOR']
233
            else:
234
                os.environ['BZR_EDITOR'] = bzr_editor
1668.4.1 by Olaf Conradi
Make msgeditor invocation comply with Debian Policy.
235
            if visual is None:
236
                del os.environ['VISUAL']
237
            else:
238
                os.environ['VISUAL'] = visual
1185.50.93 by John Arbash Meinel
Added a test for the new list of editors.
239
            if editor is None:
240
                del os.environ['EDITOR']
241
            else:
242
                os.environ['EDITOR'] = editor
2472.4.1 by Alexander Belchenko
Bugfix #110901: commit message template written with native line-endings; corresponding unit tests added
243
244
    def test__create_temp_file_with_commit_template(self):
245
        # check that commit template written properly
246
        # and has platform native line-endings (CRLF on win32)
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
247
        create_file = msgeditor._create_temp_file_with_commit_template
2472.4.2 by Alexander Belchenko
unwrapping long lines in tests
248
        msgfilename, hasinfo = create_file('infotext','----','start message')
2472.4.1 by Alexander Belchenko
Bugfix #110901: commit message template written with native line-endings; corresponding unit tests added
249
        self.assertNotEqual(None, msgfilename)
250
        self.assertTrue(hasinfo)
2472.4.2 by Alexander Belchenko
unwrapping long lines in tests
251
        expected = os.linesep.join(['start message',
252
                                    '',
253
                                    '',
254
                                    '----',
255
                                    '',
256
                                    'infotext'])
2472.4.1 by Alexander Belchenko
Bugfix #110901: commit message template written with native line-endings; corresponding unit tests added
257
        self.assertFileEqual(expected, msgfilename)
258
3004.1.1 by Daniel Watkins
Added (failing) test to check if a temp file containing a commit message can be created in a folder with a Unicode name.
259
    def test__create_temp_file_with_commit_template_in_unicode_dir(self):
3054.3.1 by Martin Pool
test__create_temp_file_with_commit_template_in_unicode_dir needs a unicode filesystem
260
        from bzrlib.tests.test_diff import UnicodeFilename
261
        self.requireFeature(UnicodeFilename)
3004.1.7 by Daniel Watkins
test__create_temp_file_with_commit_template_in_unicode_dir now uses EncodingTestAdapter info.
262
        if hasattr(self, 'info'):
263
            os.mkdir(self.info['directory'])
264
            os.chdir(self.info['directory'])
265
            msgeditor._create_temp_file_with_commit_template('infotext')
266
        else:
3004.1.8 by Daniel Watkins
Changed TestSkipped to TestNotApplicable as suggested by Aaron.
267
            raise TestNotApplicable('Test run elsewhere with non-ascii data.')
3004.1.1 by Daniel Watkins
Added (failing) test to check if a temp file containing a commit message can be created in a folder with a Unicode name.
268
2472.4.1 by Alexander Belchenko
Bugfix #110901: commit message template written with native line-endings; corresponding unit tests added
269
    def test__create_temp_file_with_empty_commit_template(self):
270
        # empty file
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
271
        create_file = msgeditor._create_temp_file_with_commit_template
2472.4.2 by Alexander Belchenko
unwrapping long lines in tests
272
        msgfilename, hasinfo = create_file('')
2472.4.1 by Alexander Belchenko
Bugfix #110901: commit message template written with native line-endings; corresponding unit tests added
273
        self.assertNotEqual(None, msgfilename)
274
        self.assertFalse(hasinfo)
275
        self.assertFileEqual('', msgfilename)
2625.9.6 by Daniel Watkins
Added test to ensure correct error message is thrown when an unencodable commit message is entered through the editor.
276
277
    def test_unsupported_encoding_commit_message(self):
278
        old_env = osutils.set_or_unset_env('LANG', 'C')
2625.9.8 by Daniel Watkins
Updated as per poolie's !tweak.
279
        try:
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
280
            # LANG env variable has no effect on Windows
281
            # but some characters anyway cannot be represented
282
            # in default user encoding
2839.6.2 by Alexander Belchenko
changes after Martin's review
283
            char = probe_bad_non_ascii(bzrlib.user_encoding)
284
            if char is None:
285
                raise TestSkipped('Cannot find suitable non-ascii character '
286
                    'for user_encoding (%s)' % bzrlib.user_encoding)
2804.4.1 by Alexander Belchenko
some win32-specific fixes for selftest
287
288
            self.make_fake_editor(message=char)
2625.9.6 by Daniel Watkins
Added test to ensure correct error message is thrown when an unencodable commit message is entered through the editor.
289
2625.9.8 by Daniel Watkins
Updated as per poolie's !tweak.
290
            working_tree = self.make_uncommitted_tree()
291
            self.assertRaises(errors.BadCommitMessageEncoding,
2772.1.1 by Martin Pool
Merge commit --show-diff feature from Goffredo
292
                              msgeditor.edit_commit_message, '')
2625.9.8 by Daniel Watkins
Updated as per poolie's !tweak.
293
        finally:
294
            osutils.set_or_unset_env('LANG', old_env)