This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-9623-39870fb165da046d13262da15e01c6608e077d4a
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 5295e7f8c49bce0a8ea58ba01c23c353fe0aef9b
Author: Xinyuan Lin <[email protected]>
AuthorDate: Mon Nov 23 22:53:20 2026 +0000

    test(pyamber): share storage, RPC, and table test fixtures (#9623)
    
    ### What changes were proposed in this PR?
    
    Shares repeated test setup, mock scaffolding, and assertion helpers
    across seven `pyamber` unit test suites without changing test coverage
    or production code:
    
    - **Large binary output stream tests:** introduces local context-manager
    helpers for paired S3 client/bucket patches and fresh test-value
    fixtures across `test_large_binary_output_stream.py`, preserving all
    literal assertions, patch lifetimes, thread-gate checks, and error
    scopes.
    - **Async RPC and debug control-handler tests:** extracts shared
    mock-handler, stream/payload factory, and invocation helpers across
    `test_debug_command_handler.py`, `test_evaluate_expression_handler.py`,
    `test_async_rpc_client.py`, and `test_async_rpc_server.py`.
    - **Table and batch-operator tests:** consolidates repeated batch/table
    construction and row-assertion helpers across `test_table.py` and
    `test_count_batch_operator.py`.
    
    All existing test names and assertions are preserved.
    
    ### Any related issues, documentation, discussions?
    
    Closes #9622.
    
    ### How was this PR tested?
    
    Ran in `amber/` against `origin/main` (`f030df12b7`) before and after
    the refactor on Python 3.12:
    
    ```bash
    ruff check src/main/python src/test/python
    ruff format --check src/main/python src/test/python
    python -m pytest -p no:timeout \
      src/test/python/pytexera/storage/test_large_binary_output_stream.py \
      
src/test/python/core/architecture/handlers/control/test_debug_command_handler.py
 \
      
src/test/python/core/architecture/handlers/control/test_evaluate_expression_handler.py
 \
      src/test/python/core/architecture/rpc/test_async_rpc_client.py \
      src/test/python/core/architecture/rpc/test_async_rpc_server.py \
      src/test/python/core/models/test_table.py \
      src/test/python/pytexera/udf/examples/test_count_batch_operator.py
    ```
    
    - `ruff check src/main/python src/test/python` and `ruff format --check
    src/main/python src/test/python`: passed.
    - Baseline vs. patched JUnit XML comparison: `119` passed, `0` failed,
    `0` skipped (`0` test name/outcome diffs across all 7 suites).
    - Negative mutation controls: breaking `large_binary_output_stream.py`
    (`if large_binary is None:`), `async_rpc_server.py` (`return command_id
    < 0`), and `count_batch_operator.py` (`self.count += 1`) each failed its
    guarding suite (`rc=1`), confirming the refactored assertions remain
    live.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Antigravity (Gemini), Claude Code (Claude Opus 5.5)
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../handlers/control/test_debug_command_handler.py |  85 +++----
 .../control/test_evaluate_expression_handler.py    |  65 ++---
 .../core/architecture/rpc/test_async_rpc_client.py |  29 +--
 .../core/architecture/rpc/test_async_rpc_server.py | 283 +++++++++------------
 amber/src/test/python/core/models/test_table.py    |  23 +-
 .../storage/test_large_binary_output_stream.py     | 131 +++-------
 .../udf/examples/test_count_batch_operator.py      | 111 +++-----
 7 files changed, 260 insertions(+), 467 deletions(-)

diff --git 
a/amber/src/test/python/core/architecture/handlers/control/test_debug_command_handler.py
 
b/amber/src/test/python/core/architecture/handlers/control/test_debug_command_handler.py
index 382d30412d..9dbdd6f2d2 100644
--- 
a/amber/src/test/python/core/architecture/handlers/control/test_debug_command_handler.py
+++ 
b/amber/src/test/python/core/architecture/handlers/control/test_debug_command_handler.py
@@ -31,6 +31,14 @@ from proto.org.apache.texera.amber.engine.architecture.rpc 
import (
 )
 
 
+def _translate(cmd: str, context) -> str:
+    return WorkerDebugCommandHandler.translate_debug_command(cmd, context)
+
+
+def _run_debug(handler, cmd: str):
+    return asyncio.run(handler.debug_command(DebugCommandRequest(cmd=cmd)))
+
+
 class TestTranslateDebugCommand:
     @pytest.fixture
     def context(self):
@@ -39,53 +47,36 @@ class TestTranslateDebugCommand:
         )
 
     def test_break_with_lineno_prepends_module(self, context):
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("b 5", context)
-            == "b my_udf:5"
-        )
+        assert _translate("b 5", context) == "b my_udf:5"
 
     def test_long_break_with_lineno_prepends_module(self, context):
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("break 12", 
context)
-            == "break my_udf:12"
-        )
+        assert _translate("break 12", context) == "break my_udf:12"
 
     def test_break_preserves_condition_arg(self, context):
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("b 7 x > 0", 
context)
-            == "b my_udf:7 x > 0"
-        )
+        assert _translate("b 7 x > 0", context) == "b my_udf:7 x > 0"
 
     def test_break_with_no_args_passes_through(self, context):
         # No args → falls through to the else branch (no module rewriting).
-        assert WorkerDebugCommandHandler.translate_debug_command("b", context) 
== "b"
+        assert _translate("b", context) == "b"
 
     def test_non_break_command_passes_through(self, context):
-        assert WorkerDebugCommandHandler.translate_debug_command("n", context) 
== "n"
+        assert _translate("n", context) == "n"
 
     def test_non_break_command_with_args_is_rejoined(self, context):
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("p some_var", 
context)
-            == "p some_var"
-        )
+        assert _translate("p some_var", context) == "p some_var"
 
     def test_leading_and_trailing_whitespace_is_stripped(self, context):
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("  c  ", 
context) == "c"
-        )
+        assert _translate("  c  ", context) == "c"
 
     def test_internal_whitespace_is_collapsed_to_single_space(self, context):
         # split() with no args collapses any run of whitespace, so the rejoined
         # form has single spaces regardless of how many the user typed.
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("p   foo    
bar", context)
-            == "p foo bar"
-        )
+        assert _translate("p   foo    bar", context) == "p foo bar"
 
     def test_break_with_only_lineno_has_no_trailing_space(self, context):
         # The implementation joins the (empty) tail with " "; the final strip()
         # must remove the trailing whitespace so the command stays valid pdb.
