def test_sorting_with_cmp():
    @thesefy
    class Person(object): pass

    query = these((who, who2) for who in Person for who2 in Person)

    # Sort with tokens + filters
    sorted_parts =  list(sorted(query.tokens + query.filters,
                                key=functools.cmp_to_key(translation.cmp)))

    _k = functools.cmp_to_key(translation.cmp)
    for i, part in enumerate(sorted_parts):
        if i < len(sorted_parts) + 1:
            for after in sorted_parts[i+1:]:
                assert _k(part) <= _k(after), (part, after)


    # Now sort with filters + tokens
    sorted_parts =  list(sorted(query.filters + query.tokens,
                                key=functools.cmp_to_key(translation.cmp)))

    _k = functools.cmp_to_key(translation.cmp)
    for i, part in enumerate(sorted_parts):
        if i < len(sorted_parts) + 1:
            for after in sorted_parts[i+1:]:
                assert _k(part) <= _k(after), (part, after)
def test_cotraverse_expression():
    from xoutil.compat import zip
    from xotl.ql.expressions import is_a
    from xotl.ql.translation import cotraverse_expression

    @thesefy
    class Person(object):
        pass

    @thesefy
    class Partnership(object):
        pass

    query = these((person, partner)
                  for person, partner in zip(Person, Person)
                  for rel in Partnership
                  if (rel.subject == person) & (rel.obj == partner))
    filters = list(query.filters)
    person, partner = query.selection
    person_is_a_person = is_a(person, Person)
    partner_is_a_person = is_a(partner, Person)
    rel_token = query.tokens[-1]
    rel_subject = rel_token.expression.subject
    rel_obj = rel_token.expression.obj
    with context(UNPROXIFING_CONTEXT):
        assert person != partner
        assert person_is_a_person in filters
        assert partner_is_a_person in filters
        expected_terms_order = [person, partner, rel_token.expression, rel_subject, person, rel_obj, partner]
        assert expected_terms_order == list(cotraverse_expression(query))

    assert UNPROXIFING_CONTEXT not in context
def test_get_term_signature():
    assert get_term_signature(this.a) == ((), (None, 'a'))

    query = these(child
                  for parent in this('parent')
                  for child in parent.children)
    term = query.selection
    assert get_term_signature(term) == (('parent', 'children'), ('parent', 'children'))

    term = query.tokens[0].expression
    assert get_term_signature(term) == (('parent', ), ('parent', ))

    term = query.tokens[1].expression
    assert get_term_signature(term) == (('parent', 'children'), ('parent', 'children'))