aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_shellcomp.py
blob: 7f9cc833833795875b14ab4deb1cedf4e30ff0ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Test cases for twisted.python._shellcomp
"""

import sys
from cStringIO import StringIO

from twisted.trial import unittest
from twisted.python import _shellcomp, usage, reflect
from twisted.python.usage import Completions, Completer, CompleteFiles
from twisted.python.usage import CompleteList



class ZshScriptTestMeta(type):
    """
    Metaclass of ZshScriptTestMixin.
    """
    def __new__(cls, name, bases, attrs):
        def makeTest(cmdName, optionsFQPN):
            def runTest(self):
                return test_genZshFunction(self, cmdName, optionsFQPN)
            return runTest

        # add test_ methods to the class for each script
        # we are testing.
        if 'generateFor' in attrs:
            for cmdName, optionsFQPN in attrs['generateFor']:
                test = makeTest(cmdName, optionsFQPN)
                attrs['test_genZshFunction_' + cmdName] = test

        return type.__new__(cls, name, bases, attrs)



class ZshScriptTestMixin(object):
    """
    Integration test helper to show that C{usage.Options} classes can have zsh
    completion functions generated for them without raising errors.

    In your subclasses set a class variable like so:

    #            | cmd name | Fully Qualified Python Name of Options class |
    #
    generateFor = [('conch',  'twisted.conch.scripts.conch.ClientOptions'),
                   ('twistd', 'twisted.scripts.twistd.ServerOptions'),
                   ]

    Each package that contains Twisted scripts should contain one TestCase
    subclass which also inherits from this mixin, and contains a C{generateFor}
    list appropriate for the scripts in that package.
    """
    __metaclass__ = ZshScriptTestMeta



def test_genZshFunction(self, cmdName, optionsFQPN):
    """
    Generate completion functions for given twisted command - no errors
    should be raised

    @type cmdName: C{str}
    @param cmdName: The name of the command-line utility e.g. 'twistd'

    @type optionsFQPN: C{str}
    @param optionsFQPN: The Fully Qualified Python Name of the C{Options}
        class to be tested.
    """
    outputFile = StringIO()
    self.patch(usage.Options, '_shellCompFile', outputFile)

    # some scripts won't import or instantiate because of missing
    # dependencies (PyCrypto, etc) so we have to skip them.
    try:
        o = reflect.namedAny(optionsFQPN)()
    except Exception, e:
        raise unittest.SkipTest("Couldn't import or instantiate "
                                "Options class: %s" % (e,))

    try:
        o.parseOptions(["", "--_shell-completion", "zsh:2"])
    except ImportError, e:
        # this can happen for commands which don't have all
        # the necessary dependencies installed. skip test.
        # skip
        raise unittest.SkipTest("ImportError calling parseOptions(): %s", (e,))
    except SystemExit:
        pass # expected
    else:
        self.fail('SystemExit not raised')
    outputFile.seek(0)
    # test that we got some output
    self.assertEqual(1, len(outputFile.read(1)))
    outputFile.seek(0)
    outputFile.truncate()

    # now, if it has sub commands, we have to test those too
    if hasattr(o, 'subCommands'):
        for (cmd, short, parser, doc) in o.subCommands:
            try:
                o.parseOptions([cmd, "", "--_shell-completion",
                                "zsh:3"])
            except ImportError, e:
                # this can happen for commands which don't have all
                # the necessary dependencies installed. skip test.
                raise unittest.SkipTest("ImportError calling parseOptions() "
                        "on subcommand: %s", (e,))
            except SystemExit:
                pass # expected
            else:
                self.fail('SystemExit not raised')

            outputFile.seek(0)
            # test that we got some output
            self.assertEqual(1, len(outputFile.read(1)))
            outputFile.seek(0)
            outputFile.truncate()

    # flushed because we don't want DeprecationWarnings to be printed when
    # running these test cases.
    self.flushWarnings()



class ZshTestCase(unittest.TestCase):
    """
    Tests for zsh completion code
    """
    def test_accumulateMetadata(self):
        """
        Are `compData' attributes you can place on Options classes
        picked up correctly?
        """
        opts = FighterAceExtendedOptions()
        ag = _shellcomp.ZshArgumentsGenerator(opts, 'ace', 'dummy_value')

        descriptions = FighterAceOptions.compData.descriptions.copy()
        descriptions.update(FighterAceExtendedOptions.compData.descriptions)

        self.assertEqual(ag.descriptions, descriptions)
        self.assertEqual(ag.multiUse,
                          set(FighterAceOptions.compData.multiUse))
        self.assertEqual(ag.mutuallyExclusive,
                          FighterAceOptions.compData.mutuallyExclusive)

        optActions = FighterAceOptions.compData.optActions.copy()
        optActions.update(FighterAceExtendedOptions.compData.optActions)
        self.assertEqual(ag.optActions, optActions)

        self.assertEqual(ag.extraActions,
                          FighterAceOptions.compData.extraActions)


    def test_mutuallyExclusiveCornerCase(self):
        """
        Exercise a corner-case of ZshArgumentsGenerator.makeExcludesDict()
        where the long option name already exists in the `excludes` dict being
        built.
        """
        class OddFighterAceOptions(FighterAceExtendedOptions):
            # since "fokker", etc, are already defined as mutually-
            # exclusive on the super-class, defining them again here forces
            # the corner-case to be exercised.
            optFlags = [['anatra', None,
                         'Select the Anatra DS as your dogfighter aircraft']]
            compData = Completions(
                            mutuallyExclusive=[['anatra', 'fokker', 'albatros',
                                                'spad', 'bristol']])

        opts = OddFighterAceOptions()
        ag = _shellcomp.ZshArgumentsGenerator(opts, 'ace', 'dummy_value')

        expected = {
             'albatros': set(['anatra', 'b', 'bristol', 'f',
                              'fokker', 's', 'spad']),
             'anatra': set(['a', 'albatros', 'b', 'bristol',
                            'f', 'fokker', 's', 'spad']),
             'bristol': set(['a', 'albatros', 'anatra', 'f',
                             'fokker', 's', 'spad']),
             'fokker': set(['a', 'albatros', 'anatra', 'b',
                            'bristol', 's', 'spad']),
             'spad': set(['a', 'albatros', 'anatra', 'b',
                          'bristol', 'f', 'fokker'])}

        self.assertEqual(ag.excludes, expected)


    def test_accumulateAdditionalOptions(self):
        """
        We pick up options that are only defined by having an
        appropriately named method on your Options class,
        e.g. def opt_foo(self, foo)
        """
        opts = FighterAceExtendedOptions()
        ag = _shellcomp.ZshArgumentsGenerator(opts, 'ace', 'dummy_value')

        self.assertIn('nocrash', ag.flagNameToDefinition)
        self.assertIn('nocrash', ag.allOptionsNameToDefinition)

        self.assertIn('difficulty', ag.paramNameToDefinition)
        self.assertIn('difficulty', ag.allOptionsNameToDefinition)


    def test_verifyZshNames(self):
        """
        Using a parameter/flag name that doesn't exist
        will raise an error
        """
        class TmpOptions(FighterAceExtendedOptions):
            # Note typo of detail
            compData = Completions(optActions={'detaill' : None})

        self.assertRaises(ValueError, _shellcomp.ZshArgumentsGenerator,
                          TmpOptions(), 'ace', 'dummy_value')

        class TmpOptions2(FighterAceExtendedOptions):
            # Note that 'foo' and 'bar' are not real option
            # names defined in this class
            compData = Completions(
                           mutuallyExclusive=[("foo", "bar")])

        self.assertRaises(ValueError, _shellcomp.ZshArgumentsGenerator,
                          TmpOptions2(), 'ace', 'dummy_value')


    def test_zshCode(self):
        """
        Generate a completion function, and test the textual output
        against a known correct output
        """
        outputFile = StringIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        self.patch(sys, 'argv', ["silly", "", "--_shell-completion", "zsh:2"])
        opts = SimpleProgOptions()
        self.assertRaises(SystemExit, opts.parseOptions)
        self.assertEqual(testOutput1, outputFile.getvalue())


    def test_zshCodeWithSubs(self):
        """
        Generate a completion function with subcommands,
        and test the textual output against a known correct output
        """
        outputFile = StringIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        self.patch(sys, 'argv', ["silly2", "", "--_shell-completion", "zsh:2"])
        opts = SimpleProgWithSubcommands()
        self.assertRaises(SystemExit, opts.parseOptions)
        self.assertEqual(testOutput2, outputFile.getvalue())


    def test_incompleteCommandLine(self):
        """
        Completion still happens even if a command-line is given
        that would normally throw UsageError.
        """
        outputFile = StringIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        opts = FighterAceOptions()

        self.assertRaises(SystemExit, opts.parseOptions,
                          ["--fokker", "server", "--unknown-option",
                           "--unknown-option2",
                           "--_shell-completion", "zsh:5"])
        outputFile.seek(0)
        # test that we got some output
        self.assertEqual(1, len(outputFile.read(1)))


    def test_incompleteCommandLine_case2(self):
        """
        Completion still happens even if a command-line is given
        that would normally throw UsageError.

        The existance of --unknown-option prior to the subcommand
        will break subcommand detection... but we complete anyway
        """
        outputFile = StringIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        opts = FighterAceOptions()

        self.assertRaises(SystemExit, opts.parseOptions,
                          ["--fokker", "--unknown-option", "server",
                           "--list-server", "--_shell-completion", "zsh:5"])
        outputFile.seek(0)
        # test that we got some output
        self.assertEqual(1, len(outputFile.read(1)))

        outputFile.seek(0)
        outputFile.truncate()


    def test_incompleteCommandLine_case3(self):
        """
        Completion still happens even if a command-line is given
        that would normally throw UsageError.

        Break subcommand detection in a different way by providing
        an invalid subcommand name.
        """
        outputFile = StringIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        opts = FighterAceOptions()

        self.assertRaises(SystemExit, opts.parseOptions,
                          ["--fokker", "unknown-subcommand",
                           "--list-server", "--_shell-completion", "zsh:4"])
        outputFile.seek(0)
        # test that we got some output
        self.assertEqual(1, len(outputFile.read(1)))


    def test_skipSubcommandList(self):
        """
        Ensure the optimization which skips building the subcommand list
        under certain conditions isn't broken.
        """
        outputFile = StringIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        opts = FighterAceOptions()

        self.assertRaises(SystemExit, opts.parseOptions,
                          ["--alba", "--_shell-completion", "zsh:2"])
        outputFile.seek(0)
        # test that we got some output
        self.assertEqual(1, len(outputFile.read(1)))


    def test_poorlyDescribedOptMethod(self):
        """
        Test corner case fetching an option description from a method docstring
        """
        opts = FighterAceOptions()
        argGen = _shellcomp.ZshArgumentsGenerator(opts, 'ace', None)

        descr = argGen.getDescription('silly')

        # docstring for opt_silly is useless so it should just use the
        # option name as the description
        self.assertEqual(descr, 'silly')


    def test_brokenActions(self):
        """
        A C{Completer} with repeat=True may only be used as the
        last item in the extraActions list.
        """
        class BrokenActions(usage.Options):
            compData = usage.Completions(
                extraActions=[usage.Completer(repeat=True),
                              usage.Completer()]
                )

        outputFile = StringIO()
        opts = BrokenActions()
        self.patch(opts, '_shellCompFile', outputFile)
        self.assertRaises(ValueError, opts.parseOptions,
                          ["", "--_shell-completion", "zsh:2"])


    def test_optMethodsDontOverride(self):
        """
        opt_* methods on Options classes should not override the
        data provided in optFlags or optParameters.
        """
        class Options(usage.Options):
            optFlags = [['flag', 'f', 'A flag']]
            optParameters = [['param', 'p', None, 'A param']]

            def opt_flag(self):
                """ junk description """

            def opt_param(self, param):
                """ junk description """

        opts = Options()
        argGen = _shellcomp.ZshArgumentsGenerator(opts, 'ace', None)

        self.assertEqual(argGen.getDescription('flag'), 'A flag')
        self.assertEqual(argGen.getDescription('param'), 'A param')



class EscapeTestCase(unittest.TestCase):
    def test_escape(self):
        """
        Verify _shellcomp.escape() function
        """
        esc = _shellcomp.escape

        test = "$"
        self.assertEqual(esc(test), "'$'")

        test = 'A--\'$"\\`--B'
        self.assertEqual(esc(test), '"A--\'\\$\\"\\\\\\`--B"')



