Skip to content

Commit 83538b9

Browse files
committed
fix: simplify test code
1 parent a2ba725 commit 83538b9

19 files changed

Lines changed: 288 additions & 412 deletions

‎tests/conftest.py‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,112 @@
44

55
import pyarrow as pa
66
import pytest
7+
import structlog
8+
9+
from vgi.function import Arguments, Invocation, InvocationType
10+
11+
# =============================================================================
12+
# Utility Functions (not fixtures, can be imported directly)
13+
# =============================================================================
14+
15+
16+
def make_schema(fields: list[Any]) -> pa.Schema:
17+
"""Create schema with proper typing for field list.
18+
19+
This is a helper to avoid mypy errors when creating schemas from
20+
field tuples like [("name", pa.string())].
21+
"""
22+
return pa.schema(fields)
23+
24+
25+
def make_invocation(
26+
input_schema: pa.Schema | None = None,
27+
function_type: InvocationType = InvocationType.TABLE,
28+
arguments: Arguments | None = None,
29+
function_name: str = "test",
30+
) -> Invocation:
31+
"""Create a test invocation with flexible parameters."""
32+
return Invocation(
33+
function_name=function_name,
34+
input_schema=input_schema,
35+
function_type=function_type,
36+
correlation_id="test",
37+
invocation_id=b"test",
38+
arguments=arguments or Arguments(),
39+
)
40+
41+
42+
def make_scalar_invocation(
43+
input_schema: pa.Schema,
44+
arguments: Arguments | None = None,
45+
) -> Invocation:
46+
"""Create a scalar function test invocation."""
47+
return make_invocation(
48+
input_schema=input_schema,
49+
function_type=InvocationType.SCALAR,
50+
arguments=arguments,
51+
)
52+
53+
54+
def make_table_invocation(
55+
input_schema: pa.Schema,
56+
arguments: Arguments | None = None,
57+
) -> Invocation:
58+
"""Create a table function test invocation."""
59+
return make_invocation(
60+
input_schema=input_schema,
61+
function_type=InvocationType.TABLE,
62+
arguments=arguments,
63+
)
64+
65+
66+
def filter_non_empty(batches: list[pa.RecordBatch]) -> list[pa.RecordBatch]:
67+
"""Filter out empty batches."""
68+
return [b for b in batches if b.num_rows > 0]
69+
70+
71+
def assert_single_result(
72+
batches: list[pa.RecordBatch],
73+
expected: dict[str, list[Any]],
74+
) -> None:
75+
"""Assert a single-row aggregation result.
76+
77+
Filters out empty batches, asserts there's exactly one non-empty batch,
78+
and checks that its contents match the expected dictionary.
79+
"""
80+
non_empty = filter_non_empty(batches)
81+
assert len(non_empty) == 1, f"Expected 1 non-empty batch, got {len(non_empty)}"
82+
assert non_empty[0].to_pydict() == expected
83+
84+
85+
def total_rows(batches: list[pa.RecordBatch]) -> int:
86+
"""Return total row count across all batches."""
87+
return sum(b.num_rows for b in batches)
88+
89+
90+
def assert_total_rows(batches: list[pa.RecordBatch], expected: int) -> None:
91+
"""Assert total row count across all batches."""
92+
actual = total_rows(batches)
93+
assert actual == expected, f"Expected {expected} rows, got {actual}"
94+
95+
96+
def empty_batch_from_schema(schema: pa.Schema) -> pa.RecordBatch:
97+
"""Create an empty batch with the given schema."""
98+
return pa.RecordBatch.from_pydict(
99+
{field.name: [] for field in schema}, schema=schema
100+
)
101+
102+
103+
# =============================================================================
104+
# Fixtures
105+
# =============================================================================
106+
107+
108+
@pytest.fixture
109+
def test_logger() -> structlog.stdlib.BoundLogger:
110+
"""Provide a shared test logger."""
111+
logger: structlog.stdlib.BoundLogger = structlog.get_logger().bind(component="test")
112+
return logger
7113

8114

9115
@pytest.fixture

‎tests/scalar/test_client.py‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import pyarrow as pa
88
import pytest
99

10+
from tests.conftest import assert_total_rows
1011
from vgi.client import Client
1112
from vgi.client.client import ClientError
1213
from vgi.function import Arguments
@@ -88,8 +89,7 @@ def test_multiple_batches(self, example_worker: str) -> None:
8889

