public
Description: Syntactic sugar for creating Python command line scripts by introspecting a function definition
Homepage: http://simonwillison.net/2009/May/28/optfunc/
Clone URL: git://github.com/simonw/optfunc.git
optfunc / test.py
100644 271 lines (216 sloc) 9.182 kb
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
import unittest
import optfunc
from StringIO import StringIO
 
class TestOptFunc(unittest.TestCase):
    def test_three_positional_args(self):
        
        has_run = [False]
        def func(one, two, three):
            has_run[0] = True
        
        # Should only have the -h help option
        parser, required_args = optfunc.func_to_optionparser(func)
        self.assertEqual(len(parser.option_list), 1)
        self.assertEqual(str(parser.option_list[0]), '-h/--help')
        
        # Should have three required args
        self.assertEqual(required_args, ['one', 'two', 'three'])
        
        # Running it with the wrong number of arguments should cause an error
        for argv in (
            ['one'],
            ['one', 'two'],
            ['one', 'two', 'three', 'four'],
        ):
            e = StringIO()
            optfunc.run(func, argv, stderr=e)
            self.assert_('Required 3 arguments' in e.getvalue(), e.getvalue())
            self.assertEqual(has_run[0], False)
        
        # Running it with the right number of arguments should be fine
        e = StringIO()
        optfunc.run(func, ['one', 'two', 'three'], stderr=e)
        self.assertEqual(e.getvalue(), '')
        self.assertEqual(has_run[0], True)
    
    def test_one_arg_one_option(self):
        
        has_run = [False]
        def func(one, option=''):
            has_run[0] = (one, option)
        
        # Should have -o option as well as -h option
        parser, required_args = optfunc.func_to_optionparser(func)
        self.assertEqual(len(parser.option_list), 2)
        strs = [str(o) for o in parser.option_list]
        self.assert_('-h/--help' in strs)
        self.assert_('-o/--option' in strs)
        
        # Should have one required arg
        self.assertEqual(required_args, ['one'])
        
        # Should execute
        self.assert_(not has_run[0])
        optfunc.run(func, ['the-required', '-o', 'the-option'])
        self.assert_(has_run[0])
        self.assertEqual(has_run[0], ('the-required', 'the-option'))
        
        # Option should be optional
        has_run[0] = False
        optfunc.run(func, ['required2'])
        self.assert_(has_run[0])
        self.assertEqual(has_run[0], ('required2', ''))
    
    def test_options_are_correctly_named(self):
        def func1(one, option='', verbose=False):
            pass
        
        parser, required_args = optfunc.func_to_optionparser(func1)
        strs = [str(o) for o in parser.option_list]
        self.assertEqual(strs, ['-h/--help', '-o/--option', '-v/--verbose'])
    
    def test_option_with_hyphens(self):
        def func2(option_with_hyphens=True):
            pass
        
        parser, required_args = optfunc.func_to_optionparser(func2)
        strs = [str(o) for o in parser.option_list]
        self.assertEqual(strs, ['-h/--help', '-o/--option-with-hyphens'])
    
    def test_options_with_same_inital_use_next_letter(self):
        def func1(one, version='', verbose=False):
            pass
        
        parser, required_args = optfunc.func_to_optionparser(func1)
        strs = [str(o) for o in parser.option_list]
        self.assertEqual(strs, ['-h/--help', '-v/--version', '-e/--verbose'])
 
        def func2(one, host=''):
            pass
        
        parser, required_args = optfunc.func_to_optionparser(func2)
        strs = [str(o) for o in parser.option_list]
        self.assertEqual(strs, ['-h/--help', '-o/--host'])
    
    def test_short_option_can_be_named_explicitly(self):
        def func1(one, option='', q_verbose=False):
            pass
        
        parser, required_args = optfunc.func_to_optionparser(func1)
        strs = [str(o) for o in parser.option_list]
        self.assertEqual(strs, ['-h/--help', '-o/--option', '-q/--verbose'])
 
        e = StringIO()
        optfunc.run(func1, ['one', '-q'], stderr=e)
        self.assertEqual(e.getvalue().strip(), '')
    
    def test_notstrict(self):
        "@notstrict tells optfunc to tolerate missing required arguments"
        def strict_func(one):
            pass
        
        e = StringIO()
        optfunc.run(strict_func, [], stderr=e)
        self.assertEqual(e.getvalue().strip(), 'Required 1 arguments, got 0')
        
        @optfunc.notstrict
        def notstrict_func(one):
            pass
        
        e = StringIO()
        optfunc.run(notstrict_func, [], stderr=e)
        self.assertEqual(e.getvalue().strip(), '')
    
    def test_arghelp(self):
        "@arghelp('foo', 'help about foo') sets help text for parameters"
        @optfunc.arghelp('foo', 'help about foo')
        def foo(foo = False):
            pass
        
        parser, required_args = optfunc.func_to_optionparser(foo)
        opt = parser.option_list[1]
        self.assertEqual(str(opt), '-f/--foo')
        self.assertEqual(opt.help, 'help about foo')
    
    def test_multiple_invalid_subcommand(self):
        "With multiple subcommands, invalid first arg should raise an error"
        def one(arg):
            pass
        def two(arg):
            pass
        def three(arg):
            pass
        
        # Invalid first argument should raise an error
        e = StringIO()
        optfunc.run([one, two], ['three'], stderr=e)
        self.assertEqual(
            e.getvalue().strip(), "Unknown command: try 'one' or 'two'"
        )
        e = StringIO()
        optfunc.run([one, two, three], ['four'], stderr=e)
        self.assertEqual(
            e.getvalue().strip(),
            "Unknown command: try 'one', 'two' or 'three'"
        )
        
        # No argument at all should raise an error
        e = StringIO()
        optfunc.run([one, two, three], [], stderr=e)
        self.assertEqual(
            e.getvalue().strip(),
            "Unknown command: try 'one', 'two' or 'three'"
        )
    
    def test_multiple_valid_subcommand_invalid_argument(self):
        "Subcommands with invalid arguments should report as such"
        def one(arg):
            executed.append(('one', arg))
        
        def two(arg):
            executed.append(('two', arg))
 
        e = StringIO()
        executed = []
        optfunc.run([one, two], ['one'], stderr=e)
        self.assertEqual(
            e.getvalue().strip(), 'one: Required 1 arguments, got 0'
        )
    
    def test_multiple_valid_subcommand_valid_argument(self):
        "Subcommands with valid arguments should execute as expected"
        def one(arg):
            executed.append(('one', arg))
        
        def two(arg):
            executed.append(('two', arg))
 
        e = StringIO()
        executed = []
        optfunc.run([one, two], ['two', 'arg!'], stderr=e)
        self.assertEqual(e.getvalue().strip(), '')
        self.assertEqual(executed, [('two', 'arg!')])
 
    def test_run_class(self):
        class Class:
            def __init__(self, one, option=''):
                self.has_run = [(one, option)]
        
        class NoInitClass:
            pass
 
        # Should execute
        e = StringIO()
        c = optfunc.run(Class, ['the-required', '-o', 'the-option'], stderr=e)
        self.assertEqual(e.getvalue().strip(), '')
        self.assert_(c.has_run[0])
        self.assertEqual(c.has_run[0], ('the-required', 'the-option'))
        
        # Option should be optional
        c = None
        e = StringIO()
        c = optfunc.run(Class, ['required2'], stderr=e)
        self.assertEqual(e.getvalue().strip(), '')
        self.assert_(c.has_run[0])
        self.assertEqual(c.has_run[0], ('required2', ''))
 
        # Classes without init should work too
        c = None
        e = StringIO()
        c = optfunc.run(NoInitClass, [], stderr=e)
        self.assert_(c)
        self.assertEqual(e.getvalue().strip(), '')
    
    def test_stdin_special_argument(self):
        consumed = []
        def func(stdin):
            consumed.append(stdin.read())
        
        class FakeStdin(object):
            def read(self):
                return "hello"
        
        optfunc.run(func, stdin=FakeStdin())
        self.assertEqual(consumed, ['hello'])
    
    def test_stdout_special_argument(self):
        def upper(stdin, stdout):
            stdout.write(stdin.read().upper())
        
        class FakeStdin(object):
            def read(self):
                return "hello"
        
        class FakeStdout(object):
            written = ''
            def write(self, w):
                self.written = w
        
        stdout = FakeStdout()
        self.assertEqual(stdout.written, '')
        optfunc.run(upper, stdin=FakeStdin(), stdout=stdout)
        self.assertEqual(stdout.written, 'HELLO')
    
    def test_stderr_special_argument(self):
        def upper(stderr):
            stderr.write('an error')
        
        class FakeStderr(object):
            written = ''
            def write(self, w):
                self.written = w
        
        stderr = FakeStderr()
        self.assertEqual(stderr.written, '')
        optfunc.run(upper, stderr=stderr)
        self.assertEqual(stderr.written, 'an error')
 
if __name__ == '__main__':
    unittest.main()