~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_msgeditor.py

  • Committer: Ian Clatworthy
  • Date: 2009-07-22 14:07:56 UTC
  • mto: (4568.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4569.
  • Revision ID: ian.clatworthy@canonical.com-20090722140756-rx3dbtf3rlubfy4r
Improve the names and location of the quick reference cards

Show diffs side-by-side

added added

removed removed

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