Пример #1
0
def queue_tester(ops):
    from test_framework.test_failure import TestFailure

    try:
        q = Queue()

        for (op, arg) in ops:
            if op == 'Queue':
                q = Queue()
            elif op == 'enqueue':
                q.enqueue(arg)
            elif op == 'dequeue':
                result = q.dequeue()
                if result != arg:
                    raise TestFailure("Dequeue: expected " + str(arg) +
                                      ", got " + str(result))
            else:
                raise RuntimeError("Unsupported queue operation: " + op)
    except IndexError:
        raise TestFailure('Unexpected IndexError exception')
Пример #2
0
def queue_tester(ops):
    q = Queue(1)

    for (op, arg) in ops:
        if op == 'Queue':
            q = Queue(arg)
        elif op == 'enqueue':
            q.enqueue(arg)
        elif op == 'dequeue':
            result = q.dequeue()
            if result != arg:
                raise TestFailure('Dequeue: expected ' + str(arg) + ', got ' +
                                  str(result))
        elif op == 'size':
            result = q.size()
            if result != arg:
                raise TestFailure('Size: expected ' + str(arg) + ', got ' +
                                  str(result))
        else:
            raise RuntimeError('Unsupported queue operation: ' + op)
Пример #3
0
def find_smallest_sequentially_covering_subset_wrapper(executor, paragraph,
                                                       keywords):
    result = executor.run(
        functools.partial(find_smallest_sequentially_covering_subset,
                          paragraph, keywords))

    kw_idx = 0
    para_idx = result.start
    if para_idx < 0:
        raise RuntimeError("Subarray start index is negative")

    while kw_idx < len(keywords):
        if para_idx >= len(paragraph):
            raise TestFailure("Not all keywords are in the generated subarray")
        if para_idx >= len(paragraph):
            raise TestFailure("Subarray end index exceeds array size")
        if paragraph[para_idx] == keywords[kw_idx]:
            kw_idx += 1
        para_idx += 1

    return result.end - result.start + 1
Пример #4
0
def solve_sudoku_wrapper(executor, partial_assignment):
    solved = copy.deepcopy(partial_assignment)

    executor.run(functools.partial(solve_sudoku, solved))

    if len(partial_assignment) != len(solved):
        raise TestFailure('Initial cell assignment has been changed')

    for (br, sr) in zip(partial_assignment, solved):
        if len(br) != len(sr):
            raise TestFailure('Initial cell assignment has been changed')
        for (bcell, scell) in zip(br, sr):
            if bcell != 0 and bcell != scell:
                raise TestFailure('Initial cell assignment has been changed')

    block_size = int(math.sqrt(len(solved)))

    for i in range(len(solved)):
        assert_unique_seq(solved[i])
        assert_unique_seq([row[i] for row in solved])
        assert_unique_seq(gather_square_block(solved, block_size, i))
Пример #5
0
def run_test(commands):
    if len(commands) < 1 or commands[0][0] != "LruCache":
        raise RuntimeError("Expected LruCache as first command")

    cache = LruCache(commands[0][1])

    for cmd in commands[1:]:
        if cmd[0] == "lookup":
            result = cache.lookup(cmd[1])
            if result != cmd[2]:
                raise TestFailure("Lookup: expected " + str(cmd[2]) +
                                  ", got " + str(result))
        elif cmd[0] == "insert":
            cache.insert(cmd[1], cmd[2])
        elif cmd[0] == "erase":
            result = 1 if cache.erase(cmd[1]) else 0
            if result != cmd[2]:
                raise TestFailure("Erase: expected " + str(cmd[2]) + ", got " +
                                  str(result))
        else:
            raise RuntimeError("Unexpected command " + cmd[0])
Пример #6
0
def lca_wrapper(executor, tree, key1, key2):
    strip_parent_link(tree)
    result = executor.run(
        functools.partial(
            lca, tree, must_find_node(tree, key1), must_find_node(tree, key2)
        )
    )

    if result is None:
        raise TestFailure("Result can't be None")

    return result.data
Пример #7
0
def lru_cache_tester(commands):
    if len(commands) < 1 or commands[0][0] != 'LruCache':
        raise RuntimeError('Expected LruCache as first command')

    cache = LruCache(commands[0][1])

    for cmd in commands[1:]:
        if cmd[0] == 'lookup':
            result = cache.lookup(cmd[1])
            if result != cmd[2]:
                raise TestFailure('Lookup: expected ' + str(cmd[2]) +
                                  ', got ' + str(result))
        elif cmd[0] == 'insert':
            cache.insert(cmd[1], cmd[2])
        elif cmd[0] == 'erase':
            result = 1 if cache.erase(cmd[1]) else 0
            if result != cmd[2]:
                raise TestFailure('Erase: expected ' + str(cmd[2]) + ', got ' +
                                  str(result))
        else:
            raise RuntimeError('Unexpected command ' + cmd[0])
