"""Unit tests for the snippet serialize/parse helpers (pure functions, no DB).""" from scribe.services import snippets as s def test_compose_title_with_and_without_usage(): assert s.compose_title("debounce", "rate-limit a callback") == "debounce — rate-limit a callback" assert s.compose_title(" debounce ", "") == "debounce" assert s.compose_title("debounce") == "debounce" def test_compose_tags_lowercases_language_and_dedups(): assert s.compose_tags("Python", ["util", "python"]) == ["python", "snippet", "util"] assert s.compose_tags("", None) == ["snippet"] assert s.compose_tags("vue", ["snippet"]) == ["vue", "snippet"] def test_compose_body_includes_fields_and_fence(): body = s.compose_body( code="return 1", language="python", signature="f() -> int", when_to_use="always", repo="scribe", path="a.py", symbol="f", ) assert "**When to use:** always" in body assert "**Signature:** `f() -> int`" in body assert "`scribe` · `a.py` · `f`" in body assert "```python\nreturn 1\n```" in body assert body.rstrip().endswith("```") def test_compose_body_bare_code_only(): body = s.compose_body(code="x = 1") assert body.strip() == "```\nx = 1\n```" def test_parse_round_trips_a_composed_snippet(): title = s.compose_title("useDebouncedRef", "debounce a reactive ref") body = s.compose_body( code="const x = 1", language="ts", signature="useDebouncedRef(v, ms)", when_to_use="debounce a reactive ref", repo="scribe", path="frontend/src/composables/x.ts", symbol="useDebouncedRef", ) got = s.parse_snippet_fields(title, body, ["ts", "snippet"]) assert got["name"] == "useDebouncedRef" assert got["when_to_use"] == "debounce a reactive ref" assert got["signature"] == "useDebouncedRef(v, ms)" assert got["language"] == "ts" assert got["code"] == "const x = 1" assert got["repo"] == "scribe" assert got["path"] == "frontend/src/composables/x.ts" assert got["symbol"] == "useDebouncedRef" def test_parse_is_tolerant_of_plain_body(): got = s.parse_snippet_fields("just a name", "no structure here", None) assert got["name"] == "just a name" assert got["when_to_use"] == "" assert got["signature"] == "" assert got["code"] == "" # never raises on an unstructured body def test_parse_falls_back_to_tag_for_language(): got = s.parse_snippet_fields("n — u", "```\ncode\n```", ["ruby", "snippet"]) assert got["language"] == "ruby" def test_snippet_to_dict_includes_parsed_fields(): class FakeNote: title = "debounce — rate-limit" body = "```js\ncode\n```\n" tags = ["js", "snippet"] def to_dict(self): return {"id": 1, "title": self.title, "note_type": "snippet", "tags": self.tags} data = s.snippet_to_dict(FakeNote()) assert data["snippet"]["name"] == "debounce" assert data["snippet"]["language"] == "js" assert data["snippet"]["code"] == "code"