|
| 1 | +import asyncio |
| 2 | + |
| 3 | +from codeboxapi import CodeBox |
| 4 | + |
| 5 | + |
| 6 | +def test_codebox(): |
| 7 | + codebox = CodeBox() |
| 8 | + assert run_sync(codebox), "Failed to run sync codebox remotely" |
| 9 | + assert asyncio.run(run_async(codebox)), "Failed to run async codebox remotely" |
| 10 | + |
| 11 | + |
| 12 | +def test_localbox(): |
| 13 | + codebox = CodeBox(local=True) |
| 14 | + assert run_sync(codebox), "Failed to run sync codebox locally" |
| 15 | + assert asyncio.run(run_async(codebox)), "Failed to run async codebox locally" |
| 16 | + |
| 17 | + |
| 18 | +def run_sync(codebox: CodeBox) -> bool: |
| 19 | + try: |
| 20 | + assert codebox.start() == "started" |
| 21 | + |
| 22 | + assert codebox.status() == "running" |
| 23 | + |
| 24 | + assert codebox.run("print('Hello World!')") == "Hello World!\n" |
| 25 | + |
| 26 | + file_name = "test_file.txt" |
| 27 | + assert file_name in str(codebox.upload(file_name, b"Hello World!")) |
| 28 | + |
| 29 | + assert codebox.download(file_name).content == b"Hello World!" |
| 30 | + |
| 31 | + package_name = "matplotlib" |
| 32 | + assert package_name in str(codebox.install(package_name)) |
| 33 | + assert ( |
| 34 | + "error" |
| 35 | + != codebox.run("import matplotlib; print(matplotlib.__version__)").type |
| 36 | + ) |
| 37 | + |
| 38 | + o = codebox.run( |
| 39 | + "import matplotlib.pyplot as plt;" |
| 40 | + "plt.plot([1, 2, 3, 4], [1, 4, 2, 3]); plt.show()" |
| 41 | + ) |
| 42 | + assert o.type == "image/png" |
| 43 | + |
| 44 | + finally: |
| 45 | + assert codebox.stop() == "stopped" |
| 46 | + |
| 47 | + return True |
| 48 | + |
| 49 | + |
| 50 | +async def run_async(codebox: CodeBox) -> bool: |
| 51 | + try: |
| 52 | + assert await codebox.astart() == "started" |
| 53 | + |
| 54 | + assert await codebox.astatus() == "running" |
| 55 | + |
| 56 | + assert await codebox.arun("print('Hello World!')") == "Hello World!\n" |
| 57 | + |
| 58 | + file_name = "test_file.txt" |
| 59 | + assert file_name in str(await codebox.aupload(file_name, b"Hello World!")) |
| 60 | + |
| 61 | + assert (await codebox.adownload(file_name)).content == b"Hello World!" |
| 62 | + |
| 63 | + package_name = "matplotlib" |
| 64 | + assert package_name in str(await codebox.ainstall(package_name)) |
| 65 | + assert ( |
| 66 | + "error" |
| 67 | + != ( |
| 68 | + await codebox.arun("import matplotlib; print(matplotlib.__version__)") |
| 69 | + ).type |
| 70 | + ) |
| 71 | + |
| 72 | + o = await codebox.arun( |
| 73 | + "import matplotlib.pyplot as plt;" |
| 74 | + "plt.plot([1, 2, 3, 4], [1, 4, 2, 3]); plt.show()" |
| 75 | + ) |
| 76 | + assert o.type == "image/png" |
| 77 | + |
| 78 | + finally: |
| 79 | + assert await codebox.astop() == "stopped" |
| 80 | + |
| 81 | + return True |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + test_codebox() |
| 86 | + test_localbox() |
0 commit comments