blob: 9ddf879387c78a518b56aec0233f2e5a5faf862d [file] [log] [blame]
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001"""Various utility functions."""
2
Michael Foord225a0992010-02-18 20:30:09 +00003def safe_repr(obj):
4 try:
5 return repr(obj)
6 except Exception:
7 return object.__repr__(obj)
8
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00009def strclass(cls):
10 return "%s.%s" % (cls.__module__, cls.__name__)
11
12def sorted_list_difference(expected, actual):
13 """Finds elements in only one or the other of two, sorted input lists.
14
15 Returns a two-element tuple of lists. The first list contains those
16 elements in the "expected" list but not in the "actual" list, and the
17 second contains those elements in the "actual" list but not in the
18 "expected" list. Duplicate elements in either input list are ignored.
19 """
20 i = j = 0
21 missing = []
22 unexpected = []
23 while True:
24 try:
25 e = expected[i]
26 a = actual[j]
27 if e < a:
28 missing.append(e)
29 i += 1
30 while expected[i] == e:
31 i += 1
32 elif e > a:
33 unexpected.append(a)
34 j += 1
35 while actual[j] == a:
36 j += 1
37 else:
38 i += 1
39 try:
40 while expected[i] == e:
41 i += 1
42 finally:
43 j += 1
44 while actual[j] == a:
45 j += 1
46 except IndexError:
47 missing.extend(expected[i:])
48 unexpected.extend(actual[j:])
49 break
50 return missing, unexpected
Michael Foord98e7b762010-03-20 03:00:34 +000051
52
53def unorderable_list_difference(expected, actual, ignore_duplicate=False):
54 """Same behavior as sorted_list_difference but
55 for lists of unorderable items (like dicts).
56
57 As it does a linear search per item (remove) it
58 has O(n*n) performance.
59 """
60 missing = []
61 unexpected = []
62 while expected:
63 item = expected.pop()
64 try:
65 actual.remove(item)
66 except ValueError:
67 missing.append(item)
68 if ignore_duplicate:
69 for lst in expected, actual:
70 try:
71 while True:
72 lst.remove(item)
73 except ValueError:
74 pass
75 if ignore_duplicate:
76 while actual:
77 item = actual.pop()
78 unexpected.append(item)
79 try:
80 while True:
81 actual.remove(item)
82 except ValueError:
83 pass
84 return missing, unexpected
85
86 # anything left in actual is unexpected
87 return missing, actual