python3 - 2to3 + miscell obvious tweaks
[sfa.git] / sfa / client / candidates.py
1
2
3 # utility to match command-line args to names
4
5
6 class Candidates:
7
8     def __init__(self, names):
9         self.names = names
10     # is an input string acceptable for one of the known names?
11
12     @staticmethod
13     def fits(input, name):
14         return name.find(input) == 0
15     # returns one of the names if the input name has a unique match
16     # or None otherwise
17
18     def only_match(self, input):
19         if input in self.names:
20             return input
21         matches = [name for name in self.names if Candidates.fits(input, name)]
22         if len(matches) == 1:
23             return matches[0]
24         else:
25             return None
26
27 # minimal test
28 candidates_specs = [
29     ('create delete reset resources slices start status stop version create_gid',
30      [('ver', 'version'),
31       ('r', None),
32          ('re', None),
33          ('res', None),
34          ('rese', 'reset'),
35          ('reset', 'reset'),
36          ('reso', 'resources'),
37          ('sli', 'slices'),
38          ('st', None),
39          ('sta', None),
40          ('stop', 'stop'),
41          ('a', None),
42          ('cre', None),
43          ('create', 'create'),
44          ('create_', 'create_gid'),
45          ('create_g', 'create_gid'),
46          ('create_gi', 'create_gid'),
47          ('create_gid', 'create_gid'),
48       ])
49 ]
50
51
52 def test_candidates():
53     for (names, tuples) in candidates_specs:
54         names = names.split()
55         for (input, expected) in tuples:
56             got = Candidates(names).only_match(input)
57             if got == expected:
58                 print('.', end=' ')
59             else:
60                 print('X FAIL', 'names[', names, '] input',
61                       input, 'expected', expected, 'got', got)
62
63 if __name__ == '__main__':
64     test_candidates()