Пример #8
0
def assert_lists_equal(orig, copy):
    node_mapping = dict()
    o_it = orig
    c_it = copy
    while o_it:
        if not c_it:
            raise TestFailure('Copied list has fewer nodes than the original')
        if o_it.order != c_it.order:
            raise TestFailure('Order value mismatch')
        node_mapping[o_it] = c_it
        o_it = o_it.next
        c_it = c_it.next

    if c_it:
        raise TestFailure('Copied list has more nodes than the original')

    o_it = orig
    c_it = copy
    while o_it:
        if c_it in node_mapping:
            raise TestFailure(
                'Copied list contains a node from the original list')
        if o_it.jump is None:
            if c_it.jump is not None:
                raise TestFailure(
                    'Jump link points to a different nodes in the copied list')
        else:
            if not node_mapping[o_it.jump] is c_it.jump:
                raise TestFailure(
                    'Jump link points to a different nodes in the copied list')
        o_it = o_it.next
        c_it = c_it.next
def dutch_flag_partition_wrapper(executor, A, pivot_idx):
    count = [0, 0, 0]
    for x in A:
        count[x] += 1
    pivot = A[pivot_idx]

    A = executor.run(functools.partial(dutch_flag_partition, pivot_idx, A))
    i = 0
    while i < len(A) and A[i] < pivot:
        count[A[i]] -= 1
        i += 1
    while i < len(A) and A[i] == pivot:
        count[A[i]] -= 1
        i += 1
    while i < len(A) and A[i] > pivot:
        count[A[i]] -= 1
        i += 1

    if i != len(A):
        raise TestFailure('Not partitioned after {}th element'.format(i))
    elif any(count):
        raise TestFailure("Some elements are missing from original array")
 def impl(node, path, min, max):
     if node is None:
         return
     value = node.data
     if not type(value) is int:
         raise RuntimeError('Only integer keys are supported')
     if value < min or value > max:
         raise TestFailure('Binary search tree constraints violation') \
             .with_mismatch_info(path,
                                 'Value between {} and {}'.format(min, max),
                                 value)
     impl(node.left, path.with_left(), min, value)
     impl(node.right, path.with_right(), value, max)
Пример #11
0
def assert_all_values_present(reference, result):
    reference_set = collections.defaultdict(int)

    for x in reference:
        reference_set[x] += 1

    for x in result:
        reference_set[x] -= 1

    flatten = lambda l: [item for sublist in l for item in sublist]
    excess_items = flatten(
        [x] * -count for x, count in reference_set.items() if count < 0)
    missing_items = flatten(
        [x] * count for x, count in reference_set.items() if count > 0)

    if excess_items or missing_items:
        e = TestFailure('Value set changed')\
            .with_property(PropertyName.RESULT, result)
        if excess_items:
            e.with_property(PropertyName.EXCESS_ITEMS, excess_items)
        if missing_items:
            e.with_property(PropertyName.MISSING_ITEMS, missing_items)
        raise e
Пример #12
0
def overlapping_lists_wrapper(executor, l0, l1, common, cycle0, cycle1):
    if common:
        if not l0:
            l0 = common
        else:
            it = l0
            while it.next:
                it = it.next
            it.next = common

        if not l1:
            l1 = common
        else:
            it = l1
            while it.next:
                it = it.next
            it.next = common

    if cycle0 != -1 and l0:
        last = l0
        while last.next:
            last = last.next
        it = l0
        for _ in range(cycle0):
            if not it:
                raise RuntimeError('Invalid input data')
            it = it.next
        last.next = it

    if cycle1 != -1 and l1:
        last = l1
        while last.next:
            last = last.next
        it = l1
        for _ in range(cycle1):
            if not it:
                raise RuntimeError('Invalid input data')
            it = it.next
        last.next = it

    common_nodes = set()
    it = common
    while it and id(it) not in common_nodes:
        common_nodes.add(id(it))
        it = it.next

    result = executor.run(functools.partial(overlapping_lists, l0, l1))

    if not (id(result) in common_nodes or (not common_nodes and not result)):
        raise TestFailure('Invalid result')
