|
| 1 | +import importlib.metadata |
1 | 2 | import os
|
2 | 3 | import sys
|
3 | 4 | import unittest
|
|
22 | 23 | here = os.path.abspath(os.path.dirname(__file__))
|
23 | 24 |
|
24 | 25 |
|
| 26 | +def is_package_installed(package_name): |
| 27 | + """Check if a package is installed. This is a preferred way to check if a |
| 28 | + package is installed or not than doing a try-catch around an import |
| 29 | + because it avoids name conflict with local modules and |
| 30 | + code execution in the imported module.""" |
| 31 | + try: |
| 32 | + importlib.metadata.version(package_name) |
| 33 | + return True |
| 34 | + except importlib.metadata.PackageNotFoundError: |
| 35 | + return False |
| 36 | + |
| 37 | + |
| 38 | +docker_package_installed = is_package_installed("docker") |
| 39 | + |
| 40 | + |
25 | 41 | # def test_find_code():
|
26 | 42 | # try:
|
27 | 43 | # import openai
|
@@ -293,10 +309,6 @@ def scrape(url):
|
293 | 309 | assert len(codeblocks) == 1 and codeblocks[0] == ("", "source setup.sh")
|
294 | 310 |
|
295 | 311 |
|
296 |
| -@pytest.mark.skipif( |
297 |
| - sys.platform in ["darwin"], |
298 |
| - reason="do not run on MacOS", |
299 |
| -) |
300 | 312 | def test_execute_code(use_docker=None):
|
301 | 313 | try:
|
302 | 314 | import docker
|
@@ -338,15 +350,27 @@ def test_execute_code(use_docker=None):
|
338 | 350 | assert isinstance(image, str) or docker is None or os.path.exists("/.dockerenv") or use_docker is False
|
339 | 351 |
|
340 | 352 |
|
| 353 | +@pytest.mark.skipif(docker_package_installed is False, reason="docker package not installed") |
| 354 | +def test_execute_code_with_custom_filename_on_docker(): |
| 355 | + exit_code, msg, image = execute_code("print('hello world')", filename="tmp/codetest.py", use_docker=True) |
| 356 | + assert exit_code == 0 and msg == "hello world\n", msg |
| 357 | + assert image == "python:tmp_codetest.py" |
| 358 | + |
| 359 | + |
| 360 | +@pytest.mark.skipif(docker_package_installed is False, reason="docker package not installed") |
| 361 | +def test_execute_code_with_misformed_filename_on_docker(): |
| 362 | + exit_code, msg, image = execute_code( |
| 363 | + "print('hello world')", filename="tmp/codetest.py (some extra information)", use_docker=True |
| 364 | + ) |
| 365 | + assert exit_code == 0 and msg == "hello world\n", msg |
| 366 | + assert image == "python:tmp_codetest.py__some_extra_information_" |
| 367 | + |
| 368 | + |
341 | 369 | def test_execute_code_raises_when_code_and_filename_are_both_none():
|
342 | 370 | with pytest.raises(AssertionError):
|
343 | 371 | execute_code(code=None, filename=None)
|
344 | 372 |
|
345 | 373 |
|
346 |
| -@pytest.mark.skipif( |
347 |
| - sys.platform in ["darwin"], |
348 |
| - reason="do not run on MacOS", |
349 |
| -) |
350 | 374 | def test_execute_code_nodocker():
|
351 | 375 | test_execute_code(use_docker=False)
|
352 | 376 |
|
|
0 commit comments