blob: c3f4a2d0179e0d235d9eb3e5a851777f2a92c876 [file] [log] [blame]
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001"""Various utility functions."""
2
Benjamin Petersondccc1fc2010-03-22 00:15:53 +00003__unittest = True
4
Michael Foordcb11b252010-06-05 13:14:43 +00005_MAX_LENGTH = 80
6def safe_repr(obj, short=False):
Benjamin Peterson847a4112010-03-14 15:04:17 +00007 try:
Michael Foordcb11b252010-06-05 13:14:43 +00008 result = repr(obj)
Benjamin Peterson847a4112010-03-14 15:04:17 +00009 except Exception:
Michael Foordcb11b252010-06-05 13:14:43 +000010 result = object.__repr__(obj)
11 if not short or len(result) < _MAX_LENGTH:
12 return result
13 return result[:_MAX_LENGTH] + ' [truncated]...'
14
Benjamin Peterson847a4112010-03-14 15:04:17 +000015
Benjamin Petersonbed7d042009-07-19 21:01:52 +000016def strclass(cls):
17 return "%s.%s" % (cls.__module__, cls.__name__)
18
19def sorted_list_difference(expected, actual):
20 """Finds elements in only one or the other of two, sorted input lists.
21
22 Returns a two-element tuple of lists. The first list contains those
23 elements in the "expected" list but not in the "actual" list, and the
24 second contains those elements in the "actual" list but not in the
25 "expected" list. Duplicate elements in either input list are ignored.
26 """
27 i = j = 0
28 missing = []
29 unexpected = []
30 while True:
31 try:
32 e = expected[i]
33 a = actual[j]
34 if e < a:
35 missing.append(e)
36 i += 1
37 while expected[i] == e:
38 i += 1
39 elif e > a:
40 unexpected.append(a)
41 j += 1
42 while actual[j] == a:
43 j += 1
44 else:
45 i += 1
46 try:
47 while expected[i] == e:
48 i += 1
49 finally:
50 j += 1
51 while actual[j] == a:
52 j += 1
53 except IndexError:
54 missing.extend(expected[i:])
55 unexpected.extend(actual[j:])
56 break
57 return missing, unexpected
58
59
60def unorderable_list_difference(expected, actual):
61 """Same behavior as sorted_list_difference but
62 for lists of unorderable items (like dicts).
63
64 As it does a linear search per item (remove) it
65 has O(n*n) performance."""
66 missing = []
67 while expected:
68 item = expected.pop()
69 try:
70 actual.remove(item)
71 except ValueError:
72 missing.append(item)
73
74 # anything left in actual is unexpected
75 return missing, actual
76
Benjamin Petersonbed7d042009-07-19 21:01:52 +000077def three_way_cmp(x, y):
78 """Return -1 if x < y, 0 if x == y and 1 if x > y"""
79 return (x > y) - (x < y)