Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
abidlabs committed Feb 26, 2025
1 parent 8927c96 commit 0e95a08
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
20 changes: 19 additions & 1 deletion groovy/transpiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,10 +508,28 @@ def get_expr_type(self, node: ast.AST) -> type | None:
return None


def transpile(fn: Callable) -> str:
def transpile(fn: Callable, validate: bool = False) -> str:
"""
Transpiles a Python function to JavaScript and returns the JavaScript code as a string.
Parameters:
fn: The Python function to transpile.
validate: If True, the function will be validated to ensure it takes no arguments & only returns gradio component property updates.
Returns:
The JavaScript code as a string.
Raises:
TranspilerError: If the function cannot be transpiled or if the transpiled function is not valid.
"""
if validate:
sig = inspect.signature(fn)
if sig.parameters:
param_names = list(sig.parameters.keys())
raise TranspilerError(
message=f"Function must take no arguments, but got: {param_names}"
)

try:
source = inspect.getsource(fn)
source = textwrap.dedent(source)
Expand Down
23 changes: 23 additions & 0 deletions tests/test_transpiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,26 @@ def filter_rows_by_term(data: list, search_term: str) -> list:
return data.filter(row => row[0].includes(search_term));
}"""
assert transpile(filter_rows_by_term).strip() == expected.strip()


def test_validate_no_arguments():
def no_args_function():
return gradio.Textbox(value="This is valid")

# This should pass validation
result = transpile(no_args_function, validate=True)
expected = """function no_args_function() {
return {"value": "This is valid", "__type__": "update"};
}"""
assert result.strip() == expected.strip()


def test_validate_with_arguments():
def function_with_args(text_input):
return gradio.Textbox(value=f"You entered: {text_input}")

# This should fail validation
with pytest.raises(TranspilerError) as e:
transpile(function_with_args, validate=True)

assert "text_input" in str(e.value)

0 comments on commit 0e95a08

Please sign in to comment.