|
| 1 | +import glob |
| 2 | +import subprocess |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import pytest |
| 7 | + |
| 8 | + |
| 9 | +def no_op(*args, **kwargs): |
| 10 | + """A no-operation function to replace plt.show during tests.""" |
| 11 | + pass |
| 12 | + |
| 13 | + |
| 14 | +example_scripts = glob.glob("docs/examples/ch*/solutions/diffpy-cmi/*.py") |
| 15 | + |
| 16 | + |
| 17 | +@pytest.mark.parametrize("script_path", example_scripts) |
| 18 | +def test_script_execution(monkeypatch, script_path): |
| 19 | + """Test execution of each example script while suppressing plot |
| 20 | + display.""" |
| 21 | + monkeypatch.setattr(plt, "show", no_op) |
| 22 | + # Special handling for fitNPPt.py which depends on fitBulkNi.py |
| 23 | + if script_path.endswith("fitNPPt.py"): |
| 24 | + ni_script = script_path.replace("fitNPPt.py", "fitBulkNi.py") |
| 25 | + ni_script_path = Path(ni_script) |
| 26 | + if not ni_script_path.exists(): |
| 27 | + pytest.fail( |
| 28 | + f"Required script {ni_script} not found for {script_path}" |
| 29 | + ) |
| 30 | + # Run Ni calibration first |
| 31 | + result_ni = subprocess.run( |
| 32 | + ["python", str(ni_script_path)], |
| 33 | + stdout=subprocess.PIPE, |
| 34 | + stderr=subprocess.PIPE, |
| 35 | + text=True, |
| 36 | + ) |
| 37 | + if result_ni.returncode != 0: |
| 38 | + pytest.fail( |
| 39 | + f"Calibration script {ni_script}", |
| 40 | + " failed with error:\n{result_ni.stderr}", |
| 41 | + ) |
| 42 | + # Run rest of the scripts |
| 43 | + result = subprocess.run( |
| 44 | + ["python", script_path], |
| 45 | + stdout=subprocess.PIPE, |
| 46 | + stderr=subprocess.PIPE, |
| 47 | + text=True, |
| 48 | + ) |
| 49 | + |
| 50 | + assert ( |
| 51 | + result.returncode == 0 |
| 52 | + ), f"Script {script_path} failed with error:\n{result.stderr}" |
0 commit comments