Repository navigation
fix: report Graphviz stderr when dot fails to render a diagram #672
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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,52 @@ | ||
| """Run the Graphviz ``dot`` program and report its failures.""" | ||
|
|
||
| import subprocess | ||
|
|
||
| from statemachine.exceptions import StateMachineError | ||
|
|
||
| GRAPHVIZ_DOWNLOAD_URL = "https://graphviz.org/download/" | ||
|
|
||
|
|
||
| class GraphvizError(StateMachineError): | ||
| """Raised when the Graphviz ``dot`` program cannot run or fails to render a graph.""" | ||
|
|
||
|
|
||
| def run_graphviz(dot_source: str, fmt: str, prog: str = "dot") -> bytes: | ||
| """Render ``dot_source`` with Graphviz and return the output bytes. | ||
|
|
||
| Args: | ||
| dot_source: Graph in the DOT language. | ||
| fmt: Graphviz output format, passed as ``-T<fmt>`` (``"svg"``, ``"png"``, ...). | ||
| prog: Graphviz layout program to run, looked up on ``PATH``. | ||
|
|
||
| Raises: | ||
| GraphvizError: If ``prog`` cannot be run or exits with a non-zero code. | ||
| The message carries what Graphviz wrote to stderr. | ||
| """ | ||
| command = [prog, f"-T{fmt}"] | ||
| try: | ||
| completed = subprocess.run( | ||
| command, | ||
| input=dot_source.encode("utf-8"), | ||
| capture_output=True, | ||
| creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), | ||
| ) | ||
| except FileNotFoundError as err: | ||
| raise GraphvizError( | ||
| f"{prog!r} not found in PATH. Install Graphviz from {GRAPHVIZ_DOWNLOAD_URL} " | ||
| "to generate diagrams." | ||
| ) from err | ||
| except OSError as err: | ||
| raise GraphvizError(f"{prog!r} could not be run: {err}") from err | ||
|
|
||
| if completed.returncode != 0: | ||
| if completed.returncode < 0: | ||
| message = f"{' '.join(command)} was terminated by signal {-completed.returncode}." | ||
| else: | ||
| message = f"{' '.join(command)} failed with exit code {completed.returncode}." | ||
| stderr = completed.stderr.decode("utf-8", errors="replace").strip() | ||
| if stderr: | ||
| message = f"{message}\n{stderr}" | ||
| raise GraphvizError(message) | ||
|
|
||
| return completed.stdout |
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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,72 @@ | ||
| """Issue #649: ``run_graphviz`` errors that need no Graphviz installed.""" | ||
|
|
||
| import subprocess | ||
| import sys | ||
|
|
||
| import pytest | ||
| from statemachine.contrib.diagram import main | ||
|
|
||
|
|
||
| class TestGraphvizWithoutDot: | ||
| _QUALNAME = "tests.examples.traffic_light_machine.TrafficLightMachine" | ||
|
|
||
| def test_run_graphviz_without_stderr_output(self, monkeypatch): | ||
| from statemachine.contrib.diagram import GraphvizError | ||
| from statemachine.contrib.diagram.graphviz import run_graphviz | ||
|
|
||
| monkeypatch.setattr( | ||
| "subprocess.run", | ||
| lambda *args, **kwargs: subprocess.CompletedProcess(args, 3, b"", b""), | ||
| ) | ||
|
|
||
| with pytest.raises(GraphvizError, match=r"dot -Tpng failed with exit code 3\.$"): | ||
| run_graphviz("digraph {}", "png") | ||
|
|
||
| def test_run_graphviz_terminated_by_signal(self, monkeypatch): | ||
| from statemachine.contrib.diagram import GraphvizError | ||
| from statemachine.contrib.diagram.graphviz import run_graphviz | ||
|
|
||
| monkeypatch.setattr( | ||
| "subprocess.run", | ||
| lambda *args, **kwargs: subprocess.CompletedProcess(args, -9, b"", b"killed"), | ||
| ) | ||
|
|
||
| with pytest.raises(GraphvizError, match=r"dot -Tsvg was terminated by signal 9\.\nkilled"): | ||
| run_graphviz("digraph {}", "svg") | ||
|
|
||
| def test_run_graphviz_without_dot_in_path(self, monkeypatch, tmp_path): | ||
| from statemachine.contrib.diagram import GraphvizError | ||
| from statemachine.contrib.diagram.graphviz import run_graphviz | ||
|
|
||
| monkeypatch.setenv("PATH", str(tmp_path)) | ||
|
|
||
| with pytest.raises(GraphvizError, match="'dot' not found in PATH") as excinfo: | ||
| run_graphviz("digraph {}", "svg") | ||
|
|
||
| assert "graphviz.org/download" in str(excinfo.value) | ||
| assert isinstance(excinfo.value.__cause__, FileNotFoundError) | ||
|
|
||
| @pytest.mark.skipif(sys.platform == "win32", reason="file mode bits are POSIX only") | ||
| def test_run_graphviz_with_dot_that_cannot_run(self, monkeypatch, tmp_path): | ||
| from statemachine.contrib.diagram import GraphvizError | ||
| from statemachine.contrib.diagram.graphviz import run_graphviz | ||
|
|
||
| (tmp_path / "dot").write_text("") | ||
| monkeypatch.setenv("PATH", str(tmp_path)) | ||
|
|
||
| with pytest.raises(GraphvizError, match="'dot' could not be run: .*Permission denied"): | ||
| run_graphviz("digraph {}", "svg") | ||
|
|
||
| def test_graphviz_error_is_a_statemachine_error(self): | ||
| from statemachine.contrib.diagram import GraphvizError | ||
| from statemachine.exceptions import StateMachineError | ||
|
|
||
| assert issubclass(GraphvizError, StateMachineError) | ||
|
|
||
| def test_write_image_raw_writes_dot_source_without_running_dot(self, tmp_path, monkeypatch): | ||
| monkeypatch.setenv("PATH", str(tmp_path)) | ||
| out = tmp_path / "sm.raw" | ||
|
|
||
| main([self._QUALNAME, str(out)]) | ||
|
|
||
| assert out.read_text(encoding="utf-8").startswith("digraph TrafficLightMachine {") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.