Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/py-polars/tests/unit/interchange/test_buffer.py
6939 views
1
from __future__ import annotations
2
3
import pytest
4
5
import polars as pl
6
from polars.interchange.buffer import PolarsBuffer
7
from polars.interchange.protocol import CopyNotAllowedError, DlpackDeviceType
8
9
10
@pytest.mark.parametrize(
11
("data", "allow_copy"),
12
[
13
(pl.Series([1, 2]), True),
14
(pl.Series([1, 2]), False),
15
(pl.concat([pl.Series([1, 2]), pl.Series([1, 2])], rechunk=False), True),
16
],
17
)
18
def test_init(data: pl.Series, allow_copy: bool) -> None:
19
buffer = PolarsBuffer(data, allow_copy=allow_copy)
20
assert buffer._data.n_chunks() == 1
21
22
23
def test_init_invalid_input() -> None:
24
s = pl.Series([1, 2])
25
data = pl.concat([s, s], rechunk=False)
26
27
with pytest.raises(
28
CopyNotAllowedError, match="non-contiguous buffer must be made contiguous"
29
):
30
PolarsBuffer(data, allow_copy=False)
31
32
33
@pytest.mark.parametrize(
34
("data", "expected"),
35
[
36
(pl.Series([1, 2], dtype=pl.Int8), 2),
37
(pl.Series([1, 2], dtype=pl.Int64), 16),
38
(pl.Series([1.4, 2.9, 3.0], dtype=pl.Float32), 12),
39
(pl.Series([97, 98, 99, 195, 169, 195, 162, 195, 167], dtype=pl.UInt8), 9),
40
(pl.Series([0, 1, 0, 2, 0], dtype=pl.UInt32), 20),
41
(pl.Series([True, False], dtype=pl.Boolean), 1),
42
(pl.Series([True] * 8, dtype=pl.Boolean), 1),
43
(pl.Series([True] * 9, dtype=pl.Boolean), 2),
44
(pl.Series([True] * 9, dtype=pl.Boolean)[5:], 2),
45
],
46
)
47
def test_bufsize(data: pl.Series, expected: int) -> None:
48
buffer = PolarsBuffer(data)
49
assert buffer.bufsize == expected
50
51
52
@pytest.mark.parametrize(
53
"data",
54
[
55
pl.Series([1, 2]),
56
pl.Series([1.2, 2.9, 3.0]),
57
pl.Series([True, False]),
58
pl.Series([True, False])[1:],
59
pl.Series([97, 98, 97], dtype=pl.UInt8),
60
pl.Series([], dtype=pl.Float32),
61
],
62
)
63
def test_ptr(data: pl.Series) -> None:
64
buffer = PolarsBuffer(data)
65
result = buffer.ptr
66
# Memory address is unpredictable, so we just check if an integer is returned
67
assert isinstance(result, int)
68
69
70
def test__dlpack__() -> None:
71
data = pl.Series([1, 2])
72
buffer = PolarsBuffer(data)
73
with pytest.raises(NotImplementedError):
74
buffer.__dlpack__()
75
76
77
def test__dlpack_device__() -> None:
78
data = pl.Series([1, 2])
79
buffer = PolarsBuffer(data)
80
assert buffer.__dlpack_device__() == (DlpackDeviceType.CPU, None)
81
82
83
def test__repr__() -> None:
84
data = pl.Series([True, False, True])
85
buffer = PolarsBuffer(data)
86
print(buffer.__repr__())
87
88