Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(rnd): Add Agent Block sample/test input output for auto-generated unit testing for block (#7310)

Zamil Majdyd9c9b2288612
diff --git a/rnd/autogpt_server/README.md b/rnd/autogpt_server/README.md
index e01106174b..2d7397a73e 100644
--- a/rnd/autogpt_server/README.md
+++ b/rnd/autogpt_server/README.md
@@ -4,21 +4,6 @@ This is a research project into creating the next generation of autogpt, which i
The agent server will enable the creation of composite multi-agent system that utilize AutoGPT Agent as its default agent.
-
-## Project Outline
-
-Currently the project mainly consist of these components:
-
-*agent_api*
-A component that will expose API endpoints for the creation & execution of agents.
-This component will make connections to the database to persist and read the agents.
-It will also trigger the agent execution by pushing its execution request to the ExecutionQueue.
-
-*agent_executor*
-A component that will execute the agents.
-This component will be a pool of processes/threads that will consume the ExecutionQueue and execute the agent accordingly.
-The result and progress of its execution will be persisted in the database.
-
## Setup
This setup is for MacOS/Linux.
@@ -112,3 +97,65 @@ To run the tests
```
poetry run pytest
```
+
+## Project Outline
+
+The current project has the following main modules:
+
+### **blocks**
+
+This module stores all the Agent Block, a reusable component to build a graph that represents the agent's behavior.
+
+### **data**
+
+This module stores the logical model that is persisted in the database.
+This module abstracts the database operation into a function that can be called by the service layer.
+Any code that interacts with Prisma objects or databases should live in this module.
+The main models are:
+* `block`: anything related to the block used in the graph
+* `execution`: anything related to the execution graph execution
+* `graph`: anything related to the graph, node, and its relation
+
+### **execution**
+
+This module stores the business logic of executing the graph.
+It currently has the following main modules:
+* `manager`: A service that consumes the queue of the graph execution and executes the graph. It contains both of the logic.
+* `scheduler`: A service that triggers scheduled graph execution based on cron expression. It will push an execution request to the manager.
+
+### **server**
+
+This module stores the logic for the server API.
+It stores all the logic used for the API that allows the client to create/execute/monitor the graph and its execution.
+This API service will interact with other services like the ones defined in `manager` and `scheduler`.
+
+### **utils**
+
+This module stores the utility functions that are used across the project.
+Currently, it only has two main modules:
+* `process`: A module that contains the logic to spawn a new process.
+* `service`: A module that becomes a parent class for all the services in the project.
+
+## Service Communication
+
+Currently, there are only 3 active services:
+
+- AgentServer (the API, defined in `server.py`)
+- ExecutionManager (the executor, defined in `manager.py`)
+- ExecutionScheduler (the scheduler, defined in `scheduler.py`)
+
+The service is running in an independent python process and communicates through an IPC.
+A communication layer (`service.py`) is created to decouple the communication library from the implementation.
+
+Currently, the IPC is done using Pyro5 and abstracted in a way that it allows a function that is decorated with an `@expose` function can be called from the different process.
+
+## Adding a new Agent Block
+
+To add a new agent block, you need to create a new class that inherits from `Block` that provide these information:
+* `input_schema`: the schema of the input data, represented by a pydantic object.
+* `output_schema`: the schema of the output data, represented by a pydantic object.
+* `run` method: the main logic of the block
+* `test_input` & `test_output`: the sample input and output data for the block, this will be used to auto-test the block.
+* You can mock the functions declared in the block using the `test_mock` field for your unit test.
+* If you introduced a new module under the `blocks` package, you need to import the module in `blocks/__init__.py` to make it available to the server.
+* Once you finished creating the block, you can test it by running the test using `pytest test/block/test_block.py`.
diff --git a/rnd/autogpt_server/autogpt_server/blocks/__init__.py b/rnd/autogpt_server/autogpt_server/blocks/__init__.py
index 225af0bfc9..b7631b954f 100644
--- a/rnd/autogpt_server/autogpt_server/blocks/__init__.py
+++ b/rnd/autogpt_server/autogpt_server/blocks/__init__.py
@@ -1,4 +1,4 @@
-from autogpt_server.blocks import sample, reddit, text, object, ai
+from autogpt_server.blocks import sample, reddit, text, ai
from autogpt_server.data.block import Block
AVAILABLE_BLOCKS = {
@@ -6,4 +6,4 @@ AVAILABLE_BLOCKS = {
for block in [v() for v in Block.__subclasses__()]
}
-__all__ = ["ai", "object", "sample", "reddit", "text", "AVAILABLE_BLOCKS"]
+__all__ = ["ai", "sample", "reddit", "text", "AVAILABLE_BLOCKS"]
diff --git a/rnd/autogpt_server/autogpt_server/blocks/ai.py b/rnd/autogpt_server/autogpt_server/blocks/ai.py
index b9a8ef7698..8cffcabce9 100644
--- a/rnd/autogpt_server/autogpt_server/blocks/ai.py
+++ b/rnd/autogpt_server/autogpt_server/blocks/ai.py
@@ -36,10 +36,36 @@ class LlmCallBlock(Block):
id="ed55ac19-356e-4243-a6cb-bc599e9b716f",
input_schema=LlmCallBlock.Input,
output_schema=LlmCallBlock.Output,
+ test_input={
+ "config": {
+ "model": "gpt-4-turbo",
+ "api_key": "fake-api",
+ },
+ "expected_format": {
+ "key1": "value1",
+ "key2": "value2",
+ },
+ "sys_prompt": "System prompt",
+ "usr_prompt": "User prompt",
+ },
+ test_output=("response", {"key1": "key1Value","key2": "key2Value"}),
+ test_mock={"llm_call": lambda *args, **kwargs: json.dumps({
+ "key1": "key1Value",
+ "key2": "key2Value",
+ })},
)
+ @staticmethod
+ def llm_call(api_key: str, model: LlmModel, prompt: list[dict]) -> str:
+ openai.api_key = api_key
+ response = openai.chat.completions.create(
+ model=model,
+ messages=prompt, # type: ignore
+ response_format={"type": "json_object"},
+ )
+ return response.choices[0].message.content or ""
+
def run(self, input_data: Input) -> BlockOutput:
- openai.api_key = input_data.config.api_key
expected_format = [f'"{k}": "{v}"' for k, v in
input_data.expected_format.items()]
@@ -78,12 +104,11 @@ class LlmCallBlock(Block):
logger.warning(f"LLM request: {prompt}")
retry_prompt = ""
for retry_count in range(input_data.retry):
- response = openai.chat.completions.create(
- model=input_data.config.model,
- messages=prompt, # type: ignore
- response_format={"type": "json_object"},
+ response_text = self.llm_call(
+ input_data.config.api_key,
+ input_data.config.model,
+ prompt
)
- response_text = response.choices[0].message.content or ""
logger.warning(f"LLM attempt-{retry_count} response: {response_text}")
parsed_dict, parsed_error = parse_response(response_text)
diff --git a/rnd/autogpt_server/autogpt_server/blocks/object.py b/rnd/autogpt_server/autogpt_server/blocks/object.py
deleted file mode 100644
index 2a566e34bd..0000000000
--- a/rnd/autogpt_server/autogpt_server/blocks/object.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from typing import Any
-
-from autogpt_server.data.block import Block, BlockOutput, BlockSchema
-
-
-class ObjectParser(Block):
- class Input(BlockSchema):
- object: Any
- field_path: str
-
- class Output(BlockSchema):
- field_value: Any
-
- def __init__(self):
- super().__init__(
- id="be45299a-193b-4852-bda4-510883d21814",
- input_schema=ObjectParser.Input,
- output_schema=ObjectParser.Output,
- )
-
- def run(self, input_data: Input) -> BlockOutput:
- field_path = input_data.field_path.split(".")
- field_value = input_data.object
- for field in field_path:
- if isinstance(field_value, dict) and field in field_value:
- field_value = field_value.get(field)
- elif isinstance(field_value, object) and hasattr(field_value, field):
- field_value = getattr(field_value, field)
- else:
- yield "error", input_data.object
- return
-
- yield "field_value", field_value
diff --git a/rnd/autogpt_server/autogpt_server/blocks/reddit.py b/rnd/autogpt_server/autogpt_server/blocks/reddit.py
index 85ed2510c5..93d6642cbe 100644
--- a/rnd/autogpt_server/autogpt_server/blocks/reddit.py
+++ b/rnd/autogpt_server/autogpt_server/blocks/reddit.py
@@ -5,8 +5,10 @@ from datetime import datetime, timedelta, timezone
import praw
from typing import Any
from pydantic import BaseModel, Field
+from typing import Iterator
from autogpt_server.data.block import Block, BlockOutput, BlockSchema
+from autogpt_server.util.mock import MockObject
class RedditCredentials(BaseModel):
@@ -64,13 +66,42 @@ class RedditGetPostsBlock(Block):
id="c6731acb-4285-4ee1-bc9b-03d0766c370f",
input_schema=RedditGetPostsBlock.Input,
output_schema=RedditGetPostsBlock.Output,
+ test_input={
+ "creds": {
+ "client_id": "client_id",
+ "client_secret": "client_secret",
+ "username": "username",
+ "password": "password",
+ "user_agent": "user_agent",
+ },
+ "subreddit": "subreddit",
+ "last_post": "id3",
+ "post_limit": 2,
+ },
+ test_output=[
+ ("post", RedditPost(
+ id="id1", subreddit="subreddit", title="title1", body="body1")),
+ ("post", RedditPost(
+ id="id2", subreddit="subreddit", title="title2", body="body2")),
+ ],
+ test_mock={
+ "get_posts": lambda _: [
+ MockObject(id="id1", title="title1", selftext="body1"),
+ MockObject(id="id2", title="title2", selftext="body2"),
+ MockObject(id="id3", title="title2", selftext="body2"),
+ ]
+ }
)
-
- def run(self, input_data: Input) -> BlockOutput:
+
+ @staticmethod
+ def get_posts(input_data: Input) -> Iterator[praw.reddit.Submission]:
client = get_praw(input_data.creds)
subreddit = client.subreddit(input_data.subreddit)
- for post in subreddit.new(limit=input_data.post_limit):
- if input_data.last_post and post.created_utc < datetime.now(tz=timezone.utc) - \
+ return subreddit.new(limit=input_data.post_limit)
+
+ def run(self, input_data: Input) -> BlockOutput:
+ for post in self.get_posts(input_data):
+ if input_data.last_minutes and post.created_utc < datetime.now(tz=timezone.utc) - \
timedelta(minutes=input_data.last_minutes):
break
@@ -79,7 +110,7 @@ class RedditGetPostsBlock(Block):
yield "post", RedditPost(
id=post.id,
- subreddit=subreddit.display_name,
+ subreddit=input_data.subreddit,
title=post.title,
body=post.selftext
)
diff --git a/rnd/autogpt_server/autogpt_server/blocks/sample.py b/rnd/autogpt_server/autogpt_server/blocks/sample.py
index 6b08b484e0..57fe95bcc7 100644
--- a/rnd/autogpt_server/autogpt_server/blocks/sample.py
+++ b/rnd/autogpt_server/autogpt_server/blocks/sample.py
@@ -15,6 +15,8 @@ class ParrotBlock(Block):
id="1ff065e9-88e8-4358-9d82-8dc91f622ba9",
input_schema=ParrotBlock.Input,
output_schema=ParrotBlock.Output,
+ test_input={"input": "Hello, World!"},
+ test_output=("output", "Hello, World!"),
)
def run(self, input_data: Input) -> BlockOutput:
@@ -33,6 +35,8 @@ class PrintingBlock(Block):
id="f3b1c1b2-4c4f-4f0d-8d2f-4c4f0d8d2f4c",
input_schema=PrintingBlock.Input,
output_schema=PrintingBlock.Output,
+ test_input={"text": "Hello, World!"},
+ test_output=("status", "printed"),
)
def run(self, input_data: Input) -> BlockOutput:
diff --git a/rnd/autogpt_server/autogpt_server/blocks/text.py b/rnd/autogpt_server/autogpt_server/blocks/text.py
index 57594783b1..609671e4bf 100644
--- a/rnd/autogpt_server/autogpt_server/blocks/text.py
+++ b/rnd/autogpt_server/autogpt_server/blocks/text.py
@@ -22,6 +22,18 @@ class TextMatcherBlock(Block):
id="3060088f-6ed9-4928-9ba7-9c92823a7ccd",
input_schema=TextMatcherBlock.Input,
output_schema=TextMatcherBlock.Output,
+ test_input=[
+ {"text": "ABC", "match": "ab", "data": "X", "case_sensitive": False},
+ {"text": "ABC", "match": "ab", "data": "Y", "case_sensitive": True},
+ {"text": "Hello World!", "match": ".orld.+", "data": "Z"},
+ {"text": "Hello World!", "match": "World![a-z]+", "data": "Z"},
+ ],
+ test_output=[
+ ("positive", "X"),
+ ("negative", "Y"),
+ ("positive", "Z"),
+ ("negative", "Z"),
+ ],
)
def run(self, input_data: Input) -> BlockOutput:
@@ -55,6 +67,20 @@ class TextFormatterBlock(Block):
id="db7d8f02-2f44-4c55-ab7a-eae0941f0c30",
input_schema=TextFormatterBlock.Input,
output_schema=TextFormatterBlock.Output,
+ test_input=[
+ {"texts": ["Hello"], "format": "{texts[0]}"},
+ {
+ "texts": ["Hello", "World!"],
+ "named_texts": {"name": "Alice"},
+ "format": "{texts[0]} {texts[1]} {name}",
+ },
+ {"format": "Hello, World!"},
+ ],
+ test_output=[
+ ("output", "Hello"),
+ ("output", "Hello World! Alice"),
+ ("output", "Hello, World!"),
+ ],
)
def run(self, input_data: Input) -> BlockOutput:
diff --git a/rnd/autogpt_server/autogpt_server/data/block.py b/rnd/autogpt_server/autogpt_server/data/block.py
index d13b9b24b5..fa413452cb 100644
--- a/rnd/autogpt_server/autogpt_server/data/block.py
+++ b/rnd/autogpt_server/autogpt_server/data/block.py
@@ -8,7 +8,9 @@ from pydantic import BaseModel
from autogpt_server.util import json
-BlockData = dict[str, Any]
+BlockInput = dict[str, Any]
+BlockData = tuple[str, Any]
+BlockOutput = Generator[BlockData, None, None]
class BlockSchema(BaseModel):
@@ -36,7 +38,7 @@ class BlockSchema(BaseModel):
return cls.cached_jsonschema
@classmethod
- def validate_data(cls, data: BlockData) -> str | None:
+ def validate_data(cls, data: BlockInput) -> str | None:
"""
Validate the data against the schema.
Returns the validation error message if the data does not match the schema.
@@ -48,7 +50,7 @@ class BlockSchema(BaseModel):
return str(e)
@classmethod
- def validate_field(cls, field_name: str, data: BlockData) -> str | None:
+ def validate_field(cls, field_name: str, data: BlockInput) -> str | None:
"""
Validate the data against a specific property (one of the input/output name).
Returns the validation error message if the data does not match the schema.
@@ -80,7 +82,6 @@ class BlockSchema(BaseModel):
}
-BlockOutput = Generator[tuple[str, Any], None, None]
BlockSchemaInputType = TypeVar("BlockSchemaInputType", bound=BlockSchema)
BlockSchemaOutputType = TypeVar("BlockSchemaOutputType", bound=BlockSchema)
@@ -95,15 +96,29 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):
id: str = "",
input_schema: Type[BlockSchemaInputType] = EmptySchema,
output_schema: Type[BlockSchemaOutputType] = EmptySchema,
+ test_input: BlockInput | list[BlockInput] | None = None,
+ test_output: BlockData | list[BlockData] | None = None,
+ test_mock: dict[str, Any] | None = None,
):
"""
- The unique identifier for the block, this value will be persisted in the DB.
- So it should be a unique and constant across the application run.
- Use the UUID format for the ID.
+ Initialize the block with the given schema.
+
+ Args:
+ id: The unique identifier for the block, this value will be persisted in the
+ DB. So it should be a unique and constant across the application run.
+ Use the UUID format for the ID.
+ input_schema: The schema, defined as a Pydantic model, for the input data.
+ output_schema: The schema, defined as a Pydantic model, for the output data.
+ test_input: The list or single sample input data for the block, for testing.
+ test_output: The list or single expected output if the test_input is run.
+ test_mock: function names on the block implementation to mock on test run.
"""
self.id = id
self.input_schema = input_schema
self.output_schema = output_schema
+ self.test_input = test_input
+ self.test_output = test_output
+ self.test_mock = test_mock
@abstractmethod
def run(self, input_data: BlockSchemaInputType) -> BlockOutput:
@@ -130,7 +145,7 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):
"outputSchema": self.output_schema.jsonschema(),
}
- def execute(self, input_data: BlockData) -> BlockOutput:
+ def execute(self, input_data: BlockInput) -> BlockOutput:
if error := self.input_schema.validate_data(input_data):
raise ValueError(
f"Unable to execute block with invalid input data: {error}"
@@ -144,11 +159,13 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):
# ======================= Block Helper Functions ======================= #
-import autogpt_server.blocks
+def get_blocks() -> dict[str, Block]:
+ from autogpt_server.blocks import AVAILABLE_BLOCKS # noqa: E402
+ return AVAILABLE_BLOCKS
async def initialize_blocks() -> None:
- for block in autogpt_server.blocks.AVAILABLE_BLOCKS.values():
+ for block in get_blocks().values():
if await AgentBlock.prisma().find_unique(where={"id": block.id}):
continue
@@ -162,9 +179,5 @@ async def initialize_blocks() -> None:
)
-def get_blocks() -> list[Block]:
- return list(autogpt_server.blocks.AVAILABLE_BLOCKS.values())
-
-
def get_block(block_id: str) -> Block | None:
- return autogpt_server.blocks.AVAILABLE_BLOCKS.get(block_id)
+ return get_blocks().get(block_id)
diff --git a/rnd/autogpt_server/autogpt_server/server/server.py b/rnd/autogpt_server/autogpt_server/server/server.py
index a65d9c09f1..85a6439448 100644
--- a/rnd/autogpt_server/autogpt_server/server/server.py
+++ b/rnd/autogpt_server/autogpt_server/server/server.py
@@ -1,10 +1,9 @@
import asyncio
import uuid
-from contextlib import asynccontextmanager
from typing import Annotated, Any, Dict
import uvicorn
-from fastapi import APIRouter, Body, FastAPI, HTTPException, WebSocket
+from fastapi import WebSocket
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
@@ -18,7 +17,6 @@ from autogpt_server.data.graph import (
get_graph,
get_graph_ids,
Graph,
- Link,
)
from autogpt_server.executor import ExecutionManager, ExecutionScheduler
from autogpt_server.server.conn_manager import ConnectionManager
@@ -73,6 +71,11 @@ class AgentServer(AppService):
endpoint=self.get_graph_blocks, # type: ignore
methods=["GET"],
)
+ router.add_api_route(
+ path="/blocks/{block_id}/execute",
+ endpoint=self.execute_graph_block,
+ methods=["POST"],
+ )
router.add_api_route(
path="/graphs",
endpoint=self.get_graphs,
@@ -125,6 +128,8 @@ class AgentServer(AppService):
methods=["POST"],
)
+ app.add_exception_handler(500, self.handle_internal_error)
+
app.mount(
path="/frontend",
app=StaticFiles(directory=get_frontend_path(), html=True),
@@ -147,19 +152,40 @@ class AgentServer(AppService):
def execution_scheduler_client(self) -> ExecutionScheduler:
return get_service_client(ExecutionScheduler)
- def get_graph_blocks(self) -> list[dict[Any, Any]]:
- return [v.to_dict() for v in block.get_blocks()]
+ @classmethod
+ def handle_internal_error(cls, request, exc):
+ return JSONResponse(
+ content={
+ "message": f"{request.url.path} call failure",
+ "error": str(exc),
+ },
+ status_code=500,
+ )
+
+ @classmethod
+ def get_graph_blocks(cls) -> list[dict[Any, Any]]:
+ return [v.to_dict() for v in block.get_blocks().values()]
+
+ @classmethod
+ def execute_graph_block(cls, block_id: str, data: dict[str, Any]) -> list:
+ obj = block.get_block(block_id)
+ if not obj:
+ raise HTTPException(status_code=404, detail=f"Block #{block_id} not found.")
+ return [{name: data} for name, data in obj.execute(data)]
- async def get_graphs(self) -> list[str]:
+ @classmethod
+ async def get_graphs(cls) -> list[str]:
return await get_graph_ids()
- async def get_graph(self, graph_id: str) -> Graph:
+ @classmethod
+ async def get_graph(cls, graph_id: str) -> Graph:
graph = await get_graph(graph_id)
if not graph:
raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")
return graph
- async def create_new_graph(self, graph: Graph) -> Graph:
+ @classmethod
+ async def create_new_graph(cls, graph: Graph) -> Graph:
# TODO: replace uuid generation here to DB generated uuids.
graph.id = str(uuid.uuid4())
id_map = {node.id: str(uuid.uuid4()) for node in graph.nodes}
@@ -182,15 +208,17 @@ class AgentServer(AppService):
msg = e.__str__().encode().decode("unicode_escape")
raise HTTPException(status_code=400, detail=msg)
- async def list_graph_runs(self, graph_id: str) -> list[str]:
+ @classmethod
+ async def list_graph_runs(cls, graph_id: str) -> list[str]:
graph = await get_graph(graph_id)
if not graph:
raise HTTPException(status_code=404, detail=f"Agent #{graph_id} not found.")
return await execution.list_executions(graph_id)
+ @classmethod
async def get_run_execution_results(
- self, graph_id: str, run_id: str
+ cls, graph_id: str, run_id: str
) -> list[execution.ExecutionResult]:
graph = await get_graph(graph_id)
if not graph:
@@ -228,8 +256,9 @@ class AgentServer(AppService):
self.event_queue.put(execution_result)
)
+ @classmethod
def update_configuration(
- self,
+ cls,
updated_settings: Annotated[
Dict[str, Any], Body(examples=[{"config": {"num_workers": 10}}])
],
diff --git a/rnd/autogpt_server/autogpt_server/util/mock.py b/rnd/autogpt_server/autogpt_server/util/mock.py
new file mode 100644
index 0000000000..70befa04b6
--- /dev/null
+++ b/rnd/autogpt_server/autogpt_server/util/mock.py
@@ -0,0 +1,12 @@
+class MockObject:
+ def __init__(self, **kwargs):
+ self.__dict__.update(kwargs)
+
+ def __getattr__(self, name):
+ return self.__dict__.get(name)
+
+ def __call__(self, *args, **kwargs):
+ return self
+
+ def __setattr__(self, name, value):
+ self.__dict__[name] = value
diff --git a/rnd/autogpt_server/test/block/test_block.py b/rnd/autogpt_server/test/block/test_block.py
new file mode 100644
index 0000000000..547dce8d25
--- /dev/null
+++ b/rnd/autogpt_server/test/block/test_block.py
@@ -0,0 +1,54 @@
+import logging
+
+from autogpt_server.data.block import Block, get_blocks
+
+logger = logging.getLogger(__name__)
+log = print
+
+
+def execute_block_test(block: Block):
+ prefix = f"[Test-{block.name}]"
+
+ if not block.test_input or not block.test_output:
+ log(f"{prefix} No test data provided")
+ return
+ if not isinstance(block.test_input, list):
+ block.test_input = [block.test_input]
+ if not isinstance(block.test_output, list):
+ block.test_output = [block.test_output]
+
+ output_index = 0
+ log(f"{prefix} Executing {len(block.test_input)} tests...")
+ prefix = " " * 4 + prefix
+
+ for mock_name, mock_obj in (block.test_mock or {}).items():
+ log(f"{prefix} mocking {mock_name}...")
+ setattr(block, mock_name, mock_obj)
+
+ for input_data in block.test_input:
+ log(f"{prefix} in: {input_data}")
+
+ for output_name, output_data in block.execute(input_data):
+ if output_index >= len(block.test_output):
+ raise ValueError(f"{prefix} produced output more than expected")
+ ex_output_name, ex_output_data = block.test_output[output_index]
+
+ def compare(data, expected_data):
+ if isinstance(expected_data, type):
+ is_matching = isinstance(data, expected_data)
+ else:
+ is_matching = data == expected_data
+
+ mark = "✅" if is_matching else "❌"
+ log(f"{prefix} {mark} comparing `{data}` vs `{expected_data}`")
+ if not is_matching:
+ raise ValueError(f"{prefix}: wrong output {data} vs {expected_data}")
+
+ compare(output_name, ex_output_name)
+ compare(output_data, ex_output_data)
+ output_index += 1
+
+
+def test_available_blocks():
+ for block in get_blocks().values():
+ execute_block_test(type(block)())