Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/py-polars/tests/unit/utils/parse/test_expr.py
8422 views
1
from __future__ import annotations
2
3
from datetime import date
4
from typing import Any
5
6
import pytest
7
8
import polars as pl
9
from polars._utils.parse.expr import parse_into_expression
10
from polars._utils.wrap import wrap_expr
11
from polars.testing import assert_frame_equal
12
13
14
def assert_expr_equal(result: pl.Expr, expected: pl.Expr) -> None:
15
"""
16
Evaluate the given expressions in a simple context to assert equality.
17
18
WARNING: This is not a fully featured function - it's just to evaluate the tests in
19
this module. Do not use it elsewhere.
20
"""
21
df = pl.DataFrame({"a": [1, 2], "b": [3, 4]})
22
assert_frame_equal(df.select(result), df.select(expected))
23
24
25
@pytest.mark.parametrize(
26
"input", [5, 2.0, pl.Series([1, 2, 3]), date(2022, 1, 1), b"hi"]
27
)
28
def test_parse_into_expression_lit(input: Any) -> None:
29
result = wrap_expr(parse_into_expression(input))
30
expected = pl.lit(input)
31
assert_expr_equal(result, expected)
32
33
34
def test_parse_into_expression_col() -> None:
35
result = wrap_expr(parse_into_expression("a"))
36
expected = pl.col("a")
37
assert_expr_equal(result, expected)
38
39
40
@pytest.mark.parametrize("input", [pl.lit(4), pl.col("a")])
41
def test_parse_into_expression_expr(input: pl.Expr) -> None:
42
result = wrap_expr(parse_into_expression(input))
43
expected = input
44
assert_expr_equal(result, expected)
45
46
47
@pytest.mark.parametrize(
48
"input", [pl.when(True).then(1), pl.when(True).then(1).when(False).then(0)]
49
)
50
def test_parse_into_expression_whenthen(input: Any) -> None:
51
result = wrap_expr(parse_into_expression(input))
52
expected = input.otherwise(None)
53
assert_expr_equal(result, expected)
54
55
56
@pytest.mark.parametrize("input", [[1, 2, 3], (1, 2)])
57
def test_parse_into_expression_list(input: Any) -> None:
58
result = wrap_expr(parse_into_expression(input))
59
expected = pl.lit(pl.Series("literal", [input]))
60
assert_expr_equal(result, expected)
61
62
63
def test_parse_into_expression_str_as_lit() -> None:
64
result = wrap_expr(parse_into_expression("a", str_as_lit=True))
65
expected = pl.lit("a")
66
assert_expr_equal(result, expected)
67
68
69
def test_parse_into_expression_structify() -> None:
70
result = wrap_expr(parse_into_expression(pl.col("a", "b"), structify=True))
71
expected = pl.struct("a", "b")
72
assert_expr_equal(result, expected)
73
74
75
def test_parse_into_expression_structify_multiple_outputs() -> None:
76
# note: this only works because assert_expr_equal evaluates on a dataframe with
77
# columns "a" and "b"
78
result = wrap_expr(parse_into_expression(pl.col("*"), structify=True))
79
expected = pl.struct("a", "b")
80
assert_expr_equal(result, expected)
81
82