-        result = WorkerDebugCommandHandler.translate_debug_command("b 5", 
context)
+        result = _translate("b 5", context)
         assert result == "b my_udf:5"
         assert not result.endswith(" ")
 
@@ -93,54 +84,40 @@ class TestTranslateDebugCommand:
 
     def test_empty_command_raises_descriptive_error(self, context):
         with pytest.raises(ValueError, match="cannot be empty"):
-            WorkerDebugCommandHandler.translate_debug_command("", context)
+            _translate("", context)
 
     def test_whitespace_only_command_raises_descriptive_error(self, context):
         with pytest.raises(ValueError, match="cannot be empty"):
-            WorkerDebugCommandHandler.translate_debug_command("   \t  ", 
context)
+            _translate("   \t  ", context)
 
     def test_uppercase_break_is_not_recognized(self, context):
         # The match list is case-sensitive: ("b", "break"). "BREAK" / "B" fall
         # through to the pass-through branch and won't get the module prefix.
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("BREAK 5", 
context)
-            == "BREAK 5"
-        )
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("B 5", context) 
== "B 5"
-        )
+        assert _translate("BREAK 5", context) == "BREAK 5"
+        assert _translate("B 5", context) == "B 5"
 
     def test_break_with_function_name_passes_through(self, context):
         # pdb's `b` accepts a bare function name and resolves it itself; the
         # `module:funcname` form is invalid (pdb expects a lineno after a
         # filename prefix). So we leave function-name args unchanged.
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("b my_func", 
context)
-            == "b my_func"
-        )
+        assert _translate("b my_func", context) == "b my_func"
 
     def test_break_with_explicit_filename_passes_through(self, context):
         # The user already typed `filename:lineno` — don't double-prefix.
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("b foo.py:5", 
context)
-            == "b foo.py:5"
-        )
+        assert _translate("b foo.py:5", context) == "b foo.py:5"
 
     def test_break_with_lineno_before_module_init_raises(self, context):
         # Without an initialized executor module we cannot construct
         # `module:lineno`, so refuse instead of emitting `b None:5`.
         context.executor_manager.operator_module_name = None
         with pytest.raises(ValueError, match="executor module not 
initialized"):
-            WorkerDebugCommandHandler.translate_debug_command("b 5", context)
+            _translate("b 5", context)
 
     def test_break_with_function_name_before_module_init_passes_through(self, 
context):
         # Function-name and filename:lineno forms don't need the module name,
         # so they should still work even before the executor is initialized.
         context.executor_manager.operator_module_name = None
-        assert (
-            WorkerDebugCommandHandler.translate_debug_command("b my_func", 
context)
-            == "b my_func"
-        )
+        assert _translate("b my_func", context) == "b my_func"
 
 
 class TestDebugCommandAsyncFlow:
@@ -157,13 +134,13 @@ class TestDebugCommandAsyncFlow:
         return instance
 
     def test_translates_then_forwards_to_debug_manager(self, handler):
-        asyncio.run(handler.debug_command(DebugCommandRequest(cmd="b 5")))
+        _run_debug(handler, "b 5")
         
handler.context.debug_manager.put_debug_command.assert_called_once_with(
             "b my_udf:5"
         )
 
     def test_resumes_all_three_pause_types(self, handler):
-        asyncio.run(handler.debug_command(DebugCommandRequest(cmd="c")))
+        _run_debug(handler, "c")
         actual = [
             call.args[0] for call in 
handler.context.pause_manager.resume.call_args_list
         ]
@@ -174,11 +151,11 @@ class TestDebugCommandAsyncFlow:
         ]
 
     def test_returns_empty_return(self, handler):
-        result = 
asyncio.run(handler.debug_command(DebugCommandRequest(cmd="n")))
+        result = _run_debug(handler, "n")
         assert isinstance(result, EmptyReturn)
 
     def test_passes_through_non_break_command_unchanged(self, handler):
-        asyncio.run(handler.debug_command(DebugCommandRequest(cmd="p x")))
+        _run_debug(handler, "p x")
         
handler.context.debug_manager.put_debug_command.assert_called_once_with("p x")
 
     def test_empty_cmd_propagates_value_error(self, handler):
@@ -186,10 +163,10 @@ class TestDebugCommandAsyncFlow:
         # handler does not catch it — the RPC layer will surface the failure
         # back to the caller. Pin this so silent swallowing doesn't sneak in.
         with pytest.raises(ValueError):
-            asyncio.run(handler.debug_command(DebugCommandRequest(cmd="")))
+            _run_debug(handler, "")
 
     def test_translation_failure_skips_put_and_resume(self, handler):
         with pytest.raises(ValueError):
-            asyncio.run(handler.debug_command(DebugCommandRequest(cmd="")))
+            _run_debug(handler, "")
         handler.context.debug_manager.put_debug_command.assert_not_called()
         handler.context.pause_manager.resume.assert_not_called()
diff --git 
a/amber/src/test/python/core/architecture/handlers/control/test_evaluate_expression_handler.py
 
b/amber/src/test/python/core/architecture/handlers/control/test_evaluate_expression_handler.py
index a72c1f8263..db064aca2d 100644
--- 
a/amber/src/test/python/core/architecture/handlers/control/test_evaluate_expression_handler.py
+++ 
b/amber/src/test/python/core/architecture/handlers/control/test_evaluate_expression_handler.py
@@ -31,6 +31,20 @@ from proto.org.apache.texera.amber.engine.architecture.rpc 
import (
 )
 
 
+_EVALUATE_TARGET = (
+    "core.architecture.handlers.control.evaluate_expression_handler"
+    ".ExpressionEvaluator.evaluate"
+)
+
+
+def _eval(handler, expression: str):
+    return asyncio.run(
+        handler.evaluate_python_expression(
+            EvaluatePythonExpressionRequest(expression=expression)
+        )
+    )
+
+
 class TestEvaluateExpressionHandler:
     @pytest.fixture
     def executor(self):
