/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 breezy/tests/test_msgeditor.py

  • Committer: Breezy landing bot
  • Author(s): Colin Watson
  • Date: 2020-11-16 21:47:08 UTC
  • mfrom: (7521.1.1 remove-lp-workaround)
  • Revision ID: breezy.the.bot@gmail.com-20201116214708-jos209mgxi41oy15
Remove breezy.git workaround for bazaar.launchpad.net.

Merged from https://code.launchpad.net/~cjwatson/brz/remove-lp-workaround/+merge/393710

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2012, 2016 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
20
20
import os
21
21
import sys
22
22
 
23
 
from bzrlib import (
 
23
from .. import (
24
24
    commit,
25
25
    config,
26
26
    errors,
28
28
    osutils,
29
29
    trace,
30
30
    )
31
 
from bzrlib.msgeditor import (
 
31
from ..msgeditor import (
32
32
    make_commit_message_template_encoded,
33
33
    edit_commit_message_encoded
34
34
)
35
 
from bzrlib.tests import (
 
35
from . import (
36
36
    features,
37
37
    TestCaseInTempDir,
38
38
    TestCaseWithTransport,
39
39
    TestNotApplicable,
40
 
    TestSkipped,
41
40
    multiply_tests,
42
41
    probe_bad_non_ascii,
 
42
    probe_unicode_in_user_encoding,
43
43
    split_suite_by_re,
44
44
    )
45
 
from bzrlib.tests.EncodingAdapter import encoding_scenarios
46
 
from bzrlib.trace import mutter
47
 
 
48
 
 
49
 
def load_tests(standard_tests, module, loader):
 
45
from .EncodingAdapter import encoding_scenarios
 
46
from ..trace import mutter
 
47
 
 
48
 
 
49
def load_tests(loader, standard_tests, pattern):
50
50
    """Parameterize the test for tempfile creation with different encodings."""
51
 
    to_adapt, result = split_suite_by_re(standard_tests,
 
51
    to_adapt, result = split_suite_by_re(
 
52
        standard_tests,
52
53
        "test__create_temp_file_with_commit_template_in_unicode_dir")
53
54
    return multiply_tests(to_adapt, encoding_scenarios, result)
54
55
 
58
59
    def make_uncommitted_tree(self):
59
60
        """Build a branch with uncommitted unicode named changes in the cwd."""
60
61
        working_tree = self.make_branch_and_tree('.')
61
 
        b = working_tree.branch
62
62
        filename = u'hell\u00d8'
63
63
        try:
64
 
            self.build_tree_contents([(filename, 'contents of hello')])
 
64
            self.build_tree_contents([(filename, b'contents of hello')])
65
65
        except UnicodeEncodeError:
66
 
            raise TestSkipped("can't build unicode working tree in "
67
 
                "filesystem encoding %s" % sys.getfilesystemencoding())
 
66
            self.skipTest("can't build unicode working tree in "
 
67
                          "filesystem encoding %s" % sys.getfilesystemencoding())
68
68
        working_tree.add(filename)
69
69
        return working_tree
70
70
 
72
72
        """Test building a commit message template"""
73
73
        working_tree = self.make_uncommitted_tree()
74
74
        template = msgeditor.make_commit_message_template(working_tree,
75
 
                                                                 None)
 
75
                                                          None)
76
76
        self.assertEqualDiff(template,
77
 
u"""\
 
77
                             u"""\
78
78
added:
79
79
  hell\u00d8
80
80
""")
83
83
        config.GlobalStack().set('email', 'Bilbo Baggins <bb@hobbit.net>')
84
84
        tree = self.make_branch_and_tree('a')
85
85
        tree.commit('Initial checkin.', timestamp=1230912900, timezone=0)
86
 
        tree2 = tree.bzrdir.clone('b').open_workingtree()
 
86
        tree2 = tree.controldir.clone('b').open_workingtree()
87
87
        tree.commit('Minor tweak.', timestamp=1231977840, timezone=0)
88
88
        tree2.commit('Feature X work.', timestamp=1233186240, timezone=0)
89
 
        tree3 = tree2.bzrdir.clone('c').open_workingtree()
 
89
        tree3 = tree2.controldir.clone('c').open_workingtree()
90
90
        tree2.commit('Feature X finished.', timestamp=1233187680, timezone=0)
91
91
        tree3.commit('Feature Y, based on initial X work.',
92
92
                     timestamp=1233285960, timezone=0)
102
102
        working_tree = self.make_multiple_pending_tree()
103
103
        template = msgeditor.make_commit_message_template(working_tree, None)
104
104
        self.assertEqualDiff(template,
105
 
u"""\
 
105
                             u"""\
106
106
pending merges:
107
107
  Bilbo Baggins 2009-01-29 Feature X finished.
108
108
    Bilbo Baggins 2009-01-28 Feature X work.
116
116
                                                        None,
117
117
                                                        output_encoding='utf8')
118
118
        self.assertEqualDiff(template,
119
 
u"""\
 
119
                             u"""\
120
120
added:
121
121
  hell\u00d8
122
122
""".encode("utf8"))
123
123
 
124
 
 
125
124
    def test_commit_template_and_diff(self):
126
125
        """Test building a commit message template"""
127
126
        working_tree = self.make_uncommitted_tree()
130
129
                                                        diff=True,
131
130
                                                        output_encoding='utf8')
132
131
 
133
 
        self.assertTrue("""\
 
132
        self.assertTrue(b"""\
134
133
@@ -0,0 +1,1 @@
135
134
+contents of hello
136
135
""" in template)
142
141
    def make_do_nothing_editor(self, basename='fed'):
143
142
        if sys.platform == "win32":
144
143
            name = basename + '.bat'
145
 
            f = file(name, 'w')
146
 
            f.write('@rem dummy fed')
147
 
            f.close()
 
144
            with open(name, 'w') as f:
 
145
                f.write('@rem dummy fed')
148
146
            return name
149
147
        else:
150
148
            name = basename + '.sh'
151
 
            f = file(name, 'wb')
152
 
            f.write('#!/bin/sh\n')
153
 
            f.close()
154
 
            os.chmod(name, 0755)
 
149
            with open(name, 'wb') as f:
 
150
                f.write(b'#!/bin/sh\n')
 
151
            os.chmod(name, 0o755)
155
152
            return './' + name
156
153
 
157
154
    def test_run_editor(self):
158
 
        self.overrideEnv('BZR_EDITOR', self.make_do_nothing_editor())
 
155
        self.overrideEnv('BRZ_EDITOR', self.make_do_nothing_editor())
159
156
        self.assertEqual(True, msgeditor._run_editor(''),
160
157
                         'Unable to run dummy fake editor')
161
158
 
164
161
 
165
162
        See <https://bugs.launchpad.net/bzr/+bug/220331>
166
163
        """
167
 
        self.overrideEnv('BZR_EDITOR',
168
 
            '"%s"' % self.make_do_nothing_editor('name with spaces'))
169
 
        self.assertEqual(True, msgeditor._run_editor('a_filename'))    
 
164
        self.overrideEnv('BRZ_EDITOR',
 
165
                         '"%s"' % self.make_do_nothing_editor('name with spaces'))
 
166
        self.assertEqual(True, msgeditor._run_editor('a_filename'))
170
167
 
171
 
    def make_fake_editor(self, message='test message from fed\\n'):
 
168
    def make_fake_editor(self, message='test message from fed\n'):
172
169
        """Set up environment so that an editor will be a known script.
173
170
 
174
 
        Sets up BZR_EDITOR so that if an editor is spawned it will run a
 
171
        Sets up BRZ_EDITOR so that if an editor is spawned it will run a
175
172
        script that just adds a known message to the start of the file.
176
173
        """
177
 
        f = file('fed.py', 'wb')
178
 
        f.write('#!%s\n' % sys.executable)
179
 
        f.write("""\
 
174
        if not isinstance(message, bytes):
 
175
            message = message.encode('utf-8')
 
176
        with open('fed.py', 'w') as f:
 
177
            f.write('#!%s\n' % sys.executable)
 
178
            f.write("""\
180
179
# coding=utf-8
181
180
import sys
182
181
if len(sys.argv) == 2:
183
182
    fn = sys.argv[1]
184
 
    f = file(fn, 'rb')
185
 
    s = f.read()
186
 
    f.close()
187
 
    f = file(fn, 'wb')
188
 
    f.write('%s')
189
 
    f.write(s)
190
 
    f.close()
 
183
    with open(fn, 'rb') as f:
 
184
        s = f.read()
 
185
    with open(fn, 'wb') as f:
 
186
        f.write(%r)
 
187
        f.write(s)
191
188
""" % (message, ))
192
 
        f.close()
193
189
        if sys.platform == "win32":
194
 
            # [win32] make batch file and set BZR_EDITOR
195
 
            f = file('fed.bat', 'w')
196
 
            f.write("""\
 
190
            # [win32] make batch file and set BRZ_EDITOR
 
191
            with open('fed.bat', 'w') as f:
 
192
                f.write("""\
197
193
@echo off
198
194
"%s" fed.py %%1
199
195
""" % sys.executable)
200
 
            f.close()
201
 
            self.overrideEnv('BZR_EDITOR', 'fed.bat')
 
196
            self.overrideEnv('BRZ_EDITOR', 'fed.bat')
202
197
        else:
203
 
            # [non-win32] make python script executable and set BZR_EDITOR
204
 
            os.chmod('fed.py', 0755)
205
 
            self.overrideEnv('BZR_EDITOR', './fed.py')
 
198
            # [non-win32] make python script executable and set BRZ_EDITOR
 
199
            os.chmod('fed.py', 0o755)
 
200
            self.overrideEnv('BRZ_EDITOR', './fed.py')
206
201
 
207
 
    def test_edit_commit_message(self):
208
 
        working_tree = self.make_uncommitted_tree()
 
202
    def test_edit_commit_message_without_infotext(self):
 
203
        self.make_uncommitted_tree()
209
204
        self.make_fake_editor()
210
205
 
211
206
        mutter('edit_commit_message without infotext')
212
207
        self.assertEqual('test message from fed\n',
213
208
                         msgeditor.edit_commit_message(''))
214
209
 
 
210
    def test_edit_commit_message_with_ascii_infotext(self):
 
211
        self.make_uncommitted_tree()
 
212
        self.make_fake_editor()
 
213
 
215
214
        mutter('edit_commit_message with ascii string infotext')
216
215
        self.assertEqual('test message from fed\n',
217
216
                         msgeditor.edit_commit_message('spam'))
218
217
 
 
218
    def test_edit_commit_message_with_unicode_infotext(self):
 
219
        self.make_uncommitted_tree()
 
220
        self.make_fake_editor()
 
221
 
219
222
        mutter('edit_commit_message with unicode infotext')
 
223
        uni_val, ue_val = probe_unicode_in_user_encoding()
 
224
        if ue_val is None:
 
225
            self.skipTest(
 
226
                'Cannot find a unicode character that works in encoding %s'
 
227
                % (osutils.get_user_encoding(),))
 
228
 
220
229
        self.assertEqual('test message from fed\n',
221
 
                         msgeditor.edit_commit_message(u'\u1234'))
 
230
                         msgeditor.edit_commit_message(uni_val))
222
231
 
223
232
        tmpl = edit_commit_message_encoded(u'\u1234'.encode("utf8"))
224
233
        self.assertEqual('test message from fed\n', tmpl)
227
236
        self.make_uncommitted_tree()
228
237
        self.make_fake_editor()
229
238
        self.assertEqual('test message from fed\nstart message\n',
230
 
                         msgeditor.edit_commit_message('',
231
 
                                              start_message='start message\n'))
 
239
                         msgeditor.edit_commit_message(
 
240
                             '', start_message='start message\n'))
232
241
        self.assertEqual('test message from fed\n',
233
 
                         msgeditor.edit_commit_message('',
234
 
                                              start_message=''))
 
242
                         msgeditor.edit_commit_message(
 
243
                             '', start_message=''))
235
244
 
236
245
    def test_deleted_commit_message(self):
237
 
        working_tree = self.make_uncommitted_tree()
 
246
        self.make_uncommitted_tree()
238
247
 
239
248
        if sys.platform == 'win32':
240
249
            editor = 'cmd.exe /c del'
241
250
        else:
242
251
            editor = 'rm'
243
 
        self.overrideEnv('BZR_EDITOR', editor)
 
252
        self.overrideEnv('BRZ_EDITOR', editor)
244
253
 
245
 
        self.assertRaises((IOError, OSError), msgeditor.edit_commit_message, '')
 
254
        self.assertRaises((EnvironmentError, errors.NoSuchFile),
 
255
                          msgeditor.edit_commit_message, '')
246
256
 
247
257
    def test__get_editor(self):
248
 
        self.overrideEnv('BZR_EDITOR', 'bzr_editor')
 
258
        self.overrideEnv('BRZ_EDITOR', 'bzr_editor')
249
259
        self.overrideEnv('VISUAL', 'visual')
250
260
        self.overrideEnv('EDITOR', 'editor')
251
261
 
252
262
        conf = config.GlobalStack()
253
 
        conf.store._load_from_string('[DEFAULT]\neditor = config_editor\n')
 
263
        conf.store._load_from_string(b'[DEFAULT]\neditor = config_editor\n')
254
264
        conf.store.save()
255
265
        editors = list(msgeditor._get_editor())
256
266
        editors = [editor for (editor, cfg_src) in editors]
264
274
            self.assertEqual(['/usr/bin/editor', 'vi', 'pico', 'nano', 'joe'],
265
275
                             editors[4:])
266
276
 
267
 
 
268
277
    def test__run_editor_EACCES(self):
269
278
        """If running a configured editor raises EACESS, the user is warned."""
270
 
        self.overrideEnv('BZR_EDITOR', 'eacces.py')
271
 
        f = file('eacces.py', 'wb')
272
 
        f.write('# Not a real editor')
273
 
        f.close()
 
279
        self.overrideEnv('BRZ_EDITOR', 'eacces.py')
 
280
        with open('eacces.py', 'wb') as f:
 
281
            f.write(b'# Not a real editor')
274
282
        # Make the fake editor unreadable (and unexecutable)
275
283
        os.chmod('eacces.py', 0)
276
284
        # Set $EDITOR so that _run_editor will terminate before trying real
278
286
        self.overrideEnv('EDITOR', self.make_do_nothing_editor())
279
287
        # Call _run_editor, capturing mutter.warning calls.
280
288
        warnings = []
 
289
 
281
290
        def warning(*args):
282
291
            if len(args) > 1:
283
292
                warnings.append(args[0] % args[1:])
289
298
            msgeditor._run_editor('')
290
299
        finally:
291
300
            trace.warning = _warning
292
 
        self.assertStartsWith(warnings[0], 'Could not start editor "eacces.py"')
 
301
        self.assertStartsWith(
 
302
            warnings[0], 'Could not start editor "eacces.py"')
293
303
 
294
304
    def test__create_temp_file_with_commit_template(self):
295
305
        # check that commit template written properly
296
306
        # and has platform native line-endings (CRLF on win32)
297
307
        create_file = msgeditor._create_temp_file_with_commit_template
298
 
        msgfilename, hasinfo = create_file('infotext','----','start message')
 
308
        msgfilename, hasinfo = create_file(
 
309
            b'infotext', '----', b'start message')
299
310
        self.assertNotEqual(None, msgfilename)
300
311
        self.assertTrue(hasinfo)
301
312
        expected = os.linesep.join(['start message',
313
324
            os.mkdir(tmpdir)
314
325
            # Force the creation of temp file in a directory whose name
315
326
            # requires some encoding support
316
 
            msgeditor._create_temp_file_with_commit_template('infotext',
 
327
            msgeditor._create_temp_file_with_commit_template(b'infotext',
317
328
                                                             tmpdir=tmpdir)
318
329
        else:
319
330
            raise TestNotApplicable('Test run elsewhere with non-ascii data.')
333
344
        # in default user encoding
334
345
        char = probe_bad_non_ascii(osutils.get_user_encoding())
335
346
        if char is None:
336
 
            raise TestSkipped('Cannot find suitable non-ascii character '
 
347
            self.skipTest(
 
348
                'Cannot find suitable non-ascii character '
337
349
                'for user_encoding (%s)' % osutils.get_user_encoding())
338
350
 
339
351
        self.make_fake_editor(message=char)
340
352
 
341
 
        working_tree = self.make_uncommitted_tree()
342
 
        self.assertRaises(errors.BadCommitMessageEncoding,
 
353
        self.make_uncommitted_tree()
 
354
        self.assertRaises(msgeditor.BadCommitMessageEncoding,
343
355
                          msgeditor.edit_commit_message, '')
344
356
 
345
357
    def test_set_commit_message_no_hooks(self):
346
358
        commit_obj = commit.Commit()
347
359
        self.assertIs(None,
348
 
            msgeditor.set_commit_message(commit_obj))
 
360
                      msgeditor.set_commit_message(commit_obj))
349
361
 
350
362
    def test_set_commit_message_hook(self):
351
363
        msgeditor.hooks.install_named_hook("set_commit_message",
352
 
                lambda commit_obj, existing_message: "save me some typing\n", None)
 
364
                                           lambda commit_obj, existing_message: "save me some typing\n", None)
353
365
        commit_obj = commit.Commit()
354
 
        self.assertEquals("save me some typing\n",
355
 
            msgeditor.set_commit_message(commit_obj))
 
366
        self.assertEqual("save me some typing\n",
 
367
                         msgeditor.set_commit_message(commit_obj))
356
368
 
357
369
    def test_generate_commit_message_template_no_hooks(self):
358
370
        commit_obj = commit.Commit()
359
371
        self.assertIs(None,
360
 
            msgeditor.generate_commit_message_template(commit_obj))
 
372
                      msgeditor.generate_commit_message_template(commit_obj))
361
373
 
362
374
    def test_generate_commit_message_template_hook(self):
363
375
        msgeditor.hooks.install_named_hook("commit_message_template",
364
 
                lambda commit_obj, msg: "save me some typing\n", None)
 
376
                                           lambda commit_obj, msg: "save me some typing\n", None)
365
377
        commit_obj = commit.Commit()
366
 
        self.assertEquals("save me some typing\n",
367
 
            msgeditor.generate_commit_message_template(commit_obj))
 
378
        self.assertEqual("save me some typing\n",
 
379
                         msgeditor.generate_commit_message_template(commit_obj))
368
380
 
369
381
 
370
382
# GZ 2009-11-17: This wants moving to osutils when the errno checking code is
374
386
    def test_subprocess_call_bad_file(self):
375
387
        if sys.platform != "win32":
376
388
            raise TestNotApplicable("Workarounds for windows only")
377
 
        import subprocess, errno
 
389
        import subprocess
 
390
        import errno
378
391
        ERROR_BAD_EXE_FORMAT = 193
379
 
        file("textfile.txt", "w").close()
 
392
        open("textfile.txt", "w").close()
380
393
        e = self.assertRaises(WindowsError, subprocess.call, "textfile.txt")
381
394
        self.assertEqual(e.errno, errno.ENOEXEC)
382
395
        self.assertEqual(e.winerror, ERROR_BAD_EXE_FORMAT)