8990
# Should get 3 output batches (one per input)
9091
assert len(outputs) == 3
91-
total_rows = sum(b.num_rows for b in outputs)
92-
assert total_rows == 6
92+
assert_total_rows(outputs, 6)
9393

9494
# Verify the values (order may vary in parallel mode, but we're single-worker)
9595
all_values: list[int] = []
@@ -159,8 +159,7 @@ def test_large_batch(self, example_worker: str) -> None:
159159
)
160160
)
161161

162-
total_rows = sum(b.num_rows for b in outputs)
163-
assert total_rows == 10000
162+
assert_total_rows(outputs, 10000)
164163

165164
# Verify first and last values
166165
all_values = []
@@ -221,8 +220,7 @@ def test_parallel_double_column(self, example_worker: str) -> None:
221220
)
222221

223222
# Should get all 1000 rows back
224-
total_rows = sum(b.num_rows for b in outputs)
225-
assert total_rows == 1000
223+
assert_total_rows(outputs, 1000)
226224

227225
# Verify all values are correctly doubled
228226
all_values = set()
@@ -252,8 +250,7 @@ def test_parallel_add_columns(self, example_worker: str) -> None:
252250
)
253251

254252
# Should get 60 rows total (20 batches * 3 rows)
255-
total_rows = sum(b.num_rows for b in outputs)
256-
assert total_rows == 60
253+
assert_total_rows(outputs, 60)
257254

258255
def test_parallel_empty_batches_mixed(self, example_worker: str) -> None:
259256
"""Test parallel processing with mix of empty and non-empty batches."""
@@ -276,8 +273,7 @@ def test_parallel_empty_batches_mixed(self, example_worker: str) -> None:
276273
)
277274

278275
# Should get 6 rows total (2 + 0 + 1 + 0 + 3)
279-
total_rows = sum(b.num_rows for b in outputs)
280-
assert total_rows == 6
276+
assert_total_rows(outputs, 6)
281277

282278
# Verify values
283279
all_values = set()

‎tests/scalar/test_function.py‎

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import pytest
99
import structlog
1010

11+
from tests.conftest import make_scalar_invocation
1112
from vgi.arguments import Arg
1213
from vgi.function import Arguments, Invocation, InvocationType, SchemaValidationError
1314
from vgi.log import Level, Message
@@ -20,18 +21,6 @@
2021
)
2122

2223

23-
def create_invocation(input_schema: pa.Schema) -> Invocation:
24-
"""Create a test invocation with the given input schema."""
25-
return Invocation(
26-
function_name="test_function",
27-
input_schema=input_schema,
28-
function_type=InvocationType.SCALAR,
29-
correlation_id="test-correlation",
30-
invocation_id=b"test-invocation",
31-
arguments=Arguments(),
32-
)
33-
34-
3524
class TestScalarFunctionGenerator:
3625
"""Tests for the generator-based ScalarFunctionGenerator."""
3726

@@ -58,7 +47,7 @@ def process(self, batch: pa.RecordBatch) -> ScalarOutputGenerator:
5847
batch = received
5948

6049
input_schema = pa.schema([("x", pa.int64())])
61-
invocation = create_invocation(input_schema)
50+
invocation = make_scalar_invocation(input_schema)
6251
logger = structlog.get_logger()
6352

6453
func = DoubleColumn(invocation=invocation, logger=logger)
@@ -110,7 +99,7 @@ def process(self, batch: pa.RecordBatch) -> ScalarOutputGenerator:
11099
_ = yield Output(self.empty_output_batch)
111100

112101
input_schema = pa.schema([("x", pa.int64())])
113-
invocation = create_invocation(input_schema)
102+
invocation = make_scalar_invocation(input_schema)
114103

115104
with pytest.raises(SchemaValidationError, match="exactly 1 output column"):
116105
TwoColumnOutput(invocation=invocation, logger=structlog.get_logger())
@@ -139,7 +128,7 @@ def process(self, batch: pa.RecordBatch) -> ScalarOutputGenerator:
139128
batch = received
140129

141130
input_schema = pa.schema([("x", pa.int64())])
142-
invocation = create_invocation(input_schema)
131+
invocation = make_scalar_invocation(input_schema)
143132
func = LoggingScalar(invocation=invocation, logger=structlog.get_logger())
144133

