summaryrefslogtreecommitdiff
path: root/cliapp/app_tests.py
blob: 9f2843abd84b51b1722f5e6ff7988e565c8cbe92 (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
# Copyright (C) 2011  Lars Wirzenius
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from __future__ import unicode_literals

try:
    from StringIO import StringIO
    # Fake these types that exist only in Python 3
    TextIOBase = file
except ImportError:
    from io import StringIO, TextIOBase
import sys
import unittest

import cliapp


def devnull(msg):
    pass


class AppExceptionTests(unittest.TestCase):

    def setUp(self):
        self.e = cliapp.AppException('foo')

    def test_error_message_contains_foo(self):
        self.assertTrue('foo' in str(self.e))


class ApplicationTests(unittest.TestCase):

    def setUp(self):
        self.app = cliapp.Application()

    def test_creates_settings(self):
        self.assertTrue(isinstance(self.app.settings, cliapp.Settings))

    def test_calls_add_settings_only_in_run(self):

        class Foo(cliapp.Application):

            def process_args(self, args):
                pass

            def add_settings(self):
                self.settings.string(['foo'], '')

        foo = Foo()
        self.assertFalse('foo' in foo.settings)
        foo.run(args=[])
        self.assertTrue('foo' in foo.settings)

    def test_run_uses_string_list_options_only_once(self):

        class Foo(cliapp.Application):

            def add_settings(self):
                self.settings.string_list(['foo'], '')

            def process_args(self, args):
                pass

        foo = Foo()
        foo.run(args=['--foo=yo'])
        self.assertEqual(foo.settings['foo'], ['yo'])

    def test_run_sets_up_logging(self):
        self.called = False

        def setup():
            self.called = True

        self.app.setup_logging = setup
        self.app.process_args = lambda args: None
        self.app.run([])
        self.assertTrue(self.called)

    def test_run_sets_progname_from_sysargv0(self):
        self.app.process_args = lambda args: None
        self.app.run(args=[], sysargv=['foo'])
        self.assertEqual(self.app.settings.progname, 'foo')

    def test_run_calls_process_args(self):
        self.called = None
        self.app.process_args = lambda args: setattr(self, 'called', args)
        self.app.run(args=['foo', 'bar'])
        self.assertEqual(self.called, ['foo', 'bar'])

    def test_run_processes_input_files(self):
        self.inputs = []
        self.app.process_input = self.inputs.append
        self.app.run(args=['foo', 'bar'])
        self.assertEqual(self.inputs, ['foo', 'bar'])

    def test_run_sets_output_attribute(self):
        self.app.process_args = lambda args: None
        self.app.run(args=[])
        self.assertEqual(self.app.output, sys.stdout)

    def test_run_sets_output_to_file_if_output_option_is_set(self):
        self.app.process_args = lambda args: None
        self.app.run(args=['--output=/dev/null'])
        self.assertEqual(self.app.output.name, '/dev/null')

    def test_run_calls_parse_args(self):
        class DummyOptions(object):
            def __init__(self):
                self.output = None
                self.log = None
        self.called = None
        self.app.parse_args = lambda args, **kw: setattr(self, 'called', args)
        self.app.process_args = lambda args: None
        self.app.settings.options = DummyOptions()
        self.app.run(args=['foo', 'bar'])
        self.assertEqual(self.called, ['foo', 'bar'])

    def test_makes_envname_correctly(self):
        self.assertEqual(self.app.envname('foo'), 'FOO')
        self.assertEqual(self.app.envname('foo.py'), 'FOO')
        self.assertEqual(self.app.envname('foo bar'), 'FOO_BAR')
        self.assertEqual(self.app.envname('foo-bar'), 'FOO_BAR')
        self.assertEqual(self.app.envname('foo/bar'), 'BAR')
        self.assertEqual(self.app.envname('foo_bar'), 'FOO_BAR')

    def test_parses_options(self):
        self.app.settings.string(['foo'], 'foo help')
        self.app.settings.boolean(['bar'], 'bar help')
        self.app.parse_args(['--foo=foovalue', '--bar'])
        self.assertEqual(self.app.settings['foo'], 'foovalue')
        self.assertEqual(self.app.settings['bar'], True)

    def test_calls_setup(self):

        context = {}

        class App(cliapp.Application):

            def setup(self):
                context['setup-called'] = True

            def process_inputs(self, args):
                pass

        app = App()
        app.run(args=[])
        self.assertTrue(context['setup-called'])

    def test_calls_cleanup(self):

        context = {}

        class App(cliapp.Application):

            def cleanup(self):
                context['cleanup-called'] = True

            def process_inputs(self, args):
                pass

        app = App()
        app.run(args=[])
        self.assertTrue(context['cleanup-called'])

    def test_process_args_calls_process_inputs(self):
        self.called = False

        def process_inputs(args):
            self.called = True

        self.app.process_inputs = process_inputs
        self.app.process_args([])
        self.assertTrue(self.called)

    def test_process_inputs_calls_process_input_for_each_arg(self):
        self.args = []

        def process_input(arg):
            self.args.append(arg)

        self.app.process_input = process_input
        self.app.process_inputs(['foo', 'bar'])
        self.assertEqual(self.args, ['foo', 'bar'])

    def test_process_inputs_calls_process_input_with_dash_if_no_inputs(self):
        self.args = []

        def process_input(arg):
            self.args.append(arg)

        self.app.process_input = process_input
        self.app.process_inputs([])
        self.assertEqual(self.args, ['-'])

    def test_open_input_opens_file(self):
        f = self.app.open_input('/dev/null')
        self.assertTrue(isinstance(f, TextIOBase))
        self.assertEqual(getattr(f, 'mode'), 'r')

    def test_open_input_opens_file_in_binary_mode_when_requested(self):
        f = self.app.open_input('/dev/null', mode='rb')
        self.assertEqual(getattr(f, 'mode'), 'rb')

    def test_open_input_opens_stdin_if_dash_given(self):
        self.assertEqual(self.app.open_input('-'), sys.stdin)

    def test_process_input_calls_open_input(self):
        self.called = None

        def open_input(name):
            self.called = name
            return StringIO('')

        self.app.open_input = open_input
        self.app.process_input('foo')
        self.assertEqual(self.called, 'foo')

    def test_process_input_does_not_close_stdin(self):
        self.closed = False

        def close():
            self.closed = True

        f = StringIO('')
        f.close = close

        def open_input(name):
            if name == '-':
                return f

        self.app.open_input = open_input
        self.app.process_input('-', stdin=f)
        self.assertEqual(self.closed, False)

    def test_processes_input_lines(self):

        lines = []

        class Foo(cliapp.Application):

            def open_input(self, name, mode=None):
                return StringIO(''.join('%s%d\n' % (name, i)
                                        for i in range(2)))

            def process_input_line(self, name, line):
                lines.append(line)

        foo = Foo()
        foo.run(args=['foo', 'bar'])
        self.assertEqual(lines, ['foo0\n', 'foo1\n', 'bar0\n', 'bar1\n'])

    def test_process_input_line_can_access_counters(self):
        counters = []

        class Foo(cliapp.Application):

            def open_input(self, name, mode=None):
                return StringIO(''.join('%s%d\n' % (name, i)
                                        for i in range(2)))

            def process_input_line(self, name, line):
                counters.append((self.fileno, self.global_lineno, self.lineno))

        foo = Foo()
        foo.run(args=['foo', 'bar'])
        self.assertEqual(counters,
                         [(1, 1, 1),
                          (1, 2, 2),
                          (2, 3, 1),
                          (2, 4, 2)])

    def test_run_prints_out_error_for_appexception(self):
        def raise_error(args):
            raise cliapp.AppException('xxx')
        self.app.process_args = raise_error
        f = StringIO()
        self.assertRaises(SystemExit, self.app.run, [], stderr=f, log=devnull)
        self.assertTrue('xxx' in f.getvalue())

    def test_run_prints_out_stack_trace_for_not_appexception(self):
        def raise_error(args):
            raise Exception('xxx')
        self.app.process_args = raise_error
        f = StringIO()
        self.assertRaises(SystemExit, self.app.run, [], stderr=f, log=devnull)
        self.assertTrue('Traceback' in f.getvalue())

    def test_run_raises_systemexit_for_systemexit(self):
        def raise_error(args):
            raise SystemExit(123)
        self.app.process_args = raise_error
        f = StringIO()
        self.assertRaises(SystemExit, self.app.run, [], stderr=f, log=devnull)

    def test_run_raises_systemexit_for_keyboardint(self):
        def raise_error(args):
            raise KeyboardInterrupt()
        self.app.process_args = raise_error
        f = StringIO()
        self.assertRaises(SystemExit, self.app.run, [], stderr=f, log=devnull)


class DummySubcommandApp(cliapp.Application):

    def cmd_foo(self, args):
        self.foo_called = True


class SubcommandTests(unittest.TestCase):

    def setUp(self):
        self.app = DummySubcommandApp()
        self.trash = StringIO()

    def test_lists_subcommands(self):
        self.assertEqual(self.app._subcommand_methodnames(), ['cmd_foo'])

    def test_normalizes_subcommand(self):
        self.assertEqual(self.app._normalize_cmd('foo'), 'cmd_foo')
        self.assertEqual(self.app._normalize_cmd('foo-bar'), 'cmd_foo_bar')

    def test_raises_error_for_no_subcommand(self):
        self.assertRaises(SystemExit, self.app.run, [],
                          stderr=self.trash, log=devnull)

    def test_raises_error_for_unknown_subcommand(self):
        self.assertRaises(SystemExit, self.app.run, ['what?'],
                          stderr=self.trash, log=devnull)

    def test_calls_subcommand_method(self):
        self.app.run(['foo'], stderr=self.trash, log=devnull)
        self.assertTrue(self.app.foo_called)

    def test_calls_subcommand_method_via_alias(self):
        self.bar_called = False

        def bar(*args):
            self.bar_called = True

        self.app.add_subcommand('bar', bar, aliases=['yoyo'])
        self.app.run(['yoyo'], stderr=self.trash, log=devnull)
        self.assertTrue(self.bar_called)

    def test_adds_default_subcommand_help(self):
        self.app.run(['foo'], stderr=self.trash, log=devnull)
        self.assertTrue('help' in self.app.subcommands)


class ExtensibleSubcommandTests(unittest.TestCase):

    def setUp(self):
        self.app = cliapp.Application()

    def test_lists_no_subcommands(self):
        self.assertEqual(self.app.subcommands, {})

    def test_adds_subcommand(self):
        def help_callback(arg):
            pass
        self.app.add_subcommand('foo', help_callback)
        self.assertEqual(self.app.subcommands, {'foo': help_callback})