/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_msgeditor.py

  • Committer: Andrew Bennetts
  • Date: 2008-03-14 17:07:55 UTC
  • mto: This revision was merged to the branch mainline in revision 3756.
  • Revision ID: andrew.bennetts@canonical.com-20080314170755-th4th2bapqdzowxa
More initial import hackery.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
#
 
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.
 
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
 
 
23
from bzrlib import (
 
24
    errors,
 
25
    msgeditor,
 
26
    osutils,
 
27
    )
 
28
from bzrlib.branch import Branch
 
29
from bzrlib.config import ensure_config_dir_exists, config_filename
 
30
from bzrlib.msgeditor import (
 
31
    make_commit_message_template_encoded,
 
32
    edit_commit_message_encoded
 
33
)
 
34
from bzrlib.tests import (
 
35
    iter_suite_tests,
 
36
    probe_bad_non_ascii,
 
37
    split_suite_by_re,
 
38
    TestCaseWithTransport,
 
39
    TestNotApplicable,
 
40
    TestSkipped,
 
41
    )
 
42
from bzrlib.tests.EncodingAdapter import EncodingTestAdapter
 
43
from bzrlib.trace import mutter
 
44
 
 
45
 
 
46
def load_tests(standard_tests, module, loader):
 
47
    """Parameterize the test for tempfile creation with different encodings."""
 
48
    to_adapt, result = split_suite_by_re(standard_tests,
 
49
        "test__create_temp_file_with_commit_template_in_unicode_dir")
 
50
    for test in iter_suite_tests(to_adapt):
 
51
        result.addTests(EncodingTestAdapter().adapt(test))
 
52
    return result
 
53
 
 
54
 
 
55
class MsgEditorTest(TestCaseWithTransport):
 
56
 
 
57
    def make_uncommitted_tree(self):
 
58
        """Build a branch with uncommitted unicode named changes in the cwd."""
 
59
        working_tree = self.make_branch_and_tree('.')
 
60
        b = working_tree.branch
 
61
        filename = u'hell\u00d8'
 
62
        try:
 
63
            self.build_tree_contents([(filename, 'contents of hello')])
 
64
        except UnicodeEncodeError:
 
65
            raise TestSkipped("can't build unicode working tree in "
 
66
                "filesystem encoding %s" % sys.getfilesystemencoding())
 
67
        working_tree.add(filename)
 
68
        return working_tree
 
69
    
 
70
    def test_commit_template(self):
 
71
        """Test building a commit message template"""
 
72
        working_tree = self.make_uncommitted_tree()
 
73
        template = msgeditor.make_commit_message_template(working_tree,
 
74
                                                                 None)
 
75
        self.assertEqualDiff(template,
 
76
u"""\
 
77
added:
 
78
  hell\u00d8
 
79
""")
 
80
 
 
81
    def test_commit_template_encoded(self):
 
82
        """Test building a commit message template"""
 
83
        working_tree = self.make_uncommitted_tree()
 
84
        template = make_commit_message_template_encoded(working_tree,
 
85
                                                        None,
 
86
                                                        output_encoding='utf8')
 
87
        self.assertEqualDiff(template,
 
88
u"""\
 
89
added:
 
90
  hell\u00d8
 
91
""".encode("utf8"))
 
92
 
 
93
 
 
94
    def test_commit_template_and_diff(self):
 
95
        """Test building a commit message template"""
 
96
        working_tree = self.make_uncommitted_tree()
 
97
        template = make_commit_message_template_encoded(working_tree,
 
98
                                                        None,
 
99
                                                        diff=True,
 
100
                                                        output_encoding='utf8')
 
101
 
 
102
        self.assertTrue("""\
 
103
@@ -0,0 +1,1 @@
 
104
+contents of hello
 
105
""" in template)
 
106
        self.assertTrue(u"""\
 
107
added:
 
108
  hell\u00d8
 
109
""".encode('utf8') in template)
 
110
 
 
111
    def test_run_editor(self):
 
112
        if sys.platform == "win32":
 
113
            f = file('fed.bat', 'w')
 
114
            f.write('@rem dummy fed')
 
115
            f.close()
 