@@ -55,30 +69,20 @@ class TestEvaluateExpressionHandler:
             value=TypedValue(expression="1+1", value_ref="2", value_type="int")
         )
         with patch(
-            "core.architecture.handlers.control.evaluate_expression_handler"
-            ".ExpressionEvaluator.evaluate",
+            _EVALUATE_TARGET,
             return_value=sentinel,
         ) as evaluate:
-            result = asyncio.run(
-                handler.evaluate_python_expression(
-                    EvaluatePythonExpressionRequest(expression="1+1")
-                )
-            )
+            result = _eval(handler, "1+1")
 
         assert result is sentinel
         evaluate.assert_called_once()
 
     def test_runtime_context_exposes_self_tuple_input(self, handler, executor):
         with patch(
-            "core.architecture.handlers.control.evaluate_expression_handler"
-            ".ExpressionEvaluator.evaluate",
+            _EVALUATE_TARGET,
             return_value=EvaluatedValue(),
         ) as evaluate:
-            asyncio.run(
-                handler.evaluate_python_expression(
-                    EvaluatePythonExpressionRequest(expression="self.state")
-                )
-            )
+            _eval(handler, "self.state")
 
         expression, runtime_context = evaluate.call_args.args
         assert expression == "self.state"
@@ -99,22 +103,13 @@ class TestEvaluateExpressionHandler:
             return EvaluatedValue()
 
         with patch(
-            "core.architecture.handlers.control.evaluate_expression_handler"
-            ".ExpressionEvaluator.evaluate",
+            _EVALUATE_TARGET,
             side_effect=capture,
         ):
-            asyncio.run(
-                handler.evaluate_python_expression(
-                    EvaluatePythonExpressionRequest(expression="x")
-                )
-            )
+            _eval(handler, "x")
             handler.context.tuple_processing_manager.current_input_tuple = 
{"col": 99}
             handler.context.tuple_processing_manager.current_input_port_id = 
"port-1"
-            asyncio.run(
-                handler.evaluate_python_expression(
-                    EvaluatePythonExpressionRequest(expression="x")
-                )
-            )
+            _eval(handler, "x")
 
         assert captured == [({"col": 42}, "port-0"), ({"col": 99}, "port-1")]
 
@@ -125,15 +120,10 @@ class TestEvaluateExpressionHandler:
         handler.context.tuple_processing_manager.current_input_tuple = None
         handler.context.tuple_processing_manager.current_input_port_id = None
         with patch(
-            "core.architecture.handlers.control.evaluate_expression_handler"
-            ".ExpressionEvaluator.evaluate",
+            _EVALUATE_TARGET,
             return_value=EvaluatedValue(),
         ) as evaluate:
-            asyncio.run(
-                handler.evaluate_python_expression(
-                    EvaluatePythonExpressionRequest(expression="self.state")
-                )
-            )
+            _eval(handler, "self.state")
 
         _expression, runtime_context = evaluate.call_args.args
         assert runtime_context["tuple_"] is None
@@ -144,13 +134,8 @@ class TestEvaluateExpressionHandler:
         # expression, etc.), the handler must not swallow it — the RPC layer
         # is responsible for surfacing the failure to the frontend.
         with patch(
-            "core.architecture.handlers.control.evaluate_expression_handler"
-            ".ExpressionEvaluator.evaluate",
+            _EVALUATE_TARGET,
             side_effect=AttributeError("no such attribute"),
         ):
             with pytest.raises(AttributeError, match="no such attribute"):
-                asyncio.run(
-                    handler.evaluate_python_expression(
-                        
EvaluatePythonExpressionRequest(expression="self.missing")
-                    )
-                )
+                _eval(handler, "self.missing")
diff --git 
a/amber/src/test/python/core/architecture/rpc/test_async_rpc_client.py 
b/amber/src/test/python/core/architecture/rpc/test_async_rpc_client.py
index 8d2336f493..c8243864d7 100644
--- a/amber/src/test/python/core/architecture/rpc/test_async_rpc_client.py
+++ b/amber/src/test/python/core/architecture/rpc/test_async_rpc_client.py
@@ -34,6 +34,14 @@ from proto.org.apache.texera.amber.engine.architecture.rpc 
import (
 )
 
 
