3 User Friendly Lookup routine
4 Copyright 2015 Cray Inc. All Rights Reserved
7 # TBD: Maybe it would be more useful to replace prefixok with
8 # substringok, for cases with lots of common prefix, like
9 # CAP_SYS_PTRACE and CAP_SYS_TTY_CONFIG
11 # Wait until there's a user for it.
13 def UFLookup(d, key, casesensitive=False, prefixok=True):
14 """User Friendly Lookup
16 By default, case-insensitive, unique-prefix-accepting lookups on
19 def _casesensitive_prefixok(d, key):
20 """case sensitive, prefixes ok"""
29 raise KeyError("{0} matches multiple keys: {1}".format(
30 key, ", ".join(matches)))
32 def _caseinsensitive_prefixok(d, key):
33 """case insensitive, prefixes ok"""
39 if s.lower().startswith(lkey):
42 raise KeyError("No match for {0}".format(key))
45 raise KeyError("{0} matches multiple keys: {1}".format(
46 key, ", ".join(matches)))
48 def _caseinsensitive_noprefix(d, key):
49 """case insensitive, prefixes not ok"""
54 raise KeyError("No match for {0}".format(key))
56 def _casesensitive_noprefix(d, key):
57 """case sensitive, prefixes not ok"""
60 if casesensitive and not prefixok:
61 return _casesensitive_noprefix(d, key)
63 return _casesensitive_prefixok(d, key)
65 return _caseinsensitive_prefixok(d, key)
66 return _caseinsensitive_noprefix(d, key)
70 if __name__ == '__main__':
73 class Test_UFLookup_FBBZZ(unittest.TestCase):
81 def checkall(self, expectedlist, key):
82 """Test UFLookup(self.d, key) for all four flags combinations.
84 expectedlist[] contains the four expected results,
85 [0]: casesensitive = False, prefixok = False
86 [1]: casesensitive = False, prefixok = True
87 [2]: casesensitive = True, prefixok = False
88 [3]: casesensitive = True, prefixok = True
90 If expectedlist[i] is None, then UFLookup should raise
91 KeyError for that case. Otherwise, it's the value that
92 should be returned."""
94 kdicts = [{"casesensitive": False, "prefixok": False},
95 {"casesensitive": False, "prefixok": True},
96 {"casesensitive": True, "prefixok": False},
97 {"casesensitive": True, "prefixok": True}]
98 for i in xrange(len(expectedlist)):
101 self.assertRaises(KeyError,
102 UFLookup, self.d, key, **kdicts[i])
104 self.assertEqual(e, UFLookup(self.d, key, **kdicts[i]))
107 self.checkall([1, 1, 1, 1], "FOO")
109 self.checkall([1, 1, None, None], "foo")
111 self.checkall([None, 1, None, 1], "F")
113 self.checkall([None, 1, None, None], "f")
116 def test_ambig_prefix_zin(self):
117 self.checkall([None, None, None, None], "zin")
118 def test_semiambig_prefix_ba(self):
119 self.checkall([None, None, None, 3], "ba")
120 def test_prefix_exactmatch_zing(self):
121 self.checkall([4, 4, 4, 4], "zing")
122 def test_prefix_semiexact_zinG(self):
123 self.checkall([4, 4, None, 5], "zinG")