~bzr-pqm/bzr/bzr.dev

0.32.4 by Martin von Gagern
Added some selftests executed through bash.
1
# Copyright (C) 2010 by 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
5636.1.2 by Vincent Ladeuil
Raise KnownFailure on windows for bug #709104.
17
import sys
18
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
19
import bzrlib
5147.5.13 by Martin von Gagern
Import modules in tests, not classes or functions.
20
from bzrlib import commands, tests
5255.4.4 by Martin von Gagern
Properly import bzrlib.tests.features.
21
from bzrlib.tests import features
5147.5.13 by Martin von Gagern
Import modules in tests, not classes or functions.
22
from bzrlib.plugins.bash_completion.bashcomp import *
23
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
24
import subprocess
5147.5.13 by Martin von Gagern
Import modules in tests, not classes or functions.
25
26
0.32.5 by Martin von Gagern
Test bash completion for tags.
27
class BashCompletionMixin(object):
28
    """Component for testing execution of a bash completion script."""
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
29
5255.4.4 by Martin von Gagern
Properly import bzrlib.tests.features.
30
    _test_needs_features = [features.bash_feature]
5636.1.1 by Vincent Ladeuil
Get rid of the useless __init__.
31
    script = None
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
32
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
33
    def complete(self, words, cword=-1):
0.32.5 by Martin von Gagern
Test bash completion for tags.
34
        """Perform a bash completion.
35
36
        :param words: a list of words representing the current command.
37
        :param cword: the current word to complete, defaults to the last one.
38
        """
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
39
        if self.script is None:
40
            self.script = self.get_script()
5255.4.4 by Martin von Gagern
Properly import bzrlib.tests.features.
41
        proc = subprocess.Popen([features.bash_feature.path,
5147.5.24 by Martin von Gagern
Move ExecutableFeature instances to tests.features module.
42
                                 '--noprofile'],
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
43
                                stdin=subprocess.PIPE,
44
                                stdout=subprocess.PIPE,
45
                                stderr=subprocess.PIPE)
46
        if cword < 0:
47
            cword = len(words) + cword
0.32.6 by Martin von Gagern
Reformat bash input snippet.
48
        input = '%s\n' % self.script
49
        input += ('COMP_WORDS=( %s )\n' %
50
                  ' '.join(["'"+w.replace("'", "'\\''")+"'" for w in words]))
51
        input += 'COMP_CWORD=%d\n' % cword
52
        input += '%s\n' % getattr(self, 'script_name', '_bzr')
53
        input += 'echo ${#COMPREPLY[*]}\n'
54
        input += "IFS=$'\\n'\n"
55
        input += 'echo "${COMPREPLY[*]}"\n'
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
56
        (out, err) = proc.communicate(input)
0.32.5 by Martin von Gagern
Test bash completion for tags.
57
        if '' != err:
58
            raise AssertionError('Unexpected error message:\n%s' % err)
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
59
        self.assertEqual('', err, 'No messages to standard error')
60
        #import sys
61
        #print >>sys.stdout, '---\n%s\n---\n%s\n---\n' % (input, out)
62
        lines = out.split('\n')
63
        nlines = int(lines[0])
64
        del lines[0]
65
        self.assertEqual('', lines[-1], 'Newline at end')
66
        del lines[-1]
67
        if nlines == 0 and len(lines) == 1 and lines[0] == '':
68
            del lines[0]
69
        self.assertEqual(nlines, len(lines), 'No newlines in generated words')
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
70
        self.completion_result = set(lines)
71
        return self.completion_result
72
73
    def assertCompletionEquals(self, *words):
74
        self.assertEqual(set(words), self.completion_result)
75
76
    def assertCompletionContains(self, *words):
77
        missing = set(words) - self.completion_result
0.32.5 by Martin von Gagern
Test bash completion for tags.
78
        if missing:
79
            raise AssertionError('Completion should contain %r but it has %r'
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
80
                                 % (missing, self.completion_result))
81
82
    def assertCompletionOmits(self, *words):
83
        surplus = set(words) & self.completion_result
0.32.5 by Martin von Gagern
Test bash completion for tags.
84
        if surplus:
85
            raise AssertionError('Completion should omit %r but it has %r'
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
86
                                 % (surplus, res, self.completion_result))
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
87
88
    def get_script(self):
0.32.12 by Martin von Gagern
Duplicate script creation steps in get_script testing method.
89
        commands.install_bzr_command_hooks()
90
        dc = DataCollector()