+def _control_channel(from_name: str) -> ChannelIdentity:
+    return ChannelIdentity(
+        from_worker_id=ActorVirtualIdentity(name=from_name),
+        to_worker_id=ActorVirtualIdentity(name="self"),
+        is_control=True,
+    )
+
+
 def _make_client():
     """AsyncRPCClient with mock queue and a SimpleNamespace context.
 
@@ -100,22 +108,13 @@ class TestCreateFuture:
 
 
 class TestFulfillPromise:
-    def _channel(self, name: str) -> ChannelIdentity:
-        # `_fulfill_promise` looks up the dict by `from_.from_worker_id`; build
-        # a ChannelIdentity whose sender slot matches the actor we promised to.
-        return ChannelIdentity(
-            from_worker_id=ActorVirtualIdentity(name=name),
-            to_worker_id=ActorVirtualIdentity(name="self"),
-            is_control=True,
-        )
-
     def test_resolves_matching_future_and_clears_the_entry(self):
         client = _make_client()
         actor = ActorVirtualIdentity(name="A")
         fut = client._create_future(actor)
         ret = ControlReturn()
 
-        client._fulfill_promise(self._channel("A"), command_id=0, 
control_return=ret)
+        client._fulfill_promise(_control_channel("A"), command_id=0, 
control_return=ret)
 
         assert fut.done() and fut.result() is ret
         assert (actor, 0) not in client._unfulfilled_promises
@@ -140,7 +139,7 @@ class TestFulfillPromise:
         # No prior _create_future for actor "A" — nothing to match. Method
         # must not raise.
         client._fulfill_promise(
-            self._channel("A"), command_id=99, control_return=ControlReturn()
+            _control_channel("A"), command_id=99, 
control_return=ControlReturn()
         )
 
         assert len(warning_calls) == 1
@@ -157,7 +156,7 @@ class TestFulfillPromise:
         fut_b = client._create_future(actor_b)
 
         client._fulfill_promise(
-            self._channel("A"), command_id=0, control_return=ControlReturn()
+            _control_channel("A"), command_id=0, control_return=ControlReturn()
         )
 
         assert fut_a.done()
@@ -172,11 +171,7 @@ class TestReceive:
         fut = client._create_future(actor)
         ret = ControlReturn()
         invocation = ReturnInvocation(command_id=0, return_value=ret)
-        from_ = ChannelIdentity(
-            from_worker_id=actor,
-            to_worker_id=ActorVirtualIdentity(name="self"),
-            is_control=True,
-        )
+        from_ = _control_channel("A")
 
         client.receive(from_, invocation)
 
diff --git 
a/amber/src/test/python/core/architecture/rpc/test_async_rpc_server.py 
b/amber/src/test/python/core/architecture/rpc/test_async_rpc_server.py
index d56c33a4d4..62b443f593 100644
--- a/amber/src/test/python/core/architecture/rpc/test_async_rpc_server.py
+++ b/amber/src/test/python/core/architecture/rpc/test_async_rpc_server.py
@@ -86,11 +86,13 @@ def _make_invocation(
     return invocation
 
 
-def _make_channel(from_name: str, to_name: str) -> ChannelIdentity:
+def _make_channel(
+    from_name: str, to_name: str, is_control: bool = True
+) -> ChannelIdentity:
     return ChannelIdentity(
         from_worker_id=ActorVirtualIdentity(name=from_name),
         to_worker_id=ActorVirtualIdentity(name=to_name),
-        is_control=True,
+        is_control=is_control,
     )
 
 
@@ -108,6 +110,41 @@ def _return_invocation_of(element: DCMElement) -> 
ReturnInvocation:
     return get_one_of(element.payload, sealed=False)
 
 
+def _reply_handler(*messages) -> grpclib.const.Handler:
+    async def handler_func(stream):
+        for message in messages:
+            await stream.send_message(message)
+
+    return _make_handler(handler_func)
+
+
+def _error_handler(exc: Exception) -> grpclib.const.Handler:
+    async def handler_func(stream):
+        raise exc
+
+    return _make_handler(handler_func)
+
+
+def _dispatch(
+    handlers: dict,
+    method_name: str,
+    command_id: int,
+    *,
+    from_name: str = "A",
+    to_name: str = "B",
+    context: AsyncRpcContext | None = None,
+    is_control: bool = True,
+) -> AsyncRPCServer:
+    server = _make_server(handlers)
+    channel = _make_channel(from_name, to_name, is_control=is_control)
+    server.receive(channel, _make_invocation(method_name, command_id, 
context=context))
+    return server
+
+
+def _drain_return(server: AsyncRPCServer) -> ReturnInvocation:
+    return _return_invocation_of(_drain_single_element(server._output_queue))
+
+
 class TestHandlerMapConstruction:
     def _server_with_mapping(self, monkeypatch, mapping: dict) -> 
AsyncRPCServer:
         """Runs the real __init__ against a stubbed AsyncRPCHandlerInitializer.
@@ -198,14 +235,11 @@ class TestWrapAsStream:
 class TestReceiveSuccess:
     @pytest.mark.timeout(2)
     def test_reply_carries_command_id_and_round_tripped_return_value(self):