116
            os.environ['BZR_EDITOR'] = 'fed.bat'
 
117
        else:
 
118
            f = file('fed.sh', 'wb')
 
119
            f.write('#!/bin/sh\n')
 
120
            f.close()
 
121
            os.chmod('fed.sh', 0755)
 
122
            os.environ['BZR_EDITOR'] = './fed.sh'
 
123
 
 
124
        self.assertEqual(True, msgeditor._run_editor(''),
 
125
                         'Unable to run dummy fake editor')
 
126
 
 
127
    def make_fake_editor(self, message='test message from fed\\n'):
 
128
        """Set up environment so that an editor will be a known script.
 
129
 
 
130
        Sets up BZR_EDITOR so that if an editor is spawned it will run a
 
131
        script that just adds a known message to the start of the file.
 
132
        """
 
133
        f = file('fed.py', 'wb')
 
134
        f.write('#!%s\n' % sys.executable)
 
135
        f.write("""\
 
136
# coding=utf-8
 
137
import sys
 
138
if len(sys.argv) == 2:
 
139
    fn = sys.argv[1]
 
140
    f = file(fn, 'rb')
 
141
    s = f.read()
 
142
    f.close()
 
143
    f = file(fn, 'wb')
 
144
    f.write('%s')
 
145
    f.write(s)
 
146
    f.close()
 
147
""" % (message, ))
 
148
        f.close()
 
149
        if sys.platform == "win32":
 
150
            # [win32] make batch file and set BZR_EDITOR
 
151
            f = file('fed.bat', 'w')
 
152
            f.write("""\
 
153
@echo off
 
154
"%s" fed.py %%1
 
155
""" % sys.executable)
 
156
            f.close()
 
157
            os.environ['BZR_EDITOR'] = 'fed.bat'
 
158
        else:
 
159
            # [non-win32] make python script executable and set BZR_EDITOR
 
160
            os.chmod('fed.py', 0755)
 
161
            os.environ['BZR_EDITOR'] = './fed.py'
 
162
 
 
163
    def test_edit_commit_message(self):
 
164
        working_tree = self.make_uncommitted_tree()
 
165
        self.make_fake_editor()
 
166
 
 
167
        mutter('edit_commit_message without infotext')
 
168
        self.assertEqual('test message from fed\n',
 
169
                         msgeditor.edit_commit_message(''))
 
170
 
 
171
        mutter('edit_commit_message with ascii string infotext')
 
172
        self.assertEqual('test message from fed\n',
 
173
                         msgeditor.edit_commit_message('spam'))
 
174
 
 
175
        mutter('edit_commit_message with unicode infotext')
 
176
        self.assertEqual('test message from fed\n',
 
177
                         msgeditor.edit_commit_message(u'\u1234'))
 
178
 
 
179
        tmpl = edit_commit_message_encoded(u'\u1234'.encode("utf8"))
 
180
        self.assertEqual('test message from fed\n', tmpl)
 
181
 
 
182
    def test_start_message(self):
 
183
        self.make_uncommitted_tree()
 
184
        self.make_fake_editor()
 
185
        self.assertEqual('test message from fed\nstart message\n',
 
186
                         msgeditor.edit_commit_message('',
 
187
                                              start_message='start message\n'))
 
188
        self.assertEqual('test message from fed\n',
 
189
                         msgeditor.edit_commit_message('',
 
190
                                              start_message=''))
 
191
 
 
192
    def test_deleted_commit_message(self):
 
193
        working_tree = self.make_uncommitted_tree()
 
194
 
 
195
        if sys.platform == 'win32':
 
196
            os.environ['BZR_EDITOR'] = 'cmd.exe /c del'
 
197
        else:
 
198
            os.environ['BZR_EDITOR'] = 'rm'
 
199
 
 
200
        self.assertRaises((IOError, OSError), msgeditor.edit_commit_message, '')
 
201
 
 
202
    def test__get_editor(self):
 
203
        # Test that _get_editor can return a decent list of items
 
204
        bzr_editor = os.environ.get('BZR_EDITOR')
 
205
        visual = os.environ.get('VISUAL')
 
206
        editor = os.environ.get('EDITOR')
 