91
        data = dc.collect()
92
        cg = BashCodeGen(data)
93
        res = cg.function()
94
        return res
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
95
0.32.5 by Martin von Gagern
Test bash completion for tags.
96
5147.5.13 by Martin von Gagern
Import modules in tests, not classes or functions.
97
class TestBashCompletion(tests.TestCase, BashCompletionMixin):
0.32.5 by Martin von Gagern
Test bash completion for tags.
98
    """Test bash completions that don't execute bzr."""
99
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
100
    def test_simple_scipt(self):
101
        """Ensure that the test harness works as expected"""
102
        self.script = """
103
_bzr() {
104
    COMPREPLY=()
105
    # add all words in reverse order, with some markup around them
106
    for ((i = ${#COMP_WORDS[@]}; i > 0; --i)); do
107
        COMPREPLY+=( "-${COMP_WORDS[i-1]}+" )
108
    done
109
    # and append the current word
110
    COMPREPLY+=( "+${COMP_WORDS[COMP_CWORD]}-" )
111
}
112
"""
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
113
        self.complete(['foo', '"bar', "'baz"], cword=1)
114
        self.assertCompletionEquals("-'baz+", '-"bar+', '-foo+', '+"bar-')
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
115
116
    def test_cmd_ini(self):
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
117
        self.complete(['bzr', 'ini'])
118
        self.assertCompletionContains('init', 'init-repo', 'init-repository')
119
        self.assertCompletionOmits('commit')
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
120
121
    def test_init_opts(self):
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
122
        self.complete(['bzr', 'init', '-'])
123
        self.assertCompletionContains('-h', '--2a', '--format=2a')
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
124
125
    def test_global_opts(self):
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
126
        self.complete(['bzr', '-', 'init'], cword=1)
127
        self.assertCompletionContains('--no-plugins', '--builtin')
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
128
129
    def test_commit_dashm(self):
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
130
        self.complete(['bzr', 'commit', '-m'])
131
        self.assertCompletionEquals('-m')
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
132
133
    def test_status_negated(self):
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
134
        self.complete(['bzr', 'status', '--n'])
135
        self.assertCompletionContains('--no-versioned', '--no-verbose')
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
136
137
    def test_init_format_any(self):
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
138
        self.complete(['bzr', 'init', '--format', '=', 'directory'], cword=3)
139
        self.assertCompletionContains('1.9', '2a')
0.32.4 by Martin von Gagern
Added some selftests executed through bash.
140
141
    def test_init_format_2(self):
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
142
        self.complete(['bzr', 'init', '--format', '=', '2', 'directory'],
143
                      cword=4)
144
        self.assertCompletionContains('2a')
145
        self.assertCompletionOmits('1.9')
0.32.5 by Martin von Gagern
Test bash completion for tags.
146
147
5147.5.13 by Martin von Gagern
Import modules in tests, not classes or functions.
148
class TestBashCompletionInvoking(tests.TestCaseWithTransport,
149
                                 BashCompletionMixin):
0.32.5 by Martin von Gagern
Test bash completion for tags.
150
    """Test bash completions that might execute bzr.
151
152
    Only the syntax ``$(bzr ...`` is supported so far. The bzr command
153
    will be replaced by the bzr instance running this selftest.
154
    """
155
5636.1.2 by Vincent Ladeuil
Raise KnownFailure on windows for bug #709104.
156
    def setUp(self):
157
        super(TestBashCompletionInvoking, self).setUp()
158
        if sys.platform == 'win32':
159
            raise tests.KnownFailure(
160
                'see bug #709104, completion is broken on windows')
0.32.5 by Martin von Gagern
Test bash completion for tags.
161
162
    def get_script(self):
163
        s = super(TestBashCompletionInvoking, self).get_script()
164
        return s.replace("$(bzr ", "$('%s' " % self.get_bzr_path())
165
166
    def test_revspec_tag_all(self):
5255.4.4 by Martin von Gagern
Properly import bzrlib.tests.features.
167
        self.requireFeature(features.sed_feature)
0.32.7 by Martin von Gagern
Allow different formats for tag completion.
168
        wt = self.make_branch_and_tree('.', format='dirstate-tags')
0.32.5 by Martin von Gagern
Test bash completion for tags.
169
        wt.branch.tags.set_tag('tag1', 'null:')
0.32.16 by Martin von Gagern
Ensure proper quoting of spaces in tag names.
170
        wt.branch.tags.set_tag('tag2', 'null:')
