Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions deeptutor/agents/visualize/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def extract_code_block(text: str, language: str = "") -> str:

If *language* is given the block must start with that tag;
otherwise any triple-backtick fence is accepted.
A language miss returns ``""`` so callers can fall back with ``or``.
"""
# Closing fence may sit on the same line as the last content line.
if language:
Expand All @@ -46,6 +47,9 @@ def extract_code_block(text: str, language: str = "") -> str:
match = re.search(pattern, text or "", re.IGNORECASE)
if match:
return match.group(1).strip()
# Language miss must be falsy so `hint or any-fence` can fall through.
if language:
return ""
return (text or "").strip()


Expand Down
11 changes: 11 additions & 0 deletions tests/agents/visualize/test_extract_code_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,22 @@


def test_extract_code_block_closing_fence_without_leading_newline() -> None:
"""Extract a closing fence attached to the final content line."""
raw = "```mermaid\ngraph TD\n A-->B```"
assert extract_code_block(raw, "mermaid") == "graph TD\n A-->B"
assert extract_code_block(raw) == "graph TD\n A-->B"


def test_extract_code_block_normal_fenced_block() -> None:
"""Extract a standard fenced block with its requested language."""
raw = "```javascript\nconst x = 1;\n```"
assert extract_code_block(raw, "javascript") == "const x = 1;"


def test_extract_code_block_language_miss_is_empty_for_or_fallback() -> None:
"""Return empty on a language miss so generic extraction can run."""
cfg = '{"type": "bar", "data": {"labels": ["A"], "datasets": [{"data": [1]}]}}'
raw = f"```json\n{cfg}\n```\nThanks."
assert extract_code_block(raw, "javascript") == ""
extracted = extract_code_block(raw, "javascript") or extract_code_block(raw)
assert extracted == cfg
Loading