Files
fiona-assistant/tests/test_graph_generator.py
T
2026-09-30 13:37:01 +02:00

1694 lines
69 KiB
Python

"""Tests for wiki graph_generator module.
Test cases for MarkdownLinkParser, WikiGraph, and HTMLGraphRenderer classes.
"""
import json
import os
import fiona.wiki.graph_generator as wiki_graph
from fiona.wiki.graph_generator import (
HTMLGraphRenderer,
MarkdownLinkParser,
WikiGraph,
load_constellation_themes,
load_graph_settings,
resolve_theme,
wiki_graph_main,
)
def _html_nodes(html: str) -> list[dict]:
"""Return the node list embedded in generated graph HTML.
Generated by AI/LLM: 2026-09-29 - read nodeData from the page script.
"""
marker = "const nodeData = "
start = html.index(marker) + len(marker)
end = html.index(";", start)
nodes = json.loads(html[start:end])
assert isinstance(nodes, list)
return nodes
class TestLoadGraphSettings:
"""Tests for load_graph_settings function."""
def test_load_graph_settings_not_found(self):
"""A missing file still uses the packaged graph section.
Generated by AI/LLM: 2026-09-29 - repo-root graph reads the shipped file.
"""
settings = load_graph_settings("/nonexistent/path")
assert settings["show_legend"] is True
assert settings["show_arrows"] is False
assert settings["show_glow"] is True
assert settings["show_link_card"] is True
assert settings["first_fit_ms"] == 12000
assert settings["hover_link_tail_chars"] == 12
assert settings["simplify_external_links"] is True
def test_load_graph_settings_found(self, tmp_path):
"""Test loading settings when file exists."""
settings_dir = tmp_path / "subdir"
settings_dir.mkdir()
settings_file = settings_dir / "fiona-settings.json"
settings_file.write_text(json.dumps({
"fiona": {
"wiki": {
"graph": {
"wikilinks_enabled": False,
"external_links": True,
"max_files": 100
}
}
}
}))
settings = load_graph_settings(str(settings_dir))
assert settings["wikilinks_enabled"] is False
assert settings["external_links"] is True
assert settings["max_files"] == 100
assert settings["show_arrows"] is False
def test_load_graph_settings_invalid_json(self, tmp_path):
"""Test loading settings with invalid JSON."""
settings_file = tmp_path / "fiona-settings.json"
settings_file.write_text("invalid json")
settings = load_graph_settings(str(tmp_path))
assert settings["show_arrows"] is False
assert "wikilinks_enabled" not in settings
def test_load_graph_settings_parent_directory(self, tmp_path):
"""Test loading settings from parent directory."""
subdir = tmp_path / "subdir"
subdir.mkdir()
settings_file = tmp_path / "fiona-settings.json"
settings_file.write_text(json.dumps({
"fiona": {
"wiki": {
"graph": {
"test_key": "test_value"
}
}
}
}))
settings = load_graph_settings(str(subdir))
assert settings["test_key"] == "test_value"
assert settings["show_legend"] is True
class TestConstellationThemes:
"""Themes in constellation-settings.json."""
def test_missing_theme_key_comes_from_default(self):
"""A partial theme keeps unspecified keys from the default theme.
Generated by AI/LLM: 2026-09-29 - theme fallback contract.
"""
filled = resolve_theme(
{"text_color": "#ffffff"},
{"text_color": "#000000", "font_family": "Arial, sans-serif"},
)
assert filled["text_color"] == "#ffffff"
assert filled["font_family"] == "Arial, sans-serif"
def test_packaged_themes_cover_colorful_night_sky_and_grayscale(self):
"""The packaged catalog has a complete colorful theme and the others.
Generated by AI/LLM: 2026-09-29 - colorful, night-sky, and grayscale.
Modified by AI/LLM: 2026-09-30 - grayscale dark mid and high node colors.
"""
themes = load_constellation_themes()
assert "default" not in themes
assert themes["colorful"]["node_colors"]["low"] == "#8f8272"
assert themes["colorful"]["node_colors"]["mid"] == "#e0943a"
assert themes["colorful"]["node_colors"]["high"] == "#c23b4a"
assert themes["colorful"]["edge_colors"]["mid"] == "#b86a1a"
assert themes["colorful"]["highlight"]["node_color"] == "#2aa7a1"
assert themes["colorful"]["buttons"]["background"] == "#0f6e78"
assert themes["colorful"]["node_radius"]["max"] == 40
assert themes["colorful"]["shapes"]["page"] == "circle"
assert themes["colorful"]["shapes"]["external"] == "cloud"
assert themes["colorful"]["edge_width"] == 1
assert themes["night-sky"]["edge_width"] == 1
assert themes["night-sky"]["shapes"]["page"] == "circle"
assert themes["night-sky"]["shapes"]["external"] == "star"
assert themes["night-sky"]["background"] == "#070b14"
assert themes["night-sky"]["node_radius"]["min"] == 3
assert themes["night-sky"]["node_radius"]["max"] == 20
assert themes["grayscale"]["node_colors"]["low"] == "#5a5a5a"
assert themes["grayscale"]["node_colors"]["high"] == "#0d0d0d"
assert themes["grayscale"]["node_stroke"] == "#141414"
assert themes["grayscale"]["font_family"] == themes["colorful"]["font_family"]
assert themes["grayscale"]["shapes"]["page"] == "circle"
assert themes["grayscale"]["shapes"]["external"] == "cloud"
assert themes["grayscale"]["node_radius"]["min"] == 5
assert themes["grayscale"]["highlight"]["size_multiplier"] == 1.4
assert themes["grayscale"]["dark"]["background"] == "#2c2c2c"
assert themes["grayscale"]["dark"]["node_colors"]["low"] == "#8d8d8d"
assert themes["grayscale"]["dark"]["node_colors"]["mid"] == "#fff4c4"
assert themes["grayscale"]["dark"]["node_colors"]["high"] == "#f5b44a"
assert themes["grayscale"]["dark"]["font_family"] == "Arial, sans-serif"
assert themes["grayscale"]["dark"]["shapes"]["external"] == "cloud"
assert themes["grayscale"]["dark"]["edge_width"] == 1
def test_dark_theme_is_a_blue_slate_night(self):
"""The dark theme is a blue-slate night, not a black field.
Generated by AI/LLM: 2026-09-29 - dark theme beside grayscale.
Modified by AI/LLM: 2026-09-30 - night slate instead of black.
"""
themes = load_constellation_themes()
dark = themes["dark"]
assert dark["background"] == "#1e2836"
assert dark["graph_background"] == "#283448"
assert dark["text_color"] == "#e7eef8"
assert dark["node_colors"]["low"] == "#7d8da3"
assert dark["node_colors"]["high"] == "#f7fbff"
assert dark["edge_colors"]["low"] == "#51627a"
assert dark["edge_colors"]["high"] == "#d5e2f2"
assert dark["node_stroke"] == "none"
assert dark["font_family"] == "Segoe UI, sans-serif"
assert dark["node_radius"]["max"] == 24
assert dark["highlight"]["size_multiplier"] == 1.45
assert dark["shapes"]["page"] == "circle"
assert dark["shapes"]["external"] == "cloud"
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "#7d8da3" in html
def test_professional_theme_is_a_boardroom_palette(self):
"""The professional theme is a light boardroom palette.
Generated by AI/LLM: 2026-09-29 - corporate theme for the graph.
Modified by AI/LLM: 2026-09-30 - lighter blue instead of navy.
"""
themes = load_constellation_themes()
theme = themes["professional"]
assert theme["background"] == "#f7fafc"
assert theme["graph_background"] == "#fcfdfe"
assert theme["text_color"] == "#4a5d70"
assert theme["node_colors"]["low"] == "#e4eef4"
assert theme["node_colors"]["mid"] == "#a9c6d8"
assert theme["node_colors"]["high"] == "#7eabc4"
assert theme["node_stroke"] == "#9bb8cb"
assert theme["edge_colors"]["low"] == "#e7f0f5"
assert theme["edge_colors"]["high"] == "#8eb4c9"
assert theme["edge_width"] == 1
assert theme["buttons"]["background"] == "#8eb4c9"
assert theme["buttons"]["text"] == "#ffffff"
assert theme["shapes"]["page"] == "circle"
assert theme["shapes"]["external"] == "cloud"
assert theme["node_radius"]["max"] == 26
assert "Calibri" in theme["font_family"]
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "#7eabc4" in html
assert "function edgeWidth" in html
assert "theme.edge_width" in html
def test_local_constellation_file_overrides_a_theme(self, tmp_path):
"""A wiki file can personalize one theme key.
Generated by AI/LLM: 2026-09-29 - local constellation settings win.
"""
(tmp_path / "constellation-settings.json").write_text(
json.dumps({"themes": {"night-sky": {"background": "#111111"}}}),
encoding="utf-8",
)
themes = load_constellation_themes(str(tmp_path))
assert themes["night-sky"]["background"] == "#111111"
assert themes["night-sky"]["shapes"]["page"] == "circle"
assert themes["night-sky"]["shapes"]["external"] == "star"
def test_node_radius_keeps_a_fraction(self, tmp_path):
"""A fractional min and max stay fractional and drive the drawing.
Generated by AI/LLM: 2026-09-29 - node radius is a float.
"""
(tmp_path / "constellation-settings.json").write_text(
json.dumps({
"themes": {
"night-sky": {"node_radius": {"min": 3.25, "max": 20.5}},
},
}),
encoding="utf-8",
)
themes = load_constellation_themes(str(tmp_path))
assert themes["night-sky"]["node_radius"]["min"] == 3.25
assert themes["night-sky"]["node_radius"]["max"] == 20.5
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "function radiusLimit" in html
assert "radiusLimit('min'" in html
assert "radiusLimit('max'" in html
def test_html_offers_a_theme_select(self):
"""The graph page lists the packaged themes.
Generated by AI/LLM: 2026-09-29 - theme control in the graph HTML.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert 'id="theme-select"' in html
assert "colorful" in html
assert "night-sky" in html
assert "grayscale" in html
assert '"dark"' in html
assert "professional" in html
assert 'pickTheme("night-sky")' in html
assert "function resolveTheme" in html
assert "function starPath" in html
assert "theme.clicked.node_color" in html
def test_graph_opens_on_the_configured_theme(self):
"""The theme setting chooses the theme the page opens on.
Generated by AI/LLM: 2026-09-29 - night-sky is the opening theme.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
colorful = HTMLGraphRenderer(graph, {"theme": "colorful"}).generate_html()
assert 'pickTheme("colorful")' in colorful
unknown = HTMLGraphRenderer(graph, {"theme": "nope"}).generate_html()
assert 'pickTheme("night-sky")' in unknown
class TestMarkdownLinkParser:
"""Tests for MarkdownLinkParser class."""
def test_parse_standard_markdown_links(self):
"""Test parsing standard markdown links: [text](path/to/file.md)."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = "This is a link to [file1](wiki/concepts/file1.md)."
links = parser._extract_links_from_content(content)
assert len(links) == 1
assert links[0] == "wiki/concepts/file1.md"
def test_parse_multiple_standard_links(self):
"""Test parsing multiple standard markdown links."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = """
Link to [file1](wiki/concepts/file1.md) and [file2](wiki/concepts/file2.md).
Also [file3](wiki/other/file3.md).
"""
links = parser._extract_links_from_content(content)
assert len(links) == 3
assert "wiki/concepts/file1.md" in links
assert "wiki/concepts/file2.md" in links
assert "wiki/other/file3.md" in links
def test_parse_relative_paths(self):
"""Test parsing relative paths: ./file.md, ../dir/file.md."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = """
Relative: [file1](./file1.md) and [file2](../dir/file2.md).
"""
links = parser._extract_links_from_content(content)
assert len(links) == 2
assert "./file1.md" in links
assert "../dir/file2.md" in links
def test_parse_absolute_paths(self):
"""Test parsing absolute paths within wiki root."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = "Absolute: [file1](/path/to/wiki/file1.md)."
links = parser._extract_links_from_content(content)
assert len(links) == 1
assert "/path/to/wiki/file1.md" in links
def test_parse_wikilinks_enabled(self):
"""Test parsing wikilinks format: [[file]], [[dir/file]]."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki", wikilinks_enabled=True)
content = "Wikilinks: [[file1]] and [[dir/file2]]."
links = parser._extract_links_from_content(content)
assert len(links) == 2
assert "file1" in links
assert "dir/file2" in links
def test_parse_wikilinks_disabled(self):
"""Test that wikilinks are not parsed when disabled."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki", wikilinks_enabled=False)
content = "Wikilinks: [[file1]] and [[dir/file2]]."
links = parser._extract_links_from_content(content)
assert len(links) == 0
def test_resolve_link_paths(self):
"""Test resolving link paths to absolute paths."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
# Test relative path resolution with ./ (source in /path/to/wiki/dir/)
resolved = parser._resolve_link_path("./file.md", "/path/to/wiki/dir/source.md")
assert resolved == "/path/to/wiki/dir/file.md"
# Test parent path resolution (go up from /path/to/wiki/dir/ to /path/to/wiki/)
resolved = parser._resolve_link_path("../file.md", "/path/to/wiki/dir/source.md")
assert resolved == "/path/to/wiki/file.md"
# Test absolute path within wiki root
resolved = parser._resolve_link_path("/path/to/wiki/file.md", "/path/to/wiki/dir/source.md")
assert resolved == "/path/to/wiki/file.md"
# Test path without ./ or ../ (resolved relative to source directory)
resolved = parser._resolve_link_path("concepts/file.md", "/path/to/wiki/dir/source.md")
assert resolved == "/path/to/wiki/dir/concepts/file.md"
def test_parse_file(self):
"""Test parsing a complete markdown file."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = """
# Title
This links to [file1](concepts/file1.md) and [[file2]].
Also [relative](./local.md) and [absolute](/path/to/wiki/abs.md).
"""
links = parser.parse_content(content, "/path/to/wiki/source.md")
assert len(links) == 4
# concepts/file1.md is resolved relative to source directory (/path/to/wiki/)
assert "/path/to/wiki/concepts/file1.md" in links
# [[file2]] becomes file2.md (wikilink with extension added)
assert "/path/to/wiki/file2.md" in links
# ./local.md is resolved relative to source directory
assert "/path/to/wiki/local.md" in links
# Absolute path
assert "/path/to/wiki/abs.md" in links
def test_identify_external_links(self):
"""Test that external URLs are identified and filtered out."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = """
External: [Google](https://www.google.com) and [GitHub](http://github.com).
Also [FTP](ftp://example.com/file.zip).
"""
# Internal links should be empty
links = parser._extract_links_from_content(content)
assert len(links) == 0
def test_parse_mixed_internal_and_external_links(self):
"""Test parsing file with both internal and external links."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = """
Internal: [file1](wiki/file1.md) and external: [Google](https://www.google.com).
Also [file2](wiki/file2.md) and [GitHub](http://github.com).
"""
links = parser._extract_links_from_content(content)
# Should only get internal links
assert len(links) == 2
assert "wiki/file1.md" in links
assert "wiki/file2.md" in links
def test_track_external_links_per_file(self):
"""Test tracking external links count per file."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = """
Internal: [file1](wiki/file1.md).
External: [Google](https://www.google.com) and [GitHub](http://github.com).
More external: [Docs](https://docs.example.com).
Another internal: [file2](wiki/file2.md).
"""
# Parse with tracking enabled
internal_links, external_links = parser.parse_content_with_external(content, "/path/to/wiki/source.md")
assert len(internal_links) == 2
assert len(external_links) == 3
# Internal links are resolved to absolute paths relative to source file
assert "/path/to/wiki/wiki/file1.md" in internal_links
assert "/path/to/wiki/wiki/file2.md" in internal_links
assert "https://www.google.com" in external_links
assert "http://github.com" in external_links
assert "https://docs.example.com" in external_links
def test_extract_links_with_fragment(self):
"""Test that links with fragments are filtered out."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
content = "Link with [fragment](file.md#section)."
links = parser._extract_links_from_content(content)
assert len(links) == 0
def test_extract_wikilinks_with_fragment(self):
"""Test that wikilinks with fragments are filtered out (line 112)."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki", wikilinks_enabled=True)
content = "Wikilink with [[file#section]]."
links = parser._extract_links_from_content(content)
assert len(links) == 0
def test_extract_wikilinks_with_external_url(self):
"""Test that wikilinks with external URLs are filtered out."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki", wikilinks_enabled=True)
content = "External wikilink: [[https://example.com]]."
links = parser._extract_links_from_content(content)
assert len(links) == 0
def test_is_external_or_fragment_with_fragment(self):
"""Test fragment detection in _is_external_or_fragment (line 128)."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
assert parser._is_external_or_fragment("file.md#section") == True
assert parser._is_external_or_fragment("#section") == True
assert parser._is_external_or_fragment("file.md") == False
def test_is_valid_markdown_link(self):
"""Test _is_valid_markdown_link method (line 169)."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki")
# Valid markdown links
assert parser._is_valid_markdown_link("file.md") == True
assert parser._is_valid_markdown_link("path/to/file.md") == True
assert parser._is_valid_markdown_link("file") == True
# Invalid links
assert parser._is_valid_markdown_link("https://example.com") == False
assert parser._is_valid_markdown_link("file.md#section") == False
def test_parse_file_nonexistent(self, tmp_path):
"""Test parse_file with non-existent file (lines 286-288)."""
parser = MarkdownLinkParser(wiki_root=str(tmp_path))
links = parser.parse_file("/nonexistent/file.md")
assert links == []
def test_parse_file_with_external_nonexistent(self, tmp_path):
"""Test parse_file_with_external with non-existent file (lines 303-305)."""
parser = MarkdownLinkParser(wiki_root=str(tmp_path))
internal, external = parser.parse_file_with_external("/nonexistent/file.md")
assert internal == []
assert external == []
def test_parse_content_with_external_wikilink_external_url(self):
"""Test parse_content_with_external with external URL wikilinks (lines 263-269)."""
parser = MarkdownLinkParser(wiki_root="/path/to/wiki", wikilinks_enabled=True)
content = "Wikilink: [[https://example.com]] and normal wikilink: [[file1]]."
internal, external = parser.parse_content_with_external(content, "/path/to/wiki/source.md")
assert len(external) == 1
assert "https://example.com" in external
# Internal wikilink should be resolved
assert len(internal) == 1
assert "/path/to/wiki/file1.md" in internal
class TestWikiGraph:
"""Tests for WikiGraph class."""
def test_add_node(self):
"""Test adding nodes to the graph."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
assert len(graph.nodes) == 2
assert "wiki/file1.md" in graph.nodes
assert "wiki/file2.md" in graph.nodes
def test_add_edge(self):
"""Test adding edges between nodes."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
assert len(graph.edges) == 1
assert ("wiki/file1.md", "wiki/file2.md") in graph.edges
def test_add_edge_increases_weight(self):
"""Test that adding the same edge multiple times increases weight."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
assert graph.edges[("wiki/file1.md", "wiki/file2.md")] == 2
def test_get_in_degree(self):
"""Test getting in-degree of a node."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_node("wiki/file3.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
graph.add_edge("wiki/file3.md", "wiki/file2.md")
assert graph.get_in_degree("wiki/file2.md") == 2
assert graph.get_in_degree("wiki/file1.md") == 0
def test_repeated_links_score_below_two_unique_sources(self):
"""Ten copies from one file score below two files that link once.
Generated by AI/LLM: 2026-09-29 - size uses unique sources.
"""
crowded = WikiGraph()
for _ in range(10):
crowded.add_edge("wiki/only.md", "wiki/target.md")
assert crowded.get_unique_points("wiki/target.md") == 1
assert crowded.get_total_points("wiki/target.md") == 10
assert crowded.get_link_score("wiki/target.md") < 2
pair = WikiGraph()
pair.add_edge("wiki/a.md", "wiki/target.md")
pair.add_edge("wiki/b.md", "wiki/target.md")
assert pair.get_unique_points("wiki/target.md") == 2
assert pair.get_total_points("wiki/target.md") == 2
assert pair.get_link_score("wiki/target.md") == 2
assert pair.get_link_score("wiki/target.md") > crowded.get_link_score(
"wiki/target.md"
)
def test_get_out_degree(self):
"""Test getting out-degree of a node."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_node("wiki/file3.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file3.md")
assert graph.get_out_degree("wiki/file1.md") == 2
assert graph.get_out_degree("wiki/file2.md") == 0
def test_identify_orphans(self):
"""Test identifying orphan files (no incoming or outgoing links)."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_node("wiki/file3.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
orphans = graph.get_orphans()
assert len(orphans) == 1
assert "wiki/file3.md" in orphans
def test_build_from_files(self):
"""Test building graph from file links."""
graph = WikiGraph()
file_links = {
"wiki/file1.md": ["wiki/file2.md", "wiki/file3.md"],
"wiki/file2.md": ["wiki/file3.md"],
"wiki/file3.md": []
}
graph.build_from_files(file_links)
assert len(graph.nodes) == 3
assert len(graph.edges) == 3
assert graph.get_in_degree("wiki/file3.md") == 2
def test_add_external_link(self):
"""Test adding external links to the graph."""
graph = WikiGraph()
graph.add_external_link("wiki/file1.md", "https://example.com")
graph.add_external_link("wiki/file1.md", "https://another.com")
graph.add_external_link("wiki/file2.md", "https://third.com")
assert graph.get_external_links_count() == 3
assert len(graph.get_all_external_links()) == 3
external_per_file = graph.get_external_links_per_file()
assert external_per_file["wiki/file1.md"] == 2
assert external_per_file["wiki/file2.md"] == 1
def test_build_from_files_with_external(self):
"""Test building graph with external links."""
graph = WikiGraph()
file_links = {
"wiki/file1.md": ["wiki/file2.md"],
"wiki/file2.md": []
}
external_links = {
"wiki/file1.md": ["https://example.com", "https://another.com"],
"wiki/file2.md": ["https://third.com"]
}
graph.build_from_files_with_external(file_links, external_links)
assert len(graph.nodes) == 2
assert len(graph.edges) == 1
assert graph.get_external_links_count() == 3
assert len(graph.get_all_external_links()) == 3
class TestHTMLGraphRenderer:
"""Tests for HTMLGraphRenderer class."""
def test_generate_html_basic(self):
"""Test generating basic HTML with graph data."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
assert "<!DOCTYPE html>" in html
assert "wiki/file1.md" in html
assert "wiki/file2.md" in html
def test_generate_html_includes_d3js(self):
"""Test that generated HTML includes D3.js library."""
graph = WikiGraph()
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
assert "d3.js" in html or "https://d3js.org" in html
def test_generate_html_has_valid_javascript(self):
"""Test that generated HTML contains valid JavaScript method chains.
This catches errors like calling .numIterations() on the wrong object,
which would cause 'is not a function' errors in the browser.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
# Check for valid D3 force simulation method chains
# The simulation should have .alphaDecay(), .alphaMin(), .velocityDecay()
assert ".alphaDecay(" in html
assert ".alphaMin(" in html
assert ".velocityDecay(" in html
# Check for valid force configurations
assert "forceSimulation" in html
assert "forceLink" in html
assert "forceManyBody" in html
assert "forceCenter" in html
assert "forceCollide" in html
# Check that forces are properly chained with .id(), .distance(), etc.
assert ".id(" in html
assert ".distance(" in html
assert ".strength(" in html
def test_generate_html_keeps_nodes_centered_with_gravity(self):
"""The graph uses center gravity and does not pin nodes to the edge.
Generated by AI/LLM: 2026-09-29 - center gravity contract for the
wiki graph layout.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
assert "const CENTER_STRENGTH = 1;" in html
assert "const GRAVITY_STRENGTH = 0.05;" in html
assert "const EDGE_PADDING_MULTIPLIER = 0;" in html
assert "const HITBOX_SCALE = 1.25;" in html
assert "function hitboxRadius" in html
assert "function separateOverlaps" in html
assert "const SEPARATE_PASSES = 20;" in html
assert "const COLLIDE_STRENGTH = 1;" in html
assert "function forceCanvasMargin" in html
assert "const CANVAS_MARGIN = 56;" in html
assert "const FLOAT_AMPLITUDE = 2;" in html
assert "requestAnimationFrame(floatLoop)" in html
assert "function floatOffset" in html
assert "forceX(" in html
assert "forceY(" in html
assert "d3.zoom(" in html
assert "d.x = Math.max(20" not in html
def test_graph_script_is_pasted_from_graph_physics_js(self):
"""The page script is graph_physics.js, pasted into the HTML.
Generated by AI/LLM: 2026-09-30 - keep the script in its own file.
"""
template_dir = os.path.join(os.path.dirname(wiki_graph.__file__), "templates")
script = os.path.join(template_dir, "graph_physics.js")
template = os.path.join(template_dir, "graph_template.html")
with open(script, encoding="utf-8") as script_file:
script_text = script_file.read()
with open(template, encoding="utf-8") as template_file:
template_text = template_file.read()
assert "function frameNodes" in script_text
assert "{{graph_physics_js}}" in template_text
assert "function frameNodes" not in template_text
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "function frameNodes" in html
assert "{{graph_physics_js}}" not in html
assert "const LINK_STRENGTH = 0.4;" in html
def test_generate_html_frames_shown_nodes_on_load(self):
"""See all fits on the first node and again on the last.
Modified by AI/LLM: 2026-09-30 - a second fit keeps the zoom moving.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "function frameNodes" in html
assert "const FIT_PADDING = 64;" in html
assert "const FIT_MS = 4200;" in html
assert "const FIRST_FIT_MS = 12000;" in html
assert "if (idx === 0) frameNodes(FIRST_FIT_MS);" in html
assert "else if (idx === animQueue.length - 1) frameNodes();" in html
assert "const omega = 6 / (frameMs / 1000);" in html
assert 'id="fit-button"' in html
assert "See all" in html
assert "d3.zoomIdentity" in html
assert "zoom.transform" in html
assert "Math.min(scale, 6)" in html
assert "scaleExtent" in html
assert "if (idx === 0 || idx === animQueue.length - 1) frameNodes();" not in html
assert "function followFrame" in html
assert "if (frameRaf) return;" in html
assert "frameNodes(false)" not in html
assert "frameZooming" not in html
assert "FIT_BLEND" not in html
assert "tick.frame" not in html
theme_change = html.split("themeSelect.addEventListener('change'", 1)[1].split(
"applyTheme(", 1
)[1]
assert theme_change.startswith("this.value);\n")
assert "frameNodes()" in theme_change.split("addEventListener", 1)[0]
dark_mode = html.split(
"matchMedia('(prefers-color-scheme: dark)').addEventListener", 1
)[1].split("});", 1)[0]
assert "applyTheme(themeSelect.value);" in dark_mode
assert "frameNodes()" in dark_mode
def test_first_fit_ms_comes_from_settings(self):
"""The first node fit duration is first_fit_ms.
Generated by AI/LLM: 2026-09-30 - opening zoom speed is a graph setting.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
slow = HTMLGraphRenderer(graph, {"first_fit_ms": 8000}).generate_html()
assert "const FIRST_FIT_MS = 8000;" in slow
missing = HTMLGraphRenderer(graph, {"first_fit_ms": 0}).generate_html()
assert "const FIRST_FIT_MS = 12000;" in missing
text = HTMLGraphRenderer(graph, {"first_fit_ms": "nope"}).generate_html()
assert "const FIRST_FIT_MS = 12000;" in text
def test_hover_card_truncates_long_links(self):
"""A long URL on the hover card keeps the host and a short tail.
Generated by AI/LLM: 2026-09-30 - hover link length is a graph setting.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "const HOVER_LINK_TAIL_CHARS = 12;" in html
assert "host + '/.../' + last" in html
assert "host + '/...' + last.slice(-tail)" in html
assert "callout-name" in html
assert "callout-stats" in html
short = HTMLGraphRenderer(graph, {"hover_link_tail_chars": 5}).generate_html()
assert "const HOVER_LINK_TAIL_CHARS = 5;" in short
fallback = HTMLGraphRenderer(graph, {"hover_link_tail_chars": 0}).generate_html()
assert "const HOVER_LINK_TAIL_CHARS = 12;" in fallback
def test_graph_page_lengths_are_relative(self):
"""The graph page writes lengths in em or rem, not px.
Generated by AI/LLM: 2026-09-29 - web lengths stay relative.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "px" not in html
assert "0.75em" in html
assert "function cssLength" in html
def test_search_matches_glow(self):
"""A search match is drawn with a glow.
Generated by AI/LLM: 2026-09-29 - search matches glow for emphasis.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "search-glow" in html
assert "feGaussianBlur" in html
assert "url(#search-glow)" in html
assert "function applySearchGlow" in html
glow = html.split("function applySearchGlow", 1)[1].split(
"function nodeOpacity", 1
)[0]
assert "d.id === highlightedNode" in glow
assert "d.id === hoveredNode" in glow
assert "if (!showGlow) return null;" in glow
highlight = html.split("function highlightNode", 1)[1].split(
"function removeNodeHighlight", 1
)[0]
assert "applySearchGlow()" in highlight
cleared = html.split("function removeNodeHighlight", 1)[1].split(
"svg.on('click'", 1
)[0]
assert "applySearchGlow()" in cleared
def test_glow_and_link_card_follow_settings(self):
"""Glow and the link card start on and can be turned off.
Generated by AI/LLM: 2026-09-30 - settings for glow and the link card.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
shown = HTMLGraphRenderer(graph).generate_html()
assert "const showGlow = true;" in shown
assert "const showLinkCard = true;" in shown
assert "if (!showLinkCard)" in shown
hidden = HTMLGraphRenderer(graph, {"show_glow": False, "show_link_card": False}).generate_html()
assert "const showGlow = false;" in hidden
assert "const showLinkCard = false;" in hidden
def test_generate_html_has_edge_highlight_on_hover(self):
"""Test that generated HTML includes edge highlighting on node hover."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_node("wiki/file3.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file3.md")
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
# Check that node hover handler includes edge highlighting logic
# Should contain code that sets opacity on hover to dim non-connected edges
assert "linkD.source.id" in html or "linkD.source" in html
assert "return 0.2" in html # Dimmed opacity for non-connected edges
def test_generate_html_orphan_control_is_a_toggle(self):
"""Orphans are shown with a checkbox toggle, not a button.
Generated by AI/LLM: 2026-09-29 - orphan control is a toggle.
"""
graph = WikiGraph()
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
assert 'id="orphan-toggle"' in html
assert 'type="checkbox"' in html
assert "Show Orphan Nodes" in html
assert "<button id=\"orphan-toggle\"" not in html
assert "Hide Orphan Nodes" not in html
def test_generate_html_hover_keeps_click_highlight(self):
"""Hover paints its own edges and leaves the click highlight.
Generated by AI/LLM: 2026-09-29 - click highlight survives hover.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
assert "function applyEdgeStyles" in html
assert "hoveredNode" in html
assert "edgeTouches(linkD, hoveredNode)" in html
assert "edgeTouches(linkD, highlightedNode)" in html
assert "pinHighlightedNode(d.id)" in html
assert "function calloutLines" in html
assert "function hoverLinkLabel" in html
assert "function forceCalloutCards" in html
assert "widest * CALLOUT_FONT" in html
def test_generate_html_click_pins_only_that_node(self):
"""A clicked node stays put. Its neighbors keep simulating.
Generated by AI/LLM: 2026-09-29 - pin only the highlighted node.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
assert "function pinHighlightedNode" in html
assert "function releaseHighlightedNode" in html
assert "node.fx = node.x" in html
assert "node.fy = node.y" in html
assert "if (d.id !== highlightedNode && d.id !== hoveredNode)" in html
def test_external_toggle_uses_settings_default(self):
"""The external-link toggle starts from show_external_links.
Generated by AI/LLM: 2026-09-29 - settings default for the toggle.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
off = HTMLGraphRenderer(graph).generate_html()
assert 'id="external-toggle"' in off
assert "Show External Links" in off
assert 'id="external-toggle" checked' not in off
on = HTMLGraphRenderer(graph, {"show_external_links": True}).generate_html()
assert 'id="external-toggle" checked' in on
assert ".style('opacity', nodeOpacity)" in on
assert "applyVisibility()" in on
def test_frontmatter_source_is_drawn_and_toggleable(self):
"""A frontmatter source value is a cloud node with a toggle.
Generated by AI/LLM: 2026-09-29 - show_source draws the source key.
"""
graph = WikiGraph()
graph.add_node("wiki/rules.md")
graph.set_frontmatter("wiki/rules.md", {
"source": "https://example.com/rules.md",
})
graph.add_node("wiki/list.md")
graph.set_frontmatter("wiki/list.md", {
"source": ["https://a.example/x", " ", "https://b.example/y"],
})
graph.add_node("wiki/shared.md")
graph.set_frontmatter("wiki/shared.md", {"source": "https://a.example/x"})
graph.add_node("wiki/plain.md")
graph.set_frontmatter("wiki/plain.md", {"source": 12})
html = HTMLGraphRenderer(graph).generate_html()
nodes = _html_nodes(html)
by_id = {node["id"]: node for node in nodes}
assert by_id["https://example.com/rules.md"]["kind"] == "source"
assert by_id["https://a.example/x"]["kind"] == "source"
assert by_id["https://a.example/x"]["unique_points"] == 2
assert by_id["https://b.example/y"]["kind"] == "source"
assert "https://example.com/rules.md" not in {
node["id"] for node in nodes if node["kind"] == "page"
}
assert all(node["id"] != "12" for node in nodes)
assert 'id="source-toggle" checked' in html
assert "Show Sources" in html
assert "const initialShowSources = true" in html
assert "let showSources = initialShowSources" in html
assert "d.kind === 'source'" in html
hidden = HTMLGraphRenderer(graph, {"show_source": False}).generate_html()
assert 'id="source-toggle" checked' not in hidden
assert "const initialShowSources = false" in hidden
assert any(
node["kind"] == "source" for node in _html_nodes(hidden)
)
settings = load_graph_settings("/nonexistent/path")
assert settings["show_source"] is True
def test_html_draws_external_nodes_as_clouds(self):
"""External URLs are cloud nodes in HTML and stay out of JSON nodes.
Generated by AI/LLM: 2026-09-29 - cloud shape for external links.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_external_link("wiki/file1.md", "https://example.com")
renderer = HTMLGraphRenderer(graph)
html = renderer.generate_html()
assert '"kind": "external"' in html
assert "https://example.com" in html
assert "\\u2601" in html
assert "function cloudPath" not in html
data = json.loads(renderer.generate_json("/wiki"))
assert all(node["id"] != "https://example.com" for node in data["nodes"])
def test_simplify_external_links_labels_the_host(self):
"""A simplified external subtitle is the host, not the URL.
Generated by AI/LLM: 2026-09-29 - short external subtitles.
"""
graph = WikiGraph()
graph.add_node("wiki/a.md")
graph.add_external_link("wiki/a.md", "https://www.domain.com/abc")
graph.add_external_link("wiki/a.md", "https://domain.com/acd")
renderer = HTMLGraphRenderer(graph, {"simplify_external_links": True})
nodes, edges = renderer._external_display_data()
by_id = {node["id"]: node for node in nodes}
assert set(by_id) == {
"https://www.domain.com/abc",
"https://domain.com/acd",
}
assert by_id["https://www.domain.com/abc"]["subtitle"] == "domain.com"
assert by_id["https://domain.com/acd"]["subtitle"] == "domain.com"
assert len(edges) == 2
assert "d.subtitle" in renderer.generate_html()
plain = HTMLGraphRenderer(graph)._external_display_data()[0]
assert all("subtitle" not in node for node in plain)
def test_consolidate_external_links_merges_one_host(self):
"""URLs on one host become a single domain.com/* node.
Generated by AI/LLM: 2026-09-29 - consolidate external hosts.
"""
graph = WikiGraph()
graph.add_node("wiki/a.md")
graph.add_node("wiki/b.md")
graph.add_external_link("wiki/a.md", "https://www.domain.com/abc")
graph.add_external_link("wiki/b.md", "https://domain.com/acd")
graph.add_external_link("wiki/a.md", "https://other.test/x")
renderer = HTMLGraphRenderer(graph, {
"consolidate_external_links": True,
"simplify_external_links": False,
})
nodes, edges = renderer._external_display_data()
by_id = {node["id"]: node for node in nodes}
assert set(by_id) == {"domain.com/*", "other.test/*"}
domain = by_id["domain.com/*"]
assert domain["name"] == "domain.com/*"
assert domain["subtitle"] == "domain.com"
assert domain["unique_points"] == 2
assert domain["total_points"] == 2
assert domain["link_score"] == 2
assert domain["url"] == "https://domain.com/"
assert {edge["target"] for edge in edges} == {"domain.com/*", "other.test/*"}
crowded = WikiGraph()
crowded.add_node("wiki/a.md")
for path in ("/a", "/b", "/c", "/d", "/e", "/f", "/g", "/h", "/i", "/j"):
crowded.add_external_link("wiki/a.md", f"https://domain.com{path}")
merged, _edges = HTMLGraphRenderer(
crowded, {"consolidate_external_links": True}
)._external_display_data()
assert len(merged) == 1
assert merged[0]["unique_points"] == 1
assert merged[0]["total_points"] == 10
assert merged[0]["link_score"] < 2
def test_consolidate_depth_keeps_path_parts(self):
"""Depth 0 is off. Deeper values keep that many path parts.
Generated by AI/LLM: 2026-09-29 - consolidate by path depth.
"""
graph = WikiGraph()
graph.add_node("wiki/a.md")
graph.add_external_link("wiki/a.md", "https://domain.com/abc/one")
graph.add_external_link("wiki/a.md", "https://domain.com/abc/two")
graph.add_external_link("wiki/a.md", "https://domain.com/zzz/one")
graph.add_external_link("wiki/a.md", "https://www.domain.com/a/b/c")
graph.add_external_link("wiki/a.md", "https://domain.com/abcdefghij/b/c")
off, _edges = HTMLGraphRenderer(graph, {
"consolidate_external_links": True,
"consolidate_external_links_depth": 0,
})._external_display_data()
assert len(off) == 5
depth_two = HTMLGraphRenderer(graph, {
"consolidate_external_links_depth": 2,
"simplify_external_links": False,
})._external_display_data()[0]
by_id = {node["id"]: node for node in depth_two}
assert "domain.com/abc/*" in by_id
assert "domain.com/zzz/*" in by_id
assert by_id["domain.com/abc/*"]["subtitle"] == "domain.com"
assert by_id["domain.com/abc/*"]["url"] == "https://domain.com/abc/"
assert by_id["domain.com/abc/*"]["total_points"] == 2
depth_three = HTMLGraphRenderer(graph, {
"consolidate_external_links_depth": 3,
})._external_display_data()[0]
by_id = {node["id"]: node for node in depth_three}
assert by_id["domain.com/a/b/*"]["url"] == "https://domain.com/a/b/"
assert "domain.com/.../b/*" in by_id
assert "domain.com/abcdefghij/b/*" not in by_id
kept = HTMLGraphRenderer(graph, {
"consolidate_external_links_depth": 3,
"consolidate_external_links_max_char": 12,
})._external_display_data()[0]
assert any(node["id"] == "domain.com/abcdefghij/b/*" for node in kept)
def test_subtitle_uses_settings_and_frontmatter_name(self):
"""Large nodes label with frontmatter name, else the filename.
Generated by AI/LLM: 2026-09-29 - subtitle threshold and toggle.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.set_frontmatter("wiki/file1.md", {"name": "Page Title"})
default = HTMLGraphRenderer(graph).generate_html()
assert 'id="subtitle-toggle" checked' in default
assert "Show Subtitles" in default
assert "function subtitleThreshold" in default
assert "function subtitleText" in default
assert "meta.name" in default
assert "visualRadius(d) < subtitleThreshold()" in default
assert "radiusLimit('max'" in default
themes = load_constellation_themes()
assert themes["colorful"]["subtitle"]["min_radius"] == 0.8
assert themes["night-sky"]["subtitle"]["min_radius"] == 0.8
assert themes["grayscale"]["subtitle"]["min_radius"] == 0.8
custom = HTMLGraphRenderer(graph, {
"subtitle": {"enabled": False},
}).generate_html()
assert 'id="subtitle-toggle" checked' not in custom
def test_subtitle_style_comes_from_the_theme(self):
"""Gap, size, stacking, and outline are theme subtitle keys.
Generated by AI/LLM: 2026-09-29 - subtitle style lives on the theme.
"""
themes = load_constellation_themes()
colorful = themes["colorful"]["subtitle"]
assert colorful["padding"] == 2
assert colorful["size"] == 6
assert colorful["on_top"] is True
assert colorful["outline"] is False
assert colorful["outline_width"] == 3
assert colorful["outline_color"] == "#fffdf8"
grayscale = themes["grayscale"]["subtitle"]
assert grayscale["padding"] == colorful["padding"]
assert grayscale["size"] == colorful["size"]
assert grayscale["on_top"] is colorful["on_top"]
assert grayscale["outline"] is colorful["outline"]
assert themes["night-sky"]["subtitle"]["outline_color"] == "#0b1020"
assert themes["dark"]["subtitle"]["outline_color"] == "#283448"
assert themes["grayscale"]["dark"]["subtitle"]["outline_color"] == "#2c2c2c"
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph).generate_html()
assert "function subtitlePadding" in html
assert "function subtitleFontSize" in html
assert "function subtitlesOnTop" in html
assert "function subtitleOutlineOn" in html
assert "subtitle-layer" in html
assert "paint-order" in html
assert "bottom + 12" not in html
assert "font-size', '11px'" not in html
def test_refresh_resets_toggles_to_the_settings(self):
"""A reload puts the toggles back to the settings defaults.
Generated by AI/LLM: 2026-09-29 - ignore the browser's saved form state.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
html = HTMLGraphRenderer(graph, {"show_arrows": False}).generate_html()
assert "function resetControls" in html
assert "pageshow" in html
assert 'autocomplete="off"' in html
assert "orphan-toggle" in html
assert "arrow-toggle" in html
def test_legend_toggle_uses_settings_default(self):
"""The legend card starts from show_legend.
Generated by AI/LLM: 2026-09-29 - upper-right shape and color key.
"""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
shown = HTMLGraphRenderer(graph).generate_html()
assert 'id="legend-toggle" checked' in shown
assert "Show Legend" in shown
assert 'id="legend-card"' in shown
assert "External link" in shown
assert "Files pointing here" in shown
assert "Few" in shown
assert "Linked once" in shown
assert "legend-heading" in shown
assert "placeLegend" in shown
hidden = HTMLGraphRenderer(graph, {"show_legend": False}).generate_html()
assert 'id="legend-toggle" checked' not in hidden
assert 'id="legend-card" class="legend-card" style="display: none;"' in hidden
def test_arrow_toggle_uses_settings_default(self):
"""Arrowheads start from show_arrows and point at the target.
Generated by AI/LLM: 2026-09-29 - direction toggle on graph edges.
"""
graph = WikiGraph()
graph.add_node("wiki/a.md")
graph.add_node("wiki/b.md")
graph.add_edge("wiki/a.md", "wiki/b.md")
shown = HTMLGraphRenderer(graph).generate_html()
assert 'id="arrow-toggle" checked' in shown
assert "Show Arrows" in shown
assert "'edge-arrow'" in shown
assert "marker-end" in shown
assert "context-stroke" in shown
assert "let showArrows = true" in shown
hidden = HTMLGraphRenderer(graph, {"show_arrows": False}).generate_html()
assert 'id="arrow-toggle" checked' not in hidden
assert "let showArrows = false" in hidden
def test_node_stores_every_frontmatter_field(self):
"""Markdown nodes keep the full frontmatter object.
Modified by AI/LLM: 2026-09-30 - a click lists every field at the upper left.
"""
graph = WikiGraph()
graph.add_node("wiki/page.md")
graph.set_frontmatter("wiki/page.md", {
"name": "Page Title",
"version": "1.2.3",
"created": "2026-09-29",
"tags": ["alpha", "beta"],
})
renderer = HTMLGraphRenderer(graph)
data = json.loads(renderer.generate_json("/wiki"))
frontmatter = data["nodes"][0]["frontmatter"]
assert frontmatter["name"] == "Page Title"
assert frontmatter["version"] == "1.2.3"
assert frontmatter["created"] == "2026-09-29"
assert frontmatter["tags"] == ["alpha", "beta"]
html = renderer.generate_html()
assert "Page Title" in html
assert "function syncCallouts" in html
assert "callout-arrow" in html
assert 'id="frontmatter-card"' in html
assert "function frontmatterCardHtml" in html
assert "Object.keys(meta)" in html
assert "Unique points:" in html
highlight = html.split("function highlightNode", 1)[1].split(
"function removeNodeHighlight", 1
)[0]
assert "frontmatterCardHtml(selected)" in highlight
assert "frontmatterCard.style('display', 'block')" in highlight
cleared = html.split("function removeNodeHighlight", 1)[1].split(
"svg.on('click'", 1
)[0]
assert "frontmatterCard.style('display', 'none')" in cleared
assert "pinCallout" not in html
assert "hoveredNode !== highlightedNode" not in html
def test_node_size_uses_link_score(self):
"""Radius and color follow unique sources, not raw repeats.
Generated by AI/LLM: 2026-09-29 - the card lists both point counts.
"""
graph = WikiGraph()
for _ in range(10):
graph.add_edge("wiki/only.md", "wiki/repeat.md")
graph.add_edge("wiki/left.md", "wiki/pair.md")
graph.add_edge("wiki/right.md", "wiki/pair.md")
for _ in range(10):
graph.add_external_link("wiki/only.md", "https://repeat.example")
graph.add_external_link("wiki/left.md", "https://pair.example")
graph.add_external_link("wiki/right.md", "https://pair.example")
renderer = HTMLGraphRenderer(graph)
data = json.loads(renderer.generate_json("/wiki"))
by_id = {node["id"]: node for node in data["nodes"]}
assert by_id["wiki/repeat.md"]["unique_points"] == 1
assert by_id["wiki/repeat.md"]["total_points"] == 10
assert by_id["wiki/repeat.md"]["link_score"] < 2
assert by_id["wiki/pair.md"]["link_score"] == 2
external, _edges = renderer._external_display_data()
by_url = {node["id"]: node for node in external}
assert by_url["https://repeat.example"]["unique_points"] == 1
assert by_url["https://repeat.example"]["total_points"] == 10
assert by_url["https://repeat.example"]["link_score"] < 2
assert by_url["https://pair.example"]["unique_points"] == 2
assert by_url["https://pair.example"]["link_score"] == 2
html = renderer.generate_html()
assert "const maxLinkScore" in html
assert "d.link_score / maxLinkScore" in html
assert "d.unique_points + ':' + d.total_points" in html
assert "Unique points:" in html
assert "Total points:" in html
def test_generate_json(self):
"""Test generating JSON output."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
renderer = HTMLGraphRenderer(graph)
json_output = renderer.generate_json(" /path/to/wiki")
data = json.loads(json_output)
assert "metadata" in data
assert "nodes" in data
assert "edges" in data
assert len(data["nodes"]) == 2
assert len(data["edges"]) == 1
def test_generate_json_with_external_links(self):
"""Test generating JSON output with external links."""
graph = WikiGraph()
graph.add_node("wiki/file1.md")
graph.add_node("wiki/file2.md")
graph.add_edge("wiki/file1.md", "wiki/file2.md")
graph.add_external_link("wiki/file1.md", "https://example.com")
graph.add_external_link("wiki/file1.md", "https://another.com")
graph.add_external_link("wiki/file2.md", "https://third.com")
renderer = HTMLGraphRenderer(graph)
json_output = renderer.generate_json(" /path/to/wiki")
data = json.loads(json_output)
assert "metadata" in data
assert "external_links_count" in data["metadata"]
assert "external_links" in data["metadata"]
assert data["metadata"]["external_links_count"] == 3
assert len(data["metadata"]["external_links"]) == 3
assert "https://example.com" in data["metadata"]["external_links"]
class TestWikiGraphMain:
"""Tests for wiki_graph_main CLI entry point."""
def test_main_with_html_output(self, tmp_path):
"""Test main function with HTML output."""
# Create temporary markdown files
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n\nLink to [file2](file2.md).")
md_file2 = tmp_path / "file2.md"
md_file2.write_text("# File 2\n")
output_file = tmp_path / "graph.html"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file),
format_type="html"
)
assert result == 0
assert output_file.exists()
def test_main_saves_frontmatter_for_every_markdown_file(self, tmp_path):
"""Each scanned markdown file contributes its frontmatter.
Generated by AI/LLM: 2026-09-29 - missing YAML is an empty object.
"""
(tmp_path / "file1.md").write_text(
"---\nname: Alpha\nversion: 2.0.0\nupdated: 2026-09-29\n---\n# A\n",
encoding="utf-8",
)
(tmp_path / "file2.md").write_text("# No frontmatter\n", encoding="utf-8")
(tmp_path / "bad.md").write_text("---\n: [\n---\n# Bad\n", encoding="utf-8")
output_file = tmp_path / "graph.json"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file),
format_type="json",
)
assert result == 0
data = json.loads(output_file.read_text(encoding="utf-8"))
by_name = {node["name"]: node for node in data["nodes"]}
assert by_name["file1.md"]["frontmatter"]["name"] == "Alpha"
assert by_name["file1.md"]["frontmatter"]["version"] == "2.0.0"
assert by_name["file1.md"]["frontmatter"]["updated"] == "2026-09-29"
assert by_name["file2.md"]["frontmatter"] == {}
assert by_name["bad.md"]["frontmatter"] == {}
def test_main_with_json_output(self, tmp_path):
"""Test main function with JSON output."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n\nLink to [file2](file2.md).")
md_file2 = tmp_path / "file2.md"
md_file2.write_text("# File 2\n")
output_file = tmp_path / "graph.json"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file),
format_type="json"
)
assert result == 0
assert output_file.exists()
with open(output_file) as f:
data = json.load(f)
assert "nodes" in data
assert "edges" in data
def test_main_default_output(self, tmp_path, monkeypatch):
"""Test main function with default output file."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n")
# Change to tmp_path
original_cwd = os.getcwd()
monkeypatch.chdir(tmp_path)
try:
result = wiki_graph_main(
directory=str(tmp_path)
)
assert result == 0
assert (tmp_path / "wiki_graph.html").exists()
finally:
os.chdir(original_cwd)
def test_main_wikilinks_disabled(self, tmp_path):
"""Test main function with wikilinks disabled."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n\nWikilink: [[file2]].")
md_file2 = tmp_path / "file2.md"
md_file2.write_text("# File 2\n")
output_file = tmp_path / "graph.json"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file),
format_type="json",
wikilinks=False
)
assert result == 0
with open(output_file) as f:
data = json.load(f)
# With wikilinks disabled, the wikilink shouldn't create an edge
assert len(data["edges"]) == 0
def test_main_with_external_links(self, tmp_path):
"""Test main function with external links tracking enabled."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n\n[Internal](file2.md) and [External](https://example.com).")
md_file2 = tmp_path / "file2.md"
md_file2.write_text("# File 2\n\n[Another External](https://another.com).")
output_file = tmp_path / "graph.json"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file),
format_type="json",
external_links=True
)
assert result == 0
with open(output_file) as f:
data = json.load(f)
# Should have internal link
assert len(data["edges"]) == 1
# Should have external links in metadata
assert "external_links_count" in data["metadata"]
assert data["metadata"]["external_links_count"] == 2
assert "https://example.com" in data["metadata"]["external_links"]
assert "https://another.com" in data["metadata"]["external_links"]
def test_main_directory_not_found(self):
"""Test main function with non-existent directory (lines 651-652)."""
result = wiki_graph_main(directory="/nonexistent/path")
assert result == 1
def test_main_with_settings_override(self, tmp_path):
"""Test main function with settings override from fiona-settings.json (lines 651-652, 660, 663, 666)."""
# Create settings file
settings_file = tmp_path / "fiona-settings.json"
settings_file.write_text(json.dumps({
"fiona": {
"wiki": {
"graph": {
"wikilinks_enabled": False,
"external_links": True,
"max_files": 5
}
}
}
}))
# Create markdown files with wikilinks
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n\nWikilink: [[file2]].")
md_file2 = tmp_path / "file2.md"
md_file2.write_text("# File 2\n")
output_file = tmp_path / "graph.json"
# Wikilinks should be disabled via settings
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file),
format_type="json"
)
assert result == 0
with open(output_file) as f:
data = json.load(f)
# With wikilinks disabled via settings, no edges should be created
assert len(data["edges"]) == 0
def test_main_output_directory_not_exists(self, tmp_path):
"""Test main function when output directory doesn't exist (lines 678-683)."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n")
# Output to a non-existent subdirectory
output_file = tmp_path / "nonexistent" / "graph.html"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file)
)
assert result == 0
assert output_file.exists()
def test_main_output_directory_creation_fails(self, tmp_path, monkeypatch):
"""Test main function when output directory creation fails (lines 678-683)."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n")
# Mock os.makedirs to raise an error
def mock_makedirs(path, exist_ok=False):
raise OSError("Permission denied")
monkeypatch.setattr("os.makedirs", mock_makedirs)
output_file = tmp_path / "restricted" / "graph.html"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file)
)
assert result == 1
def test_main_output_not_writable(self, tmp_path):
"""Test main function when output file is not writable (lines 687-690)."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n")
# Create a read-only output file
output_file = tmp_path / "graph.html"
output_file.write_text("existing content")
os.chmod(output_file, 0o444) # Read-only
try:
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file)
)
assert result == 1
finally:
# Restore permissions for cleanup
os.chmod(output_file, 0o644)
def test_main_output_directory_not_writable(self, tmp_path, monkeypatch):
"""Test main function when output directory is not writable (lines 694-696)."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n")
# AI/LLM: chmod does not clear directory write access on Windows.
target = os.path.normcase(os.path.abspath(tmp_path))
real_access = os.access
def deny_directory_write(path, mode):
if os.path.normcase(os.path.abspath(path)) == target and mode == os.W_OK:
return False
return real_access(path, mode)
monkeypatch.setattr("fiona.wiki.graph_generator.os.access", deny_directory_write)
output_file = tmp_path / "graph.html"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file)
)
assert result == 1
def test_main_max_files_limit(self, tmp_path):
"""Test main function respects max_files limit from settings (lines 712-713)."""
# Create settings file with max_files
settings_file = tmp_path / "fiona-settings.json"
settings_file.write_text(json.dumps({
"fiona": {
"wiki": {
"graph": {
"max_files": 5
}
}
}
}))
# Create more files than max_files
for i in range(10):
md_file = tmp_path / f"file{i}.md"
md_file.write_text(f"# File {i}\n")
output_file = tmp_path / "graph.json"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file),
format_type="json",
include_pattern="*.md"
)
assert result == 0
with open(output_file) as f:
data = json.load(f)
# Should only process first 5 files
assert len(data["nodes"]) == 5
def test_main_overwrite_existing_file(self, tmp_path):
"""Test main function overwrites existing file (line 753)."""
md_file1 = tmp_path / "file1.md"
md_file1.write_text("# File 1\n")
output_file = tmp_path / "graph.html"
output_file.write_text("old content")
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file)
)
assert result == 0
# File should be overwritten
content = output_file.read_text()
assert "old content" not in content
assert "File 1" in content or "file1.md" in content
def test_main_exception_handling(self, tmp_path, monkeypatch):
"""Test main function exception handling (lines 766-769)."""
# Mock glob.glob to raise an exception
def mock_glob(pattern, root_dir=None, recursive=False):
raise OSError("glob error")
monkeypatch.setattr("glob.glob", mock_glob)
output_file = tmp_path / "graph.html"
result = wiki_graph_main(
directory=str(tmp_path),
output=str(output_file)
)
assert result == 1