0.32.5 by Martin von Gagern
Test bash completion for tags.
171
        wt.branch.tags.set_tag('3tag', 'null:')
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
172
        self.complete(['bzr', 'log', '-r', 'tag', ':'])
0.32.16 by Martin von Gagern
Ensure proper quoting of spaces in tag names.
173
        self.assertCompletionEquals('tag1', 'tag2', '3tag')
0.32.5 by Martin von Gagern
Test bash completion for tags.
174
175
    def test_revspec_tag_prefix(self):
5255.4.4 by Martin von Gagern
Properly import bzrlib.tests.features.
176
        self.requireFeature(features.sed_feature)
0.32.7 by Martin von Gagern
Allow different formats for tag completion.
177
        wt = self.make_branch_and_tree('.', format='dirstate-tags')
0.32.5 by Martin von Gagern
Test bash completion for tags.
178
        wt.branch.tags.set_tag('tag1', 'null:')
0.32.16 by Martin von Gagern
Ensure proper quoting of spaces in tag names.
179
        wt.branch.tags.set_tag('tag2', 'null:')
0.32.5 by Martin von Gagern
Test bash completion for tags.
180
        wt.branch.tags.set_tag('3tag', 'null:')
0.32.11 by Martin von Gagern
Turn completion assertions into separate methods.
181
        self.complete(['bzr', 'log', '-r', 'tag', ':', 't'])
0.32.16 by Martin von Gagern
Ensure proper quoting of spaces in tag names.
182
        self.assertCompletionEquals('tag1', 'tag2')
183
184
    def test_revspec_tag_spaces(self):
5255.4.4 by Martin von Gagern
Properly import bzrlib.tests.features.
185
        self.requireFeature(features.sed_feature)
0.32.16 by Martin von Gagern
Ensure proper quoting of spaces in tag names.
186
        wt = self.make_branch_and_tree('.', format='dirstate-tags')
187
        wt.branch.tags.set_tag('tag with spaces', 'null:')
188
        self.complete(['bzr', 'log', '-r', 'tag', ':', 't'])
189
        self.assertCompletionEquals(r'tag\ with\ spaces')
190
        self.complete(['bzr', 'log', '-r', '"tag:t'])
191
        self.assertCompletionEquals('tag:tag with spaces')
192
        self.complete(['bzr', 'log', '-r', "'tag:t"])
193
        self.assertCompletionEquals('tag:tag with spaces')
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
194
0.32.20 by Martin von Gagern
Allow completion of tags at end of revision range.
195
    def test_revspec_tag_endrange(self):
5255.4.4 by Martin von Gagern
Properly import bzrlib.tests.features.
196
        self.requireFeature(features.sed_feature)
0.32.20 by Martin von Gagern
Allow completion of tags at end of revision range.
197
        wt = self.make_branch_and_tree('.', format='dirstate-tags')
198
        wt.branch.tags.set_tag('tag1', 'null:')
199
        wt.branch.tags.set_tag('tag2', 'null:')
200
        self.complete(['bzr', 'log', '-r', '3..tag', ':', 't'])
201
        self.assertCompletionEquals('tag1', 'tag2')
202
        self.complete(['bzr', 'log', '-r', '"3..tag:t'])
203
        self.assertCompletionEquals('3..tag:tag1', '3..tag:tag2')
204
        self.complete(['bzr', 'log', '-r', "'3..tag:t"])
205
        self.assertCompletionEquals('3..tag:tag1', '3..tag:tag2')
206
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
207
5147.5.13 by Martin von Gagern
Import modules in tests, not classes or functions.
208
class TestBashCodeGen(tests.TestCase):
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
209
210
    def test_command_names(self):
211
        data = CompletionData()
212
        bar = CommandData('bar')
213
        bar.aliases.append('baz')
214
        data.commands.append(bar)
215
        data.commands.append(CommandData('foo'))
216
        cg = BashCodeGen(data)
217
        self.assertEqual('bar baz foo', cg.command_names())
218
219
    def test_debug_output(self):
220
        data = CompletionData()
221
        self.assertEqual('', BashCodeGen(data, debug=False).debug_output())
222
        self.assertTrue(BashCodeGen(data, debug=True).debug_output())
223
224
    def test_bzr_version(self):
225
        data = CompletionData()
226
        cg = BashCodeGen(data)
227
        self.assertEqual('%s.' % bzrlib.version_string, cg.bzr_version())