class CompleterNotImplementedTestCase(unittest.TestCase):
    """
    Test that using an unknown shell constant with SubcommandAction
    raises NotImplementedError

    The other Completer() subclasses are tested in test_usage.py
    """
    def test_unknownShell(self):
        """
        Using an unknown shellType should raise NotImplementedError
        """
        action = _shellcomp.SubcommandAction()

        self.assertRaises(NotImplementedError, action._shellCode,
                          None, "bad_shell_type")



class FighterAceServerOptions(usage.Options):
    """
    Options for FighterAce 'server' subcommand
    """
    optFlags = [['list-server', None,
                 'List this server with the online FighterAce network']]
    optParameters = [['packets-per-second', None,
                      'Number of update packets to send per second', '20']]



class FighterAceOptions(usage.Options):
    """
    Command-line options for an imaginary `Fighter Ace` game
    """
    optFlags = [['fokker', 'f',
                 'Select the Fokker Dr.I as your dogfighter aircraft'],
                ['albatros', 'a',
                 'Select the Albatros D-III as your dogfighter aircraft'],
                ['spad', 's',
                 'Select the SPAD S.VII as your dogfighter aircraft'],
                ['bristol', 'b',
                 'Select the Bristol Scout as your dogfighter aircraft'],
                ['physics', 'p',
                 'Enable secret Twisted physics engine'],
                ['jam', 'j',
                 'Enable a small chance that your machine guns will jam!'],
                ['verbose', 'v',
                 'Verbose logging (may be specified more than once)'],
                ]

    optParameters = [['pilot-name', None, "What's your name, Ace?",
                      'Manfred von Richthofen'],
                     ['detail', 'd',
                      'Select the level of rendering detail (1-5)', '3'],
            ]

    subCommands = [['server', None, FighterAceServerOptions,
                    'Start FighterAce game-server.'],
                   ]

    compData = Completions(
        descriptions={'physics' : 'Twisted-Physics',
                      'detail' : 'Rendering detail level'},
        multiUse=['verbose'],
        mutuallyExclusive=[['fokker', 'albatros', 'spad',
                            'bristol']],
        optActions={'detail' : CompleteList(['1' '2' '3'
                                         '4' '5'])},
        extraActions=[CompleteFiles(descr='saved game file to load')]
        )
                              
    def opt_silly(self):
        # A silly option which nobody can explain
        """ """