Пример #13
0
def search_maze_wrapper(executor, maze, s, e):
    s = Coordinate(*s)
    e = Coordinate(*e)
    cp = copy.deepcopy(maze)

    path = executor.run(functools.partial(search_maze, cp, s, e))

    if not path:
        return s == e

    if path[0] != s or path[-1] != e:
        raise TestFailure("Path doesn't lay between start and end points")

    for i in range(1, len(path)):
        if not path_element_is_feasible(maze, path[i - 1], path[i]):
            path_i_1 = path[i - 1]
            path_i = path[i]
            print('path_element_is_feasible path[i - 1]={}, path[i]={}'.format(
                path[i - 1], path[i]))
            print('maze(path[i - 1])={}, maze[path[i]]={}'.format(
                maze[path_i_1.x][path_i_1.y], maze[path_i.x][path_i.y]))
            raise TestFailure("Path contains invalid segments")

    return True
Пример #14
0
def queue_tester(ops):

    try:
        q = QueueWithMax()

        for (op, arg) in ops:
            if op == "QueueWithMax":
                q = QueueWithMax()
            elif op == "enqueue":
                q.enqueue(arg)
            elif op == "dequeue":
                result = q.dequeue()
                if result != arg:
                    raise TestFailure("Dequeue: expected " + str(arg) +
                                      ", got " + str(result))
            elif op == "max":
                result = q.max()
                if result != arg:
                    raise TestFailure("Max: expected " + str(arg) + ", got " +
                                      str(result))
            else:
                raise RuntimeError("Unsupported queue operation: " + op)
    except IndexError:
        raise TestFailure("Unexpected IndexError exception")
Пример #15
0
def find_kth_node_binary_tree_wrapper(executor, tree, k):
    def init_size(node):
        if not node:
            return 0
        node.size = 1 + init_size(node.left) + init_size(node.right)
        return node.size

    init_size(tree)

    result = executor.run(functools.partial(find_kth_node_binary_tree, tree,
                                            k))

    if not result:
        raise TestFailure("Result can't be None")
    return result.data
Пример #16
0
def build_bst_from_sorted_doubly_list_wrapper(executor, l):
    input_list = None
    for v in reversed(l):
        input_list = DoublyListNode(v, next=input_list)
        if input_list.next != None:
            input_list.next.prev = input_list

    input_list = executor.run(
        functools.partial(build_bst_from_sorted_doubly_list, input_list,
                          len(l)))

    it = iter(l)
    compare_vector_and_tree(input_list, it)
    if next(it, None) is not None:
        raise TestFailure("Too many l in the tree")
Пример #17
0
def list_pivoting_wrapper(executor, l, x):
    original = linked_to_list(l)

    l = executor.run(functools.partial(list_pivoting, l, x))

    pivoted = linked_to_list(l)
    mode = -1
    for i in pivoted:
        if mode == -1:
            if i == x:
                mode = 0
            elif i > x:
                mode = 1
        elif mode == 0:
            if i < x:
                raise TestFailure('List is not pivoted')
            elif i > x:
                mode = 1
        else:
            if i <= x:
                raise TestFailure('List is not pivoted')

    if sorted(original) != sorted(pivoted):
        raise TestFailure('Result list contains different values')
Пример #18
0
def queue_tester(ops):

    try:
        q = QueueWithMax()

        for (op, arg) in ops:
            if op == 'QueueWithMax':
                q = QueueWithMax()
            elif op == 'enqueue':
                q.enqueue(arg)
            elif op == 'dequeue':
                result = q.dequeue()
                if result != arg:
                    raise TestFailure('Dequeue: expected ' + str(arg) +
                                      ', got ' + str(result))
            elif op == 'max':
                result = q.max()
                if result != arg:
                    raise TestFailure('Max: expected ' + str(arg) + ', got ' +
                                      str(result))
            else:
                raise RuntimeError('Unsupported queue operation: ' + op)
    except IndexError:
        raise TestFailure('Unexpected IndexError exception')
    def assert_results_equal(self, expected, result):
        if self._comp is not None:
            comparison_result = self._comp(expected, result)
        elif expected is None:
            comparison_result = result is None
        elif isinstance(expected, float) or isinstance(result, float):
            comparison_result = math.isclose(expected, result)
        elif is_object_tree_type(expected) or is_object_tree_type(result):
            assert_equal_binary_trees(expected, result)
            return
        else:
            comparison_result = expected == result

        if not comparison_result:
            raise TestFailure()\
                .with_property(PropertyName.EXPECTED, expected)\
                .with_property(PropertyName.RESULT, result)
