blob: 26805def31496b89ac28f3c8aea701866f130ab8 [file] [log] [blame]
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001"""Various utility functions."""
2
3def strclass(cls):
4 return "%s.%s" % (cls.__module__, cls.__name__)
5
6def sorted_list_difference(expected, actual):
7 """Finds elements in only one or the other of two, sorted input lists.
8
9 Returns a two-element tuple of lists. The first list contains those
10 elements in the "expected" list but not in the "actual" list, and the
11 second contains those elements in the "actual" list but not in the
12 "expected" list. Duplicate elements in either input list are ignored.
13 """
14 i = j = 0
15 missing = []
16 unexpected = []
17 while True:
18 try:
19 e = expected[i]
20 a = actual[j]
21 if e < a:
22 missing.append(e)
23 i += 1
24 while expected[i] == e:
25 i += 1
26 elif e > a:
27 unexpected.append(a)
28 j += 1
29 while actual[j] == a:
30 j += 1
31 else:
32 i += 1
33 try:
34 while expected[i] == e:
35 i += 1
36 finally:
37 j += 1
38 while actual[j] == a:
39 j += 1
40 except IndexError:
41 missing.extend(expected[i:])
42 unexpected.extend(actual[j:])
43 break
44 return missing, unexpected
45
46
47def unorderable_list_difference(expected, actual):
48 """Same behavior as sorted_list_difference but
49 for lists of unorderable items (like dicts).
50
51 As it does a linear search per item (remove) it
52 has O(n*n) performance."""
53 missing = []
54 while expected:
55 item = expected.pop()
56 try:
57 actual.remove(item)
58 except ValueError:
59 missing.append(item)
60
61 # anything left in actual is unexpected
62 return missing, actual
63
64def CmpToKey(mycmp):
65 'Convert a cmp= function into a key= function'
66 class K(object):
67 def __init__(self, obj, *args):
68 self.obj = obj
69 def __lt__(self, other):
70 return mycmp(self.obj, other.obj) == -1
71 return K
72
73def three_way_cmp(x, y):
74 """Return -1 if x < y, 0 if x == y and 1 if x > y"""
75 return (x > y) - (x < y)