145134
generator = func.run()
@@ -215,7 +204,7 @@ def compute(self, batch: pa.RecordBatch) -> pa.Array[Any]:
215204
return pc.multiply(batch.column("x"), 2)
216205

217206
input_schema = pa.schema([("x", pa.int64())])
218-
invocation = create_invocation(input_schema)
207+
invocation = make_scalar_invocation(input_schema)
219208
func = LoggingFunc(invocation=invocation, logger=structlog.get_logger())
220209

221210
generator = func.run()
@@ -247,7 +236,7 @@ def compute(self, batch: pa.RecordBatch) -> pa.Array[Any]:
247236
return pa.array([1, 2])
248237

249238
input_schema = pa.schema([("x", pa.int64())])
250-
invocation = create_invocation(input_schema)
239+
invocation = make_scalar_invocation(input_schema)
251240
func = WrongRowCount(invocation=invocation, logger=structlog.get_logger())
252241

253242
generator = func.run()
@@ -275,7 +264,7 @@ def compute(self, batch: pa.RecordBatch) -> pa.Array[Any]:
275264
return pc.multiply(batch.column("x"), 2)
276265

277266
input_schema = pa.schema([("x", pa.int64())])
278-
invocation = create_invocation(input_schema)
267+
invocation = make_scalar_invocation(input_schema)
279268
func = DoubleFunc(invocation=invocation, logger=structlog.get_logger())
280269

281270
generator = func.run()
Lines changed: 10 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
"""Tests for the ConstantTableFunction."""
22

33
import pyarrow as pa
4+
import pytest
5+
import structlog
46

7+
from tests.conftest import make_invocation
58
from vgi.examples.table import ConstantTableFunction
9+
from vgi.function import Arguments
610
from vgi.testing import assert_table_function_output, batch
711

812
from .conftest import RunnerWithMode
@@ -27,16 +31,8 @@ def test_metadata(self) -> None:
2731

2832
def test_cardinality(self) -> None:
2933
"""Cardinality should always be 1."""
30-
import structlog
31-
32-
from vgi.function import Arguments, Invocation, InvocationType
33-
34-
invocation = Invocation(
34+
invocation = make_invocation(
3535
function_name="constant_table",
36-
input_schema=None,
37-
function_type=InvocationType.TABLE,
38-
correlation_id="test",
39-
invocation_id=b"test",
4036
arguments=Arguments(positional=(pa.scalar(42),)),
4137
)
4238
func = ConstantTableFunction(
@@ -52,31 +48,14 @@ def test_cardinality(self) -> None:
5248
class TestConstantTableFunctionBothModes:
5349
"""Tests that run both in-process and via Client subprocess."""
5450

55-
def test_returns_constant_value(
56-
self, run_table_function_mode: RunnerWithMode
51+
@pytest.mark.parametrize("value", [42, -100, 0])
52+
def test_returns_value(
53+
self, run_table_function_mode: RunnerWithMode, value: int
5754
) -> None:
5855
"""Constant table should return a single row with the given value."""
5956
runner, mode = run_table_function_mode
60-
outputs, logs = runner(ConstantTableFunction, (42,))
61-
62-
table = pa.Table.from_batches(outputs)
63-
assert table.num_rows == 1
64-
assert table.column("value").to_pylist() == [42]
65-
66-
def test_negative_value(self, run_table_function_mode: RunnerWithMode) -> None:
67-
"""Constant table should handle negative values."""
68-
runner, mode = run_table_function_mode
69-
outputs, logs = runner(ConstantTableFunction, (-100,))
70-
71-
table = pa.Table.from_batches(outputs)
72-
assert table.num_rows == 1
73-
assert table.column("value").to_pylist() == [-100]
74-
75-
def test_zero_value(self, run_table_function_mode: RunnerWithMode) -> None:
76-
"""Constant table should handle zero."""
77-
runner, mode = run_table_function_mode
78-
outputs, logs = runner(ConstantTableFunction, (0,))
57+
outputs, logs = runner(ConstantTableFunction, (value,))
7958

8059
table = pa.Table.from_batches(outputs)
8160
assert table.num_rows == 1
82-
assert table.column("value").to_pylist() == [0]
61+
assert table.column("value").to_pylist() == [value]

0 commit comments

Comments
 (0)