Пример #20
0
def assert_equal_binary_trees(expected, result):
    s = [(expected, result, TreePath())]

    while s:
        expected, result, path = s.pop()

        expected_data = expected.data if expected is not None else None
        result_data = result.data if result is not None else None

        if expected_data != result_data:
            raise TestFailure() \
                .with_property(PropertyName.RESULT, result) \
                .with_property(PropertyName.EXPECTED, expected) \
                .with_mismatch_info(path, expected_data, result_data)

        if expected is not None and result is not None:
            s.append((expected.left, result.left, path.with_left()))
            s.append((expected.right, result.right, path.with_right()))
def overlapping_no_cycle_lists_wrapper(executor, l0, l1, common):
    if common:
        if l0:
            i = l0
            while i.next:
                i = i.next
            i.next = common
        else:
            l0 = common

        if l1:
            i = l1
            while i.next:
                i = i.next
            i.next = common
        else:
            l1 = common

    result = executor.run(functools.partial(overlapping_no_cycle_lists, l0,
                                            l1))

    if result != common:
        raise TestFailure('Invalid result')
Пример #22
0
def overlapping_no_cycle_lists_wrapper(executor, L0, L1, common):
    if common:
        if L0:
            i = L0
            while i.next:
                i = i.next
            i.next = common
        else:
            L0 = common

        if L1:
            i = L1
            while i.next:
                i = i.next
            i.next = common
        else:
            L1 = common

    result = executor.run(functools.partial(overlapping_no_cycle_lists, L0,
                                            L1))

    if result != common:
        raise TestFailure('Invalid result')
Пример #23
0
def assert_all_values_present(reference, result):
    reference_set = collections.defaultdict(int)

    for x in reference:
        reference_set[x] += 1

    for x in result:
        reference_set[x] -= 1

    flatten = lambda l: [item for sublist in l for item in sublist]
    excess_items = flatten([x] * -count for x, count in reference_set.items()
                           if count < 0)
    missing_items = flatten([x] * count for x, count in reference_set.items()
                            if count > 0)

    if excess_items or missing_items:
        e = TestFailure("Value set changed").with_property(
            PropertyName.RESULT, result)
        if excess_items:
            e.with_property(PropertyName.EXCESS_ITEMS, excess_items)
        if missing_items:
            e.with_property(PropertyName.MISSING_ITEMS, missing_items)
        raise e
Пример #24
0
            # Try to copy vertex e.
            if e not in vertex_map:
                vertex_map[e] = GraphVertex(e.label)
                q.append(e)
            # Copy edge.
            vertex_map[v].edges.append(vertex_map[e])
    return vertex_map[problems.graph]


def copy_labels(edges):
    return [e.label for e in edges]


def check_graph(node, problems.graph):
    if node is None:
        raise TestFailure('Graph was not copied')

    vertex_set = set()
    q = collections.deque()
    q.append(node)
    vertex_set.add(node)
    while q:
        vertex = q.popleft()
        if vertex.label >= len(problems.graph):
            raise TestFailure('Invalid vertex label')
        label1 = copy_labels(vertex.edges)
        label2 = copy_labels(problems.graph[vertex.label].edges)
        if sorted(label1) != sorted(label2):
            raise TestFailure('Edges mismatch')
        for e in vertex.edges:
            if e not in vertex_set:
Пример #25
0
def find_missing_element_wrapper(data):
    try:
        return find_missing_element(iter(data))
    except ValueError:
        raise TestFailure('Unexpected no_missing_element exception')
def create_list_of_leaves_wrapper(executor, tree):
    result = executor.run(functools.partial(create_list_of_leaves, tree))

    if any(x is None for x in result):
        raise TestFailure("Result list can't contain None")
    return [x.data for x in result]
def wrapper(x, s):
    if int_to_string(x) != s:
        raise TestFailure("Int to string conversion failed")
    if string_to_int(s) != x:
        raise TestFailure("String to int conversion failed")
Пример #28
0
def wrapper(x, s):
    if int(int_to_string(x)) != x:
        raise TestFailure('Int to string conversion failed')
    if string_to_int(s) != x:
        raise TestFailure('String to int conversion failed')
Пример #29
0
def create_output_list(L):
    if any(l is None for l in L):
        raise TestFailure('Resulting list contains None')
    return [l.data for l in L]
Пример #30
0
def rle_tester(encoded, decoded):
    if decoding(encoded) != decoded:
        raise TestFailure('Decoding failed')
    if encoding(decoded) != encoded:
        raise TestFailure('Encoding failed')
def wrapper(x, s):
    if int(int_to_string(x)) != x:
        raise TestFailure('int_to_string')
    if string_to_int(s) != x:
        raise TestFailure('string_to_int')