-
-
Notifications
You must be signed in to change notification settings - Fork 106
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a new TestCase that asserts that examples exit successfully.
- Loading branch information
Showing
1 changed file
with
75 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,75 @@ | ||
""" | ||
build123d Example tests | ||
name: test_examples.py | ||
by: fischman | ||
date: February 21 2025 | ||
desc: Unit tests for the build123d examples, ensuring they don't raise. | ||
""" | ||
|
||
from pathlib import Path | ||
|
||
import os | ||
import subprocess | ||
import sys | ||
import tempfile | ||
import unittest | ||
|
||
|
||
_examples_dir = Path(os.path.abspath(os.path.dirname(__file__))).parent / "examples" | ||
|
||
_MOCK_OCP_VSCODE_CONTENTS = """ | ||
import sys | ||
from unittest.mock import Mock | ||
mock_module = Mock() | ||
mock_module.show = Mock() | ||
mock_module.show_object = Mock() | ||
mock_module.show_all = Mock() | ||
sys.modules["ocp_vscode"] = mock_module | ||
""" | ||
|
||
|
||
def generate_example_test(path: Path): | ||
"""Generate and return a function to test the example at `path`.""" | ||
name = path.name | ||
|
||
def assert_example_does_not_raise(self): | ||
with tempfile.TemporaryDirectory( | ||
prefix=f"build123d_test_examples_{name}" | ||
) as tmpdir: | ||
mock_ocp_vscode = Path(tmpdir) / "_mock_ocp_vscode.py" | ||
with open(mock_ocp_vscode, "w", encoding="utf-8") as f: | ||
f.write(_MOCK_OCP_VSCODE_CONTENTS) | ||
got = subprocess.run( | ||
[ | ||
sys.executable, | ||
"-c", | ||
f"exec(open('{mock_ocp_vscode}').read()); exec(open('{path}').read())", | ||
], | ||
capture_output=True, | ||
cwd=tmpdir, | ||
check=False, | ||
) | ||
self.assertEqual( | ||
0, got.returncode, f"stdout/stderr: {got.stdout} / {got.stderr}" | ||
) | ||
|
||
return assert_example_does_not_raise | ||
|
||
|
||
class TestExamples(unittest.TestCase): | ||
"""Tests build123d examples.""" | ||
|
||
|
||
for example in sorted(_examples_dir.iterdir()): | ||
if example.name.startswith("_"): | ||
continue | ||
setattr( | ||
TestExamples, | ||
f"test_{example.name.replace('.', '_')}", | ||
generate_example_test(example), | ||
) | ||
|
||
if __name__ == "__main__": | ||
unittest.main() |