class FighterAceExtendedOptions(FighterAceOptions):
    """
    Extend the options and zsh metadata provided by FighterAceOptions.
    _shellcomp must accumulate options and metadata from all classes in the
    hiearchy so this is important to test.
    """
    optFlags = [['no-stalls', None,
                 'Turn off the ability to stall your aircraft']]
    optParameters = [['reality-level', None,
                      'Select the level of physics reality (1-5)', '5']]

    compData = Completions(
        descriptions={'no-stalls' : 'Can\'t stall your plane'},
        optActions={'reality-level' :
                        Completer(descr='Physics reality level')}
        )

    def opt_nocrash(self):
        """
        Select that you can't crash your plane
        """


    def opt_difficulty(self, difficulty):
        """
        How tough are you? (1-10)
        """



def _accuracyAction():
                                    # add tick marks just to exercise quoting
    return CompleteList(['1', '2', '3'], descr='Accuracy\'`?')



class SimpleProgOptions(usage.Options):
    """
    Command-line options for a `Silly` imaginary program
    """
    optFlags = [['color', 'c', 'Turn on color output'],
                ['gray', 'g', 'Turn on gray-scale output'],
                ['verbose', 'v',
                 'Verbose logging (may be specified more than once)'],
                ]

    optParameters = [['optimization', None, '5',
                      'Select the level of optimization (1-5)'],
                     ['accuracy', 'a', '3',
                      'Select the level of accuracy (1-3)'],
                     ]


    compData = Completions(
        descriptions={'color' : 'Color on',
                      'optimization' : 'Optimization level'},
        multiUse=['verbose'],
        mutuallyExclusive=[['color', 'gray']],
        optActions={'optimization' : CompleteList(['1', '2', '3', '4', '5'],
                                                  descr='Optimization?'),
                    'accuracy' : _accuracyAction},
        extraActions=[CompleteFiles(descr='output file')]
        )

    def opt_X(self):
        """
        usage.Options does not recognize single-letter opt_ methods
        """



