def test_comprehension_filter_cast_assumptions(): assert isinstance( c.generator_comp(c.this).filter(c.this).execute(range(10)), GeneratorType, ) assert isinstance( c.generator_comp(c.this).filter(c.this, cast=None).execute(range(10)), GeneratorType, ) assert (c.list_comp(c.this).filter(c.this).execute(range(3))) == [ 1, 2, ] def f(x): f.number_of_calls += 1 if f.number_of_calls > f.max_number_of_calls: raise ValueError return bool(x) f.max_number_of_calls = 2 f.number_of_calls = 0 assert (c.set_comp(c.this).filter(c.call_func(f, c.this)).execute([0, 0, 1])) == { 1, } assert (c.set_comp(c.this).filter(c.this, cast=list).execute([0, 0, 1])) == [ 1, ] assert (c.set_comp(c.this).filter(c.this).execute(range(3))) == { 1, 2, } assert (c.tuple_comp(c.this).filter(c.this).execute(range(3))) == ( 1, 2, ) assert (c.tuple_comp(c.this).filter(c.this, list).execute(range(3))) == [ 1, 2, ] assert (c.dict_comp(c.this, c.this).filter(c.item(0)).execute(range(3))) == { 1: 1, 2: 2, } assert (c.dict_comp(c.this, c.this).filter(c.item(0), dict).execute(range(3))) == { 1: 1, 2: 2, }
def test_tuple_comprehension(): assert c.tuple_comp(1).gen_converter()(range(5)) == (1, ) * 5 data = [{"name": "John"}, {"name": "Bill"}, {"name": "Nick"}] assert c.tuple_comp(c.item("name")).sort( key=lambda n: n).gen_converter()(data) == ("Bill", "John", "Nick") assert c.tuple_comp(c.item("name")).sort().gen_converter()(data) == ( "Bill", "John", "Nick", ) assert c.tuple_comp(c.item("name")).sort( key=lambda n: n, reverse=True).gen_converter()(data) == ("Nick", "John", "Bill")
def test_comprehensions_sorting(): assert c.generator_comp(c.this()).sort().execute( [2, 1, 3], debug=False ) == [1, 2, 3] assert c.list_comp(c.this()).sort().execute([2, 1, 3], debug=False) == [ 1, 2, 3, ] assert c.this().pipe(c.list_comp(c.this())).sort().execute( [2, 1, 3], debug=False ) == [ 1, 2, 3, ] assert c.list_comp(c.this()).sort().sort(reverse=True).execute( [2, 1, 3], debug=False ) == [3, 2, 1] assert c.set_comp(c.this()).sort().execute([2, 2, 1, 3], debug=False) == [ 1, 2, 3, ] assert c.tuple_comp(c.this()).sort().execute( [2, 2, 1, 3], debug=False ) == ( 1, 2, 2, 3, ) assert c.dict_comp(c.this() * -1, c.this()).sort().execute( [2, 2, 1, 3], debug=False ) == OrderedDict( [ (-3, 3), (-2, 2), (-1, 1), ] )