~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_msgeditor.py

  • Committer: INADA Naoki
  • Date: 2011-05-18 06:27:34 UTC
  • mfrom: (5887 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5894.
  • Revision ID: songofacandy@gmail.com-20110518062734-1ilhll0rrqyyp8um
merge from lp:bzr and resolve conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
22
22
 
23
23
from bzrlib import (
24
24
    commit,
 
25
    config,
25
26
    errors,
26
27
    msgeditor,
27
28
    osutils,
28
29
    tests,
29
30
    trace,
30
31
    )
31
 
from bzrlib.branch import Branch
32
 
from bzrlib.config import ensure_config_dir_exists, config_filename
33
32
from bzrlib.msgeditor import (
34
33
    make_commit_message_template_encoded,
35
34
    edit_commit_message_encoded
36
35
)
37
36
from bzrlib.tests import (
 
37
    TestCaseInTempDir,
38
38
    TestCaseWithTransport,
39
39
    TestNotApplicable,
40
40
    TestSkipped,
81
81
 
82
82
    def make_multiple_pending_tree(self):
83
83
        from bzrlib import config
84
 
        self.thisFailsStrictLockCheck() # clone?
85
84
        config.GlobalConfig().set_user_option('email',
86
85
                                              'Bilbo Baggins <bb@hobbit.net>')
87
86
        tree = self.make_branch_and_tree('a')
94
93
        tree3.commit('Feature Y, based on initial X work.',
95
94
                     timestamp=1233285960, timezone=0)
96
95
        tree.merge_from_branch(tree2.branch)
97
 
        tree.merge_from_branch(tree3.branch)
 
96
        tree.merge_from_branch(tree3.branch, force=True)
98
97
        return tree
99
98
 
100
99
    def test_commit_template_pending_merges(self):
142
141
  hell\u00d8
143
142
""".encode('utf8') in template)
144
143
 
145
 
    def make_do_nothing_editor(self):
 
144
    def make_do_nothing_editor(self, basename='fed'):
146
145
        if sys.platform == "win32":
147
 
            f = file('fed.bat', 'w')
 
146
            name = basename + '.bat'
 
147
            f = file(name, 'w')
148
148
            f.write('@rem dummy fed')
149
149
            f.close()
150
 
            return 'fed.bat'
 
150
            return name
151
151
        else:
152
 
            f = file('fed.sh', 'wb')
 
152
            name = basename + '.sh'
 
153
            f = file(name, 'wb')
153
154
            f.write('#!/bin/sh\n')
154
155
            f.close()
155
 
            os.chmod('fed.sh', 0755)
156
 
            return './fed.sh'
 
156
            os.chmod(name, 0755)
 
157
            return './' + name
157
158
 
158
159
    def test_run_editor(self):
159
 
        os.environ['BZR_EDITOR'] = self.make_do_nothing_editor()
 
160
        self.overrideEnv('BZR_EDITOR', self.make_do_nothing_editor())
160
161
        self.assertEqual(True, msgeditor._run_editor(''),
161
162
                         'Unable to run dummy fake editor')
162
163
 
 
164
    def test_parse_editor_name(self):
 
165
        """Correctly interpret names with spaces.
 
166
 
 
167
        See <https://bugs.launchpad.net/bzr/+bug/220331>
 
168
        """
 
169
        self.overrideEnv('BZR_EDITOR',
 
170
            '"%s"' % self.make_do_nothing_editor('name with spaces'))
 
171
        self.assertEqual(True, msgeditor._run_editor('a_filename'))    
 
172
 
163
173
    def make_fake_editor(self, message='test message from fed\\n'):
164
174
        """Set up environment so that an editor will be a known script.
165
175
 
190
200
"%s" fed.py %%1
191
201
""" % sys.executable)
192
202
            f.close()
193
 
            os.environ['BZR_EDITOR'] = 'fed.bat'
 
203
            self.overrideEnv('BZR_EDITOR', 'fed.bat')
194
204
        else:
195
205
            # [non-win32] make python script executable and set BZR_EDITOR
196
206
            os.chmod('fed.py', 0755)
197
 
            os.environ['BZR_EDITOR'] = './fed.py'
 
207
            self.overrideEnv('BZR_EDITOR', './fed.py')
198
208
 
199
209
    def test_edit_commit_message(self):
200
210
        working_tree = self.make_uncommitted_tree()
229
239
        working_tree = self.make_uncommitted_tree()
230
240
 
231
241
        if sys.platform == 'win32':
232
 
            os.environ['BZR_EDITOR'] = 'cmd.exe /c del'
 
242
            editor = 'cmd.exe /c del'
233
243
        else:
234
 
            os.environ['BZR_EDITOR'] = 'rm'
 
244
            editor = 'rm'
 
245
        self.overrideEnv('BZR_EDITOR', editor)
235
246
 
236
247
        self.assertRaises((IOError, OSError), msgeditor.edit_commit_message, '')
237
248
 
238
249
    def test__get_editor(self):
239
 
        # Test that _get_editor can return a decent list of items
240
 
        bzr_editor = os.environ.get('BZR_EDITOR')
241
 
        visual = os.environ.get('VISUAL')
242
 
        editor = os.environ.get('EDITOR')
243
 
        try:
244
 
            os.environ['BZR_EDITOR'] = 'bzr_editor'
245
 
            os.environ['VISUAL'] = 'visual'
246
 
            os.environ['EDITOR'] = 'editor'
247
 
 
248
 
            ensure_config_dir_exists()
249
 
            f = open(config_filename(), 'wb')
250
 
            f.write('editor = config_editor\n')
251
 
            f.close()
252
 
 
253
 
            editors = list(msgeditor._get_editor())
254
 
            editors = [editor for (editor, cfg_src) in editors]
255
 
 
256
 
            self.assertEqual(['bzr_editor', 'config_editor', 'visual',
257
 
                              'editor'], editors[:4])
258
 
 
259
 
            if sys.platform == 'win32':
260
 
                self.assertEqual(['wordpad.exe', 'notepad.exe'], editors[4:])
261
 
            else:
262
 
                self.assertEqual(['/usr/bin/editor', 'vi', 'pico', 'nano',
263
 
                                  'joe'], editors[4:])
264
 
 
265
 
        finally:
266
 
            # Restore the environment
267
 
            if bzr_editor is None:
268
 
                del os.environ['BZR_EDITOR']
269
 
            else:
270
 
                os.environ['BZR_EDITOR'] = bzr_editor
271
 
            if visual is None:
272
 
                del os.environ['VISUAL']
273
 
            else:
274
 
                os.environ['VISUAL'] = visual
275
 
            if editor is None:
276
 
                del os.environ['EDITOR']
277
 
            else:
278
 
                os.environ['EDITOR'] = editor
 
250
        self.overrideEnv('BZR_EDITOR', 'bzr_editor')
 
251
        self.overrideEnv('VISUAL', 'visual')
 
252
        self.overrideEnv('EDITOR', 'editor')
 
253
 
 
254
        conf = config.GlobalConfig.from_string('editor = config_editor\n',
 
255
                                               save=True)
 
256
 
 
257
        editors = list(msgeditor._get_editor())
 
258
        editors = [editor for (editor, cfg_src) in editors]
 
259
 
 
260
        self.assertEqual(['bzr_editor', 'config_editor', 'visual', 'editor'],
 
261
                         editors[:4])
 
262
 
 
263
        if sys.platform == 'win32':
 
264
            self.assertEqual(['wordpad.exe', 'notepad.exe'], editors[4:])
 
265
        else:
 
266
            self.assertEqual(['/usr/bin/editor', 'vi', 'pico', 'nano', 'joe'],
 
267
                             editors[4:])
 
268
 
279
269
 
280
270
    def test__run_editor_EACCES(self):
281
271
        """If running a configured editor raises EACESS, the user is warned."""
282
 
        os.environ['BZR_EDITOR'] = 'eacces.py'
 
272
        self.overrideEnv('BZR_EDITOR', 'eacces.py')
283
273
        f = file('eacces.py', 'wb')
284
274
        f.write('# Not a real editor')
285
275
        f.close()
287
277
        os.chmod('eacces.py', 0)
288
278
        # Set $EDITOR so that _run_editor will terminate before trying real
289
279
        # editors.
290
 
        os.environ['EDITOR'] = self.make_do_nothing_editor()
 
280
        self.overrideEnv('EDITOR', self.make_do_nothing_editor())
291
281
        # Call _run_editor, capturing mutter.warning calls.
292
282
        warnings = []
293
283
        def warning(*args):
294
 
            warnings.append(args[0] % args[1:])
 
284
            if len(args) > 1:
 
285
                warnings.append(args[0] % args[1:])
 
286
            else:
 
287
                warnings.append(args[0])
295
288
        _warning = trace.warning
296
289
        trace.warning = warning
297
290
        try:
318
311
    def test__create_temp_file_with_commit_template_in_unicode_dir(self):
319
312
        self.requireFeature(tests.UnicodeFilenameFeature)
320
313
        if hasattr(self, 'info'):
321
 
            os.mkdir(self.info['directory'])
322
 
            os.chdir(self.info['directory'])
323
 
            msgeditor._create_temp_file_with_commit_template('infotext')
 
314
            tmpdir = self.info['directory']
 
315
            os.mkdir(tmpdir)
 
316
            # Force the creation of temp file in a directory whose name
 
317
            # requires some encoding support
 
318
            msgeditor._create_temp_file_with_commit_template('infotext',
 
319
                                                             tmpdir=tmpdir)
324
320
        else:
325
321
            raise TestNotApplicable('Test run elsewhere with non-ascii data.')
326
322
 
333
329
        self.assertFileEqual('', msgfilename)
334
330
 
335
331
    def test_unsupported_encoding_commit_message(self):
336
 
        old_env = osutils.set_or_unset_env('LANG', 'C')
337
 
        try:
338
 
            # LANG env variable has no effect on Windows
339
 
            # but some characters anyway cannot be represented
340
 
            # in default user encoding
341
 
            char = probe_bad_non_ascii(osutils.get_user_encoding())
342
 
            if char is None:
343
 
                raise TestSkipped('Cannot find suitable non-ascii character '
344
 
                    'for user_encoding (%s)' % osutils.get_user_encoding())
345
 
 
346
 
            self.make_fake_editor(message=char)
347
 
 
348
 
            working_tree = self.make_uncommitted_tree()
349
 
            self.assertRaises(errors.BadCommitMessageEncoding,
350
 
                              msgeditor.edit_commit_message, '')
351
 
        finally:
352
 
            osutils.set_or_unset_env('LANG', old_env)
 
332
        self.overrideEnv('LANG', 'C')
 
333
        # LANG env variable has no effect on Windows
 
334
        # but some characters anyway cannot be represented
 
335
        # in default user encoding
 
336
        char = probe_bad_non_ascii(osutils.get_user_encoding())
 
337
        if char is None:
 
338
            raise TestSkipped('Cannot find suitable non-ascii character '
 
339
                'for user_encoding (%s)' % osutils.get_user_encoding())
 
340
 
 
341
        self.make_fake_editor(message=char)
 
342
 
 
343
        working_tree = self.make_uncommitted_tree()
 
344
        self.assertRaises(errors.BadCommitMessageEncoding,
 
345
                          msgeditor.edit_commit_message, '')
353
346
 
354
347
    def test_generate_commit_message_template_no_hooks(self):
355
348
        commit_obj = commit.Commit()
357
350
            msgeditor.generate_commit_message_template(commit_obj))
358
351
 
359
352
    def test_generate_commit_message_template_hook(self):
360
 
        def restoreDefaults():
361
 
            msgeditor.hooks['commit_message_template'] = []
362
 
        self.addCleanup(restoreDefaults)
363
353
        msgeditor.hooks.install_named_hook("commit_message_template",
364
354
                lambda commit_obj, msg: "save me some typing\n", None)
365
355
        commit_obj = commit.Commit()
366
356
        self.assertEquals("save me some typing\n",
367
357
            msgeditor.generate_commit_message_template(commit_obj))
 
358
 
 
359
 
 
360
# GZ 2009-11-17: This wants moving to osutils when the errno checking code is
 
361
class TestPlatformErrnoWorkarounds(TestCaseInTempDir):
 
362
    """Ensuring workarounds enshrined in code actually serve a purpose"""
 
363
 
 
364
    def test_subprocess_call_bad_file(self):
 
365
        if sys.platform != "win32":
 
366
            raise TestNotApplicable("Workarounds for windows only")
 
367
        import subprocess, errno
 
368
        ERROR_BAD_EXE_FORMAT = 193
 
369
        file("textfile.txt", "w").close()
 
370
        e = self.assertRaises(WindowsError, subprocess.call, "textfile.txt")
 
371
        self.assertEqual(e.errno, errno.ENOEXEC)
 
372
        self.assertEqual(e.winerror, ERROR_BAD_EXE_FORMAT)