-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
test: add tests for component python code
- Loading branch information
the-dipsy
committed
Feb 25, 2024
1 parent
18aeade
commit 6b0d2d5
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
from unittest import TestCase | ||
from pyromaniac.compiler.code.errors import ( | ||
PythonSyntaxError, PythonRuntimeError | ||
) | ||
from pyromaniac.compiler.code.python import Python | ||
|
||
|
||
def execute( | ||
code: str, context: dict | None = None, pure: bool = False, | ||
) -> dict: | ||
context = context or {} | ||
Python.create(code, pure).execute(context) | ||
return context | ||
|
||
|
||
class TestPython(TestCase): | ||
def test_empty(self): | ||
self.assertEqual(execute(""), {}) | ||
|
||
def test_function(self): | ||
code = "def foo(): return 42\nnum = foo()" | ||
self.assertEqual(execute(code)["num"], 42) | ||
|
||
def test_pure(self): | ||
ctx = {"a": 42, "b": 69} | ||
self.assertEqual(execute("a + b", ctx, True)["result"], 42 + 69) | ||
|
||
def test_syntax_error(self): | ||
self.assertRaisesPythonSyntax("if for: true") | ||
|
||
def test_invalid_pure(self): | ||
self.assertRaisesPythonSyntax("", True) | ||
self.assertRaisesPythonSyntax("if True: 'hello'", True) | ||
self.assertRaisesPythonSyntax("num = 42", True) | ||
|
||
def test_runtime_error(self): | ||
self.assertRaisesPythonRuntime("42 + '69'") | ||
self.assertRaisesPythonRuntime("raise ValueError()") | ||
|
||
def test_error_pass_through(self): | ||
rte = PythonRuntimeError() | ||
raised = self.assertRaisesPythonRuntime("raise e", {"e": rte}) | ||
self.assertIs(rte, raised) | ||
|
||
def assertRaisesPythonSyntax(self, code: str, pure: bool = False): | ||
with self.assertRaises(PythonSyntaxError): | ||
Python.create(code, pure) | ||
|
||
def assertRaisesPythonRuntime( | ||
self, code: str, context: dict = None, pure: bool = False | ||
) -> Exception: | ||
with self.assertRaises(PythonRuntimeError) as e: | ||
execute(code, context, pure) | ||
return e.exception |