test_garden_layer.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import os
  2. import pytest
  3. import requests
  4. from typing import Any, Dict
  5. from garden_layer import GardenLayer
  6. from garden_layer.config import CLONE_OF, GRAPH, KEROSENE_ROOT, MCP_URL
  7. CYCLE_2026_3 = "http://world.eu.org/example1#ProductionCycle_21d96b6c-179"
  8. def pytest_report_header(config):
  9. return "Garden layer tests: requires virtuoso_mcp running at GardenLayer.MCP_URL"
  10. @pytest.fixture
  11. def garden_layer():
  12. layer = GardenLayer()
  13. try:
  14. layer.traverse(KEROSENE_ROOT, CLONE_OF, direction="incoming", limit=1)
  15. except requests.RequestException as exc:
  16. pytest.skip(f"Cannot reach MCP server: {exc}")
  17. return layer
  18. def test_traverse_clone_tree(garden_layer):
  19. """Walk `cloneOf` incoming edges and ensure the root has clones to inspect."""
  20. result = garden_layer.traverse(KEROSENE_ROOT, CLONE_OF, direction="incoming", limit=5)
  21. assert isinstance(result, dict)
  22. bindings = result.get("results", {}).get("bindings", [])
  23. assert isinstance(bindings, list)
  24. assert bindings, "Expected at least one clone binding"
  25. print(f"Traverse of {KEROSENE_ROOT} returned {len(bindings)} clone candidates.")
  26. def test_describe_subject(garden_layer):
  27. """Describe the root plant and surface the top predicates the garden helpers can reuse."""
  28. summary = garden_layer.describe_subject(KEROSENE_ROOT, limit=5)
  29. assert isinstance(summary, dict)
  30. bindings = summary.get("results", {}).get("bindings", [])
  31. assert bindings, "Expected describe_subject to return bindings"
  32. triples = [f"{b['predicate']['value']} -> {b['object'].get('value', '<literal>')}" for b in bindings]
  33. print("describe_subject returned:")
  34. for triple in triples:
  35. print(" ", triple)
  36. def test_path_traverse_lineage(garden_layer):
  37. """Use the path helper to follow `cloneOf` and observe the lineage step."""
  38. path = garden_layer.path_traverse(KEROSENE_ROOT, [CLONE_OF], direction="incoming", limit=5)
  39. assert isinstance(path, dict)
  40. bindings = path.get("result", {}).get("results", {}).get("bindings", [])
  41. assert isinstance(bindings, list)
  42. assert bindings, "Path traverse should find at least one step"
  43. print(f"Property path {CLONE_OF} produced {len(bindings)} step bindings.")
  44. def test_property_usage_statistics(garden_layer):
  45. """Summarize how the `cloneOf` property is used so future helpers can rely on frequency data."""
  46. stats = garden_layer.property_usage_statistics(CLONE_OF, examples_limit=3)
  47. assert isinstance(stats, dict)
  48. count_bindings = stats.get("count", {}).get("results", {}).get("bindings", [])
  49. assert count_bindings, "Expected usage count bindings"
  50. usage_count = count_bindings[0].get("usageCount", {}).get("value")
  51. example_bindings = stats.get("examples", {}).get("results", {}).get("bindings", [])
  52. assert isinstance(example_bindings, list)
  53. print(f"cloneOf usage count: {usage_count}")
  54. print("example bindings:")
  55. for binding in example_bindings:
  56. subject = binding.get("subjectLabel", {}).get("value") or binding.get("subject", {}).get("value")
  57. object_ = binding.get("objectLabel", {}).get("value") or binding.get("object", {}).get("value")
  58. print(f" - {subject} -> {object_}")
  59. def test_batch_insert(garden_layer):
  60. """Batch-insert a TTL snippet and verify the query shape"""
  61. ttl = '<http://world.eu.org/example1#batch_test_subject> <http://www.w3.org/2000/01/rdf-schema#label> "garden batch" .'
  62. result = garden_layer.batch_insert(ttl=ttl, graph=GRAPH)
  63. assert isinstance(result, dict)
  64. assert "query" in result
  65. assert "INSERT DATA" in result.get("query", "").upper()
  66. print("batch_insert generated:")
  67. print(result.get("query", ""))
  68. def call_mcp_tool(tool_name: str, payload: Dict[str, Any]) -> Any:
  69. response = requests.post(MCP_URL, json={"tool": tool_name, "input": payload}, timeout=10)
  70. response.raise_for_status()
  71. body = response.json()
  72. assert body.get("status") == "ok", f"{tool_name} failed: {body.get('detail') or 'unknown reason'}"
  73. return body["result"]
  74. def test_mcp_garden_describe_subject():
  75. result = call_mcp_tool(
  76. "garden_describe_subject",
  77. {"subject_uri": KEROSENE_ROOT, "limit": 5},
  78. )
  79. bindings = result.get("results", {}).get("bindings", [])
  80. assert bindings, "garden_describe_subject should return bindings"
  81. print("garden_describe_subject returned", len(bindings), "bindings via /mcp")
  82. def test_mcp_garden_property_usage_statistics():
  83. result = call_mcp_tool(
  84. "garden_property_usage_statistics",
  85. {"property_uri": CLONE_OF, "examples_limit": 2},
  86. )
  87. count_bindings = result.get("count", {}).get("results", {}).get("bindings", [])
  88. assert count_bindings, "Expected usage count bindings from the garden tool"
  89. examples = result.get("examples", {}).get("results", {}).get("bindings", [])
  90. assert isinstance(examples, list)
  91. print("garden_property_usage_statistics sample bindings:", len(examples))
  92. def test_mcp_garden_cycle_plants():
  93. result = call_mcp_tool(
  94. "garden_cycle_plants",
  95. {"cycle_uri": CYCLE_2026_3, "limit": 5},
  96. )
  97. bindings = result.get("results", {}).get("bindings", [])
  98. assert bindings, "Expected at least one plant binding from the cycle"
  99. print("garden_cycle_plants returned", len(bindings), "plants for cycle", CYCLE_2026_3)
  100. for binding in bindings:
  101. plant_uri = binding.get("plant", {}).get("value")
  102. assert plant_uri, "Each binding should include a plant URI"
  103. def test_load_examples_fixture(garden_layer):
  104. if os.getenv("MCP_ALLOW_EXAMPLE_LOAD", "false").lower() != "true":
  105. pytest.skip("MCP_ALLOW_EXAMPLE_LOAD must be true to load example fixtures")
  106. result = garden_layer.load_examples(files=["test_fixture.ttl"], graph=GRAPH)
  107. loaded = result.get("loaded", [])
  108. assert any(item.get("file") == "test_fixture.ttl" for item in loaded), "Expected fixture file to be loaded"