forked from simonw/optfunc
/
test.py
61 lines (48 loc) · 2.1 KB
/
test.py
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
import unittest
import optfunc
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'],
):
self.assertRaises(TypeError, optfunc.run, func, argv)
self.assertEqual(has_run[0], False)
# Running it with the right number of arguments should be fine
optfunc.run(func, ['one', 'two', 'three'])
self.assertEqual(has_run[0], True)
def test_one_arg_one_option(self):
has_run = [False]
def func(one, two=optfunc.Var('-o', '--option')):
has_run[0] = (one, two)
# 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', None))
if __name__ == '__main__':
unittest.main()