Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 180 lines 5.27 KB
Raw
1 """pytest configuration module"""
2
3 import base64
4 import hashlib
5 import hmac
6 import json
7 import os
8 from pathlib import Path
9 import typing as t
10 from unittest.mock import Mock
11
12 import pytest
13
14 from composio.core.models.triggers import Triggers
15
16
17 def get_py_fixtures_dir() -> Path:
18 """Get the Python fixtures directory path."""
19 return Path(__file__).parent / "fixtures" / "webhook"
20
21
22 def get_ts_fixtures_dir() -> Path:
23 """Get the TypeScript fixtures directory path."""
24 return (
25 Path(__file__).parent.parent.parent
26 / "ts"
27 / "packages"
28 / "core"
29 / "test"
30 / "fixtures"
31 / "webhook"
32 )
33
34
35 def get_py_json_schema_corpus_dir() -> Path:
36 """Get the Python JSON Schema conversion corpus directory path."""
37 return Path(__file__).parent / "fixtures" / "json-schema-conversion"
38
39
40 def get_ts_json_schema_corpus_dir() -> Path:
41 """Get the TypeScript JSON Schema conversion corpus directory path."""
42 return (
43 Path(__file__).parent.parent.parent
44 / "ts"
45 / "packages"
46 / "core"
47 / "test"
48 / "fixtures"
49 / "json-schema-conversion"
50 )
51
52
53 def compute_signature(
54 webhook_id: str, timestamp: str, payload: str, secret: str
55 ) -> str:
56 """Compute webhook signature using HMAC-SHA256."""
57 to_sign = f"{webhook_id}.{timestamp}.{payload}"
58 signature = hmac.new(
59 key=secret.encode("utf-8"),
60 msg=to_sign.encode("utf-8"),
61 digestmod=hashlib.sha256,
62 ).digest()
63 return f"v1,{base64.b64encode(signature).decode('utf-8')}"
64
65
66 def load_fixtures() -> list[dict]:
67 """Load all webhook fixtures from the fixtures directory."""
68 fixtures_dir = get_py_fixtures_dir()
69 fixtures = []
70 for fixture_file in fixtures_dir.glob("v*.json"):
71 if "golden" in fixture_file.name:
72 continue
73 with open(fixture_file) as f:
74 fixtures.append(json.load(f))
75 return fixtures
76
77
78 def load_golden_signatures() -> dict:
79 """Load golden signatures for contract testing."""
80 fixtures_dir = get_py_fixtures_dir()
81 with open(fixtures_dir / "golden-signatures.json") as f:
82 return json.load(f)
83
84
85 def mock_http_client(mock_cls: t.Type[Mock] = Mock) -> Mock:
86 """Build a mock ``HttpClient`` for tool-execution tests.
87
88 Production routes tool executions and proxied calls through
89 ``client.without_retries`` (a retry-disabled clone of the client). The mock
90 mirrors that by returning itself for ``without_retries``, so assertions on
91 ``client.tools.execute``, ``client.tools.proxy``, and the
92 ``client.tool_router.session`` execution methods still observe the call.
93 """
94 client = mock_cls()
95 client.without_retries = client
96 return client
97
98
99 @pytest.fixture
100 def mock_client() -> Mock:
101 """Create a mock HTTP client."""
102 client = mock_http_client()
103 client.triggers_types = Mock()
104 client.trigger_instances = Mock()
105 client.trigger_instances.manage = Mock()
106 client.connected_accounts = Mock()
107 return client
108
109
110 @pytest.fixture
111 def triggers(mock_client: Mock) -> Triggers:
112 """Create a Triggers instance."""
113 return Triggers(client=mock_client)
114
115
116 @pytest.fixture
117 def webhook_fixtures() -> list[dict]:
118 """Load all webhook fixtures."""
119 return load_fixtures()
120
121
122 @pytest.fixture
123 def golden_signatures() -> dict:
124 """Load golden signatures."""
125 return load_golden_signatures()
126
127
128 @pytest.fixture(scope="session")
129 def _real_home_baseline():
130 """The real home directory and its top-level entries, captured once.
131
132 Session-scoped so it is read before any test can monkeypatch ``$HOME``.
133 Resolving it per-test would let a test that repoints ``$HOME`` also move
134 the guard's own reference point, which is exactly the class of mistake the
135 guard exists to catch.
136 """
137 real_home = Path(os.path.expanduser("~"))
138 try:
139 return {"path": real_home, "entries": set(os.listdir(real_home))}
140 except OSError:
141 return {"path": real_home, "entries": None}
142
143
144 @pytest.fixture(autouse=True)
145 def guard_real_home_directory(request, _real_home_baseline):
146 """Fail any test that creates entries directly in the real home directory.
147
148 A test that meant to sandbox `~` but patched the wrong thing
149 (`Path.home` does not affect `Path.expanduser`, which reads `$HOME`)
150 silently writes into the developer's actual home instead. That has already
151 destroyed real user data once. This turns the silent case into a failure.
152
153 Only top-level entries are compared, so a test writing under an existing
154 `~/.composio` is unaffected; creating `~/downloads` is not.
155 """
156 if _real_home_baseline["entries"] is None:
157 yield
158 return
159
160 yield
161
162 real_home = _real_home_baseline["path"]
163 try:
164 after = set(os.listdir(real_home))
165 except OSError:
166 return
167
168 created = after - _real_home_baseline["entries"]
169 # Roll the baseline forward before failing, so one offending test does not
170 # then fail every test that follows it.
171 _real_home_baseline["entries"] = after
172 if not created:
173 return
174
175 pytest.fail(
176 f"{request.node.nodeid} created {sorted(created)} in the real home "
177 f"directory ({real_home}). Sandbox `$HOME` with "
178 f"`monkeypatch.setenv('HOME', str(tmp_path))` — patching `Path.home` "
179 f"does not affect `Path.expanduser`."
180 )