207
        try:
 
208
            os.environ['BZR_EDITOR'] = 'bzr_editor'
 
209
            os.environ['VISUAL'] = 'visual'
 
210
            os.environ['EDITOR'] = 'editor'
 
211
 
 
212
            ensure_config_dir_exists()
 
213
            f = open(config_filename(), 'wb')
 
214
            f.write('editor = config_editor\n')
 
215
            f.close()
 
216
 
 
217
            editors = list(msgeditor._get_editor())
 
218
 
 
219
            self.assertEqual(['bzr_editor', 'config_editor', 'visual',
 
220
                              'editor'], editors[:4])
 
221
 
 
222
            if sys.platform == 'win32':
 
223
                self.assertEqual(['wordpad.exe', 'notepad.exe'], editors[4:])
 
224
            else:
 
225
                self.assertEqual(['/usr/bin/editor', 'vi', 'pico', 'nano',
 
226
                                  'joe'], editors[4:])
 
227
 
 
228
        finally:
 
229
            # Restore the environment
 
230
            if bzr_editor is None:
 
231
                del os.environ['BZR_EDITOR']
 
232
            else:
 
233
                os.environ['BZR_EDITOR'] = bzr_editor
 
234
            if visual is None:
 
235
                del os.environ['VISUAL']
 
236
            else:
 
237
                os.environ['VISUAL'] = visual
 
238
            if editor is None:
 
239
                del os.environ['EDITOR']
 
240
            else:
 
241
                os.environ['EDITOR'] = editor
 
242
 
 
243
    def test__create_temp_file_with_commit_template(self):
 
244
        # check that commit template written properly
 
245
        # and has platform native line-endings (CRLF on win32)
 
246
        create_file = msgeditor._create_temp_file_with_commit_template
 
247
        msgfilename, hasinfo = create_file('infotext','----','start message')
 
248
        self.assertNotEqual(None, msgfilename)
 
249
        self.assertTrue(hasinfo)
 
250
        expected = os.linesep.join(['start message',
 
251
                                    '',
 
252
                                    '',
 
253
                                    '----',
 
254
                                    '',
 
255
                                    'infotext'])
 
256
        self.assertFileEqual(expected, msgfilename)
 
257
 
 
258
    def test__create_temp_file_with_commit_template_in_unicode_dir(self):
 
259
        from bzrlib.tests.test_diff import UnicodeFilename
 
260
        self.requireFeature(UnicodeFilename)
 
261
        if hasattr(self, 'info'):
 
262
            os.mkdir(self.info['directory'])
 
263
            os.chdir(self.info['directory'])
 
264
            msgeditor._create_temp_file_with_commit_template('infotext')
 
265
        else:
 
266
            raise TestNotApplicable('Test run elsewhere with non-ascii data.')
 
267
 
 
268
    def test__create_temp_file_with_empty_commit_template(self):
 
269
        # empty file
 
270
        create_file = msgeditor._create_temp_file_with_commit_template
 
271
        msgfilename, hasinfo = create_file('')
 
272
        self.assertNotEqual(None, msgfilename)
 
273
        self.assertFalse(hasinfo)
 
274
        self.assertFileEqual('', msgfilename)
 
275
 
 
276
    def test_unsupported_encoding_commit_message(self):
 
277
        old_env = osutils.set_or_unset_env('LANG', 'C')
 
278
        try:
 
279
            # LANG env variable has no effect on Windows
 
280
            # but some characters anyway cannot be represented
 
281
            # in default user encoding
 
282
            char = probe_bad_non_ascii(osutils.get_user_encoding())
 
283
            if char is None:
 
284
                raise TestSkipped('Cannot find suitable non-ascii character '
 
285
                    'for user_encoding (%s)' % osutils.get_user_encoding())
 
286
 
 
287
            self.make_fake_editor(message=char)
 
288
 
 
289
            working_tree = self.make_uncommitted_tree()
 
290
            self.assertRaises(errors.BadCommitMessageEncoding,
 
291
                              msgeditor.edit_commit_message, '')
 
292
        finally:
 
293
            osutils.set_or_unset_env('LANG', old_env)