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