Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 1 | """Various utility functions.""" |
| 2 | |
Benjamin Peterson | dccc1fc | 2010-03-22 00:15:53 +0000 | [diff] [blame] | 3 | __unittest = True |
| 4 | |
| 5 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame] | 6 | def safe_repr(obj): |
| 7 | try: |
| 8 | return repr(obj) |
| 9 | except Exception: |
| 10 | return object.__repr__(obj) |
| 11 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 12 | def strclass(cls): |
| 13 | return "%s.%s" % (cls.__module__, cls.__name__) |
| 14 | |
| 15 | def sorted_list_difference(expected, actual): |
| 16 | """Finds elements in only one or the other of two, sorted input lists. |
| 17 | |
| 18 | Returns a two-element tuple of lists. The first list contains those |
| 19 | elements in the "expected" list but not in the "actual" list, and the |
| 20 | second contains those elements in the "actual" list but not in the |
| 21 | "expected" list. Duplicate elements in either input list are ignored. |
| 22 | """ |
| 23 | i = j = 0 |
| 24 | missing = [] |
| 25 | unexpected = [] |
| 26 | while True: |
| 27 | try: |
| 28 | e = expected[i] |
| 29 | a = actual[j] |
| 30 | if e < a: |
| 31 | missing.append(e) |
| 32 | i += 1 |
| 33 | while expected[i] == e: |
| 34 | i += 1 |
| 35 | elif e > a: |
| 36 | unexpected.append(a) |
| 37 | j += 1 |
| 38 | while actual[j] == a: |
| 39 | j += 1 |
| 40 | else: |
| 41 | i += 1 |
| 42 | try: |
| 43 | while expected[i] == e: |
| 44 | i += 1 |
| 45 | finally: |
| 46 | j += 1 |
| 47 | while actual[j] == a: |
| 48 | j += 1 |
| 49 | except IndexError: |
| 50 | missing.extend(expected[i:]) |
| 51 | unexpected.extend(actual[j:]) |
| 52 | break |
| 53 | return missing, unexpected |
| 54 | |
| 55 | |
| 56 | def unorderable_list_difference(expected, actual): |
| 57 | """Same behavior as sorted_list_difference but |
| 58 | for lists of unorderable items (like dicts). |
| 59 | |
| 60 | As it does a linear search per item (remove) it |
| 61 | has O(n*n) performance.""" |
| 62 | missing = [] |
| 63 | while expected: |
| 64 | item = expected.pop() |
| 65 | try: |
| 66 | actual.remove(item) |
| 67 | except ValueError: |
| 68 | missing.append(item) |
| 69 | |
| 70 | # anything left in actual is unexpected |
| 71 | return missing, actual |
| 72 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 73 | def 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) |