class SimpleProgSub1(usage.Options):
    optFlags = [['sub-opt', 's', 'Sub Opt One']]



class SimpleProgSub2(usage.Options):
    optFlags = [['sub-opt', 's', 'Sub Opt Two']]



class SimpleProgWithSubcommands(SimpleProgOptions):
    optFlags = [['some-option'],
                ['other-option', 'o']]

    optParameters = [['some-param'],
                     ['other-param', 'p'],
                     ['another-param', 'P', 'Yet Another Param']]

    subCommands = [ ['sub1', None, SimpleProgSub1, 'Sub Command 1'],
                    ['sub2', None, SimpleProgSub2, 'Sub Command 2']]



testOutput1 = """#compdef silly

_arguments -s -A "-*" \\
':output file (*):_files -g "*"' \\
"(--accuracy)-a[Select the level of accuracy (1-3)]:Accuracy'\`?:(1 2 3)" \\
"(-a)--accuracy=[Select the level of accuracy (1-3)]:Accuracy'\`?:(1 2 3)" \\
'(--color --gray -g)-c[Color on]' \\
'(--gray -c -g)--color[Color on]' \\
'(--color --gray -c)-g[Turn on gray-scale output]' \\
'(--color -c -g)--gray[Turn on gray-scale output]' \\
'--help[Display this help and exit.]' \\
'--optimization=[Optimization level]:Optimization?:(1 2 3 4 5)' \\
'*-v[Verbose logging (may be specified more than once)]' \\
'*--verbose[Verbose logging (may be specified more than once)]' \\
'--version[Display Twisted version and exit.]' \\
&& return 0
"""