228
        data.plugins['foo'] = PluginData('foo', '1.0')
229
        data.plugins['bar'] = PluginData('bar', '2.0')
230
        cg = BashCodeGen(data)
231
        self.assertEqual('''\
232
%s and the following plugins:
233
# bar 2.0
234
# foo 1.0''' % bzrlib.version_string, cg.bzr_version())
235
236
    def test_global_options(self):
237
        data = CompletionData()
238
        data.global_options.add('--foo')
239
        data.global_options.add('--bar')
240
        cg = BashCodeGen(data)
241
        self.assertEqual('--bar --foo', cg.global_options())
242
243
    def test_command_cases(self):
244
        data = CompletionData()
245
        bar = CommandData('bar')
246
        bar.aliases.append('baz')
247
        bar.options.append(OptionData('--opt'))
248
        data.commands.append(bar)
249
        data.commands.append(CommandData('foo'))
250
        cg = BashCodeGen(data)
251
        self.assertEqualDiff('''\
252
\tbar|baz)
0.32.15 by Martin von Gagern
Allow spaces in tag names. Use bash arrays more extensively.
253
\t\tcmdOpts=( --opt )
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
254
\t\t;;
255
\tfoo)
0.32.15 by Martin von Gagern
Allow spaces in tag names. Use bash arrays more extensively.
256
\t\tcmdOpts=(  )
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
257
\t\t;;
258
''', cg.command_cases())
259
260
    def test_command_case(self):
261
        cmd = CommandData('cmd')
262
        cmd.plugin = PluginData('plugger', '1.0')
263
        bar = OptionData('--bar')
264
        bar.registry_keys = ['that', 'this']
265
        bar.error_messages.append('Some error message')
266
        cmd.options.append(bar)
267
        cmd.options.append(OptionData('--foo'))
268
        data = CompletionData()
269
        data.commands.append(cmd)
270
        cg = BashCodeGen(data)
271
        self.assertEqualDiff('''\
272
\tcmd)
273
\t\t# plugin "plugger 1.0"
274
\t\t# Some error message
0.32.15 by Martin von Gagern
Allow spaces in tag names. Use bash arrays more extensively.
275
\t\tcmdOpts=( --bar=that --bar=this --foo )
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
276
\t\tcase $curOpt in
0.32.15 by Martin von Gagern
Allow spaces in tag names. Use bash arrays more extensively.
277
\t\t\t--bar) optEnums=( that this ) ;;
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
278
\t\tesac
279
\t\t;;
280
''', cg.command_case(cmd))
281
282
5147.5.13 by Martin von Gagern
Import modules in tests, not classes or functions.
283
class TestDataCollector(tests.TestCase):
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
284
285
    def setUp(self):
286
        super(TestDataCollector, self).setUp()
287
        commands.install_bzr_command_hooks()
288
289
    def test_global_options(self):
290
        dc = DataCollector()
291
        dc.global_options()
292
        self.assertSubset(['--no-plugins', '--builtin'],
293
                           dc.data.global_options)
294
295
    def test_commands(self):
296
        dc = DataCollector()
297
        dc.commands()
298
        self.assertSubset(['init', 'init-repo', 'init-repository'],
299
                           dc.data.all_command_aliases())
300
0.32.19 by Martin von Gagern
Add test ensuring plugin commands get collected.
301
    def test_commands_from_plugins(self):
302
        dc = DataCollector()
303
        dc.commands()
304
        self.assertSubset(['bash-completion'],
305
                           dc.data.all_command_aliases())
306
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
307
    def test_commit_dashm(self):
308
        dc = DataCollector()
309
        cmd = dc.command('commit')
310
        self.assertSubset(['-m'],
311
                           [str(o) for o in cmd.options])
312
313
    def test_status_negated(self):
314
        dc = DataCollector()
315
        cmd = dc.command('status')
316
        self.assertSubset(['--no-versioned', '--no-verbose'],
317
                           [str(o) for o in cmd.options])
318
319
    def test_init_format(self):
320
        dc = DataCollector()
321
        cmd = dc.command('init')
322
        for opt in cmd.options:
323
            if opt.name == '--format':
324
                self.assertSubset(['2a'], opt.registry_keys)
325
                return
326
        raise AssertionError('Option --format not found')
6386.1.1 by Jelmer Vernooij
Fix bash_completion plugin.
327
328
329
class BlackboxTests(tests.TestCase):
330
331
    def test_bash_completion(self):
332
        self.run_bzr("bash-completion")