-        async def handler_func(stream):
-            await stream.send_message(StringResponse(value="hello"))
-
-        server = _make_server({"echo": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Echo", 42))
+        server = _dispatch(
+            {"echo": _reply_handler(StringResponse(value="hello"))}, "Echo", 42
+        )
 
-        element = _drain_single_element(server._output_queue)
-        return_invocation = _return_invocation_of(element)
+        return_invocation = _drain_return(server)
         assert return_invocation.command_id == 42
         assert get_one_of(return_invocation.return_value) == StringResponse(
             value="hello"
@@ -222,22 +256,19 @@ class TestReceiveSuccess:
             received.append(await stream.recv_message())
             await stream.send_message(StringResponse(value="ok"))
 
-        server = _make_server({"probe": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Probe", 1))
+        _dispatch({"probe": _make_handler(handler_func)}, "Probe", 1)
 
         assert received == [EmptyRequest()]
 
     @pytest.mark.timeout(2)
     def test_method_name_lookup_is_case_insensitive(self):
-        async def handler_func(stream):
-            await stream.send_message(StringResponse(value="ok"))
-
-        server = _make_server({"pauseworker": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), 
_make_invocation("PAUSEWorker", 7))
-
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
+        server = _dispatch(
+            {"pauseworker": _reply_handler(StringResponse(value="ok"))},
+            "PAUSEWorker",
+            7,
         )
+
+        return_invocation = _drain_return(server)
         assert get_one_of(return_invocation.return_value) == 
StringResponse(value="ok")
 
     @pytest.mark.timeout(2)
@@ -246,15 +277,9 @@ class TestReceiveSuccess:
         # set_one_of(ControlReturn, None) silently produces a ControlReturn
         # with NO variant set (it tries to assign a "none_type" attribute,
         # which betterproto ignores as a oneof). A reply is still sent.
-        async def handler_func(stream):
-            pass
-
-        server = _make_server({"silent": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Silent", 3))
+        server = _dispatch({"silent": _make_handler()}, "Silent", 3)
 
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
-        )
+        return_invocation = _drain_return(server)
         assert return_invocation.command_id == 3
         assert get_one_of(return_invocation.return_value) is None
 
@@ -266,15 +291,11 @@ class TestReceiveSuccess:
         # so set_one_of assigns an "empty_request" attribute that ControlReturn
         # has no oneof for. The reply is still sent, but its ControlReturn has
         # no variant set and serializes to nothing.
-        async def handler_func(stream):
-            await stream.send_message(EmptyRequest())
-
-        server = _make_server({"wrongtype": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("WrongType", 
4))
-
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
+        server = _dispatch(
+            {"wrongtype": _reply_handler(EmptyRequest())}, "WrongType", 4
         )
+
+        return_invocation = _drain_return(server)
         assert return_invocation.command_id == 4
         assert get_one_of(return_invocation.return_value) is None
         assert bytes(return_invocation.return_value) == b""
@@ -295,9 +316,7 @@ class TestReceiveSuccess:
         server.receive(_make_channel("A", "B"), invocation)
 
         assert received == [None]
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
-        )
+        return_invocation = _drain_return(server)
         assert return_invocation.command_id == 8
         assert get_one_of(return_invocation.return_value) == StringResponse(
             value="still works"
@@ -307,16 +326,17 @@ class TestReceiveSuccess:
     def test_handler_sending_twice_replies_with_the_last_message(self):
         # The synthetic stream keeps only one slot: a second send_message
         # overwrites the first, so the reply carries the last write.
-        async def handler_func(stream):
-            await stream.send_message(StringResponse(value="first"))
-            await stream.send_message(StringResponse(value="second"))
-
-        server = _make_server({"twice": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Twice", 14))
-
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
+        server = _dispatch(
+            {
+                "twice": _reply_handler(
+                    StringResponse(value="first"), 
StringResponse(value="second")
+                )
+            },
+            "Twice",
+            14,
         )
+
+        return_invocation = _drain_return(server)
         assert get_one_of(return_invocation.return_value) == StringResponse(
             value="second"
         )
@@ -325,15 +345,11 @@ class TestReceiveSuccess:
 class TestReceiveError:
     @pytest.mark.timeout(2)
     def test_raising_handler_replies_with_control_error(self):
-        async def handler_func(stream):
-            raise ValueError("boom")
-
-        server = _make_server({"explode": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Explode", 5))
-
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
+        server = _dispatch(
+            {"explode": _error_handler(ValueError("boom"))}, "Explode", 5
         )
+
+        return_invocation = _drain_return(server)
         assert return_invocation.command_id == 5
         error = get_one_of(return_invocation.return_value)
         assert isinstance(error, ControlError)
@@ -342,19 +358,11 @@ class TestReceiveError:
 
     @pytest.mark.timeout(2)
     def test_control_error_includes_exception_notes(self):
-        async def handler_func(stream):
-            error = ValueError("boom")
-            error.add_note("(line 2 of the UDF code)")
-            raise error
-
-        server = _make_server({"explode": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Explode", 6))
+        exc = ValueError("boom")
+        exc.add_note("(line 2 of the UDF code)")
+        server = _dispatch({"explode": _error_handler(exc)}, "Explode", 6)
 
-        error = get_one_of(
-            _return_invocation_of(
-                _drain_single_element(server._output_queue)
-            ).return_value
-        )
+        error = get_one_of(_drain_return(server).return_value)
         assert error.error_message == "boom (line 2 of the UDF code)"
 
     @pytest.mark.timeout(5)
@@ -374,21 +382,14 @@ class TestReceiveError:
         finally:
             manager.close()
 
-        error = get_one_of(
-            _return_invocation_of(
-                _drain_single_element(server._output_queue)
-            ).return_value
-        )
+        error = get_one_of(_drain_return(server).return_value)
         assert error.error_message == "'k' (KeyError at line 3 of the UDF 
code)"
 
     @pytest.mark.timeout(2)
     def 
test_unknown_method_replies_with_control_error_instead_of_raising(self):
-        server = _make_server({})
-        server.receive(_make_channel("A", "B"), 
_make_invocation("NoSuchMethod", 6))
+        server = _dispatch({}, "NoSuchMethod", 6)
 
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
-        )
+        return_invocation = _drain_return(server)
         error = get_one_of(return_invocation.return_value)
         assert isinstance(error, ControlError)
         # look_up raises KeyError('nosuchmethod') and str() of a KeyError
@@ -400,15 +401,9 @@ class TestReceiveError:
     def test_exception_with_empty_message_yields_empty_error_message(self):
         # str(ValueError()) is "", so the ControlError carries an empty
         # error_message — the reply itself is still well-formed.
-        async def handler_func(stream):
-            raise ValueError()
-
-        server = _make_server({"blank": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Blank", 15))
+        server = _dispatch({"blank": _error_handler(ValueError())}, "Blank", 
15)
 
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
-        )
+        return_invocation = _drain_return(server)
         assert return_invocation.command_id == 15
         error = get_one_of(return_invocation.return_value)
         assert isinstance(error, ControlError)
@@ -419,35 +414,27 @@ class TestReceiveError:
 class TestNoReplyNeeded:
     @pytest.mark.timeout(2)
     def test_negative_command_id_enqueues_nothing_on_success(self):
-        async def handler_func(stream):
-            await stream.send_message(StringResponse(value="ignored"))
-
-        server = _make_server({"quiet": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Quiet", -1))
+        server = _dispatch(
+            {"quiet": _reply_handler(StringResponse(value="ignored"))}, 
"Quiet", -1
+        )
 
         assert server._output_queue.size() == 0
 
     @pytest.mark.timeout(2)
     def test_negative_command_id_enqueues_nothing_on_error(self):
-        async def handler_func(stream):
-            raise RuntimeError("swallowed")
-
-        server = _make_server({"quiet": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Quiet", -7))
+        server = _dispatch(
+            {"quiet": _error_handler(RuntimeError("swallowed"))}, "Quiet", -7
+        )
 
         assert server._output_queue.size() == 0
 
     @pytest.mark.timeout(2)
     def test_command_id_zero_is_not_negative_so_a_reply_is_sent(self):
-        async def handler_func(stream):
-            await stream.send_message(StringResponse(value="zero"))
-
-        server = _make_server({"boundary": _make_handler(handler_func)})
-        server.receive(_make_channel("A", "B"), _make_invocation("Boundary", 
0))
-
-        return_invocation = _return_invocation_of(
-            _drain_single_element(server._output_queue)
+        server = _dispatch(
+            {"boundary": _reply_handler(StringResponse(value="zero"))}, 
"Boundary", 0
         )
+
+        return_invocation = _drain_return(server)
         assert return_invocation.command_id == 0
 
     @pytest.mark.timeout(2)
@@ -455,8 +442,7 @@ class TestNoReplyNeeded:
         # The fire-and-forget + missing-method combination: the KeyError is
         # swallowed into a ControlError that is then never sent, so the only
         # trace of the failed invocation is a log line.
-        server = _make_server({})
-        server.receive(_make_channel("A", "B"), 
_make_invocation("NoSuchMethod", -3))
+        server = _dispatch({}, "NoSuchMethod", -3)
 
         assert server._output_queue.size() == 0
 
@@ -469,91 +455,54 @@ class TestNoReplyNeeded:
 
 class TestReplyRouting:
     @staticmethod
-    def _ok_handler():
-        async def handler_func(stream):
-            await stream.send_message(StringResponse(value="routed"))
-
-        return _make_handler(handler_func)
+    def _route(
+        command_id: int,
+        *,
+        from_name: str = "worker-A",
+        to_name: str = "worker-B",
+        context: AsyncRpcContext | None = None,
+        is_control: bool = True,
+    ) -> ChannelIdentity:
+        server = _dispatch(
+            {"route": _reply_handler(StringResponse(value="routed"))},
+            "Route",
+            command_id,
+            from_name=from_name,
+            to_name=to_name,
+            context=context,
+            is_control=is_control,
+        )
+        return _drain_single_element(server._output_queue).tag
 
     @pytest.mark.timeout(2)
     def test_context_sender_and_receiver_set_routes_receiver_to_sender(self):
-        server = _make_server({"route": self._ok_handler()})
         context = AsyncRpcContext(
             sender=ActorVirtualIdentity(name="CONTROLLER"),
             receiver=ActorVirtualIdentity(name="worker-1"),
         )
-        server.receive(
-            _make_channel("data-in", "data-out"),
-            _make_invocation("Route", 9, context=context),
-        )
-
-        element = _drain_single_element(server._output_queue)
-        assert element.tag == ChannelIdentity(
-            from_worker_id=ActorVirtualIdentity(name="worker-1"),
-            to_worker_id=ActorVirtualIdentity(name="CONTROLLER"),
-            is_control=True,
-        )
+        assert self._route(
+            9, from_name="data-in", to_name="data-out", context=context
+        ) == _make_channel("worker-1", "CONTROLLER")
 
     @pytest.mark.timeout(2)
     def test_unset_context_falls_back_to_swapping_the_incoming_channel(self):
-        server = _make_server({"route": self._ok_handler()})
-        server.receive(
-            _make_channel("worker-A", "worker-B"), _make_invocation("Route", 
10)
-        )
-
-        element = _drain_single_element(server._output_queue)
-        assert element.tag == ChannelIdentity(
-            from_worker_id=ActorVirtualIdentity(name="worker-B"),
-            to_worker_id=ActorVirtualIdentity(name="worker-A"),
-            is_control=True,
-        )
+        assert self._route(10) == _make_channel("worker-B", "worker-A")
 
     @pytest.mark.timeout(2)
     def test_partially_set_context_also_falls_back_to_swapping(self):
         # BOTH sender and receiver names must be non-empty to use the context
         # route; with only the sender set the fallback swap is used.
-        server = _make_server({"route": self._ok_handler()})
         context = 
AsyncRpcContext(sender=ActorVirtualIdentity(name="CONTROLLER"))
-        server.receive(
-            _make_channel("worker-A", "worker-B"),
-            _make_invocation("Route", 11, context=context),
-        )
-
-        element = _drain_single_element(server._output_queue)
-        assert element.tag == ChannelIdentity(
-            from_worker_id=ActorVirtualIdentity(name="worker-B"),
-            to_worker_id=ActorVirtualIdentity(name="worker-A"),
-            is_control=True,
-        )
+        assert self._route(11, context=context) == _make_channel("worker-B", 
"worker-A")
 
     @pytest.mark.timeout(2)
     def test_context_with_only_receiver_set_also_falls_back_to_swapping(self):
         # Mirror of the sender-only case: this pins the FIRST conjunct of
         # `ctx.sender.name and ctx.receiver.name`, so dropping the sender
         # check from the condition cannot go unnoticed.
-        server = _make_server({"route": self._ok_handler()})
         context = 
AsyncRpcContext(receiver=ActorVirtualIdentity(name="worker-1"))
-        server.receive(
-            _make_channel("worker-A", "worker-B"),
-            _make_invocation("Route", 13, context=context),
-        )
-
-        element = _drain_single_element(server._output_queue)
-        assert element.tag == ChannelIdentity(
-            from_worker_id=ActorVirtualIdentity(name="worker-B"),
-            to_worker_id=ActorVirtualIdentity(name="worker-A"),
-            is_control=True,
-        )
+        assert self._route(13, context=context) == _make_channel("worker-B", 
"worker-A")
 
     @pytest.mark.timeout(2)
     def 
test_fallback_reply_channel_is_control_even_for_data_channel_input(self):
-        server = _make_server({"route": self._ok_handler()})
-        from_ = ChannelIdentity(
-            from_worker_id=ActorVirtualIdentity(name="worker-A"),
-            to_worker_id=ActorVirtualIdentity(name="worker-B"),
-            is_control=False,
-        )
-        server.receive(from_, _make_invocation("Route", 12))
-
-        element = _drain_single_element(server._output_queue)
-        assert element.tag.is_control is True
+        assert self._route(12, is_control=False).is_control is True
diff --git a/amber/src/test/python/core/models/test_table.py 
b/amber/src/test/python/core/models/test_table.py
index 80a985e5d6..ab5eba0579 100644
--- a/amber/src/test/python/core/models/test_table.py
+++ b/amber/src/test/python/core/models/test_table.py
@@ -92,6 +92,12 @@ class TestTable:
             ],
         )
 
+    @staticmethod
+    def _assert_table_round_trips(source, target_table, target_tuples):
+        table = Table(source)
+        assert table == target_table
+        assert list(table.as_tuples()) == target_tuples
+
     def test_table_creation(self, target_table, a_timestamp):
         assert target_table["field1"][0] == 1
         assert target_table["field1"][1] == 2
@@ -117,22 +123,19 @@ class TestTable:
         assert Table(target_data_frame) == target_table
 
     def test_table_from_list_of_tuples(self, target_table, target_tuples):
-        table = Table(target_tuples)
-        assert table == target_table
-        assert list(table.as_tuples()) == target_tuples
+        self._assert_table_round_trips(target_tuples, target_table, 
target_tuples)
 
     def test_table_from_list_of_series(
         self, target_table, a_timestamp, target_raw_tuples, target_tuples
     ):
-        table = Table([pandas.Series(raw_tuple) for raw_tuple in 
target_raw_tuples])
-
-        assert table == target_table
-        assert list(table.as_tuples()) == target_tuples
+        self._assert_table_round_trips(
+            [pandas.Series(raw_tuple) for raw_tuple in target_raw_tuples],
+            target_table,
+            target_tuples,
+        )
 
     def test_table_from_table(self, target_table, target_tuples):
-        table = Table(target_table)
-        assert table == target_table
-        assert list(table.as_tuples()) == target_tuples
+        self._assert_table_round_trips(target_table, target_table, 
target_tuples)
 
     def test_use_table_as_data_frame(self, target_table, target_data_frame):
         df = target_table
diff --git 
a/amber/src/test/python/pytexera/storage/test_large_binary_output_stream.py 
b/amber/src/test/python/pytexera/storage/test_large_binary_output_stream.py
index 93f09c14c1..f6ab9ee4f8 100644
--- a/amber/src/test/python/pytexera/storage/test_large_binary_output_stream.py
+++ b/amber/src/test/python/pytexera/storage/test_large_binary_output_stream.py
@@ -15,6 +15,8 @@
 # specific language governing permissions and limitations
 # under the License.
 
+from contextlib import contextmanager
+
 import queue
 import threading
 import pytest
@@ -31,12 +33,24 @@ from pytexera.storage.large_binary_manager import 
LargeBinaryManager
 large_binary_manager = LargeBinaryManager()
 
 
-class TestLargeBinaryOutputStream:
-    @pytest.fixture
-    def large_binary(self):
-        """Create a test largebinary."""
-        return largebinary("s3://test-bucket/path/to/object")
+@contextmanager
+def _mock_s3_upload():
+    with (
+        patch.object(large_binary_manager, "_get_s3_client") as get_client,
+        patch.object(large_binary_manager, "_ensure_bucket_exists") as 
ensure_bucket,
+    ):
+        client = MagicMock()
+        get_client.return_value = client
+        ensure_bucket.return_value = None
+        yield client
+
+
[email protected]
+def large_binary():
+    return largebinary("s3://test-bucket/path/to/object")
 
+
+class TestLargeBinaryOutputStream:
     def test_init_with_valid_large_binary(self, large_binary):
         """Test initialization with a valid largebinary."""
         stream = LargeBinaryOutputStream(large_binary)
@@ -53,16 +67,7 @@ class TestLargeBinaryOutputStream:
 
     def test_write_starts_upload_thread(self, large_binary):
         """Test that write() starts the upload thread."""
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
-
+        with _mock_s3_upload():
             stream = LargeBinaryOutputStream(large_binary)
             assert stream._upload_thread is None
 
@@ -76,16 +81,7 @@ class TestLargeBinaryOutputStream:
 
     def test_write_data(self, large_binary):
         """Test writing data to the stream."""
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
-
+        with _mock_s3_upload():
             stream = LargeBinaryOutputStream(large_binary)
             bytes_written = stream.write(b"test data")
             assert bytes_written == len(b"test data")
@@ -94,16 +90,7 @@ class TestLargeBinaryOutputStream:
 
     def test_write_multiple_chunks(self, large_binary):
         """Test writing multiple chunks of data."""
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
-
+        with _mock_s3_upload():
             stream = LargeBinaryOutputStream(large_binary)
             stream.write(b"chunk1")
             stream.write(b"chunk2")
@@ -140,16 +127,7 @@ class TestLargeBinaryOutputStream:
 
     def test_close_completes_upload(self, large_binary):
         """Test that close() completes the upload."""
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
-
+        with _mock_s3_upload() as mock_s3:
             stream = LargeBinaryOutputStream(large_binary)
             stream.write(b"test data")
 
@@ -161,16 +139,7 @@ class TestLargeBinaryOutputStream:
 
     def test_context_manager(self, large_binary):
         """Test using as context manager."""
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
-
+        with _mock_s3_upload():
             with LargeBinaryOutputStream(large_binary) as stream:
                 stream.write(b"test data")
                 assert not stream.closed
@@ -188,15 +157,7 @@ class TestLargeBinaryOutputStream:
 
     def test_close_handles_upload_error(self, large_binary):
         """Test that close() raises IOError if upload fails."""
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
+        with _mock_s3_upload() as mock_s3:
             mock_s3.upload_fileobj.side_effect = Exception("Upload failed")
 
             stream = LargeBinaryOutputStream(large_binary)
@@ -207,15 +168,7 @@ class TestLargeBinaryOutputStream:
 
     def test_write_after_upload_error_raises_error(self, large_binary):
         """Test that writing after upload error raises IOError."""
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
+        with _mock_s3_upload() as mock_s3:
             mock_s3.upload_fileobj.side_effect = Exception("Upload failed")
 
             stream = LargeBinaryOutputStream(large_binary)
@@ -237,12 +190,9 @@ class TestLargeBinaryOutputStream:
     def test_write_unblocks_when_upload_fails_with_full_queue(self, 
large_binary):
         with (
             patch("pytexera.storage.large_binary_output_stream._CHUNK_SIZE", 
1),
-            patch.object(large_binary_manager, "_get_s3_client") as get_client,
-            patch.object(large_binary_manager, "_ensure_bucket_exists"),
+            _mock_s3_upload() as mock_s3,
         ):
-            get_client.return_value.upload_fileobj.side_effect = RuntimeError(
-                "upload failed"
-            )
+            mock_s3.upload_fileobj.side_effect = RuntimeError("upload failed")
             stream = LargeBinaryOutputStream(large_binary)
             errors = []
 
@@ -263,16 +213,7 @@ class TestLargeBinaryOutputStream:
 
     def test_multiple_close_calls(self, large_binary):
         """Test that multiple close() calls are safe."""
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
-
+        with _mock_s3_upload():
             stream = LargeBinaryOutputStream(large_binary)
             stream.write(b"test data")
             stream.close()
@@ -283,23 +224,11 @@ class TestLargeBinaryOutputStream:
 class TestUploadWorkerCleanup:
     """Direct unit tests for the upload worker's silent-swallow cleanup."""
 
-    @pytest.fixture
-    def large_binary(self):
-        return largebinary("s3://test-bucket/path/to/object")
-
     def test_delete_object_failure_is_swallowed(self, large_binary):
         # If the post-failure cleanup itself raises, the original upload
         # IOError must still surface unmasked. Pinning this so a future
         # change that propagates cleanup errors is intentional.
-        with (
-            patch.object(large_binary_manager, "_get_s3_client") as 
mock_get_s3_client,
-            patch.object(
-                large_binary_manager, "_ensure_bucket_exists"
-            ) as mock_ensure_bucket,
-        ):
-            mock_s3 = MagicMock()
-            mock_get_s3_client.return_value = mock_s3
-            mock_ensure_bucket.return_value = None
+        with _mock_s3_upload() as mock_s3:
             mock_s3.upload_fileobj.side_effect = Exception("upload failed")
             mock_s3.delete_object.side_effect = Exception("delete also failed")
 
diff --git 
a/amber/src/test/python/pytexera/udf/examples/test_count_batch_operator.py 
b/amber/src/test/python/pytexera/udf/examples/test_count_batch_operator.py
index 4721861682..6ce5543b6d 100644
--- a/amber/src/test/python/pytexera/udf/examples/test_count_batch_operator.py
+++ b/amber/src/test/python/pytexera/udf/examples/test_count_batch_operator.py
@@ -28,95 +28,50 @@ class TestCountBatchOperator:
     def count_batch_operator(self):
         return CountBatchOperator()
 
-    def test_count_batch_operator(self, count_batch_operator):
-        count_batch_operator.open()
-        for i in range(27):
-            deque(
-                count_batch_operator.process_tuple(
-                    Tuple({"test-1": "hello", "test-2": 10}), 0
+    @staticmethod
+    def _run_batches(operator, *stages):
+        operator.open()
+        for count, batch_size in stages:
+            if batch_size is not None:
+                operator.BATCH_SIZE = batch_size
+            for _ in range(count):
+                deque(
+                    operator.process_tuple(Tuple({"test-1": "hello", "test-2": 
10}), 0)
                 )
+        deque(operator.on_finish(0))
+        batch_counter = operator.count
+        operator.close()
+        return batch_counter
+
+    @staticmethod
+    def _assert_invalid_batch_size(value_expr: str, expected_msg: str):
+        with pytest.raises(ValueError) as exc_info:
+            operator_string = 
str(inspect.getsource(CountBatchOperator)).replace(
+                "BATCH_SIZE = 10", f"BATCH_SIZE = {value_expr}"
             )
-        deque(count_batch_operator.on_finish(0))
-        batch_counter = count_batch_operator.count
-        assert batch_counter == 3
-        count_batch_operator.close()
+            operator_string += "operator = CountBatchOperator()"
+            exec(operator_string)
+        assert exc_info.value.args[0] == expected_msg
+
+    def test_count_batch_operator(self, count_batch_operator):
+        assert self._run_batches(count_batch_operator, (27, None)) == 3
 
     def test_count_batch_operator_simple(self, count_batch_operator):
-        count_batch_operator.open()
-        for i in range(20):
-            deque(
-                count_batch_operator.process_tuple(
-                    Tuple({"test-1": "hello", "test-2": 10}), 0
-                )
-            )
-        deque(count_batch_operator.on_finish(0))
-        batch_counter = count_batch_operator.count
-        assert batch_counter == 2
-        count_batch_operator.close()
+        assert self._run_batches(count_batch_operator, (20, None)) == 2
 
     def test_count_batch_operator_medium(self, count_batch_operator):
-        count_batch_operator.open()
-        for i in range(27):
-            deque(
-                count_batch_operator.process_tuple(
-                    Tuple({"test-1": "hello", "test-2": 10}), 0
-                )
-            )
-        deque(count_batch_operator.on_finish(0))
-        batch_counter = count_batch_operator.count
-        assert batch_counter == 3
-        count_batch_operator.close()
+        assert self._run_batches(count_batch_operator, (27, None)) == 3
 
     def test_count_batch_operator_hard(self, count_batch_operator):
-        count_batch_operator.open()
-        count_batch_operator.BATCH_SIZE = 10
-        for i in range(27):
-            deque(
-                count_batch_operator.process_tuple(
-                    Tuple({"test-1": "hello", "test-2": 10}), 0
-                )
-            )
-        count_batch_operator.BATCH_SIZE = 5
-        for i in range(27):
-            deque(
-                count_batch_operator.process_tuple(
-                    Tuple({"test-1": "hello", "test-2": 10}), 0
-                )
-            )
-        deque(count_batch_operator.on_finish(0))
-        batch_counter = count_batch_operator.count
-        assert batch_counter == 9
-        count_batch_operator.close()
+        assert self._run_batches(count_batch_operator, (27, 10), (27, 5)) == 9
 
     def test_edge_case_string(self):
-        with pytest.raises(ValueError) as exc_info:
-            operator_string = str(inspect.getsource(CountBatchOperator))
-            operator_string = operator_string.replace(
-                "BATCH_SIZE = 10", 'BATCH_SIZE = "test"'
-            )
-            operator_string += "operator = CountBatchOperator()"
-            exec(operator_string)
-            assert (
-                exc_info.value.args[0]
-                == "BATCH_SIZE cannot be " + str(type("test")) + "."
-            )
+        self._assert_invalid_batch_size(
+            '"test"', "BATCH_SIZE cannot be " + str(type("test")) + "."
+        )
 
     def test_edge_case_non_positive(self, count_batch_operator):
-        with pytest.raises(ValueError) as exc_info:
-            operator_string = str(inspect.getsource(CountBatchOperator))
-            operator_string = operator_string.replace(
-                "BATCH_SIZE = 10", "BATCH_SIZE = -20"
-            )
-            operator_string += "operator = CountBatchOperator()"
-            exec(operator_string)
-            assert exc_info.value.args[0] == "BATCH_SIZE should be positive."
+        self._assert_invalid_batch_size("-20", "BATCH_SIZE should be 
positive.")
 
     def test_edge_case_none(self, count_batch_operator):
-        with pytest.raises(ValueError) as exc_info:
-            operator_string = str(inspect.getsource(CountBatchOperator))
-            operator_string = operator_string.replace(
-                "BATCH_SIZE = 10", "BATCH_SIZE = None"
-            )
-            operator_string += "operator = CountBatchOperator()"
-            exec(operator_string)
-            assert exc_info.value.args[0] == "BATCH_SIZE cannot be None."
+        self._assert_invalid_batch_size("None", "BATCH_SIZE cannot be None.")

Reply via email to