# with sub-commands
testOutput2 = """#compdef silly2

_arguments -s -A "-*" \\
'*::subcmd:->subcmd' \\
':output file (*):_files -g "*"' \\
"(--accuracy)-a[Select the level of accuracy (1-3)]:Accuracy'\`?:(1 2 3)" \\
"(-a)--accuracy=[Select the level of accuracy (1-3)]:Accuracy'\`?:(1 2 3)" \\
'(--another-param)-P[another-param]:another-param:_files' \\
'(-P)--another-param=[another-param]:another-param:_files' \\
'(--color --gray -g)-c[Color on]' \\
'(--gray -c -g)--color[Color on]' \\
'(--color --gray -c)-g[Turn on gray-scale output]' \\
'(--color -c -g)--gray[Turn on gray-scale output]' \\
'--help[Display this help and exit.]' \\
'--optimization=[Optimization level]:Optimization?:(1 2 3 4 5)' \\
'(--other-option)-o[other-option]' \\
'(-o)--other-option[other-option]' \\
'(--other-param)-p[other-param]:other-param:_files' \\
'(-p)--other-param=[other-param]:other-param:_files' \\
'--some-option[some-option]' \\
'--some-param=[some-param]:some-param:_files' \\
'*-v[Verbose logging (may be specified more than once)]' \\
'*--verbose[Verbose logging (may be specified more than once)]' \\
'--version[Display Twisted version and exit.]' \\
&& return 0
local _zsh_subcmds_array
_zsh_subcmds_array=(
"sub1:Sub Command 1"
"sub2:Sub Command 2"
)

_describe "sub-command" _zsh_subcmds_array
"""